/
ContinuousScanActivity.kt
959 lines (835 loc) 路 41.3 KB
/
ContinuousScanActivity.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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/*
* 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.scan
import android.content.Intent
import android.content.SharedPreferences
import android.hardware.Camera
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.Gravity.CENTER
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.TextView.OnEditorActionListener
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.appcompat.widget.PopupMenu
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.commit
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.android.material.bottomsheet.BottomSheetBehavior.from
import com.google.zxing.BarcodeFormat
import com.google.zxing.ResultPoint
import com.google.zxing.client.android.BeepManager
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.DefaultDecoderFactory
import com.mikepenz.iconics.IconicsColor
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.IconicsSize
import com.mikepenz.iconics.typeface.library.googlematerial.GoogleMaterial
import com.squareup.picasso.Picasso
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.Completable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import openfoodfacts.github.scrachx.openfood.AppFlavors.OFF
import openfoodfacts.github.scrachx.openfood.AppFlavors.isFlavors
import openfoodfacts.github.scrachx.openfood.BuildConfig
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.ActivityContinuousScanBinding
import openfoodfacts.github.scrachx.openfood.features.ImagesManageActivity
import openfoodfacts.github.scrachx.openfood.features.compare.ProductCompareActivity
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.installBottomNavigation
import openfoodfacts.github.scrachx.openfood.features.listeners.CommonBottomListenerInstaller.selectNavigationItem
import openfoodfacts.github.scrachx.openfood.features.product.edit.ProductEditActivity
import openfoodfacts.github.scrachx.openfood.features.product.view.ProductViewActivity.ShowIngredientsAction
import openfoodfacts.github.scrachx.openfood.features.product.view.ProductViewFragment
import openfoodfacts.github.scrachx.openfood.features.product.view.ingredients_analysis.IngredientsWithTagDialogFragment
import openfoodfacts.github.scrachx.openfood.features.product.view.summary.AbstractSummaryProductPresenter
import openfoodfacts.github.scrachx.openfood.features.product.view.summary.IngredientAnalysisTagsAdapter
import openfoodfacts.github.scrachx.openfood.features.product.view.summary.SummaryProductPresenter
import openfoodfacts.github.scrachx.openfood.features.shared.BaseActivity
import openfoodfacts.github.scrachx.openfood.models.DaoSession
import openfoodfacts.github.scrachx.openfood.models.InvalidBarcodeDao
import openfoodfacts.github.scrachx.openfood.models.Product
import openfoodfacts.github.scrachx.openfood.models.entities.OfflineSavedProduct
import openfoodfacts.github.scrachx.openfood.models.entities.OfflineSavedProductDao
import openfoodfacts.github.scrachx.openfood.models.entities.allergen.AllergenHelper
import openfoodfacts.github.scrachx.openfood.models.entities.allergen.AllergenName
import openfoodfacts.github.scrachx.openfood.models.entities.analysistagconfig.AnalysisTagConfig
import openfoodfacts.github.scrachx.openfood.models.eventbus.ProductNeedsRefreshEvent
import openfoodfacts.github.scrachx.openfood.network.ApiFields
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient
import openfoodfacts.github.scrachx.openfood.repositories.ProductRepository
import openfoodfacts.github.scrachx.openfood.utils.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
@AndroidEntryPoint
class ContinuousScanActivity : BaseActivity() {
private var _binding: ActivityContinuousScanBinding? = null
private val binding get() = _binding!!
@Inject
lateinit var client: OpenFoodAPIClient
@Inject
lateinit var daoSession: DaoSession
@Inject
lateinit var offlineProductService: OfflineProductService
@Inject
lateinit var productRepository: ProductRepository
@Inject
lateinit var picasso: Picasso
@Inject
lateinit var matomoAnalytics: MatomoAnalytics
@Inject
lateinit var sharedPreferences: SharedPreferences
@Inject
lateinit var localeManager: LocaleManager
private lateinit var beepManager: BeepManager
private lateinit var quickViewBehavior: BottomSheetBehavior<LinearLayout>
private lateinit var bottomSheetCallback: BottomSheetCallback
private lateinit var errorDrawable: VectorDrawableCompat
private val barcodeInputListener = BarcodeInputListener()
private val barcodeScanCallback = BarcodeScannerCallback()
private val cameraPref by lazy { getSharedPreferences("camera", 0) }
private val settings by lazy { getSharedPreferences("prefs", 0) }
private val commonDisp = CompositeDisposable()
private var productDisp: Disposable? = null
private var hintBarcodeDisp: Disposable? = null
private var peekLarge = 0
private var peekSmall = 0
private var cameraState = 0
private var autoFocusActive = false
private var flashActive = false
private var analysisTagsEmpty = true
private var productShowing = false
private var beepActive = false
/**
boolean to determine if MLKit Scanner is to be used
*/
private var useMLScanner = false
private val mlKitView by lazy {
MlKitCameraView(this)
}
private var offlineSavedProduct: OfflineSavedProduct? = null
private var product: Product? = null
private var lastBarcode: String? = null
private var productViewFragment: ProductViewFragment? = null
private var popupMenu: PopupMenu? = null
private var summaryProductPresenter: SummaryProductPresenter? = null
private val productActivityResultLauncher = registerForActivityResult(ProductEditActivity.EditProductContract())
{ result -> if (result) lastBarcode?.let { setShownProduct(it) } }
/**
* Used by screenshot tests.
*
* @param barcode barcode to serach
*/
@Suppress("unused")
internal fun showProduct(barcode: String) {
productShowing = true
binding.barcodeScanner.isVisible = false
binding.barcodeScanner.pause()
mlKitView.stopCameraPreview()
binding.imageForScreenshotGenerationOnly.visibility = View.VISIBLE
setShownProduct(barcode)
}
/**
* Makes network call and search for the product in the database
*
* @param barcode Barcode to be searched
*/
private fun setShownProduct(barcode: String) {
if (isFinishing) return
// Dispose the previous call if not ended.
productDisp?.dispose()
summaryProductPresenter?.dispose()
// First, try to show if we have an offline saved product in the db
offlineSavedProduct = offlineProductService.getOfflineProductByBarcode(barcode).also { product ->
product?.let { showOfflineSavedDetails(it) }
}
// Then query the online db
productDisp = client.getProductStateFull(barcode, userAgent = Utils.HEADER_USER_AGENT_SCAN)
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
hideAllViews()
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
binding.quickView.setOnClickListener(null)
binding.quickViewProgress.visibility = View.VISIBLE
binding.quickViewProgressText.visibility = View.VISIBLE
binding.quickViewProgressText.text = getString(R.string.loading_product, barcode)
}
.doOnError {
try {
// A network error happened
if (it is IOException) {
hideAllViews()
val offlineSavedProduct = daoSession.offlineSavedProductDao!!.queryBuilder()
.where(OfflineSavedProductDao.Properties.Barcode.eq(barcode))
.unique()
tryDisplayOffline(offlineSavedProduct, barcode, R.string.addProductOffline)
binding.quickView.setOnClickListener { navigateToProductAddition(barcode) }
} else {
binding.quickViewProgress.visibility = View.GONE
binding.quickViewProgressText.visibility = View.GONE
Toast.makeText(this, R.string.txtConnectionError, Toast.LENGTH_LONG).run {
setGravity(CENTER, 0, 0)
show()
}
Log.i(LOG_TAG, it.message, it)
}
} catch (err: Exception) {
Log.w(LOG_TAG, err.message, err)
}
}
.subscribe { productState ->
//clear product tags
analysisTagsEmpty = true
binding.quickViewTags.adapter = null
binding.quickViewProgress.visibility = View.GONE
binding.quickViewProgressText.visibility = View.GONE
if (productState.status == 0L) {
tryDisplayOffline(offlineSavedProduct, barcode, R.string.product_not_found)
} else {
val product = productState.product!!
this.product = product
// Add product to scan history
productDisp = client.addToHistory(product).subscribeOn(Schedulers.io()).subscribe()
// If we're here from comparison -> add product, return to comparison activity
if (intent.getBooleanExtra(ProductCompareActivity.KEY_COMPARE_PRODUCT, false)) {
startActivity(Intent(this@ContinuousScanActivity, ProductCompareActivity::class.java).apply {
putExtra(ProductCompareActivity.KEY_PRODUCT_FOUND, true)
val productsToCompare = intent.extras!!.getSerializable(ProductCompareActivity.KEY_PRODUCTS_TO_COMPARE) as ArrayList<Product>
if (product in productsToCompare) {
putExtra(ProductCompareActivity.KEY_PRODUCT_ALREADY_EXISTS, true)
} else {
productsToCompare += product
matomoAnalytics.trackEvent(AnalyticsEvent.AddProductToComparison(product.code))
}
putExtra(ProductCompareActivity.KEY_PRODUCTS_TO_COMPARE, productsToCompare)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
})
}
showAllViews()
binding.txtProductCallToAction.let {
it.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
it.background = ContextCompat.getDrawable(this, R.drawable.rounded_quick_view_text)
it.setText(if (isProductIncomplete()) R.string.product_not_complete else R.string.scan_tooltip)
it.visibility = View.VISIBLE
}
setupSummary(product)
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
showProductFullScreen()
binding.quickViewProductNotFound.visibility = View.GONE
binding.quickViewProductNotFoundButton.visibility = View.GONE
// Set product name, prefer offline
if (offlineSavedProduct != null && !offlineSavedProduct?.name.isNullOrEmpty()) {
binding.quickViewName.text = offlineSavedProduct!!.name
} else if (product.productName == null || product.productName == "") {
binding.quickViewName.setText(R.string.productNameNull)
} else {
binding.quickViewName.text = product.productName
}
// Set product additives
val addTags = product.additivesTags
binding.quickViewAdditives.text = when {
addTags.isNotEmpty() -> resources.getQuantityString(R.plurals.productAdditives, addTags.size, addTags.size)
product.statesTags.contains(ApiFields.StateTags.INGREDIENTS_COMPLETED) -> getString(R.string.productAdditivesNone)
else -> getString(R.string.productAdditivesUnknown)
}
// Show nutriscore in quickView only if app flavour is OFF and the product has one
quickViewCheckNutriScore(product)
// Show nova group in quickView only if app flavour is OFF and the product has one
quickViewCheckNova(product)
// If the product has an ecoscore, show it instead of the CO2 icon
quickViewCheckEcoScore(product)
// Create the product view fragment and add it to the layout
val newProductViewFragment = ProductViewFragment.newInstance(productState)
supportFragmentManager.commit {
replace(R.id.frame_layout, newProductViewFragment)
setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
}
productViewFragment = newProductViewFragment
}
}
}
private fun quickViewCheckNutriScore(product: Product) = if (isFlavors(OFF)) {
binding.quickViewNutriScore.visibility = View.VISIBLE
binding.quickViewNutriScore.setImageResource(product.getNutriScoreResource())
} else {
binding.quickViewNutriScore.visibility = View.GONE
}
private fun quickViewCheckNova(product: Product) = if (isFlavors(OFF)) {
binding.quickViewNovaGroup.visibility = View.VISIBLE
binding.quickViewAdditives.visibility = View.VISIBLE
binding.quickViewNovaGroup.setImageResource(product.getNovaGroupResource())
} else {
binding.quickViewNovaGroup.visibility = View.GONE
}
private fun quickViewCheckEcoScore(product: Product) = if (isFlavors(OFF)) {
binding.quickViewEcoscoreIcon.setImageResource(product.getEcoscoreResource())
binding.quickViewEcoscoreIcon.visibility = View.VISIBLE
} else {
binding.quickViewEcoscoreIcon.visibility = View.GONE
}
private fun tryDisplayOffline(
offlineSavedProduct: OfflineSavedProduct?,
barcode: String,
@StringRes errorMsg: Int
) = if (offlineSavedProduct != null) showOfflineSavedDetails(offlineSavedProduct)
else showProductNotFound(getString(errorMsg, barcode))
private fun setupSummary(product: Product) {
binding.callToActionImageProgress.visibility = View.VISIBLE
summaryProductPresenter = SummaryProductPresenter(localeManager.getLanguage(), product, object : AbstractSummaryProductPresenter() {
override fun showAllergens(allergens: List<AllergenName>) {
val data = AllergenHelper.computeUserAllergen(product, allergens)
binding.callToActionImageProgress.visibility = View.GONE
if (data.isEmpty()) return
val iconicsDrawable = IconicsDrawable(this@ContinuousScanActivity, GoogleMaterial.Icon.gmd_warning)
.color(IconicsColor.colorInt(ContextCompat.getColor(this@ContinuousScanActivity, R.color.white)))
.size(IconicsSize.dp(24))
binding.txtProductCallToAction.setCompoundDrawablesWithIntrinsicBounds(iconicsDrawable, null, null, null)
binding.txtProductCallToAction.background = ContextCompat.getDrawable(this@ContinuousScanActivity, R.drawable.rounded_quick_view_text_warn)
binding.txtProductCallToAction.text = if (data.incomplete) {
getString(R.string.product_incomplete_message)
} else {
"${getString(R.string.product_allergen_prompt)}\n${data.allergens.joinToString(", ")}"
}
}
override fun showAnalysisTags(analysisTags: List<AnalysisTagConfig>) {
super.showAnalysisTags(analysisTags)
if (analysisTags.isEmpty()) {
binding.quickViewTags.visibility = View.GONE
analysisTagsEmpty = true
return
}
binding.quickViewTags.visibility = View.VISIBLE
analysisTagsEmpty = false
val adapter = IngredientAnalysisTagsAdapter(this@ContinuousScanActivity, analysisTags, picasso, sharedPreferences)
adapter.setOnItemClickListener { view: View?, _ ->
if (view == null) return@setOnItemClickListener
IngredientsWithTagDialogFragment.newInstance(product, view.getTag(R.id.analysis_tag_config) as AnalysisTagConfig).run {
show(supportFragmentManager, "fragment_ingredients_with_tag")
onDismissListener = { adapter.filterVisibleTags() }
}
}
binding.quickViewTags.adapter = adapter
}
}, productRepository).also {
it.loadAllergens { binding.callToActionImageProgress.visibility = View.GONE }
it.loadAnalysisTags()
}
}
private fun showProductNotFound(text: String) {
hideAllViews()
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
binding.quickView.setOnClickListener { lastBarcode?.let { navigateToProductAddition(it) } }
binding.quickViewProductNotFound.text = text
binding.quickViewProductNotFound.visibility = View.VISIBLE
binding.quickViewProductNotFoundButton.visibility = View.VISIBLE
binding.quickViewProductNotFoundButton.setOnClickListener { lastBarcode?.let { navigateToProductAddition(it) } }
}
private fun showProductFullScreen() {
quickViewBehavior.peekHeight = peekLarge
binding.quickView.let {
it.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
it.requestLayout()
it.rootView.requestLayout()
}
}
private fun showOfflineSavedDetails(offlineSavedProduct: OfflineSavedProduct) {
showAllViews()
val pName = offlineSavedProduct.name
binding.quickViewName.text = if (!pName.isNullOrEmpty()) pName else getString(R.string.productNameNull)
binding.txtProductCallToAction.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0)
binding.txtProductCallToAction.background = ContextCompat.getDrawable(this@ContinuousScanActivity, R.drawable.rounded_quick_view_text)
binding.txtProductCallToAction.setText(R.string.product_not_complete)
binding.txtProductCallToAction.visibility = View.VISIBLE
binding.quickViewSlideUpIndicator.visibility = View.GONE
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
private fun navigateToProductAddition(productBarcode: String) {
navigateToProductAddition(Product().apply {
code = productBarcode
lang = localeManager.getLanguage()
})
}
private fun navigateToProductAddition(product: Product?) {
productActivityResultLauncher.launch(product)
}
private fun showAllViews() {
binding.quickViewSlideUpIndicator.visibility = View.VISIBLE
binding.quickViewName.visibility = View.VISIBLE
binding.frameLayout.visibility = View.VISIBLE
binding.quickViewAdditives.visibility = View.VISIBLE
if (!analysisTagsEmpty) {
binding.quickViewTags.visibility = View.VISIBLE
} else {
binding.quickViewTags.visibility = View.GONE
}
}
private fun hideAllViews() {
binding.quickViewSearchByBarcode.visibility = View.GONE
binding.quickViewProgress.visibility = View.GONE
binding.quickViewProgressText.visibility = View.GONE
binding.quickViewSlideUpIndicator.visibility = View.GONE
binding.quickViewName.visibility = View.GONE
binding.frameLayout.visibility = View.GONE
binding.quickViewAdditives.visibility = View.GONE
binding.quickViewNutriScore.visibility = View.GONE
binding.quickViewNovaGroup.visibility = View.GONE
binding.quickViewCo2Icon.visibility = View.GONE
binding.quickViewEcoscoreIcon.visibility = View.GONE
binding.quickViewProductNotFound.visibility = View.GONE
binding.quickViewProductNotFoundButton.visibility = View.GONE
binding.txtProductCallToAction.visibility = View.GONE
binding.quickViewTags.visibility = View.GONE
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityContinuousScanBinding.inflate(layoutInflater)
setContentView(binding.root)
useMLScanner = BuildConfig.USE_MLKIT && settings.getBoolean(getString(R.string.pref_scanner_type_key), false)
binding.toggleFlash.setOnClickListener { toggleFlash() }
binding.buttonMore.setOnClickListener { showMoreSettings() }
actionBar?.hide()
peekLarge = resources.getDimensionPixelSize(R.dimen.scan_summary_peek_large)
peekSmall = resources.getDimensionPixelSize(R.dimen.scan_summary_peek_small)
errorDrawable = VectorDrawableCompat.create(resources, R.drawable.ic_product_silhouette, null)
?: error("Could not create vector drawable.")
binding.quickViewTags.isNestedScrollingEnabled = false
// The system bars are visible.
hideSystemUI()
hintBarcodeDisp = Completable.timer(15, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnComplete {
if (productShowing) return@doOnComplete
hideAllViews()
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
binding.quickViewSearchByBarcode.visibility = View.VISIBLE
binding.quickViewSearchByBarcode.requestFocus()
}.subscribe()
quickViewBehavior = from(binding.quickView)
// Initial state
quickViewBehavior.state = BottomSheetBehavior.STATE_HIDDEN
bottomSheetCallback = QuickViewCallback()
quickViewBehavior.addBottomSheetCallback(bottomSheetCallback)
cameraPref.let {
beepActive = it.getBoolean(SETTING_RING, false)
flashActive = it.getBoolean(SETTING_FLASH, false)
autoFocusActive = it.getBoolean(SETTING_FOCUS, true)
cameraState = it.getInt(SETTING_STATE, 0)
}
// Setup barcode scanner
if (!useMLScanner) {
binding.barcodeScanner.visibility = View.VISIBLE
binding.cameraPreviewViewStub.viewStub?.isVisible = false
binding.barcodeScanner.barcodeView.decoderFactory = DefaultDecoderFactory(BARCODE_FORMATS)
binding.barcodeScanner.setStatusText(null)
binding.barcodeScanner.setOnClickListener {
quickViewBehavior.state = BottomSheetBehavior.STATE_HIDDEN
binding.barcodeScanner.resume()
}
binding.barcodeScanner.barcodeView.cameraSettings.run {
requestedCameraId = cameraState
isAutoFocusEnabled = autoFocusActive
}
// Start continuous scanner
binding.barcodeScanner.decodeContinuous(barcodeScanCallback)
beepManager = BeepManager(this)
} else {
binding.barcodeScanner.isVisible = false
mlKitView.attach(binding.cameraPreviewViewStub, cameraState, flashActive, autoFocusActive)
mlKitView.onOverlayClickListener = {
quickViewBehavior.state = BottomSheetBehavior.STATE_HIDDEN
}
mlKitView.barcodeScannedCallback = {
mlBarcodeCallback(it)
}
}
binding.quickViewSearchByBarcode.setOnEditorActionListener(barcodeInputListener)
binding.bottomNavigation.bottomNavigation.installBottomNavigation(this)
// Setup popup menu
setupPopupMenu()
}
private fun mlBarcodeCallback(barcodeValue: String) {
hintBarcodeDisp?.dispose()
// Prevent duplicate scans
if (barcodeValue.isEmpty() || barcodeValue == lastBarcode) return
val invalidBarcode = daoSession.invalidBarcodeDao.queryBuilder()
.where(InvalidBarcodeDao.Properties.Barcode.eq(barcodeValue))
.unique()
// Scanned barcode is in the list of invalid barcodes, do nothing
if (invalidBarcode != null) return
lastBarcode = barcodeValue.also { if (!isFinishing) setShownProduct(it) }
}
override fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
override fun onResume() {
super.onResume()
binding.bottomNavigation.bottomNavigation.selectNavigationItem(R.id.scan_bottom_nav)
if (!useMLScanner && quickViewBehavior.state != BottomSheetBehavior.STATE_EXPANDED) {
binding.barcodeScanner.resume()
} else if (useMLScanner && quickViewBehavior.state != BottomSheetBehavior.STATE_EXPANDED) {
mlKitView.onResume()
}
matomoAnalytics.trackView(AnalyticsView.Scanner)
}
override fun onPostResume() {
super.onPostResume()
// Back to working state after the bottom sheet is dismissed.
mlKitView.updateWorkflowState(WorkflowState.DETECTING)
}
override fun onSaveInstanceState(outState: Bundle) {
productDisp?.dispose()
super.onSaveInstanceState(outState)
}
override fun onPause() {
if (!useMLScanner) {
binding.barcodeScanner.pause()
} else {
mlKitView.stopCameraPreview()
}
super.onPause()
}
override fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
override fun onDestroy() {
summaryProductPresenter?.dispose()
mlKitView.detach()
// Dispose all RxJava disposable
hintBarcodeDisp?.dispose()
commonDisp.dispose()
// Remove bottom sheet callback as it uses binding
quickViewBehavior.removeBottomSheetCallback(bottomSheetCallback)
_binding = null
super.onDestroy()
}
@Subscribe
fun onEventBusProductNeedsRefreshEvent(event: ProductNeedsRefreshEvent) {
if (event.barcode == lastBarcode) {
runOnUiThread { setShownProduct(event.barcode) }
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
//status bar will remain visible if user presses home and then reopens the activity
// hence hiding status bar again
hideSystemUI()
}
private fun hideSystemUI() {
WindowInsetsControllerCompat(window, binding.root).hide(WindowInsetsCompat.Type.statusBars())
this.actionBar?.hide()
}
private fun setupPopupMenu() {
popupMenu = PopupMenu(this, binding.buttonMore).also {
it.menuInflater.inflate(R.menu.popup_menu, it.menu)
// turn flash on if flashActive true in pref
if (flashActive) {
binding.toggleFlash.setImageResource(R.drawable.ic_flash_on_white_24dp)
if (!useMLScanner) {
binding.barcodeScanner.setTorchOn()
}
}
if (beepActive) {
it.menu.findItem(R.id.toggleBeep).isChecked = true
}
if (autoFocusActive) {
it.menu.findItem(R.id.toggleAutofocus).isChecked = true
}
}
}
private fun isProductIncomplete() = if (product == null) {
false
} else product!!.imageFrontUrl == null
|| product!!.imageFrontUrl == ""
|| product!!.quantity == null
|| product!!.quantity == ""
|| product!!.productName == null
|| product!!.productName == ""
|| product!!.brands == null
|| product!!.brands == ""
|| product!!.ingredientsText == null
|| product!!.ingredientsText == ""
@Suppress("deprecation")
private fun toggleCamera() {
cameraState = if (cameraState == Camera.CameraInfo.CAMERA_FACING_BACK) {
Camera.CameraInfo.CAMERA_FACING_FRONT
} else {
Camera.CameraInfo.CAMERA_FACING_BACK
}
cameraPref.edit { putInt(SETTING_STATE, cameraState) }
if (!useMLScanner) {
val settings = binding.barcodeScanner.barcodeView.cameraSettings
if (binding.barcodeScanner.barcodeView.isPreviewActive) {
binding.barcodeScanner.pause()
}
settings.requestedCameraId = cameraState
binding.barcodeScanner.barcodeView.cameraSettings = settings
binding.barcodeScanner.resume()
} else {
mlKitView.toggleCamera()
}
}
private fun toggleFlash() {
cameraPref.edit {
if (flashActive) {
flashActive = false
binding.toggleFlash.setImageResource(R.drawable.ic_flash_off_white_24dp)
putBoolean(SETTING_FLASH, false)
if (useMLScanner) {
mlKitView.updateFlashSetting(flashActive)
} else {
binding.barcodeScanner.setTorchOff()
}
} else {
flashActive = true
binding.toggleFlash.setImageResource(R.drawable.ic_flash_on_white_24dp)
putBoolean(SETTING_FLASH, true)
if (useMLScanner) {
mlKitView.updateFlashSetting(flashActive)
} else {
binding.barcodeScanner.setTorchOn()
}
}
}
}
private fun showMoreSettings() {
popupMenu?.let {
if (useMLScanner) {
it.menu.findItem(R.id.toggleBeep).isEnabled = false
}
it.setOnMenuItemClickListener { item: MenuItem ->
when (item.itemId) {
R.id.toggleBeep -> {
beepActive = !beepActive
item.isChecked = beepActive
cameraPref.edit {
putBoolean(SETTING_RING, beepActive)
apply()
}
}
R.id.toggleAutofocus -> {
autoFocusActive = !autoFocusActive
item.isChecked = autoFocusActive
cameraPref.edit { putBoolean(SETTING_FOCUS, autoFocusActive) }
if (useMLScanner) {
mlKitView.updateFocusModeSetting(autoFocusActive)
} else {
if (binding.barcodeScanner.barcodeView.isPreviewActive) {
binding.barcodeScanner.pause()
}
val settings = binding.barcodeScanner.barcodeView.cameraSettings
settings.isAutoFocusEnabled = autoFocusActive
binding.barcodeScanner.resume()
binding.barcodeScanner.barcodeView.cameraSettings = settings
}
}
R.id.troubleScanning -> {
hideAllViews()
hintBarcodeDisp?.dispose()
binding.quickView.setOnClickListener(null)
binding.quickViewSearchByBarcode.text = null
binding.quickViewSearchByBarcode.visibility = View.VISIBLE
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
binding.quickViewSearchByBarcode.requestFocus()
}
R.id.toggleCamera -> toggleCamera()
}
true
}
it.show()
}
}
/**
* Overridden to collapse bottom view after a back action from edit form.
*/
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
quickViewBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ImagesManageActivity.REQUEST_EDIT_IMAGE && (resultCode == RESULT_OK || resultCode == RESULT_CANCELED)) {
lastBarcode?.let { setShownProduct(it) }
} else if (resultCode == RESULT_OK && requestCode == LOGIN_ACTIVITY_REQUEST_CODE) {
navigateToProductAddition(product)
}
}
fun collapseBottomSheet() {
quickViewBehavior.state = BottomSheetBehavior.STATE_HIDDEN
}
fun showIngredientsTab(action: ShowIngredientsAction) {
quickViewBehavior.state = BottomSheetBehavior.STATE_EXPANDED
productViewFragment?.showIngredientsTab(action)
}
private inner class QuickViewCallback : BottomSheetCallback() {
private var previousSlideOffset = 0f
override fun onStateChanged(bottomSheet: View, newState: Int) {
fun stopScanner() {
if (useMLScanner) {
mlKitView.updateWorkflowState(WorkflowState.DETECTED)
mlKitView.stopCameraPreview()
} else {
binding.barcodeScanner.pause()
}
}
when (newState) {
BottomSheetBehavior.STATE_HIDDEN -> {
lastBarcode = null
binding.txtProductCallToAction.visibility = View.GONE
}
BottomSheetBehavior.STATE_COLLAPSED -> {
stopScanner()
}
BottomSheetBehavior.STATE_EXPANDED -> {
stopScanner()
matomoAnalytics.trackEvent(AnalyticsEvent.ScannedBarcodeResultExpanded(lastBarcode))
}
else -> {
stopScanner()
}
}
if (binding.quickViewSearchByBarcode.visibility == View.VISIBLE) {
quickViewBehavior.peekHeight = peekSmall
bottomSheet.layoutParams.height = quickViewBehavior.peekHeight
} else {
quickViewBehavior.peekHeight = peekLarge
bottomSheet.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT
}
bottomSheet.requestLayout()
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
val slideDelta = slideOffset - previousSlideOffset
if (binding.quickViewSearchByBarcode.visibility != View.VISIBLE && binding.quickViewProgress.visibility != View.VISIBLE) {
if (slideOffset > 0.01f || slideOffset < -0.01f) {
binding.txtProductCallToAction.visibility = View.GONE
} else if (binding.quickViewProductNotFound.visibility != View.VISIBLE) {
binding.txtProductCallToAction.visibility = View.VISIBLE
}
if (slideOffset > 0.01f) {
binding.quickViewDetails.visibility = View.GONE
binding.quickViewTags.visibility = View.GONE
if (useMLScanner) {
mlKitView.updateWorkflowState(WorkflowState.DETECTED)
mlKitView.stopCameraPreview()
} else {
binding.barcodeScanner.pause()
}
if (slideDelta > 0 && productViewFragment != null) {
productViewFragment!!.bottomSheetWillGrow()
binding.bottomNavigation.bottomNavigation.visibility = View.GONE
}
} else {
if (useMLScanner) {
mlKitView.updateWorkflowState(WorkflowState.DETECTING)
mlKitView.startCameraPreview()
} else {
binding.barcodeScanner.resume()
}
binding.quickViewDetails.visibility = View.VISIBLE
binding.quickViewTags.visibility = if (analysisTagsEmpty) View.GONE else View.VISIBLE
binding.bottomNavigation.bottomNavigation.visibility = View.VISIBLE
if (binding.quickViewProductNotFound.visibility != View.VISIBLE) {
binding.txtProductCallToAction.visibility = View.VISIBLE
}
}
}
previousSlideOffset = slideOffset
}
}
private inner class BarcodeInputListener : OnEditorActionListener {
override fun onEditorAction(textView: TextView, actionId: Int, event: KeyEvent?): Boolean {
// When user search from "having trouble" edit text
if (actionId != EditorInfo.IME_ACTION_SEARCH) return false
Utils.hideKeyboard(this@ContinuousScanActivity)
hideSystemUI()
// Check for barcode validity
val barcodeText = textView.text.toString()
// For debug only: the barcode 1 is used for test
if (!isBarcodeValid(barcodeText)) {
textView.requestFocus()
textView.error = getString(R.string.txtBarcodeNotValid)
return true
}
lastBarcode = barcodeText
textView.visibility = View.GONE
setShownProduct(barcodeText)
return true
}
}
private inner class BarcodeScannerCallback : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult) {
hintBarcodeDisp?.dispose()
// Prevent duplicate scans
if (result.text == null || result.text.isEmpty() || result.text == lastBarcode) return
val invalidBarcode = daoSession.invalidBarcodeDao.queryBuilder()
.where(InvalidBarcodeDao.Properties.Barcode.eq(result.text))
.unique()
// Scanned barcode is in the list of invalid barcodes, do nothing
if (invalidBarcode != null) return
if (beepActive) {
beepManager.playBeepSound()
}
lastBarcode = result.text
if (!isFinishing) {
setShownProduct(result.text)
matomoAnalytics.trackEvent(AnalyticsEvent.ScannedBarcode(result.text))
}
}
// Here possible results are useless but we must implement this
override fun possibleResultPoints(resultPoints: List<ResultPoint>) = Unit
}
companion object {
private const val LOGIN_ACTIVITY_REQUEST_CODE = 2
val BARCODE_FORMATS = listOf(
BarcodeFormat.UPC_A,
BarcodeFormat.UPC_E,
BarcodeFormat.EAN_13,
BarcodeFormat.EAN_8,
BarcodeFormat.RSS_14,
BarcodeFormat.CODE_39,
BarcodeFormat.CODE_93,
BarcodeFormat.CODE_128,
BarcodeFormat.ITF
)
private const val SETTING_RING = "ring"
private const val SETTING_FLASH = "flash"
private const val SETTING_FOCUS = "focus"
private const val SETTING_STATE = "cameraState"
private val LOG_TAG = this::class.simpleName!!
}
}