sensorfw & Qt is not just UI framework! or Without sensors, there's no IoT

Like it says on the Intel IoT developer site, "Without sensors, there's no IoT".

Because I am the maintainer of QtSensors, I like to inquire about  people's use of sensors and if they use QtSensors. Over the years, I have heard quite often something like, 'Qt is thought of as a UI framework'. *sigh*
 
But Qt is more than just a UI framework and it's use is not dependent on widgets or declarative wizardry. It is used in quite a few middleware components without UI elements. One of those middleware frameworks is Sensor Framework.

Sensor framework is a daemon that uses a plugin system written using Qt for reading various sensors such as accelerometer or light sensors. It was originally developed by Nokia for Harmattan and ran on the N9. It was also used in MeeGo and later included in the Mer Project and on Jolla phones and the ill fated tablet. So it has been released onto a few commercial products.

We looked at it when I was working at Nokia on the project that I still cannot name, but we had decided we would come up with our own solution. Looking back, this was the wrong decision, we should have taken the already proven sensor framework and ran with that. Why? Because it existed and works.

I started maintaining it when I was a privateer (contractor) developer for Jolla. No one else had touched it for some time so I grabbed the few not yet merged bug fixes and added support for libhybris/android libhardware adaptors.

Sensor Framework has support for multiple clients with down sampling for different data rates. It uses dbus for control lines (to start and stop, etc) but sends data through a socket. It also has a working backend in QtSensors.

I noticed that Ubuntu's Unity does nothing to respond when I put this into "tablet mode". I have to manually open the virtual keyboard among other things.

So I thought I could use sensorfw on my Dell 2 in 1. It's one of those converged laptop/tablet devices. It has a few sensors - accelerometer, gyroscope, magnetometer, and lid sensors. One problem... sensorfw does not support lid sensors, or a few other sensors that are around today in IoT (which I will add a bit later). Lid "sensor" might be a bit of a misnomer, as they could be switches but I'd like to think it is more like a hal effect sensor that uses magnets. In any case there are event nodes to use.

First one I chose is to add the lid sensor - to detect when this machine is put into tablet mode, so the UI can better deal with it.

I also noticed that this kernel has support for iio sensor interface for the accel and gyro. Sensorfw only supports sysfs, evdev and hybris interfaces, so I also wanted to add support for that.

I worked on adding iio support first. Well... really just wrote a sensor adaptor plugin. My plugin supports accelerometer, gyroscope and magnetometer, which this device seems to have. I will expand this to support other sensors later, as well as clean it up a bit.

Thanks to QtSensors sensor framework backend, I can make a UI app change with the orientation and lid changes. Better yet, I can create a game that uses accelerometer data like a marble maze game. Or I can upload the data to one of those Node.js data visualization web apps.

And since sensor framework is opensource, others can as well.


20 Free & Secure Alternatives to the Parse Push Service

Since Facebook announced the end of Parse, we’ve been looking at the best alternatives for sending push notifications.
Push notifications are an essential tool for engaging and retaining users. Developers can use them to send their users reminders, let them know about recent updates or ask for reviews and feedback. Using a reliable service for push notifications helps if you want your app or game to have active users.
Until now, Parse has been one of the best suppliers of this service. Unfortunately, it ends, in it’s current form, after January 2017. It’s becoming an open-source project and won’t offer all the same services as it used to.
Since this news broke in January 2016, a number of alternatives to Parse have grown in popularity. We’ll take a look at what these services have to offer and how they compare to the original Parse Push notification service!

Plus, find out how to integrate a push notifcation service into your V-Play App or Game with a simple code snippet!

Requirements – Alternatives to Parse

We had four main requirements in mind when looking into Parse alternatives:

download

Free Usage Plan

The new service should provide a free usage plan so developers can try it out for themselves and see how to get started. Signing up for a service without the ability to test their push notification features in a real world scenario is a serious roadblock for most developers.

Similar Feature Set

The new plugin should provide the same feature set we already offer with our Parse plugin. We still want the ability to send push notifications on a transactional basis to single devices, all devices of a user, or a group of users. This is an essential feature that must be supported. The concept of channels, used within the Parse plugin, is an optimal design pattern that we want in any potential replacement.

Easy Migration

We were looking for a scenario where transitioning from one push provider to another would only take a few seconds. The best case would see you as a Parse Plugin user making only one change to your code, simply changing your item’s name to see the new service properly set up.

Cross-Platform Performance

Like Parse, a new plugin should handle the platform-specific differences between iOS and Android transparently, both in the app or game code, and from the back end side.

player_retention_local-notifications-e1404839560228

Ideally, sending pushes from your server shouldn’t get out of control when sending different requests for iOS and Android, and dealing with sockets or customized payloads. We wanted to stick with a simple HTTP request, sending a JSON body, and the rest being handled by the push plugin when possible.

We also kept in mind that we’d probably want to have the option of supporting push notifications on new platforms in the future. So services that already provided push notification support for Windows Phone 10, Ubuntu Phone or desktop notifications earned extra points.

Available Services for Sending Push Notifications

Based on these requirements, we had a closer look at alternatives to the Parse Push service. We’ve ranked the services too, with the best Parse alternatives for V-Play developers getting extra points. These were the services that made it onto our final shortlist:

Google Cloud Messaging (GCM)

Google Cloud Messaging (GCM) soon became our favourite for a feature-complete Parse substitution for V-Play developers. Google provides an abstracted push service for both iOS and Android, using Push only is free, and Google’s topics can be created from your app without any additional server-side code.

parse_alternatives_GCM
Furthermore, as Parse is already using GCM service as a foundation for sending pushes, push performance is identical to using Parse.

OneSignal

As we started implementing GCM, we also had another look at alternatives for the V-Play Game Network. We wanted to find a way of sending and receiving push notifications for game invites, user chats or friend requests. Based on this simple feature set, we had a look into OneSignal.

parse_alternatives_OneSignal
OneSignal supports a wide range of platforms, including iOS and Android and also supports a similar feature to Parse channels, called tags. You can set a collection of tags on a device and target your push notifications based on those tags. This looked promising!

OneSignal also provides server-side localization of push notifications, maintaining the different device languages in their own database and allowing you to update your push texts without releasing a new app update. You can send a localized push notification for three languages from your back end, just like this curl request demo:

curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Authorization: Basic <API-Key>" \
--data-binary '{
"app_id": "<App-ID>",
"contents": {
"en": "New friend request",
"de": "Neue Freundschaftsanfrage",
"es": "Solicitud de nuevo amigo",
"fr": "Demande d’ajout"
}
}' \
https://onesignal.com/api/v1/notifications

Depending on the device language, only the set language will be sent to the device and shown in the push.

Tags can be aggregated and it’s also possible to use different operators. So if you tag your users with a region identifier and their current user level in your RPG game, you can send a push to users who are currently checked in at middle-earth and have a level greater than 10, with a tag combination of:


[

{"key": "region", "relation": "=", "value": "middle-earth"},

{"key": "level", "relation": ">","value": "10"}

]

 

OneSignal service is free for all push notifications and provides a lot of features. These are covered in our documentation.

Batch

While there are many great services out there, a lot of them missed our basic requirements for app and game push notifications. Some of the services lack a free plan for transactional push notifications, although they are reasonably priced for their rich feature set, such as Batch.

parse_alternatives_batch
Unfortunately, Batch doesn’t provide a concept like channels for transactional pushes. It’s only possible to assign a single value for identifying users across devices. They have a great feature set though so we will be keeping an eye on any developments regarding the Batch service.

Urban Airship

Urban Airship does a great job at handling marketing and campaigns. They automatically segment users based on events triggered from within your app, something it has in common with Batch.

parse_alternatives_Urban Airship
These features are quite nice for advanced use cases, but they’re not suitable as a replacement for Parse. Their initial set up for a new push service is much harder than the current method. Also transactional pushes with Urban Airship aren’t that feature-rich, as is the case with others.

Amazon SNS

Amazon SNS looked great when we first considered it. There’s a free plan, transactional push notifications and Amazon provides a similar concept to Parse’s channels, called topics. Unfortunately, it’s not possible to create new topics on-the-fly. You have to create topics from your server-side code first, making things a lot more complicated for your back end.

For example, sending pushes to all devices of a user, identified by a userId, is easy with Parse:


Parse {

channels: [ "userId" ]

}

When trying to do this with Amazon SNS, you first have to explicitly create this channel/topic (“userId”) from the back end. It’s not possible to create topics on-the-fly.

And there’s another restriction on Amazon SNS: You can only create up to 10.000 topics per app. While this might seem like more than enough, if you create a sports news app that sends out push notifications for a range of sports, it’s not possible for all your users to get a unique channel. Instead, you would have to manage tokens and users in your own database back end.

Note: Amazon released an even newer push notifcation service just as this article was being written. You can check out Amazon Pinpoint here.

Firebase (FCM)

Firebase was acquired by Google in 2014 but it was only this year that they started to support push notifications. It also added advertising through AdMob integration and analytics for mobile developers.

firebase
These sound like cool new features, but Google basically just added GCM as a push back end and AdMob for advertising and renamed them “Firebase”. As we currently support both features with our GCM and AdMob plugins , Firebase isn’t ranked as highly as you might expect. We are however looking into other features of Firebase and will keep you updated on this one!

Accengage

Accengage offers a range of Push services for mobile developers, from CRM connections to Push Geomarketing.

logo-accengage-205x49
You can try it for yourself with their free demo but it will cost you to use their full services. The main advantage of this service is the ability to segment users in a number of ways. You can segment your users based on a range of behaviors and target them for better engagement. The lack of a full free service is the only thing stopping it from being ranked higher.

Catapush

This service is dedicated specifically to sending push notifications and is priced depending on how many active users you have. Their free tier allows you to engage with up to 100 monthly active users.

