/
EditIngredientsFragment.kt
532 lines (450 loc) 路 19.4 KB
/
EditIngredientsFragment.kt
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
* Copyright 2016-2020 Open Food Facts
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package openfoodfacts.github.scrachx.openfood.features.product.edit.ingredients
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.net.toFile
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.hootsuite.nachos.terminator.ChipTerminatorHandler
import com.hootsuite.nachos.validator.ChipifyingNachoValidator
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsEvent
import openfoodfacts.github.scrachx.openfood.analytics.AnalyticsView
import openfoodfacts.github.scrachx.openfood.analytics.MatomoAnalytics
import openfoodfacts.github.scrachx.openfood.databinding.FragmentAddProductIngredientsBinding
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity.Companion.KEY_PERFORM_OCR
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity.Companion.KEY_SEND_UPDATED
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditFragment
import openfoodfacts.github.scrachx.openfood.images.ProductImage
import openfoodfacts.github.scrachx.openfood.models.DaoSession
import openfoodfacts.github.scrachx.openfood.models.Product
import openfoodfacts.github.scrachx.openfood.models.ProductImageField
import openfoodfacts.github.scrachx.openfood.models.entities.OfflineSavedProduct
import openfoodfacts.github.scrachx.openfood.models.entities.allergen.AllergenNameDao
import openfoodfacts.github.scrachx.openfood.network.ApiFields
import openfoodfacts.github.scrachx.openfood.network.ApiFields.Keys.lcIngredientsKey
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient
import openfoodfacts.github.scrachx.openfood.utils.*
import java.io.File
import javax.inject.Inject
/**
* Fragment for Add Product Ingredients
*
* @see R.layout.fragment_add_product_ingredients
*/
@AndroidEntryPoint
class EditIngredientsFragment : ProductEditFragment() {
private var _binding: FragmentAddProductIngredientsBinding? = null
private val binding get() = _binding!!
private val viewModel: EditIngredientsViewModel by viewModels()
@Inject
lateinit var daoSession: DaoSession
@Inject
lateinit var picasso: Picasso
@Inject
lateinit var client: OpenFoodAPIClient
@Inject
lateinit var fileDownloader: FileDownloader
@Inject
lateinit var matomoAnalytics: MatomoAnalytics
@Inject
lateinit var sharedPreferences: SharedPreferences
@Inject
lateinit var localeManager: LocaleManager
/**
* Executed when an image is returned from the camera
*/
private val photoReceiverHandler by lazy {
PhotoReceiverHandler(sharedPreferences) {
val uri = it.toURI()
imagePath = uri.path
newImageSelected = true
photoFile = it
val image = ProductImage(
code!!,
ProductImageField.INGREDIENTS,
it,
localeManager.getLanguage()
).apply {
filePath = uri.path
}
(activity as? ProductEditActivity)?.savePhoto(image, 1)
// Change UI state
hideImageProgress(false, getString(R.string.image_uploaded_successfully))
// Analytics
matomoAnalytics.trackEvent(AnalyticsEvent.ProductIngredientsPictureEdited(code))
}
}
private var photoFile: File? = null
private var code: String? = null
private var offlineProduct: OfflineSavedProduct? = null
private var product: Product? = null
private var productDetails = mutableMapOf<String, String?>()
private var imagePath: String? = null
private var newImageSelected = false
override fun allValid() = true
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentAddProductIngredientsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// FIXME: DO NOT USE INTENTS IN FRAGMENTS
val activityIntent = activity?.intent
if (activityIntent != null
&& activityIntent.getBooleanExtra(ProductEditActivity.KEY_MODIFY_NUTRITION_PROMPT, false)
&& !activityIntent.getBooleanExtra(ProductEditActivity.KEY_MODIFY_CATEGORY_PROMPT, false)
) {
(activity as ProductEditActivity).proceed()
}
binding.btnAddImageIngredients.setOnClickListener { addIngredientsImage() }
binding.btnEditImageIngredients.setOnClickListener { editIngredientsImage() }
binding.btnNext.setOnClickListener { next() }
binding.btnLooksGood.setOnClickListener { verifyIngredients() }
binding.btnSkipIngredients.setOnClickListener { skipIngredients() }
binding.btnExtractIngredients.setOnClickListener { extractIngredients() }
binding.ingredientsList.doAfterTextChanged { newText ->
binding.btnExtractIngredients.isVisible = newText.isNullOrEmpty()
}
val bundle = arguments
if (bundle == null) {
Toast.makeText(activity, R.string.error_adding_ingredients, Toast.LENGTH_SHORT).show()
requireActivity().finish()
return
}
product = getProductFromArgs()
offlineProduct = getEditOfflineProductFromArgs()
if (product != null) {
code = product!!.code
}
if (isEditingFromArgs && product != null) {
code = product!!.code
preFillProductValues(product!!)
} else if (offlineProduct != null) {
code = offlineProduct!!.barcode
preFillValuesForOffline(offlineProduct!!)
} else {
// Fast addition
val enabled = requireContext().isFastAdditionMode()
setFastAdditionMode(enabled)
}
if (bundle.getBoolean(KEY_PERFORM_OCR)) extractIngredients()
if (bundle.getBoolean(KEY_SEND_UPDATED)) editIngredientsImage()
val ingredientsImg = getImageIngredients()
if (binding.ingredientsList.isEmpty() && !ingredientsImg.isNullOrEmpty()) {
binding.btnExtractIngredients.visibility = View.VISIBLE
imagePath = ingredientsImg
} else if (
isEditingFromArgs
&& binding.ingredientsList.isEmpty()
&& !product!!.imageIngredientsUrl.isNullOrEmpty()
) {
binding.btnExtractIngredients.visibility = View.VISIBLE
}
// Allergens autosuggestion
viewModel.allergens.observe(viewLifecycleOwner) { loadAutoSuggestions(it) }
(activity as? ProductEditActivity)?.let { getAllDetails(it) }
}
override fun onResume() {
super.onResume()
matomoAnalytics.trackView(AnalyticsView.ProductEditIngredients)
}
private fun getImageIngredients() = productDetails[ApiFields.Keys.IMAGE_INGREDIENTS]
private fun getAddProductActivity() = activity as ProductEditActivity?
private fun extractTracesChipValues(product: Product?): List<String> =
product?.tracesTags
?.map { getTracesName(localeManager.getLanguage(), it) }
?: emptyList()
/**
* Pre fill the fields of the product which are already present on the server.
*/
private fun preFillProductValues(product: Product) {
loadIngredientsImage()
product.ingredientsText
?.takeUnless { it.isEmpty() }
?.let { binding.ingredientsList.setText(it) }
product.takeUnless { it.tracesTags.isEmpty() }
?.let {
binding.traces.setText(extractTracesChipValues(it))
}
}
/**
* Load ingredients image on the image view
*/
fun loadIngredientsImage() {
if (getAddProductActivity() == null) return
val newImageIngredientsUrl = product!!.getImageIngredientsUrl(getAddProductActivity()!!.getProductLanguageForEdition())
photoFile = null
if (newImageIngredientsUrl != null && newImageIngredientsUrl.isNotEmpty()) {
binding.imageProgress.visibility = View.VISIBLE
imagePath = newImageIngredientsUrl
picasso
.load(newImageIngredientsUrl)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients, object : Callback {
override fun onSuccess() = imageLoaded()
override fun onError(ex: Exception) = imageLoaded()
})
}
}
/**
* Set visibility parameters when image is loaded
*/
private fun imageLoaded() {
binding.btnEditImageIngredients.visibility = View.VISIBLE
binding.imageProgress.visibility = View.GONE
}
/**
* Returns allergen name or `tag` if nothing found.
*
* @param languageCode language in which additive name and tag are written
* @param tag Tag associated with the allergen
*/
private fun getTracesName(languageCode: String, tag: String): String {
return daoSession.allergenNameDao.unique {
where(AllergenNameDao.Properties.AllergenTag.eq(tag))
where(AllergenNameDao.Properties.LanguageCode.eq(languageCode))
}?.name ?: tag
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
/**
* To enable fast addition mode
*/
private fun setFastAdditionMode(enabled: Boolean) {
if (enabled) {
binding.traces.visibility = View.GONE
binding.sectionTraces.visibility = View.GONE
binding.hintTraces.visibility = View.GONE
binding.greyLine2.visibility = View.GONE
} else {
binding.traces.visibility = View.VISIBLE
binding.sectionTraces.visibility = View.VISIBLE
binding.hintTraces.visibility = View.VISIBLE
binding.greyLine2.visibility = View.VISIBLE
}
}
/**
* Pre fill the fields if the product is already present in SavedProductOffline db.
*/
private fun preFillValuesForOffline(prod: OfflineSavedProduct) {
productDetails = prod.productDetails.toMutableMap()
// Load ingredients image
getImageIngredients()?.let {
binding.imageProgress.visibility = View.VISIBLE
picasso
.load(LOCALE_FILE_SCHEME + it)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients, object : Callback {
override fun onSuccess() {
binding.imageProgress.visibility = View.GONE
}
override fun onError(ex: Exception) {
binding.imageProgress.visibility = View.GONE
}
})
}
prod.ingredients
?.takeUnless { it.isEmpty() }
?.let { binding.ingredientsList.setText(it) }
productDetails[ApiFields.Keys.ADD_TRACES]?.let {
binding.traces.setText(it.split(Regex("\\s*,\\s*")))
}
}
/**
* Automatically load suggestions for allergen names
*/
private fun loadAutoSuggestions(allergens: List<String>) {
binding.traces.addChipTerminator(',', ChipTerminatorHandler.BEHAVIOR_CHIPIFY_CURRENT_TOKEN)
binding.traces.setNachoValidator(ChipifyingNachoValidator())
binding.traces.enableEditChipOnTouch(false, true)
binding.traces.setAdapter(
ArrayAdapter(
requireActivity(),
android.R.layout.simple_dropdown_item_1line,
allergens
)
)
}
override fun doOnPhotosPermissionGranted() = editIngredientsImage()
private fun addIngredientsImage() {
when {
imagePath == null -> editIngredientsImage()
photoFile != null -> cropRotateImage(photoFile!!, getString(R.string.ingredients_picture))
else -> {
lifecycleScope.launchWhenResumed {
val uri = fileDownloader.download(imagePath!!)
if (uri != null) {
photoFile = uri.toFile()
cropRotateImage(uri, getString(R.string.ingredients_picture))
}
}
}
}
}
private fun editIngredientsImage() = doChooseOrTakePhotos()
private fun verifyIngredients() {
binding.ingredientsListVerified.visibility = View.VISIBLE
binding.traces.requestFocus()
binding.btnLooksGood.visibility = View.GONE
binding.btnSkipIngredients.visibility = View.GONE
}
private fun extractIngredients() {
(activity as? ProductEditActivity)?.let { activity ->
imagePath?.let { imagePath ->
if (!isEditingFromArgs || newImageSelected) {
photoFile = File(imagePath)
val image = ProductImage(code!!, ProductImageField.INGREDIENTS, photoFile!!, localeManager.getLanguage())
image.filePath = imagePath
activity.savePhoto(image, 1)
} else {
activity.lifecycleScope.launch {
activity.performOCR(
code!!,
"ingredients_" + activity.getProductLanguageForEdition()
)
}
}
}
}
}
private fun skipIngredients() {
binding.ingredientsList.text = null
binding.btnSkipIngredients.visibility = View.GONE
binding.btnLooksGood.visibility = View.GONE
}
/**
* adds all the fields to the query map even those which are null or empty.
*/
private fun getAllDetails(activity: ProductEditActivity) {
activity.initialValues?.let { targetMap ->
binding.traces.chipifyAllUnterminatedTokens()
val lc = activity.getProductLanguageForEdition()
?.takeUnless { it.isEmpty() } ?: ApiFields.Defaults.DEFAULT_LANGUAGE
targetMap[lcIngredientsKey(lc)] = binding.ingredientsList.text.toString()
targetMap[ApiFields.Keys.ADD_TRACES.substring(4)] = binding.traces.chipValues.joinToString(",")
}
}
/**
* adds only those fields to the query map which are not empty and have changed.
*/
override fun getUpdatedFieldsMap(): Map<String, String?> {
val targetMap = mutableMapOf<String, String?>()
if (activity !is ProductEditActivity) return targetMap
binding.traces.chipifyAllUnterminatedTokens()
binding.ingredientsList
.takeIf { it.isContentDifferent(product?.ingredientsText) }
?.let {
val languageCode = (activity as ProductEditActivity).getProductLanguageForEdition()
val lc = if (!languageCode.isNullOrEmpty()) languageCode else ApiFields.Defaults.DEFAULT_LANGUAGE
targetMap[lcIngredientsKey(lc)] = it.getContent()
}
binding.traces
.takeIf { it.isNotEmpty() && it.areChipsDifferent(extractTracesChipValues(product)) }
?.let {
targetMap[ApiFields.Keys.ADD_TRACES] = it.chipValues.joinToString(",")
}
return targetMap
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
photoReceiverHandler.onActivityResult(this, requestCode, resultCode, data)
}
/**
* Displays progress bar and hides other views util image is still loading
*/
override fun showImageProgress() {
binding.imageProgress.visibility = View.VISIBLE
binding.imageProgressText.visibility = View.VISIBLE
binding.imageProgressText.setText(R.string.toastSending)
binding.btnAddImageIngredients.visibility = View.INVISIBLE
binding.btnEditImageIngredients.visibility = View.INVISIBLE
}
/**
* After image is loaded hide image progress
*
* @param errorInUploading boolean variable is true, if there is an error while showing image
* @param message error message in case of failure to display image
*/
override fun hideImageProgress(errorInUploading: Boolean, message: String) {
binding.imageProgress.visibility = View.INVISIBLE
binding.imageProgressText.visibility = View.GONE
binding.btnAddImageIngredients.visibility = View.VISIBLE
binding.btnEditImageIngredients.visibility = View.VISIBLE
if (!errorInUploading) {
picasso.load(photoFile!!)
.resize(dps50ToPixels, dps50ToPixels)
.centerInside()
.into(binding.btnAddImageIngredients)
}
}
/**
* Display the list of ingredients based on the result from ocr of IngredientsList photo
*
* @param status status of ocr, in case of proper OCR it returns "set" or "0"
* @param ocrResult resultant string obtained after OCR of image
*/
fun setIngredients(status: String?, ocrResult: String?) {
if (activity == null || requireActivity().isFinishing) return
when (status) {
"set" -> {
binding.ingredientsList.setText(ocrResult)
loadIngredientsImage()
}
"0" -> {
binding.ingredientsList.setText(ocrResult)
binding.btnLooksGood.visibility = View.VISIBLE
binding.btnSkipIngredients.visibility = View.VISIBLE
}
else -> Toast.makeText(activity, R.string.unable_to_extract_ingredients, Toast.LENGTH_SHORT).show()
}
}
fun showOCRProgress() {
// Disable extract button and ingredients text field
binding.btnExtractIngredients.isEnabled = false
binding.ingredientsList.isEnabled = false
// Delete ingredients text
binding.ingredientsList.text = null
// Show progress spinner and text
binding.ocrProgress.visibility = View.VISIBLE
}
fun hideOCRProgress() {
// Re-enable extract button and ingredients text field
binding.btnExtractIngredients.isEnabled = true
binding.ingredientsList.isEnabled = true
// Hide progress spinner and text
binding.ocrProgress.visibility = View.GONE
}
private val dps50ToPixels by lazy { requireContext().dpsToPixel(50) }
}