]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/dialogs/AddDomainDialog.kt
Fix a crash when uploading files to some sites. https://redmine.stoutner.com/issues/556
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / dialogs / AddDomainDialog.kt
1 /*
2  * Copyright © 2017-2020 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.AlertDialog
24 import android.app.Dialog
25 import android.content.Context
26 import android.content.DialogInterface
27 import android.net.Uri
28 import android.os.Bundle
29 import android.text.Editable
30 import android.text.TextWatcher
31 import android.view.KeyEvent
32 import android.view.View
33 import android.view.WindowManager
34 import android.widget.EditText
35 import android.widget.TextView
36
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 class AddDomainDialog: DialogFragment() {
44     // The public interface is used to send information back to the parent activity.
45     interface AddDomainListener {
46         fun onAddDomain(dialogFragment: DialogFragment)
47     }
48
49     // The add domain listener is initialized in `onAttach()` and used in `onCreateDialog()`.
50     private lateinit var addDomainListener: AddDomainListener
51
52     override fun onAttach(context: Context) {
53         // Run the default commands.
54         super.onAttach(context)
55
56         // Get a handle for the listener from the launching context.
57         addDomainListener = context as AddDomainListener
58     }
59
60     companion object {
61         // `@JvmStatic` will no longer be required once all the code has transitioned to Kotlin.  Also, the function can then be moved out of a companion object and just become a package-level function.
62         @JvmStatic
63         fun addDomain(urlString: String): AddDomainDialog {
64             // Create an arguments bundle.
65             val argumentsBundle = Bundle()
66
67             // Store the URL in the bundle.
68             argumentsBundle.putString("url_string", urlString)
69
70             // Create a new instance of the dialog.
71             val addDomainDialog = AddDomainDialog()
72
73             // Add the arguments bundle to the dialog.
74             addDomainDialog.arguments = argumentsBundle
75
76             // Return the new dialog.
77             return addDomainDialog
78         }
79     }
80
81     // `@SuppressLing("InflateParams")` removes the warning about using `null` as the parent view group when inflating the alert dialog.
82     @SuppressLint("InflateParams")
83     override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
84         // Get the arguments.
85         val arguments = arguments!!
86
87         // Get the URL from the bundle.
88         val urlString = arguments.getString("url_string")
89
90         // Get a handle for the shared preferences.
91         val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
92
93         // Get the screenshot and theme preferences.
94         val allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false)
95         val darkTheme = sharedPreferences.getBoolean("dark_theme", false)
96
97         // Use an alert dialog builder to create the alert dialog.
98         val dialogBuilder: AlertDialog.Builder
99
100         // USet the style and the icon according to the theme.
101         if (darkTheme) {
102             // Set the dark style.
103             dialogBuilder = AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogDark)
104
105             // Set the dark icon.
106             dialogBuilder.setIcon(R.drawable.domains_dark)
107         } else {
108             // Set the light style.
109             dialogBuilder = AlertDialog.Builder(context, R.style.PrivacyBrowserAlertDialogLight)
110
111             // Set the light icon.
112             dialogBuilder.setIcon(R.drawable.domains_light)
113         }
114
115         // Set the title.
116         dialogBuilder.setTitle(R.string.add_domain)
117
118         // Set the view.  The parent view is `null` because it will be assigned by the alert dialog.
119         dialogBuilder.setView(activity!!.layoutInflater.inflate(R.layout.add_domain_dialog, null))
120
121         // Set a listener on the cancel button.  Using `null` as the listener closes the dialog without doing anything else.
122         dialogBuilder.setNegativeButton(R.string.cancel, null)
123
124         // Set a listener on the add button.
125         dialogBuilder.setPositiveButton(R.string.add) { _: DialogInterface, _: Int ->
126             // Return the dialog fragment to the parent activity on add.
127             addDomainListener.onAddDomain(this)
128         }
129
130         // Create an alert dialog from the builder.
131         val alertDialog = dialogBuilder.create()
132
133         // Disable screenshots if not allowed.
134         if (!allowScreenshots) {
135             alertDialog.window!!.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
136         }
137
138         // The alert dialog must be shown before the contents can be modified.
139         alertDialog.show()
140
141         // 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.
142         val domainsDatabaseHelper = DomainsDatabaseHelper(context, null, null, 0)
143
144         // Get handles for the views in the alert dialog.
145         val addDomainEditText: EditText = alertDialog.findViewById(R.id.domain_name_edittext)
146         val domainNameAlreadyExistsTextView: TextView = alertDialog.findViewById(R.id.domain_name_already_exists_textview)
147         val addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
148
149         //  Update the status of the warning text and the add button when the domain name changes.
150         addDomainEditText.addTextChangedListener(object: TextWatcher {
151             override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
152                 // Do nothing.
153             }
154
155             override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
156                 // Do nothing.
157             }
158
159             override fun afterTextChanged(s: Editable) {
160                 if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.text.toString()).count > 0) {  // The domain already exists.
161                     // Show the warning text.
162                     domainNameAlreadyExistsTextView.visibility = View.VISIBLE
163
164                     // Disable the add button.
165                     addButton.isEnabled = false
166                 } else {  // The domain do not yet exist.
167                     // Hide the warning text.
168                     domainNameAlreadyExistsTextView.visibility = View.GONE
169
170                     // Enable the add button.
171                     addButton.isEnabled = true
172                 }
173             }
174         })
175
176         // Convert the URL string to a URI.
177         val currentUri = Uri.parse(urlString)
178
179         // Display the host in the add domain edit text.
180         addDomainEditText.setText(currentUri.host)
181
182         // Allow the enter key on the keyboard to create the domain from the add domain edit text.
183         addDomainEditText.setOnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent ->
184             // Check the key code and event.
185             if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.action == KeyEvent.ACTION_DOWN) {  // The event is a key-down on the enter key.
186                 // Trigger the add domain listener and return the dialog fragment to the parent activity.
187                 addDomainListener.onAddDomain(this)
188
189                 // Manually dismiss the alert dialog.
190                 alertDialog.dismiss()
191
192                 // Consume the event.
193                 return@setOnKeyListener true
194             } else {  // Some other key was pressed.
195                 // Do not consume the event.
196                 return@setOnKeyListener false
197             }
198         }
199
200         // Return the alert dialog.
201         return alertDialog
202     }
203 }