-
Notifications
You must be signed in to change notification settings - Fork 1
/
maindialog.cpp
421 lines (374 loc) · 15.1 KB
/
maindialog.cpp
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
////////////////////////////////////////////////////////////////////////////////
// Implementation of MainDialog
#include <QMessageBox>
#include <QFileDialog>
#include <QDropEvent>
#include <QMimeData>
#include <QLocale>
#include <QThread>
#include <QDir>
#include <QStandardPaths>
#include <QRegularExpression>
#include "common.h"
#include "mainapplication.h"
#include "maindialog.h"
#include "ui_maindialog.h"
#include "imagewriter.h"
#include "usbdevice.h"
MainDialog::MainDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MainDialog),
m_ImageFile(""),
m_ImageSize(0),
m_LastOpenedDir(""),
m_IsWriting(false),
m_EnumFlashDevicesWaiting(false),
m_ExtProgressBar(this)
{
#if defined(Q_OS_MAC)
// Quick hack for OS X to avoid hiding our main dialog when inactive
// The Qt::WA_MacAlwaysShowToolWindow attribute does not work (see QTBUG-29816)
void disableHideOnDeactivate(WId wid);
disableHideOnDeactivate(winId());
#endif
ui->setupUi(this);
// Remove the Context Help button and add the Minimize button to the titlebar
setWindowFlags((windowFlags() | Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint) & ~Qt::WindowContextHelpButtonHint);
// Disallow to change the dialog height
setFixedHeight(size().height());
// Start in the "idle" mode
hideWritingProgress();
// Change default open dir
m_LastOpenedDir = mApp->getInitialDir();
// Get path to ISO from command line (if supplied)
QString newImageFile = mApp->getInitialImage();
if (!newImageFile.isEmpty())
{
if (newImageFile.left(7) == "file://")
newImageFile = QUrl(newImageFile).toLocalFile();
if (newImageFile != "")
{
newImageFile = QDir(newImageFile).absolutePath();
// Update the default open dir
m_LastOpenedDir = newImageFile.left(newImageFile.lastIndexOf('/'));
preprocessImageFile(newImageFile);
}
}
// Load the list of USB flash disks
enumFlashDevices();
// TODO: Increase the dialog display speed by showing it with the empty list and enumerating devices
// in the background (dialog disabled, print "please wait")
// TODO: Use dialog disabling also for manual refreshing the list
}
MainDialog::~MainDialog()
{
cleanup();
delete ui;
}
// Retrieves information about the selected file and displays it in the dialog
void MainDialog::preprocessImageFile(const QString& newImageFile)
{
QFile f(newImageFile);
if (!f.open(QIODevice::ReadOnly))
{
QMessageBox::critical(
this,
ApplicationTitle,
tr("Failed to open the image file:") + "\n" +
QDir::toNativeSeparators(newImageFile) + "\n" +
f.errorString()
);
return;
}
m_ImageSize = f.size();
f.close();
m_ImageFile = newImageFile;
ui->imageEdit->setText(QDir::toNativeSeparators(m_ImageFile) + " (" + QString::number(alignNumberDiv(m_ImageSize, DEFAULT_UNIT)) + " " + tr("MB") + ")");
// Enable the Write button (if there are USB flash disks present)
ui->writeButton->setEnabled(ui->deviceList->count() > 0);
}
// Frees the GUI-specific allocated resources
void MainDialog::cleanup()
{
// Delete all the formerly allocated UsbDevice objects attached to the combobox entries
for (int i = 0; i < ui->deviceList->count(); ++i)
{
delete ui->deviceList->itemData(i).value<UsbDevice*>();
}
}
// The reimplemented dragEnterEvent to inform which incoming drag&drop events are acceptable
void MainDialog::dragEnterEvent(QDragEnterEvent* event)
{
// Accept only files with ANSI or Unicode paths (Windows) and URIs (Linux)
if (event->mimeData()->hasFormat("application/x-qt-windows-mime;value=\"FileName\"") ||
event->mimeData()->hasFormat("application/x-qt-windows-mime;value=\"FileNameW\"") ||
event->mimeData()->hasFormat("text/uri-list"))
event->accept();
}
// The reimplemented dropEvent to process the dropped file
void MainDialog::dropEvent(QDropEvent* event)
{
QString newImageFile = "";
QByteArray droppedFileName;
// First, try to use the Unicode file name
droppedFileName = event->mimeData()->data("application/x-qt-windows-mime;value=\"FileNameW\"");
if (!droppedFileName.isEmpty())
{
newImageFile = QString::fromWCharArray(reinterpret_cast<const wchar_t*>(droppedFileName.constData()));
}
else
{
// If failed, use the ANSI name with the local codepage
droppedFileName = event->mimeData()->data("application/x-qt-windows-mime;value=\"FileName\"");
if (!droppedFileName.isEmpty())
{
newImageFile = QString::fromLocal8Bit(droppedFileName.constData());
}
else
{
// And, finally, try the URI
droppedFileName = event->mimeData()->data("text/uri-list");
if (!droppedFileName.isEmpty())
{
// If several files are dropped they are separated by newlines,
// take the first file
int newLineIndexLF = droppedFileName.indexOf('\n');
int newLineIndex = droppedFileName.indexOf("\r\n");
// Make sure both CRLF and LF are accepted
if ((newLineIndexLF != -1) && (newLineIndexLF < newLineIndex))
newLineIndex = newLineIndexLF;
if (newLineIndex != -1)
droppedFileName = droppedFileName.left(newLineIndex);
// Decode the file path from percent-encoding
QUrl url = QUrl::fromEncoded(droppedFileName);
if (url.isLocalFile())
newImageFile = url.toLocalFile();
}
}
}
if (newImageFile != "")
{
// If something was realy received update the information
preprocessImageFile(newImageFile);
}
}
// The reimplemented keyPressEvent to display confirmation if user closes the dialog during operation
void MainDialog::closeEvent(QCloseEvent* event)
{
if (m_IsWriting)
{
if (QMessageBox::question(this, ApplicationTitle, tr("Writing is in progress, abort it?")) == QMessageBox::No)
event->ignore();
}
}
// The reimplemented keyPressEvent to display confirmation if Esc is pressed during operation
// (it normally closes the dialog but does not issue closeEvent for unknown reason)
void MainDialog::keyPressEvent(QKeyEvent* event)
{
if ((event->key() == Qt::Key_Escape) && m_IsWriting)
{
if (QMessageBox::question(this, ApplicationTitle, tr("Writing is in progress, abort it?")) == QMessageBox::No)
return;
}
QDialog::keyPressEvent(event);
}
// Suggests to select image file using the Open File dialog
void MainDialog::openImageFile()
{
QString newImageFile = QFileDialog::getOpenFileName(this, "", m_LastOpenedDir, tr("Disk Images") + " (*.iso *.bin *.img);;" + tr("All Files") + " (*.*)", NULL, QFileDialog::ReadOnly);
if (newImageFile != "")
{
m_LastOpenedDir = newImageFile.left(newImageFile.lastIndexOf('/'));
preprocessImageFile(newImageFile);
}
}
// Schedules reloading the list of USB flash disks to run when possible
void MainDialog::scheduleEnumFlashDevices()
{
if (m_IsWriting)
m_EnumFlashDevicesWaiting = true;
else
enumFlashDevices();
}
void addFlashDeviceCallback(void* cbParam, UsbDevice* device)
{
Ui::MainDialog* ui = (Ui::MainDialog*)cbParam;
ui->deviceList->addItem(device->formatDisplayName(), QVariant::fromValue(device));
}
// Reloads the list of USB flash disks
void MainDialog::enumFlashDevices()
{
// Remember the currently selected device
QString selectedDevice = "";
int idx = ui->deviceList->currentIndex();
if (idx >= 0)
{
UsbDevice* dev = ui->deviceList->itemData(idx).value<UsbDevice*>();
selectedDevice = dev->m_PhysicalDevice;
}
// Remove the existing entries
cleanup();
ui->deviceList->clear();
// Disable the combobox
// TODO: Disable the whole dialog
ui->deviceList->setEnabled(false);
platformEnumFlashDevices(addFlashDeviceCallback, ui);
// Restore the previously selected device (if present)
if (selectedDevice != "")
for (int i = 0; i < ui->deviceList->count(); ++i)
{
UsbDevice* dev = ui->deviceList->itemData(i).value<UsbDevice*>();
if (dev->m_PhysicalDevice == selectedDevice)
{
ui->deviceList->setCurrentIndex(i);
break;
}
}
// Reenable the combobox
ui->deviceList->setEnabled(true);
// Update the Write button enabled/disabled state
ui->writeButton->setEnabled((ui->deviceList->count() > 0) && (m_ImageFile != ""));
// Update the Clear button enabled/disabled state
ui->clearButton->setEnabled(ui->deviceList->count() > 0);
}
// Starts writing data to the device
void MainDialog::writeToDevice(bool zeroing)
{
if ((ui->deviceList->count() == 0) || (!zeroing && (m_ImageFile == "")))
return;
UsbDevice* selectedDevice = ui->deviceList->itemData(ui->deviceList->currentIndex()).value<UsbDevice*>();
if (!zeroing && (m_ImageSize > selectedDevice->m_Size))
{
QLocale currentLocale;
QMessageBox::critical(
this,
ApplicationTitle,
tr("The image is larger than your selected device!") + "\n" +
tr("Image size:") + " " + QString::number(m_ImageSize / DEFAULT_UNIT) + " " + tr("MB") + " (" + currentLocale.toString(m_ImageSize) + " " + tr("b") + ")\n" +
tr("Disk size:") + " " + QString::number(selectedDevice->m_Size / DEFAULT_UNIT) + " " + tr("MB") + " (" + currentLocale.toString(selectedDevice->m_Size) + " " + tr("b") + ")",
QMessageBox::Ok
);
return;
}
if (QMessageBox::warning(
this,
ApplicationTitle,
"<font color=\"red\">" + tr("Warning!") + "</font> " + tr("All existing data on the selected device will be lost!") + "<br>" +
tr("Are you sure you wish to proceed?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No) == QMessageBox::No)
return;
showWritingProgress(alignNumberDiv((zeroing ? DEFAULT_UNIT : m_ImageSize), DEFAULT_UNIT));
ImageWriter* writer = new ImageWriter(zeroing ? "" : m_ImageFile, selectedDevice);
QThread *writerThread = new QThread(this);
// Connect start and end signals
connect(writerThread, &QThread::started, writer, &ImageWriter::writeImage);
// When writer finishes its job, quit the thread
connect(writer, &ImageWriter::finished, writerThread, &QThread::quit);
// Guarantee deleting the objects after completion
connect(writer, &ImageWriter::finished, writer, &ImageWriter::deleteLater);
connect(writerThread, &QThread::finished, writerThread, &QThread::deleteLater);
// If the Cancel button is pressed, inform the writer to stop the operation
// Using DirectConnection because the thread does not read its own event queue until completion
connect(ui->cancelButton, &QPushButton::clicked, writer, &ImageWriter::cancelWriting, Qt::DirectConnection);
// Each time a block is written, update the progress bar
connect(writer, &ImageWriter::blockWritten, this, &MainDialog::updateProgressBar);
// Show the message about successful completion on success
connect(writer, &ImageWriter::success, this, &MainDialog::showSuccessMessage);
// Show error message if error is sent by the worker
connect(writer, &ImageWriter::error, this, &MainDialog::showErrorMessage);
// Silently return back to normal dialog form if the operation was cancelled
connect(writer, &ImageWriter::cancelled, this, &MainDialog::hideWritingProgress);
// Now start the writer thread
writer->moveToThread(writerThread);
writerThread->start();
}
// Starts writing the image
void MainDialog::writeImageToDevice()
{
writeToDevice(false);
}
// Clears the selected USB device
void MainDialog::clearDevice()
{
writeToDevice(true);
}
// Updates GUI to the "writing" mode (progress bar shown, controls disabled)
// Also sets the progress bar limits
void MainDialog::showWritingProgress(int maxValue)
{
m_IsWriting = true;
// Do not accept dropped files while writing
setAcceptDrops(false);
// Disable the main interface
ui->imageLabel->setEnabled(false);
ui->imageEdit->setEnabled(false);
ui->imageSelectButton->setEnabled(false);
ui->deviceLabel->setEnabled(false);
ui->deviceList->setEnabled(false);
ui->deviceRefreshButton->setEnabled(false);
// Display and customize the progress bar part
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(maxValue);
ui->progressBar->setValue(0);
ui->progressBar->setVisible(true);
ui->progressBarSpacer->changeSize(0, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);
ui->writeButton->setVisible(false);
ui->clearButton->setVisible(false);
ui->cancelButton->setVisible(true);
// Expose the progress bar state to the OS
m_ExtProgressBar.InitProgressBar(maxValue);
}
// Updates GUI to the "idle" mode (progress bar hidden, controls enabled)
void MainDialog::hideWritingProgress()
{
m_IsWriting = false;
// Reenable drag&drop
setAcceptDrops(true);
// Enable the main interface
ui->imageLabel->setEnabled(true);
ui->imageEdit->setEnabled(true);
ui->imageSelectButton->setEnabled(true);
ui->deviceLabel->setEnabled(true);
ui->deviceList->setEnabled(true);
ui->deviceRefreshButton->setEnabled(true);
// Hide the progress bar
ui->progressBar->setVisible(false);
ui->progressBarSpacer->changeSize(10, 10, QSizePolicy::Expanding, QSizePolicy::Fixed);
ui->writeButton->setVisible(true);
ui->clearButton->setVisible(true);
ui->cancelButton->setVisible(false);
// Send a signal that progressbar is no longer present
m_ExtProgressBar.DestroyProgressBar();
// If device list changed during writing update it now
if (m_EnumFlashDevicesWaiting)
enumFlashDevices();
}
// Increments the progress bar counter by the specified number
void MainDialog::updateProgressBar(int increment)
{
int newValue = ui->progressBar->value() + increment;
ui->progressBar->setValue(newValue);
m_ExtProgressBar.SetProgressValue(newValue);
}
// Displays the message about successful completion and returns to the "idle" mode
void MainDialog::showSuccessMessage(QString msg)
{
QMessageBox::information(
this,
ApplicationTitle,
msg
);
hideWritingProgress();
}
// Displays the specified error message and returns to the "idle" mode
void MainDialog::showErrorMessage(QString msg)
{
m_ExtProgressBar.ProgressSetError();
QMessageBox::critical(
this,
ApplicationTitle,
msg
);
hideWritingProgress();
}