Skip to content

Welcome to Planet KDE

This is a feed aggregator that collects what the contributors to the KDE community are writing on their respective blogs, in different languages

Friday, 26 July 2024

Let’s go for my web review for the week 2024-30.


On Open Source and the Sustainability of the Commons

Tags: tech, foss, licensing, sustainability, commons, politics

It’s a piece which really resonates with me. I’ve been thinking and saying for a while that focusing mostly on the technical (licensing and dev) aspects of Open Source was a mistake. This completely overlooked the political side of the Free Software equation. This is why the industry is as it is now. We need stronger commons and indeed the AGPL is best for that.

https://ploum.net/2024-07-01-opensource_sustainability.html


2024 Stack Overflow Developer Survey

Tags: tech, programming

A few surprises in there but otherwise it feels a bit like a repeat from last year. I keep being dismayed at how low the ethical concern of the energy impact of generative AI scores in this survey.

https://survey.stackoverflow.co/2024/


Microsoft says 8.5M systems hit by CrowdStrike BSOD, releases USB recovery tool | Ars Technica

Tags: tech, windows, safety

The cleanup of that mess is still on-going. A bit more automation would help.

https://arstechnica.com/information-technology/2024/07/microsoft-says-8-5m-systems-hit-by-crowdstrike-bsod-releases-usb-recovery-tool/


The Backlash Against AI Scraping Is Real and Measurable

Tags: tech, ai, machine-learning, gpt, criticism

Content creators are clearly annoyed at the lack of consent. The more technical ones are trying to take the matter in their own hands.

https://www.404media.co/the-backlash-against-ai-scraping-is-real-and-measurable/


Astronomers discover technique to spot AI fakes using galaxy-measurement tools

Tags: tech, ai, machine-learning, gpt, graphics, astronomy, physics

Still not perfect, but that’s an interesting development.

https://arstechnica.com/information-technology/2024/07/astronomers-discover-technique-to-spot-ai-fakes-using-galaxy-measurement-tools/


AI models collapse when trained on recursively generated data | Nature

Tags: tech, data, ai, machine-learning, gpt, research

More discussion about models collapse. The provenance of data will become a crucial factor to our ability to train further models.

https://www.nature.com/articles/s41586-024-07566-y


How a North Korean Fake IT Worker Tried to Infiltrate Us

Tags: tech, security, hiring, remote-working

Interesting story. This is getting harder to hire for remote positions I guess.

https://blog.knowbe4.com/how-a-north-korean-fake-it-worker-tried-to-infiltrate-us


Secure Boot is completely broken on 200+ models from 5 big device makers | Ars Technica

Tags: tech, bios, security, hardware

A reminder that Secure Boot is worth nothing if the device makers don’t manage cryptographic keys properly…

https://arstechnica.com/security/2024/07/secure-boot-is-completely-compromised-on-200-models-from-5-big-device-makers/


Give Me the Green Light Part 1: Hacking Traffic Control Systems — Red Threat

Tags: tech, transportation, security

Make sure to read also part 2. You’d expect critical infrastructure like this to not be exposed over the Internet, and to be properly protected…

https://www.redthreatsec.com/blog/greenlightspart1


Automerge CRDT

Tags: tech, crdt, rust, javascript

Need to make a realtime collaboration application? This might come in handy.

https://automerge.org/


NAS Performance: NFS vs. SMB vs. SSHFS | Jake’s Blog

Tags: tech, networking, storage, benchmarking

Interesting comparisons, some of it was a bit unexpected to me. I didn’t expect SSHFS to be that OK.

https://blog.ja-ke.tech/2019/08/27/nas-performance-sshfs-nfs-smb.html


libfaketime modifies the system time for a single application

Tags: tech, time, tests, tools

This can definitely come in handy. I can see myself using it for testing behaviors in the past or the future on a real application. This should also help writing automated tests in some cases.

https://github.com/wolfcw/libfaketime


Does C++ allow template specialization by concepts? – Daniel Lemire’s blog

Tags: tech, c++

This is indeed a shame. It’d be nice to not add all the concepts you plan on supporting in the class declaration…

https://lemire.me/blog/2024/07/22/does-c-allow-template-specialization-by-concepts/


What’s the point of std::monostate? You can’t do anything with it!

Tags: tech, c++, type-systems

There’s a good reason to have it in the standard. As mentioned in this post it can help with std::variant.

https://devblogs.microsoft.com/oldnewthing/20240708-00/?p=109959


PsyArXiv Preprints | Psychological Affordances Can Provide a Missing Explanatory Layer for Why Interventions to Improve Developer Experience Take Hold or Fail

Tags: tech, psychology, developer-experience

Interesting preprint review. Not sure I got it all in depth, will definitely need to revisit it at some point.

https://osf.io/preprints/psyarxiv/qz43x



Bye for now!

It’s been about a month and a half since I wrote about KDE’s new Human Interface Guidelines (HIG). It turns out there’s a surprising amount to report since then!

