-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphoneaudiolink.cpp
More file actions
840 lines (697 loc) · 31.1 KB
/
phoneaudiolink.cpp
File metadata and controls
840 lines (697 loc) · 31.1 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
#include "phoneaudiolink.h"
#include "ui_phoneaudiolink.h"
#include <QRegularExpression>
#include <QProcess>
#include <QTimer>
#include <iomanip>
#include <sstream>
#include <iostream>
#define VERSION_STR() ([]() -> QString { \
std::stringstream tmp; \
tmp << std::fixed << std::setprecision(GLOBAL_MINOR_PROGRAM_VERSION_SIZE); \
tmp << GLOBAL_PROGRAM_VERSION; \
return QString::fromStdString(tmp.str()); \
})()
PhoneAudioLink::PhoneAudioLink(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::PhoneAudioLink)
, audioSessionManager(nullptr)
, audioSink(nullptr)
, updateChecker(new UpdateChecker(this))
{
ui->setupUi(this);
// Create update notification bar and add to bottom of window
updateNotificationBar = new UpdateNotificationBar(this);
// Add notification bar to the main window layout
ui->updateBarLayout->addWidget(updateNotificationBar);
// Connect update checker signals
connect(updateChecker, &UpdateChecker::updateAvailable,
this, &PhoneAudioLink::onUpdateAvailable);
connect(updateChecker, &UpdateChecker::checkFailed, this, [](const QString &error) {
qDebug() << "Update check failed:" << error;
});
connect(updateChecker, &UpdateChecker::noUpdateAvailable, this, [this](){
if(this->manuallyChecked)
QMessageBox::information(this, "Updater", "No update available!");
});
// Connect notification bar signals
connect(updateNotificationBar, &UpdateNotificationBar::seeDetailsClicked,
this, &PhoneAudioLink::showReleaseNotes);
connect(updateNotificationBar, &UpdateNotificationBar::updateClicked,
this, &PhoneAudioLink::launchMaintenanceTool);
connect(updateNotificationBar, &UpdateNotificationBar::closeClicked,
updateNotificationBar, &UpdateNotificationBar::hideBar);
connect(updateNotificationBar, &UpdateNotificationBar::closeClicked,
this, [this](){this->resize(this->width(), 316);});
// Check for updates after a short delay (let the UI load first)
QTimer::singleShot(2000, this, [this]() {
updateChecker->checkForUpdates(VERSION_STR());
});
connect(ui->actionCheckUpdate, &QAction::triggered, this, [this](){
updateChecker->checkForUpdates(VERSION_STR());
manuallyChecked = true;
});
ui->dcLabel->setStyleSheet("QLabel { color : red; }");
ui->menuAdvanced->setToolTipsVisible(true);
// Set icons based on color scheme
if(QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Light) {
ui->forward->setIcon(QPixmap(":/icons/Iconparts/forward-512.png"));
ui->back->setIcon(QPixmap(":/icons/Iconparts/back-512.png"));
}
else if(QGuiApplication::styleHints()->colorScheme() == Qt::ColorScheme::Dark) {
ui->forward->setIcon(QPixmap(":/icons/Iconparts/forward-512-white.png"));
ui->back->setIcon(QPixmap(":/icons/Iconparts/back-512-white.png"));
}
// Create A2DP Sink manager
audioSink = new BluetoothA2DPSink(this);
// Connect A2DP device discovery signals
connect(audioSink, &BluetoothA2DPSink::deviceDiscovered, this,
&PhoneAudioLink::onA2DPDeviceDiscovered);
connect(audioSink, &BluetoothA2DPSink::discoveryCompleted, this,
&PhoneAudioLink::onA2DPDiscoveryCompleted);
// Connect sink signals to UI updates
connect(audioSink, &BluetoothA2DPSink::sinkEnabled, this, [this]() {
ui->dcLabel->setText("Sink Enabled");
ui->dcLabel->setStyleSheet("QLabel { color : orange; }");
qDebug() << "A2DP Sink enabled, now open connection";
// Automatically open the connection after enabling
QTimer::singleShot(500, this, [this]() {
audioSink->openConnection();
});
});
connect(audioSink, &BluetoothA2DPSink::connectionOpened, this, [this]() {
// Only show notification if we haven't already for this connection
if (!connectionNotificationShown) {
connectionNotificationShown = true;
qDebug() << "Audio streaming active!";
// Show notification once
if (trayIcon) {
trayIcon->showMessage("Audio Streaming",
"Your phone is now streaming audio to this PC",
QSystemTrayIcon::Information, 3000);
}
}
ui->dcLabel->setText("Connected");
ui->dcLabel->setStyleSheet("QLabel { color : green; }");
ui->connect->setEnabled(false);
ui->disconnect->setEnabled(true);
});
connect(audioSink, &BluetoothA2DPSink::connectionClosed, this, [this]() {
// Reset notification flag so it shows again on next connection
connectionNotificationShown = false;
ui->dcLabel->setText("Disconnected!");
ui->dcLabel->setStyleSheet("QLabel { color : red; }");
ui->connect->setEnabled(true);
ui->disconnect->setEnabled(false);
qDebug() << "Audio streaming stopped";
});
connect(audioSink, &BluetoothA2DPSink::connectionError, this, [this](const QString &error) {
QMessageBox::warning(this, tr("Connection Error"), error);
ui->dcLabel->setText("Error");
ui->dcLabel->setStyleSheet("QLabel { color : red; }");
qWarning() << "Connection error:" << error;
});
connect(audioSink, &BluetoothA2DPSink::stateChanged, this, [](const QString &state) {
qDebug() << "Sink state:" << state;
});
//create and connect the bluetooth discovery agent
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered,
this, &PhoneAudioLink::appendDevice);
//error catching
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::errorOccurred,
this, [this](QBluetoothDeviceDiscoveryAgent::Error e){
qDebug()<<e;
if(e == QBluetoothDeviceDiscoveryAgent::NoError) return;
else if(e == 2)
QMessageBox::critical(this, tr("Bluetooth Error"), tr("PoweredOffError: Make sure that bluetooth is turned on."));
else
QMessageBox::critical(this, tr("Bluetooth Error"), tr("Unknown: Open a bug report with this info: %1").arg(e));
});
startDiscovery(); //automatically look for devices
//load initialization data from "init.json" if it exists
loadInitData();
if(maximizeBluetoothCompatability)
ui->info->setToolTip("Showing all devices for compatability's sake.\nNot all of these devices are guaranteed to be supported.");
else
ui->info->setToolTip("Filtering for only phone devices.\nUse Advanced->Maximize Bluetooth compatability to show more devices.");
//create a system tray icon
trayIcon = new QSystemTrayIcon(QIcon(":/icons/icon.ico"), this);
//create the tray context menu
trayMenu = new QMenu(this);
QTimer::singleShot(2000, this, &PhoneAudioLink::updateTrayContext);
//connect tray icon clicked signal to showFromTray
connect(trayIcon, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r){
if(r == QSystemTrayIcon::ActivationReason::MiddleClick){
this->exitApp();
return;
}
else if(r == QSystemTrayIcon::ActivationReason::Trigger || r == QSystemTrayIcon::ActivationReason::DoubleClick){
this->showFromTray();
return;
}
});
// Connect UI buttons to A2DP sink
connect(ui->playPause, &QPushButton::pressed, this, &PhoneAudioLink::playPause);
connect(ui->forward, &QPushButton::pressed, this, [this]() {
if (audioSink) audioSink->sendNext();
});
connect(ui->back, &QPushButton::pressed, this, [this]() {
if (audioSink) audioSink->sendPrevious();
});
connect(ui->refresh, &QPushButton::pressed, this, &PhoneAudioLink::startDiscovery);
connect(ui->connect, &QPushButton::pressed, this, &PhoneAudioLink::connectSelectedDevice);
connect(ui->disconnect, &QPushButton::pressed, this, &PhoneAudioLink::disconnect);
connect(ui->deviceComboBox, &QComboBox::currentIndexChanged, this,
&PhoneAudioLink::deviceComboChanged);
// Setup Menu Actions
ui->compatAction->setChecked(maximizeBluetoothCompatability);
ui->startMinimizedAction->setChecked(startMinimized);
connect(ui->compatAction, &QAction::triggered, this, [this](bool checked){
maximizeBluetoothCompatability=checked;
//change the info tooltip
if(maximizeBluetoothCompatability)
ui->info->setToolTip("Showing all devices for compatability's sake.\nNot all of these devices are guaranteed to support A2DP.");
else
ui->info->setToolTip("Filtering for only phone devices.\nUse Advanced->Maximize Bluetooth compatability to show more devices.");
//refresh devices
startDiscovery();
});
connect(ui->menuConnectOnLaunch, &QMenu::hovered, this, [this](){
static int c;
if(c == 50){
this->updateAutoConnectMenu();
this->updateTrayContext();
c = 0;
}
c++;
});
QTimer::singleShot(2000, this, &PhoneAudioLink::updateAutoConnectMenu);
connect(ui->startMinimizedAction, &QAction::triggered, this, [this](bool checked){
this->startMinimized=checked;
this->updateTrayContext();
this->updateAutoConnectMenu();
});
startupHelp = new StartupHelp(this);
connect(ui->startOnLoginAction, &QAction::triggered, this, [this](){
this->startupHelp->exec();
});
connect(ui->versionAction, &QAction::triggered, this, [this](){
QMessageBox::information(this, tr("Program Version"), tr("Version %1\t").arg(GLOBAL_PROGRAM_VERSION));
});
connect(ui->info, &QPushButton::clicked, this, [this](){
QToolTip::showText(this->mapToGlobal(ui->info->pos()), ui->info->toolTip(), this, {}, 10000);
});
connect(ui->debug, &QAction::triggered, this, [this](){
qDebug()<<"name: "<<ui->deviceComboBox->currentData().value<QBluetoothDeviceInfo>().name();
QBluetoothLocalDevice localDevice;
qDebug()<<"state: "<<localDevice.pairingStatus(ui->deviceComboBox->currentData().value<QBluetoothDeviceInfo>().address());
qDebug()<<"address:"<<ui->deviceComboBox->currentData().value<QBluetoothDeviceInfo>().address();
this->updateTrayContext();
this->updateAutoConnectMenu();
});
#ifdef RELEASE_BUILD
ui->debug->setVisible(false);
#endif
// Initial button states
ui->connect->setEnabled(true);
ui->disconnect->setEnabled(false);
// Auto-connect if enabled and device was saved
if (connectAutomatically) {
QTimer::singleShot(2000, this, [this](){
QString name = this->findDeviceName(savedDeviceAddress);
int index = this->ui->deviceComboBox->findText(name);
if(this->ui->deviceComboBox->count() > 0 && index != -1){
this->ui->deviceComboBox->setCurrentIndex(index);
this->connectSelectedDevice();
this->updateTrayContext();
this->updateAutoConnectMenu();
}
});
}
}
//destructor
PhoneAudioLink::~PhoneAudioLink() {
// Stop device watchers
if (audioSink) {
audioSink->stopDeviceDiscovery();
audioSink->deleteLater();
audioSink = nullptr;
}
if(discoveryAgent){
discoveryAgent->stop();//stop bluetooth discovery
discoveryAgent->deleteLater();
discoveryAgent = nullptr;
}
if(ui->dcLabel->text() == "Connected")
ui->disconnect->click();
delete ui;
}
//public function that returns if the program should start in a minimized state
bool PhoneAudioLink::getStartMinimized(){
return this->startMinimized;
}
//detect window minimize event
void PhoneAudioLink::changeEvent(QEvent *event) {
if (event->type() == QEvent::WindowStateChange) {
if (isMinimized()) {
saveInitData();
QTimer::singleShot(0, this, &PhoneAudioLink::hide); // hide after minimize animation
}
}
QMainWindow::changeEvent(event); //call the super method
}
void PhoneAudioLink::showEvent(QShowEvent *event) {
QMainWindow::showEvent(event);
windowShown = true;
updateTrayContext();
}
void PhoneAudioLink::hideEvent(QHideEvent *event) {
QMainWindow::hideEvent(event);
windowShown = false;
updateTrayContext();
}
//show the window from tray
void PhoneAudioLink::showFromTray() {
// show();
// setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
// raise();
showNormal();
raise();
activateWindow();
// activateWindow();
}
void PhoneAudioLink::updateTrayContext(){
trayMenu->clear();
for(auto* i:std::as_const(trayDeviceActions))
delete i;
trayDeviceActions.clear();
for(auto * i:std::as_const(trayDeviceStartupActions))
delete i;
trayDeviceStartupActions.clear();
QMenu *devicesMenu = new QMenu("Connect");
for (int i = 0; i < ui->deviceComboBox->count(); i++) {
trayDeviceActions.append(new QAction(ui->deviceComboBox->itemText(i)));
trayDeviceActions.last()->setCheckable(true);
if(ui->dcLabel->text() == "Connected" && trayDeviceActions.last()->text() == connectedDevice) trayDeviceActions.last()->setChecked(true);
else trayDeviceActions.last()->setChecked(false);
connect(trayDeviceActions.last(), &QAction::triggered, this, [this, i](){
ui->deviceComboBox->setCurrentIndex(i);
connectSelectedDevice();
});
devicesMenu->addAction(trayDeviceActions.last());
}
QAction *disconnectAction = new QAction("Disconnect", this);
disconnectAction->setCheckable(false);
if(ui->dcLabel->text() == "Disconnected!") disconnectAction->setDisabled(true);
else disconnectAction->setDisabled(false);
QMenu *settingsMenu = new QMenu("Settings");
QAction *startMinimized = new QAction("Start Minimized", this);
QMenu *autoConnect = new QMenu("Connect on Launch", this);
for (int i = 0; i < ui->deviceComboBox->count(); i++) {
trayDeviceStartupActions.append(new QAction(ui->deviceComboBox->itemText(i)));
trayDeviceStartupActions.last()->setCheckable(true);
if(connectAutomatically && [this](){
for (const QBluetoothDeviceInfo &info : std::as_const(this->discoveredDevices))
if (info.address() == this->savedDeviceAddress && info.name() == this->trayDeviceStartupActions.last()->text())
return true;
return false;
}()) trayDeviceStartupActions.last()->setChecked(true);
else trayDeviceStartupActions.last()->setChecked(false);
connect(trayDeviceStartupActions.last(), &QAction::triggered, this, [this, i](){
if(!this->connectAutomatically){
connectAutomatically = true;
this->savedDeviceAddress = ui->deviceComboBox->itemData(i).value<QBluetoothDeviceInfo>().address();
}
else connectAutomatically = false;
this->updateAutoConnectMenu();
});
autoConnect->addAction(trayDeviceStartupActions.last());
}
QAction *autoStart = new QAction("Start on Login", this);
startMinimized->setCheckable(true);
// autoConnect->setCheckable(true);
autoStart->setCheckable(false);
startMinimized->setChecked(this->startMinimized);
// autoConnect->setChecked(connectAutomatically);
settingsMenu->addAction(startMinimized);
settingsMenu->addMenu(autoConnect);
settingsMenu->addAction(autoStart);
QAction *restoreAction = new QAction("Show", this);
if(windowShown) restoreAction->setDisabled(true);
else restoreAction->setDisabled(false);
QAction *quitAction = new QAction("Exit", this);
quitAction->setCheckable(false);
//connect the tray context menu buttons to their respective actions
connect(startMinimized, &QAction::triggered, ui->startMinimizedAction, &QAction::trigger);
// connect(autoConnect, &QAction::triggered, ui->connectStartupAction, &QAction::trigger);
connect(disconnectAction, &QAction::triggered, ui->disconnect, &QPushButton::click);
connect(autoStart, &QAction::triggered, ui->startOnLoginAction, &QAction::trigger);
connect(restoreAction, &QAction::triggered, this, &PhoneAudioLink::showFromTray);
connect(quitAction, &QAction::triggered, this, &PhoneAudioLink::exitApp);
//add the actions
trayMenu->addMenu(devicesMenu);
trayMenu->addSeparator();
trayMenu->addAction(disconnectAction);
trayMenu->addSeparator();
// trayMenu->addAction(startMinimized);
// trayMenu->addAction(autoConnect);
// trayMenu->addAction(autoStart);
trayMenu->addMenu(settingsMenu);
trayMenu->addSeparator();
trayMenu->addAction(restoreAction);
trayMenu->addAction(quitAction);
//configure the tray icon
trayIcon->setContextMenu(trayMenu);
// Update tray tooltip
if(ui->dcLabel->text() == "Disconnected!") trayIcon->setToolTip("Disconnected!");
else if(ui->dcLabel->text() == "Connected") trayIcon->setToolTip("Connected to:\n"+connectedDevice);
else trayIcon->setToolTip("Connecting...");
// show the tray icon
trayIcon->show();
}
void PhoneAudioLink::updateAutoConnectMenu() {
ui->menuConnectOnLaunch->clear();
for (int i = 0; i < ui->deviceComboBox->count(); i++) {
autoConnectMenuActions.append(new QAction(ui->deviceComboBox->itemText(i)));
autoConnectMenuActions.last()->setCheckable(true);
if(connectAutomatically && [this](){
for (const QBluetoothDeviceInfo &info : std::as_const(this->discoveredDevices))
if (info.address() == this->savedDeviceAddress && info.name() == this->autoConnectMenuActions.last()->text())
return true;
return false;
}()) autoConnectMenuActions.last()->setChecked(true);
else autoConnectMenuActions.last()->setChecked(false);
connect(autoConnectMenuActions.last(), &QAction::triggered, this, [this, i](){
if(!this->connectAutomatically){
connectAutomatically = true;
this->savedDeviceAddress = ui->deviceComboBox->itemData(i).value<QBluetoothDeviceInfo>().address();
}
else connectAutomatically = false;
this->updateTrayContext();
});
ui->menuConnectOnLaunch->addAction(autoConnectMenuActions.last());
}
}
//exit the application
void PhoneAudioLink::exitApp() {
saveInitData();
// Cleanup audio session manager first (COM cleanup)
if (audioSessionManager) {
qDebug() << "Cleaning up AudioSessionManager";
audioSessionManager->cleanup();
audioSessionManager->deleteLater();
audioSessionManager = nullptr;
}
disconnect();
// Stop discovery
if (discoveryAgent) {
qDebug() << "Stopping discovery agent";
discoveryAgent->stop();
discoveryAgent->deleteLater();
discoveryAgent = nullptr;
}
if (audioSink) {
qDebug() << "Stopping A2DP sink device discovery";
audioSink->stopDeviceDiscovery();
audioSink->deleteLater();
audioSink = nullptr;
}
// hide the tray icon
trayIcon->hide();
// Process pending events before quitting
QCoreApplication::processEvents();
//QApplication::quit();//call the super method
// Force quit after a short delay to ensure cleanup completes
QTimer::singleShot(1000, []() {
qDebug() << "Force quitting application";
QCoreApplication::exit(0);
});
}
//handle the close event
void PhoneAudioLink::closeEvent(QCloseEvent *event) {
Q_UNUSED(event);
exitApp();
}
void PhoneAudioLink::playPause() {
ui->playPause->toggleState();
//TODO: change this to toggled so I know if we're paused or playing
// Send play/pause command via A2DP sink
if (audioSink)
audioSink->sendPlayPause();
}
void PhoneAudioLink::startDiscovery() {
// Reset current
ui->deviceComboBox->clear();
discoveredDevices.clear();
deviceIdMap.clear();
// Start Qt Bluetooth discovery (for display/pairing info)
discoveryAgent->stop();
discoveryAgent->start();
// Also start Windows device discovery for A2DP connection
if (audioSink) {
audioSink->startDeviceDiscovery();
}
// Update context menu after giving time for bluetooth discovery
QTimer::singleShot(3000, this, &PhoneAudioLink::updateTrayContext);
}
void PhoneAudioLink::onA2DPDeviceDiscovered(const QString &deviceId, const QString &deviceName) {
qDebug() << "A2DP device discovered:" << deviceName << "with ID:" << deviceId;
// Store the Windows device ID
deviceIdMap[deviceName] = deviceId;
}
void PhoneAudioLink::onA2DPDiscoveryCompleted() {
qDebug() << "A2DP discovery completed. Found" << deviceIdMap.size() << "devices!";
}
void PhoneAudioLink::appendDevice(const QBluetoothDeviceInfo &device) {
//filter devices
if(device.name().startsWith("Bluetooth") && device.name().contains(":")) {
return;
}
// qDebug()<<"discovered device";
// qDebug()<<"\tName: " <<device.name();
// qDebug()<<"\tMajor, Minor Device Classes: " <<device.majorDeviceClass()<<device.minorDeviceClass();
// qDebug()<<"\tDevice address: "<<device.address();
QString tag = "";
bool isPhone = device.majorDeviceClass() == QBluetoothDeviceInfo::PhoneDevice;
bool isAv = device.majorDeviceClass() == QBluetoothDeviceInfo::AudioVideoDevice;
if(maximizeBluetoothCompatability){
//set tag based off of device type
if(isPhone) tag=" [Phone Device]";
else if(isAv) tag=" [AV Device]";
else tag=" [UNKNOWN]";
//add the device
ui->deviceComboBox->addItem(device.name()+tag, QVariant::fromValue(device));
discoveredDevices.append(device);
//if it matches the saved device, set that to the current index
if(device.address() == savedDeviceAddress)
ui->deviceComboBox->setCurrentIndex(ui->deviceComboBox->findData(QVariant::fromValue(device)));
return;
}
if(isPhone){
//add the device
ui->deviceComboBox->addItem(device.name(), QVariant::fromValue(device));
discoveredDevices.append(device);
//if it matches the saved device, set that to the current index
if(device.address() == savedDeviceAddress)
ui->deviceComboBox->setCurrentIndex(ui->deviceComboBox->findData(QVariant::fromValue(device)));
return;
}
}
//connect to the device in the combo box
void PhoneAudioLink::connectSelectedDevice() {
updateTrayContext();
QString selectedText = ui->deviceComboBox->currentText();
// Remove any tags like [A2DP], [Phone Device], etc.
QString deviceName = selectedText;
deviceName.remove(QRegularExpression("\\s*\\[.*\\]\\s*"));
qDebug() << "Attempting to connect to:" << deviceName;
if (audioSink && deviceIdMap.contains(deviceName)) {
// Use the Windows device ID we got from DeviceWatcher
QString windowsDeviceId = deviceIdMap[deviceName];
qDebug() << "Using Windows device ID:" << windowsDeviceId;
ui->dcLabel->setText("Connecting...");
ui->dcLabel->setStyleSheet("QLabel { color : orange; }");
updateTrayContext();
// Enable the A2DP sink for this device
audioSink->enableSink(windowsDeviceId);
// wait a bit, then update the connected device
QTimer::singleShot(3000, this, [this, deviceName](){
if(ui->dcLabel->text() == "Connected")
this->connectedDevice = deviceName;
else //wait another 3 seconds if not connected yet
QTimer::singleShot(3000, this, [this, deviceName](){
if(ui->dcLabel->text() == "Connected") //if still not connected, then it will fail out before this happens
this->connectedDevice = deviceName;
this->updateTrayContext();
});
this->updateTrayContext();
});
// Create AudioSessionManager only when we actually need it
if (!audioSessionManager) {
audioSessionManager = new AudioSessionManager(this);
}
// Set custom name and icon in Volume Mixer
QString exePath = QCoreApplication::applicationFilePath();
QString displayName = QString("Phone Audio Link (%1)").arg(ui->deviceComboBox->currentData().value<QBluetoothDeviceInfo>().name());
// Try to set immediately, then retry after a delay, then retry again
QTimer::singleShot(500, this, [this, displayName, exePath]() {
audioSessionManager->setSessionProperties(displayName, exePath);
});
QTimer::singleShot(2000, this, [this, displayName, exePath]() {
audioSessionManager->setSessionProperties(displayName, exePath);
});
QTimer::singleShot(7000, this, [this, displayName, exePath]() {
audioSessionManager->setSessionProperties(displayName, exePath);
});
} else {
qWarning() << "Device not found in A2DP device map:" << deviceName;
QMessageBox::warning(this, tr("Connection Error"),
tr("Device not found. Please make sure the device supports A2DP and try refreshing the device list."));
}
updateTrayContext();
}
void PhoneAudioLink::disconnect() {
if (audioSink) {
audioSink->releaseConnection();
}
updateTrayContext();
}
//triggers when the index of the device combo box is changed
void PhoneAudioLink::deviceComboChanged(int i){
Q_UNUSED(i);
//qDebug()<<"changed index: "<<i;
updateAutoConnectMenu();
updateTrayContext();
}
//save initialization data
void PhoneAudioLink::saveInitData() {
//initialize the file object
QString fileName = QCoreApplication::applicationDirPath()+"/init.json";
QJsonObject config;
config["maximizeBluetoothCompatability"] = maximizeBluetoothCompatability;
config["connectAutomatically"] = connectAutomatically;
config["startMinimized"] = startMinimized;
config["device"] = savedDeviceAddress.toString();//ui->deviceComboBox->currentData().value<QBluetoothDeviceInfo>().address().toString();
//write the file
QFile file(fileName);
if (file.open(QIODevice::WriteOnly)) {
file.write(QJsonDocument(config).toJson());
file.close();
}
else {
//alert the user of errors
QMessageBox::critical(this, tr("Error"), tr("Failed to save initialization configuration file."));
}
updateTrayContext();
}
//load initialization data
void PhoneAudioLink::loadInitData(){
//initialize file object
QString initFilePath = QCoreApplication::applicationDirPath()+"/init.json";
QFile initFile(initFilePath);
bool err = false;
//check if init.json exists
if(initFile.exists()){
//read the file
if(!initFile.open(QIODevice::ReadOnly)){
QMessageBox::critical(this, tr("Error: FileReadError"), tr("Failed to open configuration file \'init.config\'"));
err = true;
}
QJsonDocument doc = QJsonDocument::fromJson(initFile.readAll());
initFile.close();
QJsonObject initConfig = doc.object();
//grab bluetooth compatability state
if (initConfig.contains("maximizeBluetoothCompatability"))
maximizeBluetoothCompatability = initConfig["maximizeBluetoothCompatability"].toBool();
else {
//alert user of incorrectly formatted configuration
QMessageBox::critical(this, tr("Error: NoBoolBluetoothError"), tr("Failed to parse configuration file \'init.config\'"));
err = true;
}
//grab automatic connection state
if(initConfig.contains("connectAutomatically"))
connectAutomatically = initConfig["connectAutomatically"].toBool();
else {
//alert user of incorrectly formatted configuration
QMessageBox::critical(this, tr("Error: NoBoolConnectError"), tr("Failed to parse configuration file \'init.config\'"));
err = true;
}
//grab start minimized state
if(initConfig.contains("startMinimized"))
startMinimized = initConfig["startMinimized"].toBool();
else {
//alert user of incorrectly formatted configuration
QMessageBox::critical(this, tr("Error: NoStartupMinimizedError"), tr("Failed to parse configuration file \'init.config\'"));
err = true;
}
//load the device
if (initConfig.contains("device")) {
savedDeviceAddress = QBluetoothAddress(initConfig["device"].toString());
}
else {
//alert user of incorrectly formatted configuration
QMessageBox::critical(this, tr("Error: NoDeviceError"), tr("Failed to parse configuration file \'init.config\'"));
err = true;
}
}
else{
//if the initialization configuration doesn't exist, set initialization info to defaults
maximizeBluetoothCompatability = false;
connectAutomatically = false;
startMinimized = false;
}
if(err)
QMessageBox::critical(this, tr("Error: Initialization Configuration File Corrupted"), tr("Try deleting the file \'init.config\' and restarting the program. \nYour Initialization settings will be cleared."));
}
//for debugging purposes
QString PhoneAudioLink::stringifyUuids(QList<QBluetoothUuid> l){
QString result = "";
for(QBluetoothUuid i:l){
result+=i.toString()+", ";
}
return result;
}
QString PhoneAudioLink::findDeviceName(const QBluetoothAddress& address){
for (const QBluetoothDeviceInfo &info : discoveredDevices) {
if (info.address() == address) {
return info.name();
}
}
// Not found
return QString();
}
void PhoneAudioLink::onUpdateAvailable(const QString &newVersion, const QString &releaseNotesUrl)
{
qDebug() << "Update available:" << newVersion;
pendingVersion = newVersion;
pendingReleaseNotesUrl = releaseNotesUrl;
updateNotificationBar->showUpdate(newVersion, releaseNotesUrl);
// Resize the main window to accomodate the update bar
this->resize(this->width(), 351);
}
void PhoneAudioLink::showReleaseNotes(const QString &releaseNotesUrl)
{
ReleaseNotesDialog *dialog = new ReleaseNotesDialog(pendingVersion, releaseNotesUrl, this);
connect(dialog, &ReleaseNotesDialog::updateRequested,
this, &PhoneAudioLink::launchMaintenanceTool);
dialog->exec();
dialog->deleteLater();
}
void PhoneAudioLink::launchMaintenanceTool()
{
QString maintenanceToolPath = QCoreApplication::applicationDirPath() + "/maintenancetool.exe";
qDebug() << "Launching maintenance tool:" << maintenanceToolPath;
if (!QFile::exists(maintenanceToolPath)) {
QMessageBox::warning(this, "Update Error",
"Maintenance tool not found. Please reinstall the application.");
return;
}
// Warn user
QMessageBox::information(this, "Update",
"The maintenance tool will now update PhoneAudioLink.\n"
"The application will now save config and close.");
// Launch maintenance tool in update mode
QProcess::startDetached(maintenanceToolPath, QStringList() << "--updater");
exitApp();
}