File size: 12,449 Bytes
b6bd94d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
/* Thin wrappers for retaining compatibility for both Qt6.x and Qt5.x */
#pragma once
#include <QJsonObject>
#include <QJsonDocument>
#include <QKeyEvent>
#include <QString>
#include <QTextDocument>
#include <QUrl>
#include <QUrlQuery>
#include <QFileInfo>
#include <QWidget>
#include "filetype.hh"
#include <string>
using std::string;
namespace Utils {
/// Checks if the application is running under a Wayland session.
bool isWayland();
QMap< QString, QString > str2map( const QString & contextsEncoded );
inline bool isCJKChar( ushort ch )
{
if ( ( ch >= 0x3400 && ch <= 0x9FFF ) || ( ch >= 0xF900 && ch <= 0xFAFF ) || ( ch >= 0xD800 && ch <= 0xDFFF ) )
return true;
return false;
}
/**
* remove right end space
*/
inline QString rstrip( const QString & str )
{
int n = str.size() - 1;
for ( ; n >= 0; --n ) {
if ( !str.at( n ).isSpace() ) {
return str.left( n + 1 );
}
}
return {};
}
inline uint32_t leadingSpaceCount( const QString & str )
{
for ( int i = 0; i < str.size(); i++ ) {
if ( str.at( i ).isSpace() ) {
continue;
}
else {
return i;
}
}
return 0;
}
inline QString trimQuotes( const QString & str )
{
const auto * begin = str.cbegin();
const auto * end = str.cend();
while ( begin < end && ( end[ -1 ] == '\'' || end[ -1 ] == '\"' ) ) {
--end;
}
while ( begin < end && ( *begin == '\'' || *begin == '\"' ) ) {
begin++;
}
return str.sliced( begin - str.cbegin(), end - begin );
}
std::string c_string( const QString & str );
bool endsWithIgnoreCase( QByteArrayView str, QByteArrayView extension );
/**
* remove punctuation , space, symbol
*
*
* " abc, '" should be "abc"
*/
inline QString trimNonChar( const QString & str )
{
QString remain;
int n = str.size() - 1;
for ( ; n >= 0; --n ) {
auto c = str.at( n );
if ( !c.isSpace() && !c.isSymbol() && !c.isNonCharacter() && !c.isPunct() && !c.isNull() ) {
remain = str.left( n + 1 );
break;
}
}
n = 0;
for ( ; n < remain.size(); n++ ) {
auto c = remain.at( n );
if ( !c.isSpace() && !c.isSymbol() && !c.isNonCharacter() && !c.isPunct() ) {
return remain.mid( n );
}
}
return "";
}
/**
* str="abc\r\n\u0000" should be returned as "abc"
* @brief rstripnull
* @param str
* @return
*/
inline QString rstripnull( const QString & str )
{
int n = str.size() - 1;
for ( ; n >= 0; --n ) {
auto c = str.at( n );
if ( !c.isSpace() && !c.isNull() ) {
return str.left( n + 1 );
}
}
return "";
}
inline bool isExternalLink( const QUrl & url )
{
return url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "ftp" || url.scheme() == "mailto"
|| url.scheme() == "file" || url.toString().startsWith( "//" );
}
inline bool isHtmlResources( const QUrl & url )
{
auto fileName = url.fileName();
qsizetype index = fileName.lastIndexOf( "." );
QStringList extensions{ ".css", ".woff", ".woff2", ".ttf", ".otf", ".bmp", ".jpg", ".png", ".gif", ".tif",
".wav", ".ogg", ".oga", ".mp3", ".mp4", ".aac", ".flac", ".mid", ".wv", ".ape" };
if ( index > -1 ) {
auto ext = fileName.mid( index );
if ( extensions.contains( ext, Qt::CaseInsensitive ) )
return true;
}
// some url has the form like https://xxxx/audio?file=***.mp3&a=1 etc links.
for ( QString extension : extensions ) {
if ( url.url().contains( extension, Qt::CaseInsensitive ) )
return true;
}
return false;
}
inline QString escape( const QString & plain )
{
return plain.toHtmlEscaped();
}
// should ignore key event.
inline bool ignoreKeyEvent( QKeyEvent * keyEvent )
{
if ( keyEvent->key() == Qt::Key_Space || keyEvent->key() == Qt::Key_Backspace || keyEvent->key() == Qt::Key_Tab
|| keyEvent->key() == Qt::Key_Backtab || keyEvent->key() == Qt::Key_Escape )
return true;
return false;
}
inline QString json2String( const QJsonObject & json )
{
return QString( QJsonDocument( json ).toJson( QJsonDocument::Compact ) );
}
inline QStringList repeat( const QString str, const int times )
{
QStringList list;
for ( int i = 0; i < times; i++ ) {
list << str;
}
return list;
}
namespace AtomicInt {
inline int loadAcquire( const QAtomicInt & ref )
{
return ref.loadAcquire();
}
} // namespace AtomicInt
/**
* Get MIME type for audio file based on file path
* @param path File path to determine MIME type for
* @param extension Output parameter for the file extension
* @return The determined MIME type
*/
QString getAudioMimeType( const QString & path, QString & extension );
namespace Url {
// This wrapper is created due to behavior change of the setPath() method
// See: https://bugreports.qt-project.org/browse/QTBUG-27728
// https://codereview.qt-project.org/#change,38257
inline QString ensureLeadingSlash( const QString & path )
{
QLatin1Char slash( '/' );
if ( path.startsWith( slash ) )
return path;
return slash + path;
}
inline bool hasQueryItem( const QUrl & url, const QString & key )
{
return QUrlQuery( url ).hasQueryItem( key );
}
inline QString queryItemValue( const QUrl & url, const QString & item )
{
return QUrlQuery( url ).queryItemValue( item, QUrl::FullyDecoded );
}
inline QByteArray encodedQueryItemValue( const QUrl & url, const QString & item )
{
return QUrlQuery( url ).queryItemValue( item, QUrl::FullyEncoded ).toLatin1();
}
inline void addQueryItem( QUrl & url, const QString & key, const QString & value )
{
QUrlQuery urlQuery( url );
urlQuery.addQueryItem( key, value );
url.setQuery( urlQuery );
}
inline void removeQueryItem( QUrl & url, const QString & key )
{
QUrlQuery urlQuery( url );
urlQuery.removeQueryItem( key );
url.setQuery( urlQuery );
}
inline void setQueryItems( QUrl & url, const QList< std::pair< QString, QString > > & query )
{
QUrlQuery urlQuery( url );
urlQuery.setQueryItems( query );
url.setQuery( urlQuery );
}
inline QString path( const QUrl & url )
{
return url.path( QUrl::FullyDecoded );
}
inline void setFragment( QUrl & url, const QString & fragment )
{
url.setFragment( fragment, QUrl::DecodedMode );
}
inline QString fragment( const QUrl & url )
{
return url.fragment( QUrl::FullyDecoded );
}
// get the query word of bword and gdlookup scheme.
// if the scheme is gdlookup or scheme ,the first value of pair is true,otherwise is false;
inline std::pair< bool, QString > getQueryWord( const QUrl & url )
{
QString word;
bool validScheme = false;
if ( url.scheme().compare( "gdlookup" ) == 0 ) {
validScheme = true;
if ( hasQueryItem( url, "word" ) ) {
word = queryItemValue( url, "word" );
}
else {
word = url.path().mid( 1 );
}
}
if ( url.scheme().compare( "bword" ) == 0 || url.scheme().compare( "entry" ) == 0 ) {
validScheme = true;
auto path = url.path();
// url like this , bword:word or bword://localhost/word
if ( !path.isEmpty() ) {
//url,bword://localhost/word
if ( path.startsWith( "/" ) )
word = path.mid( 1 );
else
word = path;
}
else {
// url looks like this, bword://word,or bword://localhost
auto host = url.host();
if ( host != "localhost" ) {
word = host;
}
}
}
return std::make_pair( validScheme, word );
}
inline QString getParams( const QUrl & url, const QString & key )
{
QString word;
if ( url.scheme().compare( "gdlookup" ) == 0 ) {
if ( hasQueryItem( url, key ) ) {
word = queryItemValue( url, key );
}
else {
word = url.path().mid( 1 );
}
}
if ( url.scheme().compare( "bword" ) == 0 || url.scheme().compare( "entry" ) == 0 ) {
auto path = url.path();
// url like this , bword:word or bword://localhost/word
if ( !path.isEmpty() ) {
//url,bword://localhost/word
if ( path.startsWith( "/" ) )
word = path.mid( 1 );
else
word = path;
}
else {
// url looks like this, bword://word,or bword://localhost
auto host = url.host();
if ( host != "localhost" ) {
word = host;
}
}
}
return word;
}
inline bool isAudioUrl( const QUrl & url )
{
if ( !url.isValid() ) {
return false;
}
// gdau links are known to be audios, (sometimes they may not have file extension).
if ( url.scheme() == "gdau" || url.scheme() == "gdprg" || url.scheme() == "gdtts" ) {
return true;
}
// Note: we check for forvo sound links explicitly, as they don't have extensions
return ( url.scheme() == "http" || url.scheme() == "https" )
&& ( Filetype::isNameOfSound( url.path().toUtf8().data() ) || url.host() == "apifree.forvo.com" );
}
inline bool isWebAudioUrl( const QUrl & url )
{
if ( !url.isValid() ) {
return false;
}
// Note: we check for forvo sound links explicitly, as they don't have extensions
return ( url.scheme() == "http" || url.scheme() == "https" )
&& ( Filetype::isNameOfSound( url.path().toUtf8().data() ) || url.host() == "apifree.forvo.com" );
}
/// Uses some heuristics to chop off the first domain name from the host name,
/// but only if it's not too base. Returns the resulting host name.
inline QString getHostBase( const QString & host )
{
QStringList domains = host.split( '.' );
int left = domains.size();
// Skip last <=3-letter domain name
if ( left && domains[ left - 1 ].size() <= 3 ) {
--left;
}
// Skip another <=3-letter domain name
if ( left && domains[ left - 1 ].size() <= 3 ) {
--left;
}
if ( left > 1 ) {
// We've got something like www.foobar.co.uk -- we can chop off the first
// domain
return host.mid( domains[ 0 ].size() + 1 );
}
else {
return host;
}
}
inline QString getHostBaseFromUrl( const QUrl & url )
{
QString host = url.host();
return getHostBase( host );
}
/// \brief Extract the base domain from a given domain string.
///
/// This method handles several cases:
/// 1. Standard domains like "example.com" -> "example.com"
/// 2. Subdomains like "www.example.com" -> "example.com"
/// 3. Generic patterns like ".com.xx", ".co.xx", ".org.xx" where xx is a 2-3 character TLD -> "example.com"
///
/// Examples:
/// - "www.example.com.jp" -> "example.com"
/// - "subdomain.example.org.uk" -> "example.org"
///
/// \param domain The domain string to process
/// \return The extracted base domain
QString extractBaseDomain( const QString & domain );
QString getSchemeAndHost( const QUrl & url );
} // namespace Url
namespace Path {
QString combine( const QString & path1, const QString & path2 );
}
namespace Widget {
void setNoResultColor( QWidget * widget, bool noResult );
}
namespace Html {
// See Issue #271: A mechanism to clean-up invalid HTML cards.
std::string getHtmlCleaner();
} // namespace Html
/// Utilities to convert a wide string or an utf8 string to the local 8bit
/// encoding of the file system, and to do other manipulations on the file
/// names.
namespace Fs {
using std::string;
/// Returns the filesystem separator (/ on Unix and clones, \ on Windows).
char separator();
/// Returns the name part of the given filename.
string basename( const string & );
void removeDirectory( const QString & directory );
void removeDirectory( const string & directory );
inline QString findFirstExistingFile( std::initializer_list< QString > filePaths )
{
for ( const QString & filePath : filePaths ) {
if ( QFileInfo::exists( filePath ) ) {
return filePath;
}
}
return QString();
}
inline std::string findFirstExistingFile( std::initializer_list< std::string > filePaths )
{
for ( const std::string & filePath : filePaths ) {
auto fp = QString::fromStdString( filePath );
if ( QFileInfo::exists( fp ) ) {
return filePath;
}
}
return {};
}
inline bool anyExistingFile( std::initializer_list< std::string > filePaths )
{
for ( const std::string & filePath : filePaths ) {
auto fp = QString::fromStdString( filePath );
if ( QFileInfo::exists( fp ) ) {
return true;
}
}
return false;
}
// used for std::string and char*
inline bool exists( std::string_view filename ) noexcept
{
return QFileInfo::exists( QString::fromUtf8( filename.data(), filename.size() ) );
}
} // namespace Fs
namespace WebSite {
QString urlReplaceWord( const QString url, QString word );
}
QString escapeAmps( const QString & str );
QString unescapeAmps( const QString & str );
} // namespace Utils
|