First of all, the news got picked up by Linux Magazine which did a story about it, including an interview with me! That felt nice.

Next, there have been a number of contributions and enhancements:

Joshua Goins

  • Fixed a lot of typos, awkward wordings, and small errors.
  • Added information about using Qt to set Task Manager badges directly.
  • Expanded the instructions on contributing to the HIG.

Thiago Sueto

  • Corrected several typos and spelling errors.

Christoph Wolk

  • Improved the grammatical correctness of one of the text recommendations.

Nate Graham (me)

  • Polished up the text some more.
  • Added additional suggested inclusiveness-related text replacements.
  • Clarified when a hamburger menu is and isn’t appropriate.
  • Updated the icon size recommendations.
  • Added examples and suggested replacements for common acronyms.
  • Wrote a recommendation for how to implement “go home” navigation.
  • Mentioned when first-run wizards are and aren’t appropriate, migrating some content from our old “Frequently discussed topics” wiki page.
  • Refined the recommendation for button length and combox text capitalization.
  • Described when it’s appropriate to shorten button labels because nearby context indicates what they affect.
  • Expanded the Icons page to offer more concrete guidelines about how to choose an icon and what style to use, and also added more pictures.

Overall I think it’s looking pretty good now, especially the Icons page which received a lot of attention recently.

In addition, there are more pending merge requests by Christoph Wolk, Emir Sari, and me. So it feels like an actual team project now! I think the goal of encouraging more contribution can be called a success.

Finally, Christoph Wolk and I have been going through System Settings pages and tweaking them to comply with the HIG. System Settings is good low-hanging fruit since it’s almost all QML at this point, so changes are easy. And there are a lot of pages, so it’s not hard to find small inconsistencies.

But were not finished yet! More eyeballs are needed. A few TODOs need resolving. More images could be helpful. So check out these two links to learn how to contribute changes:

Even a beginner developer can help out by tweaking the user interface to conform to the HIG. And if you’re a hardcore developer, we still need some more components for writing powerful QML apps.

Still too scary? Then donate to KDE. Our budget is tiny, so your money genuinely does have an impact!

Thursday, 25 July 2024

The past weeks involved a lot of work surrounding the implementation of Acrobat specific methods for processing form fields, added support for different types of form widgets and some UI improvements were made or are being worked upon. A detailed list of MRs merged and raised is described below.

MRs merged:

  • AFTime_Keystroke implementation : This method implementation specifies what input keystrokes are allowed in a form field accepting time information. !MR987
  • AFSpecial_Keystroke implementation : This method implementation specifies what input keystrokes are allowed in form fields of special type i.e. those that accept as input phone numbers, ssn and zip codes. !MR1013
  • AFPercent_Keystroke and AFNumber_Keystroke methods implemented : These methods specify input keystrokes for percents and numerical data. !MR988
  • Implement AFDate_KeystrokeEx and AFDate_FormatEx methods. : For correctly accepting input dates and formatting them according to some pre-specified format. !MR1017
  • Global object implementation : A very basic implementation of global object that allows users to read and write to the global object. Persistence and subscription not supported as of now. !MR1016
  • Commit values and restore: Implemented the feature to restore values to the previous committed value upon entering a value that is rejected by a keystroke action.!MR985
  • Fix numerical interpretation in form fields: Calculations were suffering from a major bug 474661 that caused incorrect results when using different locales. This was fixed in the !MR992. The MR focused on how numerical values should be interpreted in form fields.
  • Implemented DocClose, DocWillPrint, DocDidPrint, DocWillSave and DocDidSave events: Now actions are triggered during these events with the changes introduced in the !MR1019.
  • Radio Buttons and Check Boxes size fix: Now radio buttons and check boxes are painted with correct size and resized when zooming to provide a better user experience. !MR1015
  • Implement value (getter), numItems, currentValueIndices properties and getItemAt for FormFieldChoices: These methods were introduced to improve the functionality of FormFieldChoices. !MR1031
  • ResetForm functionality in Poppler: The Reset form functionality was added to the Qt frontend in Poppler. Introduced in this commit

Along with these, more MRs are under works for things like implementing UI experience when using form fields and extending functionality of different types of form fields and actions.

See you next time. Cheers!

We are happy to announce the release of Qt Creator 14!

Motivation

Let’s say we’re working on a QML project that involves a TextEdit.

There’s some text in it:

here is some text

We want to select part of this text and hit ctrl+B to make it bold:

here is some text

In Qt Widgets, this is trivial, but not so much in QML – we can get font.bold of the entire TextEdit, but not of just the text in the selection. We have to implement formattable selections manually.

To do this, there are two approaches we’ll look at:

  1. The first is to hack it together by getting the formatted text from the selection and editing this. Rather than setting properties of selected text, this solution actually inserts or removes formatting symbols from the underlying rich text source.
  2. The other way to do this is to create a QML object that is implemented in C++ and exposed to TextEdit as a property. This way we can make use of QTextDocument and QTextCursor to actually set text properties within the selection area. This more closely follows the patterns expected in Qt.