catapush
Anyone looking for advanced push notification features as standard should take a look at Catapush. They offer guaranteed delivery, delivery statistics and 2Way communication through push.

Quickblox

While QuickBlox isn’t an all-in-one service, it does offer separate SDKs for sending push notifications with iOS and Android. And their free plan lets you send 20 notifications per second, as long as you have less than 20,000 users.

We can’t attest for how easy it is to send these notifications or what customizable options are available. But their free plan definitely offers value for developers working within a restricted budget.

Boxcar

Boxcar calls itself the “Universal Push Notification Platform” and is another service worth checking out for those with a smaller  budget. It offers cross-platform support for iOS and Android and let’s free users send 200 Pushes Per Minute.

boxcar
On top of that, the team at Boxcar.io reckon they have the fastest Push notification network on the market.

Parse – Open Source

For a couple of months now, the Parse open-source server has been supporting the sending of push notifications. However, there are important features missing like sending queues, so it’s not really production-ready as of now.

Backendless

Backendless offers a fully-functioning mobile-backend-as-a-service to developers. This service includes the ability to send push notifications from client or server and has cross-platform capabilities.

backendless-com
Perhaps the strongest feature of the Backendless MBaaS is the ability to push to iOS, Android, Windows Phone and Amazon users at the same time. Backendless offers a free license with extra features available when you need them.

Sashido

If your main concern when finding a Parse alternative is avoiding downtime during migration, then Sashido is a strong choice. They offer to migrate your services with zero downtime.

sashido
Sashido also offer 24hr support. You can start your 14-free trial to see how quick migration really is and see if the service suits your needs. After that, you can use Sashido on a pay-as-you-go basis, choosing only the services you need!

Syncano

Syncano offers the ability to send push notifications to Android and iOS users. This is possible from a dashboard that was designed with ease-of-use in mind. Syncano is a customizable tool with the ability to add sockets to your app.

syncano
You can get started with a 30 day free trial and continue using Syncano’s services from $25/month once it ends.

TeraData

TeraData, or Appoxee as it was once known, offers their own complete tool for sending push notifications. TeraData offers a campaign builder, personalization options and a dashboard for tracking the success of push notifications to iOS and Android devices.

teradata
A demo of TeraData is available on request.

Kumulos

Although Kumulos is mainly aimed at app marketing agencies, it may have some use to you as a developer. It offers cross-platform push notifications for Android and iOS and user segmentation features.

kumulos-logo1
Kumulos service’s begin with a free trial and can be used on a pay-as-you-go basis after that.

Carnival

Not only does Carnival offer push notifications, it provides a range of rich messaging services. These allow you to customize your push notifications with images and videos. The service also includes the ability to send in-app notifications and deep-link messages that bring your user to a different part of your app.

carnival
Carnival starts with a free demo available upon request.

Streethawk

streethawk
StreetHawk offers push notifications for Android and iOS users along with a host of other user retention and engagement solutions. With a simple integration model and the ability to send triggered notifications, it may be worth checking out. StreetHawk starts as a free trial and integrates with a number of services such as Flurry. Mixpanel and Segment.io.

Pushwoosh

This service offers the ability to send push notifications to up to 500,000 devices free. It has support for Android, iOS and 19 other platforms.

If you’re interested in more than sending push notifications, things can get pricey quickly with this service. Their first paid license starts at $50/month, although it’s stacked with features.

Kinvey

Kinvey offers enterprise-level solutions for a number of business, but you can’t forget it’s MBaas too. Along with Push Notifications, it offers data storage, location tracking and more. If you have a large project in mind, it may be worth getting in touch with Kinvey to see what kind of a deal they can do for you.

While there’s no free trial to speak of, you may be interested to sign-up and take their free tutorial to see if you’re interested in what they have to offer.

Parse Alternatives for V-Play

You can add push notifications to your V-Play App or Game in just a couple of minutes. Here’s a quick code example to show you how easy it is to add OneSignal push notifications to V-Play:

import QtQuick 2.0
import VPlayPlugins 1.0

OneSignal {
  appId: "<add-your-app-id-here>"
  onNotificationReceived: {
    console.debug("Received notification with message:", message)
  }
}

For further information on how to integrate the OneSignal Plugin with your V-Play app or game, see our documentation.

 

To summarize, we decided to go with two plugins for now: Our new OneSignal plugin, which features an easy setup and simple, targeted push notifications. And the new Google Cloud Messaging plugin that supports advanced use cases like client-side localized push notifications and invisible background downloads, as already provided by our Parse plugin.

You can access V-Play Plugins for monetization, analytics and more with the V-Play Indie License. To test the plugins for yourself, download our Qt Plugin Demo App from the App Store and Google Play.

App Store Google Play

For the full source code of this sample app, including all V-Play Plugins, you can check out this GitHub sample.

Get Source Code!

More Posts like This

16 Great Sites Featuring Free Game Graphics for Developers

game graphics

The 13 Best Qt, QML & V-Play Tutorials and Resources for Beginners

tutorials capture

21 Tips That Will Improve Your User Acquisition Strategy

User Acquisition

7 Useful Tips That Will Improve Your App Store Optimization

User Acquisition

 

References

The post 20 Free & Secure Alternatives to the Parse Push Service appeared first on V-Play Engine.

How to Make tvOS Games & Apps with V-Play and Qt

tvOS is the smart TV operating system from Apple that let’s you play games and use apps on your Apple TV. Support for tvOS apps and games has been added to V-Play & Qt so now you can launch your cross-platform games and apps on your Apple TV too.

Get tvOS Support!

What is tvOS?

Apple based tvOS on iOS but it also includes a range of frameworks that are only supported on Apple TV. The company launched it in September 2015 alongside the 4th generation of Apple TV. The Apple TV is a device that acts as a digital media player and micro-console with a touch-screen interface.

tvOS lets you play games and use apps from your Apple TV. It offers a unique experience in comparison to a mobile device or tablet. It’s better suited than smaller devices at creating a shared experience for users. This is because the large screen allows multiple people to interact with it at the same time.

This shared experience is the focus of the tvOS user experience. You need to keep it in mind when you create your own tvOS apps and games.

Why Develop for tvOS?

There are many reasons why making tvOS apps and games make sense.

The Growing Popularity of Smart Homes

Smart devices like the Apple TV are only a small part of the Internet of Things that will become more popular in the next few years. Many companies are working on ways to make the home more intelligent. As this trend grows, Apple TVs and tvOS may become as popular in homes as the MacBook or iPad.

As it’s only been a little over a year since it’s release, tvOS is still a relatively young OS. While there’s no guarantee of success, it’s hard to see Apple letting one of Steve Job’s greatest passion projects fail.

app-icons-2
These factors point to one thing for developers considering the tvOS marketplace. It’s an opportunity to place your apps and games on a platform with huge potential for growth.

A Lack of Competitors

It’s no secret that it’s becoming harder for apps and games to get seen on both Google Play and the App Store. It’s not just harder for your app to get discovered, cost-per-install is on the rise for most developers too.

There are other avenues available to mobile developers. But targeting a platform other than these two means entering into shrinking marketplaces. These marketplaces are already struggling for relevance and will do for years to come.

tvOS apps and games don’t have either of these problems. They exist in a small marketplace that still has the opportunity to grow.

apple-tv-1024x390

Not having to worry so much about app store optimization and user acquisition is a bonus. It means you can invest more time in developing a great app rather than marketing. And as the marketplace grows, you’ll be in the right place to take advantage of it’s popularity

The Unique Monetisation Possibilities of tvOS

V-Play developers will know about all the mobile platforms they can launch their apps & games on. But it’s worth noting that you will also be able to port your existing apps and games to tvOS with minimal effort.

With it being so easy to bring your game or app to this new platform, you should know that it can be profitable too. Opportunities exist for both F2P and premium apps and games to make money from Apple TV users.

If your F2P game or app is doing well, it won’t hurt to get a little extra ad revenue by putting your app or game on Apple TV. The real benefit is for developers seeking to release premium apps and games.

Historically, people seem to have no problem paying to see stuff on their televisions. Whether it’s extra channels, pay per view events or apps and games. There seems to be less resistance to shelling out for something that appears on TV.

1b55bbf5f042efa750d9d695f9d3dd5f

It’s also worth noting that Apple users are more likely to buy premium apps anyway. Paid apps make up 47% of the apps available for Apple TV. So some developers must have had success in this area already.

What to Know Before Getting Started

Before you get started on making your tvOS app, here are a few considerations to keep in mind.

The Big Screen Experience

Using an app or playing a game on a TV screen is a different experience than using a phone or tablet. Make sure you understand the differences before you start making your app or game. If possible, try out the Apple TV for yourself and test some games and apps to see what works best.

Remote Controls & How to Use Them

All Apple TVs come with a remote that’s used for navigation. The main feature of the remote is a touch surface that works extensively with swipe gestures. It also features  buttons for standard actions such as play/pause and volume up/down. You’ll need to consider if these navigation differences will affect the UX that your app or game provides.

remote-and-interaction-remote-diagram_2x
Will you need to change the user interface for your app or game to accommodate the remote? It’s an important factor to consider before porting your app or game to tvOS. The purpose of the remote control is to make navigation seamless. This means you need to straighten out any hitches in your UI before you target the platform.

Keep Multiple Users in Mind

As mentioned, the Apple TV creates a shared experience; just like a traditional television set. There’s no such thing as creating a tvOS app or game for just one person. You need to be aware that there may be multiple users viewing your app or game at any time.

No Local Storage

tvOS apps have a maximum size of 200 MB and don’t make use of local storage. Instead, you need to stream app data from iCloud. Apps larger than 200MB can be packaged and loaded with On-Demand Resources. If you’re not a fan of a data-conscious approach, then tvOS apps mightn’t be for you.

