2 * Copyright 2020-2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
6 * Privacy Browser Android 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.
11 * Privacy Browser Android 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.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser Android. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.coroutines
22 import android.content.Context
24 import androidx.fragment.app.DialogFragment
25 import androidx.fragment.app.FragmentManager
27 import com.stoutner.privacybrowser.R
28 import com.stoutner.privacybrowser.activities.MainWebViewActivity
29 import com.stoutner.privacybrowser.dataclasses.PendingDialogDataClass
30 import com.stoutner.privacybrowser.dialogs.SaveDialog
31 import com.stoutner.privacybrowser.helpers.UrlHelper
33 import kotlinx.coroutines.CoroutineScope
34 import kotlinx.coroutines.Dispatchers
35 import kotlinx.coroutines.launch
36 import kotlinx.coroutines.withContext
38 import java.lang.Exception
40 object PrepareSaveDialogCoroutine {
42 fun prepareSaveDialog(context: Context, supportFragmentManager: FragmentManager, urlString: String, userAgent: String, cookiesEnabled: Boolean) {
43 // Use a coroutine to prepare the save dialog.
44 CoroutineScope(Dispatchers.Main).launch {
45 // Make the network requests on the IO thread.
46 withContext(Dispatchers.IO) {
47 // Get the file name and size.
48 val fileNameAndSize = UrlHelper.getNameAndSize(context, urlString, userAgent, cookiesEnabled)
50 // Display the dialog on the main thread.
51 withContext(Dispatchers.Main) {
52 // Instantiate the save dialog.
53 val saveDialogFragment: DialogFragment = SaveDialog.saveUrl(urlString, fileNameAndSize.first, fileNameAndSize.second, userAgent, cookiesEnabled)
55 // Try to show the dialog. Sometimes the window is not active.
57 // Show the save dialog.
58 saveDialogFragment.show(supportFragmentManager, context.getString(R.string.save_dialog))
59 } catch (exception: Exception) {
60 // Add the dialog to the pending dialog array list. It will be displayed in `onStart()`.
61 MainWebViewActivity.pendingDialogsArrayList.add(PendingDialogDataClass(saveDialogFragment, context.getString(R.string.save_dialog)))