### Main Application with Global Proxy Setup Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-netproxy.html An example of a main function that sets a global proxy and then quits after a delay. This demonstrates how to integrate the NetProxy setup within a QCoreApplication event loop. ```c++ #include #include #include int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // Set the global proxy setGlobalProxy(QUrl("https://jolla.com")); // Wait for a bit and then quit QTimer::singleShot(5000, [&app] { app.quit(); }); return app.exec(); } ``` -------------------------------- ### Retrieve and Print Installed Applications Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-applications.html Example demonstrating how to instantiate the Applications class and iterate through installed application entries to print their names and associated package information. ```cpp #include void printApplications() { QList apps = Sailfish::Mdm::Applications().getInstalledApplications(); foreach (const Sailfish::Mdm::ApplicationEntry &entry, apps) { Sailfish::Mdm::PackageEntry package = entry.package(); qInfo() << "Application name:" << entry.name(); qInfo() << "From package:" << (package.name().isEmpty() ? QStringLiteral("(none)") : QString("%1-%2").arg(package.name()).arg(package.version())); qInfo() << QStringLiteral("--------"); } } ``` -------------------------------- ### Example Usage Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-applications.html Demonstrates how to use the Applications class to retrieve and display installed application information. ```APIDOC ### Example of usage: ```cpp #include void printApplications() { Sailfish::Mdm::Applications apps; QList installedApps = apps.getInstalledApplications(); foreach (const Sailfish::Mdm::ApplicationEntry &entry, installedApps) { Sailfish::Mdm::PackageEntry package = entry.package(); qInfo() << "Application name:" << entry.name(); qInfo() << "From package:" << (package.name().isEmpty() ? QStringLiteral("(none)") : QString("%1-%2").arg(package.name()).arg(package.version())); qInfo() << QStringLiteral("--------"); } } ``` ``` -------------------------------- ### Basic Sailfish Application Structure Source: https://sailfishos.org/develop/docs/libsailfishapp/sailfishapp.html This example demonstrates the fundamental structure for a Sailfish OS application using libsailfishapp. It initializes the application, creates a QQuickView, sets the main QML file, displays the view, and starts the application's event loop. Ensure you have the necessary build requirements and project configurations set up. ```cpp #include #include #include int main(int argc, char *argv[]) { QScopedPointer app(SailfishApp::application(argc, argv)); QScopedPointer view(SailfishApp::createView()); view->setSource(SailfishApp::pathTo(QString("qml/main.qml"))); view->show(); return app->exec(); } ``` -------------------------------- ### Setting Global Proxy Example Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-netproxy.html Example demonstrating how to set a global proxy using the NetProxy class. ```APIDOC ## Setting Global Proxy ### Usage ```cpp #include void setGlobalProxy(const QUrl &server) { auto proxy = new Sailfish::Mdm::NetProxy(nullptr); QObject::connect(proxy, &Sailfish::Mdm::NetProxy::validChanged, [proxy, server] { QString identifier = "global"; bool found = proxy->selectProxy(identifier); if (found) { proxy->setType(Sailfish::Mdm::NetProxy::ProxyType::Manual); proxy->setManualProxies(QList({server})); proxy->setManualExclusions(QStringList()); } }); } ``` ### Main Function Example This example shows how to integrate the `setGlobalProxy` function into a Qt application. ```cpp #include #include #include // Assume setGlobalProxy function is defined as above void setGlobalProxy(const QUrl &server); int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); // Set the global proxy setGlobalProxy(QUrl("https://jolla.com")); // Wait for a bit and then quit QTimer::singleShot(5000, [&app] { app.quit(); }); return app.exec(); } ``` ``` -------------------------------- ### MultiVideoPickerDialog Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-multivideopickerdialog.html Example demonstrating how to use MultiVideoPickerDialog to select multiple video files. It shows how to handle accepted and rejected selections, and how to process the selected file URLs. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { property string selectedFiles SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Multi video picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Select videos" value: selectedFiles ? selectedFiles : "None" onClicked: pageStack.push(multiVideoPickerDialog) } } } Component { id: multiVideoPickerDialog MultiVideoPickerDialog { onAccepted: { selectedFiles = "" var urls = [] for (var i = 0; i < selectedContent.count; ++i) { var url = selectedContent.get(i).url // Handle selection urls.push(selectedContent.get(i).url) } selectedFiles = urls.join(", ") } onRejected: selectedFiles = "" } } } } } ``` -------------------------------- ### Usage Example Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-notificationinfo.html An example demonstrating how to create and publish a notification using the NotificationInfo class. ```APIDOC ### Request Example ```cpp #include void publishNotification(QObject *parent) { QVariantMap defaultAction; defaultAction.insert("name", "default"); defaultAction.insert("displayName", "Do It!"); defaultAction.insert("icon", "icon-s-do-it"); defaultAction.insert("service", "org.sailfishos.example"); defaultAction.insert("path", "/example"); defaultAction.insert("iface", "org.sailfishos.example"); defaultAction.insert("method", "doIt"); defaultAction.insert("arguments", QVariantList() << "argument" << 2); QVariantList remoteActions; remoteActions << defaultAction; Sailfish::Mdm::NotificationData data; data.itemCount = 5; data.category = "x-nemo.example"; data.appName = "Example App"; data.appIcon = "/usr/share/example-app/icon-l-application"; data.summary = "Notification summary"; data.body = "This is the body of an example notification"; data.previewSummary = "Notification preview summary"; data.previewBody = "This is the preview body"; data.timestamp = QDateTime::currentDateTime(); data.remoteActions = remoteActions; Sailfish::Mdm::NotificationInfo *info = new Sailfish::Mdm::NotificationInfo(parent); quint32 id = info->createNotification(data); info->deleteLater(); qInfo() << "Created notification with id:" << id; } ``` ### Response Example ```json { "notificationId": 12345 // Example ID of the created notification } ``` ``` -------------------------------- ### MultiDownloadPickerDialog Usage Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-multidownloadpickerdialog.html Example demonstrating how to use the MultiDownloadPickerDialog to select and handle multiple downloaded files. ```APIDOC ## MultiDownloadPickerDialog QML Type ### Description A download picker for selecting multiple downloaded files. ### Import Statement ``` import Sailfish.Pickers 1.0 ``` ### Request Example ```javascript import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { property string selectedFiles SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Multi download picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Upload downloaded files" value: selectedFiles ? selectedFiles : "None" onClicked: pageStack.push(multiDownloadPickerDialog) } } } Component { id: multiDownloadPickerDialog MultiDownloadPickerDialog { onAccepted: { selectedFiles = "" var urls = [] for (var i = 0; i < selectedContent.count; ++i) { var url = selectedContent.get(i).url // Handle url upload urls.push(selectedContent.get(i).url) } selectedFiles = urls.join(", ") } onRejected: selectedFiles = "" } } } } } ``` ### See Also - MultiContentPickerDialog - MultiDocumentPickerDialog - MultiFilePickerDialog - MultiImagePickerDialog - MultiMusicPickerDialog - MultiVideoPickerDialog - DownloadPickerPage (for single file selection) ``` -------------------------------- ### QDateTime Filter::start Documentation Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-callhistory-filter.html Explains the 'start' variable within the Filter class, defining the search start date/time. ```cpp The first date/time to match when searching. The search results will contain calls made between Filter::start and Filter::end (inclusive). ``` -------------------------------- ### MultiImagePickerDialog Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-multiimagepickerdialog.html Example demonstrating how to use the MultiImagePickerDialog to select multiple images. It shows how to trigger the dialog and handle the accepted and rejected events to process selected image URLs. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { property string selectedFiles SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Multi image picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Upload images" value: selectedFiles ? selectedFiles : "None" onClicked: pageStack.push(multiImagePickerDialog) } } } Component { id: multiImagePickerDialog MultiImagePickerDialog { onAccepted: { selectedFiles = "" var urls = [] for (var i = 0; i < selectedContent.count; ++i) { var url = selectedContent.get(i).url // Handle url upload urls.push(selectedContent.get(i).url) } selectedFiles = urls.join(", ") } onRejected: selectedFiles = "" } } } } } ``` -------------------------------- ### Initialize and Use SimSmsFilter Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-simsmsfilter.html Example of initializing SimSmsFilter, connecting to its signals, and adding a text rule. Note that this example quits the application after adding a rule. ```cpp #include int main(int argc, char **argv) { QCoreApplication app(arg, argv); SimSmsFilter *smsFilter = new SimSmsFilter; QObject::connect(smsFilter, &SimSmsFilter::readyChanged, [smsFilter] { qInfo() << smsFilter->textRules().count() << "text rules are currently set"; SimFilter::Rule rule("123456789", SimFilter::Block); smsFilter->addTextRule(rule); QObject::connect(smsFilter, &SimSmsFilter::textRuleAdded, [rule] { qInfo() << "Rule added for IMSI" << rule.imsi; app.quit(); }); }); return app.exec(); } ``` -------------------------------- ### Example: Add Application to Autostart Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-autostart.html Include the header and instantiate the Autostart class to add an application's desktop file to the autostart list. ```cpp #include void example() { Sailfish::Mdm::Autostart autostart; autostart.add("/usr/share/applications/your-favourite-app.desktop"); } ``` -------------------------------- ### GET /certificates/blacklist Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-certificates.html Retrieves a list of all installed certificate blacklist files. ```APIDOC ## GET /certificates/blacklist ### Description Returns a list of all installed certificate blacklist files. Certificates in these files are rejected even if validated by system certificates. ### Method GET ### Endpoint /certificates/blacklist ### Response #### Success Response (200) - **blacklistedFiles** (QList) - A list of all installed certificate blacklist files. ``` -------------------------------- ### main.cpp Example for Custom Popups Source: https://sailfishos.org/develop/docs/sailfish-components-webview/sailfish-webview-custompopups-main-cpp.html This C++ code sets up a basic Qt Quick application. It initializes the Qt GUI application and a QQuickView to display a QML file. Ensure the main.qml file is correctly referenced in the qrc resource file. ```cpp #include #include #include int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQuickView view; view.setSource(QUrl("qrc:/main.qml")); view.show(); return app.exec(); } ``` -------------------------------- ### GET /certificates Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-certificates.html Retrieves a list of all system CA certificates, combining operating system certificates and installed files. ```APIDOC ## GET /certificates ### Description Returns a list of all system CA certificates. This is a combination of the certificates provided by the operating system and those from the installedFiles(). ### Method GET ### Endpoint /certificates ### Response #### Success Response (200) - **certificates** (QList) - A list of all system CA certificates. ``` -------------------------------- ### Provisioner AccountConfiguration Property Example Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-accounts-provisioner.html Demonstrates how to get and set the accountConfiguration property, including modifying global and service-specific settings. ```APIDOC ### Property Documentation #### accountConfiguration : QVariantMap **Access functions:** QVariantMap | **accountConfiguration**() const void | **setAccountConfiguration**(const QVariantMap &_config_) **Notifier signal:** void | **accountConfigurationChanged**() **Example:** ```cpp // Get the current account configuration QVariantMap config = accountProvisioner.accountConfiguration(); // Amend the current global configuration QVariantMap globalConfig = config.value(QString()).toMap(); // global configuration is identified by an empty service name globalConfig.insert(QStringLiteral("created_by_mdm"), true); config.insert(QString(), globalConfig); // Amend the current email configuration QVariantMap emailConfig = config.value(QStringLiteral("email").toMap(); emailConfig.insert(QStringLiteral("signature"), QStringLiteral("Sent by my Sailfish OS device")); config.insert(QStringLiteral("email"), emailConfig); // Update the account configuration accountProvisioner.setAccountConfiguration(config); ``` ``` -------------------------------- ### Implement Application Cover with Color Picker Source: https://sailfishos.org/develop/docs/silica/sailfish-application-features.html This example demonstrates setting up a basic application window with an initial page containing a ColorPicker. The selected color is then displayed in the application's cover when the app is backgrounded. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 ApplicationWindow { id: appWindow property color selectedColor initialPage: Component { Page { ColorPicker { onColorClicked: appWindow.selectedColor = color } } } cover: Component { Cover { Rectangle { anchors.fill: parent color: appWindow.selectedColor } } } } ``` -------------------------------- ### Get Device Variant Information Source: https://sailfishos.org/develop/docs/sailfish-mdm/ssu.html Retrieve the device variant, for example 'sony-nile', using the deviceVariant method. This specifies a particular configuration or revision of the device. ```cpp string deviceVariant() ``` -------------------------------- ### Manage Sideloading Settings Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-securitysettings.html Example demonstrating how to instantiate SecuritySettings and update the sideloading permission state. ```cpp #include void allowOrDisallowSideLoading(bool allow, QObject *parent) { Sailfish::Mdm::SecuritySettings *settings = new Sailfish::Mdm::SecuritySettings(parent); settings->setSideloadingAllowed(allow); } ``` -------------------------------- ### Implement VideoPickerPage Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-videopickerpage.html Example usage showing how to push a VideoPickerPage onto the page stack and handle the selected content properties. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { id: page property string selectedVideo ValueButton { anchors.centerIn: parent label: "Video" value: selectedVideo ? selectedVideo : "None" onClicked: pageStack.push(videoPickerPage) } Component { id: videoPickerPage VideoPickerPage { onSelectedContentPropertiesChanged: { page.selectedVideo = selectedContentProperties.filePath } } } } } } ``` -------------------------------- ### CollectionNamesRequest Methods Source: https://sailfishos.org/develop/docs/sailfish-secrets/sailfish-secrets-collectionnamesrequest.html This section details the methods available for the CollectionNamesRequest class, including setting and getting the storage plugin name, starting requests, and checking status. ```APIDOC ## CollectionNamesRequest::setStoragePluginName ### Description Sets the name of the storage plugin from which the client wishes to retrieve collection names. ### Method `void` ### Parameters #### Path Parameters - **_pluginName_** (QString) - Required - The name of the storage plugin. ### Notes Setter function for property storagePluginName. See also storagePluginName(). ``` ```APIDOC ## CollectionNamesRequest::startRequest ### Description Starts the request to retrieve collection names from the specified storage plugin. ### Method `virtual void` ``` ```APIDOC ## CollectionNamesRequest::status ### Description Returns the status of the request. ### Method `virtual Sailfish::Secrets::Request::Status` ``` ```APIDOC ## CollectionNamesRequest::storagePluginName ### Description Returns the name of the storage plugin from which the client wishes to retrieve collection names. ### Method `QString` ### Notes Getter function for property storagePluginName. See also setStoragePluginName(). ``` ```APIDOC ## CollectionNamesRequest::waitForFinished ### Description Waits until the request is finished. ### Method `virtual void` ``` -------------------------------- ### Call D-Bus Function and Get Return Value Source: https://sailfishos.org/develop/docs/nemo-qml-plugin-dbus/examples.html This example demonstrates calling a D-Bus function and handling its asynchronous return value using a callback. The `typedCall` method is used for this purpose. ```qml import QtQuick 2.0 import Nemo.DBus 2.0 Item { DBusInterface { id: profiled service: 'com.nokia.profiled' iface: 'com.nokia.profiled' path: '/com/nokia/profiled' } Component.onCompleted: { // Call the "get_profile" method without arguments, and // when it returns, call the passed-in callback method profiled.typedCall('get_profile', [], function (result) { // This will be called when the result is available console.log('Got profile: ' + result); }); } } ``` -------------------------------- ### Implement MultiContentPickerDialog Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-multicontentpickerdialog.html Example demonstrating how to integrate the picker into a page and handle the selection of multiple files. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { property string selectedFiles SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Multi content picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Upload files" value: selectedFiles ? selectedFiles : "None" onClicked: pageStack.push(multiDocumentPickerDialog) } } } Component { id: multiDocumentPickerDialog MultiDocumentPickerDialog { title: "Select files" onAccepted: { selectedFiles = "" var urls = [] for (var i = 0; i < selectedContent.count; ++i) { var url = selectedContent.get(i).url // Handle url upload urls.push(selectedContent.get(i).url) } selectedFiles = urls.join(", ") } onRejected: selectedFiles = "" } } } } } ``` -------------------------------- ### Implement SoftwareUpdate usage Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-softwareupdate.html Example demonstrating how to instantiate the class, connect to signals for update status, and trigger a check for updates. ```cpp #include void installSoftwareUpdate(QObject *parent) { Sailfish::Mdm::SoftwareUpdate *sum = new Sailfish::Mdm::SoftwareUpdate(parent); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateInfoChanged, [sum] { if (sum->softwareUpdateIsAvailable()) { if (!sum->latestAvailableUpdateVersion().isEmpty()) { qInfo() << "OS update available, beginning software update process. Please wait..."; sum->installSoftwareUpdate(); } } else { qInfo() << "OS update not available, not updating."; } }); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateDownloading, [](const QString &version) { qInfo() << "OS update downloading; version:" << version; }); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateDownloadProgress, [](int percent) { qInfo() << "OS update download progress:" << percent << "%"; }); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateDownloaded, [] { qInfo() << "OS update downloaded!"; }); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateInstallationStarted, [] { qInfo() << "OS update installation started!"; }); QObject::connect(sum, &Sailfish::Mdm::SoftwareUpdate::softwareUpdateFailed, [] { qInfo() << "OS update failed!"; }); sum->checkForSoftwareUpdate(); } ``` -------------------------------- ### Delete Collection Example Source: https://sailfishos.org/develop/docs/sailfish-secrets/sailfish-secrets-deletecollectionrequest.html Demonstrates how to create and start a request to delete a collection from secrets storage. Ensure the SecretManager is set and specify the storage plugin, collection name, and user interaction mode. ```cpp Sailfish::Secrets::SecretManager sm; Sailfish::Secrets::DeleteCollectionRequest dcr; dcr.setManager(&sm); dcr.setStoragePluginName(Sailfish::Secrets::SecretManager::DefaultEncryptedStoragePluginName); dcr.setCollectionName(QLatin1String("ExampleCollection")); dcr.setUserInteractionMode(Sailfish::Secrets::SecretManager::SystemInteraction); dcr.startRequest(); // status() will change to Finished when complete ``` -------------------------------- ### FolderPickerDialog Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-folderpickerdialog.html Demonstrates how to use FolderPickerDialog to select a directory. The initial path can be set, and the selected path is captured upon acceptance. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { id: page property string directoryPath SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Folder picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Directory" value: directoryPath ? directoryPath : "None" onClicked: pageStack.push(folderPickerDialog) } } } Component { id: folderPickerDialog FolderPickerDialog { title: "Download to" onAccepted: directoryPath = selectedPath onRejected: directoryPath = "" } } } } } ``` -------------------------------- ### Delete a Secret using DeleteSecretRequest Source: https://sailfishos.org/develop/docs/sailfish-secrets/sailfish-secrets-deletesecretrequest.html Example demonstrating how to delete a secret. Ensure the manager is set, the identifier is specified, and the user interaction mode is configured before starting the request. The status will update upon completion. ```cpp Sailfish::Secrets::SecretManager sm; Sailfish::Secrets::DeleteSecretRequest dsr; dsr.setManager(&sm); dsr.setIdentifier(Sailfish::Secrets::Secret::Identifier("ExampleSecret", "ExampleCollection")); dsr.setUserInteractionMode(Sailfish::Secrets::SecretManager::SystemInteraction); dsr.startRequest(); // status() will change to Finished when complete ``` -------------------------------- ### Retrieve Secrets Data Health Source: https://sailfishos.org/develop/docs/sailfish-secrets/sailfish-secrets-healthcheckrequest.html Use this snippet to get information about the health of secrets data. Ensure a SecretManager is set and start the request before checking the health status. Real clients should avoid blocking with waitForFinished(). ```cpp Sailfish::Secrets::SecretManager man; Sailfish::Secrets::HealthCheckRequest req; req.setManager(&man); req.startRequest(); // status() will change to Finished when complete // real clients should not use waitForFinished() because it blocks req.waitForFinished(); qDebug() << "salt data health:" << req.saltDataHealth(); qDebug() << "masterlock health:" << req.masterlockHealth(); ``` -------------------------------- ### Create a generic account Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-accounts-genericaccountprovisioner.html Example demonstrating the instantiation of GenericAccountProvisioner and the process of setting account details before calling createAccount. ```cpp #include void createAccount(const QString &providerName, const QString &defaultServiceName, const QString &username, const QString &password) { Sailfish::Mdm::Accounts::GenericAccountProvisioner gap; gap.setProviderName(providerName); gap.setDefaultServiceName(defaultServiceName); gap.setUsername(username); gap.setPassword(password); if (!gap.createAccount()) { qWarning() << "Account creation failed:" << eap.errorMessage(); } } ``` -------------------------------- ### Initialize WebEngineSettings and set preferences Source: https://sailfishos.org/develop/docs/sailfish-components-webview/sailfishos-webenginesettings.html Demonstrates the recommended order for initializing the WebEngineSettings singleton and applying custom gecko preferences. ```cpp SailfishOS::WebEngine::instance() *engineSettings = SailfishOS::WebEngineSettings::instance(); engineSettings->initialize(); engineSettings->setPreference(QStringLiteral("ui.textSelectBackground"), QLatin1String("#55ff55")); ``` -------------------------------- ### Define initial page layout Source: https://sailfishos.org/develop/docs/silica/sailfish-application-features.html Sets up a basic page structure with an image and metadata details using QtQuick and Sailfish Silica components. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 ApplicationWindow { initialPage: Component { Page { id: page PageHeader { id: header title: "Image details" } Image { id: image anchors { top: header.bottom horizontalCenter: parent.horizontalCenter } sourceSize.width: page.width - (Theme.horizontalPageMargin * 2) fillMode: Image.PreserveAspectFit source: StandardPaths.pictures + "/img_0001.jpg" } Column { anchors { top: image.bottom topMargin: Theme.paddingLarge left: parent.left leftMargin: Theme.horizontalPageMargin right: parent.right rightMargin: Theme.horizontalPageMargin } DetailItem { label: "Name of file"; value: image.source } DetailItem { label: "Width"; value: image.width } DetailItem { label: "Height"; value: image.height } } } } } ``` -------------------------------- ### Example Usage of PluginInfoRequest Source: https://sailfishos.org/develop/docs/sailfish-secrets/sailfish-secrets-plugininforequest.html An example demonstrating how to retrieve information about available plugins using PluginInfoRequest. ```APIDOC ## Example Usage ```cpp Sailfish::Secrets::SecretManager sm; Sailfish::Secrets::PluginInfoRequest pir; pir.setManager(&sm); pir.startRequest(); // status() will change to Finished when complete // real clients should not use waitForFinished(). pir.waitForFinished(); for (const auto &plugin : pir.encryptedStoragePlugins()) { qDebug() << "Have encrypted storage plugin:" << plugin.name() << "with version:" << plugin.version(); } ``` ``` -------------------------------- ### Simple Slideshow View Example Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-slideshowview.html Demonstrates a basic implementation of SlideshowView with a model and delegate. Ensure Sailfish.Silica 1.0 is imported for usage. ```qml import QtQuick 2.2 import Sailfish.Silica 1.0 SlideshowView { id: view width: 480 height: 200 itemWidth: width / 2 model: 5 delegate: Rectangle { width: view.itemWidth height: view.height border.width: 1 Text { anchors.centerIn: parent text: "item " + index } } } ``` -------------------------------- ### Access System Information Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-sysinfo.html Example demonstrating how to retrieve and print various device properties using the SysInfo namespace. ```cpp #include void printSystemInfo() { qInfo() << "Software version:" << Sailfish::Mdm::SysInfo::softwareVersion(); qInfo() << "Software version id:" << Sailfish::Mdm::SysInfo::softwareVersionId(); qInfo() << "Device model:" << Sailfish::Mdm::SysInfo::deviceModel(); qInfo() << "Device UID:" << Sailfish::Mdm::SysInfo::deviceUid(); qInfo() << "Bluetooth MAC Address:" << Sailfish::Mdm::SysInfo::bluetoothMacAddress(); qInfo() << "Wireless LAN MAC Address:" << Sailfish::Mdm::SysInfo::wlanMacAddress(); qInfo() << "Product name:" << Sailfish::Mdm::SysInfo::productName(); qInfo() << "Manufacturer:" << Sailfish::Mdm::SysInfo::manufacturer(); } ``` -------------------------------- ### LocationInfo - Example Usage Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-locationinfo.html Example code demonstrating how to use the LocationInfo class to listen for location changes. ```APIDOC ## Example of usage: ```cpp #include void listenForLocationChange(QObject *parent) { Sailfish::Mdm::LocationInfo *info = new Sailfish::Mdm::LocationInfo(parent); QObject::connect(info, &Sailfish::Mdm::LocationInfo::positionChanged, [info] { qInfo() << "GPS: Coordinates:" << info->latitude() << "," << info->longitude(); }); info->requestUpdate(); } ``` ``` -------------------------------- ### Implement ImagePickerPage usage Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-imagepickerpage.html Example showing how to push an ImagePickerPage onto the page stack and handle the selected content properties. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { id: page Column { anchors.centerIn: parent width: parent.width - Theme.horizontalPageMargin * 2 spacing: Theme.paddingMedium Button { text: "Image" onClicked: pageStack.push(imagePickerPage) } Image { id: selectedImage sourceSize.height: Theme.itemSizeHuge } } Component { id: imagePickerPage ImagePickerPage { onSelectedContentPropertiesChanged: { selectedImage.source = selectedContentProperties.filePath } } } } } } ``` -------------------------------- ### DeviceLock Example Usage Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-devicelock.html Example demonstrating how to use the DeviceLock class to set or clear the device lockout mode. ```APIDOC ## Example Usage ```cpp #include void setOrClearDeviceLock(bool lockout, QObject *parent) { Sailfish::Mdm::DeviceLock *lock = new Sailfish::Mdm::DeviceLock(parent); if (lockout) { lock->setLockoutMode(Sailfish::Mdm::DeviceLock::RecoverableManagerLockout); QObject::connect(lock, &Sailfish::Mdm::DeviceLock::lockoutModeChanged, [] { qInfo() << "Device locked"; }); QObject::connect(lock, &Sailfish::Mdm::DeviceLock::lockoutModeError, [] { qInfo() << "Failed to lock device"; }); } else { lock->setLockoutMode(Sailfish::Mdm::DeviceLock::NoManagerLockout); QObject::connect(lock, &Sailfish::Mdm::DeviceLock::lockoutModeChanged, []() { qInfo() << "Lockout cleared"; }); QObject::connect(lock, &Sailfish::Mdm::DeviceLock::lockoutModeError, []() { qInfo() << "Failed to clear lockout"; }); } } ``` ``` -------------------------------- ### Implementing a basic IconButton Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-iconbutton.html A simple example demonstrating how to define an IconButton with an icon source and a click handler. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 IconButton { icon.source: "delete.png" onClicked: console.log("Delete!") } ``` -------------------------------- ### Sailfish-Style Flickable Example Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-silicaflickable.html A simple example demonstrating the usage of SilicaFlickable within a Rectangle. Ensure Sailfish.Silica 1.0 is imported. ```qml import QtQuick 2.2 import Sailfish.Silica 1.0 Rectangle { width: 200; height: 100 SilicaFlickable { anchors.fill: parent contentWidth: text.width; contentHeight: text.height Text { id: text text: "Hello, Sailor!" font.pixelSize: 100 } } } ``` -------------------------------- ### MusicPickerPage Usage Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-musicpickerpage.html Demonstrates how to integrate MusicPickerPage within an ApplicationWindow to select a music file and display its path. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { id: page property string selectedMusicFile ValueButton { anchors.centerIn: parent label: "Song" value: selectedMusicFile ? selectedMusicFile : "None" onClicked: pageStack.push(musicPickerPage) } Component { id: musicPickerPage MusicPickerPage { onSelectedContentPropertiesChanged: { page.selectedMusicFile = selectedContentProperties.filePath } } } } } } ``` -------------------------------- ### Amber Web Authorization Framework QML API Example Source: https://sailfishos.org/develop/docs/amber-web-authorization/amber-web-authorization-framework-amberwebauthqmlexample-example.html This example demonstrates using OAuth2AcPkce and OAuth10a helper types to request access tokens from Google and Twitter. Valid Google and Twitter API credentials must be provided for the example to function correctly. ```QML import QtQuick 2.0 import Sailfish.Web 1.0 Rectangle { id: root width: Screen.width height: Screen.height // OAuth2AcPkce for Google OAuth2AcPkce { id: googleAuth clientId: "YOUR_GOOGLE_CLIENT_ID" clientSecret: "YOUR_GOOGLE_CLIENT_SECRET" authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth" tokenUrl: "https://oauth2.googleapis.com/token" scope: "https://www.googleapis.com/auth/userinfo.email \ https://www.googleapis.com/auth/userinfo.profile" onAccessTokenReceived: { console.log("Google Access Token: " + accessToken) // Perform authorized request using accessToken } onError: { console.error("Google Auth Error: " + errorString) } } // OAuth10a for Twitter OAuth10a { id: twitterAuth consumerKey: "YOUR_TWITTER_CONSUMER_KEY" consumerSecret: "YOUR_TWITTER_CONSUMER_SECRET" requestUrl: "https://api.twitter.com/oauth/request_token" authorizationUrl: "https://api.twitter.com/oauth/authorize" tokenUrl: "https://api.twitter.com/oauth/access_token" onAccessTokenReceived: { console.log("Twitter Access Token: " + accessToken) // Perform authorized request using accessToken } onError: { console.error("Twitter Auth Error: " + errorString) } } Button { text: "Login with Google" onClicked: { googleAuth.requestToken() } } Button { text: "Login with Twitter" anchors.top: parent.top anchors.left: parent.left anchors.topMargin: 50 onClicked: { twitterAuth.requestToken() } } } ``` -------------------------------- ### Create an email account Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-accounts-emailaccountprovisioner.html Demonstrates initializing an EmailAccountProvisioner instance and setting mandatory fields to create a new account. ```cpp #include void createEmailAccount(const QString &emailAddress, const QString &password) { Sailfish::Mdm::Accounts::EmailAccountProvisioner eap; eap.setProviderName(QStringLiteral("email")); eap.setEmailAddress(emailAddress); eap.setIncomingPassword(password); if (!eap.createAccount()) { qWarning() << "Account creation failed:" << eap.errorMessage(); } } ``` -------------------------------- ### ResizeFilter QML Example Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-background-resizefilter.html Example demonstrating how to use the ResizeFilter QML type to set the size and fill mode for image resizing. ```qml ResizeFilter { size { width: 256 height: 256 } fillMode: Fill.PreserveAspectFit } ``` -------------------------------- ### Toggle WLAN connectivity Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-connectivitysettings.html Example demonstrating how to instantiate ConnectivitySettings and modify the WLAN state. ```cpp #include void enableOrDisableWlan(bool enable, QObject *parent) { Sailfish::Mdm::ConnectivitySettings *settings = new Sailfish::Mdm::ConnectivitySettings(parent); settings->setWlanEnabled(enable); } ``` -------------------------------- ### Sailfish-Styled Grid View Example Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-silicagridview.html A basic example of using SilicaGridView to display a list of items with a Sailfish-specific style. Ensure Sailfish.Silica is imported. ```QML import QtQuick 2.2 import Sailfish.Silica 1.0 SilicaGridView { width: 480; height: 800 model: ListModel { ListElement { fruit: "jackfruit" } ListElement { fruit: "orange" } ListElement { fruit: "lemon" } ListElement { fruit: "lychee" } ListElement { fruit: "apricots" } } delegate: Item { width: GridView.view.width height: Theme.itemSizeSmall Label { text: fruit } } } ``` -------------------------------- ### MultiDocumentPickerDialog Example Source: https://sailfishos.org/develop/docs/sailfish-components-pickers/qml-sailfish-pickers-multidocumentpickerdialog.html Example of using MultiDocumentPickerDialog to select multiple documents. Handles accepted and rejected selections, processing selected file URLs. ```qml import QtQuick 2.2 import Sailfish.Silica 1.0 import Sailfish.Pickers 1.0 ApplicationWindow { initialPage: Component { Page { property string selectedFiles SilicaFlickable { contentHeight: column.height + Theme.paddingLarge*2 anchors.fill: parent VerticalScrollDecorator {} Column { id: column width: parent.width PageHeader { title: "Multi document picker example" } ValueButton { anchors.horizontalCenter: parent.horizontalCenter label: "Upload documents" value: selectedFiles ? selectedFiles : "None" onClicked: pageStack.push(multiDocumentPickerDialog) } } } Component { id: multiDocumentPickerDialog MultiDocumentPickerDialog { onAccepted: { selectedFiles = "" var urls = [] for (var i = 0; i < selectedContent.count; ++i) { var url = selectedContent.get(i).url // Handle url upload urls.push(selectedContent.get(i).url) } selectedFiles = urls.join(", ") } onRejected: selectedFiles = "" } } } } } ``` -------------------------------- ### Listen for Battery Information Changes Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-batteryinfo.html This example demonstrates how to instantiate BatteryInfo and connect to its signals to receive updates on charger status, battery status, and charge percentage. Ensure you include the necessary header. ```cpp #include void listenForBatteryChanges(QObject *parent) { Sailfish::Mdm::BatteryInfo *info = new Sailfish::Mdm::BatteryInfo(parent); connect(info, &Sailfish::Mdm::BatteryInfo::chargerStatusChanged, [info] { qInfo() << "Charger status now:" << info->chargerStatus(); }); connect(info, &Sailfish::Mdm::BatteryInfo::statusChanged, [info] { qInfo() << "Battery status now:" << info->status(); }); connect(info, &Sailfish::Mdm::BatteryInfo::chargePercentageChanged, [info] { qInfo() << "Battery charge now:" << info->chargePercentage() << "%" ; }); } ``` -------------------------------- ### Minimal Notification Example in QML Source: https://sailfishos.org/develop/docs/nemo-qml-plugin-notifications/qml-nemo-notifications-notification.html A basic example of publishing a notification from a QML application. The notification properties are set directly on the Notification object. ```qml Button { Notification { id: notification summary: "Notification summary" body: "Notification body" } text: "Application notification" + (notification.replacesId ? " ID:" + notification.replacesId : "") onClicked: notification.publish() } ``` -------------------------------- ### Initialize and Use SimVoiceCallFilter in C++ Source: https://sailfishos.org/develop/docs/sailfish-mdm/sailfish-mdm-simvoicecallfilter.html This example demonstrates how to initialize the SimVoiceCallFilter, connect to its signals, and add a dial rule. It requires including the necessary header and setting up a QCoreApplication. ```cpp #include int main(int argc, char **argv) { QCoreApplication app(arg, argv); SimVoiceCallFilter *vcFilter = new SimVoiceCallFilter; QObject::connect(vcFilter, &SimVoiceCallFilter::readyChanged, [vcFilter] { qInfo() << vcFilter->dialRules().count() << "outgoing rules and" << vcFilter->incomingRules().count() << "incoming rules are currently set"; SimFilter::Rule rule("123456789", SimFilter::Block); vcFilter->addDialRule(rule); // block outgoing calls from SIM with IMSI 123456789 QObject::connect(vcFilter, &SimVoiceCallFilter::dialRuleAdded, [rule] { qInfo() << "Outcoming call rule added for IMSI" << rule.imsi; app.quit(); }); }); return app.exec(); } ``` -------------------------------- ### Sailfish-style Fade Animation Example Source: https://sailfishos.org/develop/docs/silica/qml-sailfishsilica-sailfish-silica-fadeanimation.html This example demonstrates how to use FadeAnimation within a Behavior to animate the opacity of a Rectangle. Ensure Sailfish.Silica 1.0 is imported. ```qml import QtQuick 2.2 import Sailfish.Silica 1.0 Page { property bool backgroundClicked MouseArea { anchors.fill: parent onClicked: backgroundClicked = !backgroundClicked } Rectangle { anchors.centerIn: parent width: Theme.itemSizeSmall height: width color: Theme.highlightBackgroundColor opacity: backgroundClicked ? Theme.highlightBackgroundOpacity : 1.0 Behavior on opacity { FadeAnimation {} } } } ``` -------------------------------- ### Create a New Account Source: https://sailfishos.org/develop/docs/sailfish-accounts/qml-sailfishaccounts-account.html This example uses `AccountManager` to create a new account for a specified service (e.g., 'facebook'). It then proceeds to create sign-in credentials for a specific application. The `onAccountCreated` signal provides the new account's identifier. ```qml import Sailfish.Accounts 1.0 QtObject { id: root AccountManager { id: manager Component.onCompleted: manager.createAccount("facebook") onAccountCreated: account.identifier = accountId } Account { id: account onStatusChanged: { if (status == Account.Initialized) { console.log("Successfully created account") var siParams = signInParameters("facebook-sharing") siParams.setParameter("ClientId", "123456789abcdef") createSignInCredentials("MyApp", "SharingCredentials", siParams) } } onSignInCredentialsCreated: { console.log("Successfully created credentials") for (var i in data) console.log(i+"="+data[i]); } } } ``` -------------------------------- ### Create OAuth2 Sign-in Credentials Source: https://sailfishos.org/develop/docs/sailfish-accounts/qml-sailfishaccounts-account.html This example demonstrates how to create per-application credentials for an OAuth2 service. It checks for existing credentials and either creates new ones or signs in using existing ones. The `onSignInCredentialsCreated` and `onSignInResponse` signals log the AccessToken. ```qml import Sailfish.Accounts 1.0 Account { id: account identifier: 12 // example: Facebook account id retrieved from AccountManager or AccountModel onStatusChanged: { if (status == Account.Initialized) { var siParams = signInParameters("facebook-sharing") siParams.setParameter("ClientId", "123456789abcdef") if (!hasSignInCredentials("MyApp", "MyCredentials")) { createSignInCredentials("MyApp", "SharingCredentials", siParams) } else { signIn("MyApp", "SharingCredentials", siParams) } } } onSignInCredentialsCreated: { for (var i in data) console.log(i+"="+data[i]) // will contain AccessToken } onSignInResponse: { for (var i in data) console.log(i+"="+data[i]) // will contain AccessToken } } ```