tvOS Development with V-Play

You can develop apps and games for tvOS using the exact same V-Play workflow as you would for Android or iOS. You write your code in Qt Creator and deploy it from there to an Apple TV or simulator. Porting your existing games is easy too. tvOS support for V-Play uses the same API as the current SDK, so your game or app won’t change in any way when you port it to Apple TV.

one_game

V-Play is yet to support touch input but it supports a range of swipe gestures on remote control. V-Play mapped these gestures to the up/down/left/right keys of a keyboard. This makes it possible to test your game or app on desktop before deploying to Apple TV.

Nativeutils are fully implemented for tvOS. This makes it possible to show native confirmation dialogs and input dialogs in your app or game. This feature is essential for providing your users with a native UX.

V-Play added support for key events such as buttons and focus hints. This enables you to improve the UX of your app or game by making it easier for users to see which button is selected.

You can also add the Google Analytics plugin to your tvOS app or game in just a few minutes. See our documentation for more details on how to add this plugin with just a few lines of code.

tvOS Example Game – One Card!

V-Play has an example tvOS game on the App Store. V-Play released One Card! for iOS and Android but we were able to port it to tvOS with only minor additions to the source code.

The only change we needed to make was to add support for keyboard input (up, down, left, right, enter). We wanted this feature so it would be easy to test apps and games on desktop before deployment to Apple TV.

As there’s no point device available, we also added a focus hint for the currently active (selected) item, like the currently active card from the user’s stack or the selected menu item in the main menu.

Finally we added one of those shiny app icons with parallax effect, which are the essence of the Apple TV user experience All of these changes took less than a day. You can do the same with your V-Play games or apps!

one_gameover

One Card! uses V-Play Multiplayer, an all-in-one multiplayer component that adds the following features to your game:

You can use this open-source game example as the basis for all your multiplayer card games. You can access the free source code when you download V-Play.

 

 

You can download One Card! for tvOS here and view the source code in the V-Play SDK.

itunes_download_link
You can also play One Card! on Android and iOS devices
google_play_badge-1 itunes_download_link
Current V-Play developers can also find more info on One Card! in the V-Play documentation and the source code in the V-Play SDK here:

<Path to your V-Play SDK>/Examples/V-Play/demos/OneCard/OneCard.pro

Get V-Play Support for tvOS Development

At the moment, tvOS development with V-Play is available to Enterprise customers only. Enterprise customers can access all V-Play Plugins and features and receive advanced support and training. Make sure to get in touch if you’d like to become an Enterprise customer and we can arrange your Enterprise evaluation today!

Get tvOS Support!

More Posts Like This!

16 Great Sites Featuring Free Game Graphics for Developers

game graphics

16 Great Websites Featuring Free Game Sounds for Developers

game sounds

 

21 Tips That Will Improve Your User Acquisition Strategy

User Acquisition

7 Useful Tips That Will Improve Your App Store Optimization

ASO screen capture

The post How to Make tvOS Games & Apps with V-Play and Qt appeared first on V-Play Engine.

Qt Creator 4.2 RC1 released

We are happy to announce the release of Qt Creator 4.2 RC1.

Since the release of the Beta, we’ve been busy with polishing things and fixing bugs. Just to name a few:

  • We fixed that the run button could spuriously stay disabled after parsing QMake projects.
  • Qt Creator is no longer blocked while the iOS Simulator is starting up.
  • We added preliminary support for MSVC2017 (based on its RC).

For an overview of the new features in 4.2 please head over to the Beta release blog post. See our change log for a more detailed view on what has changed.

Get Qt Creator 4.2 RC1

The opensource version is available on the Qt download page, and you find commercially licensed packages on the Qt Account Portal. Please post issues in our bug tracker. You can also find us on IRC on #qt-creator on chat.freenode.net, and on the Qt Creator mailing list.

The post Qt Creator 4.2 RC1 released appeared first on Qt Blog.

Fuzzing Qt with libFuzzer

Disclaimer: I had this blog post in the drawer for several weeks now; I just held back with publishing it to give the Qt security team time to fix the reported issues (see below under 4.).
Inspired by the great talk from Hanno Böck aboutAmerican Fuzzy Lop and Address Sanitizer at QtCon, having a try on fuzzing Qt itself seemed like an interesting thing to do. For fuzzing different parts of a library like Qt, libfuzzer is a good choice: In contrast to e.g. American Fuzzy Lop, libfuzzer runs the test cases in the same process and does not need to spawn a new process for each test, which makes it very fast.
These are the steps to set up libFuzzer and test it on Qt:
1. Compile Qt with address sanitizer and code coverage information:
To get proper output when something is wrong (e.g. "heap user after free"), Qt needs to be built with address sanitizer; in addition, libFuzzer collects information about which code paths it has visited. To enable those two settings with clang on Linux, the following patch has been applied:
diff --git a/mkspecs/linux-clang/qmake.conf b/mkspecs/linux-clang/qmake.confindex 77d913f..03d4c47 100644--- a/mkspecs/linux-clang/qmake.conf+++ b/mkspecs/linux-clang/qmake.conf@@ -11,6 +11,8 @@ include(../common/linux.conf)include(../common/gcc-base-unix.conf)include(../common/clang.conf)-QMAKE_LFLAGS += -ccc-gcc-name g++
+QMAKE_LFLAGS += -ccc-gcc-name g++ -fsanitize-coverage=edge -fsanitize=address+QMAKE_CFLAGS += -fsanitize-coverage=edge -fsanitize=address+QMAKE_CXXFLAGS += -fsanitize-coverage=edge -fsanitize=address
load(qt_config)
Even without using a fuzzer, compiling Qt and an application with address sanitizer might highlight problems within the code.
Apparently the settings above are also available for gcc; also, it might be possible to specify those changes on the command line instead of patching the mkspec file.
2. build libfuzzer:
Libfuzzer is part of llvm, and has atutorial on how to build it. The resulting libFuzzer.a needs to be linked to the executables, as explained in the steps below.
3. write test cases:
For the fuzzing test cases, there is one function to be implemented, which will be called automatically by the fuzzer. Here is an example of a simple Qt test case:
#include <QtCore>#include <QtSvg>extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {QByteArray byteArrayData(reinterpret_cast<const char *>(Data), Size);QSvgRenderer renderer(byteArrayData);return 0;}
In particular, the test programs do not need a main() function, as it is already contained in libFuzzer.a. Here is the .pro file for the test case above:
TEMPLATE = appTARGET = QSvgRendererINCLUDEPATH += .QT += svg# InputSOURCES += qsvgrenderer.cppLIBS += -L/home/peter/dev/fuzzers -lFuzzer
The full set of Qt test cases written so far can be found on github:
This repository contains tests for QImage, QJsonDocument, QtNetwork and QXmlStreamReader, among others.
4. run and report results:
The test cases can be run using all available cores via e.g. "./QSvgRenderer -jobs=4 -workers=4 testcases". Also, the github repository above contains an initial set of test cases the fuzzer can start with. For instance when fuzzing SVG images, it makes sense to start with a valid SVG file as initial input.
The tests from the repository produced some issues in Qt, which have been reported to the Qt security mailing list or the Qt bugtracker (for stack traces and information on how to reproduce see the links):
QtDbus heap use-after-free(reported to the security mailing list on 16th of October 2016)
QJsonDocument heap buffer overflow(reported to the security mailing list on 19th of October 2016)
memory leak when creating an invalid SVG filereported to the Qt bug tracker on (23rd of October 2016)
Next steps:
A good way to improve results seems to look intouser-supplied mutatorsto have more control over which input is fed into the test cases. E.g. flipping bits seems like a good default way for binary data such as images, but when it comes to JSON or XML, there might be smarter ways to produce faulty input.

SpeedCrunch 0.12 Released

Almost 3 years and 700 000 downloads later, here's the core new features of this release:
If you're curious, check out the complete list of enhancements and bug fixes. Or go straight to the downloads page. For better productivity, learn about all the user interface quirks at your disposal.

MacOS users: please note that a download is not yet available for you. If you can help us with that, please get in touch.

Don't forget to report issues or request new features in our tracker. See more ways to contribute in the Help menu on the new website. Please help us release 1.0 as quickly as possible. Have a look at what's planned already.

Massive thank you to TeyutPol WelterFelix KrullHadrien Theveneaul.inc, all the translators at Transifex, and the folks over at Portable Apps (for representing a nice chunk of our user base).

Cheers

KDAB and Meiller – Tipper Truck App

Design, Technical Excellence and Superb User Experience

Why does a tipper truck need an app? Meiller is the leading manufacturer of tippers in Europe. KDAB software developers and UI/UX designers worked with Meiller to create a mobile app that interacts with embedded hardware on the truck, allowing drivers to diagnose and fix problems – even when on the road. KDAB shows us how technical excellence and stunning user experience go hand in hand.

The post KDAB and Meiller – Tipper Truck App appeared first on KDAB.

Qt World Summit 2016 Webinar Series – Christmas Sessions

events_generic_xmas1

‘Tis the season to be jolly and as always we are just trying to be Qt /kjuːt/. We just keep on giving and giving and here is another present for you. We are hosting webinars based on the breakout sessions from The Qt World Summit 2016. So, grab a cup of cocoa and sign up for our December Tuesday webinars where you can join our R&D developers online for technical sessions that will keep your computer warm throughout 2017. The best thing of all – even if you can’t make it online – by signing up Santa will bring the recorded session to you.

Introducing Qt Visual Studio Tools

December 6th at 5 pm CET, by Maurice Kalinowski

New possibilities with Qt WebEngine

December 13th at 5 pm CET, by Allan Sandfeld Jensen

