summaryrefslogtreecommitdiffstats
path: root/examples/writemessage/messagesender.cpp
blob: 6a26ca1189f6292453c2a71d40ff4e00df636ad7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the examples of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#if defined(Q_OS_SYMBIAN)
// Maximized windows are resizing correctly on S60 w/ Qt 4.6.0
// Use tabs to reduce the minimal height required
#define USE_TABBED_LAYOUT
#endif

#include "messagesender.h"

#include <QComboBox>
#include <QCoreApplication>
#include <QDateTime>
#include <QFileDialog>
#include <QGroupBox>
#include <QLabel>
#include <QLayout>
#include <QLineEdit>
#include <QListWidget>
#include <QMessageBox>
#include <QPushButton>
#include <QTextEdit>
#include <QTimer>
#include <QDebug>
#include <QScrollArea>

#ifdef USE_TABBED_LAYOUT
#include <QTabWidget>
#endif

MessageSender::MessageSender(QWidget *parent, Qt::WindowFlags flags)
    : QWidget(parent, flags),
      accountCombo(0),
      toEdit(0),
      subjectEdit(0),
      textEdit(0),
      sendButton(0),
      removeButton(0),
      addButton(0),
      attachmentsList(0)
{
    QVBoxLayout* vbl = new QVBoxLayout(this);
    vbl->setSpacing(0);
    vbl->setContentsMargins(0,0,0,0);

    QWidget* mainWidget = new QWidget(this);

    QScrollArea* sa = new QScrollArea(this);
    vbl->addWidget(sa);
    sa->setWidget(mainWidget);
    sa->setWidgetResizable(true);

    setWindowTitle(tr("Write Message"));

    accountCombo = new QComboBox;
    connect(accountCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(accountSelected(int)));

    toEdit = new QLineEdit;

    subjectEdit = new QLineEdit;

    QLabel *accountLabel = new QLabel(tr("Account"));
    accountLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    QLabel *toLabel = new QLabel(tr("To"));
    toLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    QLabel *subjectLabel = new QLabel(tr("Subject"));
    subjectLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    QGridLayout *metaDataLayout = new QGridLayout;
    metaDataLayout->setContentsMargins(0, 0, 0, 0);
    metaDataLayout->addWidget(accountLabel, 0, 0);
    metaDataLayout->setAlignment(accountLabel, Qt::AlignRight);
    metaDataLayout->addWidget(toLabel, 1, 0);
    metaDataLayout->setAlignment(toLabel, Qt::AlignRight);
    metaDataLayout->addWidget(subjectLabel, 2, 0);
    metaDataLayout->setAlignment(subjectLabel, Qt::AlignRight);
    metaDataLayout->addWidget(accountCombo, 0, 1);
    metaDataLayout->addWidget(toEdit, 1, 1);
    metaDataLayout->addWidget(subjectEdit, 2, 1);

    removeButton = new QPushButton(tr("Remove"));
    removeButton->setEnabled(false);

    connect(removeButton, SIGNAL(clicked()), this, SLOT(removeAttachment()));

    addButton = new QPushButton(tr("Add"));

    connect(addButton, SIGNAL(clicked()), this, SLOT(addAttachment()));

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->setContentsMargins(0, 0, 0, 0);
    buttonLayout->addWidget(addButton);
    buttonLayout->addWidget(removeButton);

    attachmentsList = new QListWidget;
    attachmentsList->setSelectionMode(QAbstractItemView::SingleSelection);

    connect(attachmentsList, SIGNAL(currentRowChanged(int)), this, SLOT(attachmentSelected(int)));

    QVBoxLayout *attachmentsLayout = new QVBoxLayout;
    attachmentsLayout->setContentsMargins(0, 0, 0, 0);
    attachmentsLayout->addWidget(attachmentsList);
    attachmentsLayout->addLayout(buttonLayout);

    QGroupBox *attachmentsGroup = new QGroupBox(tr("Attachments"));
    attachmentsGroup->setLayout(attachmentsLayout);
#ifdef Q_WS_MAEMO_5
    // Maemo 5 style doesn't take group box titles into account.
    int spacingHack = QFontMetrics(QFont()).height();
    attachmentsLayout->setContentsMargins(0, spacingHack, 0, 0);
#endif

    textEdit = new QTextEdit;

    sendButton = new QPushButton(tr("Send"));

    connect(sendButton, SIGNAL(clicked()), this, SLOT(send()), Qt::QueuedConnection);

#ifdef USE_TABBED_LAYOUT
    QTabWidget *tabWidget = new QTabWidget;
    tabWidget->addTab(textEdit, tr("Text"));
    tabWidget->addTab(attachmentsGroup, tr("Attachments"));
#endif

    QVBoxLayout *mainLayout = new QVBoxLayout(mainWidget);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->addLayout(metaDataLayout, 0);
#ifdef USE_TABBED_LAYOUT
    mainLayout->addWidget(tabWidget, 0);
#else
    mainLayout->addWidget(textEdit, 2);
    mainLayout->addWidget(attachmentsGroup, 1);
#endif
    mainLayout->addWidget(sendButton, 0);
    mainLayout->setAlignment(sendButton, Qt::AlignRight);

    connect(&service, SIGNAL(stateChanged(QMessageService::State)), this, SLOT(stateChanged(QMessageService::State)));

    QTimer::singleShot(0, this, SLOT(populateAccounts()));
    
    QWidgetList focusableWidgets;
    focusableWidgets << accountCombo
                     << toEdit
                     << subjectEdit
#ifdef USE_TABBED_LAYOUT
                     << tabWidget
#else
                     << textEdit
                     << attachmentsList
#endif
                     << addButton
                     << removeButton
                     << sendButton;

    foreach(QWidget* w, focusableWidgets)
        w->setContextMenuPolicy(Qt::NoContextMenu);

    accountCombo->setFocus();
}

