File: Directory.cpp

package info (click to toggle)
wsjtx 2.3.0%2Brepack-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 63,524 kB
  • sloc: cpp: 59,051; f90: 34,130; python: 27,241; ansic: 11,205; fortran: 2,051; sh: 132; makefile: 109
file content (319 lines) | stat: -rw-r--r-- 11,036 bytes parent folder | download
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
#include "Directory.hpp"

#include <QVariant>
#include <QString>
#include <QHeaderView>
#include <QStringList>
#include <QFileInfo>
#include <QDir>
#include <QNetworkAccessManager>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QTreeWidgetItem>
#include <QTreeWidgetItemIterator>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonArray>
#include <QJsonObject>
#include <QRegularExpression>

#include "Configuration.hpp"
#include "DirectoryNode.hpp"
#include "FileNode.hpp"
#include "revision_utils.hpp"
#include "widgets/MessageBox.hpp"

#include "moc_Directory.cpp"

namespace
{
  char const * samples_dir_name = "samples";
  QString const contents_file_name = "contents_" + version (false) + ".json";
}

Directory::Directory (Configuration const * configuration
                      , QNetworkAccessManager * network_manager
                      , QWidget * parent)
  : QTreeWidget {parent}
  , configuration_ {configuration}
  , network_manager_ {network_manager}
  , http_only_ {false}
  , root_dir_ {configuration_->save_directory ()}
  , contents_ {this
        , network_manager_
        , QDir {root_dir_.absoluteFilePath (samples_dir_name)}.absoluteFilePath (contents_file_name)}
{
  dir_icon_.addPixmap (style ()->standardPixmap (QStyle::SP_DirClosedIcon), QIcon::Normal, QIcon::Off);
  dir_icon_.addPixmap (style ()->standardPixmap (QStyle::SP_DirOpenIcon), QIcon::Normal, QIcon::On);
  file_icon_.addPixmap (style ()->standardPixmap (QStyle::SP_FileIcon));

  setColumnCount (2);
  setHeaderLabels ({tr ("File"), tr ("Progress")});
  header ()->setSectionResizeMode (QHeaderView::ResizeToContents);
  setItemDelegate (&item_delegate_);

  connect (network_manager_, &QNetworkAccessManager::authenticationRequired
           , this, &Directory::authentication);
  connect (this, &Directory::itemChanged, [] (QTreeWidgetItem * item) {
      switch (item->type ())
        {
        case FileNode::Type:
          {
            FileNode * node = static_cast<FileNode *> (item);
            if (!node->sync (node->checkState (0) == Qt::Checked))
              {
                FileNode::sync_blocker b {node};
                node->setCheckState (0, node->checkState (0) == Qt::Checked ? Qt::Unchecked : Qt::Checked);
              }
          }
          break;

        default:
          break;
        }
    });
}

bool Directory::url_root (QUrl root)
{
  if (!root.path ().endsWith ('/'))
    {
      root.setPath (root.path () + '/');
    }
  bool valid = root.isValid ();
  if (valid)
    {
      url_root_ = root;
    }
  return valid;
}

void Directory::error (QString const& title, QString const& message)
{
  MessageBox::warning_message (this, title, message);
}

bool Directory::refresh (bool http_only)
{
  abort ();
  clear ();
  // update locations
  root_dir_ = configuration_->save_directory ();
  QDir contents_dir {root_dir_.absoluteFilePath (samples_dir_name)};
  contents_.local_file_path (contents_dir.absoluteFilePath (contents_file_name));
  contents_.http_only (http_only_ = http_only);
  QUrl url {url_root_.resolved (QDir {root_dir_.relativeFilePath (samples_dir_name)}.filePath (contents_file_name))};
  if (url.isValid ())
    {
      return contents_.sync (url, true, true); // attempt to fetch contents
    }
  else
    {
      MessageBox::warning_message (this
                                   , tr ("URL Error")
                                   , tr ("Invalid URL:\n\"%1\"")
                                   .arg (url.toDisplayString ()));
    }
  return false;
}

void Directory::download_finished (bool success)
{
  if (success)
    {
      QFile contents {contents_.local_file_path ()};
      if (contents.open (QFile::ReadOnly | QFile::Text))
        {
          QJsonParseError json_status;
          auto content = QJsonDocument::fromJson (contents.readAll (), &json_status);
          if (json_status.error)
            {
              MessageBox::warning_message (this
                                           , tr ("JSON Error")
                                           , tr ("Contents file syntax error %1 at character offset %2")
                                           .arg (json_status.errorString ()).arg (json_status.offset));
              return;
            }
          if (!content.isArray ())
            {
              MessageBox::warning_message (this, tr ("JSON Error")
                                           , tr ("Contents file top level must be a JSON array"));
              return;
            }
          QTreeWidgetItem * parent {invisibleRootItem ()};
          parent = new DirectoryNode {parent, samples_dir_name};
          parent->setIcon (0, dir_icon_);
          parent->setExpanded (true);
          parse_entries (content.array (), root_dir_.relativeFilePath (samples_dir_name), parent);
        }
      else
        {
          MessageBox::warning_message (this, tr ("File System Error")
                                       , tr ("Failed to open \"%1\"\nError: %2 - %3")
                                       .arg (contents.fileName ())
                                       .arg (contents.error ())
                                       .arg (contents.errorString ()));
        }
    }
}