Qt Quick Scene Graph Advancements in Qt 5.8 and Beyond 

December 20th at 10 am CET (Rescheduled from November 15th), by Laszlo Agocs

 

Also, stay tuned for details on upcoming webinars in January!

Make sure to check our events calendar for the full list of Qt-related events delivered by us and our partners.

The post Qt World Summit 2016 Webinar Series – Christmas Sessions appeared first on Qt Blog.

Captain obvious: Sign a contract before starting to work

I have worked as a freelancer for more than a decade and was very very fortunate with the projects and partners I had. I apparently let my guards down a little bit too much and this is a reminder what to look-out for.

I have nice memories working with the Trolltech PSO team and helping with architecture, performance and low-level debugging in South Korea but when Nokia stopped investing into Qt my work on Qt and QtWebKit halted and I moved to work exclusively on GSM/3G systems. Through linkedin I got approached by a Korean business owner that spent some time working in Norway and for some companies well known to (old) Qt developers with something that looked like an opportunity to pick-up my old work. Given the common background and my work in Korea I immediately trusted this person.

I have a thing for tight deadlines and some forms of death march projects and was curious of how much the landscape changed. I thought we agreed on times and material for an exploration phase to see if the rest of the project is feasible and depending on the result move on or not, HW was sent and while there was no signed agreement I began to work. The exploration was fun but the setting was difficult and turns out there was no intention to pay for the exploration phase.

Which brings me to things I have to remember and want to share with you:

  • Don’t start to work before there is a written and signed agreement
  • If there is a tight deadline the burden on making the contract is on your customer and not you. If the contract is too long to read, reject it.
  • Don’t take the risk of unpaid exploration if you have no influence on the final project

Desktops DevRoom @ FOSDEM 2017: you are still on time to submit a talk

FOSDEM 2016 is going to be great (again!) and you still have the chance to be one of the stars.

Have you submitted your talk to the Desktops DevRoom yet?

No?

Remember: we will only accept proposals until December 5th. After that, the Organization Team will get busy and vote and choose the talks.

Here is the full Call for Participation, in case you need to check the details on how to submit:

FOSDEM Desktops DevRoom 2017 Call for Participation

Topics include anything related to the Desktop: desktop environments, software development for desktop/cross-platform, applications, UI, etc

Cutelyst benchmarks on TechEmpower round 13

Right on my first blog post about Cutelyst users asked me about more "realistic" benchmarks and mentioned TechEmpower benchmarks. Though it was a sort of easy task to build the tests at that time it didn't seem to be useful to waste time as Cutelyst was moving target.

Around 0.12 it became clear that the API was nearly freezing and everyone loves benchmarks so it would serve as a "marketing" thing. Since the beginning of the project I've learned lots of optimizations which made the code get faster and faster, there is still room from improvement, but changes now need to be carefully measured.

Cutelyst is the second Web Framework on TechEmpower benchmarks that uses Qt, the other one being treefrog, but Qt's appearance was noticed on their blog:

https://www.techempower.com/blog/2016/11/16/framework-benchmarks-round-13/

The cutelyst-thread tests suffered from a segfault (that was restarted by master process), the fix is in 1.0.0 release but it was too late for round 13, so round 14 it will get even better results.

https://www.techempower.com/benchmarks/

If you want to help MongoDB/Grantlee/Clearsilver tests are still missing :D

Release 2.9.2: Qt World Summit 2016 App Showcase and New App Components

V-Play 2.9.2 is now available to download. It adds the open-source Qt World Summit 2016 Conference app example, a range of new V-Play Apps components and a number of improvements and fixes.

The Qt World Summit 2016 Conference App was created by the V-Play team. It allowed developers attending this year’s event to get an overview of the talks that were happening, find information about speakers and create their own schedule. The source code of this app is available as an open-source app example when you download or update to V-Play 2.9.2.

V-Play 2.9.2 also adds a new range of V-Play Apps components. You can now enjoy native-looking search functions, tab bars, list views and more. Get it now for free and try out these new features for yourself!

Update Now!

Qt World Summit 2016 Conference App Example

This new app example is available as an open-source demo and can be used as the basis for your own mobile apps. Along with it’s primary function as a scheduling tool, it also includes an in-app chat feature, personalization features and gamification features that are sure to boost app engagement.

native-navigation-ios-and-android

This cross-platform app includes the following features:

  • Browse the conference schedule.
  • See detailed information for all talks, speakers and tracks.
  • Manage your personal schedule by adding talks to your favorites.
  • Customize the UI and switch between different native styles and colors.
  • Earn points for each app-start and favorited talk to climb the leaderboard.
  • Make friends and send messages with the integrated in-app chat.

Viewing this app example is a great way to get acquainted with the best practices of developing a V-Play app and see how a native UI & UX looks with an app developed with V-Play.

apps-demo-qtws-ios-2 apps-demo-qtws-ios-3 apps-demo-qtws-ios-4

apps-demo-qtws-android-2 apps-demo-qtws-android-3 apps-demo-qtws-android-4

You can learn how to handle app specific requirements such as offline capability, how to use native device features like confirmation dialogs and how to use a single codebase to create an app that’s supported across multiple platforms, screen sizes and screen resolutions.

To get a look at the Qt World Summit 2016 Conference app in action, you can download it from either the App Store or Google Play using the links below. The app is free to download so get it now!

google_play_badge-1 itunes_download_link

It’s also available to download from GitHub:

github_logo

New V-Play Apps Components

V-Play Apps has added a number of new app components in this latest update to give your cross-platform apps the same look and feel as native apps for iOS and Android. This means you can create the perfect user experience for both platforms at the same time.

  • Create native-looking tabs with the new AppTabBar and AppTabButton components that also support a swipe-able content view.

apptabbar-control-ios apptabbar-control-android

  • Add a search feature by integrating the SearchBar component with Theme-based styles for iOS and Android.

searchbar-control-ios searchbar-control-android

sectionselect-control-ios sectionselect-control-android

  • Use the AppFlickable to add a native looking rebound effect to your scrolling.

appflickable-ios appflickable-android

textbuttonbaritem-control-ios textbuttonbaritem-control-android

  • Add a material-design styled FloatingActionButton to provide quick access to your Android app’s most important features.

floatingactionbutton-control

V-Play 2.9.2 also comes with improvements and fixes to V-Play Apps such as iOS 10 haptic feedback, navigation bug fixes and dialog bug fixes. For a full list of additions, improvements and fixes to V-Play Apps, check out our change log!

V-Play Game Engine Improvements

With V-Play 2.9.2, you can now check to see if your game is online with the GameWindow::isOnline property.

V-Play Multiplayer and the V-Play Game Network are also now fully compatible with V-Play Apps projects and an issue that was occurring on some Android devices with the BackgroundMusic component is now fixed.

V-Play Plugins Improvements

The latest version of V-Play now supports the most up-to-date Facebook plugin. You can use a new signal with this plugin called Facebook::sessionOpened, that gives you more information about what happens during an opened session.

V-Play 2.9.2 also includes improvements and fixes for existing V-Play Plugins. The platform libraries of the AdMob and HockeyApp plugins have been updated to the latest versions. V-Play Apps developers will also have the option to display customized notification icons with Google Cloud Messaging and OneSignal.

A full list of fixes for V-Play Plugins can be seen in the V-Play change log!

How to Update

Test out these new features by following these steps
Step 1
Open the V-Play SDK Maintenance Tool in your V-Play SDK directory. Choose “Update components” and finish the update process to get V-Play 2.9.2 as described in the V-Play Update Guide.
If you haven’t installed V-Play yet, you can do so now with the latest installer from here.
Step 2
The V-Play Sample Launcher allows you to quickly test and run all the open-source examples and demo apps & games that come with the V-Play SDK, from a single desktop application.
After installing V-Play, you can start the V-Play Sample Launcher from the application shortcut in your V-Play SDK directory.
qt_sample-launcher
Now you can explore all of the new features included in V-Play 2.9.2!
For a complete list of the changes to V-Play with this update, please check out our change log!

More Posts Like This!

16 Great Sites Featuring Free Game Graphics for Developers

game graphics

16 Great Websites Featuring Free Game Sounds for Developers

game sounds

 

21 Tips That Will Improve Your User Acquisition Strategy

User Acquisition

7 Useful Tips That Will Improve Your App Store Optimization

ASO screen capture

The post Release 2.9.2: Qt World Summit 2016 App Showcase and New App Components appeared first on V-Play Engine.

CMake support in Qt Creator (and elsewhere?)

Kitware released CMake version 3.7 on Friday night. There is one feature mentioned at the very bottom of the feature list that makes this a really exciting release for people writing tools that integrate with CMake: The server-mode.

What is CMake server-mode?

The Qt Creator team has had contact with the CMake community for a long time now and was actively involved in discussions with CMake and other IDE and tools vendors. After many discussions the CMake community decided that the best way forward to support the use-cases of IDEs was to add a new interactive way to interact with CMake, the so called server-mode. There was some initial development started by Stephen Kelly, who made an impressive prototype.

At this point the Qt Creator team decided that this functionality is crucial to enable first class CMake support in Qt Creator. So I went ahead and jumped into CMake development. The result is a set of patches that implement a production-ready server-mode for CMake that was merged in time for the CMake 3.7 release. The server-mode currently focuses on core functionality like parsing the project structure, etc.

This development happened in close collaboration with developers from KDevelop and the CMake community.

I am committed to maintain CMake server-mode support going forward and hope to continue to develop this feature in close collaboration with all interested parties.

CMake version 3.7 is the first release that ships this code.

What does CMake 3.7 enable?

The first change in CMake 3.7 is that it now provides machine-readable output with basic information about the capabilities of the CMake binary (via “cmake -E capabilities”).