MessageSender::~MessageSender()
{
}

void MessageSender::populateAccounts()
{
#ifndef _WIN32_WCE
    // How long can the accounts query take?
    setCursor(Qt::BusyCursor);
#endif

//! [accounts-listing]
    // Find the list of available accounts and add them to combo box
    foreach (const QMessageAccountId &id, manager.queryAccounts()) {
        QMessageAccount account(id);

        // What is the most capable message type supported by this account?
        QMessage::Type type(QMessage::NoType);
        if (account.messageTypes() & QMessage::Email) {
            type = QMessage::Email;
        } else if (account.messageTypes() & QMessage::Mms) {
            type = QMessage::Mms;
        } else if (account.messageTypes() & QMessage::Sms) {
            type = QMessage::Sms;
        }

        if (type != QMessage::NoType) {
            QString name(account.name());
            accountDetails.insert(name, qMakePair(type, account.id()));
            accountCombo->addItem(name);
        }
    }
//! [accounts-listing]

    if (accountDetails.isEmpty()) {
        QMessageBox::warning(0, tr("Cannot send"), tr("No accounts are available to send with!"));
        QCoreApplication::instance()->quit();
    } else {
        accountCombo->setCurrentIndex(0);
    }

#ifndef _WIN32_WCE
    setCursor(Qt::ArrowCursor);
#endif
}

void MessageSender::removeAttachment()
{
    delete attachmentsList->takeItem(attachmentsList->currentRow());
    if (attachmentsList->count() == 0) {
        removeButton->setEnabled(false);
    }
}

void MessageSender::addAttachment()
{
    QString path(QFileDialog::getOpenFileName());
    if (!path.isEmpty()) {
        attachmentsList->addItem(new QListWidgetItem(path));
    }
}

//! [account-selected]
void MessageSender::accountSelected(int index)
{
    QString name(accountCombo->itemText(index));
    if (!name.isEmpty()) {
        QPair<QMessage::Type, QMessageAccountId> details = accountDetails[name];

        // Enable subject only for email
        subjectEdit->setEnabled(details.first == QMessage::Email);

        // Disable attachments for SMS
        const bool smsOnly(details.first == QMessage::Sms);
        addButton->setEnabled(!smsOnly);
        removeButton->setEnabled(!smsOnly);
    }
}
//! [account-selected]

void MessageSender::attachmentSelected(int index)
{
    removeButton->setEnabled(index != -1);
}

void MessageSender::send()
{
//! [associate-account]
    QString accountName(accountCombo->currentText());
    if (accountName.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("No account is selected for transmission"));
        return;
    }

    QMessage message;

    QPair<QMessage::Type, QMessageAccountId> details = accountDetails[accountName];
    message.setType(details.first);
    message.setParentAccountId(details.second);
//! [associate-account]

//! [set-recipients]
    QString to(toEdit->text());
    if (to.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("Please enter a recipient address"));
        return;
    }

    // Find the address type to use for this message
    QMessageAddress::Type addrType(message.type() == QMessage::Email ? QMessageAddress::Email : QMessageAddress::Phone);

    QMessageAddressList toList;
    foreach (const QString &item, to.split(QRegExp("\\s"), QString::SkipEmptyParts)) {
        toList.append(QMessageAddress(addrType, item));
    }
    message.setTo(toList);
//! [set-recipients]

//! [set-properties]
    if (message.type() == QMessage::Email) {
        QString subject(subjectEdit->text());
        if (subject.isEmpty()) {
            QMessageBox::warning(0, tr("Missing information"), tr("Please enter a subject"));
            return;
        }
        message.setSubject(subject);
    }

    QString text(textEdit->toPlainText());
    if (text.isEmpty()) {
        QMessageBox::warning(0, tr("Missing information"), tr("Please enter a message"));
        return;
    }
    message.setBody(text);
//! [set-properties]

//! [add-attachments]
    if (message.type() != QMessage::Sms) {
        if (attachmentsList->count()) {
            QStringList paths;
            for (int i = 0; i < attachmentsList->count(); ++i) {
                paths.append(attachmentsList->item(i)->text());
            }

            message.appendAttachments(paths);
        }
    }
//! [add-attachments]

//! [send-message]
    sendButton->setEnabled(false);
    if (service.send(message)) {
        sendId = message.id();
    } else {
        sendButton->setEnabled(true);
        QMessageBox::warning(0, tr("Failed"), tr("Unable to send message"));
    }
//! [send-message]
}

//! [handle-response]
void MessageSender::stateChanged(QMessageService::State newState)
{
    if (newState == QMessageService::FinishedState) {
        if (service.error() == QMessageManager::NoError) {
            QMessageBox::information(0, tr("Success"), tr("Message sent successfully"));
        } else {
            QMessageBox::warning(0, tr("Failed"), tr("Unable to send message"));

            // Try to delete the failed message
            if (!manager.removeMessage(sendId)) {
                qWarning() << "Unable to remove failed message:" << sendId.toString();
            }
        }

        sendId = QMessageId();
        sendButton->setEnabled(true);
    }
}
//! [handle-response]