Unity 8
PromptsModel.cpp
1 /*
2  * Copyright (C) 2017 Canonical, Ltd.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 3.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program. If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17 
18 #include "PromptsModel.h"
19 
20 PromptsModel::PromptsModel(QObject* parent)
21  : QAbstractListModel(parent)
22 {
23  m_roleNames[TypeRole] = "type";
24  m_roleNames[TextRole] = "text";
25 }
26 
27 PromptsModel& PromptsModel::operator=(const PromptsModel &other)
28 {
29  beginResetModel();
30  m_prompts = other.m_prompts;
31  endResetModel();
32  Q_EMIT countChanged();
33  return *this;
34 }
35 
36 int PromptsModel::rowCount(const QModelIndex &parent) const
37 {
38  if (parent.isValid())
39  return 0;
40 
41  return m_prompts.size();
42 }
43 
44 QVariant PromptsModel::data(const QModelIndex &index, int role) const
45 {
46  if (!index.isValid() || index.column() > 0 || index.row() >= m_prompts.size())
47  return QVariant();
48 
49  switch (role) {
50  case Qt::DisplayRole: // fallthrough
51  case TextRole: return m_prompts[index.row()].prompt;
52  case TypeRole: return m_prompts[index.row()].type;
53  default: return QVariant();
54  }
55 }
56 
57 QHash<int, QByteArray> PromptsModel::roleNames() const
58 {
59  return m_roleNames;
60 }
61 
62 void PromptsModel::prepend(const QString &text, PromptType type)
63 {
64  beginInsertRows(QModelIndex(), 0, 0);
65  m_prompts.prepend(PromptInfo{text, type});
66  endInsertRows();
67 
68  Q_EMIT countChanged();
69 }
70 
71 void PromptsModel::append(const QString &text, PromptType type)
72 {
73  beginInsertRows(QModelIndex(), m_prompts.size(), m_prompts.size());
74  m_prompts.append(PromptInfo{text, type});
75  endInsertRows();
76 
77  Q_EMIT countChanged();
78 }
79 
80 void PromptsModel::clear()
81 {
82  beginResetModel();
83  m_prompts.clear();
84  endResetModel();
85 
86  Q_EMIT countChanged();
87 }
88 
89 bool PromptsModel::hasPrompt() const
90 {
91  Q_FOREACH(const PromptInfo &info, m_prompts) {
92  if (info.type == PromptType::Secret || info.type == PromptType::Question) {
93  return true;
94  }
95  }
96  return false;
97 }