This includes static information like version number or whether server-mode is available, but also details on the supported generators.

IDEs can use this information to provide a better UI for selecting generators.

CMake server-mode (started via “cmake -E server”) allows IDEs to query a range of CMake settings and project information in a machine-readable form, many of which were not available to IDEs before. This enables a more detailed view of the CMake project.

The information is also taken from CMake directly, making sure to use the same code that is also used by the CMake generators to write the actual build-system files. So the information is more accurate than what was available before. This makes the code model more exactly represent what is actually going to be built.

When will we see these improvements in action?

I think the server-mode is the way forward for all tools that need to extract information from CMake. Interest in this topic seemed very strong in my workshop about CMake at QtCon this year. I hope to see CMake server-mode flourish going forward.

There is code that makes use of the new CMake 3.7 features in the master branch of Qt Creator. So this will be present in Qt Creator 4.3, planned for spring of 2017.

What will improve in Qt Creator?

Creator will continue to support any CMake version 3.0 (or later), just as current versions of Qt Creator do. But Qt Creator master does support CMake server-mode already and will make use of the better information. You will be able to switch between CMake binaries with and without server-mode support as needed.

Using CMake server-mode enabled binaries will have the following effects:

  • Generator selection is no longer limited to those generators with support for the “CodeBlocks” extra generator. Any generator can now be used.
    CMake Generator setup in Qt Creator

    CMake Generator setup in Qt Creator

  • The Generator selection UI now knows which options are available for each generator. E.g. the “Ninja” generator used above does not support Toolsets or Platform settings.
  • The project tree is much improved and knows about projects and build targets defined in CMake."<yoastmarkThe screenshots show the project tree from Qt Creator 4.2 and from Qt Creator master — with an old CMake and with CMake server-mode.
    Qt Creator master adds all headers found in include paths of a build target and not listed in the CMakeLists.txt to the project tree (for all versions of CMake). These headers are printed with a grey text color so they can be distinguished from sources known to CMake.
    In server-mode the project structure is more visible: The “scribus” project defined in the top-level CMakeLists.txt file is clearly visible. So are the different build targets. The “scribus_colormgmt_lib” build target is expanded and all files belonging to that target are listed.
  • The code model has way more accurate information about all targets. This sounds very simple, but has not always been the case for CMake projects up to now.

What will happen next with CMake server-mode?

Stephen Kelly has pioneered interesting features in his CMake server-mode implementation prototype. Many did not make it into the new CMake release.

Going forward I would like to see more of these powerful features. This includes debugging of CMakeLists.txt files and syntax highlighting driven by CMake itself. These require deep integration into CMake and will require a much deeper understanding of CMake internals than I currently have. So I hope CMake developers find the server-mode interesting enough to help out a bit here and there:-)

I would like to say thanks to Aleix Pol (KDevelop) and Stephen Kelly (CMake community) for all the feedback they provided. Finally I have to thank Brad King from Kitware for his patience while  reviewing my code.

Where can I get this?

Get CMake 3.7 here: https://cmake.org/download/
View the Qt Creator master sources: https://code.qt.io/cgit/qt-creator/qt-creator.git/
Or use git to clone the code: git clone git://code.qt.io/qt-creator/qt-creator.git

The post CMake support in Qt Creator (and elsewhere?) appeared first on Qt Blog.

See you at Meeting C++ 2016?

KDAB is again a proud gold sponsor of this year’s Meeting C++ conference, on the 18th and 19th of November.

header_bg

This year’s program features no less than 33 talks, divided into 5 tracks. The conference will be opened with a keynote by Bjarne Stroustrup himself, the ideator of the C++ programming language, and will close with a keynote by Louis Dionne, author of the Boost.Hana metaprogramming library. Also, don’t miss the lightning talks and the official lounge track :).

The conference will be held at the Andels Hotel in Berlin. See you there!

The post See you at Meeting C++ 2016? appeared first on KDAB.

Qt Visual Studio Tools 2.0 Released

Today we are releasing Qt Visual Studio Tools 2.0. This is mainly a release moving the functionality of the old Visual Studio Add-In to newer versions of Visual Studio. In addition to some minor bug fixes the Qt Visual Studio Tools now support Visual Studio 2013 and Visual Studio 2015. The commercial version of the Add-In has been merged and there is now also support for Qt Quick (QML) in the free version of the tools. We also made them available through the Visual Studio Gallery. The version for Visual Studio 2013 can be downloaded here, while you can get the Visual Studio 2015 Version here.

Documentation:

Main Changes:

  • Supports Visual Studio 2013 and 2015
  • Major code refactoring, build system updates, and code cleanup
  • New wizard system based on the Visual Studio extension system
  • Out of the box support for Qt Type C++ Debugger Visualizers (natvis)
  • QML highlighting support
  • F1 help support

Known Issues:

  • Missing localization support
  • Supports only installed versions of Qt
  • Dropped support for older Visual Studio versions and Windows CE

Get the Qt VS Tools

The Qt Company has prepared convenient installers for the Qt Visual Studio Tools 2.0. You can download it from your Qt Account or from download.qt.io. They are also available from the Visual Studio Gallery for Visual Studio 2013 and Visual Studio 2015.

For any issues you may find with the release, please submit a detailed bug report to bugreports.qt.io (after checking for duplicates). You are also welcome to join the discussions in the Qt Project mailing lists, development forums and to contribute to Qt.

The post Qt Visual Studio Tools 2.0 Released appeared first on Qt Blog.

Over-the-Air Updates, Part 3: Repository Configuration and Handling

Part one of the blog post series introduced the challenges of implementing an update system. We looked at the OSTree project and how it can help us to bring system update functionality to Qt for Device Creation. The second part demonstrated the tooling and the API that is provided by the Qt OTA Update module. We ended the second blog post by demonstrating how to generate an update. In this blog post we will export the generated update on a static HTTP server and configure a client device to query this server for system updates. Following this will be a short history lesson on OSTree adoption in the Linux ecosystem. But first we will take a quick look at what’s new in the Qt OTA Update module since the Technology Preview release.

Status Update.

Starting with Qt 5.8 for Device Creation, the Qt OTA Update module is graduating from being a Technology Preview module to a fully supported module. Some of the new features and improvements in Qt OTA Update 1.0 are: initramfs no longer being a hard requirement for using the OTA update feature (desirable when optimizing boot time), new API for configuring how remote OSTree repositories are accessed, more status notifications from the update process for the convenience of users, some minor API renamings, improved demo application and new command line arguments for the qt-ostree tool (for fine-tuning the image and update generation).

Exporting Repository.

As mentioned earlier, we ended the second blog post by generating a new update. An update (or a system snapshot) is a commit into OSTree repository. By default, qt-ostree stores this repository in WORKDIR/ostree-repo/. For local testing you can pass --start-trivial-httpd to qt-ostree. This starts a simple HTTP server which is accessible on the local host at the address specified in the WORKDIR/httpd/httpd-address file. In a real world scenario you would want to export this repository on a production server. This is as simple as copying the contents of the WORKDIR/ostree-repo/ directory to a dedicated path on the server.

The --start-trivial-http does not have support for HTTPS so I have configured my own Apache web server. This server requires TLS client side authentication. A URL to the OSTree repository in my case is https://www.b2qtupdate.com/ostree-repo. Because the configured web server resides on my development machine, the ostree-repo/ directory from the URL is conveniently a symlink to WORKDIR/ostree-repo/. Whenever I generate a new system snapshot, it is immediately available on https://www.b2qtupdate.com/ostree-repo. The next step is to point client devices to this address.

Configuring Devices.

Extending on the demo from the previous blog post, we need to add a configuration that describes how to access the server:

OtaRepositoryConfig {
    id: secureConfig
    gpgVerify: true
    url: "https://www.b2qtupdate.com/ostree-repo"
    tlsClientCertPath: "/usr/share/ostree/certs/clientcert.pem"
    tlsClientKeyPath: "/usr/share/ostree/certs/clientkey.pem"
    tlsPermissive: false
    tlsCaPath: "/usr/share/ostree/certs/servercert.pem"
}

Here we are pointing the client device to the URL where we exported the generated OSTree repository. This configuration requires the update to be signed by a known GPG key. We also provide paths to the certificate files (on the device) which are used for client and server TLS authentication. A keyring with the trusted keys and certificate pinning should be done when creating the initial image (during the device integration step). The current configuration can be updated by calling:

OtaClient.setRepositoryConfig(OtaRepositoryConfig config)

The subsequent calls to the server (for example, fetching metadata about the remote snapshot) will use this updated configuration.

An alternative configuration could use unencrypted HTTP and look as follows:

OtaRepositoryConfig {
    id: basicConfig
    url: "http://www.b2qtupdate.com/ostree-repo"
}

If we exported the repository to scheme://host:port/my-product/system-updates/, we would point devices to that URL instead. The complete demo application is available here.

OSTree Adoption.

System updates are an everlasting area of interest. Just look at the talks dedicated to this topic on the Embedded Linux Conference this year (and the years before). OSTree was amongst the presented alternatives, receiving great feedback due to its outstanding approach. OSTree originated as a research venture in high speed continuous delivery and testing infrastructure for GNOME. It has been a well-received technology with expanding adoption in the Linux ecosystem. OSTree is being used at the core of new Linux distributions – Project Atomic, Endless OS, Papyros. Automotive Grade Linux is researching OSTree integration for the AGL reference platform. Flatpak (a framework for distributing Linux applications) is another interesting project that uses OSTree to distribute and manage applications and runtimes. As we can see, OSTree is hot technology, being adopted by a variety of projects on desktop, servers and embedded systems.

Want to have a robust and modern update system on your devices as well? The Qt OTA Update 1.0 module brings full OSTree support with convenient Qt APIs to Qt 5.8 for Device Creation.

