diff --git a/indicator/deviceindicator.cpp b/indicator/deviceindicator.cpp index e80368fc..8369f95d 100644 --- a/indicator/deviceindicator.cpp +++ b/indicator/deviceindicator.cpp @@ -1,142 +1,150 @@ /* * Copyright 2016 Aleix Pol Gonzalez * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "deviceindicator.h" #include #include #include "interfaces/dbusinterfaces.h" #include class BatteryAction : public QAction { Q_OBJECT public: BatteryAction(DeviceDbusInterface* device) : QAction(nullptr) , m_batteryIface(new DeviceBatteryDbusInterface(device->id(), this)) { setWhenAvailable(m_batteryIface->charge(), [this](int charge) { setCharge(charge); }, this); setWhenAvailable(m_batteryIface->isCharging(), [this](bool charging) { setCharging(charging); }, this); connect(m_batteryIface, SIGNAL(chargeChanged(int)), this, SLOT(setCharge(int))); connect(m_batteryIface, SIGNAL(stateChanged(bool)), this, SLOT(setCharging(bool))); setIcon(QIcon::fromTheme(QStringLiteral("battery"))); update(); } void update() { if (m_charge < 0) setText(i18n("No Battery")); else if (m_charging) setText(i18n("Battery: %1% (Charging)", m_charge)); else setText(i18n("Battery: %1%", m_charge)); } private Q_SLOTS: void setCharge(int charge) { m_charge = charge; update(); } void setCharging(bool charging) { m_charging = charging; update(); } private: DeviceBatteryDbusInterface* m_batteryIface; int m_charge = -1; bool m_charging = false; }; DeviceIndicator::DeviceIndicator(DeviceDbusInterface* device) : QMenu(device->name(), nullptr) , m_device(device) , m_remoteCommandsInterface(new RemoteCommandsDbusInterface(m_device->id())) { #ifdef Q_OS_WIN setIcon(QIcon(QStandardPaths::locate(QStandardPaths::AppDataLocation, QStringLiteral("icons/hicolor/scalable/status/") + device->iconName() + QStringLiteral(".svg")))); #else setIcon(QIcon::fromTheme(device->iconName())); #endif connect(device, SIGNAL(nameChanged(QString)), this, SLOT(setText(QString))); auto battery = new BatteryAction(device); addAction(battery); setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_battery")), [battery](bool available) { battery->setVisible(available); } , this); auto browse = addAction(QIcon::fromTheme(QStringLiteral("document-open-folder")), i18n("Browse device")); connect(browse, &QAction::triggered, device, [device](){ SftpDbusInterface* sftpIface = new SftpDbusInterface(device->id(), device); sftpIface->startBrowsing(); sftpIface->deleteLater(); }); setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_sftp")), [browse](bool available) { browse->setVisible(available); }, this); auto findDevice = addAction(QIcon::fromTheme(QStringLiteral("irc-voice")), i18n("Ring device")); connect(findDevice, &QAction::triggered, device, [device](){ FindMyPhoneDeviceDbusInterface* iface = new FindMyPhoneDeviceDbusInterface(device->id(), device); iface->ring(); iface->deleteLater(); }); setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_findmyphone")), [findDevice](bool available) { findDevice->setVisible(available); }, this); auto sendFile = addAction(QIcon::fromTheme(QStringLiteral("document-share")), i18n("Send file")); connect(sendFile, &QAction::triggered, device, [device, this](){ const QUrl url = QFileDialog::getOpenFileUrl(parentWidget(), i18n("Select file to send to '%1'", device->name()), QUrl::fromLocalFile(QDir::homePath())); if (url.isEmpty()) return; QDBusMessage msg = QDBusMessage::createMethodCall(QStringLiteral("org.kde.kdeconnect"), QStringLiteral("/modules/kdeconnect/devices/") + device->id() + QStringLiteral("/share"), QStringLiteral("org.kde.kdeconnect.device.share"), QStringLiteral("shareUrl")); msg.setArguments(QVariantList() << url.toString()); DbusHelper::sessionBus().call(msg); }); setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_share")), [sendFile](bool available) { sendFile->setVisible(available); }, this); + + if (!QStandardPaths::findExecutable(QStringLiteral("kdeconnect-sms")).isEmpty()) { + auto smsapp = addAction(QIcon::fromTheme(QStringLiteral("message-new")), i18n("SMS Messages...")); + QObject::connect(smsapp, &QAction::triggered, device, [device] () { + QProcess::startDetached(QLatin1String("kdeconnect-sms"), { QStringLiteral("--device"), device->id() }); + }); + setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_sms")), [smsapp](bool available) { smsapp->setVisible(available); }, this); + } + QMenu* remoteCommandsMenu = new QMenu(i18n("Run command"), this); QAction* menuAction = remoteCommandsMenu->menuAction(); QAction* addCommandAction = remoteCommandsMenu->addAction(QIcon::fromTheme(QStringLiteral("list-add")), i18n("Add commands")); - connect(addCommandAction, &QAction::triggered, m_remoteCommandsInterface, &RemoteCommandsDbusInterface::editCommands); addAction(menuAction); setWhenAvailable(device->hasPlugin(QStringLiteral("kdeconnect_remotecommands")), [this, remoteCommandsMenu, menuAction](bool available) { menuAction->setVisible(available); if (!available) return; const auto cmds = QJsonDocument::fromJson(m_remoteCommandsInterface->commands()).object(); for (auto it = cmds.constBegin(), itEnd = cmds.constEnd(); it!=itEnd; ++it) { const QJsonObject cont = it->toObject(); QString key = it.key(); QAction* action = remoteCommandsMenu->addAction(cont.value(QStringLiteral("name")).toString()); connect(action, &QAction::triggered, [this, key] { m_remoteCommandsInterface->triggerCommand(key); }); } }, this); } #include "deviceindicator.moc" diff --git a/indicator/main.cpp b/indicator/main.cpp index d7d68494..5cef0a78 100644 --- a/indicator/main.cpp +++ b/indicator/main.cpp @@ -1,203 +1,203 @@ /* * Copyright 2016 Aleix Pol Gonzalez * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #ifdef QSYSTRAY #include #else #include #endif #include #include #include #include #include "interfaces/devicesmodel.h" #include "interfaces/dbusinterfaces.h" #include "kdeconnect-version.h" #include "deviceindicator.h" #ifdef Q_OS_MAC #include #endif #include int main(int argc, char** argv) { QApplication app(argc, argv); KAboutData about(QStringLiteral("kdeconnect-indicator"), i18n("KDE Connect Indicator"), QStringLiteral(KDECONNECT_VERSION_STRING), i18n("KDE Connect Indicator tool"), KAboutLicense::GPL, i18n("(C) 2016 Aleix Pol Gonzalez")); KAboutData::setApplicationData(about); #ifdef Q_OS_WIN QProcess kdeconnectd; kdeconnectd.start(QStringLiteral("kdeconnectd.exe")); #endif #ifdef Q_OS_MAC // Unset launchctl env, avoid block DbusHelper::macosUnsetLaunchctlEnv(); // Get bundle path CFURLRef url = (CFURLRef)CFAutorelease((CFURLRef)CFBundleCopyBundleURL(CFBundleGetMainBundle())); QString basePath = QUrl::fromCFURL(url).path(); - + // Start kdeconnectd QProcess kdeconnectdProcess; kdeconnectdProcess.startDetached(basePath + QStringLiteral("Contents/MacOS/kdeconnectd")); // Wait for dbus daemon env QProcess getLaunchdDBusEnv; int retry = 0; do { getLaunchdDBusEnv.setProgram(QStringLiteral("launchctl")); getLaunchdDBusEnv.setArguments({ QStringLiteral("getenv"), QStringLiteral(KDECONNECT_SESSION_DBUS_LAUNCHD_ENV) }); getLaunchdDBusEnv.start(); getLaunchdDBusEnv.waitForFinished(); QString launchdDBusEnv = QString::fromLocal8Bit(getLaunchdDBusEnv.readAllStandardOutput()); if (launchdDBusEnv.length() > 0) { break; } else if (retry >= 10) { // Show a warning and exit qCritical() << "Fail to get launchctl" << KDECONNECT_SESSION_DBUS_LAUNCHD_ENV << "env"; QMessageBox::critical(nullptr, i18n("KDE Connect"), i18n("Cannot connect to DBus\n" "KDE Connect will quit"), QMessageBox::Abort, QMessageBox::Abort); return -1; } else { QThread::sleep(1); // Retry after 1s retry++; } } while(true); #endif KDBusService dbusService(KDBusService::Unique); DevicesModel model; model.setDisplayFilter(DevicesModel::Reachable | DevicesModel::Paired); QMenu* menu = new QMenu; DaemonDbusInterface iface; auto refreshMenu = [&iface, &model, &menu]() { menu->clear(); auto configure = menu->addAction(QIcon::fromTheme(QStringLiteral("configure")), i18n("Configure...")); QObject::connect(configure, &QAction::triggered, configure, [](){ KCMultiDialog* dialog = new KCMultiDialog; dialog->addModule(QStringLiteral("kcm_kdeconnect")); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); }); for (int i=0, count = model.rowCount(); iaddMenu(indicator); } const QStringList requests = iface.pairingRequests(); if (!requests.isEmpty()) { menu->addSection(i18n("Pairing requests")); for(const auto& req: requests) { DeviceDbusInterface* dev = new DeviceDbusInterface(req, menu); auto pairMenu = menu->addMenu(dev->name()); pairMenu->addAction(i18n("Pair"), dev, &DeviceDbusInterface::acceptPairing); pairMenu->addAction(i18n("Reject"), dev, &DeviceDbusInterface::rejectPairing); } } #if (defined Q_OS_MAC || defined Q_OS_WIN) // Add quit menu menu->addAction(i18n("Quit"), [](){ auto message = QDBusMessage::createMethodCall(QStringLiteral("org.kde.kdeconnect.daemon"), QStringLiteral("/MainApplication"), QStringLiteral("org.qtproject.Qt.QCoreApplication"), QStringLiteral("quit")); DbusHelper::sessionBus().call(message); QCoreApplication::quit(); // Close this application }); #endif }; QObject::connect(&iface, &DaemonDbusInterface::pairingRequestsChangedProxy, &model, refreshMenu); QObject::connect(&model, &DevicesModel::rowsInserted, &model, refreshMenu); QObject::connect(&model, &DevicesModel::rowsRemoved, &model, refreshMenu); #ifdef Q_OS_MAC QStringList themeSearchPaths = QIcon::themeSearchPaths(); themeSearchPaths << basePath + QStringLiteral("Contents/Resources/icons/"); QIcon::setThemeSearchPaths(themeSearchPaths); #endif #ifdef QSYSTRAY QSystemTrayIcon systray; #ifdef Q_OS_WIN systray.setIcon(QIcon(QStandardPaths::locate(QStandardPaths::AppLocalDataLocation, QStringLiteral("icons/hicolor/scalable/apps/kdeconnectindicatorwin.svg")))); #else systray.setIcon(QIcon::fromTheme(QStringLiteral("kdeconnectindicatordark"))); #endif systray.setVisible(true); systray.setToolTip(QStringLiteral("KDE Connect")); QObject::connect(&model, &DevicesModel::rowsChanged, &model, [&systray, &model]() { systray.setToolTip(i18np("%1 device connected", "%1 devices connected", model.rowCount())); }); systray.setContextMenu(menu); #else KStatusNotifierItem systray; systray.setIconByName(QStringLiteral("kdeconnectindicatordark")); systray.setToolTip(QStringLiteral("kdeconnect"), QStringLiteral("KDE Connect"), QStringLiteral("KDE Connect")); systray.setCategory(KStatusNotifierItem::Communications); systray.setStatus(KStatusNotifierItem::Passive); systray.setStandardActionsEnabled(false); QObject::connect(&model, &DevicesModel::rowsChanged, &model, [&systray, &model]() { const auto count = model.rowCount(); systray.setStatus(count == 0 ? KStatusNotifierItem::Passive : KStatusNotifierItem::Active); systray.setToolTip(QStringLiteral("kdeconnect"), QStringLiteral("KDE Connect"), i18np("%1 device connected", "%1 devices connected", count)); }); systray.setContextMenu(menu); #endif refreshMenu(); app.setQuitOnLastWindowClosed(false); return app.exec(); } diff --git a/interfaces/devicesmodel.h b/interfaces/devicesmodel.h index dcd0c946..763eecda 100644 --- a/interfaces/devicesmodel.h +++ b/interfaces/devicesmodel.h @@ -1,99 +1,99 @@ /** * Copyright 2013 Albert Vaca * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef DEVICESMODEL_H #define DEVICESMODEL_H #include #include #include #include "kdeconnectinterfaces_export.h" class QDBusPendingCallWatcher; class DaemonDbusInterface; class DeviceDbusInterface; class KDECONNECTINTERFACES_EXPORT DevicesModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(int displayFilter READ displayFilter WRITE setDisplayFilter) Q_PROPERTY(int count READ rowCount NOTIFY rowsChanged) public: enum ModelRoles { NameModelRole = Qt::DisplayRole, IconModelRole = Qt::DecorationRole, StatusModelRole = Qt::InitialSortOrderRole, IdModelRole = Qt::UserRole, IconNameRole, DeviceRole }; Q_ENUM(ModelRoles); // A device is always paired or reachable or both // You can combine the Paired and Reachable flags enum StatusFilterFlag { NoFilter = 0x00, Paired = 0x01, // show device only if it's paired Reachable = 0x02 // show device only if it's reachable }; Q_DECLARE_FLAGS(StatusFilterFlags, StatusFilterFlag) Q_FLAGS(StatusFilterFlags) Q_ENUM(StatusFilterFlag) explicit DevicesModel(QObject* parent = nullptr); ~DevicesModel() override; void setDisplayFilter(int flags); int displayFilter() const; QVariant data(const QModelIndex& index, int role) const override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; Q_SCRIPTABLE DeviceDbusInterface* getDevice(int row) const; QHash roleNames() const override; - int rowForDevice(const QString& id) const; + Q_SCRIPTABLE int rowForDevice(const QString& id) const; private Q_SLOTS: void deviceAdded(const QString& id); void deviceRemoved(const QString& id); void deviceUpdated(const QString& id, bool isVisible); void refreshDeviceList(); void receivedDeviceList(QDBusPendingCallWatcher* watcher); void nameChanged(const QString& newName); Q_SIGNALS: void rowsChanged(); private: void clearDevices(); void appendDevice(DeviceDbusInterface* dev); bool passesFilter(DeviceDbusInterface* dev) const; DaemonDbusInterface* m_dbusInterface; QVector m_deviceList; StatusFilterFlag m_displayFilter; }; //Q_DECLARE_OPERATORS_FOR_FLAGS(DevicesModel::StatusFilterFlag) #endif // DEVICESMODEL_H diff --git a/plasmoid/package/contents/ui/DeviceDelegate.qml b/plasmoid/package/contents/ui/DeviceDelegate.qml index 0eac563e..233c4597 100644 --- a/plasmoid/package/contents/ui/DeviceDelegate.qml +++ b/plasmoid/package/contents/ui/DeviceDelegate.qml @@ -1,300 +1,317 @@ /** * Copyright 2013 Albert Vaca * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ import QtQuick 2.1 import QtQuick.Layouts 1.1 import org.kde.plasma.core 2.0 as PlasmaCore import org.kde.plasma.components 2.0 as PlasmaComponents import org.kde.plasma.components 3.0 as PlasmaComponents3 import org.kde.kdeconnect 1.0 import QtQuick.Dialogs 1.0 import QtQuick.Controls 2.4 PlasmaComponents.ListItem { id: root readonly property QtObject device: DeviceDbusInterfaceFactory.create(model.deviceId) DropArea { id: fileDropArea anchors.fill: parent onDropped: { if (drop.hasUrls) { var urls = []; for (var v in drop.urls) { if (drop.urls[v] != null) { if (urls.indexOf(drop.urls[v].toString()) == -1) { urls.push(drop.urls[v].toString()); } } } var i; for (i = 0; i < urls.length; i++) { share.plugin.shareUrl(urls[i]); } } drop.accepted = true; } PlasmaCore.ToolTipArea { id: dropAreaToolTip anchors.fill: parent location: plasmoid.location active: true mainText: i18n("File Transfer") subText: i18n("Drop a file to transfer it onto your phone.") } } Column { width: parent.width RowLayout { Battery { id: battery device: root.device } PlasmaComponents.Label { elide: Text.ElideRight text: (battery.available && battery.charge > -1) ? i18n("%1 (%2)", display, battery.displayString) : display Layout.fillWidth: true textFormat: Text.PlainText } //Share PlasmaComponents.Button { FileDialog { id: fileDialog title: i18n("Please choose a file") folder: shortcuts.home selectMultiple: true } id: shareFile iconSource: "document-share" visible: share.available tooltip: i18n("Share file") onClicked: { fileDialog.open() fileDialog.fileUrls.forEach(function (url) { share.plugin.shareUrl(url) }) } } //Find my phone PlasmaComponents.Button { FindMyPhone { id: findmyphone device: root.device } id: ring iconSource: "irc-voice" visible: findmyphone.available tooltip: i18n("Ring my phone") onClicked: { findmyphone.ring() } } //SFTP PlasmaComponents.Button { Sftp { id: sftp device: root.device } id: browse iconSource: "document-open-folder" visible: sftp.available tooltip: i18n("Browse this device") onClicked: { sftp.browse() } } + //SMS + PlasmaComponents.Button + { + SMS { + id: sms + device: root.device + } + + iconSource: "message-new'" + visible: sms.available + tooltip: i18n("SMS Messages") + + onClicked: { + sms.plugin.launchApp() + } + } + height: browse.height width: parent.width } //RemoteKeyboard PlasmaComponents.ListItem { visible: remoteKeyboard.remoteState width: parent.width RowLayout { width: parent.width spacing: 5 PlasmaComponents.Label { id: remoteKeyboardLabel text: i18n("Remote Keyboard") } RemoteKeyboard { id: remoteKeyboard device: root.device Layout.fillWidth: true } } } //Notifications PlasmaComponents.ListItem { visible: notificationsModel.count>0 enabled: true PlasmaComponents.Label { text: i18n("Notifications:") } PlasmaComponents.ToolButton { enabled: true visible: notificationsModel.isAnyDimissable; anchors.right: parent.right iconSource: "edit-clear-history" tooltip: i18n("Dismiss all notifications") onClicked: notificationsModel.dismissAll(); } } Repeater { id: notificationsView model: NotificationsModel { id: notificationsModel deviceId: root.device.id() } delegate: PlasmaComponents.ListItem { id: listitem enabled: true onClicked: checked = !checked PlasmaCore.IconItem { id: notificationIcon source: appIcon width: (valid && appIcon.length) ? dismissButton.width : 0 height: width anchors.left: parent.left } PlasmaComponents.Label { text: appName + ": " + (title.length>0 ? (appName==title?notitext:title+": "+notitext) : display) anchors.right: replyButton.left anchors.left: notificationIcon.right elide: listitem.checked ? Text.ElideNone : Text.ElideRight maximumLineCount: listitem.checked ? 0 : 1 wrapMode: Text.WordWrap } PlasmaComponents.ToolButton { id: replyButton visible: repliable enabled: repliable anchors.right: dismissButton.left iconSource: "mail-reply-sender" tooltip: i18n("Reply") onClicked: dbusInterface.reply(); } PlasmaComponents.ToolButton { id: dismissButton visible: notificationsModel.isAnyDimissable; enabled: dismissable anchors.right: parent.right iconSource: "window-close" tooltip: i18n("Dismiss") onClicked: dbusInterface.dismiss(); } } } RemoteCommands { id: rc device: root.device } // Commands RowLayout { visible: rc.available width: parent.width PlasmaComponents.Label { text: i18n("Run command") Layout.fillWidth: true } PlasmaComponents.Button { id: addCommandButton iconSource: "list-add" tooltip: i18n("Add command") onClicked: rc.plugin.editCommands() visible: rc.plugin && rc.plugin.canAddCommand } } Repeater { id: commandsView visible: rc.available model: RemoteCommandsModel { id: commandsModel deviceId: rc.device.id() } delegate: PlasmaComponents.ListItem { enabled: true onClicked: rc.plugin.triggerCommand(key) PlasmaComponents.Label { text: name + "\n" + command } } } // Share Share { id: share device: root.device } PlasmaComponents.Label { text: i18n("Share text") } PlasmaComponents3.TextArea { id: shareText width: parent.width } PlasmaComponents.Button { id: submitTextButton anchors.right: shareText.right iconSource: "document-send" onClicked: { share.plugin.shareText(shareText.getText(0, shareText.length)) shareText.clear() } } //NOTE: More information could be displayed here } } diff --git a/plugins/sms/smsplugin.cpp b/plugins/sms/smsplugin.cpp index 2f9c3cd4..52da9c44 100644 --- a/plugins/sms/smsplugin.cpp +++ b/plugins/sms/smsplugin.cpp @@ -1,126 +1,131 @@ /** * Copyright 2013 Albert Vaca * Copyright 2018 Simon Redman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "smsplugin.h" #include #include #include #include #include +#include #include #include #include "sendreplydialog.h" K_PLUGIN_CLASS_WITH_JSON(SmsPlugin, "kdeconnect_sms.json") Q_LOGGING_CATEGORY(KDECONNECT_PLUGIN_SMS, "kdeconnect.plugin.sms") SmsPlugin::SmsPlugin(QObject* parent, const QVariantList& args) : KdeConnectPlugin(parent, args) , m_telepathyInterface(QStringLiteral("org.freedesktop.Telepathy.ConnectionManager.kdeconnect"), QStringLiteral("/kdeconnect")) , m_conversationInterface(new ConversationsDbusInterface(this)) { } SmsPlugin::~SmsPlugin() { // m_conversationInterface is self-deleting, see ~ConversationsDbusInterface for more information } bool SmsPlugin::receivePacket(const NetworkPacket& np) { if (np.type() == PACKET_TYPE_SMS_MESSAGES) { return handleBatchMessages(np); } return true; } void SmsPlugin::sendSms(const QString& phoneNumber, const QString& messageBody) { NetworkPacket np(PACKET_TYPE_SMS_REQUEST, { {QStringLiteral("sendSms"), true}, {QStringLiteral("phoneNumber"), phoneNumber}, {QStringLiteral("messageBody"), messageBody} }); qCDebug(KDECONNECT_PLUGIN_SMS) << "Dispatching SMS send request to remote"; sendPacket(np); } void SmsPlugin::requestAllConversations() { NetworkPacket np(PACKET_TYPE_SMS_REQUEST_CONVERSATIONS); sendPacket(np); } void SmsPlugin::requestConversation (const qint64& conversationID) const { NetworkPacket np(PACKET_TYPE_SMS_REQUEST_CONVERSATION); np.set(QStringLiteral("threadID"), conversationID); sendPacket(np); } void SmsPlugin::forwardToTelepathy(const ConversationMessage& message) { // If we don't have a valid Telepathy interface, bail out if (!(m_telepathyInterface.isValid())) return; qCDebug(KDECONNECT_PLUGIN_SMS) << "Passing a text message to the telepathy interface"; connect(&m_telepathyInterface, SIGNAL(messageReceived(QString,QString)), SLOT(sendSms(QString,QString)), Qt::UniqueConnection); const QString messageBody = message.body(); const QString contactName; // TODO: When telepathy support is improved, look up the contact with KPeople const QString phoneNumber = message.addresses()[0].address(); m_telepathyInterface.call(QDBus::NoBlock, QStringLiteral("sendMessage"), phoneNumber, contactName, messageBody); } bool SmsPlugin::handleBatchMessages(const NetworkPacket& np) { const auto messages = np.get(QStringLiteral("messages")); QList messagesList; messagesList.reserve(messages.count()); for (const QVariant& body : messages) { ConversationMessage message(body.toMap()); if (message.containsTextBody()) { forwardToTelepathy(message); } messagesList.append(message); } m_conversationInterface->addMessages(messagesList); return true; } - QString SmsPlugin::dbusPath() const { return QStringLiteral("/modules/kdeconnect/devices/") + device()->id() + QStringLiteral("/sms"); } +void SmsPlugin::launchApp() +{ + QProcess::startDetached(QLatin1String("kdeconnect-sms"), { QStringLiteral("--device"), device()->id() }); +} + #include "smsplugin.moc" diff --git a/plugins/sms/smsplugin.h b/plugins/sms/smsplugin.h index 5cfbe33e..ac5719e7 100644 --- a/plugins/sms/smsplugin.h +++ b/plugins/sms/smsplugin.h @@ -1,159 +1,161 @@ /** * Copyright 2013 Albert Vaca * Copyright 2018 Simon Redman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SMSPLUGIN_H #define SMSPLUGIN_H #include #include #include "conversationsdbusinterface.h" #include "interfaces/conversationmessage.h" #include "sendreplydialog.h" /** * Packet used to indicate a batch of messages has been pushed from the remote device * * The body should contain the key "messages" mapping to an array of messages * * For example: * { * "version": 2 // This is the second version of this packet type and * // version 1 packets (which did not carry this flag) * // are incompatible with the new format * "messages" : [ * { "event" : 1, // 32-bit field containing a bitwise-or of event flags * // See constants declared in SMSHelper.Message for defined * // values and explanations * "body" : "Hello", // Text message body * "addresses": > // List of Address objects, one for each participant of the conversation * // The user's Address is excluded so: * // If this is a single-target messsage, there will only be one * // Address (the other party) * // If this is an incoming multi-target message, the first Address is the * // sender and all other addresses are other parties to the conversation * // If this is an outgoing multi-target message, the sender is implicit * // (the user's phone number) and all Addresses are recipients * "date" : "1518846484880", // Timestamp of the message * "type" : "2", // Compare with Android's * // Telephony.TextBasedSmsColumns.MESSAGE_TYPE_* * "thread_id" : 132 // Thread to which the message belongs * "read" : true // Boolean representing whether a message is read or unread * }, * { ... }, * ... * ] * * The following optional fields of a message object may be defined * "sub_id": // Android's subscriber ID, which is basically used to determine which SIM card the message * // belongs to. This is mostly useful when attempting to reply to an SMS with the correct * // SIM card using PACKET_TYPE_SMS_REQUEST. * // If this value is not defined or if it does not match a valid subscriber_id known by * // Android, we will use whatever subscriber ID Android gives us as the default * * An Address object looks like: * { * "address": // Address (phone number, email address, etc.) of this object * } */ #define PACKET_TYPE_SMS_MESSAGES QStringLiteral("kdeconnect.sms.messages") /** * Packet sent to request a message be sent * * This will almost certainly need to be replaced or augmented to support MMS, * but be sure the Android side remains compatible with old desktop apps! * * The body should look like so: * { "sendSms": true, * "phoneNumber": "542904563213", * "messageBody": "Hi mom!" * } */ #define PACKET_TYPE_SMS_REQUEST QStringLiteral("kdeconnect.sms.request") /** * Packet sent to request the most-recent message in each conversations on the device * * The request packet shall contain no body */ #define PACKET_TYPE_SMS_REQUEST_CONVERSATIONS QStringLiteral("kdeconnect.sms.request_conversations") /** * Packet sent to request all the messages in a particular conversation * * The body should contain the key "threadID" mapping to the threadID being requested * For example: * { "threadID": 203 } */ #define PACKET_TYPE_SMS_REQUEST_CONVERSATION QStringLiteral("kdeconnect.sms.request_conversation") Q_DECLARE_LOGGING_CATEGORY(KDECONNECT_PLUGIN_SMS) class Q_DECL_EXPORT SmsPlugin : public KdeConnectPlugin { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kdeconnect.device.sms") public: explicit SmsPlugin(QObject* parent, const QVariantList& args); ~SmsPlugin() override; bool receivePacket(const NetworkPacket& np) override; void connected() override {} QString dbusPath() const override; public Q_SLOTS: Q_SCRIPTABLE void sendSms(const QString& phoneNumber, const QString& messageBody); /** * Send a request to the remote for all of its conversations */ Q_SCRIPTABLE void requestAllConversations(); /** * Send a request to the remote for a particular conversation * * TODO: Make interface capable of requesting limited window of messages */ Q_SCRIPTABLE void requestConversation(const qint64& conversationID) const; + Q_SCRIPTABLE void launchApp(); + private: /** * Send to the telepathy plugin if it is available */ void forwardToTelepathy(const ConversationMessage& message); /** * Handle a packet which contains many messages, such as PACKET_TYPE_TELEPHONY_MESSAGE */ bool handleBatchMessages(const NetworkPacket& np); QDBusInterface m_telepathyInterface; ConversationsDbusInterface* m_conversationInterface; }; #endif diff --git a/smsapp/main.cpp b/smsapp/main.cpp index 5a1e776a..55e7d9ec 100644 --- a/smsapp/main.cpp +++ b/smsapp/main.cpp @@ -1,79 +1,82 @@ /** * Copyright (C) 2018 Aleix Pol Gonzalez * Copyright (C) 2018 Simon Redman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "conversationmodel.h" #include "conversationlistmodel.h" #include "kdeconnect-version.h" #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { QApplication app(argc, argv); KAboutData aboutData(QStringLiteral("kdeconnect.sms"), i18n("SMS Instant Messaging"), QStringLiteral(KDECONNECT_VERSION_STRING), i18n("KDE Connect SMS"), KAboutLicense::GPL, i18n("(C) 2018-2019, KDE Connect Team")); aboutData.addAuthor(i18n("Simon Redman"), {}, QStringLiteral("simon@ergotech.com")); aboutData.addAuthor(i18n("Aleix Pol Gonzalez"), {}, QStringLiteral("aleixpol@kde.org")); aboutData.addAuthor(i18n("Nicolas Fella"), {}, QStringLiteral("nicolas.fella@gmx.de")); KAboutData::setApplicationData(aboutData); - QString initialMessage; + QString initialMessage, deviceid; { QCommandLineParser parser; aboutData.setupCommandLine(&parser); parser.addVersionOption(); parser.addHelpOption(); + parser.addOption(QCommandLineOption(QStringLiteral("device"), i18n("Select a device"), i18n("id"))); parser.addOption(QCommandLineOption(QStringLiteral("message"), i18n("Send a message"), i18n("message"))); parser.process(app); aboutData.processCommandLine(&parser); - if (parser.isSet(QStringLiteral("message"))) { - initialMessage = parser.value(QStringLiteral("message")); - } + initialMessage = parser.value(QStringLiteral("message")); + deviceid = parser.value(QStringLiteral("device")); } KDBusService service(KDBusService::Unique); qmlRegisterType(); qmlRegisterType("org.kde.kdeconnect.sms", 1, 0, "QSortFilterProxyModel"); qmlRegisterType("org.kde.kdeconnect.sms", 1, 0, "ConversationModel"); qmlRegisterType("org.kde.kdeconnect.sms", 1, 0, "ConversationListModel"); QQmlApplicationEngine engine; engine.rootContext()->setContextObject(new KLocalizedContext(&engine)); - engine.rootContext()->setContextProperty(QStringLiteral("_initialMessage"), QVariant(initialMessage)); - engine.rootContext()->setContextProperty(QStringLiteral("aboutData"), QVariant::fromValue(KAboutData::applicationData())); + engine.rootContext()->setContextProperties({ + { QStringLiteral("initialMessage"), initialMessage }, + { QStringLiteral("initialDevice"), deviceid }, + { QStringLiteral("aboutData"), QVariant::fromValue(KAboutData::applicationData()) } + }); engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); return app.exec(); } diff --git a/smsapp/qml/ConversationList.qml b/smsapp/qml/ConversationList.qml index 9f067120..4b2dfcfd 100644 --- a/smsapp/qml/ConversationList.qml +++ b/smsapp/qml/ConversationList.qml @@ -1,219 +1,223 @@ /** * Copyright (C) 2018 Aleix Pol Gonzalez * Copyright (C) 2018 Nicolas Fella * Copyright (C) 2018 Simon Redman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ import QtQuick 2.5 import QtQuick.Controls 2.1 import QtQuick.Layouts 1.1 import org.kde.people 1.0 import org.kde.kirigami 2.6 as Kirigami import org.kde.kdeconnect 1.0 import org.kde.kdeconnect.sms 1.0 Kirigami.ScrollablePage { id: page ToolTip { id: noDevicesWarning visible: !devicesCombo.enabled timeout: -1 text: "⚠️ " + i18n("No devices available") + " ⚠️" MouseArea { // Detect mouseover and show another tooltip with more information anchors.fill: parent hoverEnabled: true ToolTip.visible: containsMouse ToolTip.delay: Qt.styleHints.mousePressAndHoldInterval // TODO: Wrap text if line is too long for the screen ToolTip.text: i18n("No new messages can be sent or received, but you can browse cached content") } } contextualActions: [ Kirigami.Action { text: i18n("Refresh") icon.name: "view-refresh" enabled: devicesCombo.count > 0 onTriggered: { conversationListModel.refresh() } }, Kirigami.Action { text: i18n("About...") icon.name: "help-about" onTriggered: { applicationWindow().pageStack.push(aboutPageComponent, { aboutData: aboutData }); } } ] Component { id: aboutPageComponent Kirigami.AboutPage {} } property string initialMessage + property string initialDevice header: Kirigami.InlineMessage { Layout.fillWidth: true visible: page.initialMessage.length > 0 text: i18n("Choose recipient") actions: [ Kirigami.Action { iconName: "dialog-cancel" text: "Cancel" onTriggered: initialMessage = "" } ] } footer: ComboBox { id: devicesCombo enabled: count > 0 displayText: !enabled ? i18n("No devices available") : undefined model: DevicesSortProxyModel { id: devicesModel //TODO: make it possible to filter if they can do sms sourceModel: DevicesModel { displayFilter: DevicesModel.Paired | DevicesModel.Reachable } onRowsInserted: if (devicesCombo.currentIndex < 0) { - devicesCombo.currentIndex = 0 + if (page.initialDevice) + devicesCombo.currentIndex = devicesModel.rowForDevice(page.initialDevice); + else + devicesCombo.currentIndex = 0 } } textRole: "display" } readonly property bool deviceConnected: devicesCombo.enabled readonly property QtObject device: devicesCombo.currentIndex >= 0 ? devicesModel.data(devicesModel.index(devicesCombo.currentIndex, 0), DevicesModel.DeviceRole) : null readonly property alias lastDeviceId: conversationListModel.deviceId Component { id: chatView ConversationDisplay { deviceId: page.lastDeviceId deviceConnected: page.deviceConnected } } ListView { id: view currentIndex: 0 model: QSortFilterProxyModel { sortOrder: Qt.DescendingOrder sortRole: ConversationListModel.DateRole filterCaseSensitivity: Qt.CaseInsensitive sourceModel: ConversationListModel { id: conversationListModel deviceId: device ? device.id() : "" } } header: TextField { /** * Used as the filter of the list of messages */ id: filter placeholderText: i18n("Filter...") width: parent.width z: 10 onTextChanged: { view.model.setFilterFixedString(filter.text); view.currentIndex = 0 } onAccepted: { view.currentItem.startChat() } Keys.onReturnPressed: { event.accepted = true filter.onAccepted() } Keys.onEscapePressed: { event.accepted = filter.text != "" filter.text = "" } Shortcut { sequence: "Ctrl+F" onActivated: filter.forceActiveFocus() } } headerPositioning: ListView.OverlayHeader Keys.forwardTo: [headerItem] delegate: Kirigami.AbstractListItem { id: listItem contentItem: RowLayout { Kirigami.Icon { id: iconItem source: decoration readonly property int size: Kirigami.Units.iconSizes.smallMedium Layout.minimumHeight: size Layout.maximumHeight: size Layout.minimumWidth: size selected: listItem.highlighted || listItem.checked || (listItem.pressed && listItem.supportsMouseEvents) } ColumnLayout { Label { Layout.fillWidth: true font.weight: Font.Bold text: display maximumLineCount: 1 elide: Text.ElideRight textFormat: Text.PlainText } Label { Layout.fillWidth: true text: toolTip maximumLineCount: 1 elide: Text.ElideRight textFormat: Text.PlainText } } } function startChat() { applicationWindow().pageStack.push(chatView, { addresses: addresses, conversationId: model.conversationId, isMultitarget: isMultitarget, initialMessage: page.initialMessage, device: device}) initialMessage = "" } onClicked: { startChat(); view.currentIndex = index } // Keep the currently-open chat highlighted even if this element is not focused highlighted: chatView.conversationId == model.conversationId } Component.onCompleted: { currentIndex = -1 focus = true } } }