In Qt 6.7, the TextEdit QML element does have a cursorSelection property that works in this way, and by dissecting its implementation, we can write a pseudo-backport for other Qt versions.

Before we do this, let’s take a look at the hacky QML/JS solution.

Hacky Approach

We start by focusing on just making ctrl+B bold shortcuts work:

TextEdit {
    id: txtEdit

    anchors.fill: parent
    selectByMouse: true
    textFormat: TextEdit.RichText
}

Shortcut {
    sequence: StandardKey.Bold
    onActivated: {
        if (txtEdit.selectedText.length > 0)
        {
            const start = txtEdit.selectionStart
            const end = txtEdit.selectionEnd
            let sel = txtEdit.getFormattedText(start, end)
                             .split("<!--StartFragment-->")[1]
                             .split("<!--EndFragment-->")[0]
            txtEdit.remove(start, end)
            if (sel.includes("font-weight:600;"))
                sel = sel.replace("font-weight:600;", "")
            else
                sel = "<b>" + sel + "</b>"
            txtEdit.insert(txtEdit.cursorPosition, sel)
            txtEdit.select(start, end)
        }
    }
}

Notice that we actually remove and replace the selected text, and reselect the insertion manually.

We can set up similar shortcuts for italics and underline trivially, but what if we want to set font properties of only the text in the selected area?

To keep things simple, let’s see what happens if we want to set just the font family and size:

FontDialog {
    id: fontDlg
}

Shortcut {
    id: fontShortcut

    property string sel: ""
    property int start: 0
    property int end: 0

    sequence: StandardKey.Find
    onActivated: {
        if (txtEdit.selectedText.length > 0)
        {
            start = txtEdit.selectionStart
            end = txtEdit.selectionEnd
            sel = txtEdit.getFormattedText(start, end)
                         .split("<!--StartFragment-->")[1]
                         .split("<!--EndFragment-->")[0]
            fontDlg.open()
        }
    }
}

Connections {
    target: fontDlg

    function onAccepted() {
        txtEdit.remove(fontShortcut.start, fontShortcut.end)
        if (fontShortcut.sel.includes("font-family:")) {
            let fontToReplace = fontShortcut.sel.split("font-family:'")[1].split("';")[0]
            fontShortcut.sel = fontShortcut.sel.replace(fontToReplace, fontDlg.font.family)
        } else {
            fontShortcut.sel = "<span style=\"font-family: '"
                             + fontDlg.font.family + "'; font-size:"
                             + (fontDlg.font.pixelSize ? fontDlg.font.pixelSize
                                                       : fontDlg.font.pointSize)
                             + "\">" + fontShortcut.sel + "</span>"
        }
        txtEdit.insert(txtEdit.cursorPosition, fontShortcut.sel)
        txtEdit.select(fontShortcut.start, fontShortcut.end)
    }
}

If we start messing with other font style properties like italic, bold, spacing, etc., we will end up with almost unreadably nasty string manipulation here.

This solution is overall hacky, as we replace HTML-formatted text from a snipped out section. It would be more Qt-idiomatic to retrieve QFont info from a selection and set the properties without editing raw rich text. Furthermore, it’s better to do as much logic as possible in C++ rather than with JavaScript in QML.

Implementation of cursorSelection in Qt 6.7 QML

Let’s take a look at the cursorSelection property of QtQuick TextEdit in Qt 6.7.

By looking at its property declaration in qquicktextedit_p.h, the type of cursorSelection is QQuickTextSelection.

This type is very basic. It has four read/write properties.

Here is the header qquicktextselection_p.h:

class Q_QUICK_EXPORT QQuickTextSelection : public QObject
{
    Q_OBJECT

    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged FINAL)
    Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged FINAL)
    Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged FINAL)
    Q_PROPERTY(Qt::Alignment alignment READ alignment WRITE setAlignment NOTIFY alignmentChanged FINAL)

    QML_ANONYMOUS
    QML_ADDED_IN_VERSION(6, 7)

public:
    explicit QQuickTextSelection(QObject *parent = nullptr);

    QString text() const;
    void setText(const QString &text);

    QFont font() const;
    void setFont(const QFont &font);

    QColor color() const;
    void setColor(QColor color);

    Qt::Alignment alignment() const;
    void setAlignment(Qt::Alignment align);

Q_SIGNALS:
    void textChanged();
    void fontChanged();
    void colorChanged();
    void alignmentChanged();

private:
    QTextCursor cursor() const;
    void updateFromCharFormat(const QTextCharFormat &fmt);
    void updateFromBlockFormat();

private:
    QTextCursor m_cursor;
    QTextCharFormat m_charFormat;
    QTextBlockFormat m_blockFormat;
    QQuickTextDocument *m_doc = nullptr;
    QQuickTextControl *m_control = nullptr;
};

