forked from shadowsocks/shadowsocks-qt5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainwindow.cpp
616 lines (552 loc) · 21.3 KB
/
mainwindow.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "connection.h"
#include "editdialog.h"
#include "urihelper.h"
#include "uriinputdialog.h"
#include "sharedialog.h"
#include "logdialog.h"
#include "settingsdialog.h"
#include "qrcodecapturer.h"
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QMessageBox>
#include <QCloseEvent>
#include <QLocalSocket>
#include <botan/version.h>
MainWindow::MainWindow(ConfigHelper *confHelper, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
configHelper(confHelper)
{
Q_ASSERT(configHelper);
initSingleInstance();
ui->setupUi(this);
//setup Settings menu
#ifndef Q_OS_DARWIN
ui->menuSettings->addAction(ui->toolBar->toggleViewAction());
#endif
//initialisation
model = new ConnectionTableModel(this);
configHelper->read(model);
proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);
proxyModel->setSortRole(Qt::EditRole);
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxyModel->setFilterKeyColumn(-1);//read from all columns
ui->connectionView->setModel(proxyModel);
ui->toolBar->setToolButtonStyle(static_cast<Qt::ToolButtonStyle>
(configHelper->getToolbarStyle()));
setupActionIcon();
notifier = new StatusNotifier(this, configHelper->isHideWindowOnStartup(), this);
connect(configHelper, &ConfigHelper::toolbarStyleChanged,
ui->toolBar, &QToolBar::setToolButtonStyle);
connect(model, &ConnectionTableModel::message,
notifier, &StatusNotifier::showNotification);
connect(model, &ConnectionTableModel::rowStatusChanged,
this, &MainWindow::onConnectionStatusChanged);
connect(ui->actionSaveManually, &QAction::triggered,
this, &MainWindow::onSaveManually);
connect(ui->actionTestAllLatency, &QAction::triggered,
model, &ConnectionTableModel::testAllLatency);
//some UI changes accoding to config
ui->toolBar->setVisible(configHelper->isShowToolbar());
ui->actionShowFilterBar->setChecked(configHelper->isShowFilterBar());
ui->menuBar->setNativeMenuBar(configHelper->isNativeMenuBar());
//Move to the center of the screen
this->move(QApplication::desktop()->screen()->rect().center() -
this->rect().center());
//UI signals
connect(ui->actionImportGUIJson, &QAction::triggered,
this, &MainWindow::onImportGuiJson);
connect(ui->actionExportGUIJson, &QAction::triggered,
this, &MainWindow::onExportGuiJson);
connect(ui->actionQuit, &QAction::triggered, qApp, &QApplication::quit);
connect(ui->actionManually, &QAction::triggered,
this, &MainWindow::onAddManually);
connect(ui->actionQRCode, &QAction::triggered,
this, &MainWindow::onAddScreenQRCode);
connect(ui->actionScanQRCodeCapturer, &QAction::triggered,
this, &MainWindow::onAddScreenQRCodeCapturer);
connect(ui->actionQRCodeFromFile, &QAction::triggered,
this, &MainWindow::onAddQRCodeFile);
connect(ui->actionURI, &QAction::triggered,
this, &MainWindow::onAddFromURI);
connect(ui->actionFromConfigJson, &QAction::triggered,
this, &MainWindow::onAddFromConfigJSON);
connect(ui->actionDelete, &QAction::triggered, this, &MainWindow::onDelete);
connect(ui->actionEdit, &QAction::triggered, this, &MainWindow::onEdit);
connect(ui->actionShare, &QAction::triggered, this, &MainWindow::onShare);
connect(ui->actionConnect, &QAction::triggered,
this, &MainWindow::onConnect);
connect(ui->actionForceConnect, &QAction::triggered,
this, &MainWindow::onForceConnect);
connect(ui->actionDisconnect, &QAction::triggered,
this, &MainWindow::onDisconnect);
connect(ui->actionTestLatency, &QAction::triggered,
this, &MainWindow::onLatencyTest);
connect(ui->actionViewLog, &QAction::triggered,
this, &MainWindow::onViewLog);
connect(ui->actionMoveUp, &QAction::triggered, this, &MainWindow::onMoveUp);
connect(ui->actionMoveDown, &QAction::triggered,
this, &MainWindow::onMoveDown);
connect(ui->actionGeneralSettings, &QAction::triggered,
this, &MainWindow::onGeneralSettings);
connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::onAbout);
connect(ui->actionAboutQt, &QAction::triggered,
qApp, &QApplication::aboutQt);
connect(ui->actionReportBug, &QAction::triggered,
this, &MainWindow::onReportBug);
connect(ui->actionShowFilterBar, &QAction::toggled,
configHelper, &ConfigHelper::setShowFilterBar);
connect(ui->actionShowFilterBar, &QAction::toggled,
this, &MainWindow::onFilterToggled);
connect(ui->toolBar, &QToolBar::visibilityChanged,
configHelper, &ConfigHelper::setShowToolbar);
connect(ui->filterLineEdit, &QLineEdit::textChanged,
this, &MainWindow::onFilterTextChanged);
connect(ui->connectionView, &QTableView::clicked,
this, static_cast<void (MainWindow::*)(const QModelIndex&)>
(&MainWindow::checkCurrentIndex));
connect(ui->connectionView, &QTableView::activated,
this, static_cast<void (MainWindow::*)(const QModelIndex&)>
(&MainWindow::checkCurrentIndex));
connect(ui->connectionView, &QTableView::doubleClicked,
this, &MainWindow::onEdit);
/* set custom context menu */
ui->connectionView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->connectionView, &QTableView::customContextMenuRequested,
this, &MainWindow::onCustomContextMenuRequested);
checkCurrentIndex();
// Restore mainWindow's geometry and state
restoreGeometry(configHelper->getMainWindowGeometry());
restoreState(configHelper->getMainWindowState());
ui->connectionView->horizontalHeader()->restoreGeometry(configHelper->getTableGeometry());
ui->connectionView->horizontalHeader()->restoreState(configHelper->getTableState());
}
MainWindow::~MainWindow()
{
configHelper->save(*model);
configHelper->setTableGeometry(ui->connectionView->horizontalHeader()->saveGeometry());
configHelper->setTableState(ui->connectionView->horizontalHeader()->saveState());
configHelper->setMainWindowGeometry(saveGeometry());
configHelper->setMainWindowState(saveState());
// delete ui after everything in case it's deleted while still needed for
// the functions written above
delete ui;
}
const QUrl MainWindow::issueUrl =
QUrl("https://github.com/shadowsocks/shadowsocks-qt5/issues");
void MainWindow::startAutoStartConnections()
{
configHelper->startAllAutoStart(*model);
}
void MainWindow::onImportGuiJson()
{
QString file = QFileDialog::getOpenFileName(
this,
tr("Import Connections from gui-config.json"),
QString(),
"GUI Configuration (gui-config.json)");
if (!file.isNull()) {
configHelper->importGuiConfigJson(model, file);
}
}
void MainWindow::onExportGuiJson()
{
QString file = QFileDialog::getSaveFileName(
this,
tr("Export Connections as gui-config.json"),
QString("gui-config.json"),
"GUI Configuration (gui-config.json)");
if (!file.isNull()) {
configHelper->exportGuiConfigJson(*model, file);
}
}
void MainWindow::onSaveManually()
{
configHelper->save(*model);
}
void MainWindow::onAddManually()
{
Connection *newCon = new Connection;
newProfile(newCon);
}
void MainWindow::onAddScreenQRCode()
{
QString uri = QRCodeCapturer::scanEntireScreen();
if (uri.isNull()) {
QMessageBox::critical(
this,
tr("QR Code Not Found"),
tr("Can't find any QR code image that contains "
"valid URI on your screen(s)."));
} else {
Connection *newCon = new Connection(uri, this);
newProfile(newCon);
}
}
void MainWindow::onAddScreenQRCodeCapturer()
{
QRCodeCapturer *capturer = new QRCodeCapturer(this);
connect(capturer, &QRCodeCapturer::closed,
capturer, &QRCodeCapturer::deleteLater);
connect(capturer, &QRCodeCapturer::qrCodeFound,
this, &MainWindow::onQRCodeCapturerResultFound,
Qt::DirectConnection);
capturer->show();
}
void MainWindow::onAddQRCodeFile()
{
QString qrFile =
QFileDialog::getOpenFileName(this,
tr("Open QR Code Image File"),
QString(),
"Images (*.png *jpg *jpeg *xpm)");
if (!qrFile.isNull()) {
QImage img(qrFile);
QString uri = URIHelper::decodeImage(img);
if (uri.isNull()) {
QMessageBox::critical(this,
tr("QR Code Not Found"),
tr("Can't find any QR code image that "
"contains valid URI on your screen(s)."));
} else {
Connection *newCon = new Connection(uri, this);
newProfile(newCon);
}
}
}
void MainWindow::onAddFromURI()
{
URIInputDialog *inputDlg = new URIInputDialog(this);
connect(inputDlg, &URIInputDialog::finished,
inputDlg, &URIInputDialog::deleteLater);
connect(inputDlg, &URIInputDialog::acceptedURI, [&](const QString &uri){
Connection *newCon = new Connection(uri, this);
newProfile(newCon);
});
inputDlg->exec();
}
void MainWindow::onAddFromConfigJSON()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open config.json"),
QString(), "JSON (*.json)");
if (!file.isNull()) {
Connection *con = configHelper->configJsonToConnection(file);
if (con) {
newProfile(con);
}
}
}
void MainWindow::onDelete()
{
if (model->removeRow(proxyModel->mapToSource(
ui->connectionView->currentIndex()).row())) {
configHelper->save(*model);
}
checkCurrentIndex();
}
void MainWindow::onEdit()
{
editRow(proxyModel->mapToSource(ui->connectionView->currentIndex()).row());
}
void MainWindow::onShare()
{
QByteArray uri = model->getItem(
proxyModel->mapToSource(ui->connectionView->currentIndex()).
row())->getConnection()->getURI();
ShareDialog *shareDlg = new ShareDialog(uri, this);
connect(shareDlg, &ShareDialog::finished,
shareDlg, &ShareDialog::deleteLater);
shareDlg->exec();
}
void MainWindow::onConnect()
{
int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row();
Connection *con = model->getItem(row)->getConnection();
if (con->isValid()) {
con->start();
} else {
QMessageBox::critical(this, tr("Invalid"),
tr("The connection's profile is invalid!"));
}
}
void MainWindow::onForceConnect()
{
int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row();
Connection *con = model->getItem(row)->getConnection();
if (con->isValid()) {
model->disconnectConnectionsAt(con->getProfile().localAddress,
con->getProfile().localPort);
con->start();
} else {
QMessageBox::critical(this, tr("Invalid"),
tr("The connection's profile is invalid!"));
}
}
void MainWindow::onDisconnect()
{
int row = proxyModel->mapToSource(ui->connectionView->currentIndex()).row();
model->getItem(row)->getConnection()->stop();
}
void MainWindow::onConnectionStatusChanged(const int row, const bool running)
{
if (proxyModel->mapToSource(
ui->connectionView->currentIndex()).row() == row) {
ui->actionConnect->setEnabled(!running);
ui->actionDisconnect->setEnabled(running);
}
}
void MainWindow::onLatencyTest()
{
model->getItem(proxyModel->mapToSource(ui->connectionView->currentIndex()).
row())->testLatency();
}
void MainWindow::onViewLog()
{
Connection *con = model->getItem(
proxyModel->mapToSource(ui->connectionView->currentIndex()).
row())->getConnection();
LogDialog *logDlg = new LogDialog(con, this);
connect(logDlg, &LogDialog::finished, logDlg, &LogDialog::deleteLater);
logDlg->exec();
}
void MainWindow::onMoveUp()
{
QModelIndex proxyIndex = ui->connectionView->currentIndex();
int currentRow = proxyModel->mapToSource(proxyIndex).row();
int targetRow = proxyModel->mapToSource(
proxyModel->index(proxyIndex.row() - 1,
proxyIndex.column(),
proxyIndex.parent())
).row();
model->move(currentRow, targetRow);
checkCurrentIndex();
}
void MainWindow::onMoveDown()
{
QModelIndex proxyIndex = ui->connectionView->currentIndex();
int currentRow = proxyModel->mapToSource(proxyIndex).row();
int targetRow = proxyModel->mapToSource(
proxyModel->index(proxyIndex.row() + 1,
proxyIndex.column(),
proxyIndex.parent())
).row();
model->move(currentRow, targetRow);
checkCurrentIndex();
}
void MainWindow::onGeneralSettings()
{
SettingsDialog *sDlg = new SettingsDialog(configHelper, this);
connect(sDlg, &SettingsDialog::finished,
sDlg, &SettingsDialog::deleteLater);
if (sDlg->exec()) {
configHelper->save(*model);
configHelper->setStartAtLogin();
}
}
void MainWindow::newProfile(Connection *newCon)
{
EditDialog *editDlg = new EditDialog(newCon, this);
connect(editDlg, &EditDialog::finished, editDlg, &EditDialog::deleteLater);
if (editDlg->exec()) {//accepted
model->appendConnection(newCon);
configHelper->save(*model);
} else {
newCon->deleteLater();
}
}
void MainWindow::editRow(int row)
{
Connection *con = model->getItem(row)->getConnection();
EditDialog *editDlg = new EditDialog(con, this);
connect(editDlg, &EditDialog::finished, editDlg, &EditDialog::deleteLater);
if (editDlg->exec()) {
configHelper->save(*model);
}
}
void MainWindow::checkCurrentIndex()
{
checkCurrentIndex(ui->connectionView->currentIndex());
}
void MainWindow::checkCurrentIndex(const QModelIndex &_index)
{
QModelIndex index = proxyModel->mapToSource(_index);
const bool valid = index.isValid();
ui->actionTestLatency->setEnabled(valid);
ui->actionEdit->setEnabled(valid);
ui->actionDelete->setEnabled(valid);
ui->actionShare->setEnabled(valid);
ui->actionViewLog->setEnabled(valid);
ui->actionMoveUp->setEnabled(valid ? _index.row() > 0 : false);
ui->actionMoveDown->setEnabled(valid ?
_index.row() < model->rowCount() - 1 :
false);
if (valid) {
const bool &running =
model->getItem(index.row())->getConnection()->isRunning();
ui->actionConnect->setEnabled(!running);
ui->actionForceConnect->setEnabled(!running);
ui->actionDisconnect->setEnabled(running);
} else {
ui->actionConnect->setEnabled(false);
ui->actionForceConnect->setEnabled(false);
ui->actionDisconnect->setEnabled(false);
}
}
void MainWindow::onAbout()
{
QString text = QString("<h1>Shadowsocks-Qt5</h1><p><b>Version %1</b><br />"
"Using libQtShadowsocks %2<br />"
"Using Botan %3.%4.%5</p>"
"<p>Copyright © 2014-2016 Symeon Huang "
"(<a href='https://twitter.com/librehat'>"
"@librehat</a>)</p>"
"<p>License: <a href='http://www.gnu.org/licenses/lgpl.html'>"
"GNU Lesser General Public License Version 3</a><br />"
"Project Hosted at "
"<a href='https://github.com/shadowsocks/shadowsocks-qt5'>"
"GitHub</a></p>")
.arg(QStringLiteral(APP_VERSION))
.arg(QSS::Common::version().data())
.arg(Botan::version_major())
.arg(Botan::version_minor())
.arg(Botan::version_patch());
QMessageBox::about(this, tr("About"), text);
}
void MainWindow::onReportBug()
{
QDesktopServices::openUrl(issueUrl);
}
void MainWindow::onCustomContextMenuRequested(const QPoint &pos)
{
this->checkCurrentIndex(ui->connectionView->indexAt(pos));
ui->menuConnection->popup(ui->connectionView->viewport()->mapToGlobal(pos));
}
void MainWindow::onFilterToggled(bool show)
{
if (show) {
ui->filterLineEdit->setFocus();
}
}
void MainWindow::onFilterTextChanged(const QString &text)
{
proxyModel->setFilterWildcard(text);
}
void MainWindow::onQRCodeCapturerResultFound(const QString &uri)
{
QRCodeCapturer* capturer = qobject_cast<QRCodeCapturer*>(sender());
// Disconnect immediately to avoid duplicate signals
disconnect(capturer, &QRCodeCapturer::qrCodeFound,
this, &MainWindow::onQRCodeCapturerResultFound);
Connection *newCon = new Connection(uri, this);
newProfile(newCon);
}
void MainWindow::hideEvent(QHideEvent *e)
{
QMainWindow::hideEvent(e);
notifier->onWindowVisibleChanged(false);
}
void MainWindow::showEvent(QShowEvent *e)
{
QMainWindow::showEvent(e);
notifier->onWindowVisibleChanged(true);
this->setFocus();
}
void MainWindow::closeEvent(QCloseEvent *e)
{
if (e->spontaneous()) {
e->ignore();
hide();
} else {
QMainWindow::closeEvent(e);
}
}
void MainWindow::setupActionIcon()
{
ui->actionConnect->setIcon(QIcon::fromTheme("network-connect",
QIcon::fromTheme("network-vpn")));
ui->actionDisconnect->setIcon(QIcon::fromTheme("network-disconnect",
QIcon::fromTheme("network-offline")));
ui->actionEdit->setIcon(QIcon::fromTheme("document-edit",
QIcon::fromTheme("accessories-text-editor")));
ui->actionShare->setIcon(QIcon::fromTheme("document-share",
QIcon::fromTheme("preferences-system-sharing")));
ui->actionTestLatency->setIcon(QIcon::fromTheme("flag",
QIcon::fromTheme("starred")));
ui->actionImportGUIJson->setIcon(QIcon::fromTheme("document-import",
QIcon::fromTheme("insert-text")));
ui->actionExportGUIJson->setIcon(QIcon::fromTheme("document-export",
QIcon::fromTheme("document-save-as")));
ui->actionManually->setIcon(QIcon::fromTheme("edit-guides",
QIcon::fromTheme("accessories-text-editor")));
ui->actionURI->setIcon(QIcon::fromTheme("text-field",
QIcon::fromTheme("insert-link")));
ui->actionQRCode->setIcon(QIcon::fromTheme("edit-image-face-recognize",
QIcon::fromTheme("insert-image")));
ui->actionScanQRCodeCapturer->setIcon(ui->actionQRCode->icon());
ui->actionViewLog->setIcon(QIcon::fromTheme("view-list-text",
QIcon::fromTheme("text-x-preview")));
ui->actionGeneralSettings->setIcon(QIcon::fromTheme("configure",
QIcon::fromTheme("preferences-desktop")));
ui->actionReportBug->setIcon(QIcon::fromTheme("tools-report-bug",
QIcon::fromTheme("help-faq")));
}
bool MainWindow::isInstanceRunning() const
{
return instanceRunning;
}
void MainWindow::initSingleInstance()
{
instanceRunning = false;
QString username = qgetenv("USER");
if (username.isEmpty()) {
username = qgetenv("USERNAME");
}
QString serverName = QCoreApplication::applicationName() + "_" + username;
QLocalSocket socket;
socket.connectToServer(serverName);
if (socket.waitForConnected(500)) {
instanceRunning = true;
if (configHelper->isOnlyOneInstance()) {
qWarning() << "A instance from the same user is already running";
}
socket.write(serverName.toUtf8());
socket.waitForBytesWritten();
return;
}
/* Cann't connect to server, indicating it's the first instance of the user */
instanceServer = new QLocalServer(this);
instanceServer->setSocketOptions(QLocalServer::UserAccessOption);
connect(instanceServer, &QLocalServer::newConnection,
this,&MainWindow::onSingleInstanceConnect);
if (instanceServer->listen(serverName)) {
/* Remove server in case of crashes */
if (instanceServer->serverError() == QAbstractSocket::AddressInUseError &&
QFile::exists(instanceServer->serverName())) {
QFile::remove(instanceServer->serverName());
instanceServer->listen(serverName);
}
}
}
void MainWindow::onSingleInstanceConnect()
{
QLocalSocket *socket = instanceServer->nextPendingConnection();
if (!socket) {
return;
}
if (socket->waitForReadyRead(1000)) {
QString username = qgetenv("USER");
if (username.isEmpty()) {
username = qgetenv("USERNAME");
}
QByteArray byteArray = socket->readAll();
QString magic(byteArray);
if (magic == QCoreApplication::applicationName() + "_" + username) {
show();
}
}
delete socket;
}