content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package io.github.routis.cbor.internal private const val HALF_PRECISION_EXPONENT_BIAS = 15 private const val HALF_PRECISION_MAX_EXPONENT = 0x1f private const val HALF_PRECISION_MAX_MANTISSA = 0x3ff private const val SINGLE_PRECISION_EXPONENT_BIAS = 127 private const val SINGLE_PRECISION_MAX_EXPONENT = 0xFF private const val SINGLE_PRECISION_NORMALIZE_BASE = 0.5f private val normalizeBaseBits = SINGLE_PRECISION_NORMALIZE_BASE.toBits() /** * Copied this from kotlinx serialization * * https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/cbor/commonMain/src/kotlinx/serialization/cbor/internal/Encoding.kt#L665 * For details about half-precision floating-point numbers see https://tools.ietf.org/html/rfc7049#appendix-D */ internal fun floatFromHalfBits(bits: Short): Float { val intBits = bits.toInt() val negative = (intBits and 0x8000) != 0 val halfExp = intBits shr 10 and HALF_PRECISION_MAX_EXPONENT val halfMant = intBits and HALF_PRECISION_MAX_MANTISSA val exp: Int val mant: Int when (halfExp) { HALF_PRECISION_MAX_EXPONENT -> { // if exponent maximal - value is NaN or Infinity exp = SINGLE_PRECISION_MAX_EXPONENT mant = halfMant } 0 -> { if (halfMant == 0) { // if exponent and mantissa are zero - value is zero mant = 0 exp = 0 } else { // if exponent is zero and mantissa non-zero - value denormalized. normalize it var res = Float.fromBits(normalizeBaseBits + halfMant) res -= SINGLE_PRECISION_NORMALIZE_BASE return if (negative) -res else res } } else -> { // normalized value exp = (halfExp + (SINGLE_PRECISION_EXPONENT_BIAS - HALF_PRECISION_EXPONENT_BIAS)) mant = halfMant } } val res = Float.fromBits((exp shl 23) or (mant shl 13)) return if (negative) -res else res } // https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java internal fun halfBitsFromFloat(number: Float): Short { val bits = number.toRawBits() val sign = bits ushr 16 and 0x8000 val value = (bits and 0x7fffffff) + 0x1000 val result = when { value >= 0x47800000 -> { if (bits and 0x7fffffff >= 0x47800000) { if (value < 0x7f800000) { sign or 0x7c00 } else { sign or 0x7c00 or (bits and 0x007fffff ushr 13) } } else { sign or 0x7bff } } value >= 0x38800000 -> sign or (value - 0x38000000 ushr 13) value < 0x33000000 -> sign else -> { val otherValue = bits and 0x7fffffff ushr 23 sign or ( ( (bits and 0x7fffff or 0x800000) + (0x800000 ushr otherValue - 102) ) ushr 126 - otherValue ) } } return result.toShort() }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/HalfBits.kt
2868912067
package io.github.routis.cbor.internal import com.ionspin.kotlin.bignum.integer.BigInteger import io.github.routis.cbor.* import kotlinx.serialization.json.* internal fun JsonOptions.dataItemToJson(dataItem: DataItem): JsonElement { fun convert(item: DataItem): JsonElement = when (item) { is UnsignedIntegerDataItem -> JsonPrimitive(item.value) is NegativeIntegerDataItem -> item.asBigInteger().toJson() is ByteStringDataItem -> byteStringOption(item) is TextStringDataItem -> JsonPrimitive(item.text) is ArrayDataItem -> item.map(::convert).let(::JsonArray) is MapDataItem -> buildMap { item.forEach { (k, v) -> keyAsString(k)?.let { put(it, convert(v)) } } }.let(::JsonObject) is TaggedDataItem<*> -> when (item) { is StandardDateTimeDataItem -> convert(item.content) is IntegerEpochDataItem -> convert(item.content) is HalfFloatEpochDataItem -> convert(item.content) is SingleFloatEpochDataItem -> convert(item.content) is DoubleFloatEpochDataItem -> convert(item.content) is BigNumUnsigned -> item.asBigInteger().toJson() is BigNumNegative -> item.asBigInteger().toJson() is DecimalFraction -> TODO("Implement toJson for DecimalFraction") is BigFloat -> TODO("Implement toJson for BigFloat") is EncodedText -> convert(item.content) is CborDataItem -> convert(decode(item.content.bytes)) is SelfDescribedCbor -> convert(item.content) is UnsupportedTagDataItem -> JsonNull is CalendarDayDataItem -> convert(item.content) is CalendarDateDataItem -> convert(item.content) } is BooleanDataItem -> JsonPrimitive(item.value) is HalfPrecisionFloatDataItem -> JsonPrimitive(item.value) is SinglePrecisionFloatDataItem -> JsonPrimitive(item.value) is DoublePrecisionFloatDataItem -> JsonPrimitive(item.value) is ReservedDataItem -> JsonNull is UnassignedDataItem -> JsonNull UndefinedDataItem -> JsonNull NullDataItem -> JsonNull } return convert(dataItem) } private fun JsonOptions.keyAsString(k: Key<*>): String? = when (k) { is BoolKey -> keyOptions.boolKeyMapper?.invoke(k) is ByteStringKey -> keyOptions.byteStringKeyMapper?.invoke(k) is IntegerKey -> keyOptions.integerKeyMapper?.invoke(k) is TextStringKey -> k.item.text } private fun BigInteger.toJson() = JsonUnquotedLiteral(toString(10))
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/ToJson.kt
3673564045
package io.github.routis.cbor.internal import io.github.routis.cbor.* internal sealed interface Tag { data object StandardDateTimeString : Tag data object EpochBasedDateTime : Tag data object BigNumUnsigned : Tag data object BigNumNegative : Tag data object DecimalFraction : Tag data object BigFloat : Tag data object ToBase64Url : Tag data object ToBase64 : Tag data object ToBase16 : Tag data object CborDataItem : Tag data object Uri : Tag data object Base64Url : Tag data object Base64 : Tag data object Regex : Tag data object Mime : Tag data object SelfDescribedCbor : Tag data object CalendarDay : Tag data object CalendarDate : Tag companion object { fun of(x: ULong): Tag? = when (x) { 0uL -> StandardDateTimeString 1uL -> EpochBasedDateTime 2uL -> BigNumUnsigned 3uL -> BigNumNegative 4uL -> DecimalFraction 5uL -> BigFloat 21uL -> ToBase64Url 22uL -> ToBase64 23uL -> ToBase16 24uL -> CborDataItem 32uL -> Uri 33uL -> Base64Url 34uL -> Base64 35uL -> Regex 36uL -> Mime 55799uL -> SelfDescribedCbor 100uL -> CalendarDay 1004uL -> CalendarDate else -> null } } } internal fun Tag.value(): ULong = when (this) { Tag.StandardDateTimeString -> 0uL Tag.EpochBasedDateTime -> 1uL Tag.BigNumUnsigned -> 2uL Tag.BigNumNegative -> 3uL Tag.DecimalFraction -> 4uL Tag.BigFloat -> 5uL Tag.ToBase64Url -> 21uL Tag.ToBase64 -> 22uL Tag.ToBase16 -> 23uL Tag.CborDataItem -> 24uL Tag.Uri -> 32uL Tag.Base64Url -> 33uL Tag.Base64 -> 34uL Tag.Regex -> 35uL Tag.Mime -> 36uL Tag.SelfDescribedCbor -> 55799uL Tag.CalendarDay -> 100uL Tag.CalendarDate -> 1004uL } internal fun TaggedDataItem<*>.tagValue(): ULong = when (this) { is StandardDateTimeDataItem -> Tag.StandardDateTimeString.value() is EpochBasedDateTime<*> -> Tag.EpochBasedDateTime.value() is BigNumUnsigned -> Tag.BigNumUnsigned.value() is BigNumNegative -> Tag.BigNumNegative.value() is DecimalFraction -> Tag.DecimalFraction.value() is BigFloat -> Tag.BigFloat.value() is Base64DataItem -> Tag.Base64.value() is Base64UrlDataItem -> Tag.Base64Url.value() is MimeDataItem -> Tag.Mime.value() is RegexDataItem -> Tag.Regex.value() is UriDataItem -> Tag.Uri.value() is CborDataItem -> Tag.CborDataItem.value() is SelfDescribedCbor -> Tag.SelfDescribedCbor.value() is UnsupportedTagDataItem -> tag is CalendarDayDataItem -> Tag.CalendarDay.value() is CalendarDateDataItem -> Tag.CalendarDate.value() } internal fun DataItem.tagged(tag: Tag): TaggedDataItem<DataItem> { val dataItem = this return with(tag) { when (this) { Tag.StandardDateTimeString -> StandardDateTimeDataItem(expected(dataItem)) Tag.EpochBasedDateTime -> when (dataItem) { is IntegerDataItem -> IntegerEpochDataItem(dataItem) is HalfPrecisionFloatDataItem -> HalfFloatEpochDataItem(dataItem) is SinglePrecisionFloatDataItem -> SingleFloatEpochDataItem(dataItem) is DoublePrecisionFloatDataItem -> DoubleFloatEpochDataItem(dataItem) else -> error("$dataItem is not valid for $this. Expecting integer or float") } Tag.BigNumUnsigned -> BigNumUnsigned(expected(dataItem)) Tag.BigNumNegative -> BigNumNegative(expected(dataItem)) Tag.DecimalFraction -> exponentAndMantissa(dataItem) { e, m -> DecimalFraction(e, m) } Tag.BigFloat -> exponentAndMantissa(dataItem) { e, m -> BigFloat(e, m) } Tag.ToBase16 -> UnsupportedTagDataItem(value(), dataItem) // TODO Tag.ToBase64 -> UnsupportedTagDataItem(value(), dataItem) // TODO Tag.ToBase64Url -> UnsupportedTagDataItem(value(), dataItem) // TODO Tag.CborDataItem -> CborDataItem(expected(dataItem)) Tag.SelfDescribedCbor -> SelfDescribedCbor(dataItem) Tag.Uri -> UriDataItem(expected(dataItem)) Tag.Base64Url -> Base64UrlDataItem(expected(dataItem)) Tag.Base64 -> Base64DataItem(expected(dataItem)) Tag.Regex -> RegexDataItem(expected(dataItem)) Tag.Mime -> MimeDataItem(expected(dataItem)) Tag.CalendarDay -> CalendarDayDataItem(expected(dataItem)) Tag.CalendarDate -> CalendarDateDataItem(expected(dataItem)) } } } private inline fun <reified DI : DataItem> Tag.expected(dataItem: DataItem): DI { require(dataItem is DI) { "$dataItem is not valid for $this. Expecting ${DI::class}" } return dataItem } private fun <DI> Tag.exponentAndMantissa( dataItem: DataItem, cons: (IntegerDataItem, IntegerDataItem) -> DI, ): DI { val array = expected<ArrayDataItem>(dataItem) require(array.size == 2) { "Array must have 2 elements" } return cons(expected(array[0]), expected(array[1])) }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/Tag.kt
4115782995
package io.github.routis.cbor.internal import io.github.routis.cbor.* import kotlinx.io.* import kotlin.contracts.contract /** * When reading a byte array for [DataItem] you can * get either a [DataItemOrBreak.Item] or a [DataItemOrBreak.Break] */ private sealed interface DataItemOrBreak { data class Item(val item: DataItem) : DataItemOrBreak data object Break : DataItemOrBreak } /** * Lifts a [DataItem] to the [DataItemOrBreak] hierarchy */ private fun DataItem.orBreak() = DataItemOrBreak.Item(this) /** * Reads the next [DataItem] from the source. * * @throws IllegalStateException when instead of a [DataItem] we get break */ @Throws(IllegalStateException::class, IOException::class) internal fun Source.readDataItem(): DataItem { val dataItemOrBreak = readDataItemOrBreak() check(dataItemOrBreak is DataItemOrBreak.Item) { "Unexpected break" } return dataItemOrBreak.item } /** * Reads the next [DataItem] or break from the source. */ private fun Source.readDataItemOrBreak(): DataItemOrBreak { val initialByte = readUByte() val majorType = MajorType.fromInitialByte(initialByte) val additionalInfo = AdditionalInfo.fromInitialByte(initialByte) fun readSizeThen(block: (Size) -> DataItem): DataItem = readSize(additionalInfo).let(block) return when (majorType) { MajorType.Zero -> readUnsignedInteger(additionalInfo).orBreak() MajorType.One -> readNegativeInteger(additionalInfo).orBreak() MajorType.Two -> readSizeThen(::readByteString).orBreak() MajorType.Three -> readSizeThen(::readTextString).orBreak() MajorType.Four -> readSizeThen(::readArray).orBreak() MajorType.Five -> readSizeThen(::readMap).orBreak() MajorType.Six -> readTagged(additionalInfo).orBreak() MajorType.Seven -> readMajorSeven(additionalInfo) } } private fun Source.readUnsignedInteger(additionalInfo: AdditionalInfo): UnsignedIntegerDataItem { val value = readUnsignedInt(additionalInfo) return UnsignedIntegerDataItem(value) } private fun Source.readNegativeInteger(additionalInfo: AdditionalInfo): NegativeIntegerDataItem { val value = readUnsignedInt(additionalInfo) return NegativeIntegerDataItem(value) } private const val BRAKE_BYTE: UByte = 0b111_11111u private fun Source.readByteString(size: Size): ByteStringDataItem { val byteCount = when (size) { Size.Indefinite -> indexOf(BRAKE_BYTE.toByte()) is Size.Definite -> size.value.toLong() } val bytes = readByteArray(byteCount.toInt()) return ByteStringDataItem(bytes) } private fun Source.readTextString(size: Size): TextStringDataItem { val text = when (size) { Size.Indefinite -> { var buffer = "" untilBreak { item -> require(item is TextStringDataItem) buffer += item.text } buffer } is Size.Definite -> { require(size.value <= Long.MAX_VALUE.toULong()) { "Too big byteCount to handle" } val byteCount = size.value.toLong() readString(byteCount) } } return TextStringDataItem(text) } private fun Source.readArray(size: Size): ArrayDataItem { val items = buildList { when (size) { Size.Indefinite -> untilBreak(::add) is Size.Definite -> repeat(size.value) { add(readDataItem()) } } } return ArrayDataItem(items) } private fun Source.readMap(size: Size): MapDataItem { val items = buildMap { fun put(item: DataItem) { val key = keyOf(item) ?: error("$item cannot be used as key") check(!contains(key)) { "Duplicate $key" } val value = readDataItem() put(key, value) } when (size) { Size.Indefinite -> untilBreak(::put) is Size.Definite -> repeat(size.value) { put(readDataItem()) } } } return MapDataItem(items) } private fun Source.readTagged(additionalInfo: AdditionalInfo): TaggedDataItem<*> { val tag = readUnsignedInt(additionalInfo) val dataItem = readDataItem() return when (val supportedTag = Tag.of(tag)) { null -> UnsupportedTagDataItem(tag, dataItem) else -> dataItem.tagged(supportedTag) } } private fun Source.readMajorSeven(additionalInfo: AdditionalInfo): DataItemOrBreak { return when (additionalInfo.value) { in 0u..19u -> UnassignedDataItem(additionalInfo.value).orBreak() AdditionalInfo.BOOLEAN_FALSE -> BooleanDataItem(false).orBreak() AdditionalInfo.BOOLEAN_TRUE -> BooleanDataItem(true).orBreak() AdditionalInfo.NULL -> NullDataItem.orBreak() AdditionalInfo.UNDEFINED -> UndefinedDataItem.orBreak() AdditionalInfo.RESERVED_OR_UNASSIGNED -> when (val next = readUByte()) { in 0.toUByte()..31.toUByte() -> ReservedDataItem(next) else -> UnassignedDataItem(next) }.orBreak() AdditionalInfo.HALF_PRECISION_FLOAT -> HalfPrecisionFloatDataItem(floatFromHalfBits(readShort())).orBreak() AdditionalInfo.SINGLE_PRECISION_FLOAT -> SinglePrecisionFloatDataItem(Float.fromBits(readInt())).orBreak() AdditionalInfo.DOUBLE_PRECISION_FLOAT -> DoublePrecisionFloatDataItem(Double.fromBits(readLong())).orBreak() in 28u..30u -> UnassignedDataItem(additionalInfo.value).orBreak() AdditionalInfo.BREAK -> DataItemOrBreak.Break else -> error("Not supported") } } /** * Reads the next [DataItem] until it finds a break. * For each [DataItem] the callback [useDataItem] is being invoked */ private fun Source.untilBreak(useDataItem: (DataItem) -> Unit) { do { val dataItemOrBreak = readDataItemOrBreak() if (dataItemOrBreak is DataItemOrBreak.Item) { useDataItem(dataItemOrBreak.item) } } while (dataItemOrBreak !is DataItemOrBreak.Break) } private inline fun repeat( times: ULong, action: (ULong) -> Unit, ) { contract { callsInPlace(action) } for (index in 0uL until times) { action(index) } } private sealed interface Size { data object Indefinite : Size data class Definite(val value: ULong) : Size } private fun Source.readSize(additionalInfo: AdditionalInfo): Size = when (additionalInfo.value) { AdditionalInfo.INDEFINITE_LENGTH_INDICATOR -> Size.Indefinite else -> Size.Definite(readUnsignedInt(additionalInfo)) } /** * Reads from the [Source] an unsigned integer, using the [additionalInfo] as follows: * - if [additionalInfo] is less than 24, the result is the additional info itself * - if [additionalInfo] is 24, 25, 26 or 27 The argument's value is held in the following 1, 2, 4, or 8 bytes, * respectively, in network byte order * * @param additionalInfo the instruction on how to read the unsigned integer * @receiver The [Source] to read from * @return the unsigned integer. Regardless of the case this always a [ULong] */ private fun Source.readUnsignedInt(additionalInfo: AdditionalInfo): ULong { return when (additionalInfo.value) { in AdditionalInfo.ZeroToTwentyThreeRange -> additionalInfo.value.toULong() AdditionalInfo.SINGLE_BYTE_UINT -> readUByte().toULong() AdditionalInfo.DOUBLE_BYTE_UINT -> readUShort().toULong() AdditionalInfo.FOUR_BYTE_UINT -> readUInt().toULong() AdditionalInfo.EIGHT_BYTE_UINT -> readULong() else -> error("Cannot use ${additionalInfo.value} for reading unsigned. Valid values are in 0..27 inclusive") } }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/internal/DecodeIO.kt
2904711799
@file:JvmName("Decoder") package io.github.routis.cbor import io.github.routis.cbor.internal.readDataItem import kotlinx.io.Buffer import kotlinx.io.IOException import kotlin.io.encoding.Base64 import kotlin.jvm.JvmName /** * Decodes the given [source] into [DataItem] * * @param source the CBOR bytes Base64, URL safe, encoded. * * @throws IOException if something goes wrong with IO * @throws IllegalStateException if the given input is invalid */ @Throws(IllegalStateException::class, IOException::class) fun decodeBase64UrlSafe(source: String): DataItem { val bytes = Base64.UrlSafe.decode(source) return decode(bytes) } /** * Decodes the given [bytes] into [DataItem] * * @param bytes input to decode. * * @throws IOException if something goes wrong with IO * @throws IllegalStateException if the given input is invalid */ @Throws(IllegalStateException::class, IOException::class) fun decode(bytes: ByteArray): DataItem { return Buffer().use { buffer -> buffer.write(bytes) buffer.readDataItem() } }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Decode.kt
4113610258
@file:JvmName("Encoder") package io.github.routis.cbor import io.github.routis.cbor.internal.writeDataItem import kotlinx.io.Buffer import kotlinx.io.IOException import kotlinx.io.readByteArray import kotlin.jvm.JvmName /** * Encodes the given [dataItem] into a [ByteArray] according to CBOR * * The implementation doesn't support indefinite size (aka streaming) * for lists, maps or other types. * * @param dataItem the item to encode * @return the byte representation of the item in CBOR * * @throws IOException if something goes wrong with IO */ @Throws(IOException::class) fun encode(dataItem: DataItem): ByteArray { return Buffer().use { buffer -> buffer.writeDataItem(dataItem) buffer.readByteArray() } }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Encode.kt
2282245665
package io.github.routis.cbor sealed interface DataItem /** * Integer numbers in the range -2^64..2^64-1 inclusive */ sealed interface IntegerDataItem : DataItem /** * Unsigned integer in the range 0 to 2^64-1 inclusive * * @param value The numeric value */ data class UnsignedIntegerDataItem(val value: ULong) : IntegerDataItem { init { require(value >= 0uL) { "Value should be in range 0..2^64-1" } } } /** * Negative integer in the range -2^64 to -1 inclusive * * Please note that the [value] is the unsigned (zero or positive) representation * of the number. * * To get the actual numeric value, please use [NegativeIntegerDataItem.asBigInteger] * * @param value the unsigned representation of the Negative Integer. */ data class NegativeIntegerDataItem(val value: ULong) : IntegerDataItem { init { require(value >= 0uL) { "Value should be in range 0..2^64-1" } } } /** * A "string" of [bytes] */ data class ByteStringDataItem(val bytes: ByteArray) : DataItem { override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as ByteStringDataItem return bytes.contentEquals(other.bytes) } override fun hashCode(): Int = bytes.contentHashCode() } /** * A [text] string encoded as UTF-8. */ data class TextStringDataItem(val text: String) : DataItem /** * An array of data [items]. * Items in an array do not need to all be of the same type */ data class ArrayDataItem(private val items: List<DataItem>) : DataItem, List<DataItem> by items /** * A map (set of key value pairs) * Not all [DataItem] can be used as keys. * Check [Key] */ data class MapDataItem(private val items: Map<Key<*>, DataItem>) : DataItem, Map<Key<*>, DataItem> by items /** * A tagged [DataItem] * @param DI the type of the content */ sealed interface TaggedDataItem<out DI : DataItem> : DataItem { val content: DI } /** * Tag number 0 contains a text string in the standard format described by the * date-time production in RFC3339, as refined by Section 3.3 of RFC4287, * representing the point in time described there. */ data class StandardDateTimeDataItem(override val content: TextStringDataItem) : TaggedDataItem<TextStringDataItem> sealed interface EpochBasedDateTime<DI : DataItem> : TaggedDataItem<DI> data class IntegerEpochDataItem(override val content: IntegerDataItem) : EpochBasedDateTime<IntegerDataItem> data class HalfFloatEpochDataItem(override val content: HalfPrecisionFloatDataItem) : EpochBasedDateTime<HalfPrecisionFloatDataItem> data class SingleFloatEpochDataItem(override val content: SinglePrecisionFloatDataItem) : EpochBasedDateTime<SinglePrecisionFloatDataItem> data class DoubleFloatEpochDataItem(override val content: DoublePrecisionFloatDataItem) : EpochBasedDateTime<DoublePrecisionFloatDataItem> /** * To get the actual numeric value, please use [BigNumUnsigned.asBigInteger] */ data class BigNumUnsigned(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem> /** * To get the actual numeric value, please use [BigNumNegative.asBigInteger] */ data class BigNumNegative(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem> data class DecimalFraction( val exponent: IntegerDataItem, val mantissa: IntegerDataItem, ) : TaggedDataItem<ArrayDataItem> { override val content: ArrayDataItem get() = ArrayDataItem(listOf(exponent, mantissa)) } data class BigFloat( val exponent: IntegerDataItem, val mantissa: IntegerDataItem, ) : TaggedDataItem<ArrayDataItem> { override val content: ArrayDataItem get() = ArrayDataItem(listOf(exponent, mantissa)) } data class CborDataItem(override val content: ByteStringDataItem) : TaggedDataItem<ByteStringDataItem> { constructor(content: ByteArray) : this(ByteStringDataItem(content)) } data class SelfDescribedCbor(override val content: DataItem) : TaggedDataItem<DataItem> sealed interface EncodedText : TaggedDataItem<TextStringDataItem> data class Base64DataItem(override val content: TextStringDataItem) : EncodedText { constructor(content: String) : this(TextStringDataItem(content)) } data class Base64UrlDataItem(override val content: TextStringDataItem) : EncodedText { constructor(content: String) : this(TextStringDataItem(content)) } data class RegexDataItem(override val content: TextStringDataItem) : EncodedText { constructor(content: String) : this(TextStringDataItem(content)) } data class MimeDataItem(override val content: TextStringDataItem) : EncodedText { constructor(content: String) : this(TextStringDataItem(content)) } data class UriDataItem(override val content: TextStringDataItem) : EncodedText { constructor(content: String) : this(TextStringDataItem(content)) } data class CalendarDayDataItem(override val content: IntegerDataItem) : TaggedDataItem<IntegerDataItem> data class CalendarDateDataItem(override val content: TextStringDataItem) : TaggedDataItem<TextStringDataItem> { constructor(content: String) : this(TextStringDataItem(content)) } data class UnsupportedTagDataItem(val tag: ULong, override val content: DataItem) : TaggedDataItem<DataItem> data class BooleanDataItem(val value: Boolean) : DataItem data class HalfPrecisionFloatDataItem(val value: Float) : DataItem data class SinglePrecisionFloatDataItem(val value: Float) : DataItem data class DoublePrecisionFloatDataItem(val value: Double) : DataItem data object NullDataItem : DataItem data object UndefinedDataItem : DataItem data class UnassignedDataItem(val value: UByte) : DataItem data class ReservedDataItem(val value: UByte) : DataItem
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/DataItem.kt
177934608
package io.github.routis.cbor /** * [Data items][DataItem] that can be used as keys in a [CBOR map][MapDataItem] * @param DI The type of the data item */ sealed interface Key<out DI : DataItem> { /** * The data item of the key */ val item: DI } data class BoolKey(override val item: BooleanDataItem) : Key<BooleanDataItem> data class ByteStringKey(override val item: ByteStringDataItem) : Key<ByteStringDataItem> data class IntegerKey(override val item: IntegerDataItem) : Key<IntegerDataItem> data class TextStringKey(override val item: TextStringDataItem) : Key<TextStringDataItem> /** * Creates a [Key] for the given [dataItem] * In case the [dataItem] cannot be used as a kay a `null` is being returned. */ fun keyOf(dataItem: DataItem): Key<DataItem>? = when (dataItem) { is BooleanDataItem -> BoolKey(dataItem) is ByteStringDataItem -> ByteStringKey(dataItem) is UnsignedIntegerDataItem -> IntegerKey(dataItem) is NegativeIntegerDataItem -> IntegerKey(dataItem) is TextStringDataItem -> TextStringKey(dataItem) else -> null }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/Key.kt
639629331
@file:JvmName("JsonConverter") package io.github.routis.cbor import io.github.routis.cbor.internal.dataItemToJson import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonPrimitive import kotlin.io.encoding.Base64 typealias KeyMapper<K> = (K) -> String? /** * Options on if and how to serialize a [Key] other than [TextStringKey], * into a Json attribute name. * One may choose to not map into Json other keys (besides [TextStringKey]) * to make sure that there is no key collision in JSON. * * @param boolKeyMapper how to include [BoolKey] * @param byteStringKeyMapper how to include [ByteStringKey] * @param integerKeyMapper how to include [IntegerKey] */ data class KeyOptions @JvmOverloads constructor( val boolKeyMapper: KeyMapper<BoolKey>? = null, val byteStringKeyMapper: KeyMapper<ByteStringKey>? = null, val integerKeyMapper: KeyMapper<IntegerKey>? = null, ) /** * A function that serializes a [ByteStringDataItem] into a [JsonElement] */ typealias ByteStringOption = (ByteStringDataItem) -> JsonElement /** * Options for converting a [DataItem] into Json * * @param keyOptions options about [keys][Key] of [maps][MapDataItem] * @param byteStringOption how to serialize into JSON a [ByteStringDataItem] */ data class JsonOptions( val keyOptions: KeyOptions, val byteStringOption: ByteStringOption, ) { companion object { /** * Serializes a [ByteStringDataItem] into a base64 url encoded string */ @JvmStatic val Base64UrlEncodedBytes: ByteStringOption = { byteString -> JsonPrimitive(Base64.UrlSafe.encode(byteString.bytes)) } /** * Choice to use only [text keys][TextStringKey] */ @JvmStatic val UseOnlyTextKey: KeyOptions = KeyOptions(boolKeyMapper = null, byteStringKeyMapper = null, integerKeyMapper = null) /** * Default convention options. * Uses [UseOnlyTextKey] and [Base64UrlEncodedBytes] */ @JvmStatic val Default = JsonOptions(keyOptions = UseOnlyTextKey, byteStringOption = Base64UrlEncodedBytes) } } /** * Converts the a [DataItem] into JSON using the provided [options] * @receiver the item to convert */ @JvmOverloads fun DataItem.toJson(options: JsonOptions = JsonOptions.Default): JsonElement = with(options) { dataItemToJson(this@toJson) }
cbor/lib/src/commonMain/kotlin/io/github/routis/cbor/JsonConverter.kt
2847818842
package io.github.routis.cbor import io.github.routis.cbor.internal.AdditionalInfo import kotlin.test.Test import kotlin.test.assertEquals class AdditionalInfoTests { @Test fun additionalInfoForUnsignedInt_for_number_0_to_23_UByte() { val start: UByte = 0u val end: UByte = 23u (start..end).forEach { assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_24_to_2255_UByte() { val start: UByte = 24u val end: UByte = 255u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_0_to_23_UShort() { val start: UShort = 0u val end: UShort = 23u (start..end).forEach { assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_24_to_2255_UShort() { val start: UShort = 24u val end: UShort = 255u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_2256_to_65535_UByte() { val start: UShort = 256u val end: UShort = 65535u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_0_to_23_UInt() { val start = 0u val end = 23u (start..end).forEach { assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_24_to_2255_UInt() { val start = 24u val end = 255u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_2256_to_65535_UInt() { val start = 256u val end = 65535u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it.toULong())) } } @Test fun additionalInfoForUnsignedInt_for_number_0_to_23_ULong() { val start: ULong = 0u val end: ULong = 23u (start..end).forEach { assertEquals(AdditionalInfo(it.toUByte()), AdditionalInfo.forUnsignedInt(it)) } } @Test fun additionalInfoForUnsignedInt_for_number_24_to_2255_ULong() { val start: ULong = 24u val end: ULong = 255u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.SINGLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it)) } } @Test fun additionalInfoForUnsignedInt_for_number_2256_to_65535_ULong() { val start: ULong = 256u val end: ULong = 65535u (start..end).forEach { assertEquals(AdditionalInfo(AdditionalInfo.DOUBLE_BYTE_UINT), AdditionalInfo.forUnsignedInt(it)) } } }
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/AdditionalInfoTests.kt
3529047832
package io.github.routis.cbor import com.ionspin.kotlin.bignum.integer.BigInteger import kotlinx.serialization.encodeToString import kotlin.test.Test import kotlin.test.assertEquals class DecodeTests { @Test fun major_0_single_byte() { for (i in 0..23) { val expected = UnsignedIntegerDataItem(i.toULong()) val decoded = decode(byteArrayOf(i.toByte())) assertEquals(expected, decoded) } } @Test fun major_0_0b000_01010_is_uint_10() { val bytes = byteArrayOf(0b000_01010.toByte()) val decoded = decode(bytes) assertEquals(UnsignedIntegerDataItem(10uL), decoded) } @Test fun value_0b000_11001_followed_by_0x01F4_is_uint_500() { val bytes = byteArrayOf( 0b000_11001.toByte(), 0x01.toByte(), 0xF4.toByte(), ) val decoded = decode(bytes) assertEquals(UnsignedIntegerDataItem(500uL), decoded) } @Test fun value_minus_500_should_be_represented_as_Major_1_499() { val value499 = 499uL 0b001_11001.toHexString().also { println(it) } val bytes = byteArrayOf( 0b001_11001.toByte(), 0x01.toByte(), 0xF3.toByte(), ) val decoded = decode(bytes) assertEquals(NegativeIntegerDataItem(value499), decoded) } @Test fun value_1000000000000() { val bytes: ByteArray = byteArrayOf( 0x1B, 0x00, 0x00, 0x00, 0xE8.toByte(), 0xD4.toByte(), 0xA5.toByte(), 0x10, 0x00, ) val decoded = decode(bytes) val expected = UnsignedIntegerDataItem(1000000000000uL) assertEquals(expected, decoded) } @Test fun value_18446744073709551616() { val bytes = byteArrayOf( 0xC2.toByte(), 0x49.toByte(), 0x01.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), 0x00.toByte(), ) val decoded = decode(bytes) val expected = BigNumUnsigned(ByteStringDataItem(BigInteger.parseString("18446744073709551616").toByteArray())) assertEquals(expected, decoded) } @Test fun value_uri() { val bytes = byteArrayOf( 0xd8.toByte(), 0x20.toByte(), 0x76.toByte(), 0x68.toByte(), 0x74.toByte(), 0x74.toByte(), 0x70.toByte(), 0x3a.toByte(), 0x2f.toByte(), 0x2f.toByte(), 0x77.toByte(), 0x77.toByte(), 0x77.toByte(), 0x2e.toByte(), 0x65.toByte(), 0x78.toByte(), 0x61.toByte(), 0x6d.toByte(), 0x70.toByte(), 0x6c.toByte(), 0x65.toByte(), 0x2e.toByte(), 0x63.toByte(), 0x6f.toByte(), 0x6d.toByte(), ) val decoded = decode(bytes) val expected = UriDataItem("http://www.example.com") assertEquals(expected, decoded) } @Test fun vp_token_should_be_decoded() { decodeBase64UrlSafe(vpToken).also { cbor -> cbor.toJson().also { println(jsonSupport.encodeToString(it)) } } } @Test fun sample_msoMdoc_should_be_decoded() { decodeBase64UrlSafe(sampleMsoMdoc).also { cbor -> cbor.toJson().also { println(jsonSupport.encodeToString(it)) } } } @Test fun other_should_be_decoded() { decode(otherHex.hexToByteArray(format = HexFormat { upperCase = true })).also { cbor -> cbor.toJson().also { println(jsonSupport.encodeToString(it)) } } } private val vpToken = """ o2d2ZXJzaW9uYzEuMGlkb2N1bWVudHOBo2dkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlkLjFsaXNzdWVyU2lnbmVkompuYW1lU3BhY2VzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xkNgYWFikaGRpZ2VzdElEE2ZyYW5kb21QSmzzPZyCDv1T17NLxFK-onFlbGVtZW50SWRlbnRpZmllcmtmYW1pbHlfbmFtZWxlbGVtZW50VmFsdWVpQU5ERVJTU09O2BhYUaRoZGlnZXN0SUQEZnJhbmRvbVDqmfP2aA8nfl5TSHowY8m9cWVsZW1lbnRJZGVudGlmaWVyamdpdmVuX25hbWVsZWxlbWVudFZhbHVlY0pBTtgYWFykaGRpZ2VzdElEGBhmcmFuZG9tUJ1dU9F63fDU9XpbZ5IjMq5xZWxlbWVudElkZW50aWZpZXJqYmlydGhfZGF0ZWxlbGVtZW50VmFsdWXZA-xqMTk4NS0wMy0zMNgYWF6kaGRpZ2VzdElEDmZyYW5kb21QCU2SXHh-buWPbU6RMHcY73FlbGVtZW50SWRlbnRpZmllcnFmYW1pbHlfbmFtZV9iaXJ0aGxlbGVtZW50VmFsdWVpQU5ERVJTU09O2BhYV6RoZGlnZXN0SUQLZnJhbmRvbVDE-UnG_R9fklw8tMfXIQXOcWVsZW1lbnRJZGVudGlmaWVycGdpdmVuX25hbWVfYmlydGhsZWxlbWVudFZhbHVlY0pBTtgYWFWkaGRpZ2VzdElECmZyYW5kb21Q7aHFdl7agjf38513RbhjzHFlbGVtZW50SWRlbnRpZmllcmtiaXJ0aF9wbGFjZWxlbGVtZW50VmFsdWVmU1dFREVO2BhYZKRoZGlnZXN0SUQYGWZyYW5kb21QGVDZsN0X6o47yYU938bdR3FlbGVtZW50SWRlbnRpZmllcnByZXNpZGVudF9hZGRyZXNzbGVsZW1lbnRWYWx1ZW9GT1JUVU5BR0FUQU4gMTXYGFhcpGhkaWdlc3RJRAVmcmFuZG9tUDkVyImEeK9h7opQdhbeSDxxZWxlbWVudElkZW50aWZpZXJtcmVzaWRlbnRfY2l0eWxlbGVtZW50VmFsdWVrS0FUUklORUhPTE3YGFhdpGhkaWdlc3RJRBJmcmFuZG9tUF8F2eAL4JrvyQ0A5tBdfXpxZWxlbWVudElkZW50aWZpZXJ0cmVzaWRlbnRfcG9zdGFsX2NvZGVsZWxlbWVudFZhbHVlZTY0MTMz2BhYVKRoZGlnZXN0SUQMZnJhbmRvbVDm5aPBwr7FsyZX5k1nj2gRcWVsZW1lbnRJZGVudGlmaWVybnJlc2lkZW50X3N0YXRlbGVsZW1lbnRWYWx1ZWJTRdgYWFakaGRpZ2VzdElEAGZyYW5kb21Qi0eHxS49YJdz_yxPWTx3lnFlbGVtZW50SWRlbnRpZmllcnByZXNpZGVudF9jb3VudHJ5bGVsZW1lbnRWYWx1ZWJTRdgYWEqkaGRpZ2VzdElEA2ZyYW5kb21QDwYENdGWt-XUq7gi1iPEbHFlbGVtZW50SWRlbnRpZmllcmZnZW5kZXJsZWxlbWVudFZhbHVlAdgYWFGkaGRpZ2VzdElED2ZyYW5kb21Q4NMx_u8EloVTQkzjZ7GShXFlbGVtZW50SWRlbnRpZmllcmtuYXRpb25hbGl0eWxlbGVtZW50VmFsdWViU0XYGFhPpGhkaWdlc3RJRAJmcmFuZG9tUFE9zNuMOez7t6LQ5jnQVRBxZWxlbWVudElkZW50aWZpZXJrYWdlX292ZXJfMThsZWxlbWVudFZhbHVl9dgYWFGkaGRpZ2VzdElEFmZyYW5kb21Qa0Mdsk6zlTuKvl_ifh-rGXFlbGVtZW50SWRlbnRpZmllcmxhZ2VfaW5feWVhcnNsZWxlbWVudFZhbHVlGCbYGFhUpGhkaWdlc3RJRA1mcmFuZG9tUHVeV2RpUa1pvkam8EBOMHdxZWxlbWVudElkZW50aWZpZXJuYWdlX2JpcnRoX3llYXJsZWxlbWVudFZhbHVlGQfBamlzc3VlckF1dGiEQ6EBJqEYIVkChTCCAoEwggImoAMCAQICCRZK5ZkC3AUQZDAKBggqhkjOPQQDAjBYMQswCQYDVQQGEwJCRTEcMBoGA1UEChMTRXVyb3BlYW4gQ29tbWlzc2lvbjErMCkGA1UEAxMiRVUgRGlnaXRhbCBJZGVudGl0eSBXYWxsZXQgVGVzdCBDQTAeFw0yMzA1MzAxMjMwMDBaFw0yNDA1MjkxMjMwMDBaMGUxCzAJBgNVBAYTAkJFMRwwGgYDVQQKExNFdXJvcGVhbiBDb21taXNzaW9uMTgwNgYDVQQDEy9FVSBEaWdpdGFsIElkZW50aXR5IFdhbGxldCBUZXN0IERvY3VtZW50IFNpZ25lcjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHyTE_TBpKpOsLPraBGkmU5Z3meZZDHC864IjrehBhy2WL2MORJsGVl6yQ35nQeNPvORO6NL2yy8aYfQJ-mvnfyjgcswgcgwHQYDVR0OBBYEFNGksSQ5MvtFcnKZSPJSfZVYp00tMB8GA1UdIwQYMBaAFDKR6w4cAR0UDnZPbE_qTJY42vsEMA4GA1UdDwEB_wQEAwIHgDASBgNVHSUECzAJBgcogYxdBQECMB8GA1UdEgQYMBaGFGh0dHA6Ly93d3cuZXVkaXcuZGV2MEEGA1UdHwQ6MDgwNqA0oDKGMGh0dHBzOi8vc3RhdGljLmV1ZGl3LmRldi9wa2kvY3JsL2lzbzE4MDEzLWRzLmNybDAKBggqhkjOPQQDAgNJADBGAiEA3l-Y5x72V1ISa_LEuE_e34HSQ8pXsVvTGKq58evrP30CIQD-Ivcya0tXWP8W_obTOo2NKYghadoEm1peLIBqsUcISFkE1tgYWQTRpmd2ZXJzaW9uYzEuMG9kaWdlc3RBbGdvcml0aG1nU0hBLTI1Nmdkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlkLjFsdmFsdWVEaWdlc3RzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xuBoAWCAxMjgJkpvspLKPMN-Pnty4oh4maG2wtTFoemKpj_m5lgFYIH1Zh6Dbdoa5uXkKnqkxeq9h6djxynaGjSNEiqjsfbqnAlggTPupXMvLYNCuUxRiJH6g5qXfcWJIZ3ksZdcBA3pRwVUDWCB09uPPCqgMuIAJjQn2YRgmBl_tT9_3E9e0Jt3wburrMQRYIKyhscjEnmppDBFnWXIexzJ6VA3qO_0O_28WUVZ7Do73BVggTnDM3Imck9Hyok1Bmq4AZppNorJD00rpxc5BcXL5DJIGWCAo2rB9bGnbf9Xk5SYW22eaR2gxf1fj8a5rvDrpg66_jgdYIGo9ozvjL4bMgj7DuocMDAW5625WzDTj_BYNkHWFtgWOCFgg33OYzqyvNX-DNFMfs2ylTqBLJLnd8Yrm-ifEwMKPOhcJWCC31ffovu9YfCMFuUG7bdA3aqLaAEslQSq3whIl2pftugpYIC871wTY0U5kzcdUgKT0-HU2vOQGK_R7xTYzMeHdNW-nC1ggOWtn_Y2bEeQPO-5c0ULn9SbuLqx3et9VPV_97W_4ak0MWCCfycCaJs0xNbn_hWILpaZFvND6lWlm0oWRXTr_fA3BeA1YIKh7sCAEOwZJgTTy8o1xKD3B3x377CyYJX60oNthxPOtDlggwlmw_3oWKQZuk5zZ6J3WqWs8CPUKBgqQ_-4iiQNi-Z8PWCDrLdImBO7FEZy6AOWUKiDZqCgLy3OIAbhL3r2saF_VQhBYIKfGo-N144iz-NMxZKBHRITm8nE0ehQLPYDjvyRZ9l4eEVggU--gmFBCsGFt4k9ok9OYq1x5yRudR2EI5aoypDqdo5gSWCDWNI6q2jc9agynYGJAcI2iNFmoBYtErVC0_M-gKmrGSBNYIJ7xfKUNEwKhWfOX7XepB-wbgTRbZvBaGWXLYNb3Gf9AFFgg5C3mvEIKHsvvRRew19IErl0H7LcjBuozBqiUAqgpkWUVWCDCgU5RvDr9vu213R4u8rPTZ7h8CiVBDGTnvwH4GOe7RhZYIPOVFTWGsQyS2tAEWHFmpBX0qA33YuedXUdCM_w4El-XF1ggpWkSSNUczHH0KlnfVMYGF91Nh1k4QWNpGBAJKWISthUYGFgg6QCJ07heChHShYpVlRM2H-FmFVTEH_TQPQn4ie44ZGMYGVggDxlSeoNAWC2gPtQRoGXudIsumxrSkV6vi9ePrJYLN_NtZGV2aWNlS2V5SW5mb6FpZGV2aWNlS2V5pAECIAEhWCBUnC7AtGRRpb0PMV3aoCWymw28qjrFbRp6khJkvPK5TSJYIIzHjsTwaoV-LlDUVbScnLjsn1Nqfs6iSqo5-J2FKtPxbHZhbGlkaXR5SW5mb6Nmc2lnbmVkwHQyMDIzLTA3LTEzVDE2OjA4OjQ1Wml2YWxpZEZyb23AdDIwMjMtMDctMTNUMTY6MDg6NDVaanZhbGlkVW50aWzAdDIwMjQtMDctMTNUMTY6MDg6NDVaWEAtug-r916DygJtBmo-uBWynnJDQXy0N7zre1jnDf4qnaRq8OZENCiEfG4Jiw9saECd84Y7BKXZpTK4j1J14dvObGRldmljZVNpZ25lZKJqbmFtZVNwYWNlc9gYQaBqZGV2aWNlQXV0aKFvZGV2aWNlU2lnbmF0dXJlhEOhASag9lhA_5-pTyCo_U85BsOkGlYkKtYJjWfWz0myI6Q6lRWI-qunvUb1Bd3aWYxod5Fx6_NLDJjqs4k0SCKHwLZDhBkIHmZzdGF0dXMA """.trimIndent().replace("\n", "") private val sampleMsoMdoc = """ o2ZzdGF0dXMAZ3ZlcnNpb25jMS4waWRvY3VtZW50c4GiZ2RvY1R5cGV4GGV1LmV1cm9wYS5lYy 5ldWRpdy5waWQuMWxpc3N1ZXJTaWduZWSiamlzc3VlckF1dGiEQ6EBJqEYIVkC6DCCAuQwggJq oAMCAQICFHIybfZjCJp7UA-MPyamhcvCwtLKMAoGCCqGSM49BAMCMFwxHjAcBgNVBAMMFVBJRC BJc3N1ZXIgQ0EgLSBVVCAwMTEtMCsGA1UECgwkRVVESSBXYWxsZXQgUmVmZXJlbmNlIEltcGxl bWVudGF0aW9uMQswCQYDVQQGEwJVVDAeFw0yMzA5MDIxNzQyNTFaFw0yNDExMjUxNzQyNTBaMF QxFjAUBgNVBAMMDVBJRCBEUyAtIDAwMDExLTArBgNVBAoMJEVVREkgV2FsbGV0IFJlZmVyZW5j ZSBJbXBsZW1lbnRhdGlvbjELMAkGA1UEBhMCVVQwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAA RJBHzUHC0bpmqOtZBhZbDmk94bHOWvem1civd-0j3esn8q8L1MCColNqQkCPadXjJAYsmXS3D4 -HB9scOshixYo4IBEDCCAQwwHwYDVR0jBBgwFoAUs2y4kRcc16QaZjGHQuGLwEDMlRswFgYDVR 0lAQH_BAwwCgYIK4ECAgAAAQIwQwYDVR0fBDwwOjA4oDagNIYyaHR0cHM6Ly9wcmVwcm9kLnBr aS5ldWRpdy5kZXYvY3JsL3BpZF9DQV9VVF8wMS5jcmwwHQYDVR0OBBYEFIHv9JxcgwpQpka-91 B4WlM-P9ibMA4GA1UdDwEB_wQEAwIHgDBdBgNVHRIEVjBUhlJodHRwczovL2dpdGh1Yi5jb20v ZXUtZGlnaXRhbC1pZGVudGl0eS13YWxsZXQvYXJjaGl0ZWN0dXJlLWFuZC1yZWZlcmVuY2UtZn JhbWV3b3JrMAoGCCqGSM49BAMCA2gAMGUCMEX62qLvLZVT67SIRNhkGtAqnjqOSit32uL0Hnlf Ly2QmwPygQmUa04tkoOtf8GhhQIxAJueTu1QEJ9fDrcALM-Ys_7kEUB-Ze4w-wEEvtZzguqD3h 9cxIjmEBdkATInQ0BNClkCgNgYWQJ7pmdkb2NUeXBleBhldS5ldXJvcGEuZWMuZXVkaXcucGlk LjFndmVyc2lvbmMxLjBsdmFsaWRpdHlJbmZvo2ZzaWduZWTAdDIwMjMtMTEtMDlUMTQ6NTI6Mz laaXZhbGlkRnJvbcB0MjAyMy0xMS0wOVQxNDo1MjozOVpqdmFsaWRVbnRpbMB0MjAyNC0wMi0x N1QwMDowMDowMFpsdmFsdWVEaWdlc3RzoXgYZXUuZXVyb3BhLmVjLmV1ZGl3LnBpZC4xqQBYID 5sw3SZR5gy-dq2Hti1SpQwPIqmPLBYzhyERS_szsLjAVgglDXLX4pQBIV3H-RIT2FYLBECnQUP UuS6krTINwXgnAECWCCUJ-qaB1TSmJWD7nxa3i9ZU4iOyaBbZkUGXlHj0Vw3bQNYINLsiLYiwL I_7LvGVRIEKkaD17tl7no0hq92FX4SQ6tEBFggKPg879SPzr9iWo6vi_2wdFbep33D-izjCrqc jFDesSQFWCA2SH-DH52oGL1D4NcVRgaJqWN6You9h8ZH85cr_-AhNQZYIHBtgMUXuj0ifnFect PWHgA1XBWTcPpysjfDyaKoy9t_B1ggZeACDTM7d6fCW5Mc8er4_I0EqhLzzaTvFDf7nSVJ3R4I WCDXbFUlmVhTr88PcHI67KL3YOzWQd20-T8TkJqoZ3Cx221kZXZpY2VLZXlJbmZvoWlkZXZpY2 VLZXmkAQIgASFYIGnFtLlPlN2AJ80EKW3PKKa8kROJpSM4x1xABck19Q-lIlgg32KKtkQwHBmc rvVxoJZdmFHY4hXRakJrCkl4nSuPTjFvZGlnZXN0QWxnb3JpdGhtZ1NIQS0yNTZYQG4p4t9PWK REh0_nGgxWiYV9Oq3rOqTXhE6CYtRAR0ies_BpSVSkUTbZniLcAp-nT0IvI-_le8hWC3iWSChd WWpqbmFtZVNwYWNlc6F4GGV1LmV1cm9wYS5lYy5ldWRpdy5waWQuMYnYGFiIpGZyYW5kb21YIM O_HzYnttnHb0yHd20C61HPPbnVvhjZ-JAiwzQg_chSaGRpZ2VzdElEAGxlbGVtZW50VmFsdWV4 ISBGb28gYmF0IGFkbWluaXN0cmF0aXZlIGF1dGhvcml0eXFlbGVtZW50SWRlbnRpZmllcnFpc3 N1aW5nX2F1dGhvcml0edgYWIOkZnJhbmRvbVgg2RsmtUKTY2LLmr62OuR9XZAmqMtMP1PhpgbB yveNO_JoZGlnZXN0SUQBbGVsZW1lbnRWYWx1ZXgkNTc3MTFjMjYtZjBkNC00NmFkLTliYjQtYW RkNTE5MDI1YjNkcWVsZW1lbnRJZGVudGlmaWVyaXVuaXF1ZV9pZNgYWGSkZnJhbmRvbVggNh1c mH2nCaczqnmqcnamE-2Z9lx3ntu0OmUsXxF0ZVloZGlnZXN0SUQCbGVsZW1lbnRWYWx1ZWVCYW Jpc3FlbGVtZW50SWRlbnRpZmllcmpnaXZlbl9uYW1l2BhYbaRmcmFuZG9tWCBC9Pl6hc0JLisV 2J9IQUfs9ZTXVhCoe85FSFXBK8-qdmhkaWdlc3RJRANsZWxlbWVudFZhbHVl2QPsajIwMjQtMD ItMTdxZWxlbWVudElkZW50aWZpZXJrZXhwaXJ5X2RhdGXYGFhspGZyYW5kb21YID_I8pi1wFu6 o0UN0R7VGHP_ho-AACUBDVnth_UNJ-QRaGRpZ2VzdElEBGxlbGVtZW50VmFsdWXZA-xqMjAyMy 0xMS0wOXFlbGVtZW50SWRlbnRpZmllcmpiaXJ0aF9kYXRl2BhYX6RmcmFuZG9tWCC_AmIAH-mv urJOAnIUGsOy3G7sl8PdFMt3lLSB_fjRO2hkaWdlc3RJRAVsZWxlbWVudFZhbHVl9XFlbGVtZW 50SWRlbnRpZmllcmppc19vdmVyXzE42BhYZqRmcmFuZG9tWCBqznUqqbCSDDPMzbilMxNZ0JKp OCk32u2FBNEDv0vpFWhkaWdlc3RJRAZsZWxlbWVudFZhbHVlZlJvdXRpc3FlbGVtZW50SWRlbn RpZmllcmtmYW1pbHlfbmFtZdgYWGakZnJhbmRvbVggLHJ8WFXncKMwTD3LRagOfLkRPbOzHYNZ T4wCBPcJAFFoZGlnZXN0SUQHbGVsZW1lbnRWYWx1ZWJGQ3FlbGVtZW50SWRlbnRpZmllcm9pc3 N1aW5nX2NvdW50cnnYGFhvpGZyYW5kb21YIEp-BnPVwHaFuxEwOOvm5rWfgj1RZRi1yPr86MxX to20aGRpZ2VzdElECGxlbGVtZW50VmFsdWXZA-xqMjAyMy0xMS0wOXFlbGVtZW50SWRlbnRpZm llcm1pc3N1YW5jZV9kYXRl """.trimIndent().replace("\n", "") private val otherHex = """ A2626964781E6469643A6578616D706C653A313233343536373839616263 6465666768696E61757468656E7469636174696F6E81A462696478256469 643A6578616D706C653A313233343536373839616263646566676869236B 6579732D316474797065781A45643235353139566572696669636174696F 6E4B6579323031386A636F6E74726F6C6C6572781E6469643A6578616D70 6C653A3132333435363738396162636465666768696F7075626C69634B65 79426173653538782C483343324156764C4D7636676D4D4E616D33755641 6A5A70666B634A437744776E5A6E367A3377586D715056 """.trimIndent().replace("\n", "") }
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/DecodeTests.kt
3260717541
package io.github.routis.cbor import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement val jsonSupport = Json { prettyPrint = true ignoreUnknownKeys = true } // https://github.com/cbor/test-vectors/blob/master/appendix_a.json @Serializable data class TestVector( val cbor: String, val hex: String, @SerialName("roundtrip") val roundTrip: Boolean, val decoded: JsonElement? = null, val diagnostic: String? = null, ) { val bytes: ByteArray by lazy { hex.hexToByteArray(HexFormat.Default) } }
cbor/lib/src/commonTest/kotlin/io/github/routis/cbor/TestSupport.kt
972144710
package com.example.composeapp import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.composeapp", appContext.packageName) } }
Android-Compose-App/app/src/androidTest/java/com/example/composeapp/ExampleInstrumentedTest.kt
664356573
package com.example.composeapp import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Android-Compose-App/app/src/test/java/com/example/composeapp/ExampleUnitTest.kt
2911153763
package com.example.composeapp.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.composeapp.data.DataState import com.example.composeapp.data.model.Characters import com.example.composeapp.data.repo.remote.NetworkRepository import com.example.composeapp.data.repo.remote.RemoteRepositoryImpl import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CharacterViewModel @Inject constructor(private val repository: RemoteRepositoryImpl): ViewModel() { private val _dataState = MutableStateFlow<DataState<Characters>>(DataState.Loading) val dataState: StateFlow<DataState<Characters>> = _dataState init { fetchData() } private fun fetchData(){ _dataState.value = DataState.Loading viewModelScope.launch { val data = repository.getCharacterData() NetworkRepository<Characters>().asFlow(data).collectLatest { mappedData -> _dataState.value = mappedData } } } }
Android-Compose-App/app/src/main/java/com/example/composeapp/viewmodel/CharacterVIewModel.kt
3779628482
package com.example.composeapp.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.AsyncImage import com.example.composeapp.Utils.CommonMethods.getColorByStatus import com.example.composeapp.data.DataState import com.example.composeapp.data.model.Characters import com.example.composeapp.viewmodel.CharacterViewModel @Composable fun CharacterList(modifier: Modifier= Modifier){ val viewModel = hiltViewModel<CharacterViewModel>() val response by viewModel.dataState.collectAsStateWithLifecycle() when(response){ is DataState.Loading -> { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center){ CircularProgressIndicator() } } is DataState.Error -> { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center){ Text(text = (response as DataState.Error).exception.localizedMessage ?: "Something went wrong") } } is DataState.Success -> { LazyColumn { items((response as DataState.Success<Characters>).data.results){ item -> CharacterItem(modifier = modifier,item) } } } } } @Composable fun CharacterItem(modifier: Modifier = Modifier, item: Characters.Result? = null){ Card( modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp), shape = RoundedCornerShape(4.dp), colors = CardDefaults.cardColors( containerColor = Color(0xFF3C3E44), contentColor = Color.Transparent ) ) { Row { AsyncImage( item?.image, contentDescription = "Character Image", contentScale = ContentScale.Crop, modifier = Modifier.size(width = 125.dp, height = 125.dp)) Column( modifier = Modifier .fillMaxWidth() .padding(start = 8.dp)) { Text( text = item?.name?:"", color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold ) Row( verticalAlignment = Alignment.CenterVertically) { Box(modifier = Modifier .size(6.dp) .clip(CircleShape) .background(color = getColorByStatus(item?.status))) Text( text = item?.status.plus(" - ").plus(item?.species?:""), fontSize = 12.sp, color = Color.White, modifier = Modifier.padding(start = 4.dp)) } ItemCommonInfo("Last known Location:",item?.location?.name?:"") // ItemCommonInfo("First seen in:",item?.episode?.getOrNull(0)?:"Unknown") } } } } @Composable fun ItemCommonInfo(title:String = "Last known Location:",data:String="Earth"){ Column(modifier = Modifier .fillMaxWidth() .padding(top = 8.dp)) { Text(text = title, color = Color.LightGray, fontSize = 12.sp) Text(text = data, color = Color.White, fontSize = 14.sp) } } @Preview(showBackground = true, name = "CharacterList") @Composable fun CharacterListPreview(){ CharacterList() } @Preview(showBackground = true, name = "CharacterItem") @Composable fun CharacterItemPreview(){ CharacterItem() } @Preview(showBackground = true, name = "ItemCommonInfo") @Composable fun ItemCommonInfoPreview(){ ItemCommonInfo() }
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/ListScreen.kt
285565585
package com.example.composeapp.ui import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.composeapp.ui.theme.ComposeAppTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { ComposeAppTheme { Scaffold(modifier = Modifier.fillMaxSize()) { paddingValues -> Log.d("paddingValues","$paddingValues") MainScreen( modifier = Modifier.padding(vertical = 8.dp) ) } } } } } @Composable fun MainScreen(modifier: Modifier = Modifier) { CharacterList(modifier = modifier) } @Preview(showBackground = true, name = "Main screen preview") @Composable fun GreetingPreview() { ComposeAppTheme { MainScreen() } }
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/MainActivity.kt
2210123164
package com.example.composeapp.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Color.kt
2642260128
package com.example.composeapp.ui.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun ComposeAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Theme.kt
2547182440
package com.example.composeapp.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Android-Compose-App/app/src/main/java/com/example/composeapp/ui/theme/Type.kt
1013678622
package com.example.composeapp import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App:Application()
Android-Compose-App/app/src/main/java/com/example/composeapp/App.kt
1920916060
package com.example.composeapp.di import com.example.composeapp.Utils import com.example.composeapp.data.repo.remote.RemoteRepository import com.example.composeapp.data.repo.remote.RemoteRepositoryImpl import com.example.composeapp.data.source.remote.ApiService import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class AppModule { @Singleton @Provides fun provideBaseUrl() = Utils.Constant.BASE_URL @Singleton @Provides fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java) @Singleton @Provides fun provideRetrofit(okHttpClient:OkHttpClient,baseUrl:String): Retrofit = Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build() @Singleton @Provides fun provideOkHttp(httpLoggingInterceptor: HttpLoggingInterceptor?): OkHttpClient { val builder = OkHttpClient.Builder() httpLoggingInterceptor?.let { interceptor -> builder.addNetworkInterceptor(interceptor) } builder.connectTimeout(15, TimeUnit.SECONDS) builder.writeTimeout(15, TimeUnit.SECONDS) builder.readTimeout(15, TimeUnit.SECONDS) builder.pingInterval(15, TimeUnit.SECONDS) builder.retryOnConnectionFailure(false) builder.followRedirects(false) return builder.build() } @Singleton @Provides fun provideHttpLoggingInterceptor() = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } @Singleton @Provides fun provideRemoteRepository(apiService: ApiService):RemoteRepository = RemoteRepositoryImpl(apiService) }
Android-Compose-App/app/src/main/java/com/example/composeapp/di/AppModule.kt
2116718711
package com.example.composeapp import androidx.compose.ui.graphics.Color object Utils { object Constant{ const val BASE_URL = "https://rickandmortyapi.com/api/" } object CommonMethods{ fun getColorByStatus(status: String?) = when(status?.lowercase()){ "Alive".lowercase() -> Color.Green "Unknown".lowercase() -> Color.LightGray else -> Color.Red } } }
Android-Compose-App/app/src/main/java/com/example/composeapp/Utils.kt
1510986040
package com.example.composeapp.data.source.remote import com.example.composeapp.data.model.Characters import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface ApiService { @GET("character/") suspend fun getCharacters(@Query("page") page:Int):Response<Characters> }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/source/remote/ApiService.kt
1902851573
package com.example.composeapp.data.model import com.google.gson.annotations.SerializedName data class Characters( @SerializedName("info") val info: Info, @SerializedName("results") val results: List<Result> ) { data class Info( @SerializedName("count") val count: Int, // 826 @SerializedName("next") val next: String, // https://rickandmortyapi.com/api/character?page=2 @SerializedName("pages") val pages: Int, // 42 @SerializedName("prev") val prev: Any? // null ) data class Result( @SerializedName("created") val created: String, // 2017-11-04T18:48:46.250Z @SerializedName("episode") val episode: List<String>, @SerializedName("gender") val gender: String, // Male @SerializedName("id") val id: Int, // 1 @SerializedName("image") val image: String, // https://rickandmortyapi.com/api/character/avatar/1.jpeg @SerializedName("location") val location: Location, @SerializedName("name") val name: String, // Rick Sanchez @SerializedName("origin") val origin: Origin, @SerializedName("species") val species: String, // Human @SerializedName("status") val status: String, // Alive @SerializedName("type") val type: String, @SerializedName("url") val url: String // https://rickandmortyapi.com/api/character/1 ) { data class Location( @SerializedName("name") val name: String, // Citadel of Ricks @SerializedName("url") val url: String // https://rickandmortyapi.com/api/location/3 ) data class Origin( @SerializedName("name") val name: String, // Earth (C-137) @SerializedName("url") val url: String // https://rickandmortyapi.com/api/location/1 ) } }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/model/Characters.kt
1948656863
package com.example.composeapp.data sealed class DataState<out T> { data object Loading : DataState<Nothing>() data class Success<T>(val data: T) : DataState<T>() data class Error(val exception: Exception) : DataState<Nothing>() }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/DataState.kt
2739538894
package com.example.composeapp.data.repo interface Repository
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/Repository.kt
2102868780
package com.example.composeapp.data.repo.remote import com.example.composeapp.data.source.remote.ApiService import javax.inject.Inject class RemoteRepositoryImpl @Inject constructor( private val apiService: ApiService ):RemoteRepository { override suspend fun getCharacterData() = apiService.getCharacters(1) }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/RemoteRepositoryImpl.kt
1754981268
package com.example.composeapp.data.repo.remote import com.example.composeapp.data.DataState import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import retrofit2.Response class NetworkRepository<T> { fun asFlow(response: Response<T>) = flow<DataState<T>> { // val response = fetchFromNetwork() val data = response.body() if(response.isSuccessful && data != null){ emit(DataState.Success(data)) }else{ emit(DataState.Error(Exception(response.errorBody()?.string()))) } }.catch { emit(DataState.Error(Exception(it))) } // protected abstract suspend fun fetchFromNetwork():Response<T> }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/NetworkRepository.kt
1384528744
package com.example.composeapp.data.repo.remote import com.example.composeapp.data.model.Characters import com.example.composeapp.data.repo.Repository import kotlinx.coroutines.flow.Flow import retrofit2.Response interface RemoteRepository:Repository { suspend fun getCharacterData(): Response<Characters> }
Android-Compose-App/app/src/main/java/com/example/composeapp/data/repo/remote/RemoteRepository.kt
3887669971
package com.pluu.glidelistenerbugsample import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.pluu.glidelistenerbugsample", appContext.packageName) } }
GlideListenerBugSample/app/src/androidTest/java/com/pluu/glidelistenerbugsample/ExampleInstrumentedTest.kt
2361412476
package com.pluu.glidelistenerbugsample import org.junit.Assert.assertEquals import org.junit.Test /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
GlideListenerBugSample/app/src/test/java/com/pluu/glidelistenerbugsample/ExampleUnitTest.kt
83043424
package com.pluu.glidelistenerbugsample import android.graphics.drawable.Drawable import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import com.pluu.glidelistenerbugsample.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val image1 = "https://plus.unsplash.com/premium_photo-1669885054268-cbd716cb8b52?q=80&w=2713&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" private val image2 = "https://images.unsplash.com/photo-1547721064-da6cfb341d50?q=80&w=2574&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" private val image3 = "https://images.unsplash.com/photo-1485470733090-0aae1788d5af?q=80&w=2717&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.btn1.setOnClickListener { loadImage(image1) } binding.btn2.setOnClickListener { loadImage(image2) } binding.btn3.setOnClickListener { loadImage(image3) } } private fun loadImage(url: String) { val listener = object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { Log.d("TAG", "[onLoadFailed] = ${hashCode()}") return false } override fun onResourceReady( resource: Drawable?, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { Log.d("TAG", "[onResourceReady] = ${hashCode()}") return false } } Log.d("TAG", "[Listener] = ${listener.hashCode()} ==> $url") Glide.with(binding.imgView) .load(url) .centerCrop() .addListener(listener) .into(binding.imgView) } }
GlideListenerBugSample/app/src/main/java/com/pluu/glidelistenerbugsample/MainActivity.kt
1139665019
package com.loptor.mysamplesdkconsumer import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class WrapperModule { @Binds abstract fun bindAnalyticsService( wrapper: DemoLibraryWrapper ): Wrapper }
SimpleSDKconsumer/app/src/demo/java/com/loptor/mysamplesdkconsumer/WrapperModule.kt
4098588847
package com.loptor.mysamplesdkconsumer import javax.inject.Inject class DemoLibraryWrapper @Inject constructor() : Wrapper { override fun getGreeting(): String = "Dummy" }
SimpleSDKconsumer/app/src/demo/java/com/loptor/mysamplesdkconsumer/DemoLibraryWrapper.kt
509402088
package com.loptor.mysamplesdkconsumer import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.loptor.mysamplesdkconsumer", appContext.packageName) } }
SimpleSDKconsumer/app/src/androidTest/java/com/loptor/mysamplesdkconsumer/ExampleInstrumentedTest.kt
930285524
package com.loptor.mysamplesdkconsumer import com.loptor.dummylib.MyDummyLib import javax.inject.Inject class FullLibraryWrapper @Inject constructor() : Wrapper { override fun getGreeting(): String = MyDummyLib.getGreeting() }
SimpleSDKconsumer/app/src/full/java/com/loptor/mysamplesdkconsumer/FullLibraryWrapper.kt
3544369758
package com.loptor.mysamplesdkconsumer import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) abstract class WrapperModule { @Binds abstract fun bindAnalyticsService( wrapper: FullLibraryWrapper ): Wrapper }
SimpleSDKconsumer/app/src/full/java/com/loptor/mysamplesdkconsumer/WrapperModule.kt
3467706985
package com.loptor.mysamplesdkconsumer import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
SimpleSDKconsumer/app/src/test/java/com/loptor/mysamplesdkconsumer/ExampleUnitTest.kt
1287523541
package com.loptor.mysamplesdkconsumer.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Color.kt
3307287195
package com.loptor.mysamplesdkconsumer.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MySampleSDKconsumerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Theme.kt
3464409917
package com.loptor.mysamplesdkconsumer.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/ui/theme/Type.kt
96039688
package com.loptor.mysamplesdkconsumer import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.loptor.mysamplesdkconsumer.ui.theme.MySampleSDKconsumerTheme import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { @Inject lateinit var libWrapper: Wrapper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MySampleSDKconsumerTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting(libWrapper.getGreeting()) } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { MySampleSDKconsumerTheme { Greeting("Android") } }
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/MainActivity.kt
2711844185
package com.loptor.mysamplesdkconsumer import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class SampleApp : Application()
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/SampleApp.kt
730901113
package com.loptor.mysamplesdkconsumer interface Wrapper { fun getGreeting(): String }
SimpleSDKconsumer/app/src/main/java/com/loptor/mysamplesdkconsumer/Wrapper.kt
1051828500
package com.loptor.dummylib object MyDummyLib { fun getGreeting() = "Library" }
SimpleSDKconsumer/dummylib/src/main/java/com/loptor/dummylib/MyDummyLib.kt
3366310012
package com.example.equipoSiete import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.clase8", appContext.packageName) } }
equipoSiete/app/src/androidTest/java/com/example/equipoSiete/ExampleInstrumentedTest.kt
2515224051
package com.example.equipoSiete.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.equipoSiete.repository.InventoryRepository import com.example.equipoSiete.repository.LoginRepository import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.* import org.mockito.MockitoAnnotations class LoginViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() //código que involucra LiveData y ViewModel private lateinit var loginViewModel: LoginViewModel private lateinit var loginRepository: LoginRepository @Before fun setUp() { loginRepository = mock(LoginRepository::class.java) loginViewModel = LoginViewModel(loginRepository) } @Test fun `test método registerUser`(){ val email="[email protected]" val password="123456" val expectedResult=true //when `when`(loginRepository.registerUser(email,password){}).thenAnswer{ val callback=it.arguments[2] as (Boolean)-> Unit callback.invoke(expectedResult) } //then loginViewModel.registerUser(email,password){ result ->assert(result) } } }
equipoSiete/app/src/test/java/com/example/equipoSiete/viewmodel/LoginViewModelTest.kt
1357985971
package com.example.equipoSiete.viewmodel import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.model.Product import com.example.equipoSiete.repository.InventoryRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` class InventoryViewModelTest { @get:Rule val rule = InstantTaskExecutorRule() //código que involucra LiveData y ViewModel private lateinit var inventoryViewModel: InventoryViewModel private lateinit var inventoryRepository: InventoryRepository @Before fun setUp() { inventoryRepository = mock(InventoryRepository::class.java) inventoryViewModel = InventoryViewModel(inventoryRepository) } @Test fun `test método totalProducto`(){ //given (qué necesitamos:condiciones previas necesarias para que la prueba se ejecute correctamente) val price = 10000 val quantity = 5 val expectedResult = (price * quantity).toDouble() //when (Aquí, ejecutas el código o la función que estás evaluando.) val resul = inventoryViewModel.totalProducto(price, quantity) //Then (lo que tiene que pasar:resultados esperados ) assertEquals(expectedResult, resul,0.0) } @Test fun `test método getListInventory`() = runBlocking { //given // es responsable de ejecutar tareas en el hilo principal, necesitamos simular ese proceso Dispatchers.setMain(UnconfinedTestDispatcher()) // Configurar el comportamiento del repositorio simulado val mockInventory = mutableListOf( Inventory(7, "zapatos", 60000,4) ) `when`(inventoryRepository.getListInventory()).thenReturn(mockInventory) // Llamar a la función que queremos probar //when inventoryViewModel.getListInventory() // Asegurarse de que la LiveData de productos se haya actualizado correctamente //then assertEquals(inventoryViewModel.listInventory.value, mockInventory) // son utilizados para controlar y simular la ejecución de coroutines en el hilo principal durante las pruebas unitarias Dispatchers.resetMain() } @Test fun testSaveInventory_success() = runBlocking { //given Dispatchers.setMain(UnconfinedTestDispatcher()) val inventory= Inventory(codigo = 1, nombre = "Item1", precio = 10, cantidad = 5) `when`(inventoryRepository.saveInventory(inventory)) .thenAnswer { invocation -> val inventoryArgument = invocation.getArgument<Inventory>(0)//inventoryArgument contendrá el valor del primer argumento que se pasó al método inventoryArgument } // Llamamos al método que queremos probar inventoryViewModel.saveInventory(inventory) // Verificamos que el estado de progreso sea falso después de la operación verify(inventoryRepository).saveInventory(inventory) Dispatchers.resetMain() } }
equipoSiete/app/src/test/java/com/example/equipoSiete/viewmodel/InventoryViewModelTest.kt
2350807425
package com.example.equipoSiete.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.model.Product import com.example.equipoSiete.repository.InventoryRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class InventoryViewModel @Inject constructor( private val inventoryRepository: InventoryRepository ) : ViewModel() { private val _listInventory = MutableLiveData<MutableList<Inventory>>() val listInventory: LiveData<MutableList<Inventory>> get() = _listInventory private val _progresState = MutableLiveData(false) val progresState: LiveData<Boolean> = _progresState //para almacenar una lista de productos private val _listProducts = MutableLiveData<MutableList<Product>>() val listProducts: LiveData<MutableList<Product>> = _listProducts fun saveInventory(inventory: Inventory) { viewModelScope.launch { _progresState.value = true try { inventoryRepository.saveInventory(inventory) _progresState.value = false } catch (e: Exception) { _progresState.value = false } } } fun getListInventory() { viewModelScope.launch { _progresState.value = true try { _listInventory.value = inventoryRepository.getListInventory() _progresState.value = false } catch (e: Exception) { _progresState.value = false } } } fun deleteInventory(inventory: Inventory) { viewModelScope.launch { _progresState.value = true try { inventoryRepository.deleteInventory(inventory) _progresState.value = false } catch (e: Exception) { _progresState.value = false } } } fun updateInventory(inventory: Inventory) { viewModelScope.launch { _progresState.value = true try { inventoryRepository.updateRepositoy(inventory) _progresState.value = false } catch (e: Exception) { _progresState.value = false } } } fun totalProducto(price: Int, quantity: Int): Double { val total = price * quantity return total.toDouble() } }
equipoSiete/app/src/main/java/com/example/equipoSiete/viewmodel/InventoryViewModel.kt
432393705
package com.example.equipoSiete.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.equipoSiete.repository.InventoryRepository import com.example.equipoSiete.repository.LoginRepository import com.google.firebase.auth.FirebaseAuth import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val loginRepository: LoginRepository ) : ViewModel() { //private val repository = LoginRepository() //registerUser se comunica con el repository fun registerUser(email: String, pass: String, isRegister: (Boolean) -> Unit) { loginRepository.registerUser(email, pass) { response -> isRegister(response) } } fun loginUser(email: String, pass: String, isLogin: (Boolean) -> Unit) { if (email.isNotEmpty() && pass.isNotEmpty()) { FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, pass) .addOnCompleteListener { if (it.isSuccessful) { isLogin(true) } else { isLogin(false) } } } else { isLogin(false) } } fun sesion(email: String?, isEnableView: (Boolean) -> Unit) { if (email != null) { isEnableView(true) } else { isEnableView(false) } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/viewmodel/LoginViewModel.kt
1582342159
package com.example.equipoSiete.repository import android.widget.Toast import com.example.equipoSiete.data.InventoryDao import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.model.Product import com.example.equipoSiete.webservice.ApiService import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withContext import javax.inject.Inject class InventoryRepository @Inject constructor( private val inventoryDao: InventoryDao, private val apiService: ApiService, private val db: FirebaseFirestore, ){ suspend fun saveInventory(inventory:Inventory) { withContext(Dispatchers.IO) { try { db.collection("articulo").document(inventory.codigo.toString()).set( hashMapOf( "codigo" to inventory.codigo, "nombre" to inventory.nombre, "precio" to inventory.precio, "cantidad" to inventory.cantidad ) ).await() } catch (e: Exception) { e.printStackTrace() } } } suspend fun getListInventory():MutableList<Inventory>{ return withContext(Dispatchers.IO){ try { val snapshot = db.collection("articulo").get().await() val inventoryList = mutableListOf<Inventory>() for (document in snapshot.documents) { val codigo = document.getLong("codigo")?.toInt() ?: 0 val nombre = document.getString("nombre") ?: "" val precio = document.getLong("precio")?.toInt() ?: 0 val cantidad = document.getLong("cantidad")?.toInt() ?: 0 val item = Inventory(codigo, nombre, precio, cantidad) inventoryList.add(item) } inventoryList } catch (e: Exception) { e.printStackTrace() mutableListOf() } } } suspend fun deleteInventory(inventory: Inventory) { withContext(Dispatchers.IO) { try { // Aquí asumo que 'codigo' es un identificador único para Inventory val codigo = inventory.codigo // Obtener una referencia al documento que queremos eliminar val documentReference = db.collection("articulo").document(codigo.toString()) // Eliminar el documento documentReference.delete().await() } catch (e: Exception) { e.printStackTrace() // Manejar la excepción según tus necesidades } } } suspend fun updateRepositoy(inventory: Inventory){ withContext(Dispatchers.IO) { try { db.collection("articulo").document(inventory.codigo.toString()).update( mapOf( "nombre" to inventory.nombre, "precio" to inventory.precio, "cantidad" to inventory.cantidad ) ).await() } catch (e: Exception) { e.printStackTrace() } } } suspend fun getProducts(): MutableList<Product> { return withContext(Dispatchers.IO) { try { val response = apiService.getProducts() response } catch (e: Exception) { e.printStackTrace() mutableListOf() } } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/repository/InventoryRepository.kt
1886130425
package com.example.equipoSiete.repository import com.example.equipoSiete.data.InventoryDao import com.example.equipoSiete.webservice.ApiService import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import javax.inject.Inject class LoginRepository @Inject constructor( ){ private val firebaseAuth = FirebaseAuth.getInstance() fun registerUser(email: String, pass:String, isRegisterComplete: (Boolean)->Unit){ if(email.isNotEmpty() && pass.isNotEmpty()){ firebaseAuth.createUserWithEmailAndPassword(email,pass) .addOnCompleteListener { if (it.isSuccessful) { isRegisterComplete(true) } else { isRegisterComplete(false) } } }else{ isRegisterComplete(false) } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/repository/LoginRepository.kt
2600205870
package com.example.equipoSiete import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class AppExample:Application()
equipoSiete/app/src/main/java/com/example/equipoSiete/AppExample.kt
1345241535
package com.example.equipoSiete.di import android.content.Context import com.example.equipoSiete.data.InventoryDB import com.example.equipoSiete.data.InventoryDao import com.example.equipoSiete.utils.Constants.BASE_URL import com.example.equipoSiete.webservice.ApiService import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object Module { @Singleton @Provides fun provideInventoryDB(@ApplicationContext context: Context):InventoryDB{ return InventoryDB.getDatabase(context) } @Singleton @Provides fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } @Singleton @Provides fun provideApiService(retrofit: Retrofit): ApiService { return retrofit.create(ApiService::class.java) } @Singleton @Provides fun provideDaoReto(inventoryDB:InventoryDB): InventoryDao { return inventoryDB.inventoryDao() } @Singleton @Provides fun provideFirestoreDB(): FirebaseFirestore { return FirebaseFirestore.getInstance() } @Singleton @Provides fun provideAuthDB(): FirebaseAuth { return FirebaseAuth.getInstance() } }
equipoSiete/app/src/main/java/com/example/equipoSiete/di/Module.kt
779881955
package com.example.equipoSiete.widget import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.icu.text.NumberFormat import android.util.Log import android.widget.RemoteViews import com.example.equipoSiete.R import com.example.equipoSiete.view.LoginActivity import com.example.equipoSiete.viewmodel.InventoryViewModel import com.google.firebase.auth.FirebaseAuth import androidx.activity.viewModels import androidx.lifecycle.ViewModelProvider import com.example.equipoSiete.view.MainActivity import com.example.equipoSiete.view.fragment.HomeInventoryFragment import com.google.firebase.firestore.FirebaseFirestore import java.util.Locale /** * Implementation of App Widget functionality. */ class widget() : AppWidgetProvider() { companion object { var saldoVisible: Boolean = false var total = 0L } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // There may be multiple widgets active, so update all of them for (appWidgetId in appWidgetIds) { updateAppWidget(context, appWidgetManager, appWidgetId) } } override fun onEnabled(context: Context) { // Enter relevant functionality for when the first widget is created } override fun onDisabled(context: Context) { // Enter relevant functionality for when the last widget is disabled } override fun onReceive(context: Context?, intent: Intent?) { super.onReceive(context, intent) when (intent!!.action?: "") { "ICON_CLICKED_ACTION" -> { println(isUserLoggedIn()) if (isUserLoggedIn()) { updateSaldoWidget(context!!) } else { val loginIntent = Intent(context, LoginActivity::class.java) context?.sendBroadcast(loginIntent) loginIntent.putExtra("fromWidget", true) loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context?.startActivity(loginIntent) } } "LOGIN_SUCCESSFUL" -> { updateTextWidget(context!!) } "LOGOFF_SUCCESSFUL" -> { userLogoff(context!!) } "CONFIG_CLICKED_ACTION" -> { println(isUserLoggedIn()) if (isUserLoggedIn()) { val homeIntent = Intent(context, MainActivity::class.java) homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context?.startActivity(homeIntent) } else { val loginIntent = Intent(context, LoginActivity::class.java) loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context?.startActivity(loginIntent) } } "TEXT_GESTIONAR_CLICKED_ACTION" ->{ if (isUserLoggedIn()) { val homeIntent = Intent(context, MainActivity::class.java) homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context?.startActivity(homeIntent) } else { val loginIntent = Intent(context, LoginActivity::class.java) loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context?.startActivity(loginIntent) } } "UPDATE_TOTAL" ->{ updateTextWidget(context!!) } } } private fun updateTextWidget(context: Context) { totalInventario { newTotal -> val valor = formatearPrecio(newTotal.toDouble()) val appWidgetManager = AppWidgetManager.getInstance(context) val thisAppWidget = ComponentName(context.packageName, javaClass.name) val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget) val views = RemoteViews(context.packageName, R.layout.widget) views.setImageViewResource(R.id.iconImageView, R.drawable.visibilidad_off) views.setTextViewText(R.id.text_saldo, "$ $valor") saldoVisible = true appWidgetManager.updateAppWidget(appWidgetIds, views) } } private fun isUserLoggedIn(): Boolean { // Verificar si el usuario está autenticado en Firebase val firebaseAuth = FirebaseAuth.getInstance() return firebaseAuth.currentUser != null } private fun updateSaldoWidget(context: Context) { totalInventario { newTotal -> val valor = formatearPrecio(newTotal.toDouble()) val appWidgetManager = AppWidgetManager.getInstance(context) val thisAppWidget = ComponentName(context.packageName, javaClass.name) val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget) val views = RemoteViews(context.packageName, R.layout.widget) if (saldoVisible) { views.setImageViewResource(R.id.iconImageView, R.drawable.visibility_image) views.setTextViewText(R.id.text_saldo, "$ * * * *") saldoVisible = false } else { views.setImageViewResource(R.id.iconImageView, R.drawable.visibilidad_off) views.setTextViewText(R.id.text_saldo, "$ $valor") saldoVisible = true } // Actualizar todos los widgets appWidgetManager.updateAppWidget(appWidgetIds, views) } } private fun formatearPrecio(precio: Double): String { val numberFormat = NumberFormat.getNumberInstance(Locale("es", "ES")) numberFormat.minimumFractionDigits = 2 numberFormat.maximumFractionDigits = 2 return numberFormat.format(precio) } private fun userLogoff(context: Context) { val appWidgetManager = AppWidgetManager.getInstance(context) val thisAppWidget = ComponentName(context.packageName, javaClass.name) val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget) val views = RemoteViews(context.packageName, R.layout.widget) views.setImageViewResource(R.id.iconImageView, R.drawable.visibility_image) views.setTextViewText(R.id.text_saldo, "$ * * * *") appWidgetManager.updateAppWidget(appWidgetIds, views) } private fun totalInventario(callback: (Long) -> Unit) { var total: Long = 0 val db = FirebaseFirestore.getInstance() db.collection("articulo") .get() .addOnSuccessListener { querySnapshot -> for (document in querySnapshot) { val price = document.get("precio") as Long val quantity = document.get("cantidad") as Long println("Cantidad: ${quantity.toInt()}") println("Precio: ${price.toInt()}") total += price * quantity } callback(total) } .addOnFailureListener { exception -> println("Error al obtener datos: $exception") // Manejar el error según sea necesario } } private fun pendingIntent( context: Context?, action:String ): PendingIntent? { val intent = Intent(context, javaClass) intent.action = action return PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE ) } internal fun updateAppWidget( context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int ) { val widgetText = context.getString(R.string.appwidget_text) // Construct the RemoteViews object val views = RemoteViews(context.packageName, R.layout.widget) views.setOnClickPendingIntent(R.id.iconImageView, pendingIntent(context, "ICON_CLICKED_ACTION")) views.setOnClickPendingIntent(R.id.config_image, pendingIntent(context, "CONFIG_CLICKED_ACTION")) views.setOnClickPendingIntent(R.id.text_gestionarinventario, pendingIntent(context, "TEXT_GESTIONAR_CLICKED_ACTION")) //views.setTextViewText(R.id.appwidget_text, widgetText) // Instruct the widget manager to update the widget appWidgetManager.updateAppWidget(appWidgetId, views) } }
equipoSiete/app/src/main/java/com/example/equipoSiete/widget/widget.kt
2407598115
package com.example.equipoSiete.utils object Constants { const val NAME_BD: String ="app_data.db" const val BASE_URL="https://fakestoreapi.com/" const val END_POINT="products" }
equipoSiete/app/src/main/java/com/example/equipoSiete/utils/Constants.kt
4178214937
package com.example.equipoSiete.webservice import com.example.equipoSiete.utils.Constants.BASE_URL import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitClient { fun getRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } }
equipoSiete/app/src/main/java/com/example/equipoSiete/webservice/RetrofitClient.kt
2049354619
package com.example.equipoSiete.webservice class ApiUtils { companion object{ fun getApiService():ApiService{ return RetrofitClient.getRetrofit().create(ApiService::class.java) } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/webservice/ApiUtils.kt
3394864669
package com.example.equipoSiete.webservice import com.example.equipoSiete.model.Product import com.example.equipoSiete.utils.Constants.END_POINT import retrofit2.http.GET interface ApiService { @GET(END_POINT) suspend fun getProducts(): MutableList<Product> }
equipoSiete/app/src/main/java/com/example/equipoSiete/webservice/ApiService.kt
511427753
package com.example.equipoSiete.model import com.google.gson.annotations.SerializedName data class Product( @SerializedName("id") val id:Int, @SerializedName("title") val title: String, @SerializedName("image") val image:String )
equipoSiete/app/src/main/java/com/example/equipoSiete/model/Product.kt
2931444878
package com.example.equipoSiete.model import androidx.room.Entity import androidx.room.PrimaryKey import java.io.Serializable @Entity data class Inventory( @PrimaryKey(autoGenerate = true) val codigo: Int = 0, val nombre: String, val precio: Int, val cantidad: Int): Serializable
equipoSiete/app/src/main/java/com/example/equipoSiete/model/Inventory.kt
1878339735
package com.example.equipoSiete.view import android.os.Bundle import android.view.Window import androidx.appcompat.app.AppCompatActivity import com.example.equipoSiete.R import dagger.hilt.android.AndroidEntryPoint import com.example.equipoSiete.view.fragment.HomeInventoryFragment @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/MainActivity.kt
4287011404
package com.example.equipoSiete.view.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.navigation.NavController import androidx.recyclerview.widget.RecyclerView import com.example.equipoSiete.databinding.ItemInventoryBinding import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.view.viewholder.InventoryViewHolder class InventoryAdapter(private val listInventory:MutableList<Inventory>, private val navController: NavController):RecyclerView.Adapter<InventoryViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InventoryViewHolder { val binding = ItemInventoryBinding.inflate(LayoutInflater.from(parent.context),parent, false) return InventoryViewHolder(binding, navController) } override fun getItemCount(): Int { return listInventory.size } override fun onBindViewHolder(holder: InventoryViewHolder, position: Int) { val inventory = listInventory[position] holder.setItemInventory(inventory) } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/adapter/InventoryAdapter.kt
2158647563
package com.example.equipoSiete.view.fragment import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.widget.addTextChangedListener import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.bumptech.glide.Glide import com.example.equipoSiete.R import com.example.equipoSiete.databinding.FragmentAddItemBinding import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.view.LoginActivity import com.example.equipoSiete.view.MainActivity import com.example.equipoSiete.viewmodel.InventoryViewModel import com.example.equipoSiete.widget.widget import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class AddItemFragment : Fragment() { private lateinit var binding: FragmentAddItemBinding private val inventoryViewModel: InventoryViewModel by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentAddItemBinding.inflate(inflater) binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupButton() goHome() } private fun saveInvetory(){ val codigo = binding.addTextProductCode.text.toString().toInt() val nombre = binding.addArticleName.text.toString() val precio = binding.addPrice.text.toString().toInt() val cantidad = binding.addQuantity.text.toString().toInt() val inventory = Inventory(codigo = codigo, nombre = nombre, precio = precio, cantidad = cantidad) inventoryViewModel.saveInventory(inventory) Log.d("test",inventory.toString()) Toast.makeText(context,"Artículo guardado", Toast.LENGTH_SHORT).show() limpiarCampos() (requireActivity() as MainActivity).apply { val widgetIntent = Intent(this, widget::class.java) widgetIntent.action = "UPDATE_TOTAL" sendBroadcast(widgetIntent) } } private fun goHome(){ binding.backArrowAdd.setOnClickListener{ findNavController().navigate(R.id.action_addItemFragment_to_homeInventoryFragment) } } private fun setupButton() { // Configura el botón (Criterio 6 y 7) binding.saveButton.setOnClickListener { if (camposEstanLlenos()) { // Lógica para guardar en Firestore y mostrar en la lista de productos (Criterio 8) saveInvetory() } } // Observador de cambios en los campos para habilitar/deshabilitar el botón binding.addTextProductCode.addTextChangedListener(textWatcher) binding.addArticleName.addTextChangedListener(textWatcher) binding.addPrice.addTextChangedListener(textWatcher) binding.addQuantity.addTextChangedListener(textWatcher) } private val textWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { // Verificar si todos los campos están llenos y habilitar/deshabilitar el botón (Criterios 6 y 7) binding.saveButton.isEnabled = camposEstanLlenos() // Cambiar el color y estilo del texto del botón si está habilitado (Criterio 7) binding.saveButton.setTextColor(if (binding.saveButton.isEnabled) resources.getColor(android.R.color.white) else resources.getColor(android.R.color.black)) binding.saveButton.setTypeface(null, if (binding.saveButton.isEnabled) Typeface.BOLD else Typeface.NORMAL) } } private fun camposEstanLlenos(): Boolean { val codigo = binding.addTextProductCode.text.toString() val nombre = binding.addArticleName.text.toString() val precio = binding.addPrice.text.toString() val cantidad = binding.addQuantity.text.toString() return codigo.isNotEmpty() && nombre.isNotEmpty() && precio.isNotEmpty() && cantidad.isNotEmpty() } private fun limpiarCampos() { binding.addArticleName.setText("") binding.addTextProductCode.setText("") binding.addPrice.setText("") binding.addQuantity.setText("") } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/fragment/AddItemFragment.kt
2454348108
package com.example.equipoSiete.view.fragment import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.equipoSiete.R import com.example.equipoSiete.databinding.FragmentItemDetailsBinding import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.view.LoginActivity import com.example.equipoSiete.view.MainActivity import com.example.equipoSiete.viewmodel.InventoryViewModel import com.example.equipoSiete.widget.widget import com.google.firebase.auth.FirebaseAuth import dagger.hilt.android.AndroidEntryPoint import java.text.NumberFormat import java.util.Locale @AndroidEntryPoint class ItemDetailsFragment : Fragment() { private lateinit var binding: FragmentItemDetailsBinding private val inventoryViewModel: InventoryViewModel by viewModels() private lateinit var receivedInventory: Inventory override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentItemDetailsBinding.inflate(inflater) binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dataInventory() controladores() goHome() } private fun controladores() { binding.btnDelete.setOnClickListener { deleteInventory() } binding.fbEdit.setOnClickListener { val bundle = Bundle() bundle.putSerializable("dataInventory", receivedInventory) findNavController().navigate(R.id.action_itemDetailsFragment_to_itemEditFragment, bundle) } } private fun dataInventory() { val receivedBundle = arguments receivedInventory = receivedBundle?.getSerializable("clave") as Inventory val formattedPrice = convertToFormattedCurrency(receivedInventory.precio.toDouble()) binding.tvItem.text = "${receivedInventory.nombre}" binding.tvPrice.text = "$ ${formattedPrice}" binding.tvQuantity.text = "${receivedInventory.cantidad}" binding.txtTotal.text = "$ ${ convertToFormattedCurrency(inventoryViewModel.totalProducto( receivedInventory.precio, receivedInventory.cantidad ).toDouble()) }" } private fun convertToFormattedCurrency(amount: Double): String { val currencyFormatter = NumberFormat.getNumberInstance(Locale("es", "ES")) currencyFormatter.minimumFractionDigits = 2 currencyFormatter.maximumFractionDigits = 2 return currencyFormatter.format(amount) } private fun deleteInventory(){ inventoryViewModel.deleteInventory(receivedInventory) inventoryViewModel.getListInventory() (requireActivity() as MainActivity).apply { val widgetIntent = Intent(this, widget::class.java) widgetIntent.action = "UPDATE_TOTAL" sendBroadcast(widgetIntent) } findNavController().popBackStack() } private fun goHome(){ binding.backArrow.setOnClickListener { findNavController().navigateUp() } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/fragment/ItemDetailsFragment.kt
806447631
package com.example.equipoSiete.view.fragment import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.example.equipoSiete.R import com.example.equipoSiete.databinding.FragmentItemEditBinding import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.view.MainActivity import com.example.equipoSiete.viewmodel.InventoryViewModel import com.example.equipoSiete.widget.widget import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class ItemEditFragment : Fragment() { private lateinit var binding: FragmentItemEditBinding private val inventoryViewModel: InventoryViewModel by viewModels() private lateinit var receivedInventory: Inventory override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentItemEditBinding.inflate(inflater) binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) dataInventory() setupButton() goHome() } private fun setupButton() { // Configura el botón (Criterio 6 y 7) binding.editButton.setOnClickListener { if (camposEstanLlenos()) { // Lógica para guardar en Firestore y mostrar en la lista de productos (Criterio 8) updateInventory() } } // Observador de cambios en los campos para habilitar/deshabilitar el botón binding.editArticleName.addTextChangedListener(textWatcher) binding.editPrice.addTextChangedListener(textWatcher) binding.editQuantity.addTextChangedListener(textWatcher) } private val textWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { // Verificar si todos los campos están llenos y habilitar/deshabilitar el botón (Criterios 6 y 7) binding.editButton.isEnabled = camposEstanLlenos() // Cambiar el color y estilo del texto del botón si está habilitado (Criterio 7) binding.editButton.setTextColor(if (binding.editButton.isEnabled) resources.getColor(android.R.color.white) else resources.getColor(android.R.color.black)) binding.editButton.setTypeface(null, if (binding.editButton.isEnabled) Typeface.BOLD else Typeface.NORMAL) } } private fun camposEstanLlenos(): Boolean { val nombre = binding.editArticleName.text.toString() val precio = binding.editPrice.text.toString() val cantidad = binding.editQuantity.text.toString() return nombre.isNotEmpty() && precio.isNotEmpty() && cantidad.isNotEmpty() } private fun dataInventory(){ val receivedBundle = arguments receivedInventory = receivedBundle?.getSerializable("dataInventory") as Inventory binding.textProductCode.setText("Id: "+receivedInventory.codigo) binding.editArticleName.setText(receivedInventory.nombre) binding.editPrice.setText(receivedInventory.precio.toString()) binding.editQuantity.setText(receivedInventory.cantidad.toString()) } private fun updateInventory(){ val name = binding.editArticleName.text.toString() val price = binding.editPrice.text.toString().toInt() val quantity = binding.editQuantity.text.toString().toInt() val inventory = Inventory(receivedInventory.codigo, name,price,quantity) inventoryViewModel.updateInventory(inventory) Toast.makeText(context,"Artículo editado con exito", Toast.LENGTH_SHORT).show() (requireActivity() as MainActivity).apply { val widgetIntent = Intent(this, widget::class.java) widgetIntent.action = "UPDATE_TOTAL" sendBroadcast(widgetIntent) } val bundle = Bundle() bundle.putSerializable("clave", inventory) //findNavController().navigate(R.id.action_itemEditFragment_to_itemDetailsFragment,bundle) } private fun goHome(){ binding.backArrowEdit.setOnClickListener{ findNavController().navigateUp() } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/fragment/ItemEditFragment.kt
2733169967
package com.example.equipoSiete.view.fragment import android.content.Context 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 androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.equipoSiete.R import com.example.equipoSiete.databinding.FragmentHomeInventoryBinding import com.example.equipoSiete.view.LoginActivity import com.example.equipoSiete.view.MainActivity import com.google.firebase.firestore.FirebaseFirestore import com.example.equipoSiete.view.adapter.InventoryAdapter import com.example.equipoSiete.viewmodel.InventoryViewModel import com.example.equipoSiete.widget.widget import com.google.firebase.auth.FirebaseAuth import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HomeInventoryFragment : Fragment() { private lateinit var sharedPreferences: SharedPreferences private lateinit var binding: FragmentHomeInventoryBinding private val inventoryViewModel: InventoryViewModel by viewModels() private val db = FirebaseFirestore.getInstance() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentHomeInventoryBinding.inflate(inflater) binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) sharedPreferences = requireActivity().getSharedPreferences("shared", Context.MODE_PRIVATE) dataLogin() controladores() observadorViewModel() setup() } private fun controladores() { binding.btnAdd.setOnClickListener { findNavController().navigate(R.id.action_homeInventoryFragment_to_addItemFragment) } } private fun observadorViewModel(){ observerListInventory() observerProgress() } private fun observerListInventory(){ inventoryViewModel.getListInventory() inventoryViewModel.listInventory.observe(viewLifecycleOwner){ listInventory -> val recycler = binding.recyclerview val layoutManager =LinearLayoutManager(context) recycler.layoutManager = layoutManager val adapter = InventoryAdapter(listInventory, findNavController()) recycler.adapter = adapter adapter.notifyDataSetChanged() } } private fun observerProgress(){ inventoryViewModel.progresState.observe(viewLifecycleOwner){status -> binding.progress.isVisible = status } } private fun dataLogin() { val bundle = requireActivity().intent.extras val email = bundle?.getString("email") sharedPreferences.edit().putString("email",email).apply() } private fun setup() { binding.toolbarinclude.btnLogOut.setOnClickListener { logOut() } } private fun logOut() { sharedPreferences.edit().clear().apply() FirebaseAuth.getInstance().signOut() (requireActivity() as MainActivity).apply { val widgetIntent = Intent(this, widget::class.java) widgetIntent.action = "LOGOFF_SUCCESSFUL" sendBroadcast(widgetIntent) (requireActivity() as MainActivity).apply { startActivity(Intent(this, LoginActivity::class.java)) finish() } } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/fragment/HomeInventoryFragment.kt
2207877029
package com.example.equipoSiete.view import android.content.Context import android.content.Intent import android.content.SharedPreferences import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.Toast import androidx.activity.viewModels import androidx.databinding.DataBindingUtil import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout import androidx.fragment.app.viewModels import com.example.equipoSiete.R import com.example.equipoSiete.databinding.ActivityLoginBinding import com.example.equipoSiete.viewmodel.LoginViewModel import com.example.equipoSiete.widget.widget import com.google.android.material.textview.MaterialTextView import com.google.firebase.auth.FirebaseAuth import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class LoginActivity : AppCompatActivity() { private lateinit var binding: ActivityLoginBinding private val loginViewModel: LoginViewModel by viewModels() private lateinit var sharedPreferences: SharedPreferences private lateinit var passwordEditText: TextInputEditText private lateinit var passwordContainer: TextInputLayout private lateinit var emailEditText: TextInputEditText private lateinit var loginButton: MaterialButton private lateinit var registerButton: MaterialTextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) binding = DataBindingUtil.setContentView(this,R.layout.activity_login) sharedPreferences = getSharedPreferences("shared", Context.MODE_PRIVATE) checkSession() sesion() setup() passwordContainer = findViewById(R.id.passwordContainer) passwordEditText = findViewById(R.id.passwordEditText) emailEditText = findViewById(R.id.emailEditText) loginButton = findViewById(R.id.btnLogin) registerButton= findViewById(R.id.tvRegister) // Inicialmente deshabilitar el botón de inicio de sesión loginButton.isEnabled = false registerButton.isEnabled= false // Agregar TextWatcher para validar la contraseña en tiempo real passwordEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) { // No se necesita en este caso } override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { validatePassword(charSequence.toString()) updateLoginButtonState() } override fun afterTextChanged(editable: Editable?) { // No se necesita en este caso } }) // Agregar TextWatcher para validar el correo electrónico en tiempo real emailEditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) { // No se necesita en este caso } override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) { updateLoginButtonState() } override fun afterTextChanged(editable: Editable?) { // No se necesita en este caso } }) } private fun redirectToHomeScreen() { val homeIntent = Intent(this, MainActivity::class.java) homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) startActivity(homeIntent) // Redirigir al usuario a la pantalla de inicio del teléfono val homeScreenIntent = Intent(Intent.ACTION_MAIN) homeScreenIntent.addCategory(Intent.CATEGORY_HOME) homeScreenIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(homeScreenIntent) // Finalizar la actividad de inicio de sesión finishAffinity() } private fun validatePassword(password: String) { if (password.length in 1..5) { passwordContainer.error = "Mínimo 6 dígitos" passwordContainer.boxStrokeColor = getColor(R.color.error_color) } else { passwordContainer.error = null passwordContainer.boxStrokeColor = getColor(R.color.white) } } private fun updateLoginButtonState() { val emailFilled = emailEditText.text?.isNotEmpty() val passwordFilled = passwordEditText.text!!.length >=6 loginButton.isEnabled = emailFilled == true && passwordFilled registerButton.isEnabled = emailFilled == true && passwordFilled if (registerButton.isEnabled) { registerButton.setTextColor(getColor(R.color.white)) registerButton.setTypeface(null, android.graphics.Typeface.BOLD) } if (loginButton.isEnabled) { loginButton.setTextColor(getColor(R.color.white)) loginButton.setTypeface(null, android.graphics.Typeface.BOLD) } } private fun setup() { binding.tvRegister.setOnClickListener { registerUser() } binding.btnLogin.setOnClickListener { loginUser() } } private fun registerUser(){ val email = binding.emailEditText.text.toString() val pass = binding.passwordEditText.text.toString() loginViewModel.registerUser(email,pass) { isRegister -> if (isRegister) { goToHome() } else { Toast.makeText(this, "Error en el registro", Toast.LENGTH_SHORT).show() } } } private fun goToHome(){ val email = binding.emailEditText.text.toString() val intent = Intent (this, MainActivity::class.java).apply { putExtra("email",email) } startActivity(intent) finish() } private fun loginUser(){ val email = binding.emailEditText.text.toString() val pass = binding.passwordEditText.text.toString() val fromWidget = intent.getBooleanExtra("fromWidget", false) loginViewModel.loginUser(email,pass){ isLogin -> if (isLogin){ // Actualiza el TextView en el widget val widgetIntent = Intent(this, widget::class.java) widgetIntent.action = "LOGIN_SUCCESSFUL" sendBroadcast(widgetIntent) if (fromWidget){ redirectToHomeScreen() }else{ saveSession(email) goToHome() } }else { Toast.makeText(this, "Login incorrecto", Toast.LENGTH_SHORT).show() } } } private fun sesion(){ val email = sharedPreferences.getString("email",null) loginViewModel.sesion(email){ isEnableView -> if (isEnableView){ binding.clContenedor.visibility = View.INVISIBLE goToHome() } } } private fun saveSession(email: String) { val editor = sharedPreferences.edit() editor.putString("email", email) editor.putBoolean("isLoggedIn", true) editor.apply() } private fun checkSession() { //val isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false) val firebaseAuth = FirebaseAuth.getInstance() val isLoggedIn = firebaseAuth.currentUser if ( isLoggedIn != null) { // El usuario ya ha iniciado sesión, navega a la actividad principal u otra actividad necesaria. goToHome() } else { // El usuario no ha iniciado sesión, muestra la interfaz de inicio de sesión. } } private fun createTextWatcher(): TextWatcher { return object : TextWatcher { override fun beforeTextChanged(charSequence: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(charSequence: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(editable: Editable?) { // Verificar si ambos campos están vacíos para desactivar el botón val emailText = emailEditText.text.toString() val passwordText = passwordEditText.text.toString() binding.btnLogin.isEnabled = emailText.isNotEmpty() && passwordText.isNotEmpty() binding.tvRegister.isEnabled = emailText.isNotEmpty() && passwordText.isNotEmpty() } } } override fun onStart() { super.onStart() binding.clContenedor.visibility = View.VISIBLE } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/LoginActivity.kt
2894250865
package com.example.equipoSiete.view.viewholder import android.os.Bundle import androidx.navigation.NavController import androidx.recyclerview.widget.RecyclerView import com.example.equipoSiete.R import com.example.equipoSiete.databinding.ItemInventoryBinding import com.example.equipoSiete.model.Inventory import java.text.NumberFormat import java.util.Locale class InventoryViewHolder(binding: ItemInventoryBinding, navController: NavController) : RecyclerView.ViewHolder(binding.root) { val bindingItem = binding val navController = navController fun setItemInventory(inventory: Inventory) { val formattedPrice = convertToFormattedCurrency(inventory.precio.toDouble()) bindingItem.articleName.text = inventory.nombre bindingItem.articlePrice.text = "$${formattedPrice}" bindingItem.articleId.text = "${inventory.codigo}" bindingItem.cvInventory.setOnClickListener { val bundle = Bundle() bundle.putSerializable("clave", inventory) navController.navigate(R.id.action_homeInventoryFragment_to_itemDetailsFragment, bundle) } } private fun convertToFormattedCurrency(amount: Double): String { val currencyFormatter = NumberFormat.getNumberInstance(Locale("es", "ES")) currencyFormatter.minimumFractionDigits = 2 currencyFormatter.maximumFractionDigits = 2 return currencyFormatter.format(amount) } }
equipoSiete/app/src/main/java/com/example/equipoSiete/view/viewholder/InventoryViewHolder.kt
3723809761
package com.example.equipoSiete.data import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.example.equipoSiete.model.Inventory @Dao interface InventoryDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun saveInventory(inventory: Inventory) @Query("SELECT * FROM Inventory") suspend fun getListInventory(): MutableList<Inventory> @Delete suspend fun deleteInventory(inventory: Inventory) @Update suspend fun updateInventory(inventory: Inventory) }
equipoSiete/app/src/main/java/com/example/equipoSiete/data/InventoryDao.kt
3794534272
package com.example.equipoSiete.data import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.equipoSiete.model.Inventory import com.example.equipoSiete.utils.Constants.NAME_BD @Database(entities = [Inventory::class], version = 1) abstract class InventoryDB : RoomDatabase() { abstract fun inventoryDao(): InventoryDao companion object{ fun getDatabase(context: Context): InventoryDB { return Room.databaseBuilder( context.applicationContext, InventoryDB::class.java, NAME_BD ).build() } } }
equipoSiete/app/src/main/java/com/example/equipoSiete/data/InventoryDB.kt
845835241
package com.example.sleeptimer import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.sleeptimer", appContext.packageName) } }
AndroidSleepTimer/app/src/androidTest/java/com/example/sleeptimer/ExampleInstrumentedTest.kt
3642424952
package com.example.sleeptimer import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
AndroidSleepTimer/app/src/test/java/com/example/sleeptimer/ExampleUnitTest.kt
3954448891
package com.example.sleeptimer.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
AndroidSleepTimer/app/src/main/java/com/example/sleeptimer/ui/theme/Color.kt
3937104781
package com.example.sleeptimer.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun SleepTimerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidSleepTimer/app/src/main/java/com/example/sleeptimer/ui/theme/Theme.kt
3094769808
package com.example.sleeptimer.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
AndroidSleepTimer/app/src/main/java/com/example/sleeptimer/ui/theme/Type.kt
543077441
package com.example.sleeptimer import android.os.Bundle import android.os.CountDownTimer import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { private lateinit var timerTextView: TextView private lateinit var circularSeekBar: CircularSeekBar private lateinit var countDownTimer: CountDownTimer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) timerTextView = findViewById(R.id.timerTextView) circularSeekBar = findViewById(R.id.circularSeekBar) circularSeekBar.setOnCircularSeekBarChangeListener(object : CircularSeekBar.OnCircularSeekBarChangeListener { override fun onProgressChanged(circularSeekBar: CircularSeekBar, progress: Float, fromUser: Boolean) { updateTimerText(progress.toInt()) } override fun onStopTrackingTouch(seekBar: CircularSeekBar) { } override fun onStartTrackingTouch(seekBar: CircularSeekBar) { } }) } private fun updateTimerText(progress: Int) { timerTextView.text = String.format("%02d:%02d", progress / 60, progress % 60) } private fun startTimer(durationInSeconds: Int) { countDownTimer = object : CountDownTimer((durationInSeconds * 1000).toLong(), 1000) { override fun onTick(millisUntilFinished: Long) { updateTimerText((millisUntilFinished / 1000).toInt()) } override fun onFinish() { timerTextView.text = "00:00" } } countDownTimer.start() } }
AndroidSleepTimer/app/src/main/java/com/example/sleeptimer/MainActivity.kt
990046256
package com.example.sleeptimer import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.MotionEvent import android.view.View import kotlin.math.atan2 class CircularSeekBar(context: Context, attrs: AttributeSet) : View(context, attrs) { private val circlePaint = Paint(Paint.ANTI_ALIAS_FLAG) private val arcPaint = Paint(Paint.ANTI_ALIAS_FLAG) private val rect = RectF() private var seekBarChangeListener: OnCircularSeekBarChangeListener? = null private var maxProgress = 100 private var progress = 0f private var progressColor: Int = 0 private var seekBarRadius = 0f private val DEFAULT_PROGRESS_COLOR = Color.RED private val DEFAULT_RADIUS = 100f init { circlePaint.style = Paint.Style.STROKE arcPaint.style = Paint.Style.STROKE arcPaint.strokeCap = Paint.Cap.ROUND val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CircularSeekBar, 0, 0) try { circlePaint.color = typedArray.getColor(R.styleable.CircularSeekBar_seekBarUnselectedColor, 0xFFBDC3C7.toInt()) circlePaint.strokeWidth = typedArray.getDimensionPixelSize(R.styleable.CircularSeekBar_seekBarWidth, 10).toFloat() arcPaint.color = typedArray.getColor(R.styleable.CircularSeekBar_seekBarColor, 0xFF3498DB.toInt()) arcPaint.strokeWidth = typedArray.getDimensionPixelSize(R.styleable.CircularSeekBar_seekBarWidth, 10).toFloat() maxProgress = typedArray.getInt(R.styleable.CircularSeekBar_seekBarMax, 100) progress = typedArray.getFloat(R.styleable.CircularSeekBar_seekBarProgress, 0f) val listenerClassName = typedArray.getString(R.styleable.CircularSeekBar_seekBarChangeListener) if (listenerClassName != null) { try { val listenerClass = Class.forName(listenerClassName) seekBarChangeListener = listenerClass.newInstance() as OnCircularSeekBarChangeListener } catch (e: ClassNotFoundException) { e.printStackTrace() } catch (e: IllegalAccessError) { e.printStackTrace() } catch (e: InstantiationError) { e.printStackTrace() } } progressColor = typedArray.getColor(R.styleable.CircularSeekBar_progressColor, DEFAULT_PROGRESS_COLOR) seekBarRadius = typedArray.getDimension(R.styleable.CircularSeekBar_seekBarRadius, DEFAULT_RADIUS) } finally { typedArray.recycle() } } interface OnCircularSeekBarChangeListener { fun onProgressChanged(circularSeekBar: CircularSeekBar, progress: Float, fromUser: Boolean) fun onStartTrackingTouch(seekBar: CircularSeekBar) fun onStopTrackingTouch(seekBar: CircularSeekBar) } fun setOnCircularSeekBarChangeListener(listener: OnCircularSeekBarChangeListener?) { seekBarChangeListener = listener } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val centerX = width / 2.toFloat() val centerY = height / 2.toFloat() val radius = width / 2.toFloat() - circlePaint.strokeWidth / 2 canvas.drawCircle(centerX, centerY, radius, circlePaint) rect.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius) val angle = 360 * (progress / maxProgress) canvas.drawArc(rect, -90f, angle, false, arcPaint) } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { if (seekBarChangeListener != null) { seekBarChangeListener!!.onStartTrackingTouch(this) } } MotionEvent.ACTION_MOVE -> { val x = event.x val y = event.y updateOnTouch(x, y) } MotionEvent.ACTION_UP -> if (seekBarChangeListener != null) { seekBarChangeListener!!.onStopTrackingTouch(this) } } return true } private fun updateOnTouch(x: Float, y: Float) { val centerX = width / 2.toFloat() val centerY = height / 2.toFloat() val angle = atan2((y - centerY).toDouble(), (x - centerX).toDouble()) * (180 / Math.PI).toFloat() val calculatedProgress = ((angle + 360) % 360 * maxProgress / 360).toFloat() setProgress(calculatedProgress) } fun setProgress(progress: Float) { if (progress < 0) { this.progress = 0f } else if (progress > maxProgress) { this.progress = maxProgress.toFloat() } else { this.progress = progress } if (seekBarChangeListener != null) { seekBarChangeListener!!.onProgressChanged(this, this.progress, true) } invalidate() } }
AndroidSleepTimer/app/src/main/java/com/example/sleeptimer/CircularSeekBar.kt
2540099812
package com.part2.a3dify import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("bae.part2.a3dify", appContext.packageName) } }
3Dify/app/src/androidTest/java/com/part2/a3dify/ExampleInstrumentedTest.kt
1546888595
package com.part2.a3dify import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
3Dify/app/src/test/java/com/part2/a3dify/ExampleUnitTest.kt
55102691
package com.part2.a3dify.local_db import android.content.Context import androidx.security.crypto.EncryptedSharedPreferences import androidx.security.crypto.MasterKeys import com.part2.a3dify.common.SECRET_USER_INFO class LoginEncryptSharedPreference(context : Context) { // MasterKey in the AndroidX Security library. // Same key is used if already exists for configuration. private val masterKey : String = MasterKeys.getOrCreate( MasterKeys.AES256_GCM_SPEC // Android Keystore. Encrypt files. ) private val loginEncryptSharedPreference = EncryptedSharedPreferences.create( SECRET_USER_INFO, masterKey, context, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) }
3Dify/app/src/main/java/com/part2/a3dify/local_db/LoginEncryptSharedPreference.kt
652711558
package com.part2.a3dify.common const val SECRET_USER_INFO = "secret_user_info" const val SERVER_CLIENT_ID = "423296288365-tnadkkvggct11g8v48jlfpp933e68dub.apps.googleusercontent.com"
3Dify/app/src/main/java/com/part2/a3dify/common/Const.kt
22658188
package com.part2.a3dify.common import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow open class CommonViewModel<T>(initialState: T) : ViewModel() { protected val _uiState = MutableStateFlow(initialState) val uiState: StateFlow<T> = _uiState.asStateFlow() protected var fetchJob: Job? = null }
3Dify/app/src/main/java/com/part2/a3dify/common/CommonViewModel.kt
346520420
package com.part2.a3dify.app_entry import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.add import androidx.fragment.app.commit import androidx.fragment.app.replace import com.part2.a3dify.R import com.part2.a3dify.databinding.FragmentInitialBinding class InitialFragment : Fragment() { private lateinit var binding : FragmentInitialBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentInitialBinding.inflate(inflater) binding.nonMember.setOnClickListener { parentFragmentManager.commit { replace<MainFragment>(R.id.fragment) setReorderingAllowed(true) addToBackStack(null) } } binding.member.setOnClickListener { parentFragmentManager.commit { replace<LoginFragment>(R.id.fragment) setReorderingAllowed(true) addToBackStack(null) } } return binding.root } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/InitialFragment.kt
776799531
package com.part2.a3dify.app_entry.uistates data class LoginFragmentUiStates ( val isLogin: Boolean = false, // below values are non-null only when 'true' val userId: String? = null, val name: String? = null )
3Dify/app/src/main/java/com/part2/a3dify/app_entry/uistates/LoginFragmentUiStates.kt
56320671
package com.part2.a3dify.app_entry.uistates data class RegisterRequest ( val id: String, // shouldn't be null, required val email: String, val pwd: String ) data class RegisterResponse( val success: Boolean, val message: String, val id: String ) data class RegisterFragmentUiStates ( val registerRequest: RegisterRequest? = null, val registerResponse: RegisterResponse?= null )
3Dify/app/src/main/java/com/part2/a3dify/app_entry/uistates/RegisterFragmentUiStates.kt
1691142838
package com.part2.a3dify.app_entry.uistates import com.part2.a3dify.app_entry.image_recycler_view.ImageDataClass data class MainFragmentUiStates ( val uriList : List<ImageDataClass>? = null, val showLoading : Boolean? = null )
3Dify/app/src/main/java/com/part2/a3dify/app_entry/uistates/MainFragmentUiStates.kt
2283174341
package com.part2.a3dify.app_entry.viewmodels import android.app.Application import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.net.Uri import android.provider.MediaStore import android.util.Log import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY import androidx.lifecycle.createSavedStateHandle import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.CreationExtras import com.part2.a3dify.app_containers.ThrDifyApplication import com.part2.a3dify.common.CommonViewModel import com.part2.a3dify.app_entry.image_recycler_view.ImageAdapter import com.part2.a3dify.app_entry.image_recycler_view.ImageDataClass import com.part2.a3dify.app_entry.uistates.MainFragmentUiStates import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainFragmentViewModel(private val application: Application, private val savedStateHandle: SavedStateHandle): CommonViewModel<MainFragmentUiStates>(MainFragmentUiStates()) { companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T { // Get the Application object from extras val application = checkNotNull(extras[APPLICATION_KEY]) // Create a SavedStateHandle for this ViewModel from extras val savedStateHandle = extras.createSavedStateHandle() return MainFragmentViewModel((application as ThrDifyApplication), savedStateHandle) as T } } } fun updateRecyclerImages(uriList: List<Uri>) { fetchJob?.cancel() fetchJob = viewModelScope.launch { withContext(Dispatchers.Main) { _uiState.update { progressBarLoading() } } withContext(Dispatchers.Default) { _uiState.update { updateImages(uriList) } } } fetchJob?.invokeOnCompletion { if (it == null) { // finished completely fetchJob = null } else { Log.d("fetchJob", "Something Wrong") } } } private fun progressBarLoading() : MainFragmentUiStates { return MainFragmentUiStates(null, true) } private fun updateImages(uriList: List<Uri>) : MainFragmentUiStates { val images = uriList.map{ImageDataClass( it, configureBitmap(it) )} return MainFragmentUiStates(images, false) } private fun configureBitmap(uri: Uri): Bitmap { var bitmap = MediaStore.Images.Media.getBitmap(application.applicationContext.contentResolver, uri) val matrix = Matrix() matrix.postRotate(90.0f) bitmap = Bitmap.createScaledBitmap(bitmap, 1000, 1000, true) return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) } override fun onCleared() { fetchJob?.cancel() } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/viewmodels/MainFragmentViewModel.kt
2200861740
package com.part2.a3dify.app_entry.viewmodels import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.createSavedStateHandle import androidx.lifecycle.viewmodel.CreationExtras import com.part2.a3dify.common.CommonViewModel import com.part2.a3dify.app_entry.uistates.LoginFragmentUiStates class LoginFragmentViewModel(private val savedStateHandle: SavedStateHandle): CommonViewModel<LoginFragmentUiStates>(LoginFragmentUiStates()) { companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T { // Get the Application object from extras val application = checkNotNull(extras[ViewModelProvider.AndroidViewModelFactory.APPLICATION_KEY]) // Create a SavedStateHandle for this ViewModel from extras val savedStateHandle = extras.createSavedStateHandle() return LoginFragmentViewModel(savedStateHandle) as T } } } fun login() { } fun register() { } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/viewmodels/LoginFragmentViewModel.kt
2816975001
package com.part2.a3dify.app_entry import android.content.DialogInterface import android.content.pm.PackageManager import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat internal fun MainFragment.checkPermission() { when { // utility class provided by the Android Support Library / Androidx context?.let { ContextCompat.checkSelfPermission( it, // context of the activity in which the fragment is hosted in android.Manifest.permission.READ_EXTERNAL_STORAGE ) } == PackageManager.PERMISSION_GRANTED -> { loadImage() } // already tried once to get permission -> show UI Rationale before asking permission shouldShowRequestPermissionRationale( android.Manifest.permission.READ_EXTERNAL_STORAGE ) -> { showPermissionInfoDialog() } else -> { // Reaching here when : // 1. never tried to reach the gallery requestReadExternalStorage() } } } // Already requested for permission, but rejected -> Double checking using dialog internal fun MainFragment.showPermissionInfoDialog() { context?.let { AlertDialog.Builder(it).apply { setMessage("To get image from storage, need READ permission for storage.") setNegativeButton("Cancel") { dialogInterface, _ -> dialogInterface.dismiss() } setPositiveButton("Ok") { dialogInterface, which -> dialogInterface.dismiss() if (which == DialogInterface.BUTTON_POSITIVE) { requestReadExternalStorage() } } }.show() } } internal fun MainFragment.requestReadExternalStorage() { requestReadExternalStorageLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE) }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/Permissions.kt
2325869258
package com.part2.a3dify.app_entry import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.fragment.app.add import androidx.fragment.app.commit import com.part2.a3dify.R import com.part2.a3dify.databinding.ActivityMainBinding import java.io.File class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // ######### Doesn't need this because it's inside FrameLayout now ########## // Adding toolbar support // binding.mainToolbar.title = "3Dify" // val toolbar = findViewById<MaterialToolbar>(R.id.topAppBar) // setSupportActionBar(toolbar) // How to set supportActionBar // // Log.d("Cache Directory", baseContext.filesDir.toString()) /data/user/0/com.part2.a3dify/files if (savedInstanceState == null) { // to ensure that the fragment is added only once supportFragmentManager.commit { setReorderingAllowed(true) add<InitialFragment>(R.id.fragment) } } } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/MainActivity.kt
969976612
package com.part2.a3dify.app_entry import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.RequiresApi import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.auth.api.signin.internal.SignInHubActivity import com.google.android.gms.common.Scopes import com.google.android.gms.common.api.ApiException import com.google.android.gms.common.api.Scope import com.google.android.gms.tasks.Task import com.part2.a3dify.R import com.part2.a3dify.app_containers.LoginFragmentContainer import com.part2.a3dify.app_containers.ThrDifyApplication import com.part2.a3dify.app_entry.viewmodels.LoginFragmentViewModel import com.part2.a3dify.common.SERVER_CLIENT_ID import com.part2.a3dify.databinding.FragmentLoginBinding import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch class LoginFragment : Fragment() { private lateinit var binding : FragmentLoginBinding private val viewModel : LoginFragmentViewModel by viewModels { var temp = (requireActivity().application as ThrDifyApplication).mainContainer.loginFragmentContainer if (temp == null) { temp = LoginFragmentContainer() return@viewModels temp.loginFragmentViewModelFactory } else return@viewModels temp.loginFragmentViewModelFactory } private lateinit var gso: GoogleSignInOptions private lateinit var mGoogleSignInClient: GoogleSignInClient private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {result-> Log.d("Launcher", "${result.resultCode}") if (result.resultCode == Activity.RESULT_OK) { val task = GoogleSignIn.getSignedInAccountFromIntent(result.data) handleSignInResult(task) Log.d("Launcher", "Result OK") } } private fun handleSignInResult(task: Task<GoogleSignInAccount>) { try { val account = task.getResult(ApiException::class.java) // Signed in successfully, show authenticated UI or proceed with the account details. Log.d("Sign In", "Successful") if (account != null) { Log.d("email", "${account.email}") Log.d("email", "${account.serverAuthCode}") Log.d("email", "${account.idToken}") Log.d("email", "${account.grantedScopes}") Log.d("email", "${account.isExpired}") Log.d("email", "${account.id}") } } catch (e: ApiException) { // The ApiException status code indicates the detailed failure reason. Log.w("API Error", "signInResult:failed code=" + e.statusCode) } } private fun moveSignUpActivity() { requireActivity().run { startActivity(Intent(requireContext(), SignInHubActivity::class.java)) finish() } } // before view, check for login state of Google Account override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Configure sign-in to request the user's ID, email address and basic profile. // ID and basic profile are included in DEFAULT_SIGN_IN gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) // .requestServerAuthCode(getString(R.string.server_client_id)) // Only for backend Server .requestScopes(Scope(Scopes.DRIVE_APPFOLDER)) .requestEmail() .build() // for addional scopes, specify them with 'requestScopes' mGoogleSignInClient = GoogleSignIn.getClient(requireActivity(), gso) binding = FragmentLoginBinding.inflate(inflater) binding.googleLoginButton.setOnClickListener { val account: GoogleSignInAccount? = GoogleSignIn.getLastSignedInAccount(requireContext()) mGoogleSignInClient.signOut() val signInIntent = mGoogleSignInClient.signInIntent // startActivityForResult(signInIntent, RC_SIGN_IN) resultLauncher.launch(signInIntent) // if (account == null) { // val signInIntent = mGoogleSignInClient.signInIntent //// startActivityForResult(signInIntent, RC_SIGN_IN) // resultLauncher.launch(signInIntent) // } else { // Log.d("Account Check", "Existing") // Log.d("email", "${account.email}") // Log.d("email", "${account.serverAuthCode}") // Log.d("email", "${account.id}") // } } return binding.root } override fun onDestroyView() { super.onDestroyView() } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/LoginFragment.kt
2696418146
package com.part2.a3dify.app_entry.image_recycler_view import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.RequiresApi import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.part2.a3dify.databinding.ViewholderImageBinding class ImageAdapter(private val context: Context) : RecyclerView.Adapter<ImageViewHolder>() { inner class DiffUtilCallback() : DiffUtil.ItemCallback<ImageDataClass>() { override fun areItemsTheSame( oldItem: ImageDataClass, newItem: ImageDataClass ): Boolean { return oldItem === newItem } override fun areContentsTheSame( oldItem: ImageDataClass, newItem: ImageDataClass ): Boolean { return oldItem == newItem } } private val asyncDiffer = AsyncListDiffer(this, DiffUtilCallback()) private var imagesGroup : List<ImageDataClass> = emptyList() // Preventing possible memory leak fun changeImageGroup(_imagesGroup : List<ImageDataClass>) { imagesGroup = _imagesGroup asyncDiffer.submitList(imagesGroup) // on background thread } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val binding = ViewholderImageBinding.inflate(inflater, parent, false) return ImageViewHolder(binding, context) } override fun getItemCount(): Int { return imagesGroup.size } override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { holder.bind(imagesGroup[position]) } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/image_recycler_view/ImageAdapter.kt
4090798114
package com.part2.a3dify.app_entry.image_recycler_view import android.graphics.Bitmap import android.net.Uri data class ImageDataClass( val uri : Uri, val bitmapMini : Bitmap )
3Dify/app/src/main/java/com/part2/a3dify/app_entry/image_recycler_view/ImageDataClass.kt
1649008737
package com.part2.a3dify.app_entry.image_recycler_view import android.content.Context import android.graphics.Bitmap import android.os.Build import android.provider.MediaStore import android.util.Size import androidx.annotation.RequiresApi import androidx.recyclerview.widget.RecyclerView import com.part2.a3dify.databinding.ViewholderImageBinding // RecyclerView.ViewHolder sets data member 'itemView' to the 'binding.root' class ImageViewHolder(private val binding: ViewholderImageBinding, private val context: Context) : RecyclerView.ViewHolder(binding.root) { fun bind(item : ImageDataClass) { // binding.previewImageView.setImageURI(item.uri) --- Old Way // Modern Method, but not quite good for RecyclerView which doesn't have context // binding.previewImageView.setImageBitmap(context.contentResolver.loadThumbnail( // item.uri, // Size(binding.previewImageView.width, binding.previewImageView.height), null) // ) binding.previewImageView.setImageBitmap(item.bitmapMini) } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/image_recycler_view/ImageViewHolder.kt
3549452263
package com.part2.a3dify.app_entry import android.content.ContentUris import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Matrix import android.net.Uri import android.os.Bundle import android.os.Handler import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.GridLayoutManager import com.part2.a3dify.app_containers.MainContainer import com.part2.a3dify.app_containers.MainFragmentContainer import com.part2.a3dify.app_containers.ThrDifyApplication import com.part2.a3dify.app_entry.image_recycler_view.ImageAdapter import com.part2.a3dify.app_entry.image_recycler_view.ImageDataClass import com.part2.a3dify.app_entry.viewmodels.MainFragmentViewModel import com.part2.a3dify.databinding.FragmentMainBinding import com.part2.a3dify.threed_graphic.ThreedActivity import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class MainFragment : Fragment() { private lateinit var binding : FragmentMainBinding private lateinit var imageAdapter : ImageAdapter private val viewModel : MainFragmentViewModel by viewModels { var temp : MainFragmentContainer? = (requireActivity().application as ThrDifyApplication).mainContainer.mainFragmentContainer if (temp == null) { temp = MainFragmentContainer() return@viewModels temp.mainFragmentViewModelFactory } else return@viewModels temp.mainFragmentViewModelFactory } private val imageLoadLauncher = registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { uriList -> // List<Uri>! viewModel.updateRecyclerImages(uriList) // Currently from Gallery, but in future it will get images (history) from backend } internal val requestReadExternalStorageLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted : Boolean -> if (isGranted) { loadImage() } else { Toast.makeText(context, "Image not accessible.", Toast.LENGTH_SHORT).show() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { imageAdapter = ImageAdapter(requireContext()) binding = FragmentMainBinding.inflate(inflater) binding.progressBarRecycler.hide() binding.gallery.setOnClickListener { checkPermission() } binding.threed.setOnClickListener { val intent = Intent(context, ThreedActivity::class.java) startActivity(intent) } binding.imageRecyclerView.apply { adapter = imageAdapter layoutManager = GridLayoutManager(context, 4) } viewLifecycleOwner.lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.uiState.collect { uiState-> Log.d("coroutine", "MainFragment") if (uiState.showLoading == true) binding.progressBarRecycler.show() else binding.progressBarRecycler.hide() // includes false, null if (uiState.uriList == null) return@collect imageAdapter.changeImageGroup(uiState.uriList) // only invoked when collected } } } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Log.d("MainFragment", "OnViewCreated") } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) Log.d("MainFragment", "OnViewStateRestored") } // Coming back from Gallery invokes this method. -- meaning // Coroutine repeatOnLifecycle(Start) should be called. Or Resumed? override fun onStart() { super.onStart() Log.d("MainFragment", "OnStart") } // Need to check on memory when working on 3D task and delete viewModel override fun onDestroyView() { super.onDestroyView() (requireActivity().application as ThrDifyApplication).mainContainer.mainFragmentContainer = null } internal fun loadImage() { imageLoadLauncher.launch("image/*") // Specifying for images } // internal fun fetchImages(context: Context): List<ImageDataClass> { // Log.d("fetchImages", "Invoked") // val imageList = mutableListOf<ImageDataClass>() // // val projection = arrayOf( // MediaStore.Images.Media._ID, // MediaStore.Images.Media.SIZE // ) // // val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC" // // context.contentResolver.query( // MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // projection, // null, // No selection // null, // No selection args // sortOrder // )?.use {cursor -> // // Cache column indices so that you don't need to call 'getColumnIndexOrThrow()' each time // // you process a row from the query result. // val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID) // val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE) // // while (cursor.moveToNext()) { // val id = cursor.getLong(idColumn) // val size = cursor.getInt(sizeColumn) // // val contentUri: Uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) // // val thumbnailUri = MediaStore.Images.Thumbnails.getThumbnail // imageList += ImageDataClass(contentUri) // } // } // return imageList // } }
3Dify/app/src/main/java/com/part2/a3dify/app_entry/MainFragment.kt
2564902637
package com.part2.a3dify.app_containers class MainContainer { var mainFragmentContainer : MainFragmentContainer? = null var loginFragmentContainer : LoginFragmentContainer? = null }
3Dify/app/src/main/java/com/part2/a3dify/app_containers/MainContainer.kt
2972919906
package com.part2.a3dify.app_containers import android.content.Context import com.part2.a3dify.app_entry.image_recycler_view.ImageAdapter import com.part2.a3dify.app_entry.viewmodels.MainFragmentViewModel class MainFragmentContainer() { val mainFragmentViewModelFactory = MainFragmentViewModel.factory // Other souces of Repository (made of data sources) }
3Dify/app/src/main/java/com/part2/a3dify/app_containers/MainFragmentContainer.kt
3000449497
package com.part2.a3dify.app_containers import android.app.Application // Invoked by (application as ThrDifyApplication) in activity and fragment class ThrDifyApplication : Application() { val mainContainer = MainContainer() }
3Dify/app/src/main/java/com/part2/a3dify/app_containers/ThrDifyApplication.kt
3147004442