Repository navigation
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1590 lines (1479 loc) · 67.2 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1590 lines (1479 loc) · 67.2 KB
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 "mainwindow.h"
#include <QDateTime>
#include <QDesktopServices>
#include <QDir>
#include <QCloseEvent>
#include <QCoreApplication>
#include <QRegularExpression>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QRegularExpression>
#include <QTextStream>
#include <QVersionNumber>
#include <QtEndian>
#include "ui_mainwindow.h"
#include "version.h"
//VS 安装根目录的首次默认值,之后以 config.ini 中保存的值为准
const QString MainWindow::DEFAULT_VS_ROOT_DIR = QStringLiteral("C:/Program Files/Microsoft Visual Studio");
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), shuttingDown(false)
{
ui->setupUi(this);
//标题栏显示中文程序名与版本号:工程会产出多份不同 Qt 版本/编译器的构建,
//靠标题即可区分当前运行的是哪一版;版本号由 Version 模块提供,含本次编译时间
setWindowTitle(QStringLiteral("%1 v%2").arg(QStringLiteral("Qt 部署助手"), Version::getDisplayVersion()));
deployProcess = new QProcess(this);
connect(deployProcess, &QProcess::finished, this, &MainWindow::onDeployFinished);
connect(deployProcess, &QProcess::readyReadStandardOutput, this, &MainWindow::onDeployReadyReadStdout);
connect(deployProcess, &QProcess::readyReadStandardError, this, &MainWindow::onDeployReadyReadStderr);
//Enigma 封包同样走异步:一次封包几十兆文件要跑很久,同步 waitForFinished 会让整个界面失去响应
enigmaProcess = new QProcess(this);
enigmaProcess->setProcessChannelMode(QProcess::MergedChannels);
connect(enigmaProcess, &QProcess::readyReadStandardOutput, this, &MainWindow::onEnigmaReadyRead);
connect(enigmaProcess, &QProcess::finished, this, &MainWindow::onEnigmaFinished);
loadSettings();
//记下当前目标exe路径:之后用于判断用户是否真的改了路径,只有改过才让输出目录跟随
lastExePath = ui->edtExePath->text();
//清掉上次打包继承下来的占用备份文件(此时锁已释放)
cleanupLockedBackups();
}
void MainWindow::stopRunningProcesses()
{
//windeployqt 与封包器都是异步子进程,窗口关掉后主进程会一直等它们结束;
//enigmavbconsole 一次封包可能跑很久,不主动结束就会让进程残留,文件也一直被锁
QProcess *processList[2] = { deployProcess, enigmaProcess };
for(int i = 0; i < 2; ++i)
{
QProcess *proc = processList[i];
if(proc == Q_NULLPTR || proc->state() == QProcess::NotRunning)
{
continue;
}
proc->kill();
proc->waitForFinished(3000);
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
//置位后两个 finished 回调不再发起重试或封包,避免关窗这一刻又拉起新进程
shuttingDown = true;
stopRunningProcesses();
QMainWindow::closeEvent(event);
}
MainWindow::~MainWindow()
{
saveSettings();
shuttingDown = true;
stopRunningProcesses();
//退出前再清一次:打包其它程序时,对方若已退出这些备份文件就能删掉了
cleanupLockedBackups();
delete ui;
}
void MainWindow::appendLog(const QString &msg)
{
QString timeStamp = QDateTime::currentDateTime().toString(QStringLiteral("[yyyy-MM-dd HH:mm:ss] "));
ui->txtLog->appendPlainText(timeStamp + msg);
}
bool MainWindow::loadSettings()
{
QSettings settings(QCoreApplication::applicationDirPath() + QStringLiteral("/config.ini"), QSettings::IniFormat);
settings.beginGroup(QStringLiteral("Paths"));
ui->edtExePath->setText(settings.value(QStringLiteral("exePath"), QStringLiteral("")).toString());
ui->edtQtBin->setText(settings.value(QStringLiteral("qtBin"), QStringLiteral("")).toString());
ui->edtOutputDir->setText(settings.value(QStringLiteral("outputDir"), QStringLiteral("")).toString());
ui->edtQmlDir->setText(settings.value(QStringLiteral("qmlDir"), QStringLiteral("")).toString());
ui->edtEnigmaVbPath->setText(settings.value(QStringLiteral("enigmaVbConsole"), QStringLiteral("")).toString());
//VS 安装根目录:首次给默认路径,之后沿用保存过的值(VS 装在非 C 盘时用户只需改一次)
QString vsRootDir = settings.value(QStringLiteral("vsRootDir"), DEFAULT_VS_ROOT_DIR).toString();
ui->edtVsRootDir->setText(vsRootDir);
settings.endGroup();
settings.beginGroup(QStringLiteral("Options"));
ui->chkCleanOld->setChecked(settings.value(QStringLiteral("chkCleanOld"), false).toBool());
ui->chkMultimedia->setChecked(settings.value(QStringLiteral("chkMultimedia"), false).toBool());
ui->chkZip->setChecked(settings.value(QStringLiteral("chkZip"), false).toBool());
ui->chkSlimPlugin->setChecked(settings.value(QStringLiteral("chkSlimPlugin"), false).toBool());
ui->edtCustomKeepPlugins->setText(settings.value(QStringLiteral("customKeepPlugins"), QStringLiteral("")).toString());
ui->chkCopyVcRuntime->setChecked(settings.value(QStringLiteral("chkCopyVcRuntime"), false).toBool());
ui->edtVersion->setText(settings.value(QStringLiteral("version"), QStringLiteral("1.0.0")).toString());
ui->edtExtraDlls->setText(settings.value(QStringLiteral("extraDlls"), QStringLiteral("")).toString());
ui->chkEnigmaPack->setChecked(settings.value(QStringLiteral("chkEnigmaPack"), false).toBool());
ui->edtKeepFiles->setText(settings.value(QStringLiteral("keepFiles"), QStringLiteral("config.ini")).toString());
settings.endGroup();
return true;
}
bool MainWindow::saveSettings()
{
QSettings settings(QCoreApplication::applicationDirPath() + QStringLiteral("/config.ini"), QSettings::IniFormat);
settings.beginGroup(QStringLiteral("Paths"));
settings.setValue(QStringLiteral("exePath"), ui->edtExePath->text());
settings.setValue(QStringLiteral("qtBin"), ui->edtQtBin->text());
settings.setValue(QStringLiteral("outputDir"), ui->edtOutputDir->text());
settings.setValue(QStringLiteral("qmlDir"), ui->edtQmlDir->text());
settings.setValue(QStringLiteral("enigmaVbConsole"), ui->edtEnigmaVbPath->text());
settings.setValue(QStringLiteral("vsRootDir"), ui->edtVsRootDir->text());
settings.endGroup();
settings.beginGroup(QStringLiteral("Options"));
settings.setValue(QStringLiteral("chkCleanOld"), ui->chkCleanOld->isChecked());
settings.setValue(QStringLiteral("chkMultimedia"), ui->chkMultimedia->isChecked());
settings.setValue(QStringLiteral("chkZip"), ui->chkZip->isChecked());
settings.setValue(QStringLiteral("chkSlimPlugin"), ui->chkSlimPlugin->isChecked());
settings.setValue(QStringLiteral("customKeepPlugins"), ui->edtCustomKeepPlugins->text());
settings.setValue(QStringLiteral("chkCopyVcRuntime"), ui->chkCopyVcRuntime->isChecked());
settings.setValue(QStringLiteral("version"), ui->edtVersion->text());
settings.setValue(QStringLiteral("extraDlls"), ui->edtExtraDlls->text());
settings.setValue(QStringLiteral("chkEnigmaPack"), ui->chkEnigmaPack->isChecked());
settings.setValue(QStringLiteral("keepFiles"), ui->edtKeepFiles->text());
settings.endGroup();
return true;
}
bool MainWindow::checkDeployInput()
{
if(ui->edtExePath->text().trimmed().isEmpty() || !QFile::exists(ui->edtExePath->text()))
{
QMessageBox::warning(this, QStringLiteral("校验失败"), QStringLiteral("目标EXE不存在!"));
return false;
}
if(ui->edtQtBin->text().trimmed().isEmpty() || !QDir(ui->edtQtBin->text()).exists())
{
QMessageBox::warning(this, QStringLiteral("校验失败"), QStringLiteral("Qt bin目录不存在!"));
return false;
}
if(ui->edtOutputDir->text().trimmed().isEmpty())
{
QMessageBox::warning(this, QStringLiteral("校验失败"), QStringLiteral("输出目录不能为空!"));
return false;
}
if(ui->chkEnigmaPack->isChecked())
{
QString enigmaPath = ui->edtEnigmaVbPath->text().trimmed();
if(enigmaPath.isEmpty() || !QFile::exists(enigmaPath))
{
QMessageBox::warning(this, QStringLiteral("校验失败"), QStringLiteral("已勾选Enigma打包,请选择有效的 enigmavbconsole.exe!"));
return false;
}
}
return true;
}
bool MainWindow::clearDirectoryKeepSelf(const QDir &dir, const QStringList &keepPatterns)
{
if(!dir.exists())
{
return true;
}
QFileInfoList entryList = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::AllEntries);
for(const QFileInfo &info: entryList)
{
QString fileName = info.fileName();
bool needKeep = false;
//支持通配符匹配 *.ini, readme*
for(const QString &pattern: keepPatterns)
{
QString pat = pattern.trimmed();
if(pat.isEmpty())
{
continue;
}
if(QDir::match(pat, fileName))
{
needKeep = true;
break;
}
}
if(needKeep)
{
appendLog(QStringLiteral("ℹ️ 跳过保留文件:%1(匹配规则)").arg(info.fileName()));
continue;
}
if(info.isDir())
{
QDir subDir(info.absoluteFilePath());
if(!subDir.removeRecursively())
{
appendLog(QStringLiteral("⚠️ 删除子目录失败:%1").arg(info.absoluteFilePath()));
}
}
else
{
if(!QFile::remove(info.absoluteFilePath()))
{
appendLog(QStringLiteral("⚠️ 删除文件失败:%1").arg(info.absoluteFilePath()));
}
}
}
return true;
}
//计算文件/目录选择对话框的起始目录:跟随输入框当前已填的路径
QString MainWindow::dialogStartDir(const QString ¤tPath, bool currentIsDir) const
{
QString startDir = QDir::homePath();
QString path = currentPath.trimmed();
if(!path.isEmpty())
{
QFileInfo info(path);
//currentIsDir=true(目录选择框)直接用当前目录;否则(文件选择框)用其所在目录
QString dir = currentIsDir ? info.absoluteFilePath() : info.absolutePath();
if(QDir(dir).exists())
{
startDir = dir;
}
}
return startDir;
}
void MainWindow::on_btnSelectExe_clicked()
{
QString filePath = QFileDialog::getOpenFileName(this, QStringLiteral("选择目标EXE"), dialogStartDir(ui->edtExePath->text(), false), QStringLiteral("Executable(*.exe)"));
if(!filePath.isEmpty())
{
ui->edtExePath->setText(filePath);
lastExePath = filePath;
//选完目标exe后输出目录默认跟随该exe所在目录:原地部署是最常见用法,省去再手动选一次,用户之后仍可改
ui->edtOutputDir->setText(QFileInfo(filePath).absolutePath());
}
}
void MainWindow::on_edtExePath_editingFinished()
{
//手输路径与按钮选择保持一致:exe 换了,输出目录跟着换。
//只在路径确实变化时跟随,否则用户单独编辑输出目录后一失焦就会被这里覆盖掉
QString exePath = ui->edtExePath->text().trimmed();
if(exePath == lastExePath)
{
return;
}
lastExePath = exePath;
if(exePath.isEmpty())
{
return;
}
ui->edtOutputDir->setText(QFileInfo(exePath).absolutePath());
}
void MainWindow::on_btnSelectQtBin_clicked()
{
QString dir = QFileDialog::getExistingDirectory(this, QStringLiteral("选择Qt bin目录"), dialogStartDir(ui->edtQtBin->text(), true));
if(!dir.isEmpty())
{
ui->edtQtBin->setText(dir);
}
}
void MainWindow::on_btnOpenOutput_clicked()
{
QString path = ui->edtOutputDir->text().trimmed();
if(QDir(path).exists())
{
QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
else
{
appendLog(QStringLiteral("⚠️ 输出目录不存在"));
}
}
void MainWindow::on_btnSelectQmlDir_clicked()
{
//支持多个 QML 目录:输入框内用英文分号分隔,再点一次“选择”就追加到末尾
const QStringList currentDirs = ui->edtQmlDir->text().split(QStringLiteral(";"), Qt::SkipEmptyParts);
const QString startDir = currentDirs.isEmpty() ? QString() : currentDirs.first().trimmed();
QString dir = QFileDialog::getExistingDirectory(this, QStringLiteral("选择QML源码目录"), dialogStartDir(startDir, true));
if(dir.isEmpty())
{
return;
}
dir = QDir::toNativeSeparators(dir);
if(currentDirs.contains(dir))
{
return; //同一个目录不重复添加
}
QString newText = ui->edtQmlDir->text().trimmed();
if(newText.isEmpty())
{
ui->edtQmlDir->setText(dir);
return;
}
ui->edtQmlDir->setText(newText + QStringLiteral(";") + dir);
}
void MainWindow::on_btnSelectEnigmaVb_clicked()
{
QString filePath = QFileDialog::getOpenFileName(this, QStringLiteral("选择 enigmavbconsole.exe"), dialogStartDir(ui->edtEnigmaVbPath->text(), false), QStringLiteral("Enigma Console(enigmavbconsole.exe)"));
if(!filePath.isEmpty())
{
ui->edtEnigmaVbPath->setText(filePath);
}
}
void MainWindow::on_btnSelectVsRoot_clicked()
{
QString dirPath = QFileDialog::getExistingDirectory(this,
QStringLiteral("选择 Visual Studio 安装根目录"),
dialogStartDir(ui->edtVsRootDir->text(), true));
if(!dirPath.isEmpty())
{
ui->edtVsRootDir->setText(QDir::toNativeSeparators(dirPath));
}
}
void MainWindow::on_btnStartDeploy_clicked()
{
if(deployProcess->state() != QProcess::NotRunning)
{
QMessageBox::information(this, QStringLiteral("提示"), QStringLiteral("打包进程正在运行!"));
return;
}
if(!checkDeployInput())
{
return;
}
appendLog(QStringLiteral("===== 开始准备打包 ====="));
deployOutputBuffer.clear();
QString exePath = ui->edtExePath->text().trimmed();
QString qtBinDir = ui->edtQtBin->text().trimmed();
QString outputDir = ui->edtOutputDir->text().trimmed();
QString compilerType;
QString qtVersion;
detectQtCompiler(qtBinDir, compilerType, qtVersion);
//记录本次打包的 Qt 版本/编译器,供 Enigma 单文件命名使用
currentQtVersion = qtVersion;
currentCompilerType = compilerType;
//先核对所选 Qt 与目标 EXE 是否配套:不匹配就中止,避免把错误版本的 DLL 拷进输出目录
if(!checkQtTargetMatch(exePath, qtBinDir, compilerType))
{
appendLog(QStringLiteral("❌ 已中止打包:所选 Qt 与目标 EXE 不匹配"));
return;
}
//输出目录若与目标exe所在目录相同,源exe必须始终保留,防止清空旧目录时删掉原文件
QFileInfo exeInfo(exePath);
QDir outDir(outputDir);
QString destExe = outDir.filePath(exeInfo.fileName());
//就地打包:输出目录就是源 exe 所在目录,此时目标文件与源文件是同一个
const bool inPlacePack = (exeInfo.canonicalFilePath() == QFileInfo(destExe).canonicalFilePath());
//打包自身:目标 exe 就是当前正在运行的这个程序
const bool packSelf = (QFileInfo(QCoreApplication::applicationFilePath()).canonicalFilePath() == exeInfo.canonicalFilePath());
if(packSelf)
{
appendLog(QStringLiteral("ℹ️ 检测到正在打包程序自身:运行中的 exe 与已加载的 DLL 被系统锁定,"
"已存在的同名文件不会覆盖,建议另选一个空输出目录"));
}
if(ui->chkCleanOld->isChecked())
{
if(inPlacePack)
{
//就地打包时清空会把目录里的第三方 DLL 一起删掉,正在使用的文件也删不掉,
//所以这种情况下跳过清空,只补部署缺失的文件
appendLog(QStringLiteral("⚠️ 输出目录与源 exe 同目录,跳过“清空旧目录”,避免误删目录内其它 DLL"));
}
else
{
appendLog(QStringLiteral("⚠️ 清空旧输出目录(保留目录本身,跳过配置的保留文件)"));
QString rawKeep = ui->edtKeepFiles->text().trimmed();
QStringList keepList = rawKeep.split(QStringLiteral(","), Qt::SkipEmptyParts);
keepList << exeInfo.fileName();
clearDirectoryKeepSelf(outDir, keepList);
}
}
outDir.mkpath(QStringLiteral("."));
//拷贝exe到输出目录:目标与源为同一文件(输出目录=源exe目录)时跳过删除与复制,避免删掉原exe
if(inPlacePack)
{
appendLog(QStringLiteral("ℹ️ 输出目录与源exe目录相同,主程序已就位,无需复制:%1").arg(destExe));
}
else
{
QFile::remove(destExe);
if(!QFile::copy(exePath, destExe))
{
appendLog(QStringLiteral("❌ 复制主程序到输出目录失败:%1").arg(destExe));
return;
}
appendLog(QStringLiteral("✅ 复制主程序到输出目录:%1").arg(destExe));
}
//运行库提前让位:windeployqt 对这些 DLL 是先删后拷,目标程序运行中删不掉就会以退出码 1 结束
preBackupRuntimeDlls(outputDir, compilerType, ui->chkCopyVcRuntime->isChecked());
QString windeployqt = QDir(qtBinDir).filePath(QStringLiteral("windeployqt.exe"));
QStringList args;
args << destExe;
if(ui->chkMultimedia->isChecked())
{
args << QStringLiteral("--multimedia");
}
//QML 目录可填多个(英文分号分隔):windeployqt 支持重复传 --qmldir,每个目录各扫一遍 import
const QStringList qmlDirs = ui->edtQmlDir->text().split(QStringLiteral(";"), Qt::SkipEmptyParts);
for(const QString &qmlDir: qmlDirs)
{
const QString trimmedDir = qmlDir.trimmed();
if(!trimmedDir.isEmpty())
{
args << QStringLiteral("--qmldir") << trimmedDir;
}
}
if(ui->chkSlimPlugin->isChecked())
{
args << QStringLiteral("--no-plugins");
}
if(ui->chkCopyVcRuntime->isChecked())
{
//MSVC 部署需要随包带上 VC 运行库;windeployqt 自身可能取不到 Redist 路径,
//部署完成后还会由 copyVcRuntimeDlls() 兜底复制
//就地打包时 windeployqt 对已存在的运行库文件是先删后拷,目标程序运行中删不掉会直接失败;
//MinGW 运行库在输出目录里已齐全时不必再传该参数
bool mingwRuntimeAllPresent = false;
if(inPlacePack)
{
const QStringList mingwRuntimeDlls = QStringList()
<< QStringLiteral("libgcc_s_seh-1.dll")
<< QStringLiteral("libstdc++-6.dll")
<< QStringLiteral("libwinpthread-1.dll");
mingwRuntimeAllPresent = true;
for(const QString &dllName: mingwRuntimeDlls)
{
if(!QFile::exists(outDir.filePath(dllName)))
{
mingwRuntimeAllPresent = false;
break;
}
}
}
if(mingwRuntimeAllPresent)
{
appendLog(QStringLiteral("ℹ️ 输出目录已存在完整的 MinGW 运行库,本次跳过 --compiler-runtime(避免删除被占用的同名 DLL)"));
}
else
{
args << QStringLiteral("--compiler-runtime");
}
}
appendLog(QStringLiteral("执行 windeployqt: %1 %2").arg(windeployqt, args.join(QStringLiteral(" "))));
deployProcess->setProgram(windeployqt);
deployProcess->setArguments(args);
deployProcess->setWorkingDirectory(qtBinDir);
//将配套 MinGW 工具链 bin 前置到 PATH,避免 windeployqt 从 PATH 中其它 MinGW 目录复制版本不匹配的运行库 DLL
QString mingwRuntimeDir = findMinGwRuntimeDir(qtBinDir);
if(!mingwRuntimeDir.isEmpty())
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert(QStringLiteral("PATH"), mingwRuntimeDir + QDir::listSeparator() + env.value(QStringLiteral("PATH")));
deployProcess->setProcessEnvironment(env);
appendLog(QStringLiteral("ℹ️ 已前置 MinGW 运行库目录到 PATH:%1").arg(mingwRuntimeDir));
}
//保存本次启动参数,被锁文件改名让位后需要原样重跑
lastWindeployqtPath = windeployqt;
lastDeployArgs = args;
lastDeployWorkDir = qtBinDir;
lastDeployRuntimeDir = mingwRuntimeDir;
deployRetryCount = 0;
deployProcess->start();
}
void MainWindow::on_btnStopDeploy_clicked()
{
if(deployProcess->state() != QProcess::NotRunning)
{
deployProcess->kill();
appendLog(QStringLiteral("⚠️ 打包进程已终止"));
}
}
void MainWindow::onDeployFinished(int exitCode, QProcess::ExitStatus status)
{
if(shuttingDown)
{
return; //窗口已在关闭,不再发起重试或封包
}
if(status == QProcess::NormalExit && exitCode == 0)
{
appendLog(QStringLiteral("✅ windeployqt执行完成"));
QString outputDir = ui->edtOutputDir->text().trimmed();
//windeployqt 完成后校正 MinGW 运行库 DLL 来源,防止输出目录混入从其它 MinGW 目录复制来的版本
//运行库来源固定为界面上选的 Qt Bin 目录(该 Qt 版本的 bin 自带配套运行库),
//不再去系统里找别的 MinGW,避免混入 Strawberry Perl 之类自带工具链的版本
fixMinGwRuntimeDlls(outputDir, ui->edtQtBin->text().trimmed());
if(ui->chkCopyVcRuntime->isChecked())
{
copyVcRuntimeDlls(outputDir);
}
if(ui->chkEnigmaPack->isChecked())
{
QString enigmaConsolePath = ui->edtEnigmaVbPath->text().trimmed();
//以界面填写的目标EXE为准确定主程序与Single命名(目录内存在其它exe时不再取错)
QString targetExe = QDir(outputDir).filePath(QFileInfo(ui->edtExePath->text().trimmed()).fileName());
runEnigmaVbPack(outputDir, enigmaConsolePath, targetExe, currentQtVersion, currentCompilerType);
}
else
{
//未封包时部署到此结束,立即尝试清理部署过程中改名让位的备份文件
cleanupLockedBackups(outputDir);
}
}
else
{
//被锁文件让位后重跑:windeployqt 对 MinGW 运行库是先删后拷,
//目标程序正在运行时同名 DLL 删不掉,重跑前把文件改名绕过文件锁
if(deployRetryCount < 2)
{
const int backedUpCount = backupLockedFilesFromOutput();
if(backedUpCount > 0)
{
++deployRetryCount;
restartDeployProcess();
return;
}
}
//彻底失败:先把提前让位的运行库改回原名,别让输出目录少 DLL
restorePreBackups();
appendLog(QStringLiteral("❌ windeployqt失败 exitCode=%1").arg(exitCode));
//常见失败原因提示:目标exe与所选Qt Bin版本/编译器不匹配
if(deployOutputBuffer.contains(QStringLiteral("does not seem to be a Qt executable"), Qt::CaseInsensitive))
{
appendLog(QStringLiteral("⚠️ 提示:目标exe与所选“Qt Bin目录”版本/编译器不匹配(例如用Qt6的windeployqt部署Qt5程序,或MinGW版windeployqt部署MSVC程序)。"));
appendLog(QStringLiteral(" 请将Qt Bin目录切换为目标exe实际使用的Qt版本与编译器对应的bin目录(含windeployqt.exe),并重新打包。"));
}
}
}
//启动 windeployqt 之前,把部署目录里会被它「先删后拷」的运行库一次性改名让位:
//目标程序正在运行时这些 DLL 被锁,删不掉就会以 exitCode=1 结束;逐个等它报错再让位
//要重试好几轮,提前让位后目标文件不存在,windeployqt 会直接拷贝新文件,一次到位
void MainWindow::preBackupRuntimeDlls(const QString &outputDir, const QString &compilerType, bool copyVcRuntime)
{
preBackupOriginals.clear();
QStringList runtimeDllNames;
if(compilerType.compare(QStringLiteral("MinGW"), Qt::CaseInsensitive) == 0)
{
runtimeDllNames << QStringLiteral("libgcc_s_seh-1.dll")
<< QStringLiteral("libstdc++-6.dll")
<< QStringLiteral("libwinpthread-1.dll");
}
//VC 运行库只有在勾选「复制VC运行库」时才会被补回(windeployqt --compiler-runtime 或本程序兜底),
//否则让位后目录里就缺这几个 DLL,因此跟勾选状态绑定
if(copyVcRuntime)
{
runtimeDllNames << QStringLiteral("vcruntime140.dll")
<< QStringLiteral("vcruntime140_1.dll")
<< QStringLiteral("msvcp140.dll")
<< QStringLiteral("msvcp140_1.dll")
<< QStringLiteral("msvcp140_2.dll")
<< QStringLiteral("concrt140.dll");
}
const QString backupSuffix = QStringLiteral(".wdh-locked");
QDir dir(outputDir);
for(const QString &name: runtimeDllNames)
{
const QString filePath = dir.filePath(name);
if(!QFile::exists(filePath))
{
continue;
}
const QString backupPath = filePath + backupSuffix;
if(QFile::exists(backupPath))
{
QFile::remove(backupPath); //上次的备份此时已不被占用,先清掉
}
if(QFile::rename(filePath, backupPath))
{
preBackupOriginals << filePath;
}
}
if(!preBackupOriginals.isEmpty())
{
appendLog(QStringLiteral("ℹ️ 已提前让位 %1 个运行库(运行中的程序会锁住它们,改名不影响其继续运行)")
.arg(preBackupOriginals.size()));
}
}
//部署彻底失败时把提前让位的运行库改回原名,避免输出目录里少了这些 DLL
void MainWindow::restorePreBackups()
{
for(const QString &filePath: preBackupOriginals)
{
const QString backupPath = filePath + QStringLiteral(".wdh-locked");
if(!QFile::exists(backupPath))
{
continue;
}
QFile::remove(filePath); //windeployqt 可能已放入同名新文件,先清掉再恢复旧文件
QFile::rename(backupPath, filePath);
}
if(!preBackupOriginals.isEmpty())
{
appendLog(QStringLiteral("ℹ️ 部署失败,已恢复提前让位的 %1 个运行库").arg(preBackupOriginals.size()));
}
preBackupOriginals.clear();
}
int MainWindow::backupLockedFilesFromOutput()
{
//windeployqt 失败时会输出「Cannot remove existing file <完整路径>」:把这些文件在同目录内改名,
//文件句柄仍指向原文件,运行中的程序不受影响,而同名新文件可以正常写入
static const QRegularExpression lockedPattern(QStringLiteral("Cannot remove existing file ([^\\r\\n]+)"));
const QString backupSuffix = QStringLiteral(".wdh-locked");
QStringList lockedFilePaths;
QRegularExpressionMatchIterator matchIt = lockedPattern.globalMatch(deployOutputBuffer);
while(matchIt.hasNext())
{
QRegularExpressionMatch match = matchIt.next();
//windeployqt 在路径后还跟一个冒号作分隔("...\libgcc_s_seh-1.dll:"),
//不剥掉就会拿着一个带冒号、实际不存在的文件名去改名,让位必然失败
QString capturedPath = match.captured(1).trimmed();
while(capturedPath.endsWith(QLatin1Char(':')))
{
capturedPath.chop(1);
capturedPath = capturedPath.trimmed();
}
const QString filePath = QDir::fromNativeSeparators(capturedPath);
if(!lockedFilePaths.contains(filePath))
{
lockedFilePaths << filePath;
}
}
if(lockedFilePaths.isEmpty())
{
return 0;
}
int backedUpCount = 0;
for(const QString &filePath: lockedFilePaths)
{
const QString backupPath = filePath + backupSuffix;
if(QFile::exists(backupPath))
{
QFile::remove(backupPath); //上次的备份此时已不被占用,先清掉
}
QFile lockedFile(filePath);
if(lockedFile.exists() && lockedFile.rename(backupPath))
{
++backedUpCount;
appendLog(QStringLiteral("ℹ️ 文件被占用,已改名让位:%1 → %2")
.arg(QFileInfo(filePath).fileName(), QFileInfo(backupPath).fileName()));
}
else
{
//日志带上具体系统错误,便于区分「路径解析错」和「被其它进程独占」
appendLog(QStringLiteral("⚠️ 无法改名占用文件(%1):%2")
.arg(lockedFile.exists() ? lockedFile.errorString() : QStringLiteral("文件不存在"),
filePath));
}
}
return backedUpCount;
}
void MainWindow::restartDeployProcess()
{
deployOutputBuffer.clear();
deployProcess->setProgram(lastWindeployqtPath);
deployProcess->setArguments(lastDeployArgs);
deployProcess->setWorkingDirectory(lastDeployWorkDir);
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
if(!lastDeployRuntimeDir.isEmpty())
{
env.insert(QStringLiteral("PATH"), lastDeployRuntimeDir + QDir::listSeparator() + env.value(QStringLiteral("PATH")));
}
deployProcess->setProcessEnvironment(env);
appendLog(QStringLiteral("↻ 文件让位完成,重新执行 windeployqt(第 %1 次重试)").arg(deployRetryCount));
deployProcess->start();
}
void MainWindow::cleanupLockedBackups(const QString &dirPath)
{
//被占用改名让位留下的备份:锁一释放就能删,所以在打包结束、封包结束、程序退出时各试一次
const QString scanDir = dirPath.isEmpty() ? QCoreApplication::applicationDirPath() : dirPath;
QDir scanQDir(scanDir);
if(!scanQDir.exists())
{
return;
}
const QFileInfoList backupFiles = scanQDir.entryInfoList(QStringList() << QStringLiteral("*.wdh-locked"), QDir::Files);
if(backupFiles.isEmpty())
{
return;
}
int removedCount = 0;
int leftCount = 0;
for(const QFileInfo &fileInfo: backupFiles)
{
if(QFile::remove(fileInfo.absoluteFilePath()))
{
++removedCount;
}
else
{
++leftCount;
}
}
if(removedCount > 0)
{
appendLog(QStringLiteral("🧹 已清理占用备份文件 %1 个").arg(removedCount));
}
if(leftCount > 0)
{
appendLog(QStringLiteral("ℹ️ 仍有 %1 个备份文件被占用删不掉,将在下次启动时清理").arg(leftCount));
}
}
void MainWindow::onDeployReadyReadStdout()
{
QString out = QString::fromUtf8(deployProcess->readAllStandardOutput());
deployOutputBuffer.append(out);
appendLog(out);
}
void MainWindow::onDeployReadyReadStderr()
{
QString err = QString::fromUtf8(deployProcess->readAllStandardError());
deployOutputBuffer.append(err);
appendLog(err);
}
void MainWindow::on_btnSaveConfig_clicked()
{
saveSettings();
appendLog(QStringLiteral("✅ 配置已保存到 config.ini"));
}
void MainWindow::on_btnLoadConfig_clicked()
{
loadSettings();
appendLog(QStringLiteral("✅ 已加载 config.ini"));
}
void MainWindow::on_btnClearLog_clicked()
{
ui->txtLog->clear();
}
void MainWindow::on_btnSaveLog_clicked()
{
QString filePath = QFileDialog::getSaveFileName(this, QStringLiteral("保存日志"), QStringLiteral("deploy_log.txt"), QStringLiteral("Text(*.txt)"));
if(filePath.isEmpty())
{
return;
}
QFile f(filePath);
if(f.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream ts(&f);
ts << ui->txtLog->toPlainText();
f.close();
appendLog(QStringLiteral("✅ 日志保存至 %1").arg(filePath));
}
else
{
appendLog(QStringLiteral("❌ 日志保存失败"));
}
}
bool MainWindow::detectQtCompiler(const QString &qtBinDir, QString &compilerType, QString &qtVersion)
{
compilerType = QStringLiteral("Unknown");
qtVersion = QString();
QString qmakePath = QDir(qtBinDir).filePath(QStringLiteral("qmake.exe"));
if(!QFile::exists(qmakePath))
{
appendLog(QStringLiteral("⚠️ qmake.exe不存在,无法识别编译器"));
return false;
}
QProcess proc;
proc.setProgram(qmakePath);
proc.setArguments({QStringLiteral("-v")});
proc.start();
if(!proc.waitForFinished(3000))
{
appendLog(QStringLiteral("⚠️ qmake -v 执行超时"));
proc.kill();
return false;
}
QString output = QString::fromUtf8(proc.readAllStandardOutput());
appendLog(QStringLiteral("qmake -v 输出:\n") + output);
//解析版本号:qmake -v 输出形如 "Using Qt version 6.8.3 in E:/Qt/6.8.3/mingw_64/lib"
const QRegularExpression versionRe(QStringLiteral("Using Qt version\\s+([0-9]+(?:\\.[0-9]+)*)"));
const QRegularExpressionMatch versionMatch = versionRe.match(output);
if(versionMatch.hasMatch())
{
qtVersion = versionMatch.captured(1);
}
else
{
appendLog(QStringLiteral("⚠️ 未能从 qmake -v 输出解析 Qt 版本号,单文件名将使用 unknown 占位"));
}
if(output.contains(QStringLiteral("MSVC"), Qt::CaseInsensitive) || output.contains(QStringLiteral("Microsoft Visual Studio"), Qt::CaseInsensitive))
{
compilerType = QStringLiteral("MSVC");
}
else if(output.contains(QStringLiteral("MinGW"), Qt::CaseInsensitive) || output.contains(QStringLiteral("g++"), Qt::CaseInsensitive))
{
compilerType = QStringLiteral("MinGW");
}
appendLog(QStringLiteral("✅ 识别编译器类型:%1(Qt 版本:%2)").arg(compilerType, qtVersion.isEmpty() ? QStringLiteral("未知") : qtVersion));
return true;
}
//打包前核对「所选 Qt」与「目标 EXE」是否配套:不匹配就用错版本的 Qt 去部署,
//会把不相关的 DLL 拷进输出目录,甚至覆盖掉程序真正需要的那份,所以这里先拦下来
bool MainWindow::checkQtTargetMatch(const QString &exePath, const QString &qtBinDir, const QString &compilerType)
{
//只看导入表里的真实依赖,不做全文扫描(本程序自身代码里也写满了这些 DLL 名)
const QStringList importedDlls = readImportDllNames(exePath);
if(importedDlls.isEmpty())
{
appendLog(QStringLiteral("❌ 无法解析目标 EXE 的导入表,未能校验 Qt 版本:%1")
.arg(QDir::toNativeSeparators(exePath)));
return false;
}
const bool targetUsesQt5 = importedDlls.contains(QStringLiteral("Qt5Core.dll"), Qt::CaseInsensitive);
const bool targetUsesQt6 = importedDlls.contains(QStringLiteral("Qt6Core.dll"), Qt::CaseInsensitive);
//MinGW 的程序动态链接 libgcc/libstdc++,若用了 -static-libgcc -static-libstdc++ 则只剩
//libwinpthread-1.dll 这一个 MinGW 特征,所以三个都要看
const bool targetIsMinGw = importedDlls.contains(QStringLiteral("libgcc_s_seh-1.dll"), Qt::CaseInsensitive)
|| importedDlls.contains(QStringLiteral("libgcc_s_dw2-1.dll"), Qt::CaseInsensitive)
|| importedDlls.contains(QStringLiteral("libstdc++-6.dll"), Qt::CaseInsensitive)
|| importedDlls.contains(QStringLiteral("libwinpthread-1.dll"), Qt::CaseInsensitive);
const bool targetIsMsvc = importedDlls.contains(QStringLiteral("vcruntime140.dll"), Qt::CaseInsensitive)
|| importedDlls.contains(QStringLiteral("msvcp140.dll"), Qt::CaseInsensitive);
//所选 Qt 的版本看 bin 目录里装的是 Qt5Core.dll 还是 Qt6Core.dll,二者不会同时存在
QDir qtBin(qtBinDir);
QString kitCoreDll;
const bool kitUsesQt5 = QFile::exists(qtBin.filePath(QStringLiteral("Qt5Core.dll")));
const bool kitUsesQt6 = QFile::exists(qtBin.filePath(QStringLiteral("Qt6Core.dll")));
if(kitUsesQt5 && !kitUsesQt6)
{
kitCoreDll = QStringLiteral("Qt5Core.dll");
}
else if(kitUsesQt6 && !kitUsesQt5)
{
kitCoreDll = QStringLiteral("Qt6Core.dll");
}
else
{
appendLog(QStringLiteral("⚠️ 无法从 Qt Bin 目录判断所选 Qt 版本(Qt5Core.dll/Qt6Core.dll 缺失或同时存在),跳过版本校验"));
}
//1) Qt 主版本必须一致
if(!kitCoreDll.isEmpty())
{
if(targetUsesQt5 && kitCoreDll == QStringLiteral("Qt6Core.dll"))
{
appendLog(QStringLiteral("❌ 版本不匹配:目标 EXE 是 Qt5 程序,所选 Qt 是 Qt6(%1),请改选 Qt5 的 bin 目录")
.arg(QDir::toNativeSeparators(qtBinDir)));
return false;
}
if(targetUsesQt6 && kitCoreDll == QStringLiteral("Qt5Core.dll"))
{
appendLog(QStringLiteral("❌ 版本不匹配:目标 EXE 是 Qt6 程序,所选 Qt 是 Qt5(%1),请改选 Qt6 的 bin 目录")
.arg(QDir::toNativeSeparators(qtBinDir)));
return false;
}
if(!targetUsesQt5 && !targetUsesQt6)
{
appendLog(QStringLiteral("⚠️ 目标 EXE 未发现 Qt5Core.dll/Qt6Core.dll 依赖(可能是静态链接 Qt),跳过 Qt 版本校验"));
}
}
//2) 位数必须一致:目标 EXE 与所选 Qt 的 Core DLL 各读一次 PE 头
const QString targetBits = getExeArchBits(exePath);
const QString kitBits = kitCoreDll.isEmpty() ? QString() : getExeArchBits(qtBin.filePath(kitCoreDll));
if(!targetBits.isEmpty() && !kitBits.isEmpty() && targetBits != kitBits)
{
appendLog(QStringLiteral("❌ 位数不匹配:目标 EXE 是 %1 位,所选 Qt 是 %2 位(%3),请改选 %1 位的 Qt")
.arg(targetBits, kitBits, QDir::toNativeSeparators(qtBinDir)));
return false;
}
//3) 编译器类型必须一致(目标 EXE 的运行库是静态链接时判不出来,此时不做阻断)
if(targetIsMinGw && !targetIsMsvc && compilerType.compare(QStringLiteral("MSVC"), Qt::CaseInsensitive) == 0)
{
appendLog(QStringLiteral("❌ 编译器不匹配:目标 EXE 依赖 MinGW 运行库(libgcc/libstdc++),所选 Qt 是 MSVC 版,请改选 MinGW 版 Qt"));
return false;
}
if(targetIsMsvc && !targetIsMinGw && compilerType.compare(QStringLiteral("MinGW"), Qt::CaseInsensitive) == 0)
{
appendLog(QStringLiteral("❌ 编译器不匹配:目标 EXE 依赖 VC 运行库(vcruntime140/msvcp140),所选 Qt 是 MinGW 版,请改选 MSVC 版 Qt"));
return false;
}
if(!targetIsMinGw && !targetIsMsvc)
{
appendLog(QStringLiteral("ℹ️ 未能从目标 EXE 判断编译器类型(运行库可能静态链接),跳过编译器校验"));
}
appendLog(QStringLiteral("✅ Qt 版本校验通过:目标 EXE 与所选 Qt(%1 / %2 / %3 位)配套")
.arg(kitCoreDll.isEmpty() ? QStringLiteral("版本未知") : kitCoreDll, compilerType,
kitBits.isEmpty() ? QStringLiteral("?") : kitBits));
return true;
}
//定位与所选 Qt Bin 配套的 MinGW 工具链 bin 目录(含 libstdc++-6.dll 等运行库 DLL)
QString MainWindow::findMinGwRuntimeDir(const QString &qtBinDir) const
{
QDir qtBin(qtBinDir);
const QString kitStdCppPath = qtBin.filePath(QStringLiteral("libstdc++-6.dll"));
const qint64 kitStdCppSize = QFileInfo(kitStdCppPath).size();
//1) 优先 <Qt根>/Tools/mingw*/bin:windeployqt 是靠 PATH 里的 g++.exe 定位 MinGW 运行库来源的,
// Qt kit 的 bin 里只有 DLL 没有 g++,只前置它仍会命中系统里别的 MinGW(例如 Strawberry Perl
// 自带的 D:\Strawberry\c\bin),部署出来的运行库版本与 Qt 不匹配,下次打包就因旧文件删不掉而失败。
// 工具链有多个版本时,按 libstdc++-6.dll 大小与 Qt kit 完全一致来认定同版本
QDir qtRoot = qtBin;
qtRoot.cdUp(); //<Qt根>/<版本>/<kit>
qtRoot.cdUp(); //<Qt根>/<版本>
qtRoot.cdUp(); //<Qt根>
const QDir toolsDir(qtRoot.filePath(QStringLiteral("Tools")));
QStringList candidates;
QStringList sameVersionCandidates;
if(toolsDir.exists())
{
const QStringList mingwDirs = toolsDir.entryList(QStringList() << QStringLiteral("mingw*"), QDir::Dirs | QDir::NoDotAndDotDot);
for(const QString &dirName: mingwDirs)
{
QDir binDir(toolsDir.filePath(dirName + QStringLiteral("/bin")));
QString gppPath = binDir.filePath(QStringLiteral("g++.exe"));
QString stdCppPath = binDir.filePath(QStringLiteral("libstdc++-6.dll"));
if(!QFile::exists(gppPath) || !QFile::exists(stdCppPath))
{
continue;
}
candidates << binDir.absolutePath();
if(kitStdCppSize > 0 && QFileInfo(stdCppPath).size() == kitStdCppSize)
{
sameVersionCandidates << binDir.absolutePath();
}
}
}
if(!sameVersionCandidates.isEmpty())
{
return sameVersionCandidates.first();
}
//2) 没有严格同版本的工具链时,退回 Qt kit 自带运行库:版本与 Qt 一致,能保证程序可运行
if(QFile::exists(kitStdCppPath))
{
return qtBin.absolutePath();