1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings.bluetooth;
18
19import android.app.AlertDialog;
20import android.app.Dialog;
21import android.app.DialogFragment;
22import android.bluetooth.BluetoothAdapter;
23import android.content.BroadcastReceiver;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.os.Bundle;
29import android.text.Editable;
30import android.text.InputFilter;
31import android.text.TextWatcher;
32import android.util.Log;
33import android.view.KeyEvent;
34import android.view.LayoutInflater;
35import android.view.View;
36import android.view.WindowManager;
37import android.view.inputmethod.EditorInfo;
38import android.widget.Button;
39import android.widget.EditText;
40import android.widget.TextView;
41
42import com.android.settings.R;
43
44/**
45 * Dialog fragment for renaming the local Bluetooth device.
46 */
47public final class BluetoothNameDialogFragment extends DialogFragment implements TextWatcher {
48    private static final int BLUETOOTH_NAME_MAX_LENGTH_BYTES = 248;
49
50    private AlertDialog mAlertDialog;
51    private Button mOkButton;
52
53    // accessed from inner class (not private to avoid thunks)
54    static final String TAG = "BluetoothNameDialogFragment";
55    final LocalBluetoothAdapter mLocalAdapter;
56    EditText mDeviceNameView;
57
58    // This flag is set when the name is updated by code, to distinguish from user changes
59    private boolean mDeviceNameUpdated;
60
61    // This flag is set when the user edits the name (preserved on rotation)
62    private boolean mDeviceNameEdited;
63
64    // Key to save the edited name and edit status for restoring after rotation
65    private static final String KEY_NAME = "device_name";
66    private static final String KEY_NAME_EDITED = "device_name_edited";
67
68    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
69        @Override
70        public void onReceive(Context context, Intent intent) {
71            String action = intent.getAction();
72            if (action.equals(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED)) {
73                updateDeviceName();
74            } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED) &&
75                    (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) ==
76                            BluetoothAdapter.STATE_ON)) {
77                updateDeviceName();
78            }
79        }
80    };
81
82    public BluetoothNameDialogFragment() {
83        LocalBluetoothManager localManager = LocalBluetoothManager.getInstance(getActivity());
84        mLocalAdapter = localManager.getBluetoothAdapter();
85    }
86
87    @Override
88    public Dialog onCreateDialog(Bundle savedInstanceState) {
89        String deviceName = mLocalAdapter.getName();
90        if (savedInstanceState != null) {
91            deviceName = savedInstanceState.getString(KEY_NAME, deviceName);
92            mDeviceNameEdited = savedInstanceState.getBoolean(KEY_NAME_EDITED, false);
93        }
94        mAlertDialog = new AlertDialog.Builder(getActivity())
95                .setTitle(R.string.bluetooth_rename_device)
96                .setView(createDialogView(deviceName))
97                .setPositiveButton(R.string.bluetooth_rename_button,
98                        new DialogInterface.OnClickListener() {
99                            public void onClick(DialogInterface dialog, int which) {
100                                String deviceName = mDeviceNameView.getText().toString();
101                                setDeviceName(deviceName);
102                            }
103                        })
104                .setNegativeButton(android.R.string.cancel, null)
105                .create();
106        mAlertDialog.getWindow().setSoftInputMode(
107                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
108
109        return mAlertDialog;
110    }
111
112    private void setDeviceName(String deviceName) {
113        Log.d(TAG, "Setting device name to " + deviceName);
114        mLocalAdapter.setName(deviceName);
115    }
116
117    @Override
118    public void onSaveInstanceState(Bundle outState) {
119        outState.putString(KEY_NAME, mDeviceNameView.getText().toString());
120        outState.putBoolean(KEY_NAME_EDITED, mDeviceNameEdited);
121    }
122
123    private View createDialogView(String deviceName) {
124        final LayoutInflater layoutInflater = (LayoutInflater)getActivity()
125            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
126        View view = layoutInflater.inflate(R.layout.dialog_edittext, null);
127        mDeviceNameView = (EditText) view.findViewById(R.id.edittext);
128        mDeviceNameView.setFilters(new InputFilter[] {
129                new Utf8ByteLengthFilter(BLUETOOTH_NAME_MAX_LENGTH_BYTES)
130        });
131        mDeviceNameView.setText(deviceName);    // set initial value before adding listener
132        mDeviceNameView.addTextChangedListener(this);
133        mDeviceNameView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
134            @Override
135            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
136                if (actionId == EditorInfo.IME_ACTION_DONE) {
137                    setDeviceName(v.getText().toString());
138                    mAlertDialog.dismiss();
139                    return true;    // action handled
140                } else {
141                    return false;   // not handled
142                }
143            }
144        });
145        return view;
146    }
147
148    @Override
149    public void onDestroy() {
150        super.onDestroy();
151        mAlertDialog = null;
152        mDeviceNameView = null;
153        mOkButton = null;
154    }
155
156    @Override
157    public void onResume() {
158        super.onResume();
159        if (mOkButton == null) {
160            mOkButton = mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
161            mOkButton.setEnabled(mDeviceNameEdited);    // Ok button enabled after user edits
162        }
163        IntentFilter filter = new IntentFilter();
164        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
165        filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
166        getActivity().registerReceiver(mReceiver, filter);
167    }
168
169    @Override
170    public void onPause() {
171        super.onPause();
172        getActivity().unregisterReceiver(mReceiver);
173    }
174
175    void updateDeviceName() {
176        if (mLocalAdapter != null && mLocalAdapter.isEnabled()) {
177            mDeviceNameUpdated = true;
178            mDeviceNameEdited = false;
179            mDeviceNameView.setText(mLocalAdapter.getName());
180        }
181    }
182
183    public void afterTextChanged(Editable s) {
184        if (mDeviceNameUpdated) {
185            // Device name changed by code; disable Ok button until edited by user
186            mDeviceNameUpdated = false;
187            mOkButton.setEnabled(false);
188        } else {
189            mDeviceNameEdited = true;
190            if (mOkButton != null) {
191                mOkButton.setEnabled(s.length() != 0);
192            }
193        }
194    }
195
196    /* Not used */
197    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
198    }
199
200    /* Not used */
201    public void onTextChanged(CharSequence s, int start, int before, int count) {
202    }
203}
204