]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt
464a24ab068d5c428c4c9c42b51dbf8a9ea7fa0e
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / AddDomainDialog.kt
1 /*
2  * Copyright © 2017-2021 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.dialogs
21
22 import android.annotation.SuppressLint
23 import android.app.Dialog
24 import android.content.Context
25 import android.content.DialogInterface
26 import android.net.Uri
27 import android.os.Bundle
28 import android.text.Editable
29 import android.text.TextWatcher
30 import android.view.KeyEvent
31 import android.view.View
32 import android.view.WindowManager
33 import android.widget.EditText
34 import android.widget.TextView
35
36 import androidx.appcompat.app.AlertDialog
37 import androidx.fragment.app.DialogFragment
38 import androidx.preference.PreferenceManager
39
40 import com.stoutner.privacybrowser.R
41 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper
42
43 // Declare the class constants.
44 private const val URL_STRING = "url_string"
45
46 class AddDomainDialog : DialogFragment() {
47     // Declare the class variables
48     private lateinit var addDomainListener: AddDomainListener
49
50     // The public interface is used to send information back to the parent activity.
51     interface AddDomainListener {
52         fun onAddDomain(dialogFragment: DialogFragment)
53     }
54
55     override fun onAttach(context: Context) {
56         // Run the default commands.
57         super.onAttach(context)
58
59         // Get a handle for the listener from the launching context.
60         addDomainListener = context as AddDomainListener
61     }
62
63     companion object {
64         // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.
65         @JvmStatic
66         fun addDomain(urlString: String): AddDomainDialog {
67             // Create an arguments bundle.
68             val argumentsBundle = Bundle()
69
70             // Store the URL in the bundle.
71             argumentsBundle.putString(URL_STRING, urlString)
72
73             // Create a new instance of the dialog.
74             val addDomainDialog = AddDomainDialog()
75
76             // Add the arguments bundle to the dialog.
77             addDomainDialog.arguments = argumentsBundle
78
79             // Return the new dialog.
80             return addDomainDialog
81         }
82     }
83
84     // `@SuppressLint("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
85     @SuppressLint("InflateParams")
86     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
87         // Get the arguments.
88         val arguments = requireArguments()
89
90         // Get the URL from the bundle.
91         val urlString = arguments.getString(URL_STRING)
92
93         // Use an alert dialog builder to create the alert dialog.
94         val dialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext(), R.style.PrivacyBrowserAlertDialog)
95
96         // Set the icon according to the theme.
97         dialogBuilder.setIconAttribute(R.attr.domainsBlueIcon)
98
99         // Set the title.
100         dialogBuilder.setTitle(R.string.add_domain)
101
102         // Set the view.  The parent view is `null` because it will be assigned by the alert dialog.
103         dialogBuilder.setView(requireActivity().layoutInflater.inflate(R.layout.add_domain_dialog, null))
104
105         // Set the cancel button listener.  Using `null` as the listener closes the dialog without doing anything else.
106         dialogBuilder.setNegativeButton(R.string.cancel, null)
107
108         // Set the add button listener.
109         dialogBuilder.setPositiveButton(R.string.add) { _: DialogInterface, _: Int ->
110             // Return the dialog fragment to the parent activity on add.
111             addDomainListener.onAddDomain(this)
112         }
113
114         // Create an alert dialog from the builder.
115         val alertDialog = dialogBuilder.create()
116
117         // Get a handle for the shared preferences.
118         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
119
120         // Get the screenshot preference.
121         val allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots), false)
122
123         // Disable screenshots if not allowed.
124         if (!allowScreenshots) {
125             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
126         }
127
128         // The alert dialog must be shown before the contents can be modified.
129         alertDialog.show()
130
131         // Initialize the domains database helper.  The `0` specifies the database version, but that is ignored and set instead using a constant in domains database helper.
132         val domainsDatabaseHelper = DomainsDatabaseHelper(context, null, null, 0)
133
134         // Get handles for the views in the alert dialog.
135         val addDomainEditText = alertDialog.findViewById<EditText>(R.id.domain_name_edittext)!!
136         val domainNameAlreadyExistsTextView = alertDialog.findViewById<TextView>(R.id.domain_name_already_exists_textview)!!
137         val addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
138
139         //  Update the status of the warning text and the add button when the domain name changes.
140         addDomainEditText.addTextChangedListener(object: TextWatcher {
141             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
142                 // Do nothing.
143             }
144
145             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
146                 // Do nothing.
147             }
148
149             override fun afterTextChanged(s: Editable) {
150                 if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.text.toString()).count > 0) {  // The domain already exists.
151                     // Show the warning text.
152                     domainNameAlreadyExistsTextView.visibility = View.VISIBLE
153
154                     // Disable the add button.
155                     addButton.isEnabled = false
156                 } else {  // The domain do not yet exist.
157                     // Hide the warning text.
158                     domainNameAlreadyExistsTextView.visibility = View.GONE
159
160                     // Enable the add button.
161                     addButton.isEnabled = true
162                 }
163             }
164         })
165
166         // Convert the URL string to a URI.
167         val currentUri = Uri.parse(urlString)
168
169         // Display the host in the add domain edit text.
170         addDomainEditText.setText(currentUri.host)
171
172         // Allow the enter key on the keyboard to create the domain from the add domain edit text.
173         addDomainEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
174             // Check the key code and event.
175             if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.action == KeyEvent.ACTION_DOWN) {  // The event is a key-down on the enter key.
176                 // Trigger the add domain listener and return the dialog fragment to the parent activity.
177                 addDomainListener.onAddDomain(this)
178
179                 // Manually dismiss the alert dialog.
180                 alertDialog.dismiss()
181
182                 // Consume the event.
183                 return@setOnKeyListener true
184             } else {  // Some other key was pressed.
185                 // Do not consume the event.
186                 return@setOnKeyListener false
187             }
188         }
189
190         // Return the alert dialog.
191         return alertDialog
192     }
193 }