Notice we’ve got these private data members:

QTextCursor m_cursor;
QTextCharFormat m_charFormat;
QTextBlockFormat m_blockFormat;
QQuickTextDocument *m_doc = nullptr;
QQuickTextControl *m_control = nullptr;

The m_doc and m_control are retrieved from the TextEdit which parents the selection object. The object is always constructed by a QQuickTextEdit, so in the constructor, the parent is cast to one using qmlobject_cast. Then we set these two fields.

QQuickTextSelection::QQuickTextSelection(QObject *parent)
    : QObject(parent)
{
    // When QQuickTextEdit creates its cursorSelection, it passes itself as the parent
    if (auto *textEdit = qmlobject_cast<QQuickTextEdit *>(parent)) {
        m_doc = textEdit->textDocument();
        m_control = QQuickTextEditPrivate::get(textEdit)->control;
        // ...
        // ...

Now what are m_charFormat and m_blockFormat?

Text documents are composed of a list of text blocks, which can be paragraphs, lists, tables, images, etc. Thus, a block format represents an individual block’s alignment formatting. Char format contains formatting information at the character level, like font family, weight, style, size, color, and so forth.

To initialize these, we need to get the cursor from the text control.

QTextCursor QQuickTextSelection::cursor() const
{
    if (m_control)
        return m_control->textCursor();
    return m_cursor;
}

The cursor will give us a char format and a block format, which we use to get the font / color / alignment at the cursor’s location.

QFont QQuickTextSelection::font() const
{
    return cursor().charFormat().font();
}

// ...

QColor QQuickTextSelection::color() const
{
    return cursor().charFormat().foreground().color();
}

// ...

Qt::Alignment QQuickTextSelection::alignment() const
{
    return cursor().blockFormat().alignment();
}

currentCharFormatChanged is emitted by QQuickTextControl when the cursor moves or the document’s contents change. If this format is indeed different from the fields of the selection object, we must update them and emit the selection’s signals, just as we would in setters. Since we keep track of block alignment too, we have to do the same when the cursor moves and block format is different.

QQuickTextSelection::QQuickTextSelection(QObject *parent)
    : QObject(parent)
{
    // When QQuickTextEdit creates its cursorSelection, it passes itself as the parent
    if (auto *textEdit = qmlobject_cast<QQuickTextEdit *>(parent)) {
        m_doc = textEdit->textDocument();
        m_control = QQuickTextEditPrivate::get(textEdit)->control;
        connect(m_control, &QQuickTextControl::currentCharFormatChanged,
                this, &QQuickTextSelection::updateFromCharFormat);
        connect(m_control, &QQuickTextControl::cursorPositionChanged,
                this, &QQuickTextSelection::updateFromBlockFormat);
    }
}

// ...
// ...
// ...

inline void QQuickTextSelection::updateFromCharFormat(const QTextCharFormat &fmt)
{
    if (fmt.font() != m_charFormat.font())
        emit fontChanged();
    if (fmt.foreground().color() != m_charFormat.foreground().color())
        emit colorChanged();

    m_charFormat = fmt;
}

inline void QQuickTextSelection::updateFromBlockFormat()
{
    QTextBlockFormat fmt = cursor().blockFormat();

    if (fmt.alignment() != m_blockFormat.alignment())
        emit alignmentChanged();

    m_blockFormat = fmt;
}

Here are the setters for the properties, which use the cursor to access and mutate the character or block properties at its position.

void QQuickTextSelection::setText(const QString &text)
{
    auto cur = cursor();
    if (cur.selectedText() == text)
        return;

    cur.insertText(text);
    emit textChanged();
}

// ...

void QQuickTextSelection::setFont(const QFont &font)
{
    auto cur = cursor();
    if (cur.selection().isEmpty())
        cur.select(QTextCursor::WordUnderCursor);

    if (font == cur.charFormat().font())
        return;

    QTextCharFormat fmt;
    fmt.setFont(font);
    cur.mergeCharFormat(fmt);
    emit fontChanged();
}

// ...

void QQuickTextSelection::setColor(QColor color)
{
    auto cur = cursor();
    if (cur.selection().isEmpty())
        cur.select(QTextCursor::WordUnderCursor);

    if (color == cur.charFormat().foreground().color())
        return;

    QTextCharFormat fmt;
    fmt.setForeground(color);
    cur.mergeCharFormat(fmt);
    emit colorChanged();
}

// ...

void QQuickTextSelection::setAlignment(Qt::Alignment align)
{
    if (align == alignment())
        return;

    QTextBlockFormat format;
    format.setAlignment(align);
    cursor().mergeBlockFormat(format);
    emit alignmentChanged();
}

Now, we want to do something like this in our code. The issue is that this implementation resides in the Qt source code itself, and cursorSelection is a property of QQuickTextEdit. If we want to do something like this without changing Qt source code, we have to use attached properties.

Implementing an Attached Property

Using CursorSelection as an attached property for a TextEdit in QML might look something like this:

Item {
    // ...
    // ...
    // ...
    
    Shortcut {
        // ctrl+B to toggle bold / not bold for selection
        sequence: StandardKey.Bold
        onActivated: {
            txtEdit.CursorSelection.font = Qt.font({
                bold: txtEdit.CursorSelection.font.bold !== true
            })
        }
    }

    TextEdit {
        id: txtEdit

        // ...
        
        CursorSelection.font {
            bold: false
            italic: false
            underline: false
        }
    }
}

To create our own attached property, we have to create two classes: CursorSelectionAttached and CursorSelection.

CursorSelectionAttached will contain the implementation of the selection, while CursorSelection serves as the attaching type, using the qmlAttachedProperties() method to expose the signals and properties of an instance of CursorSelectionAttached to the parent to which it is attached.

CursorSelection also needs the QML_ATTACHED() macro in its header declaration, and we must specify that it has an attached property with the macro QML_DECLARE_TYPEINFO() outside the class scope.

Thus, CursorSelection will just look like this:

// CursorSelection.h

class CursorSelection : public QObject
{
    Q_OBJECT
    QML_ATTACHED(CursorSelectionAttached)
    QML_ELEMENT

public:
    static CursorSelectionAttached *qmlAttachedProperties(QObject *object);
};

QML_DECLARE_TYPEINFO(CursorSelection, QML_HAS_ATTACHED_PROPERTIES)

Where the entire implementation is just this function definition:

// CursorSelection.cpp

CursorSelectionAttached *CursorSelection::qmlAttachedProperties(QObject *object)
{
    if (auto *textEdit = qobject_cast<QQuickTextEdit *>(object))
        return new CursorSelectionAttached(textEdit);
    return nullptr;
}

Notice that we perform the qobject_cast here and forward the result as the parent of the attached object. This way we only construct an attached object if we can cast the parent object to a TextEdit.

Now, let’s see how CursorSelectionAttached should be implemented. We begin with the constructor:

// we know that parent will be a QQuickTextEdit *
CursorSelectionAttached::CursorSelectionAttached(QQuickTextEdit *parent) noexcept
    : QObject(parent)
    , mEdit(parent)		// this is the TextEdit we are attached to 
{
    // make sure the QTextDocument exists
    const auto *const quickDoc = mEdit->textDocument(); // QQuickTextDocument *
    auto *doc = quickDoc->textDocument();               // QTextDocument *
    Q_ASSERT(doc != nullptr);

    // retrieve QTextCursor from the QTextDocument
    mCursor = QTextCursor(doc);

    // When deselecting, the cursor position and anchor are
    // set to the TextEdit's cursor position
    connect(mEdit, &QQuickTextEdit::selectedTextChanged,
            this, &CursorSelectionAttached::moveAnchorIfDeselected);
    
    connect(mEdit, &QQuickTextEdit::cursorPositionChanged,
            this, &CursorSelectionAttached::updatePosition);
    
    // if we set a format with no selection, we keep it in an optional
    // then when new text is added, it will have this formatting
    // for example, with no selection we press ctrl+B and then start
    // typing. we expect the text to be bold.
    connect(mEdit->textDocument()->textDocument(),
            &QTextDocument::contentsChange,
            this,
            &CursorSelectionAttached::applyFormatToNewTextIfNeeded);
}

Note that we connect to these three slots:

  • moveAnchorIfDeselected
  • updatePosition
  • applyFormatToNewTextIfNeeded

Let’s investigate the purpose of these.

moveAnchorIfDeselected is invoked when the TextEdit’s selected text changes. A QTextCursor has an anchor, which controls selection area. If text is being selected, the anchor is fixed in place where the selection is started, and the cursor position moves independently of the anchor. The selection area is located between the two positions. When a cursor moves without selecting anything, the anchor is located at and moves along with the cursor position.

Thus, when a cursor’s position is moved, we need to know if the anchor should be moved with it.

Since we invoke moveAnchorIfDeselected when the selected text changes, we know that if the selection is now empty, this means there was a selection that has been deselected. Thus, the cursor and anchor should be equal to one another.

void CursorSelectionAttached::moveAnchorIfDeselected()
{
    if (mEdit->selectedText().isEmpty())
        mCursor.setPosition(mEdit->cursorPosition(), QTextCursor::MoveAnchor);
}

updatePosition is invoked when the TextEdit’s cursor position changes. Depending on the TextEdit’s selection start and end positions, there are a few ways the cursor could be updated.

If there is no selected area in the TextEdit, the cursor and anchor should move together. If a selection’s start and end position both change, we must move the cursor twice: once to the start position, with the anchor moving, and once to the end position, with the anchor fixed in place. If the selection area is being resized, for example by dragging or using Shift+ArrowKeys, the cursor should move with the anchor fixed in place.

void CursorSelectionAttached::updatePosition()
{
    // if there's no selection, just move the cursor & anchor
    if (mEdit->selectionEnd() == mEdit->selectionStart())
    {
        mCursor.setPosition(mEdit->cursorPosition(), QTextCursor::MoveAnchor);
    }

    // if both the start and end need to be updated:
    // move cursor and anchor to selection start, and
    // move cursor to selection end while keeping anchor at start
    //
    // we have to make sure the anchor is moved correctly so the
    // whole selection matches up -- otherwise cursor selection 
    // start or end might be in the middle of the actual
    // selection, wherever the anchor is
    else if (mEdit->selectionStart() != mCursor.selectionStart() &&
             mEdit->selectionEnd() != mCursor.selectionEnd())
    {
        mCursor.setPosition(mEdit->selectionStart(), QTextCursor::MoveAnchor);
        mCursor.setPosition(mEdit->selectionEnd(), QTextCursor::KeepAnchor);
    }

    // these two cases are for selection dragging, only start or
    // end will move, so anchor stays in place
    else if (mEdit->selectionStart() != mCursor.selectionStart())
    {
        mCursor.setPosition(mEdit->selectionStart(), QTextCursor::KeepAnchor);
    }
    else if (mEdit->selectionEnd() != mCursor.selectionEnd())
    {
        mCursor.setPosition(mEdit->selectionEnd(), QTextCursor::KeepAnchor);
    }
}

applyFormatToNewTextIfNeeded is invoked when the contents of the text document change. This is because font properties might be set without an active selection. In this case, the expected behavior is for the characters added afterwards will have these properties.

For example, if the font family is changed with no selection, and we start typing, we expect our text to be in this new font. To do this, we need an optional in which we can save a format to apply to new text if needed, or otherwise contains nullopt. We will call it mOptFormat. It can be set in property setters, which you will see later. For now, we just make sure to use it when the text document content changes and there exists a value in the optional.

void CursorSelectionAttached::applyFormatToNewTextIfNeeded(int from, int charsRemoved, int charsAdded)
{
    if (charsAdded && mOptFormat)
    {
        mCursor.setPosition(mCursor.position() - 1, QTextCursor::KeepAnchor);
        mCursor.mergeCharFormat(mOptFormat.value());
        mOptFormat.reset();
    }
}

Now, let’s take a look at the properties to expose to QML, and how they can be retrieved and set using the cursor. Like the QQuickTextSelection implementation, we will have properties text and font. We can implement the others as well, but for the sake of brevity, we will just focus on these two.

Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged FINAL)
Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged FINAL)

