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
qqmlimport.cpp
Go to the documentation of this file.
1// Copyright (C) 2017 Crimson AS <info@crimson.no>
2// Copyright (C) 2016 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant
5
6#include "qqmlimport_p.h"
7
8#include <QtCore/qdebug.h>
9#include <QtCore/qdir.h>
10#include <QtQml/qqmlfile.h>
11#include <QtCore/qfileinfo.h>
12#include <QtCore/qpluginloader.h>
13#include <QtCore/qloggingcategory.h>
14#include <QtCore/qscopeguard.h>
15#include <QtQml/qqmlextensioninterface.h>
16#include <QtQml/qqmlextensionplugin.h>
17#include <private/qqmlextensionplugin_p.h>
18#include <private/qqmlglobal_p.h>
19#include <private/qqmltypenamecache_p.h>
20#include <private/qqmlengine_p.h>
21#include <private/qqmltypemodule_p.h>
22#include <private/qqmltypeloaderqmldircontent_p.h>
23#include <private/qqmlpluginimporter_p.h>
24#include <QtCore/qjsonobject.h>
25#include <QtCore/qjsonarray.h>
26#include <QtQml/private/qqmltype_p_p.h>
27#include <QtQml/private/qqmlimportresolver_p.h>
28
29#include <algorithm>
30#include <functional>
31
32using namespace Qt::Literals::StringLiterals;
33
35
37
39{
41public:
42
44 {
45 // We have to explicitly setEnabled() here because for categories that start with
46 // "qt." it won't accept QtDebugMsg as argument. Debug messages are off by default
47 // for all Qt logging categories.
48 if (qmlImportTrace())
49 m_category.setEnabled(QtDebugMsg, true);
50 }
51
53
54 const QLoggingCategory &category() const { return m_category; }
55
56private:
57 QLoggingCategory m_category;
58};
59
61{
62 static const QmlImportCategoryHolder holder;
63 return holder.category();
64}
65
67
68static const QLatin1Char Dot('.');
69static const QLatin1Char Slash('/');
70static const QLatin1Char Backslash('\\');
71static const QLatin1Char Colon(':');
72static const QLatin1String Slash_qmldir("/qmldir");
73static const QLatin1String String_qmldir("qmldir");
74static const QString dotqml_string(QStringLiteral(".qml"));
75static const QString dotuidotqml_string(QStringLiteral(".ui.qml"));
76static bool designerSupportRequired = false;
77
78namespace {
79
80QTypeRevision relevantVersion(const QString &uri, QTypeRevision version)
81{
82 return QQmlMetaType::latestModuleVersion(uri).isValid() ? version : QTypeRevision();
83}
84
85QString resolveLocalUrl(const QString &url, const QString &relative)
86{
87 if (relative.contains(Colon)) {
88 // contains a host name
89 return QUrl(url).resolved(QUrl(relative)).toString();
90 } else if (relative.isEmpty()) {
91 return url;
92 } else if (relative.at(0) == Slash || !url.contains(Slash)) {
93 return relative;
94 } else {
95 const QStringView baseRef = QStringView{url}.left(url.lastIndexOf(Slash) + 1);
96 if (relative == QLatin1String("."))
97 return baseRef.toString();
98
99 QString base = baseRef + relative;
100
101 // Remove any relative directory elements in the path
102 int length = base.size();
103 int index = 0;
104 while ((index = base.indexOf(QLatin1String("/."), index)) != -1) {
105 if ((length > (index + 2)) && (base.at(index + 2) == Dot) &&
106 (length == (index + 3) || (base.at(index + 3) == Slash))) {
107 // Either "/../" or "/..<END>"
108 int previous = base.lastIndexOf(Slash, index - 1);
109 if (previous == -1)
110 break;
111
112 int removeLength = (index - previous) + 3;
113 base.remove(previous + 1, removeLength);
114 length -= removeLength;
115 index = previous;
116 } else if ((length == (index + 2)) || (base.at(index + 2) == Slash)) {
117 // Either "/./" or "/.<END>"
118 base.remove(index, 2);
119 length -= 2;
120 } else {
121 ++index;
122 }
123 }
124
125 return base;
126 }
127}
128
129} // namespace
130
131/*!
132 \internal
133 \class QQmlImportInstance
134
135 A QQmlImportType represents a single import of a document, held within a
136 namespace.
137
138 \note The uri here may not necessarily be unique (e.g. for file imports).
139
140 \note Version numbers may be -1 for file imports: this means that no
141 version was specified as part of the import. Type resolution will be
142 responsible for attempting to find the "best" possible version.
143*/
144
145/*!
146 \internal
147 \class QQmlImportNamespace
148
149 A QQmlImportNamespace is a way of seperating imports into a local namespace.
150
151 Within a QML document, there is at least one namespace (the
152 "unqualified set") where imports without a qualifier are placed, i.e:
153
154 import QtQuick 2.6
155
156 will have a single namespace (the unqualified set) containing a single import
157 for QtQuick 2.6. However, there may be others if an import statement gives
158 a qualifier, i.e the following will result in an additional new
159 QQmlImportNamespace in the qualified set:
160
161 import MyFoo 1.0 as Foo
162*/
163
164/*!
165\class QQmlImports
166\brief The QQmlImports class encapsulates one QML document's import statements.
167\internal
168*/
169
170QQmlError QQmlImports::moduleNotFoundError(const QString &uri, QTypeRevision version)
171{
172 QQmlError error;
173 if (version.hasMajorVersion()) {
174 error.setDescription(QQmlImports::tr(
175 "module \"%1\" version %2.%3 is not installed")
176 .arg(uri).arg(version.majorVersion())
177 .arg(version.hasMinorVersion()
178 ? QString::number(version.minorVersion())
179 : QLatin1String("x")));
180 } else {
181 error.setDescription(QQmlImports::tr("module \"%1\" is not installed")
182 .arg(uri));
183 }
184 return error;
185}
186
187QTypeRevision QQmlImports::validVersion(QTypeRevision version)
188{
189 // If the given version is invalid, return a valid but useless version to signal "It's OK".
190 return version.isValid() ? version : QTypeRevision::fromMinorVersion(0);
191}
192
193/*!
194 Sets the base URL to be used for all relative file imports added.
195*/
196void QQmlImports::setBaseUrl(const QUrl& url, const QString &urlString)
197{
198 m_baseUrl = url;
199
200 if (urlString.isEmpty())
201 m_base = url.toString();
202 else
203 m_base = urlString;
204}
205
206/*!
207 \fn QQmlImports::baseUrl()
208 \internal
209
210 Returns the base URL to be used for all relative file imports added.
211*/
212
213/*
214 \internal
215
216 This method is responsible for populating data of all types visible in this
217 document's imports into the \a cache for resolution elsewhere (e.g. in JS,
218 or when loading additional types).
219
220 \note This is for C++ types only. Composite types are handled separately,
221 as they do not have a QQmlTypeModule.
222*/
223void QQmlImports::populateCache(QQmlTypeNameCache *cache) const
224{
225 const QQmlImportNamespace &set = m_unqualifiedset;
226
227 for (int ii = set.imports.size() - 1; ii >= 0; --ii) {
228 const QQmlImportInstance *import = set.imports.at(ii);
229 QQmlTypeModule *module = QQmlMetaType::typeModule(import->uri, import->version);
230 if (module) {
231 cache->m_anonymousImports.append(QQmlTypeModuleVersion(module, import->version));
232 }
233 }
234
235 for (QQmlImportNamespace *ns = m_qualifiedSets.first(); ns; ns = m_qualifiedSets.next(ns)) {
236
237 const QQmlImportNamespace &set = *ns;
238
239 // positioning is important; we must create the namespace even if there is no module.
240 QQmlImportRef &typeimport = cache->m_namedImports[set.prefix];
241 typeimport.m_qualifier = set.prefix;
242
243 for (int ii = set.imports.size() - 1; ii >= 0; --ii) {
244 const QQmlImportInstance *import = set.imports.at(ii);
245 QQmlTypeModule *module = QQmlMetaType::typeModule(import->uri, import->version);
246 if (module) {
247 QQmlImportRef &typeimport = cache->m_namedImports[set.prefix];
248 typeimport.modules.append(QQmlTypeModuleVersion(module, import->version));
249 }
250 }
251 }
252}
253
254// We need to exclude the entry for the current baseUrl. This can happen for example
255// when handling qmldir files on the remote dir case and the current type is marked as
256// singleton.
257bool excludeBaseUrl(const QString &importUrl, const QString &fileName, const QString &baseUrl)
258{
259 if (importUrl.isEmpty())
260 return false;
261
262 if (baseUrl.startsWith(importUrl))
263 {
264 if (fileName == QStringView{baseUrl}.mid(importUrl.size()))
265 return false;
266 }
267
268 return true;
269}
270
271void findCompositeSingletons(const QQmlImportNamespace &set, QList<QQmlImports::CompositeSingletonReference> &resultList, const QUrl &baseUrl)
272{
273 typedef QQmlDirComponents::const_iterator ConstIterator;
274
275 for (int ii = set.imports.size() - 1; ii >= 0; --ii) {
276 const QQmlImportInstance *import = set.imports.at(ii);
277
278 const QQmlDirComponents &components = import->qmlDirComponents;
279
280 const QTypeRevision importVersion = import->version;
281 auto shouldSkipSingleton = [importVersion](QTypeRevision singletonVersion) -> bool {
282 return importVersion.hasMajorVersion() &&
283 (singletonVersion.majorVersion() > importVersion.majorVersion()
284 || (singletonVersion.majorVersion() == importVersion.majorVersion()
285 && singletonVersion.minorVersion() > importVersion.minorVersion()));
286 };
287
288 ConstIterator cend = components.constEnd();
289 for (ConstIterator cit = components.constBegin(); cit != cend; ++cit) {
290 if (cit->singleton && excludeBaseUrl(import->url, cit->fileName, baseUrl.toString())) {
291 if (shouldSkipSingleton(cit->version))
292 continue;
293 QQmlImports::CompositeSingletonReference ref;
294 ref.typeName = cit->typeName;
295 ref.prefix = set.prefix;
296 ref.version = cit->version;
297 resultList.append(ref);
298 }
299 }
300
301 if (QQmlTypeModule *module = QQmlMetaType::typeModule(import->uri, import->version)) {
302 module->walkCompositeSingletons([&resultList, &set, &shouldSkipSingleton](const QQmlType &singleton) {
303 if (shouldSkipSingleton(singleton.version()))
304 return;
305 QQmlImports::CompositeSingletonReference ref;
306 ref.typeName = singleton.elementName();
307 ref.prefix = set.prefix;
308 ref.version = singleton.version();
309 resultList.append(ref);
310 });
311 }
312 }
313}
314
315/*
316 \internal
317
318 Returns a list of all composite singletons present in this document's
319 imports.
320
321 This information is used by QQmlTypeLoader to ensure that composite singletons
322 are marked as dependencies during type loading.
323*/
324QList<QQmlImports::CompositeSingletonReference> QQmlImports::resolvedCompositeSingletons() const
325{
326 QList<QQmlImports::CompositeSingletonReference> compositeSingletons;
327
328 const QQmlImportNamespace &set = m_unqualifiedset;
329 findCompositeSingletons(set, compositeSingletons, baseUrl());
330
331 for (QQmlImportNamespace *ns = m_qualifiedSets.first(); ns; ns = m_qualifiedSets.next(ns)) {
332 const QQmlImportNamespace &set = *ns;
333 findCompositeSingletons(set, compositeSingletons, baseUrl());
334 }
335
336 std::stable_sort(compositeSingletons.begin(), compositeSingletons.end(),
337 [](const QQmlImports::CompositeSingletonReference &lhs,
338 const QQmlImports::CompositeSingletonReference &rhs) {
339 if (lhs.prefix != rhs.prefix)
340 return lhs.prefix < rhs.prefix;
341
342 if (lhs.typeName != rhs.typeName)
343 return lhs.typeName < rhs.typeName;
344
345 return lhs.version.majorVersion() != rhs.version.majorVersion()
346 ? lhs.version.majorVersion() < rhs.version.majorVersion()
347 : lhs.version.minorVersion() < rhs.version.minorVersion();
348 });
349
350 return compositeSingletons;
351}
352
353/*
354 \internal
355
356 Returns a list of scripts imported by this document. This is used by
357 QQmlTypeLoader to properly handle dependencies on imported scripts.
358*/
359QList<QQmlImports::ScriptReference> QQmlImports::resolvedScripts() const
360{
361 QList<QQmlImports::ScriptReference> scripts;
362
363 const QQmlImportNamespace &set = m_unqualifiedset;
364
365 for (int ii = set.imports.size() - 1; ii >= 0; --ii) {
366 const QQmlImportInstance *import = set.imports.at(ii);
367
368 for (const QQmlDirParser::Script &script : import->qmlDirScripts) {
369 ScriptReference ref;
370 ref.nameSpace = script.nameSpace;
371 ref.fileName = QUrl(script.fileName);
372 ref.location = QUrl(import->url).resolved(ref.fileName);
373 scripts.append(ref);
374 }
375 }
376
377 for (QQmlImportNamespace *ns = m_qualifiedSets.first(); ns; ns = m_qualifiedSets.next(ns)) {
378 const QQmlImportNamespace &set = *ns;
379
380 for (int ii = set.imports.size() - 1; ii >= 0; --ii) {
381 const QQmlImportInstance *import = set.imports.at(ii);
382
383 for (const QQmlDirParser::Script &script : import->qmlDirScripts) {
384 ScriptReference ref;
385 ref.nameSpace = script.nameSpace;
386 ref.qualifier = set.prefix;
387 ref.fileName = QUrl(script.fileName);
388 ref.location = QUrl(import->url).resolved(ref.fileName);
389 scripts.append(ref);
390 }
391 }
392 }
393
394 return scripts;
395}
396
397/*!
398 Forms complete paths to a qmldir file, from a base URL, a module URI and version specification.
399
400 For example, QtQml.Models 2.0:
401 - base/QtQml/Models.2.0/qmldir
402 - base/QtQml.2.0/Models/qmldir
403 - base/QtQml/Models.2/qmldir
404 - base/QtQml.2/Models/qmldir
405 - base/QtQml/Models/qmldir
406*/
407QStringList QQmlImports::completeQmldirPaths(const QString &uri, const QStringList &basePaths,
408 QTypeRevision version)
409{
410 QStringList paths = qQmlResolveImportPaths(uri, basePaths, version);
411 for (QString &path : paths)
412 path += Slash_qmldir;
413 return paths;
414}
415
416QString QQmlImports::versionString(QTypeRevision version, ImportVersion versionMode)
417{
418 if (versionMode == QQmlImports::FullyVersioned) {
419 // extension with fully encoded version number (eg. MyModule.3.2)
420 return QString::asprintf(".%d.%d", version.majorVersion(), version.minorVersion());
421 } else if (versionMode == QQmlImports::PartiallyVersioned) {
422 // extension with encoded version major (eg. MyModule.3)
423 return QString::asprintf(".%d", version.majorVersion());
424 } // else extension without version number (eg. MyModule)
425 return QString();
426}
427
428/*!
429 \internal
430
431 The given (namespace qualified) \a type is resolved to either
432 \list
433 \li a QQmlImportNamespace stored at \a result in \c{ns}, or
434 \li a QQmlType stored at \a result in \c{type},
435 \endlist
436
437 If any return pointer is 0, the corresponding search is not done.
438
439 \sa addFileImport(), addLibraryImport
440*/
441bool QQmlImports::resolveType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type,
442 QQmlImportResolutionResult *result,
443 QQmlType::RegistrationType registrationType,
444 QQmlImport::RecursionRestriction recursionRestriction) const
445{
446 QQmlImportNamespace *ns = findQualifiedNamespace(type);
447 if (ns) {
448 result->ns = ns;
449 return true;
450 }
451 if (resolveQualifiedType(typeLoader, type, result, registrationType, recursionRestriction)) {
452 if (lcQmlImport().isDebugEnabled()) {
453#define RESOLVE_TYPE_DEBUG qCDebug(lcQmlImport)
454 << "resolveType:" << qPrintable(baseUrl().toString()) << type.toString() << " => "
455
456 if (result->type.isValid()) {
457 if (result->type.isCompositeSingleton()) {
458 RESOLVE_TYPE_DEBUG << result->type.typeName() << ' '
459 << result->type.sourceUrl() << " TYPE/URL-SINGLETON";
460 } else if (result->type.isInlineComponent()) {
461 RESOLVE_TYPE_DEBUG << result->type.typeName() << ' '
462 << result->type.sourceUrl() << " TYPE(INLINECOMPONENT)";
463 } else if (result->type.isComposite()) {
464 RESOLVE_TYPE_DEBUG << result->type.typeName() << ' '
465 << result->type.sourceUrl() << " TYPE/URL";
466 } else {
467 RESOLVE_TYPE_DEBUG << result->type.typeName() << " TYPE";
468 }
469 }
470#undef RESOLVE_TYPE_DEBUG
471 }
472 return true;
473 }
474 return false;
475}
476
477const QQmlImportInstance *QQmlImports::findImportByModuleUri(const QString &uri,
478 QTypeRevision version) const
479{
480 if (const QQmlImportInstance *import = m_unqualifiedset.findImportByModuleUri(uri, version))
481 return import;
482
483 for (QQmlImportNamespace *ns = m_qualifiedSets.first(); ns; ns = m_qualifiedSets.next(ns)) {
484 if (const QQmlImportInstance *import = ns->findImportByModuleUri(uri, version))
485 return import;
486 }
487
488 return nullptr;
489}
490
491bool QQmlImportInstance::setQmldirContent(const QString &resolvedUrl,
492 const QQmlTypeLoaderQmldirContent &qmldir,
493 QQmlImportNamespace *nameSpace, QList<QQmlError> *errors)
494{
495 Q_ASSERT(resolvedUrl.endsWith(Slash));
496 url = resolvedUrl;
497
498 qmlDirComponents = qmldir.components();
499
500 const QQmlDirScripts &scripts = qmldir.scripts();
501 if (!scripts.isEmpty()) {
502 // Verify that we haven't imported these scripts already
503 for (QList<QQmlImportInstance *>::const_iterator it = nameSpace->imports.constBegin();
504 it != nameSpace->imports.constEnd(); ++it) {
505 if ((*it != this) && ((*it)->uri == uri)) {
506 QQmlError error;
507 error.setDescription(
508 QQmlImports::tr("\"%1\" is ambiguous. Found in %2 and in %3")
509 .arg(uri, url, (*it)->url));
510 errors->prepend(error);
511 return false;
512 }
513 }
514
515 qmlDirScripts = getVersionedScripts(scripts, version);
516 }
517
518 return true;
519}
520
521QQmlDirScripts QQmlImportInstance::getVersionedScripts(const QQmlDirScripts &qmldirscripts,
522 QTypeRevision version)
523{
524 QMap<QString, QQmlDirParser::Script> versioned;
525
526 for (QList<QQmlDirParser::Script>::const_iterator sit = qmldirscripts.constBegin();
527 sit != qmldirscripts.constEnd(); ++sit) {
528 // Only include scripts that match our requested version
529 if ((!version.hasMajorVersion() || (sit->version.majorVersion() == version.majorVersion()))
530 && (!version.hasMinorVersion()
531 || (sit->version.minorVersion() <= version.minorVersion()))) {
532 // Load the highest version that matches
533 const auto vit = versioned.constFind(sit->nameSpace);
534 if (vit == versioned.cend()
535 || (vit->version.minorVersion() < sit->version.minorVersion())) {
536 versioned.insert(sit->nameSpace, *sit);
537 }
538 }
539 }
540
541 return versioned.values();
542}
543
544/*!
545 \internal
546
547 Searching \e only in the namespace \c{ns} in \a result (previously returned in a call to
548 resolveType(), \a type is found and returned to
549 a QQmlType stored at \c{type} in \a result. If the type is from a QML file, the returned
550 type will be a CompositeType.
551
552 If the return pointer is 0, the corresponding search is not done.
553*/
554
555bool QQmlImportInstance::resolveType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type,
557 QQmlType::RegistrationType registrationType,
558 QQmlImport::RecursionRestriction recursionRestriction) const
559{
560 // QQmlMetaType assumes that without a URI, it should look for types in any module
561 // But QQmlImportInstance without a URI represents a directory import, and _must not_ find
562 // types from completely unrelated modules
563 QQmlType t = uri.isEmpty() ? QQmlType() : QQmlMetaType::qmlType(type, uri, version);
564 if (t.isValid()) {
565 result->version = version;
566 result->url = t.sourceUrl();
567 result->type = t;
568 return true;
569 }
570
571 const QStringView typeView(type.constData(), type.length());
572 if (isInlineComponent) {
573 bool ret = type == uri;
574 if (ret) {
575 Q_ASSERT(!result->type.isValid());
576 result->url = QUrl(url);
577 result->type = QQmlMetaType::findOrCreateSpeculativeInlineComponentType(result->url);
578 // If the IC doesn't exist in an already-registered CU, we get an invalid type
579 if (!result->type.isValid())
580 ret = false;
581 }
582 return ret;
583 }
584 QQmlDirComponents::ConstIterator it = qmlDirComponents.constFind(typeView);
585 const QQmlDirComponents::ConstIterator end = qmlDirComponents.constEnd();
586 if (it != end) {
587 QString componentUrl;
588 QQmlMetaType::CompositeTypeLookupMode lookupMode = QQmlMetaType::NonSingleton;
589 QQmlDirComponents::ConstIterator candidate = end;
590 for ( ; it != end && type == it.key(); ++it) {
591 const QQmlDirParser::Component &c = *it;
592 switch (registrationType) {
593 case QQmlType::AnyRegistrationType:
594 break;
595 case QQmlType::CompositeSingletonType:
596 if (!c.singleton)
597 continue;
598 break;
599 default:
600 if (c.singleton)
601 continue;
602 break;
603 }
604
605 // importing invalid version means import ALL versions
606 if (!version.hasMajorVersion() || (implicitlyImported && c.internal)
607 // allow the implicit import of internal types
608 || (c.version.majorVersion() == version.majorVersion()
609 && c.version.minorVersion() <= version.minorVersion())) {
610 // Is this better than the previous candidate?
611 if ((candidate == end)
612 || (c.version.majorVersion() > candidate->version.majorVersion())
613 || ((c.version.majorVersion() == candidate->version.majorVersion())
614 && (c.version.minorVersion() > candidate->version.minorVersion()))) {
615 if (!result->base.isEmpty()) {
616 componentUrl = resolveLocalUrl(QString(url + c.typeName + dotqml_string), c.fileName);
617 if (c.internal && resolveLocalUrl(result->base, c.fileName) != componentUrl) {
618 // This can happen if the module is spread over multiple directories.
619 // We need to check that the accessing component belongs to the same
620 // module.
621 const auto componentsBegin = qmlDirComponents.cbegin();
622 const auto componentsEnd = qmlDirComponents.cend();
623 if (std::find_if(componentsBegin, componentsEnd,
624 [&](const QQmlDirParser::Component &component) {
625 return resolveLocalUrl(url, component.fileName)
626 == result->base;
627 })
628 == componentsEnd) {
629 continue; // failed attempt to access an internal type
630 }
631 }
632
633 const bool recursion = result->base == componentUrl;
634 result->typeRecursionDetected = recursion;
635
636 if (recursionRestriction == QQmlImport::PreventRecursion && recursion) {
637 continue; // no recursion
638 }
639 }
640
641 // This is our best candidate so far
642 candidate = it;
643 lookupMode = c.singleton ? QQmlMetaType::Singleton : QQmlMetaType::NonSingleton;
644 }
645 }
646 }
647
648 if (candidate != end) {
649 if (result->base.isEmpty()) // ensure we have a componentUrl
650 componentUrl = resolveLocalUrl(QString(url + candidate->typeName + dotqml_string), candidate->fileName);
651 result->url = QUrl(componentUrl);
652 QQmlType returnType = QQmlMetaType::typeForUrl(
653 typeLoader->interceptUrl(result->url, QQmlAbstractUrlInterceptor::QmlFile),
654 type, lookupMode, nullptr, candidate->version);
655 result->version = candidate->version;
656 result->type = returnType;
657 return returnType.isValid();
658 }
659 } else if (!isLibrary) {
660 // the base path of the import if it's a local file
661 const QString localDirectoryPath = QQmlFile::urlToLocalFileOrQrc(url);
662 if (localDirectoryPath.isEmpty())
663 return false;
664
665 QString qmlUrl;
666
667 const QString urlsToTry[2] = {
668 typeView + dotqml_string, // Type -> Type.qml
669 typeView + dotuidotqml_string // Type -> Type.ui.qml
670 };
671 for (const QString &urlToTry : urlsToTry) {
672 if (typeLoader->fileExists(localDirectoryPath, urlToTry)) {
673 qmlUrl = url + urlToTry;
674 break;
675 }
676 }
677
678 if (!qmlUrl.isEmpty()) {
679 const bool recursion = !result->base.isEmpty() && result->base == qmlUrl;
680 result->typeRecursionDetected = recursion;
681 if (recursionRestriction == QQmlImport::AllowRecursion || !recursion) {
682 result->url = QUrl(qmlUrl);
683 QQmlType returnType = QQmlMetaType::typeForUrl(
684 typeLoader->interceptUrl(result->url, QQmlAbstractUrlInterceptor::QmlFile),
685 type, registrationType == QQmlType::CompositeSingletonType
686 ? QQmlMetaType::Singleton
687 : QQmlMetaType::NonSingleton,
688 &result->errors);
689 result->type = returnType;
690 return returnType.isValid();
691 }
692 }
693 }
694
695 return false;
696}
697
698bool QQmlImports::resolveQualifiedType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type,
699 QQmlImportResolutionResult *result,
700 QQmlType::RegistrationType registrationType,
701 QQmlImport::RecursionRestriction recursionRestriction) const
702{
703 const QList<QHashedStringRef> splitName = type.split(Dot);
704
705 auto resolveTypeInNamespace = [&](
706 QHashedStringRef unqualifiedtype, QQmlImportNamespace *nameSpace) -> bool {
707 result->base = m_base;
708 if (nameSpace->resolveType(
709 typeLoader, unqualifiedtype, result, registrationType, recursionRestriction)) {
710 return true;
711 }
712 if (nameSpace->imports.size() == 1
713 && !nameSpace->imports.at(0)->isLibrary
714 && nameSpace != &m_unqualifiedset) {
715 // qualified, and only 1 url
716 const QString urlString = resolveLocalUrl(
717 nameSpace->imports.at(0)->url, unqualifiedtype.toString() + dotqml_string);
718 result->url = QUrl(urlString);
719 result->type = QQmlMetaType::typeForUrl(
720 typeLoader->interceptUrl(result->url, QQmlAbstractUrlInterceptor::QmlFile),
721 type, QQmlMetaType::NonSingleton, &result->errors);
722 return result->type.isValid();
723 }
724 return false;
725 };
726
727 switch (splitName.size()) {
728 case 1: {
729 // must be a simple type
730 return resolveTypeInNamespace(type, &m_unqualifiedset);
731 }
732 case 2: {
733 // either namespace + simple type OR simple type + inline component OR failure
734 QQmlImportNamespace *s = findQualifiedNamespace(splitName.at(0));
735
736 if (s) {
737 // namespace + simple type
738 return resolveTypeInNamespace(splitName.at(1), s);
739 }
740
741 {
742 // Preserve the original errors
743 QList<QQmlError> errors = std::exchange(result->errors, {});
744 const auto restoreErrors = qScopeGuard([&]() { result->errors = std::move(errors); });
745
746 if (resolveTypeInNamespace(splitName.at(0), &m_unqualifiedset)) {
747 // simple type + inline component
748 result->type = QQmlMetaType::findOrCreateSpeculativeInlineComponentType(
749 result->type, splitName.at(1).toString());
750 if (result->type.isValid())
751 return true;
752 }
753 }
754
755 // failure
756 QQmlError error;
757 error.setDescription(QQmlImports::tr("- %1 is neither a type nor a namespace")
758 .arg(splitName.at(0).toString()));
759 result->errors.prepend(error);
760 return false;
761 }
762 case 3: {
763 // must be namespace + simple type + inline component
764 QQmlImportNamespace *s = findQualifiedNamespace(splitName.at(0));
765 QQmlError error;
766 if (!s) {
767 error.setDescription(QQmlImports::tr("- %1 is not a namespace").arg(splitName.at(0).toString()));
768 } else {
769 // Preserve the original errors
770 QList<QQmlError> errors = std::exchange(result->errors, {});
771 const auto restoreErrors = qScopeGuard([&]() { result->errors = std::move(errors); });
772
773 if (resolveTypeInNamespace(splitName.at(1), s)) {
774 result->type = QQmlMetaType::findOrCreateSpeculativeInlineComponentType(
775 result->type, splitName.at(2).toString());
776 if (result->type.isValid())
777 return true;
778
779 // IC doesn't exist in already-registered base type
780 error.setDescription(QQmlImports::tr(
781 "- %1 is not an inline component")
782 .arg(splitName.at(2).toString()));
783 } else {
784 error.setDescription(QQmlImports::tr("- %1 is not a type").arg(splitName.at(1).toString()));
785 }
786 }
787 result->errors.prepend(error);
788 return false;
789 }
790 default: {
791 // all other numbers suggest a user error
792 QQmlError error;
793 error.setDescription(QQmlImports::tr("- nested namespaces not allowed"));
794 result->errors.prepend(error);
795 return false;
796 }
797 }
798 Q_UNREACHABLE();
799}
800
802 const QString &moduleUri, QTypeRevision version) const
803{
804 const auto end = imports.cend();
805 const auto it = std::find_if(imports.cbegin(), end, [&](const QQmlImportInstance *import) {
806 return import->uri == moduleUri && import->version == version;
807 });
808 return it == end ? nullptr : *it;
809}
810
812 const QString &location, QTypeRevision version) const
813{
814 const auto end = imports.cend();
815 const auto it = std::find_if(imports.cbegin(), end, [&](const QQmlImportInstance *import) {
816 return import->url == location && import->version == version;
817 });
818 return it == end ? nullptr : *it;
819}
820
821bool QQmlImportNamespace::resolveType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type,
823 QQmlType::RegistrationType registrationType,
824 QQmlImport::RecursionRestriction recursionRestriction)
825{
826 // TODO: move the sorting somewhere else and make resolveType() const.
827 if (needsSorting()) {
828 std::stable_partition(imports.begin(), imports.end(), [](QQmlImportInstance *import) {
829 return import->isInlineComponent;
830 });
832 }
833 for (int i=0; i<imports.size(); ++i) {
834 const QQmlImportInstance *import = imports.at(i);
835 if (import->resolveType(typeLoader, type, result, registrationType, recursionRestriction)) {
836 if (qmlCheckTypes()) {
837 // check for type clashes
838 for (int j = i+1; j<imports.size(); ++j) {
839 const QQmlImportInstance *import2 = imports.at(j);
841 clash.base = result->base;
842 if (import2->resolveType(typeLoader, type, &clash, registrationType)) {
843 QString u1 = import->url;
844 QString u2 = import2->url;
845 if (!result->base.isEmpty()) {
846 QStringView b(result->base);
847 int dot = b.lastIndexOf(Dot);
848 if (dot >= 0) {
849 b = b.left(dot+1);
850 QStringView l = b.left(dot);
851 if (u1.startsWith(b))
852 u1 = u1.mid(b.size());
853 else if (u1 == l)
854 u1 = QQmlImports::tr("local directory");
855 if (u2.startsWith(b))
856 u2 = u2.mid(b.size());
857 else if (u2 == l)
858 u2 = QQmlImports::tr("local directory");
859 }
860 }
861
862 QQmlError error;
863 if (u1 != u2) {
864 error.setDescription(
865 QQmlImports::tr(
866 "is ambiguous. Found in %1 and in %2")
867 .arg(u1, u2));
868 } else {
869 error.setDescription(
870 QQmlImports::tr(
871 "is ambiguous. Found in %1 in version "
872 "%2.%3 and %4.%5")
873 .arg(u1)
874 .arg(import->version.majorVersion())
875 .arg(import->version.minorVersion())
876 .arg(import2->version.majorVersion())
877 .arg(import2->version.minorVersion()));
878 }
879 result->errors.prepend(error);
880 return false;
881 }
882 }
883 }
884 return true;
885 }
886 }
887
888 QQmlError error;
889 if (result->typeRecursionDetected)
890 error.setDescription(QQmlImports::tr("is instantiated recursively"));
891 else
892 error.setDescription(QQmlImports::tr("is not a type"));
893 result->errors.prepend(error);
894 return false;
895}
896
897QQmlImportNamespace *QQmlImports::findQualifiedNamespace(const QHashedStringRef &prefix) const
898{
899 for (QQmlImportNamespace *ns = m_qualifiedSets.first(); ns; ns = m_qualifiedSets.next(ns)) {
900 if (prefix == ns->prefix)
901 return ns;
902 }
903 return nullptr;
904}
905
906/*
907Import an extension defined by a qmldir file.
908*/
909QTypeRevision QQmlImports::importExtension(
910 QQmlTypeLoader *typeLoader, const QString &uri, QTypeRevision version,
911 const QQmlTypeLoaderQmldirContent *qmldir, QList<QQmlError> *errors)
912{
913 Q_ASSERT(qmldir->hasContent());
914
915 qCDebug(lcQmlImport)
916 << "importExtension:" << qPrintable(m_base) << "loaded" << qmldir->qmldirLocation();
917
918 if (designerSupportRequired && !qmldir->designerSupported()) {
919 if (errors) {
920 QQmlError error;
921 error.setDescription(
922 QQmlImports::tr("module does not support the designer \"%1\"")
923 .arg(qmldir->typeNamespace()));
924 error.setUrl(QUrl::fromLocalFile(qmldir->qmldirLocation()));
925 errors->prepend(error);
926 }
927 return QTypeRevision();
928 }
929
930 if (qmldir->plugins().isEmpty())
931 return validVersion(version);
932
933 QQmlPluginImporter importer(uri, version, qmldir, typeLoader, errors);
934 return importer.importPlugins();
935}
936
937void QQmlImports::registerBuiltinModuleTypes(
938 const QQmlTypeLoaderQmldirContent &qmldir, QTypeRevision version)
939{
940 if (!qmldir.plugins().isEmpty())
941 return;
942
943 // If the qmldir does not register a plugin, we might still have declaratively
944 // registered types (if we are dealing with an application instead of a library)
945
946 const QString qmldirUri = qmldir.typeNamespace();
947 if (!QQmlMetaType::typeModule(qmldirUri, version))
948 QQmlMetaType::qmlRegisterModuleTypes(qmldirUri);
949}
950
951QString QQmlImports::redirectQmldirContent(
952 QQmlTypeLoader *typeLoader, QQmlTypeLoaderQmldirContent *qmldir)
953{
954 const QString preferredPath = qmldir->preferredPath();
955 const QString url = preferredPath.startsWith(u':')
956 ? QStringLiteral("qrc") + preferredPath
957 : QUrl::fromLocalFile(preferredPath).toString();
958
959 QQmlTypeLoaderQmldirContent redirected
960 = typeLoader->qmldirContent(url + QLatin1String("qmldir"));
961
962 // Ignore errors: If the qmldir doesn't exist, stick to the old one.
963 if (redirected.hasContent() && !redirected.hasError())
964 *qmldir = std::move(redirected);
965
966 return url;
967}
968
969bool QQmlImports::getQmldirContent(
970 QQmlTypeLoader *typeLoader, const QString &qmldirIdentifier, const QString &uri,
971 QQmlTypeLoaderQmldirContent *qmldir, QList<QQmlError> *errors)
972{
973 Q_ASSERT(errors);
974 Q_ASSERT(qmldir);
975
976 *qmldir = typeLoader->qmldirContent(qmldirIdentifier);
977 if (!qmldir->hasContent() || !qmldir->hasError())
978 return true;
979
980 errors->append(qmldir->errors(uri, QUrl::fromLocalFile(qmldirIdentifier)));
981 return false;
982}
983
984QString QQmlImports::resolvedUri(const QString &dir_arg, QQmlTypeLoader *typeLoader)
985{
986 QString dir = dir_arg;
987 if (dir.endsWith(Slash) || dir.endsWith(Backslash))
988 dir.chop(1);
989
990 QStringList paths = typeLoader->importPathList();
991 if (!paths.isEmpty())
992 std::sort(paths.begin(), paths.end(), std::greater<QString>()); // Ensure subdirs preceed their parents.
993
994 QString stableRelativePath = dir;
995 for (const QString &path : std::as_const(paths)) {
996 if (dir.startsWith(path)) {
997 stableRelativePath = dir.mid(path.size()+1);
998 break;
999 }
1000 }
1001
1002 stableRelativePath.replace(Backslash, Slash);
1003
1004 // remove optional versioning in dot notation from uri
1005 int versionDot = stableRelativePath.lastIndexOf(Dot);
1006 if (versionDot >= 0) {
1007 int nextSlash = stableRelativePath.indexOf(Slash, versionDot);
1008 if (nextSlash >= 0)
1009 stableRelativePath.remove(versionDot, nextSlash - versionDot);
1010 else
1011 stableRelativePath = stableRelativePath.left(versionDot);
1012 }
1013
1014 stableRelativePath.replace(Slash, Dot);
1015
1016 return stableRelativePath;
1017}
1018
1020 const QQmlTypeLoaderQmldirContent &qmldir, const QString &uri, QTypeRevision version,
1021 QList<QQmlError> *errors)
1022{
1023 int bestMajorVersion = -1;
1024 quint8 lowestMinorVersion = std::numeric_limits<quint8>::max();
1025 quint8 highestMinorVersion = 0;
1026
1027 auto addVersion = [&](QTypeRevision newVersion) {
1028 if (!newVersion.hasMajorVersion())
1029 return;
1030 if (!version.hasMajorVersion() || version.majorVersion() == newVersion.majorVersion()) {
1031 if (newVersion.majorVersion() > bestMajorVersion) {
1032 bestMajorVersion = newVersion.majorVersion();
1033 if (newVersion.hasMinorVersion()) {
1034 lowestMinorVersion = newVersion.minorVersion();
1035 highestMinorVersion = newVersion.minorVersion();
1036 }
1037 } else if (newVersion.majorVersion() == bestMajorVersion
1038 && newVersion.hasMinorVersion()) {
1039 lowestMinorVersion = qMin(lowestMinorVersion, newVersion.minorVersion());
1040 highestMinorVersion = qMax(highestMinorVersion, newVersion.minorVersion());
1041 }
1042 }
1043 };
1044
1045 typedef QQmlDirComponents::const_iterator ConstIterator;
1046 const QQmlDirComponents &components = qmldir.components();
1047
1048 const QQmlDirExports exports = qmldir.exports();
1049 for (QQmlDirParser::Export exp : exports) {
1050 Q_ASSERT(exp.hasMajorVersion()); // Can't specify a minor-only version in qmldir
1051 addVersion(QTypeRevision::fromVersion(exp.majorVersion(), 0));
1052 addVersion(exp.hasMinorVersion() ? exp
1053 : QTypeRevision::fromVersion(exp.majorVersion(), 254));
1054 }
1055
1056 ConstIterator cend = components.constEnd();
1057 for (ConstIterator cit = components.constBegin(); cit != cend; ++cit) {
1058 for (ConstIterator cit2 = components.constBegin(); cit2 != cit; ++cit2) {
1059 if (cit2->typeName == cit->typeName && cit2->version == cit->version) {
1060 // This entry clashes with a predecessor
1061 QQmlError error;
1062 error.setDescription(
1063 QQmlImports::tr(
1064 "\"%1\" version %2.%3 is defined more than once in module \"%4\"")
1065 .arg(cit->typeName).arg(cit->version.majorVersion())
1066 .arg(cit->version.minorVersion()).arg(uri));
1067 errors->prepend(error);
1068 return QTypeRevision();
1069 }
1070 }
1071
1072 addVersion(cit->version);
1073 }
1074
1075 typedef QList<QQmlDirParser::Script>::const_iterator SConstIterator;
1076 const QQmlDirScripts &scripts = qmldir.scripts();
1077
1078 SConstIterator send = scripts.constEnd();
1079 for (SConstIterator sit = scripts.constBegin(); sit != send; ++sit) {
1080 for (SConstIterator sit2 = scripts.constBegin(); sit2 != sit; ++sit2) {
1081 if (sit2->nameSpace == sit->nameSpace && sit2->version == sit->version) {
1082 // This entry clashes with a predecessor
1083 QQmlError error;
1084 error.setDescription(QQmlImports::tr("\"%1\" version %2.%3 is defined more than once in module \"%4\"")
1085 .arg(sit->nameSpace).arg(sit->version.majorVersion())
1086 .arg(sit->version.minorVersion()).arg(uri));
1087 errors->prepend(error);
1088 return QTypeRevision();
1089 }
1090 }
1091
1092 addVersion(sit->version);
1093 }
1094
1095 // Failure to find a match is only an error if we were asking for a specific version ...
1096 if (version.hasMajorVersion()
1097 && (bestMajorVersion < 0
1098 || (version.hasMinorVersion()
1099 && (lowestMinorVersion > version.minorVersion()
1100 || highestMinorVersion < version.minorVersion())))) {
1101 errors->prepend(QQmlImports::moduleNotFoundError(uri, version));
1102 return QTypeRevision();
1103 }
1104
1105 // ... otherwise, anything is valid.
1106 if (bestMajorVersion < 0)
1107 return QQmlImports::validVersion();
1108
1109 return QTypeRevision::fromVersion(
1110 bestMajorVersion,
1111 (version.hasMajorVersion() && version.hasMinorVersion())
1112 ? version.minorVersion()
1113 : highestMinorVersion);
1114}
1115
1116QQmlImportNamespace *QQmlImports::importNamespace(const QString &prefix)
1117{
1118 QQmlImportNamespace *nameSpace = nullptr;
1119
1120 if (prefix.isEmpty()) {
1121 nameSpace = &m_unqualifiedset;
1122 } else {
1123 nameSpace = findQualifiedNamespace(prefix);
1124
1125 if (!nameSpace) {
1126 nameSpace = new QQmlImportNamespace;
1127 nameSpace->prefix = prefix;
1128 m_qualifiedSets.append(nameSpace);
1129 }
1130 }
1131
1132 return nameSpace;
1133}
1134
1135static QString getVersionInfo(QTypeRevision version) {
1136 return version.isValid() ? QDebug::toString(version) : u"(latest)"_s;
1137}
1138
1140 const QString &uri, QTypeRevision version, QList<QQmlError> *errors)
1141{
1142 const QTypeRevision matchingVersion = QQmlMetaType::matchingModuleVersion(uri, version);
1143 if (!matchingVersion.isValid())
1144 errors->prepend(QQmlImports::moduleNotFoundError(uri, relevantVersion(uri, version)));
1145 return matchingVersion;
1146}
1147
1149 const QString &uri, QTypeRevision version, const QQmlTypeLoaderQmldirContent &qmldir,
1150 QQmlImportInstance *inserted, QList<QQmlError> *errors)
1151{
1152 // Ensure that we are actually providing something
1153 const QTypeRevision matchingVersion = QQmlMetaType::matchingModuleVersion(uri, version);
1154 if (matchingVersion.isValid())
1155 return matchingVersion;
1156
1157 if (inserted->qmlDirComponents.isEmpty() && inserted->qmlDirScripts.isEmpty()) {
1158 if (qmldir.plugins().isEmpty()) {
1159 if (!qmldir.imports().isEmpty())
1160 return QQmlImports::validVersion(); // This is a pure redirection
1161 if (qmldir.hasTypeInfo())
1162 return QQmlImports::validVersion(); // A pure C++ module without plugin
1163 }
1164 errors->prepend(QQmlImports::moduleNotFoundError(uri, relevantVersion(uri, version)));
1165 return QTypeRevision();
1166 } else {
1167 // Verify that the qmldir content is valid for this version
1168 version = matchingQmldirVersion(qmldir, uri, version, errors);
1169 if (!version.isValid())
1170 return QTypeRevision();
1171 }
1172
1173 Q_ASSERT(version.isValid());
1174 return version;
1175}
1176
1177QTypeRevision QQmlImports::addLibraryImport(
1178 QQmlTypeLoader *typeLoader, const QString &uri, const QString &prefix,
1179 QTypeRevision requestedVersion, const QString &qmldirIdentifier, const QString &qmldirUrl,
1180 ImportFlags flags, quint8 precedence, QList<QQmlError> *errors)
1181{
1182 Q_ASSERT(typeLoader);
1183 Q_ASSERT(errors);
1184
1185 if (lcQmlImport().isDebugEnabled()) {
1186 qCDebug(lcQmlImport)
1187 << "addLibraryImport:" << qPrintable(baseUrl().toString())
1188 << uri << "version" << getVersionInfo(requestedVersion) << "as" << prefix;
1189 }
1190
1191 QQmlImportNamespace *nameSpace = importNamespace(prefix);
1192 Q_ASSERT(nameSpace);
1193
1194 const bool noQmldir = qmldirIdentifier.isEmpty();
1195 const bool isIncomplete = (flags & QQmlImports::ImportIncomplete);
1196 if (noQmldir || isIncomplete) {
1197 QQmlImportInstance *inserted = addImportToNamespace<IsLibrary::Yes>(
1198 nameSpace, uri, qmldirUrl, requestedVersion, precedence);
1199 Q_ASSERT(inserted);
1200
1201 if (noQmldir && !isIncomplete) {
1202 // No need to wait for the qmldir to become available if we're not supposed to use it.
1203 if (!QQmlMetaType::typeModule(uri, requestedVersion))
1204 QQmlMetaType::qmlRegisterModuleTypes(uri);
1205 return matchingModuleVersionForLibraryImport(uri, requestedVersion, errors);
1206 }
1207
1208 return validVersion(requestedVersion);
1209 }
1210
1211 QQmlTypeLoaderQmldirContent qmldir;
1212 if (!getQmldirContent(typeLoader, qmldirIdentifier, uri, &qmldir, errors)) {
1213 // qmldir had errors.
1214 return QTypeRevision();
1215 }
1216
1217 // qmldir is remote and can't be loaded synchronously, but we may already know the module.
1218 if (!qmldir.hasContent())
1219 return matchingModuleVersionForLibraryImport(uri, requestedVersion, errors);
1220
1221 // Load the plugin before redirecting. Otherwise we might not find the qmldir we're looking for.
1222 const QTypeRevision importedVersion = importExtension(
1223 typeLoader, uri, requestedVersion, &qmldir, errors);
1224 if (!importedVersion.isValid())
1225 return QTypeRevision();
1226
1227 QString resolvedUrl;
1228 QString resolvedUri;
1229 if (qmldir.hasRedirection()) {
1230 resolvedUrl = redirectQmldirContent(typeLoader, &qmldir);
1231 resolvedUri = qmldir.typeNamespace();
1232 } else {
1233 resolvedUrl = qmldirUrl;
1234 resolvedUri = uri;
1235 }
1236
1237 if (QQmlImportInstance *existing
1238 = nameSpace->findImportByLocation(resolvedUrl, requestedVersion);
1239 existing && existing->isLibrary && existing->uri == resolvedUri) {
1240 // Even if the precedence stays the same we have to re-insert. The ordering wrt other
1241 // imports of the same precendence may change.
1242 nameSpace->imports.removeOne(existing);
1243 existing->precedence = std::min(precedence, existing->precedence);
1244 existing->implicitlyImported = existing->precedence >= QQmlImportInstance::Implicit;
1245 insertImport(nameSpace, existing);
1246 return finalizeLibraryImport(uri, importedVersion, qmldir, existing, errors);
1247 }
1248
1249 return finalizeImport<IsLibrary::Yes>(
1250 nameSpace, qmldir, resolvedUri, resolvedUrl, precedence, requestedVersion,
1251 importedVersion, errors, [&](QQmlImportInstance *inserted) {
1252 return finalizeLibraryImport(uri, importedVersion, qmldir, inserted, errors);
1253 });
1254}
1255
1256/*!
1257 \internal
1258
1259 Adds information to \a database such that subsequent calls to resolveType()
1260 will resolve types qualified by \a prefix by considering types found at the given \a uri.
1261
1262 The \a uri is either a directory (if importType is FileImport), or a URI resolved using paths
1263 added via addImportPath() (if importType is LibraryImport).
1264
1265 The \a prefix may be empty, in which case the import location is considered for
1266 unqualified types.
1267
1268 The base URL must already have been set with Import::setBaseUrl().
1269
1270 Optionally, the qmldir the import resolved to can be returned by providing the \a localQmldir
1271 parameter. Not all imports will have a local qmldir. If there is none, the \a localQmldir
1272 parameter won't be set.
1273
1274 Returns a valid QTypeRevision on success, and an invalid one on failure.
1275 In case of failure, the \a errors array will filled appropriately.
1276*/
1277QTypeRevision QQmlImports::addFileImport(
1278 QQmlTypeLoader *typeLoader, const QString &uri, const QString &prefix,
1279 QTypeRevision requestedVersion, ImportFlags flags, quint8 precedence, QString *localQmldir,
1280 QList<QQmlError> *errors)
1281{
1282 Q_ASSERT(typeLoader);
1283 Q_ASSERT(errors);
1284
1285 if (lcQmlImport().isDebugEnabled()) {
1286 qCDebug(lcQmlImport)
1287 << "addFileImport:" << qPrintable(baseUrl().toString())
1288 << uri << "version" << getVersionInfo(requestedVersion) << "as" << prefix;
1289 }
1290
1291 if (uri.startsWith(Slash) || uri.startsWith(Colon)) {
1292 QQmlError error;
1293 const QString fix = uri.startsWith(Slash) ? QLatin1String("file:") + uri
1294 : QLatin1String("qrc") + uri;
1295 error.setDescription(QQmlImports::tr(
1296 "\"%1\" is not a valid import URL. "
1297 "You can pass relative paths or URLs with schema, but not "
1298 "absolute paths or resource paths. Try \"%2\".").arg(uri, fix));
1299 errors->prepend(error);
1300 return QTypeRevision();
1301 }
1302
1303 Q_ASSERT(errors);
1304
1305 QQmlImportNamespace *nameSpace = importNamespace(prefix);
1306 Q_ASSERT(nameSpace);
1307
1308 // The uri for this import. For library imports this is the same as uri
1309 // specified by the user, but it may be different in the case of file imports.
1310 QString importUri = uri;
1311 QString qmldirUrl = resolveLocalUrl(m_base, importUri + (importUri.endsWith(Slash)
1312 ? String_qmldir
1313 : Slash_qmldir));
1314 qmldirUrl = typeLoader->interceptUrl(
1315 QUrl(qmldirUrl), QQmlAbstractUrlInterceptor::QmldirFile).toString();
1316 QString qmldirIdentifier;
1317
1318 if (QQmlFile::isLocalFile(qmldirUrl)) {
1319
1320 const QString localFileOrQrc = QQmlFile::urlToLocalFileOrQrc(qmldirUrl);
1321 Q_ASSERT(!localFileOrQrc.isEmpty());
1322
1323 const QString dir = localFileOrQrc.left(localFileOrQrc.lastIndexOf(Slash) + 1);
1324 if (!typeLoader->directoryExists(dir)) {
1325 if (precedence < QQmlImportInstance::Implicit) {
1326 QQmlError error;
1327 error.setDescription(QQmlImports::tr("\"%1\": no such directory").arg(uri));
1328 error.setUrl(QUrl(qmldirUrl));
1329 errors->prepend(error);
1330 }
1331 return QTypeRevision();
1332 }
1333
1334 // Transforms the (possible relative) uri into our best guess relative to the
1335 // import paths.
1336 importUri = resolvedUri(dir, typeLoader);
1337 if (importUri.endsWith(Slash))
1338 importUri.chop(1);
1339
1340 if (QString cleanPath = typeLoader->cleanFilePath(localFileOrQrc); !cleanPath.isEmpty()) {
1341 qmldirIdentifier = std::move(cleanPath);
1342 if (localQmldir)
1343 *localQmldir = qmldirIdentifier;
1344 }
1345
1346 } else if (nameSpace->prefix.isEmpty() && !(flags & QQmlImports::ImportIncomplete)) {
1347
1348 if (precedence < QQmlImportInstance::Implicit) {
1349 QQmlError error;
1350 error.setDescription(QQmlImports::tr("import \"%1\" has no qmldir and no namespace").arg(importUri));
1351 error.setUrl(QUrl(qmldirUrl));
1352 errors->prepend(error);
1353 }
1354
1355 return QTypeRevision();
1356
1357 }
1358
1359 // The url for the path containing files for this import
1360 QString url = resolveLocalUrl(m_base, uri);
1361 if (url.isEmpty()) {
1362 QQmlError error;
1363 error.setDescription(
1364 QQmlImports::tr("Cannot resolve URL for import \"%1\"").arg(uri));
1365 error.setUrl(m_baseUrl);
1366 errors->prepend(error);
1367 return QTypeRevision();
1368 }
1369
1370 if (!url.endsWith(Slash) && !url.endsWith(Backslash))
1371 url += Slash;
1372
1373 // ### For enum support, we are now adding the implicit import always (and earlier). Bail early
1374 // if the implicit import has already been explicitly added, otherwise we can run into issues
1375 // with duplicate imports. However remember that we attempted to add this as implicit import, to
1376 // allow for the loading of internal types.
1377 if (precedence >= QQmlImportInstance::Implicit) {
1378 for (QList<QQmlImportInstance *>::const_iterator it = nameSpace->imports.constBegin();
1379 it != nameSpace->imports.constEnd(); ++it) {
1380 if ((*it)->url == url) {
1381 (*it)->implicitlyImported = true;
1382 return validVersion(requestedVersion);
1383 }
1384 }
1385 }
1386
1387 if ((flags & QQmlImports::ImportIncomplete) || qmldirIdentifier.isEmpty()) {
1388 QQmlImportInstance *inserted = addImportToNamespace<IsLibrary::No>(
1389 nameSpace, importUri, url, requestedVersion, precedence);
1390 Q_ASSERT(inserted);
1391 return validVersion(requestedVersion);
1392 }
1393
1394 QQmlTypeLoaderQmldirContent qmldir;
1395 if (!getQmldirContent(typeLoader, qmldirIdentifier, importUri, &qmldir, errors))
1396 return QTypeRevision();
1397
1398 if (!qmldir.hasContent()) {
1399 QQmlImportInstance *inserted = addImportToNamespace<IsLibrary::No>(
1400 nameSpace, importUri, url, requestedVersion, precedence);
1401 Q_ASSERT(inserted);
1402 return validVersion(requestedVersion);
1403 }
1404
1405 // Prefer the qmldir URI. Unless it doesn't exist.
1406 if (qmldir.hasTypeNamespace())
1407 importUri = qmldir.typeNamespace();
1408
1409 // Load the plugin before redirecting. Otherwise we might not find the qmldir we're looking for.
1410 const QTypeRevision importedVersion
1411 = importExtension(typeLoader, importUri, requestedVersion, &qmldir, errors);
1412 if (!importedVersion.isValid())
1413 return QTypeRevision();
1414
1415 if (qmldir.hasRedirection()) {
1416 const QString resolvedUrl = redirectQmldirContent(typeLoader, &qmldir);
1417 importUri = qmldir.typeNamespace();
1418 if (resolvedUrl != url) {
1419 if (QQmlImportInstance *existing
1420 = nameSpace->findImportByLocation(resolvedUrl, requestedVersion)) {
1421 // We've alraedy seen this import. No need to add another entry.
1422 return validVersion(existing->version);
1423 }
1424 }
1425
1426 return finalizeImport<IsLibrary::No>(
1427 nameSpace, qmldir, importUri, resolvedUrl, precedence, requestedVersion,
1428 importedVersion, errors);
1429 }
1430
1431 return finalizeImport<IsLibrary::No>(
1432 nameSpace, qmldir, importUri, url, precedence, requestedVersion,
1433 importedVersion, errors);
1434}
1435
1436static QTypeRevision qmldirContentError(const QString &uri, QList<QQmlError> *errors)
1437{
1438 if (errors->isEmpty()) {
1439 QQmlError error;
1440 error.setDescription(QQmlTypeLoader::tr("Cannot update qmldir content for '%1'").arg(uri));
1441 errors->prepend(error);
1442 }
1443 return QTypeRevision();
1444}
1445
1446QTypeRevision QQmlImports::updateQmldirContent(
1447 QQmlTypeLoader *typeLoader, const QString &uri, QTypeRevision version,
1448 const QString &prefix, const QString &qmldirIdentifier, const QString &qmldirUrl,
1449 QList<QQmlError> *errors)
1450{
1451 Q_ASSERT(typeLoader);
1452 Q_ASSERT(errors);
1453
1454 qCDebug(lcQmlImport)
1455 << "updateQmldirContent:" << qPrintable(baseUrl().toString())
1456 << uri << "to" << qmldirUrl << "as" << prefix;
1457
1458 QQmlImportNamespace *nameSpace = importNamespace(prefix);
1459 Q_ASSERT(nameSpace);
1460
1461 QQmlImportInstance *import = nameSpace->findImportByModuleUri(uri, version);
1462 if (!import)
1463 return qmldirContentError(uri, errors);
1464
1465 QQmlTypeLoaderQmldirContent qmldir;
1466 if (!getQmldirContent(typeLoader, qmldirIdentifier, uri, &qmldir, errors))
1467 return QTypeRevision();
1468
1469 if (!qmldir.hasContent())
1470 return qmldirContentError(uri, errors);
1471
1472 // Load the plugin before redirecting. Otherwise we might not find the qmldir we're looking for.
1473 version = importExtension(typeLoader, uri, import->version, &qmldir, errors);
1474 if (!version.isValid())
1475 return QTypeRevision();
1476
1477 QString resolvedUrl;
1478 if (qmldir.hasRedirection()) {
1479 resolvedUrl = redirectQmldirContent(typeLoader, &qmldir);
1480 if (resolvedUrl != import->url) {
1481 if (QQmlImportInstance *existing
1482 = nameSpace->findImportByLocation(resolvedUrl, import->version)) {
1483 // We've re-discovered the same module via a different redirect.
1484 // No need to import it again.
1485 nameSpace->imports.removeOne(import);
1486 delete import;
1487 return validVersion(existing->version);
1488 }
1489 import->url = resolvedUrl;
1490 }
1491 import->uri = qmldir.typeNamespace();
1492 } else {
1493 resolvedUrl = qmldirUrl;
1494 }
1495
1496 registerBuiltinModuleTypes(qmldir, version);
1497
1498 if (import->setQmldirContent(resolvedUrl, qmldir, nameSpace, errors)) {
1499 if (import->qmlDirComponents.isEmpty() && import->qmlDirScripts.isEmpty()) {
1500 // The implicit import qmldir can be empty, and plugins have no extra versions
1501 if (uri != QLatin1String(".")
1502 && !QQmlMetaType::matchingModuleVersion(import->uri, version).isValid()) {
1503 errors->prepend(moduleNotFoundError(uri, relevantVersion(uri, version)));
1504 return QTypeRevision();
1505 }
1506 } else {
1507 // Verify that the qmldir content is valid for this version
1508 version = matchingQmldirVersion(qmldir, import->uri, version, errors);
1509 if (!version.isValid())
1510 return QTypeRevision();
1511 }
1512 return validVersion(version);
1513 }
1514
1515 return qmldirContentError(uri, errors);
1516}
1517
1518/*!
1519 \fn QQmlImports::addImplicitImport(QQmlTypeLoader *typeLoader, QString *localQmldir, QList<QQmlError> *errors)
1520 \internal
1521
1522 Adds an implicit "." file import. This is equivalent to calling addFileImport(), but error
1523 messages related to the path or qmldir file not existing are suppressed.
1524
1525 Additionally, this will add the import with lowest instead of highest precedence.
1526*/
1527
1528
1529/*!
1530 \internal
1531 */
1532bool QQmlImports::addInlineComponentImport(
1533 QQmlImportInstance *const importInstance, const QString &name, const QUrl &importUrl)
1534{
1535 importInstance->url = importUrl.toString();
1536 importInstance->uri = name;
1537 importInstance->isInlineComponent = true;
1538 importInstance->version = QTypeRevision::zero();
1539 m_unqualifiedset.imports.push_back(importInstance);
1540 m_unqualifiedset.setNeedsSorting(true);
1541 return true;
1542}
1543
1544QUrl QQmlImports::urlFromLocalFileOrQrcOrUrl(const QString &file)
1545{
1546 QUrl url(QLatin1String(file.at(0) == Colon ? "qrc" : "") + file);
1547
1548 // We don't support single character schemes as those conflict with windows drive letters.
1549 if (url.scheme().size() < 2)
1550 return QUrl::fromLocalFile(file);
1551 return url;
1552}
1553
1554void QQmlImports::setDesignerSupportRequired(bool b)
1555{
1556 designerSupportRequired = b;
1557}
1558
1559QT_END_NAMESPACE
QQmlImportInstance * findImportByModuleUri(const QString &moduleUri, QTypeRevision version) const
bool needsSorting() const
QQmlImportInstance * findImportByLocation(const QString &location, QTypeRevision version) const
bool resolveType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type, QQmlImportResolutionResult *result, QQmlType::RegistrationType registrationType, QQmlImport::RecursionRestriction recursionRestriction)
void setNeedsSorting(bool needsSorting)
const QLoggingCategory & category() const
~QmlImportCategoryHolder()=default
static const QLatin1String String_qmldir("qmldir")
#define RESOLVE_TYPE_DEBUG
static const QString dotuidotqml_string(QStringLiteral(".ui.qml"))
static const QLatin1Char Colon(':')
static QTypeRevision qmldirContentError(const QString &uri, QList< QQmlError > *errors)
static const QString dotqml_string(QStringLiteral(".qml"))
static bool designerSupportRequired
void findCompositeSingletons(const QQmlImportNamespace &set, QList< QQmlImports::CompositeSingletonReference > &resultList, const QUrl &baseUrl)
static QTypeRevision matchingModuleVersionForLibraryImport(const QString &uri, QTypeRevision version, QList< QQmlError > *errors)
static QString getVersionInfo(QTypeRevision version)
static const QLatin1Char Dot('.')
static QTypeRevision matchingQmldirVersion(const QQmlTypeLoaderQmldirContent &qmldir, const QString &uri, QTypeRevision version, QList< QQmlError > *errors)
bool excludeBaseUrl(const QString &importUrl, const QString &fileName, const QString &baseUrl)
static const QLatin1Char Slash('/')
static const QLatin1Char Backslash('\\')
static const QLatin1String Slash_qmldir("/qmldir")
static QTypeRevision finalizeLibraryImport(const QString &uri, QTypeRevision version, const QQmlTypeLoaderQmldirContent &qmldir, QQmlImportInstance *inserted, QList< QQmlError > *errors)
const QLoggingCategory & lcQmlImport()
DEFINE_BOOL_CONFIG_OPTION(forceDiskCache, QML_FORCE_DISK_CACHE)
bool setQmldirContent(const QString &resolvedUrl, const QQmlTypeLoaderQmldirContent &qmldir, QQmlImportNamespace *nameSpace, QList< QQmlError > *errors)
bool resolveType(QQmlTypeLoader *typeLoader, const QHashedStringRef &type, QQmlImportResolutionResult *result, QQmlType::RegistrationType=QQmlType::AnyRegistrationType, QQmlImport::RecursionRestriction recursionRestriction=QQmlImport::PreventRecursion) const