-
Notifications
You must be signed in to change notification settings - Fork 9
/
mainwindow.cpp
1519 lines (1350 loc) · 50 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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <QDebug>
#include "facilemenu.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "usettings.h"
#include "myjson.h"
#include "fileutil.h"
#include "imageutil.h"
#include "netutil.h"
#include "netimageutil.h"
#include "signaltransfer.h"
#include "headerutil.h"
#ifdef Q_OS_WIN
#include "windows.h"
#endif
#include "widgets/customtabstyle.h"
#include "widgets/settings/accountwidget.h"
#include "widgets/settings/debugwidget.h"
#include "widgets/settings/groupwidget.h"
#include "widgets/settings/bannerwidget.h"
#include "widgets/settings/replywidget.h"
#include "widgets/settings/aboutwidget.h"
#include "widgets/settings/leavemodewidget.h"
#include "widgets/settings/remotecontrolwidget.h"
#include "widgets/settings/filewidget.h"
#include "widgets/settings/applicationwidget.h"
#include "widgets/settings/specialwidget.h"
#include "widgets/settings/countwidget.h"
#include "widgets/settings/speechwidget.h"
#include "widgets/settings/stylewidget.h"
#include "contact/contactpage.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
initService();
initView(); // 因为要绑定 service,所以要在 initService 后面
initTray();
initKey();
startMessageLoop();
}
MainWindow::~MainWindow()
{
delete ui;
deleteDir(rt->CACHE_PATH);
}
void MainWindow::initView()
{
// 设置属性
ui->settingsTabWidget->setAttribute(Qt::WA_StyledBackground);
ui->settingsTabWidget->setTabPosition(QTabWidget::West);
ui->settingsTabWidget->tabBar()->setStyle(new CustomTabStyle);
ui->settingsTabWidget->setCurrentIndex(us->i("mainwindow/settingsTabIndex"));
ui->auxiliaryTabWidget->setAttribute(Qt::WA_StyledBackground);
ui->auxiliaryTabWidget->setTabPosition(QTabWidget::West);
ui->auxiliaryTabWidget->tabBar()->setStyle(new CustomTabStyle);
ui->auxiliaryTabWidget->setCurrentIndex(us->i("mainwindow/settingsTabIndex"));
ui->dataTabWidget->setAttribute(Qt::WA_StyledBackground);
ui->dataTabWidget->setTabPosition(QTabWidget::West);
ui->dataTabWidget->tabBar()->setStyle(new CustomTabStyle);
ui->dataTabWidget->setCurrentIndex(us->i("mainwindow/settingsTabIndex"));
// 添加各种Tab页
ui->settingsTabWidget->clear();
ui->settingsTabWidget->addTab(new AccountWidget(cqhttpService, this), QIcon("://icons/account.png"), "账号绑定");
ui->settingsTabWidget->addTab(new GroupWidget(this), QIcon("://icons/group.png"), "通知过滤");
ui->settingsTabWidget->addTab(new BannerWidget(this), QIcon("://icons/banner.png"), "横幅弹窗");
ui->settingsTabWidget->addTab(new ReplyWidget(this), QIcon("://icons/reply.png"), "消息回复");
ui->settingsTabWidget->addTab(new FileWidget(this), QIcon("://icons/file.png"), "文件管理");
ui->settingsTabWidget->addTab(new SpecialWidget(this), QIcon("://icons/care.png"), "特别关心");
ui->settingsTabWidget->addTab(new StyleWidget(this), QIcon("://icons/bubble.png"), "卡片样式");
// ui->settingsTabWidget->addTab(new QWidget(this), QIcon("://icons/animation.png"), "动画调整");
ui->settingsTabWidget->addTab(new ApplicationWidget(this), QIcon("://icons/startup.png"), "程序设置");
ui->auxiliaryTabWidget->clear();
ui->auxiliaryTabWidget->addTab(new SpeechWidget(this), QIcon("://icons/speech.png"), "语音识别");
ui->auxiliaryTabWidget->addTab(new LeaveModeWidget(this), QIcon("://icons/ai.png"), "离开模式");
ui->auxiliaryTabWidget->addTab(new RemoteControlWidget(this), QIcon("://icons/control.png"), "远程控制");
ui->auxiliaryTabWidget->addTab(new QWidget(this), QIcon("://icons/reply.png"), "快速回复");
ui->auxiliaryTabWidget->addTab(new QWidget(this), QIcon("://icons/model.png"), "模型训练");
ui->dataTabWidget->clear();
ui->dataTabWidget->addTab(new AboutWidget(this), QIcon("://icons/about.png"), "关于程序");
ui->dataTabWidget->addTab(new CountWidget(this), QIcon("://icons/statistical.png"), "数据统计");
ui->dataTabWidget->addTab(new QWidget(this), QIcon("://icons/history_message.png"), "历史消息");
ui->dataTabWidget->addTab(new DebugWidget(cqhttpService, this), QIcon("://icons/debug.png"), "开发调试");
// 回复上次索引及索引改变信号
ui->sideButtons->setCurrentRow(us->i("mainwindow/sideIndex"));
ui->settingsTabWidget->setCurrentIndex(us->i("mainwindow/settingsTabIndex"));
ui->auxiliaryTabWidget->setCurrentIndex(us->i("mainwindow/auxiliaryTabIndex"));
ui->dataTabWidget->setCurrentIndex(us->i("mainwindow/dataTabIndex"));
connect(ui->settingsTabWidget, &QTabWidget::currentChanged, this, [=](int index) {
us->set("mainwindow/settingsTabIndex", index);
});
connect(ui->auxiliaryTabWidget, &QTabWidget::currentChanged, this, [=](int index) {
us->set("mainwindow/auxiliaryTabIndex", index);
});
connect(ui->dataTabWidget, &QTabWidget::currentChanged, this, [=](int index) {
us->set("mainwindow/dataTabIndex", index);
});
// 应用更改按钮
confirmButton = new InteractiveButtonBase("应用更改", this);
confirmButton->setBorderColor(Qt::gray);
confirmButton->setFixedForeSize();
confirmButton->setFixedForePos();
confirmButton->move(this->rect().bottomRight() - QPoint(confirmButton->width(), confirmButton->height()));
confirmButton->setFocusPolicy(Qt::StrongFocus);
if (ui->sideButtons->currentRow() == 2)
confirmButton->hide();
confirmButton->setCursor(Qt::PointingHandCursor);
}
void MainWindow::on_sideButtons_currentRowChanged(int currentRow)
{
ui->stackedWidget->setCurrentIndex(currentRow);
us->set("mainwindow/sideIndex", currentRow);
// 只有设置才显示应用更改
if (confirmButton)
{
if (currentRow == 0 || currentRow == 1)
this->confirmButton->show();
else
this->confirmButton->hide();
}
}
void MainWindow::startMessageLoop()
{
if (!us->host.isEmpty() && !us->host.contains("*"))
{
emit sig->hostChanged(us->host, us->accessToken);
}
}
void MainWindow::showHistoryListMenu()
{
// 显示最多十个好友/群组
qint64 time = QDateTime::currentMSecsSinceEpoch() - 6 * 60 * 60 * 1000; // 只显示最近六小时的
QList<QList<MsgBean>> msgss = ac->userMsgHistory.values() + ac->groupMsgHistory.values();
QList<QList<MsgBean>> msgsl;
for (int i = 0; i < msgss.size(); i++)
{
if (msgss.at(i).count() == 0 || msgss.at(i).last().timestamp < time)
msgss.removeAt(i--);
else
msgsl.append(msgss.at(i));
}
// 按最后一条消息时间排序
std::sort(msgsl.begin(), msgsl.end(), [=](const QList<MsgBean>& a, const QList<MsgBean>& b) {
return a.last().timestamp > b.last().timestamp;
});
// 如果没有消息,就不做操作了吧
if (!msgsl.size())
return ;
newFacileMenu;
int maxIndex = msgsl.size() - 1;
if (maxIndex > 10)
maxIndex = 10;
for (int i = 0; i <= maxIndex; i++) // 正序(最新消息在上面,符合习惯)
// for (int i = maxIndex; i >= 0; i--) // 倒序(最新消息在下面,交互方便)
{
const QList<MsgBean>& msgs = msgsl.at(i);
const MsgBean& msg = msgs.last();
if (!us->showDisabledGroup && msg.isGroup() && !us->enabledGroups.contains(msg.groupId))
continue;
QString name;
QPixmap pixmap;
AccountInfo::CardColor cc;
if (msg.isPrivate())
{
name = ac->friendName(msg.friendId);
name = us->userLocalNames.value(msg.friendId, name);
if (isFileExist(rt->userHeader(msg.friendId)))
pixmap = NetImageUtil::toRoundedPixmap(QPixmap(rt->userHeader(msg.friendId)));
cc = ac->userHeaderColor.value(msg.friendId);
}
else if (msg.isGroup())
{
name = ac->groupName(msg.groupId);
name = us->groupLocalNames.value(msg.groupId, name);
if (isFileExist(rt->groupHeader(msg.groupId)))
pixmap = NetImageUtil::toRoundedPixmap(QPixmap(rt->groupHeader(msg.groupId)));
cc = ac->groupHeaderColor.value(msg.groupId);
}
// 添加自定义控件
InteractiveButtonBase *w = new InteractiveButtonBase(menu);
QLabel* headerLabel = new QLabel(w);
QLabel* titleLabel = new QLabel(w);
QVBoxLayout* vlayout = new QVBoxLayout;
vlayout->addWidget(titleLabel);
QHBoxLayout* hlayout = new QHBoxLayout(w);
hlayout->addWidget(headerLabel);
hlayout->addLayout(vlayout);
hlayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
headerLabel->setPixmap(pixmap.isNull() ? QPixmap("://icons/ignore") : pixmap);
titleLabel->setText(name);
titleLabel->setMaximumWidth(us->bannerFixedWidth);
headerLabel->setScaledContents(true);
titleLabel->adjustSize();
// 遍历显示消息历史
int hei = titleLabel->height();
int maxCount = us->showMultiMessageHistories ? 3 : 1;
maxCount = qMin(maxCount, msgs.size());
QList<QLabel*> labels;
int loopCount = maxCount;
QLabel* lastMsgLabel = nullptr;
while (--loopCount >= 0)
{
const MsgBean& cMsg = msgs.at(msgs.count() - loopCount - 1);
QLabel* messageLabel = new QLabel(w);
lastMsgLabel = messageLabel;
vlayout->addWidget(messageLabel);
QString disp = MessageView::simpleMessage(cMsg);
if (disp.contains("\n"))
disp = disp.left(disp.indexOf("\n"));
if (cMsg.senderId == ac->myId)
messageLabel->setText("你:" + disp);
else if (cMsg.isPrivate())
messageLabel->setText(disp);
else
{
QString s = cMsg.username();
// 昵称简化
s = s.replace(QRegularExpression("^(?:id|ID|Id)[:|:](.+)$"), "\\1")
.replace(QRegularExpression("^(.+)\\s*[\\((].+[\\))]$"), "\\1");
messageLabel->setText(s + ": " + disp);
}
messageLabel->setMaximumWidth(us->bannerFixedWidth);
messageLabel->adjustSize();
hei += messageLabel->height();
labels.append(messageLabel);
messageLabel->setToolTip(disp);
}
headerLabel->setFixedSize(40, 40);
hei += vlayout->spacing() * maxCount + hlayout->margin() * 2;
w->setFixedSize(us->bannerFixedWidth, hei);
/* w->setDoubleClicked(true);
connect(w, &InteractiveButtonBase::click, this, [=]{
// 根据聊天信息,重新打开对应的对话框
focusOrShowMessageCard(msg, false, "", true);
}); */
connect(w, &InteractiveButtonBase::clicked, this, [=]{
// 因为要聚焦,所有这个popup的菜单必须要关闭
menu->close();
// 根据聊天信息,重新打开对应的对话框
focusOrShowMessageCard(msg, true, "", true);
});
if (cc.isValid() && us->bannerUseHeaderColor)
{
w->setBgColor(cc.bg);
titleLabel->setStyleSheet("font-weight: 500; color:" + QVariant(cc.fg).toString());
for (QLabel* la: labels)
{
la->setStyleSheet("color:" + QVariant(cc.fg).toString());
}
}
else
{
titleLabel->setStyleSheet("font-weight: 500;");
}
menu->addWidget(w);
// 添加显示未读消息
int unreadCount = msg.isGroup() ? ac->groupUnreadCount.value(msg.groupId) : ac->userUnreadCount.value(msg.friendId);
QLabel* unreadLabel = nullptr;
if (unreadCount > 0)
{
unreadLabel = new QLabel(snum(unreadCount), w);
hlayout->addWidget(unreadLabel);
// TODO: 根据重要性等级显示不同颜色的未读数字气泡
/* int im = getMsgImportance(msg);
QColor c = Qt::red;
if (im == VeryImportant && im >= us->lowestImportance)
c = Qt::red;
else if (im == LittleImportant && im >= us->lowestImportance)
c = Qt::blue;
else if (im == NormalImportant && im >= us->lowestImportance)
c = Qt::gray;
else
c = QColor();
qDebug() << "优先级:" << im << us->lowestImportance << c.isValid();
if (c.isValid())
{
unreadLabel->setFixedSize(24, 24);
unreadLabel->setStyleSheet("color: white; background-color: " + QVariant(c).toString() + "; border-radius: 8");
} */
}
hlayout->setStretch(1, 1);
// 显示的时候还可以实时更新消息
// 但是只能修改最新一条
connect(cqhttpService, &CqhttpService::signalMessage, w, [=](const MsgBean& m){
if (!msg.isMsg())
return ;
if (!msg.isSameObject(m))
return ;
QString disp;
if (msg.isPrivate())
disp = MessageView::simpleMessage(m);
else if (msg.senderId == ac->myId)
disp = "你:" + MessageView::simpleMessage(m);
else
disp = m.nickname + ": " + MessageView::simpleMessage(m);
if (us->showMultiMessageHistories)
{
// 取消过期消息
int count = vlayout->count();
if (count >= maxCount + 1)
{
auto item = vlayout->itemAt(1);
auto widget = item->widget();
vlayout->removeItem(item);
delete item;
widget->deleteLater();
}
// 添加最新消息
QLabel* la = new QLabel(disp, w);
if (cc.isValid() && us->bannerUseHeaderColor)
la->setStyleSheet("color:" + QVariant(cc.fg).toString());
la->setToolTip(disp);
vlayout->addWidget(la);
}
else
{
lastMsgLabel->setText(disp);
}
if (unreadLabel)
unreadLabel->setText(snum(unreadLabel->text().toInt() + 1));
});
// 使用默认的菜单机制(太朴素了)
/* auto action = menu->addAction(pixmap.isNull() ? QIcon("://icons/hideView") : QIcon(pixmap), name, [=]{
// 根据聊天信息,重新打开对应的对话框
focusOrShowMessageCard(msg, true);
});
if (cc.isValid())
{
action->fgColor(cc.fg)->bgColor(cc.bg);
} */
}
menu->adjustSize();
menu->setAppearAnimation(false);
menu->exec();
ac->userUnreadCount.clear();
ac->groupUnreadCount.clear();
}
QRect MainWindow::screenGeometry() const
{
auto screens = QGuiApplication::screens();
int& index = us->bannerScreenIndex;
if (index >= screens.size())
index = screens.size() - 1;
if (index < 0)
return QRect();
return screens.at(us->bannerScreenIndex)->geometry();
}
void MainWindow::initTray()
{
#if defined(ENABLE_TRAY)
tray = new QSystemTrayIcon(this);
tray->setIcon(QIcon("://appicon"));
tray->setToolTip(APPLICATION_NAME);
tray->show();
connect(tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(trayAction(QSystemTrayIcon::ActivationReason)));
trayRestoreTimer = new QTimer(this);
trayRestoreTimer->setInterval(us->trayShowIconDuration);
connect(trayRestoreTimer, &QTimer::timeout, this, [=]{
tray->setIcon(ac->myHeader.isNull() ? QIcon("://appicon") : QIcon(ac->myHeader));
currentTrayMsg = MsgBean();
trayFlashPixmap = QPixmap();
trayHiding = false;
trayHideTimer->stop();
});
trayHideTimer = new QTimer(this);
trayHideTimer->setInterval(us->trayFlashingInterval);
connect(trayHideTimer, &QTimer::timeout, this, [=]{
if (!trayHiding) // 隐藏图标
{
QPixmap pixmap(32, 32);
pixmap.fill(Qt::transparent);
tray->setIcon(pixmap);
trayHiding = true;
}
else // 显示图标
{
tray->setIcon(trayFlashPixmap.isNull() ? ac->myHeader.isNull() ? QIcon("://appicon") : QIcon(ac->myHeader) : trayFlashPixmap);
trayHiding = false;
trayHideTimer->stop();
}
});
trayUnreadTimer = new QTimer(this);
trayUnreadTimer->setInterval(us->trayFlickerInterval);
connect(trayUnreadTimer, &QTimer::timeout, this, [=]{
// 判断有没有未读消息
if ((ac->userUnreadCount.isEmpty() && ac->groupUnreadCount.isEmpty()))
{
trayUnreadTimer->stop();
return ;
}
if (ac->userUnreadCount.contains(ac->lastUnreadId))
{
if (ac->userMsgHistory.value(ac->lastUnreadId).size())
showTrayIcon(ac->userMsgHistory.value(ac->lastUnreadId).last());
}
else if (ac->groupUnreadCount.contains(ac->lastUnreadId))
{
if (ac->groupMsgHistory.value(ac->lastUnreadId).size())
showTrayIcon(ac->groupMsgHistory.value(ac->lastUnreadId).last());
}
else
{
trayUnreadTimer->stop();
return ;
}
});
#endif
}
void MainWindow::trayAction(QSystemTrayIcon::ActivationReason reason)
{
if (us->autoPauseByOtherDevice && us->isPausingByOtherDevice)
{
qInfo() << "从暂停通知中恢复";
us->isPausingByOtherDevice = false;
}
rt->mySendCount = 0;
switch(reason)
{
case QSystemTrayIcon::Trigger:
showHistoryListMenu();
break;
case QSystemTrayIcon::MiddleClick:
if (!this->isHidden())
{
this->hide();
}
else
{
this->showNormal();
this->activateWindow();
}
break;
case QSystemTrayIcon::Context:
{
FacileMenu* menu = new FacileMenu;
menu->addAction(QIcon("://icons/leaveMode.png"), "临时离开", [=] {
// 这里的离开模式不会保存,重启后还是以设置中为准
us->leaveMode = !us->leaveMode;
})->check(us->leaveMode)->tooltip("开启离开模式,可能开启了私聊AI回复\n重启后将恢复原来状态")->hide();
menu->addAction(QIcon("://icons/silent.png"), "临时静默", [=] {
// 这里的静默模式不会保存,重启后还是以设置中为准
rt->notificationSlient = !rt->notificationSlient;
if (rt->notificationSlient)
closeAllCard();
})->check(rt->notificationSlient)->tooltip("临时屏蔽所有消息\n重启后将恢复原来状态");
auto importanceMenu = menu->split()->addMenu(QIcon("://icons/importance.png"), "过滤重要性");
auto setImportance = [=](int im) {
us->set("importance/lowestImportance", us->lowestImportance = im);
};
importanceMenu->addAction(QIcon("://icons/veryImportant.png"), "很重要", [=]{
setImportance(VeryImportant);
})->check(us->lowestImportance == VeryImportant);
importanceMenu->addAction(QIcon("://icons/important.png"), "重要", [=]{
setImportance(LittleImportant);
})->check(us->lowestImportance == LittleImportant);
importanceMenu->addAction(QIcon("://icons/normalImportant.png"), "一般", [=]{
setImportance(NormalImportant);
})->check(us->lowestImportance == NormalImportant);
importanceMenu->addAction(QIcon("://icons/unimportant.png"), "不重要", [=]{
setImportance(Unimportant);
})->check(us->lowestImportance == Unimportant);
menu->split()->addAction(QIcon("://icons/settings.png"), "设置", [=]{
this->show();
this->activateWindow();
});
menu->addAction(QIcon("://icons/search.png"), "搜索", [=]{
ContactPage::getInstance()->show();
});
menu->addAction(QIcon("://icons/quit.png"), "退出", [=]{
qApp->quit();
});
menu->exec(QCursor::pos());
}
break;
default:
break;
}
}
void MainWindow::initService()
{
// 网络服务
cqhttpService = new CqhttpService(this);
connect(cqhttpService, SIGNAL(signalMessage(const MsgBean&)), this, SLOT(messageReceived(const MsgBean&)));
connect(cqhttpService, SIGNAL(signalMessage(const MsgBean&)), this, SLOT(autoReplyMessage(const MsgBean&)));
connect(sig, SIGNAL(hostChanged(QString, QString)), cqhttpService, SLOT(openHost(QString, QString)));
connect(sig, &SignalTransfer::sendSocketText, cqhttpService, &CqhttpService::sendTextMessage);
connect(sig, &SignalTransfer::sendSocketJson, cqhttpService, &CqhttpService::sendJsonMessage);
connect(sig, &SignalTransfer::loadGroupMembers, cqhttpService, &CqhttpService::refreshGroupMembers);
connect(sig, &SignalTransfer::recallMessage, cqhttpService, &CqhttpService::recallMessage);
connect(sig, &SignalTransfer::setGroupBan, cqhttpService, &CqhttpService::setGroupBan);
connect(sig, SIGNAL(getGroupMsgHistory(qint64, qint64)), cqhttpService, SLOT(getGroupMsgHistory(qint64, qint64)));
connect(sig, &SignalTransfer::myHeader, this, [=](const QPixmap& pixmap) {
ac->myHeader = NetImageUtil::toRoundedPixmap(pixmap);
if (tray)
tray->setIcon(pixmap);
});
connect(sig, &SignalTransfer::openUserCard, this, [=](qint64 userId, const QString& username, const QString& text) {
MsgBean msg(userId, username);
msg.privt(userId, userId);
focusOrShowMessageCard(msg, true, text);
});
connect(sig, &SignalTransfer::openGroupCard, this, [=](qint64 groupId, const QString& text) {
MsgBean msg(0, "");
msg.group(groupId, ac->groupName(groupId));
focusOrShowMessageCard(msg, true, text);
});
connect(sig, SIGNAL(showTrayIcon(const MsgBean&)), this, SLOT(showTrayIcon(const MsgBean&)));
// 远程控制
remoteControlService = new RemoteControlServie(this);
// 其他API服务
// 刷新百度API的token
if (!us->baiduSpeechAccessToken.isEmpty())
{
qint64 time = QDateTime::currentSecsSinceEpoch();
qint64 prevTime = us->l("baiduSpeech/tokenRefreshTime", time);
if (time - prevTime >= 30 * 24 * 3600)
{
SpeechWidget::refreshToken();
}
}
// 可编程代码
codeRunner = new DevCodeRunner(cqhttpService);
// 定时刷新
QTimer* refreshTimer = new QTimer(this);
refreshTimer->setInterval(3600000);
refreshTimer->setSingleShot(false);
connect(refreshTimer, &QTimer::timeout, this, [=]{
if (cqhttpService->isConnected())
{
cqhttpService->refreshFriends();
cqhttpService->refreshGroups();
}
});
refreshTimer->start();
}
void MainWindow::initKey()
{
#if defined(ENABLE_SHORTCUT)
editShortcut = new QxtGlobalShortcut(this);
QString def_key = us->value("banner/replyKey", "shift+alt+x").toString();
editShortcut->setShortcut(QKeySequence(def_key));
connect(editShortcut, &QxtGlobalShortcut::activated, this, [=]() {
if (us->autoPauseByOtherDevice && us->isPausingByOtherDevice)
{
qInfo() << "从暂停通知中恢复";
us->isPausingByOtherDevice = false;
}
rt->mySendCount = 0;
#if defined(Q_OS_WIN32)
auto hwnd = GetForegroundWindow();
bool isMe = false;
foreach (auto card, notificationCards)
if (HWND(card->winId()) == hwnd)
{
isMe = true;
break;
}
// 如果不是自己的通知卡片
if (!isMe)
prevWindow = hwnd;
#endif
// this->activateWindow();
focusCardReply();
});
connect(sig, &SignalTransfer::setReplyKey, this, [=](QString key) {
editShortcut->setShortcut(QKeySequence(key));
});
#endif
connect(sig, &SignalTransfer::runCode, codeRunner, &DevCodeRunner::runCode);
}
void MainWindow::showEvent(QShowEvent *e)
{
QMainWindow::showEvent(e);
us->set("mainwindow/hide", false);
static bool first = true;
if (first)
{
first = false;
restoreGeometry(us->value("mainwindow/geometry").toByteArray());
restoreState(us->value("mainwindow/state").toByteArray());
}
}
void MainWindow::closeEvent(QCloseEvent *e)
{
us->setValue("mainwindow/geometry", this->saveGeometry());
us->setValue("mainwindow/state", this->saveState());
us->sync();
#if defined(ENABLE_TRAY)
e->ignore();
this->hide();
// 因为关闭程序也会触发这个,所以需要定时一下
QTimer::singleShot(5000, [=]{
us->set("mainwindow/hide", true);
});
QTimer::singleShot(5000, [=]{
if (!this->isHidden())
return ;
us->setValue("mainwindow/autoShow", false);
});
#else
QMainWindow::closeEvent(e);
#endif
}
void MainWindow::resizeEvent(QResizeEvent *e)
{
QMainWindow::resizeEvent(e);
confirmButton->move(this->rect().bottomRight() - QPoint(confirmButton->width() + us->bannerSpacing, confirmButton->height() + us->bannerSpacing));
}
void MainWindow::returnToPrevWindow()
{
#ifdef Q_OS_WIN32
if (this->prevWindow)
SwitchToThisWindow(prevWindow, true);
prevWindow = nullptr;
#endif
}
/// 接收到的所有消息都会在这里(只要有解析过的)
/// 在这里判断要不要显示
void MainWindow::messageReceived(const MsgBean &msg, bool blockSelf)
{
// ========== 记录消息 ==========
if (msg.isMsg())
{
us->addCount(us->countReceiveAll, "receiveAll");
if (msg.isPrivate())
{
qint64 friendId = msg.friendId;
if (ac->friendList.contains(friendId))
ac->friendList[friendId].lastMsgTime = QDateTime::currentMSecsSinceEpoch();
// 判断私聊是否是重复接收了
if (ac->userMsgHistory.contains(friendId))
{
const auto& msgs = ac->userMsgHistory.value(friendId);
if (msgs.size() && msgs.last().messageId == msg.messageId)
{
qInfo() << "忽略自己发送给非好友的重复消息:" << msg.messageId << msg.message;
return ;
}
}
else
ac->userMsgHistory.insert(friendId, QList<MsgBean>());
ac->userMsgHistory[friendId].append(msg);
ac->receiveCountAfterMySendPrivate[friendId] = ac->receiveCountAfterMySendPrivate.value(friendId) + 1;
// 判断自己发的还是接收的
if (msg.senderId != ac->myId)
{
us->addCount(us->countReceivePrivate, "receivePrivate");
ac->userUnreadCount[friendId]++;
}
else
{
ac->userUnreadCount.remove(friendId);
}
}
else if (msg.isGroup())
{
qint64 groupId = msg.groupId;
if (ac->groupList.contains(groupId))
ac->groupList[groupId].lastMsgTime = QDateTime::currentMSecsSinceEpoch();
if (!ac->groupMsgHistory.contains(groupId))
ac->groupMsgHistory.insert(groupId, QList<MsgBean>());
ac->groupMsgHistory[groupId].append(msg);
ac->receivedCountAfterMySentGroup[groupId] = ac->receivedCountAfterMySentGroup.value(groupId) + 1;
// 判断自己发的还是接收的
if (msg.senderId != ac->myId)
{
us->addCount(us->countReceiveGroup, "receiveGroup");
ac->groupUnreadCount[groupId]++;
}
else
{
ac->groupUnreadCount.remove(groupId);
}
}
// 自己发送的消息
if (msg.senderId == ac->myId)
{
// 判断是不是自己当前程序发送的
if (us->autoPauseByOtherDevice && rt->mySendCount == 0)
{
qInfo() << "其他设备发送消息,暂停通知";
us->isPausingByOtherDevice = true;
}
}
}
// 执行代码
if (us->devCode.contains(msg.keyId()))
{
QString code = us->devCode.value(msg.keyId());
codeRunner->runCode(code, msg);
}
// 托盘通知
if (us->trayShowAllMessageIcon)
showTrayIcon(msg);
// ========== 显示通知 ==========
// 如果已经显示了卡片,那么忽略所有开关
NotificationCard* currentCard = nullptr;
foreach (auto card, notificationCards)
{
if (card->is(msg))
{
currentCard = card;
break;
}
}
if (!currentCard) // 需要显示新卡片
{
if (!canNewCardShow(msg))
return ;
}
// 解除智能聚焦
// 重要的必定发送,除非静默
if (us->smartFocus && msg.senderId != ac->myId)
{
if (msg.isPrivate())
{
if (ac->askUser.contains(msg.senderId))
{
ac->askUser.remove(msg.senderId);
qInfo() << "移除私聊疑问智能聚焦:" << msg.senderId;
}
}
else if (msg.isGroup())
{
if (ac->askGroup.contains(msg.groupId))
{
ac->askGroup.remove(msg.groupId);
qInfo() << "移除群聊疑问智能聚焦:" << msg.groupId << msg.senderId;
}
if (ac->groupList.value(msg.groupId).atMember.contains(msg.senderId))
{
ac->groupList[msg.groupId].atMember.remove(msg.senderId);
qInfo() << "移除群聊艾特智能聚焦:" << msg.groupId << msg.senderId;
}
}
}
showMessageCard(msg, blockSelf);
}
/// 是否需要显示新卡片
/// 就收到消息优先级不够
bool MainWindow::canNewCardShow(const MsgBean &msg) const
{
if (!msg.isMsg() && !msg.is(ActionJoin))
{
return false;
}
// 静默模式
if (rt->notificationSlient || us->isPausingByOtherDevice)
{
if (us->trayShowSlientPrivateMessageIcon && msg.isPrivate())
showTrayIcon(msg);
// 不需要进行优先级的判断
/* if (!us->trayShowAllSlientMessageIcon && !us->trayShowSlientSpecialMessageIcon && !us->trayShowLowImportanceMessageIcon)
return false; */
}
// 判断群组显示开关
qint64 cur = QDateTime::currentMSecsSinceEpoch();
if (msg.isGroup() && !us->isGroupShow(msg.groupId)) // 未打开群组消息开关
{
if (ac->askGroup.contains(msg.groupId)) // 要显示群组通知
{}
else if (ac->groupList[msg.groupId].atMember.contains(msg.senderId)) // 艾特成员的消息
{}
else if (ac->mySendGroupTime.contains(msg.groupId)
&& (cur - ac->mySendGroupTime[msg.groupId] <= 180000
|| ac->receivedCountAfterMySentGroup[msg.groupId] <= 10))
{}
else // 无关紧要的群组
return false;
}
int im = getMsgImportance(msg);
// 不足优先级,不通知
if (im < us->lowestImportance)
{
// 静默消息的托盘图标
if (((rt->notificationSlient || us->isPausingByOtherDevice) && (us->trayShowAllSlientMessageIcon|| (us->trayShowSlientSpecialMessageIcon && im >= VeryImportant)))
|| us->trayShowLowImportanceMessageIcon)
showTrayIcon(msg);
return false;
}
else
{
// 显示未读消息
if (msg.senderId != ac->myId)
{
im = getMsgImportance(msg, false); // 不包括动态重要性的原始重要性,以及智能聚焦
if (im < us->lowestImportance)
{
ac->lastUnreadId = msg.isPrivate() ? msg.friendId : msg.groupId;
if (us->unreadFlicker && trayUnreadTimer)
trayUnreadTimer->start();
}
}
}
return !rt->notificationSlient && !us->isPausingByOtherDevice;
}
/// 获取一个聊天对象的重要性
/// @param dynamic 是否根据智能聚焦和动态重要性来自动调整
int MainWindow::getMsgImportance(const MsgBean &msg, bool dynamic) const
{
// 特别关心(叠加)
int special = (us->userSpecial.contains(msg.senderId) ? 1 : 0)
+ (us->groupMemberSpecial.contains(msg.senderId) ? 1 : 0);
if (us->userBlocklist.contains(msg.senderId))
special = -1;
// 判断消息级别开关
int im = NormalImportant;
if (msg.isPrivate())
{
im = us->userImportance.value(msg.senderId, us->userDefaultImportance);
}
else if (msg.isGroup())
{
if (!us->enabledGroups.contains(msg.groupId)) // 本来是不显示通知的群组
im = Unimportant;
else
im = us->groupImportance.value(msg.groupId, us->groupDefaultImportance);
// 判断发送者的重要性,max(用户,群组)
if (us->groupUseFriendImportance)
{
int im2 = us->userImportance.value(msg.senderId, im);
im = qMax(im, im2);
}
}
// 特别关心(好友/群内)
im += special;
if (special < 0)
im = BlockImportant;
// 全局提醒词
bool globalRemind = false;
for (auto w: us->globalRemindWords)
{
if (w.trimmed().isEmpty())
continue;
if (msg.message.contains(w))
{
globalRemind = true;
im++;
if (!us->remindOverlay)
break;
}
}
// 群组提醒词
bool groupRemind = false;
if ((us->remindOverlay || !globalRemind) && msg.isGroup() && us->groupRemindWords.contains(msg.groupId))
{
for (auto w: us->groupRemindWords.value(msg.groupId))
{
if (w.trimmed().isEmpty())
continue;
if (msg.message.contains(w))
{
groupRemind = true;
im++;
if (!us->remindOverlay)
break;
}
}
}
// @全体成员/@我
if (us->improveAtAllImportance && msg.hasAt(0))
{
im++;
}
if (us->improveAtMeImportance && msg.hasAt(ac->myId))
{
im++;
}
// 动态重要性
if (us->dynamicImportance && dynamic)
{
qint64 cur = QDateTime::currentMSecsSinceEpoch();
qint64 time = 0;
int count = 0;
if (msg.isPrivate())
{
time = ac->mySendPrivateTime.value(msg.friendId, 0);
count = ac->receiveCountAfterMySendPrivate.value(msg.friendId);
}
else if (msg.isGroup())
{
time = ac->mySendGroupTime.value(msg.groupId, 0);
count = ac->receivedCountAfterMySentGroup.value(msg.groupId);
}