We’ll need to declare and define these getters and setters, and declare the signals:

Getters:

[[nodiscard]] QString text() const;
[[nodiscard]] QFont font() const;

Setters:

void setText(const QString &text);
void setFont(const QFont &font);

Signals:

void textChanged();
void fontChanged();

The getter and setter implementations will look very similar to the previous implementations shown for QQuickTextSelection, with some minor differences.

Getter implementations:

QString CursorSelectionAttached::text() const
{
    return mCursor.selectedText();
}

QFont CursorSelectionAttached::font() const
{
    // simply get the font at the cursor position using charFormat
    auto ret = mCursor.charFormat().font();

    // if the cursor is at the start of a selection, we need to take the font
    // at the position right in front of it. otherwise, the font will refer to the 
    // character at the position right before the selection begins
    if (mCursor.hasSelection() && mCursor.position() == mCursor.selectionStart())
    {
        auto cur = mCursor;
        cur.setPosition(cur.position() + 1);
        ret = cur.charFormat().font();
    }
    return ret;
}

Setter implementations:

void CursorSelectionAttached::setText(const QString &text)
{
    if (mCursor.selectedText() == text)
        return;

    mCursor.insertText(text);
    emit textChanged();
}

void CursorSelectionAttached::setFont(const QFont &font)
{
    if (font == mCursor.charFormat().font())
        return;

    QTextCharFormat fmt = mCursor.charFormat();
    fmt.setFont(font, QTextCharFormat::FontPropertiesSpecifiedOnly);

    // when no selection, formatting must be set on the next insertion
    if (mCursor.selection().isEmpty())
        mOptFormat = fmt;
    else
        mCursor.mergeCharFormat(fmt);

    emit fontChanged();
}