Conclusion.

This concludes the series of the blog posts introducing the Qt OTA Update module. Try it yourself with Qt for Device Creation and let us know what you think. Feedback and feature requests are always welcome and appreciated.

The post Over-the-Air Updates, Part 3: Repository Configuration and Handling appeared first on Qt Blog.

Cutelyst 1.0.0 with stable API/ABI is out!

Cutelyst the Qt web framework just reached it's first stable release, it's been 3 years since the first commit and I can say it finally got to a shape where I think I'm able to keep it's API/ABI stable. The idea is to have any break into a 2.0 release by the end of next year although I don't expect many changes as the I'm quite happy with it's current state.

The biggest change from the last release is the SessionStoreFile class, it initially used QSettings for it's simplicity but it was obvious that it's performance would be far from ideal, so I replaced QSettings with a plain QFile and QDataStream, this produced smaller session files and made the code twice as fast, but profiling was showing it was still slow because it was writing to disk multiple times on the same request. So the code was changed to merge the changes and only save to disk when the Context get's destroyed, on my machine the performance went from 3,5k to 8.5k on read and writes and 4k to 12k on reads, this is on the same session id, should probably be faster with different ids. This is also very limited by the disk IO as we use a QLockFile to avoid concurrency, so if you need something faster you can subclass SessionStore and use Sql or Redis...

Besides that the TechEmpower 13th preview rounds showed a segfault in the new Cutelyst WSGI in threaded mode, a very hard to reproduce but with an easy fix. The initial fix made the code a bit ugly so I searched to see if XCode clang got an update on thread_local feature and finally, XCode 8 has support for it, if you are using XCode clang now you need version 8.

Many other small bugs also got in and API from 0.13.0 is probably unchanged.

Now if you are a distro packager please :D package it, or if you are a dev and was afraid of API breaks keep calm and have fun!

Download: https://github.com/cutelyst/cutelyst/archive/r1.0.0.tar.gz

Qt on the NVIDIA Jetson TX1 – Device Creation Style

NVIDIA’s Jetson line of development platforms is not new to Qt; a while ago we already talked about how to utilize OpenGL and CUDA in Qt applications on the Jetson TK1. Since then, most of Qt’s focus has been on the bigger brothers, namely the automotive-oriented DRIVE CX and PX systems. However, this does not mean that the more affordable and publicly available Jetson TX1 devkits are left behind. In this post we are going to take a look how to get started with the latest Qt versions in a proper embedded device creation manner, using cross-compilation and remote deployment for both Qt itself and applications.

jetson

The photo above shows our TX1 development board (with a DRIVE CX sitting next to it), hooked up to a 13″ touch-capable display. We are going to use the best-supported, Ubuntu 16.04-based sample root filesystem from Linux for Tegra R24.2, albeit in a bit different manner than what is shown here: instead of going for the default approach based on OpenGL + GLX via the xcb platform plugin, we will instead set up Qt for OpenGL ES + EGL via the eglfs. Our applications will still run on X11, but in fullscreen. Instead of building or developing anything on the device itself, we will follow the standard embedded practice of developing and cross-compiling on a Linux-based host PC.

Why this approach?

  • Fast. While building on target is fully feasible with all the power the TX1 packs, it is still no match for compiling on a desktop machine.
  • By building Qt ourselves we can test the latest version, or even unreleased snapshots from git, not tied to the out-of-date version provided by the distro (5.5).
  • This way the graphics and input device configuration is under control: we are after EGL and GLES, with apps running in fullscreen (good for vsync, see below) and launched remotely, not a desktop-ish, X11-oriented build. We can also exercise the usual embedded input stack for touch/mouse/keyboard/tablet devices, either via Qt’s own evdev code, or libinput.
  • While we are working with X11 for now, the custom builds will allow using other windowing system approaches in the future, once they become available (Wayland, or just DRM+EGLDevice/EGLOutput/EGLStream).
  • Unwanted Qt modules can be skipped: in fact in the below instructions only qtbase, qtdeclarative and qtgraphicaleffects get built.
  • Additionally, with the approach of fine-grained configurability provided by the Qt Lite project, even the must-have modules can be tuned to include only the features that are actually in use.

Setting Up the Toolchain

We will use L4T R24.2, which features a proper 64-bit userspace.

After downloading Tegra210_Linux_R24.2.0_aarch64.tbz2 and Tegra_Linux_Sample-Root-Filesystem_R24.2.0_aarch64.tbz2, follow the instructions to extract, prepare and flash the device.

Verify that the device boots and the X11 desktop with Unity is functional. Additionally, it is strongly recommended to set up the serial console, as shown here. If there is no output on the connected display, which happened sometimes with our test display as well, it could well be an issue with the HDMI EDID queries: if running get-edid on the console shows no results, this is likely the case. Try disconnecting and reconnecting the display while the board is running.

Once the device is ready, we need a toolchain. For instance, get gcc-linaro-5.3.1-2016.05-x86_64_aarch64-linux-gnu.tar.xz from Linaro (no need for the runtime or sysroot packages now).

Now, how do we add more development files into our sysroot? The default system provided by the sample root file system in Linux_for_Tegra/rootfs is a good start, but is not sufficient. On the device, it is easy to install headers and libraries using apt-get. With cross-compilation however, we have to sync them back to the host as well.

First, let’s install some basic dependencies on the device:

sudo apt-get install '.*libxcb.*' libxrender-dev libxi-dev libfontconfig1-dev libudev-dev

Then, a simple option is to use rsync: after installing new -dev packages on the target device, we can just switch to rootfs/usr on the host PC and run the following (replacing the IP address as appropriate):

sudo rsync -e ssh -avz ubuntu@10.9.70.50:/usr/include .
sudo rsync -e ssh -avz ubuntu@10.9.70.50:/usr/lib .

Almost there. There is one more issue: some symbolic links in rootfs/usr/lib/aarch64-linux-gnu are absolute, which is fine when deploying the rootfs onto the device, but pretty bad when using the same tree as the sysroot for cross-compilation. Fix this by running a simple script, for instance this one. This will have to be done every time new libraries are pulled from the target.

Graphics Considerations

By default Qt gets configured for GLX and OpenGL (supporting up to version 4.5 contexts). For EGL and OpenGL ES (up to version 3.2) we need some additional steps first:

The headers are missing by default. Normally we would install packages like libegl1-mesa-dev, however it is likely safer to avoid this and not risk pulling in the Mesa graphics stack, potentially overwriting the NVIDIA proprietary binaries. Run something like the following on the device:

apt-get download libgles2-mesa-dev libegl1-mesa-dev
ar x ...
tar xf data.tar.xz (do this for both)
sudo cp -r EGL GLES2 GLES3 KHR /usr/include

then rsync usr/include back into the sysroot on the host.

Library-wise we are mostly good, except one symlink. Do this on the device in /usr/lib/aarch64-linux-gnu:

sudo ln -s /usr/lib/aarch64-linux-gnu/tegra-egl/libGLESv2.so.2 libGLESv2.so

then sync the libraries back as usual.

Qt can now be configured with -opengl es2. (don’t be misled by “es2”, OpenGL ES 3.0, 3.1 and 3.2 will all be available as well; Qt applications will get version 3.2 contexts automatically due to the backwards compatible nature of OpenGL ES)

Configuring and Building Qt

