-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathMainFragment.kt
More file actions
395 lines (341 loc) · 14.3 KB
/
MainFragment.kt
File metadata and controls
395 lines (341 loc) · 14.3 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package com.itsaky.androidide.fragments
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.text.HtmlCompat
import androidx.fragment.app.viewModels
import com.adfa.constants.FEEDBACK_EMAIL
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.itsaky.androidide.R
import com.itsaky.androidide.activities.MainActivity
import com.itsaky.androidide.activities.PreferencesActivity
import com.itsaky.androidide.activities.TerminalActivity
import com.itsaky.androidide.adapters.MainActionsListAdapter
import com.itsaky.androidide.app.BaseApplication
import com.itsaky.androidide.app.BaseIDEActivity
import com.itsaky.androidide.buildinfo.BuildInfo
import com.itsaky.androidide.common.databinding.LayoutDialogProgressBinding
import com.itsaky.androidide.databinding.FragmentMainBinding
import com.itsaky.androidide.idetooltips.IDETooltipDatabase
import com.itsaky.androidide.models.MainScreenAction
import com.itsaky.androidide.preferences.databinding.LayoutDialogTextInputBinding
import com.itsaky.androidide.preferences.internal.GITHUB_PAT
import com.itsaky.androidide.resources.R.string
import com.itsaky.androidide.tasks.runOnUiThread
import com.itsaky.androidide.utils.DialogUtils
import com.itsaky.androidide.utils.Environment
import com.itsaky.androidide.utils.TooltipUtils
import com.itsaky.androidide.utils.flashError
import com.itsaky.androidide.utils.flashSuccess
import com.itsaky.androidide.viewmodel.MainViewModel
import com.termux.shared.termux.TermuxConstants.TERMUX_APP.TERMUX_ACTIVITY
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.eclipse.jgit.api.CloneCommand
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.ProgressMonitor
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
import org.slf4j.LoggerFactory
import java.io.File
import java.text.MessageFormat
import java.util.concurrent.CancellationException
import com.itsaky.androidide.BuildConfig
import com.itsaky.androidide.idetooltips.IDETooltipItem
class MainFragment : BaseFragment() {
private val viewModel by viewModels<MainViewModel>(
ownerProducer = { requireActivity() })
private var binding: FragmentMainBinding? = null
companion object {
private val log = LoggerFactory.getLogger(MainFragment::class.java)
const val KEY_TOOLTIP_URL = "tooltip_url"
}
private val shareActivityResultLauncher = registerForActivityResult<Intent, ActivityResult>(
ActivityResultContracts.StartActivityForResult()
) { //ACTION_SEND always returns RESULT_CANCELLED, ignore it
// There are no request codes
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentMainBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val actions = MainScreenAction.mainScreen().also { actions ->
val onClick = { action: MainScreenAction, _: View ->
when (action.id) {
MainScreenAction.ACTION_CREATE_PROJECT -> showCreateProject()
MainScreenAction.ACTION_OPEN_PROJECT -> showViewSavedProjects()
MainScreenAction.ACTION_DELETE_PROJECT -> pickDirectoryForDeletion()
MainScreenAction.ACTION_CLONE_REPO -> cloneGitRepo()
MainScreenAction.ACTION_OPEN_TERMINAL -> startActivity(
Intent(requireActivity(), TerminalActivity::class.java)
)
MainScreenAction.ACTION_PREFERENCES -> gotoPreferences()
MainScreenAction.ACTION_DOCS -> BaseApplication.getBaseInstance().openDocs()
}
}
val onLongClick = { action: MainScreenAction, _: View ->
performOptionsMenuClick(action)
true
}
actions.forEach { action ->
action.onClick = onClick
action.onLongClick = onLongClick
if (action.id == MainScreenAction.ACTION_OPEN_TERMINAL) {
action.onLongClick = { _: MainScreenAction, _: View ->
val intent = Intent(requireActivity(), TerminalActivity::class.java).apply {
putExtra(TERMUX_ACTIVITY.EXTRA_FAILSAFE_SESSION, true)
}
startActivity(intent)
true
}
}
}
}
binding!!.actions.adapter = MainActionsListAdapter(actions)
binding!!.greetingText.setOnClickListener {
TooltipUtils.showWebPage(
requireContext(),
"file:///android_asset/idetooltips/getstarted_top.html"
)
}
binding!!.floatingActionButton?.setOnClickListener {
performFeedbackAction()
}
}
// this method will handle the onclick options click
private fun performOptionsMenuClick(action: MainScreenAction) {
val view = action.view
val tag = action.id.toString()
CoroutineScope(Dispatchers.IO).launch {
val dao = IDETooltipDatabase.getDatabase(requireContext()).idetooltipDao()
val item = dao.getTooltip("ui", tag)
val buttons = item.buttons
withContext((Dispatchers.Main)) {
(context?.let {
TooltipUtils.showIDETooltip(
it,
view!!,
0,
IDETooltipItem(
tooltipTag = item?.tooltipTag ?: "",
detail = item?.detail ?: "",
summary = item?.summary ?: "",
buttons = item?.buttons ?: arrayListOf(),
)
)
})
}
}
}
private fun performFeedbackAction() {
val builder = context?.let { DialogUtils.newMaterialDialogBuilder(it) }
builder?.let { builder ->
builder.setTitle("Alert!")
.setMessage(
HtmlCompat.fromHtml(
getString(R.string.feedback_warning),
HtmlCompat.FROM_HTML_MODE_COMPACT
)
)
.setNegativeButton(android.R.string.cancel) { dialog, _ -> dialog.dismiss() }
.setPositiveButton(android.R.string.ok) { dialog, _ ->
run {
val stackTrace = Exception().stackTrace.asList().toString().replace(",", "\n")
val feedbackMessage = getString(
R.string.feedback_message,
BuildConfig.VERSION_NAME,
stackTrace
)
val feedbackIntent = Intent(Intent.ACTION_SEND)
val subject = MessageFormat.format(
resources.getString(R.string.feedback_subject),
"Main"
)
feedbackIntent.data = Uri.parse("mailto:")
feedbackIntent.type = "text/plain"
feedbackIntent.putExtra(
Intent.EXTRA_EMAIL,
arrayOf(FEEDBACK_EMAIL)
)
feedbackIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
feedbackIntent.putExtra(Intent.EXTRA_TEXT, feedbackMessage)
shareActivityResultLauncher.launch(feedbackIntent)
dialog.dismiss()
}
}
.create()
.show()
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private fun pickDirectory() {
pickDirectory(this::openProject)
}
private fun pickDirectoryForDeletion() {
viewModel.setScreen(MainViewModel.SCREEN_DELETE_PROJECTS)
}
private fun showCreateProject() {
viewModel.setScreen(MainViewModel.SCREEN_TEMPLATE_LIST)
}
private fun showViewSavedProjects() {
viewModel.setScreen(MainViewModel.SCREEN_SAVED_PROJECTS)
}
fun openProject(root: File) {
(requireActivity() as MainActivity).openProject(root)
}
private fun cloneGitRepo() {
val builder = DialogUtils.newMaterialDialogBuilder(requireContext())
val binding = LayoutDialogTextInputBinding.inflate(layoutInflater)
binding.name.setHint(string.git_clone_repo_url)
builder.setView(binding.root)
builder.setTitle(string.git_clone_repo)
builder.setCancelable(true)
builder.setPositiveButton(string.git_clone) { dialog, _ ->
dialog.dismiss()
val url = binding.name.editText?.text?.toString()
doClone(url)
}
builder.setNegativeButton(android.R.string.cancel, null)
builder.show()
}
private fun doClone(repo: String?) {
if (repo.isNullOrBlank()) {
log.warn("Unable to clone repo. Invalid repo URL : {}'", repo)
return
}
var url = repo.trim()
if (!url.endsWith(".git")) {
url += ".git"
}
val builder = DialogUtils.newMaterialDialogBuilder(requireContext())
val binding = LayoutDialogProgressBinding.inflate(layoutInflater)
binding.message.visibility = View.VISIBLE
builder.setTitle(string.git_clone_in_progress)
builder.setMessage(url)
builder.setView(binding.root)
builder.setCancelable(false)
val prefs = BaseApplication.getBaseInstance().prefManager
val repoName = url.substringAfterLast('/').substringBeforeLast(".git")
val targetDir = File(Environment.PROJECTS_DIR, repoName)
if (targetDir.exists()) {
showCloneDirExistsError(targetDir)
return
}
val progress = GitCloneProgressMonitor(binding.progress, binding.message)
val coroutineScope =
(activity as? BaseIDEActivity?)?.activityScope ?: viewLifecycleScope
var getDialog: Function0<AlertDialog?>? = null
val cloneJob = coroutineScope.launch(Dispatchers.IO) {
val git = try {
val cmd: CloneCommand = Git.cloneRepository()
cmd
.setURI(url)
.setDirectory(targetDir)
.setProgressMonitor(progress)
val token = prefs.getString(GITHUB_PAT, "")
//error is caught in showCloneError
if (!token.isNullOrBlank()) {
cmd.setCredentialsProvider(
UsernamePasswordCredentialsProvider(
"<token>",
token
)
)
}
cmd.call()
} catch (err: Throwable) {
if (!progress.isCancelled) {
err.printStackTrace()
withContext(Dispatchers.Main) {
getDialog?.invoke()?.also { if (it.isShowing) it.dismiss() }
showCloneError(err)
}
}
null
}
try {
git?.close()
} finally {
val success = git != null
withContext(Dispatchers.Main) {
getDialog?.invoke()?.also { dialog ->
if (dialog.isShowing) dialog.dismiss()
if (success) flashSuccess(string.git_clone_success)
}
}
}
}
builder.setPositiveButton(android.R.string.cancel) { iface, _ ->
iface.dismiss()
progress.cancel()
cloneJob.cancel(CancellationException("Cancelled by user"))
}
val dialog = builder.show()
getDialog = { dialog }
}
private fun showCloneDirExistsError(targetDir: File) {
val builder = context?.let { AlertDialog.Builder(it) }
builder?.setTitle(string.title_warning)
builder?.setMessage(string.git_clone_dir_exists)
builder?.setPositiveButton(android.R.string.ok) { _, _ -> targetDir.deleteRecursively() }
builder?.setNegativeButton(android.R.string.cancel) { dlg, _ -> dlg.dismiss() }
builder?.show()
}
private fun showCloneError(error: Throwable?) {
if (error == null) {
flashError(string.git_clone_failed)
return
}
val builder = DialogUtils.newMaterialDialogBuilder(requireContext())
builder.setTitle(string.git_clone_failed)
builder.setMessage(error.localizedMessage)
builder.setPositiveButton(android.R.string.ok, null)
builder.show()
}
private fun gotoPreferences() {
startActivity(Intent(requireActivity(), PreferencesActivity::class.java))
}
// TODO(itsaky) : Improve this implementation
class GitCloneProgressMonitor(
val progress: LinearProgressIndicator,
val message: TextView
) : ProgressMonitor {
private var cancelled = false
fun cancel() {
cancelled = true
}
override fun start(totalTasks: Int) {
runOnUiThread { progress.max = totalTasks }
}
override fun beginTask(title: String?, totalWork: Int) {
runOnUiThread { message.text = title }
}
override fun update(completed: Int) {
runOnUiThread { progress.progress = completed }
}
override fun showDuration(enabled: Boolean) {
// no-op
}
override fun endTask() {}
override fun isCancelled(): Boolean {
return cancelled || Thread.currentThread().isInterrupted
}
}
}