The only thing that needs to be done now is override the destructor, which can just be set to default:

~CursorSelectionAttached() override = default;

Now we have all the implementation we need to use the attached property. If we put the two classes in one header file, it will look like this:

#pragma once

#include <QObject>
#include <QTextCursor>
#include <QtQml>
#include <optional>

class QQuickTextEdit;

class CursorSelectionAttached : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged FINAL)
    Q_PROPERTY(QFont font READ font WRITE setFont NOTIFY fontChanged FINAL)
    QML_ANONYMOUS

public:
    explicit CursorSelectionAttached(QQuickTextEdit *parent) noexcept;
    ~CursorSelectionAttached() override = default;
    [[nodiscard]] QString text() const;
    [[nodiscard]] QFont font() const;
    void setText(const QString &text);
    void setFont(const QFont &font);

signals:
    void textChanged();
    void fontChanged();

private slots:
    void moveAnchorIfDeselected();
    void updatePosition();
    void applyFormatToNewTextIfNeeded(int from, int charsRemoved, int charsAdded);

private:
    QTextCursor mCursor;
    QQuickTextEdit *mEdit;
    std::optional<QTextCharFormat> mOptFormat;
};

class CursorSelection : public QObject
{
    Q_OBJECT
    QML_ATTACHED(CursorSelectionAttached)
    QML_ELEMENT

public:
    static CursorSelectionAttached *qmlAttachedProperties(QObject *object);
};