void Directory::parse_entries (QJsonArray const& entries, QDir const& dir, QTreeWidgetItem * parent)
{
  if (dir.isRelative () && !dir.path ().startsWith ('.'))
    {
      for (auto const& value: entries)
        {
          if (value.isObject ())
            {
              auto const& entry = value.toObject ();
              auto const& name = entry["name"].toString ();
              if (name.size () && !name.contains (QRegularExpression {R"([/:;])"}))
                {
                  auto const& type = entry["type"].toString ();
                  if ("file" == type)
                    {
                      QUrl url {url_root_.resolved (dir.filePath (name))};
                      if (url.isValid ())
                        {
                          auto node = new FileNode {parent, network_manager_
                                                    , QDir {root_dir_.filePath (dir.path ())}.absoluteFilePath (name)
                                                    , url, http_only_};
                          FileNode::sync_blocker b {node};
                          node->setIcon (0, file_icon_);
                          node->setCheckState (0, node->local () ? Qt::Checked : Qt::Unchecked);
                          update (parent);
                        }
                      else
                        {
                          MessageBox::warning_message (this
                                                       , tr ("URL Error")
                                                       , tr ("Invalid URL:\n\"%1\"")
                                                       .arg (url.toDisplayString ()));
                        }
                    }
                  else if ("directory" == type)
                    {
                          auto node = new DirectoryNode {parent, name};
                          node->setIcon (0, dir_icon_);
                          auto const& entries = entry["entries"];
                          if (entries.isArray ())
                            {
                              parse_entries (entries.toArray ()
                                             , QDir {root_dir_.relativeFilePath (dir.path ())}.filePath (name)
                                             , node);
                            }
                          else
                            {
                              MessageBox::warning_message (this, tr ("JSON Error")
                                                           , tr ("Contents entries must be a JSON array"));
                            }
                    }
                  else
                    {
                      MessageBox::warning_message (this, tr ("JSON Error")
                                                   , tr ("Contents entries must have a valid type"));
                    }
                }
              else
                {
                  MessageBox::warning_message (this, tr ("JSON Error")
                                               , tr ("Contents entries must have a valid name"));
                }
            }
          else
            {
              MessageBox::warning_message (this, tr ("JSON Error")
                                           , tr ("Contents entries must be JSON objects"));
            }
        }
    }
  else
    {
      MessageBox::warning_message (this, tr ("JSON Error")
                                   , tr ("Contents directories must be relative and within \"%1\"")
                                   .arg (samples_dir_name));
    }
}

void Directory::abort ()
{
  QTreeWidgetItemIterator iter {this};
  while (*iter)
    {
      if ((*iter)->type () == FileNode::Type)
        {
          auto * node = static_cast<FileNode *> (*iter);
          node->abort ();
        }
      ++iter;
    }
}

namespace
{
  //
  // traverse the passed subtree accumulating the number of items, the
  // number we have size data for, the bytes downloaded so far and the
  // maximum bytes to expect
  //
  int recurse_children (QTreeWidgetItem const * item, int * counted
                        , qint64 * bytes, qint64 * max)
  {
    int items {0};
    for (int index {0}; index < item->childCount (); ++index)
      {
        auto const * child = item->child (index);
        if (child->type () == FileNode::Type)  // only count files
          {
            ++items;
            if (auto size = child->data (1, Qt::UserRole).toLongLong ())
              {
                *max += size;
                ++*counted;
              }
            *bytes += child->data (1, Qt::DisplayRole).toLongLong ();
          }
        else
          {
            // recurse into sub-directory subtrees
            items += recurse_children (child, counted, bytes, max);
          }
      }
    return items;
  }
}

void Directory::update (QTreeWidgetItem * item)
{
  // iterate the tree under item and accumulate the progress
  if (item)
    {
      Q_ASSERT (item->type () == DirectoryNode::Type);
      qint64 max {0};
      qint64 bytes {0};
      int counted {0};

      // get the count, progress and size of children
      int items {recurse_children (item, &counted, &bytes, &max)};

      // estimate size of items not yet downloaded as average of
      // those actually present
      if (counted)
        {
          max += (items - counted) * max / counted;
        }

      // save as our progress
      item->setData (1, Qt::UserRole, max);
      item->setData (1, Qt::DisplayRole, bytes);

      // recurse up to top
      update (item->parent ());
    }
}

void Directory::authentication (QNetworkReply * /* reply */
                                , QAuthenticator * /* authenticator */)
{
  MessageBox::warning_message (this, tr ("Network Error"), tr ("Authentication required"));
}