/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

/**
 * Copyright (C) 2023-2026 Linaro Limited (or its affiliates). All rights reserved.
 * Copyright (C) 2012-2023 Arm Limited (or its affiliates).
 * All rights reserved.
 */

#include <QFont>
#include <QFontDatabase>
#include <QFontMetrics>
#include <QString>
#include <QStringList>
#include "terminalutil.h"

// From Qt 4.7.4 qprocess.cpp
QStringList parseCombinedArgString(const QString &program)
{
    QStringList args;
    QString tmp;
    int quoteCount = 0;
    bool inQuote = false;

    // handle quoting. tokens can be surrounded by double quotes
    // "hello world". three consecutive double quotes represent
    // the quote character itself.
    for (int i = 0; i < program.size(); ++i) {
        if (program.at(i) == QLatin1Char('"')) {
            ++quoteCount;
            if (quoteCount == 3) {
                // third consecutive quote
                quoteCount = 0;
                tmp += program.at(i);
            }
            continue;
        }
        if (quoteCount) {
            if (quoteCount == 1)
                inQuote = !inQuote;
            quoteCount = 0;
        }
        if (!inQuote && program.at(i).isSpace()) {
            if (!tmp.isEmpty()) {
                args += tmp;
                tmp.clear();
            }
        } else {
            tmp += program.at(i);
        }
    }
    if (!tmp.isEmpty())
        args += tmp;

    return args;
}

// From Qt 4.7.4 qprocess_win.cpp
#if defined (Q_OS_WIN)          // +explicit-local
QString qt_create_commandline(const QString &program, const QStringList &arguments)
{
    QString args;
    if (!program.isEmpty()) {
        QString programName = program;
        if (!programName.startsWith(QLatin1Char('\"')) && !programName.endsWith(QLatin1Char('\"')) && programName.contains(QLatin1Char(' ')))
            programName = QLatin1Char('\"') + programName + QLatin1Char('\"');
        programName.replace(QLatin1Char('/'), QLatin1Char('\\'));

        // add the prgram as the first arg ... it works better
        args = programName + QLatin1Char(' ');
    }

    for (int i=0; i<arguments.size(); ++i) {
        QString tmp = arguments.at(i);
        // in the case of \" already being in the string the \ must also be escaped
        tmp.replace( QLatin1String("\\\""), QLatin1String("\\\\\"") );
        // escape a single " because the arguments will be parsed
        tmp.replace( QLatin1Char('\"'), QLatin1String("\\\"") );
        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) {
            // The argument must not end with a \ since this would be interpreted
            // as escaping the quote -- rather put the \ behind the quote: e.g.
            // rather use "foo"\ than "foo\"
            QString endQuote(QLatin1Char('\"'));
            int i = tmp.length();
            while (i>0 && tmp.at(i-1) == QLatin1Char('\\')) {
                --i;
                endQuote += QLatin1Char('\\');
            }
            args += QLatin1String(" \"") + tmp.left(i) + endQuote;
        } else {
            args += QLatin1Char(' ') + tmp;
        }
    }
    return args;
}
#endif  // Q_OS_WIN

namespace {
    //! Check to see if a font contains Latin characters
    bool checkFont(const QString& family, int size)
    {
        QFont font(family, size);
        QFontMetrics fm(font);
        return fm.inFont(QLatin1Char('0')) &&
               fm.horizontalAdvance(QLatin1Char('0')) > 0 &&
               fm.inFont(QLatin1Char('a')) &&
               fm.horizontalAdvance(QLatin1Char('a')) > 0 &&
               fm.inFont(QLatin1Char('A')) &&
               fm.horizontalAdvance(QLatin1Char('A')) > 0;
    }
}


QFont findGoodFont(int size)
{
    /* Workaround for Qt 3.3.5 bug! */
    QFontDatabase fdb;
    QStringList families = fdb.families();
    /* Most preferred font comes last */
    QStringList preferredFonts = QStringList() << QLatin1String("Courier New")
                                               << QLatin1String("Bitstream Terminal")
                                               << QLatin1String("Monospace")
                                               << QLatin1String("Typewriter")
                                               << QLatin1String("FreeMono")
                                               << QLatin1String("Lucidatypewriter")
                                               << QLatin1String("LucidaTypewriter")
                                               << QLatin1String("Terminus");

    const int lengthPreferredFonts = preferredFonts.length();
    int bestScore = 0;
    QString bestFamily;
    for ( QStringList::Iterator f = families.begin(); f != families.end(); ++f ) {
        QString family = *f;
        int score = 0;
        for (int i = 0; i < lengthPreferredFonts ; ++i) {
            if (family == preferredFonts[i] && checkFont(family, size)) {
                score = 0x300 + i;
                break;
            }
        }
        if (score > bestScore) {
            bestScore = score;
            bestFamily = family;
        }
    }
    if (bestScore != 0)
        return QFont(bestFamily, size);
    for ( QStringList::Iterator f = families.begin(); f != families.end(); ++f ) {
        QString family = *f;
        int score = 0;
        if (fdb.isFixedPitch(family))
            score += 0x200;
        if (fdb.isSmoothlyScalable(family))
            score += 0x80;
        else if (fdb.isScalable(family))
            score += 0x40;
        QStringList styles = fdb.styles( family );
        bool hasBold = false, hasItalic = false, smoothAt10points = true;
        for ( QStringList::Iterator s = styles.begin(); s != styles.end(); ++s ) {
            QString style = *s;
            if (fdb.bold(family, style) && !fdb.italic(family, style))
                hasBold = true;
            if (fdb.italic(family, style) && !fdb.bold(family, style))
                hasItalic = true;
            bool has10points = false;
            QList<int> smoothies = fdb.smoothSizes( family, style );
            for ( QList<int>::Iterator points = smoothies.begin(); points != smoothies.end(); ++points ) {
                if (*points == size) {
                    has10points = true;
                    break;
                }
            }
            if (!has10points)
                smoothAt10points = false;
        }
        if (smoothAt10points)
            score += 0x100;
        if (hasBold)
            score += 0x20;
        if (hasItalic)
            score += 0x10;
        if (score > bestScore && checkFont(family, size)) {
            bestScore = score;
            bestFamily = family;
        }
    }
    if (bestFamily.isNull())
        bestFamily = QLatin1String("helvetica"); // https://doc.qt.io/qt-5/qfont-obsolete.html#lastResortFamily
    return QFont(bestFamily, size);
}