QML_DECLARE_TYPEINFO(CursorSelection, QML_HAS_ATTACHED_PROPERTIES)

With this header, an implementation file containing the definitions, and a call to qmlRegisterUncreatableType<CursorSelection> in your main.cpp, the attached property can be used in QML.

Final Remarks

Though this is not a perfect backport, this code allows us to set font properties for selected text in QML in a nearly identical way to its implementation in Qt 6.7. This is especially useful to implement any kind of richtext editing in a QML application, where this functionality is severely lacking in any Qt version prior to 6.7. Hopefully this is a helpful guide to backporting features, implementing attached properties, and doing more sane text editing in QML apps. 🙂

About KDAB

If you like this article and want to read similar material, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Formatting Selected Text in QML appeared first on KDAB.

Wednesday, 24 July 2024

Multiple Subtitle Track

I continued to refine the feature proposed in my previous blog. We can now add new layers directly on the timeline by simply dragging the existing subtitle out of the bottom border of the subtitle track. Adding, moving, and deleting subtitles work as before, now with layer support.

I also added an indicator to the header of the subtitle track. It looks like this:

Besides setting a style to a specific subtitle event, I also plan to add the feature of setting different default styles for different subtitle layers. This will allow us to easily apply a consistent style to groups of subtitles within each layer.

Improved Subtitle Manager

Layer management is now integrated into the subtitle manager, giving it a fresh new look.

The duplicate and delete operations now work for layers as well.

Automatic Conversion of .srt Subtitle

To better test and develop the style feature, I switched the subtitle storage format to .ass. With the help of my mentor, we can now automatically convert the .srt files from old projects to .ass files while keeping the original .srt file.

There are still some minor issues with style conversion, such as incorrect font sizes. However, I believe it’s time to shift my focus to the styling widget and address these bugs later. The next two weeks will be dedicated to style management, which is the most important part of the project, so stay tuned!

Tuesday, 23 July 2024

Dear fans of music & open source music players,
in preparation of the upcoming Amarok 3.1 release, a beta release (3.0.81) has been prepared.