Assuming our working directory for L4T and the toolchain is $HOME/tx1, check out qtbase into $HOME/tx1/qtbase (e.g. run git clone git://code.qt.io/qt/qtbase.git -b dev – using the dev branch, i.e. what will become Qt 5.9, is highly recommended for now because the TX1 device spec is only present there) and run the following:

./configure
-device linux-jetson-tx1-g++
-device-option CROSS_COMPILE=$HOME/tx1/gcc-linaro-5.3.1-2016.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-
-sysroot $HOME/tx1/Linux_for_Tegra/rootfs
-nomake examples
-nomake tests
-prefix /usr/local/qt5
-extprefix $HOME/tx1/qt5
-hostprefix $HOME/tx1/qt5-host
-opengl es2

Note the dash at the end of the CROSS_COMPILE device option. It is a prefix (for aarch64-linux-gnu-gcc and others) so the dash is necessary.

This will be a release build. Add -force-debug-info if debug symbols are needed. Switching to full debug builds is also possible by specifying -debug.

Check the output of configure carefully, paying extra attention to the graphics bits. Below is an extract with an ideal setup:

Qt Gui:
  FreeType ............................... yes
    Using system FreeType ................ yes
  HarfBuzz ............................... yes
    Using system HarfBuzz ................ no
  Fontconfig ............................. yes
  Image formats:
    GIF .................................. yes
    ICO .................................. yes
    JPEG ................................. yes
      Using system libjpeg ............... no
    PNG .................................. yes
      Using system libpng ................ yes
  OpenGL:
    EGL .................................. yes
    Desktop OpenGL ....................... no
    OpenGL ES 2.0 ........................ yes
    OpenGL ES 3.0 ........................ yes
    OpenGL ES 3.1 ........................ yes
  Session Management ..................... yes
Features used by QPA backends:
  evdev .................................. yes
  libinput ............................... no
  mtdev .................................. no
  tslib .................................. no
  xkbcommon-evdev ........................ no
QPA backends:
  DirectFB ............................... no
  EGLFS .................................. yes
  EGLFS details:
    EGLFS i.Mx6 .......................... no
    EGLFS i.Mx6 Wayland .................. no
    EGLFS EGLDevice ...................... yes
    EGLFS GBM ............................ no
    EGLFS Mali ........................... no
    EGLFS Rasberry Pi .................... no
    EGL on X11 ........................... yes
  LinuxFB ................................ yes
  Mir client ............................. no
  X11:
    Using system provided XCB libraries .. yes
    EGL on X11 ........................... yes
    Xinput2 .............................. yes
    XCB XKB .............................. yes
    XLib ................................. yes
    Xrender .............................. yes
    XCB render ........................... yes
    XCB GLX .............................. yes
    XCB Xlib ............................. yes
    Using system-provided xkbcommon ...... no
Qt Widgets:
  GTK+ ................................... no
  Styles ................................. Fusion Windows

We will rely on EGLFS and EGL on X11 so make sure these are enabled. Having the other X11-related features enabled will not hurt either, a fully functional xcb platform plugin can come handy later on.

Now build Qt and install into $HOME/tx1/qt5. This is the directory we will sync to the device later under /usr/local/qt5 (which has to match -prefix). The host tools (i.e. the x86-64 builds of qmake, moc, etc.) are installed into $HOME/tx1/qt5-host. These are the tools we are going to use to build applications and other Qt modules.

make -j8
make install

On the device, create /usr/local/qt5:

mkdir /usr/local/qt5
sudo chown ubuntu:ubuntu qt5

Now synchronize:

rsync -e ssh -avz qt5 ubuntu@10.9.70.50:/usr/local

Building Applications and other Qt Modules

To build applications, use the host tools installed to $HOME/tx1/qt5-host. For example, go to qtbase/examples/opengl/qopenglwidget and run $HOME/tx1/qt5-host/bin/qmake, followed by make. The resulting aarch64 binary can now be deployed to the device, via scp for instance: scp qopenglwidget ubuntu@10.9.70.52:/home/ubuntu

The process is same for additional Qt modules. For example, to get Qt Quick up and running, check out qtdeclarative (git clone git://code.qt.io/qt/qtdeclarative.git -b dev) and do qmake && make -j8 && make install. Then rsync $HOME/tx1/qt5 like we did earlier. Repeat the same for qtgraphicaleffects, this will be needed by the Cinematic Experience demo later on.

Running Applications

We are almost ready to launch an application manually on the device, to verify that the Qt build is functional. There is one last roadblock when using an example from the Qt source tree (like qopenglwidget): these binaries will not have rpath set and there is a Qt 5.5.1 installation on the device, right there in /usr/lib/aarch64-linux-gnu. By running ldd on our application (qopenglwidget) it becomes obvious that it would pick that Qt version up by default. There are two options: the easy, temporary solution is to set LD_LIBRARY_PATH to /usr/local/qt5/lib. The other one is to make sure no Qt-dependent processes are running, and then wipe the system Qt. Let’s choose the former, though, since the issue will not be present for any ordinary application as those will have rpath pointing to /usr/local/qt5/lib.

The default platform plugin is eglfs, with the eglfs_x11 backend, which does not do more than opening a fullscreen window. This is good enough for most purposes, and also eliminates one common source of confusion: the lack of vsync for non-fullscreen windows. In the default X11-based system there is apparently no vertical synchronization for OpenGL content, unless the window is fullscreen. This is the same behavior like with the Jetson TK1. Running the qopenglwidget example in a regular window will result in an unthrottled rendering rate of 500-600 FPS. Changing to showFullScreen() triggers the expected behavior, the application gets throttled to 60 FPS. Qt Quick is problematic in particular, because the default and best, threaded render loop will result in bad animation timing if vsync-based throttling is not active. This could be worked around by switching to the less smooth basic render loop, but the good news is that with eglfs the problem will not exist in the first place.

Input is handled via evdev, skipping X11. The device nodes may need additional permissions: sudo chmod a+rwx /dev/input/event* (or set up a udev rule). To debug the input devices on application startup, do export QT_LOGGING_RULES=qt.qpa.input=true. If needed, disable devices (e.g. the mouse, in order to prevent two cursors) from X11 via the xinput tool (xinput list, find the device, find the enabled property with xinput list-props, then change it to 0 via xinput set-prop).

And the end result:

qopenglwidget_tx1
qopenglwidget, a mixed QWidget + QPainter via OpenGL + custom OpenGL application

cinematic_tx1
The Qt 5 Cinematic Experience demo (sources available on GitHub) for Qt Quick, with fully functional touch input

Qt Creator

Building and deploying applications manually from the terminal is nice, but not always the most productive approach. What about Qt Creator?

Let’s open Qt Creator 4.1 and the Build & Run page in Options. At minimum, we have to teach Creator where our cross-compiler and Qt build can be found, and associate these with a kit.

Go to Compilers, hit Add, choose GCC. Change the Name to something more descriptive. The Compiler path is the g++ executable in our Linaro toolchain. Leave ABI unchanged. Hit Apply.

tx1_creator1

Now go to Qt Versions, hit Add. Select qmake from qt5-host/bin. Hit Apply.

tx1_creator2

Go to Kits, hit Add. Change the Name. Change the Device type to Generic Linux Device. Change Sysroot to Linux_for_Tegra/rootfs. Change the Compiler to the new GCC entry we just created. Change Qt version to the Qt Versions entry we just created. Hit Apply.

tx1_creator3

That is the basic setup. If gdb is wanted, it has to be set up under Debuggers and Kits, similarly to the Compiler.

Now go to the Devices page in Options. Hit Add. Choose Generic Linux Device and start the wizard. Enter the IP address and ubuntu/ubuntu as username and password. Hit Next and Finish. The testing should succeed. There is no need to associate this Device with the Kit if there is only one Generic Linux Device, but it may become necessary once there are multiple devices configured.

tx1_creator4

Building and Deploying from Qt Creator

Let’s check out the Cinematic Experience demo sources: git clone https://github.com/alpqr/qt5-cinematic-experience.git. In the Configure Project page, select only the kit just created. The configuration is Release since our Qt build was release only. Hit Configure Project. When creating a new project, the approach is the same: make sure the correct kit is selected.

Build the project. Creator will now correctly pick up the cross-compilation toolchain. The result is an ARM binary on our host PC. Let’s deploy and run it.

Choose Deploy. This will likely fail, watch the output in the Compile Output tab (Alt+4). This is because the installation settings are not yet specified in the .pro file. Check this under Run settings on the Projects page. The list in “Files to deploy” is likely empty. To fix this, edit qt5-cinematic-experience.pro and add the following lines at the end:

target.path = /home/ubuntu/qt/$$TARGET
INSTALLS += target

After this, our deployment settings will look a lot better:
tx1_creator7

Choose Run (or just hit Ctrl+R). Creator now uploads the application binary to the device and launches the application remotely. If necessary, the process can also be killed remotely by hitting the Stop button.

tx1_remote
The host and the target

This means that from now on, when doing further changes or developing new applications, the changes can be tested on the device right away, with just a single click.

What’s Next

That’s all for now. There are other interesting areas, multimedia (accelerated video, camera), CUDA, and Vulkan in particular, which unfortunately do not fit in this single post but may get explored in the future. Another future topic is Yocto support and possibly a reference image in the Qt for Device Creation offering. Let us know what you think.

The post Qt on the NVIDIA Jetson TX1 – Device Creation Style appeared first on Qt Blog.

Qt 5.8 Beta Released

I am pleased to announce that Qt 5.8 Beta is now released. Containing all-new configuration system, new graphics architecture with integrated Qt Quick 2D Renderer for devices without OpenGL, build in QML cache for improved startup and many other new features, Qt 5.8 will be a very interesting release. I hope many will take the Qt 5.8 Beta release, test it and provide feedback for us to complete Qt 5.8. For the big picture of the release, see the alpha release blog post.

We have prepared convenient binary installers for the Qt 5.8 Beta, so it is easy to download, test and provide feedback. For any issues you may find with the Beta, please submit a detailed bug report to bugreports.qt.io (after checking the known issues). You are also welcome to join the discussions in the Qt Project mailing lists, developer forums and of course to contribute to Qt.

To try out the new features you can download Qt 5.8 Beta from your Qt Account or from download.qt.io.

The post Qt 5.8 Beta Released appeared first on Qt Blog.

Qt World Summit 2016 Webinar Series Kicks Off

November Qt World Summit Webinars

This month, be sure to catch our upcoming online events and register now:

Qt Quick Scene Graph Advancements in Qt 5.8 and Beyond
presented by Laszlo Agocs, Senior Software Engineer, Qt R&D

The Curse of Choice: An overview of GUI technologies in Qt?
presented by Andy Nichols, Senior Software Engineer, Qt R&D

Qt & IoT: Do they fit together?
presented by Alex Blasche, Senior Software Engineer, Qt R&D

Stay tuned for details on upcoming webinars for December!

All upcoming events from The Qt Company and its partners are available in our new community calendar at www.qt.io/events.

The post Qt World Summit 2016 Webinar Series Kicks Off appeared first on Qt Blog.

CppCon Special Report

KDAB has long supported the C++ community, as C++ is the backbone of Qt and up-to-date knowledge of its changes keeps us on the leading edge in the Qt world.

Later this year we shall be supporting Europe’s Meeting C++ in Berlin, but now that this year’s talks have been released we felt it was time for a Special Report on CppCon which ran from September 17th-23rd this autumn in Bellevue, WA.

KDAB’s Kévin Ottens was on the program committee and reviewed the talks at this year’s show, while Giuseppe D’Angelo (Peppe) contributed a day’s training on Programming with Qt Widgets, and two Lightning Talks on Qt (see them here and here), as well as attending the rest of the event.

We asked Kévin and Peppe to list their top three talks so we could get the insider as well as the attendee perspective. This is what they gave us:

Kévin’s top three

1. C++ on the Web: Let’s have some serious fun (Video)

  • “Shows that C++ is very versatile and can be used even in the trendy web field unlike what most engineers assume.”

2. Iterator Haiku, Casey Carter (Video)

  • “Because iterators in general reduce opportunities of errors in your code, and it will become even better with the ranges.”

3. How to test static_assert? (Video)

  • “I love static_assert to catch mistakes and wrong assumptions even earlier in the development process, but I also want my code to be tested as much as possible. As the title implies, it’s a perfect match.”

Peppe’s top three

1. Lifetime Safety… By Default: Making Code Leak-Free by Construction (Video)

  • “It was the keynote by Herb Sutter. Great speaker and great content.”

2. What C++ Programmers Need to Know about Header <random> (Video)

  • “Because everyone has a program that needs a random integer between 1 and 42 and does it wrong. <random> does it right.”

3. My Little Optimizer: Undefined Behavior is Magic (Video)

  • “In case you were looking for arguments why you should never ever ever ever trigger undefined behavior: compilers see your bluffs and do terrible things.”

You can see Giuseppe’s blog post about CppCon here.

The post CppCon Special Report appeared first on KDAB.

Qt Creator 4.2 Beta released

We are happy to announce the release of Qt Creator 4.2 Beta.

Qt SCXML Editor

Flat Dark Theme - Qt Creator 4.1

Qt SCXML is a new module in Qt that allows you to create state machines from State Chart XML and embed them into Qt C++ and Qt Quick applications (Overview). It was released as Technical Preview in Qt 5.7 and will be released fully supported with Qt 5.8.

Qt Creator 4.2 now supplements the module by offering a graphical editor for SCXML (experimental). It features editing states and sub-states, transitions, events, and all kinds of properties. The editor is experimental and the plugin is not loaded by default. Turn it on in Help > About Plugins (Qt Creator > About Plugins on macOS) to try it.

Projects Mode

We reworked how you select the project and it’s diverse settings in Projects mode. Instead of nested tabs, you now select the project from a dropdown, and the settings that you want to edit from a tree that shows all available kits and other categories, making for a much cleaner UI. Enabling use of a kit for a project is now easily done by clicking the entry in the tree. Please provide feedback on any remaining issues through our bug tracker.

Qt Quick Designer

Qt Quick Designer has received many smaller features in this release. In the connections editor there is a new section for managing the imports and property definitions that are necessary for using C++ backend objects (documentation). Also support for padding (Qt Quick 2.6) was added, and you can now edit the when condition of states, and the diverse font properties of text items.

Other Additions and Improvements

When profiling your QML code you now have the option to show memory usage and allocations as flame graphs as well.

We added Tools > Diff > Diff Current File and Diff Open Files for showing a local diff of the modifications of files in Qt Creator with respect to their versions on disk.

Performance of opening CMake projects was improved, and support for predefined options for properties was added.

There were many more changes, which are described in more detail in our change log.

Get Qt Creator 4.2 Beta

The opensource version is available on the Qt download page, and you find commercially licensed packages on the Qt Account Portal. Please post issues in our bug tracker. You can also find us on IRC on #qt-creator on chat.freenode.net, and on the Qt Creator mailing list.

The post Qt Creator 4.2 Beta released appeared first on Qt Blog.

Tuple And Pair in C++ APIs?

Quick: When you design C++ APIs, when and how should you use pair and tuple?

The answer is as simple as it is surprising: Never. Ever.

When we design APIs, we naturally strive for qualities such as readability, ease-of-use, and discoverability. Some C++ types are enablers in this regard: std::optional, std::variant, std::string_view/gsl::string_span, and, of course, std::unique_ptr. They help you design good interfaces by providing what we call vocabulary types. These types may be trivial to implement, but, just like STL algorithms, they provide a higher level of abstraction (a vocabulary) in which to reason about code. Unlike algorithms, though, which appear mostly in the implementation, and don’t affect APIs much, vocabulary types are at their best when used in APIs.

So, I asked myself, are std::pair and std::tuple vocabulary types?

Vocabulary Types

To answer the question, I looked at what these types help model. This should be trivial to answer for vocabulary types, much as it’s trivial to remember what an STL algorithm does just by looking at the name.

Take std::optional, for example. It models a value that may be absent, i.e. an optional value. This is great. When you start looking for uses, you can’t help but see lots of opportunities just jumping out at you: std::optional is the perfect value type for hash tables that use open addressing. The atoi() return value could finally distinguish between a zero and an error:

if (auto result = atoi(str))
    std::cout << "got " << *result << std::endl;
else
    std::cout << "failed to parse \"" << str << "\" as an integer: " << "???" << std::endl;

But what if you want to return an error code, or a human-readable error description? Then std::optional is not the prime choice. There should never be an error and a valid parsed value returned from the same invocation of atoi(), so something like std::variant seems perfect.

But is it?

Consider:

auto result = atoi(str);
if (auto i = std::get_if<int>(&result))
    std::cout << "got " << i << std::endl;
else if (auto error = std::get_if<std::error_code>(&result)))
    std::cout << "failed to parse \"" << str << "\" as an integer: " << error.message() << std::endl;
else
    std::cout << "oops, variant was in invalid state" << std::endl;

Some people may call this good API, I call it horrible. If you force your users to query the result with a chain of get_ifs, then you are abusing std::variant, which is designed to contain alternative types with similar purpose, so that it can be efficiently handled using a static visitor. You could use a visitor to handle the result of atoi(), but is that really an API you’d want to work with?

A New Vocabulary Type

Put yourself into the position of the users of your API. What they want is a std::optional where the option is not between presence and absence of a value, but between a value and an error code. So, give it to them:

template <typename T>
class value_or_error {
    std::variant<T, std::error_code> m_v; // space-saving impl detail
public:
    explicit value_or_error(std::error_code e)
        : m_v(std::move(e)) {}
    explicit value_or_error(T t)
        : m_v(std::move(t)) {}

    std::error_code error() const {
        if (auto e = std::get_if<std::error_code>(&m_v))
            return *e;
        else
            return std::error_code();
    }

    T& operator *() { return std::get<0>(m_v); }
    T const& operator *() const { return std::get<0>(m_v); }

    explicit operator bool() const { return !error(); }
    bool operator !() const { return error(); } 
};

Usage:

if (auto result = atoi(str))
    std::cout << "got " << *result << std::endl;
else
    std::cout << "failed to parse \"" << str << "\" as an integer: " << result.error().message() << std::endl;

There, we just created a possible new vocabulary type.

But ok, I digress. Back to std::pair and std::tuple. What do they model?

As best as I can put it, a std::pair models a pair of two values, and std::tuple models a … tuple of zero to (insert your implementation limit here) values. Sounds simple, but what does that actually mean? Since std::pair is a subset of std::tuple, let’s restrict ourselves to just tuples.

We have a language construct, inherited from C (boo!), that allows us to package a pair or a triple or … of values into one object: it’s called struct. It doesn’t even have a limit on the arity of the object. Surprise!

Pair Models … Struct, Tuple Models … Struct

So, what’s the advantage of a tuple over a struct?

I have no idea! But I guess the answer is “none”.

Ok, so what’s the advantage of a struct over a tuple?

Where should I begin?

First, you get to choose names for the values. The std::set::insert() function could be as easy to use as

template <typename Iterator>
struct insert_result {
    Iterator iterator;
    bool inserted;
};
auto result = set.insert(obj);
if (!result.inserted)
    *result.iterator = obj;

Sadly, what we got is std::pair:

auto result = set.insert(obj);
if (!result.second) // or was it .first?! - I can never remember...
    *result.first = obj;

Second, you can enforce invariants amongst the data members by making them private and mediating access via member functions, as we did in the value_or_error example, where accessing the value when an error was set would throw an exception.

Third, you can add (convenience) methods to the struct, possibly making it a reusable component in its own right:

template <typename Iterator>
struct equal_range_result {
    Iterator first;
    Iterator last;

    friend auto begin(const equal_range_result &r) { return r.first; } 
    friend auto end(const equal_range_result &r) { return r.last; } 
};
for (auto && [key, value] : map.equal_range(obj))
   // ...

None of this is possible if you use std::pair or std::tuple in your APIs.

Variadic Woes

There’s just one problem with structs: they cannot be variadic (yet), and that’s when using tuples as API is somewhat acceptable, because we have nothing else at the moment. But there’s hardly a handful of such cases in the standard library, and most deal with implementing std::tuple in the first place (std::tie(), std::make_tuple(), std::forward_as_tuple(), …). About the only example that’s not in <tuple> is the zip() function that’s being discussed:

auto v1 = ...;
//...
auto vN = ...;
for (auto &&e : zip(v1, ..., vN))
   // ...

And you need Structured Bindings to make that acceptable:

for (auto && [e1, ..., eN] : zip(v1, ..., vN))
   // ...

Conclusion

I hope I could convince you that using std::pair and std::tuple in APIs is a bad idea. Or, to say it in the style of Sean Parent: “No raw tuples.”

Defining a small class or struct is almost always the superior alternative. C++ currently lacks just one feature that would all but obsolete tuples: a way to define variadic structs. Maybe the static reflection work will yield that mechanism, maybe we need a different mechanism.

In any case, if you are not in that 0.01% of cases where you need variadic return values, then there’s already no reason to continue using tuples and pairs in APIs.

Since we’re a Qt shop, too, I’ll leave you with an example of how even Qt, which somewhat rightfully prides itself for its API design, can get this wrong:

// Qt 5:
typedef QPair<qreal, QColor> QGradientStop;
// Qt 6 (hopefully):
struct QGradientStop {
   qreal location;
   QColor colour;
};

About KDAB

KDAB is a consulting company offering a wide variety of expert services in Qt, C++ and 3D/OpenGL and providing training courses in:

KDAB believes that it is critical for our business to contribute to the Qt framework and C++ thinking, to keep pushing these technologies forward to ensure they remain competitive.

The post Tuple And Pair in C++ APIs? appeared first on KDAB.