EuiccChannelFragmentUtils.kt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package im.angry.openeuicc.util
  2. import android.os.Bundle
  3. import androidx.fragment.app.Fragment
  4. import im.angry.openeuicc.core.EuiccChannel
  5. import im.angry.openeuicc.core.EuiccChannelManager
  6. import im.angry.openeuicc.service.EuiccChannelManagerService
  7. import im.angry.openeuicc.ui.BaseEuiccAccessActivity
  8. interface EuiccChannelFragmentMarker: OpenEuiccContextMarker
  9. // We must use extension functions because there is no way to add bounds to the type of "self"
  10. // in the definition of an interface, so the only way is to limit where the extension functions
  11. // can be applied.
  12. fun <T> newInstanceEuicc(clazz: Class<T>, slotId: Int, portId: Int, addArguments: Bundle.() -> Unit = {}): T where T: Fragment, T: EuiccChannelFragmentMarker {
  13. val instance = clazz.newInstance()
  14. instance.arguments = Bundle().apply {
  15. putInt("slotId", slotId)
  16. putInt("portId", portId)
  17. addArguments()
  18. }
  19. return instance
  20. }
  21. // Convenient methods to avoid using `channel` for these
  22. // `channel` requires that the channel actually exists in EuiccChannelManager, which is
  23. // not always the case during operations such as switching
  24. val <T> T.slotId: Int where T: Fragment, T: EuiccChannelFragmentMarker
  25. get() = requireArguments().getInt("slotId")
  26. val <T> T.portId: Int where T: Fragment, T: EuiccChannelFragmentMarker
  27. get() = requireArguments().getInt("portId")
  28. val <T> T.isUsb: Boolean where T: Fragment, T: EuiccChannelFragmentMarker
  29. get() = requireArguments().getInt("slotId") == EuiccChannelManager.USB_CHANNEL_ID
  30. val <T> T.euiccChannelManager: EuiccChannelManager where T: Fragment, T: OpenEuiccContextMarker
  31. get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManager
  32. val <T> T.euiccChannelManagerService: EuiccChannelManagerService where T: Fragment, T: OpenEuiccContextMarker
  33. get() = (requireActivity() as BaseEuiccAccessActivity).euiccChannelManagerService
  34. suspend fun <T, R> T.withEuiccChannel(fn: suspend (EuiccChannel) -> R): R where T : Fragment, T : EuiccChannelFragmentMarker {
  35. ensureEuiccChannelManager()
  36. return euiccChannelManager.withEuiccChannel(slotId, portId, fn)
  37. }
  38. suspend fun <T> T.ensureEuiccChannelManager() where T: Fragment, T: OpenEuiccContextMarker =
  39. (requireActivity() as BaseEuiccAccessActivity).euiccChannelManagerLoaded.await()
  40. interface EuiccProfilesChangedListener {
  41. fun onEuiccProfilesChanged()
  42. }