As is observable from the ChangeLog, in addition to various bugfixes, there will be some, but not that many, new features included in the upcoming version. However, there has been a lot of Qt6 compatibility preparation work done under the hood, so version number 3.1 reflects the amount of changed code better than 3.0.2 would. 3.1.0 is likely to be released in early August, and all help catching any regressions during this period is highly appreciated. (n.b. one won't be able to compile a Qt6 Amarok with 3.1 yet, but perhaps with the eventual 3.2)

The source tarball is available on download.kde.org and it has been signed with Tuomas Nurmi's GPG key. There doesn't appear to be many binary packages of the beta available, at least at the moment, but the various nightly git builds provided by various splendid packagers are also based on corresponding source code, so using them and reporting findings is also a valid way to participate in the beta test effort.

Happy listening!

Kirigami Addons 1.4 is out! This release introduce a new module to manage actions similar to that we can find in the QtWidgets world with KXmlGui. This was not written from scratch but upstream the existing infrastructure from Merkuro (ex-Kalendar) and Marknote. These two applications have already been ported to this new module and more like Tokodon or KDE Keychain will follow soon.

This includes a shortcut editor to assign and modify the shortcuts of an application and a command bar to quickly search and trigger actions

Shortcut editor
Shortcut editor

Command bar
Command bar

Similar to KXmlGui, the actions are defined in C++, which allows to make use KStandardActions and get consistent shortcuts accross all your applications.

class MyApplication : public AbstractKirigamiApplication
{
 Q_OBJECT
 QML_ELEMENT

public:
 explicit MyApplication(QObject *parent = nullptr);

 void setupActions() override;

Q_SIGNALS:
 void addNotebook();
};

MyApplication::MyApplication(QObject *parent)
 : AbstractKirigamiApplication(parent)
{
 setupActions();
}

void MyApplication::setupActions()
{
 AbstractKirigamiApplication::setupActions();

 auto actionName = QLatin1String("add_notebook");
 if (KAuthorized::authorizeAction(actionName)) {
 auto action = mainCollection()->addAction(actionName, this, &MyApplication::addNotebook);
 action->setText(i18nc("@action:inmenu", "New Notebook"));
 action->setIcon(QIcon::fromTheme(QStringLiteral("list-add-symbolic")));
 mainCollection()->addAction(action->objectName(), action);
 mainCollection()->setDefaultShortcut(action, QKeySequence(Qt::CTRL | Qt::SHIFT | Qt::Key_N));
 }
}

These new actions can then be used from QML thanks to the new Kirigami.Action::fromQAction property.

import org.kde.kirigamiaddons.statefulapp as StatefulApp
import org.kde.kirigamiaddons.settings as Settings

StatefulApp.StatefulWindow {
 id: root

 windowName: 'Main'
 application: MyApplication {
 configurationView: Settings.ConfigurationView { ... }
 }

 Kirigami.Action {
 fromQAction: MyApplication.action('add_notebook')
 }

 Connections {
 target: MyApplication

 function onAddNotebook(): void {
 ...
 }
 }
}

There is a new template available in KAppTemplate, which allows you to kickstart your new Kirigami application with the basic skeleton with this new module and other “Kirigami Addons” modules.

Other Changes

The FormCard design was tweaked a bit more when using a dark theme, thanks to James and Joshua for their feedback.

Speaking of FormCard, with the development of KeyChain, I ended up adding a new component to the FormCard collection: FormTextAreaDelegate. This component is the equivalent of FormTextFieldDelegate but with a TextArea instead. FormComboBoxDelegate and FormTextFieldDelegate also received a bunch of new properties and functions to proxy the underlying QtQuick.Controls component.

Evgeniy Harchenko tweaked a bit the headers of the TableView component.

Finally, a new contributor Andreas Gattringer fixed a crash in the video maximizing component which was affecting NeoChat.

Packager Section

You can find the package on download.kde.org and it has been signed with my GPG key.

Building QML Android Applications

Qt Creator uses Gradle for project building. Once your project code is ready, select the Android kit for building in Qt Creator. Click build, and Qt Creator will generate Gradle configuration files for you. However, you may encounter errors such as:

Execution failed for task ':processDebugResources'. A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction Android resource linking failed aapt2 E 07-23 15:59:44 51907 51907 LoadedArsc.cpp:94] RES_TABLE_TYPE_TYPE entry offsets overlap actual entry data. aapt2 E 07-23 15:59:44 51907 51907 ApkAssets.cpp:149] Failed to load resources table in APK '/home/zhy/Android/Sdk/platforms/android-35/android.jar'.

This is because the current Gradle plugin version does not support android-35. SeeHow to fix "Execution failed for task ':app:processDebugResources'. > Android resource linking failed"[Android/Flutter] - Stack Overflow

To resolve this issue, you need to modify the Gradle configuration.

Navigate to the /build/Qt_6_7_2_Clang_arm64_v8a-Debug/android-build folder in your project.

Open the build.gradle file and locate the dependencies block:

dependencies {
        classpath 'com.android.tools.build:gradle:7.4.1'
    }

com.android.tools.build:gradle:7.4.1 refers to the Android Gradle Plugin (AGP). This default version is from 2022 and is quite outdated.

You can find the latest version here: Maven Repository: com.android.tools.build » gradle

Update the plugin version to a newer one, for example:

    dependencies {
        classpath 'com.android.tools.build:gradle:8.4.1'
    }

Additionally, when upgrading the plugin version, ensure compatibility with the Gradle version.

Check the relationship between the Gradle and AGP versions here: Android Gradle plugin 8.5 release notes | Android Studio | Android Developers

Reference: Could not find com.android.tools.build:gradle:7.3.3. error found in build.gradle file - Stack Overflow

Therefore, you should use at least Gradle version 8.6 to support this plugin.

Navigate to the ./gradle/wrapper folder and open the gradle-wrapper.properties file. This file defines the Gradle version used by the project.

Find the line: distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip

Change it to:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip

This update specifies that the project will use Gradle version 8.6.

After making these changes, click on build. It will automatically download the specified version of Gradle and then download the necessary Gradle plugins.

If successful, you can find the built APK at ./build/outputs/apk/debug.

Running and Installing APK

In a Linux environment, you can use the adb command to install the APK on your Android device. Alternatively, you can use Qt Creator for one-click deployment.

After connecting your Android device via USB, use the adb command to install the APK:

adb install android-build-debug.apk

Make sure that your Android device has Developer Mode enabled. You can find specific instructions on how to enable Developer Mode based on your device model through an online search.

Monday, 22 July 2024

Since our main problem up to this point is to deal with the constant micro-pixel calls, we decided to discard all these < 1 pixel movements by filtering out distances of less than 1 pixel before they go down the pipeline in KisToolFreehandHelper::pai...