summaryrefslogtreecommitdiff
path: root/src/com/android/settings/connecteddevice/audiosharing/audiostreams/AudioStreamsProgressCategoryController.java
blob: 45f0c2fda3e3ad575d74f6b42c9f8d3f75b8fc27 (plain)
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
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings.connecteddevice.audiosharing.audiostreams;

import static java.util.Collections.emptyList;

import android.app.AlertDialog;
import android.app.settings.SettingsEnums;
import android.bluetooth.BluetoothLeBroadcastMetadata;
import android.bluetooth.BluetoothLeBroadcastReceiveState;
import android.content.Context;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;

import com.android.settings.R;
import com.android.settings.bluetooth.Utils;
import com.android.settings.connecteddevice.audiosharing.AudioSharingUtils;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.core.SubSettingLauncher;
import com.android.settingslib.bluetooth.BluetoothUtils;
import com.android.settingslib.bluetooth.LocalBluetoothLeBroadcastAssistant;
import com.android.settingslib.utils.ThreadUtils;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.annotation.Nullable;

public class AudioStreamsProgressCategoryController extends BasePreferenceController
        implements DefaultLifecycleObserver {
    private static final String TAG = "AudioStreamsProgressCategoryController";
    private static final boolean DEBUG = BluetoothUtils.D;

    private final Executor mExecutor;
    private final AudioStreamsBroadcastAssistantCallback mBroadcastAssistantCallback;
    private final AudioStreamsHelper mAudioStreamsHelper;
    private final @Nullable LocalBluetoothLeBroadcastAssistant mLeBroadcastAssistant;
    private final ConcurrentHashMap<Integer, AudioStreamPreference> mBroadcastIdToPreferenceMap =
            new ConcurrentHashMap<>();
    private AudioStreamsProgressCategoryPreference mCategoryPreference;

    public AudioStreamsProgressCategoryController(Context context, String preferenceKey) {
        super(context, preferenceKey);
        mExecutor = Executors.newSingleThreadExecutor();
        mAudioStreamsHelper = new AudioStreamsHelper(Utils.getLocalBtManager(mContext));
        mLeBroadcastAssistant = mAudioStreamsHelper.getLeBroadcastAssistant();
        mBroadcastAssistantCallback = new AudioStreamsBroadcastAssistantCallback(this);
    }

    @Override
    public int getAvailabilityStatus() {
        return AVAILABLE;
    }

    @Override
    public void displayPreference(PreferenceScreen screen) {
        super.displayPreference(screen);
        mCategoryPreference = screen.findPreference(getPreferenceKey());
    }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) {
        if (mLeBroadcastAssistant == null) {
            Log.w(TAG, "onStart(): LeBroadcastAssistant is null!");
            return;
        }
        mBroadcastIdToPreferenceMap.clear();
        if (mCategoryPreference != null) {
            mCategoryPreference.removeAll();
        }
        mExecutor.execute(
                () -> {
                    mLeBroadcastAssistant.registerServiceCallBack(
                            mExecutor, mBroadcastAssistantCallback);
                    if (DEBUG) {
                        Log.d(TAG, "scanAudioStreamsStart()");
                    }
                    mLeBroadcastAssistant.startSearchingForSources(emptyList());
                    // Display currently connected streams
                    var unused =
                            ThreadUtils.postOnBackgroundThread(
                                    () ->
                                            mAudioStreamsHelper
                                                    .getAllSources()
                                                    .forEach(this::handleSourceConnected));
                });
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        if (mLeBroadcastAssistant == null) {
            Log.w(TAG, "onStop(): LeBroadcastAssistant is null!");
            return;
        }
        mExecutor.execute(
                () -> {
                    if (mLeBroadcastAssistant.isSearchInProgress()) {
                        if (DEBUG) {
                            Log.d(TAG, "scanAudioStreamsStop()");
                        }
                        mLeBroadcastAssistant.stopSearchingForSources();
                    }
                    mLeBroadcastAssistant.unregisterServiceCallBack(mBroadcastAssistantCallback);
                });
    }

    void setScanning(boolean isScanning) {
        ThreadUtils.postOnMainThread(
                () -> {
                    if (mCategoryPreference != null) mCategoryPreference.setProgress(isScanning);
                });
    }

    void handleSourceFound(BluetoothLeBroadcastMetadata source) {
        Preference.OnPreferenceClickListener addSourceOrShowDialog =
                preference -> {
                    if (DEBUG) {
                        Log.d(TAG, "preferenceClicked(): attempt to join broadcast");
                    }
                    if (source.isEncrypted()) {
                        ThreadUtils.postOnMainThread(
                                () -> launchPasswordDialog(source, preference));
                    } else {
                        mAudioStreamsHelper.addSource(source);
                    }
                    return true;
                };
        mBroadcastIdToPreferenceMap.computeIfAbsent(
                source.getBroadcastId(),
                k -> {
                    var preference = AudioStreamPreference.fromMetadata(mContext, source);
                    ThreadUtils.postOnMainThread(
                            () -> {
                                preference.setIsConnected(false, addSourceOrShowDialog);
                                if (mCategoryPreference != null) {
                                    mCategoryPreference.addPreference(preference);
                                }
                            });
                    return preference;
                });
    }

    void handleSourceLost(int broadcastId) {
        var toRemove = mBroadcastIdToPreferenceMap.remove(broadcastId);
        if (toRemove != null) {
            ThreadUtils.postOnMainThread(
                    () -> {
                        if (mCategoryPreference != null) {
                            mCategoryPreference.removePreference(toRemove);
                        }
                    });
        }
        mAudioStreamsHelper.removeSource();
    }

    void handleSourceConnected(BluetoothLeBroadcastReceiveState state) {
        // TODO(chelseahao): only continue when the state indicates a successful connection
        mBroadcastIdToPreferenceMap.compute(
                state.getBroadcastId(),
                (k, v) -> {
                    // True if this source has been added either by scanning, or it's currently
                    // connected to another active sink.
                    boolean existed = v != null;
                    AudioStreamPreference preference =
                            existed ? v : AudioStreamPreference.fromReceiveState(mContext, state);

                    ThreadUtils.postOnMainThread(
                            () -> {
                                preference.setIsConnected(
                                        true, p -> launchDetailFragment((AudioStreamPreference) p));
                                if (mCategoryPreference != null && !existed) {
                                    mCategoryPreference.addPreference(preference);
                                }
                            });

                    return preference;
                });
    }

    void showToast(String msg) {
        AudioSharingUtils.toastMessage(mContext, msg);
    }

    private boolean launchDetailFragment(AudioStreamPreference preference) {
        Bundle broadcast = new Bundle();
        broadcast.putString(
                Settings.Secure.BLUETOOTH_LE_BROADCAST_PROGRAM_INFO,
                (String) preference.getTitle());

        new SubSettingLauncher(mContext)
                .setTitleText("Audio stream details")
                .setDestination(AudioStreamDetailsFragment.class.getName())
                // TODO(chelseahao): Add logging enum
                .setSourceMetricsCategory(SettingsEnums.PAGE_UNKNOWN)
                .setArguments(broadcast)
                .launch();
        return true;
    }

    private void launchPasswordDialog(BluetoothLeBroadcastMetadata source, Preference preference) {
        View layout =
                LayoutInflater.from(mContext)
                        .inflate(R.layout.bluetooth_find_broadcast_password_dialog, null);
        ((TextView) layout.requireViewById(R.id.broadcast_name_text))
                .setText(preference.getTitle());
        AlertDialog alertDialog =
                new AlertDialog.Builder(mContext)
                        .setTitle(R.string.find_broadcast_password_dialog_title)
                        .setView(layout)
                        .setNeutralButton(android.R.string.cancel, null)
                        .setPositiveButton(
                                R.string.bluetooth_connect_access_dialog_positive,
                                (dialog, which) -> {
                                    var code =
                                            ((EditText)
                                                    layout.requireViewById(
                                                            R.id.broadcast_edit_text))
                                                    .getText()
                                                    .toString();
                                    mAudioStreamsHelper.addSource(
                                            new BluetoothLeBroadcastMetadata.Builder(source)
                                                    .setBroadcastCode(
                                                            code.getBytes(StandardCharsets.UTF_8))
                                                    .build());
                                })
                        .create();
        alertDialog.show();
    }
}