content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package top.chengdongqing.weui.feature.samples.components.digitalkeyboard import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.Backspace import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable 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.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable internal fun ActionBar( widthPerItem: Dp, confirmButtonOptions: DigitalKeyboardConfirmOptions, isEmpty: Boolean, onBack: () -> Unit, onConfirm: () -> Unit ) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Box( modifier = Modifier .width(widthPerItem) .height(50.dp) .clip(RoundedCornerShape(4.dp)) .background(MaterialTheme.colorScheme.onBackground) .clickable { onBack() }, contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.AutoMirrored.Filled.Backspace, contentDescription = "回退", tint = MaterialTheme.colorScheme.onPrimary ) } Box( modifier = Modifier .width(widthPerItem) .height((50 * 3 + 8 * 2).dp) .clip(RoundedCornerShape(4.dp)) .background(if (isEmpty) confirmButtonOptions.color.copy(0.4f) else confirmButtonOptions.color) .clickable(enabled = !isEmpty) { onConfirm() }, contentAlignment = Alignment.Center ) { Text(text = confirmButtonOptions.text, color = Color.White, fontSize = 17.sp) } } }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/digitalkeyboard/ActionBar.kt
2191079306
package top.chengdongqing.weui.feature.samples.components.digitalkeyboard import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.tween import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import kotlinx.coroutines.delay @Composable internal fun KeyboardPopup(visible: Boolean, onHide: () -> Unit, content: @Composable () -> Unit) { val popupPositionProvider = remember { object : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset { return IntOffset(0, windowSize.height) } } } var localVisible by remember { mutableStateOf(false) } LaunchedEffect(visible) { if (!visible) { delay(250) } localVisible = visible } BackHandler(visible) { onHide() } if (visible || localVisible) { Popup(popupPositionProvider) { AnimatedVisibility( visible = visible && localVisible, enter = slideInVertically( animationSpec = tween(250), initialOffsetY = { it } ), exit = slideOutVertically( animationSpec = tween(250), targetOffsetY = { it } ) ) { content() } } } }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/digitalkeyboard/KeyboardPopup.kt
4122281917
package top.chengdongqing.weui.feature.samples.components.digitalkeyboard import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @OptIn(ExperimentalLayoutApi::class) @Composable internal fun RowScope.DigitalGrid( widthPerItem: Dp, allowDecimal: Boolean, onClick: (String) -> Unit ) { FlowRow( modifier = Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), maxItemsInEachRow = 3 ) { repeat(9) { index -> val value = (index + 1).toString() KeyItem( key = value, modifier = Modifier.weight(1f) ) { onClick(value) } } KeyItem( key = "0", modifier = Modifier.width(widthPerItem * 2 + 8.dp) ) { onClick("0") } KeyItem( key = if (allowDecimal) "." else "", modifier = Modifier.weight(1f), clickable = allowDecimal ) { onClick(".") } } } @Composable private fun KeyItem( key: String, modifier: Modifier, clickable: Boolean = true, onClick: () -> Unit ) { Box( modifier = modifier .height(50.dp) .clip(RoundedCornerShape(4.dp)) .background(MaterialTheme.colorScheme.onBackground) .clickable(enabled = clickable) { onClick() }, contentAlignment = Alignment.Center ) { Text( text = key, color = MaterialTheme.colorScheme.onPrimary, fontSize = 20.sp, fontWeight = FontWeight.Bold ) } }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/digitalkeyboard/DigitalGrid.kt
241138970
package top.chengdongqing.weui.feature.samples.components import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowLeft import androidx.compose.material.icons.automirrored.outlined.KeyboardArrowRight import androidx.compose.material.icons.outlined.KeyboardDoubleArrowLeft import androidx.compose.material.icons.outlined.KeyboardDoubleArrowRight import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.nlf.calendar.Lunar import com.nlf.calendar.Solar import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.utils.ChineseDateFormatter import java.time.LocalDate import java.time.YearMonth import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit @OptIn(ExperimentalFoundationApi::class) @Composable fun WeCalendar(state: CalendarState = rememberCalendarState()) { Column { Header(state.currentMonth) { state.setMonth(it) } WeekDaysBar() WeDivider() DaysGrid(state.pagerState) } } @Composable private fun Header(currentMonth: LocalDate, onMonthChange: (LocalDate) -> Unit) { val formatter = remember { DateTimeFormatter.ofPattern(ChineseDateFormatter) } Row( modifier = Modifier .fillMaxWidth() .padding(top = 15.dp), verticalAlignment = Alignment.CenterVertically ) { IconButton(onClick = { onMonthChange(currentMonth.minusYears(1)) }) { Icon( imageVector = Icons.Outlined.KeyboardDoubleArrowLeft, contentDescription = "上一年", tint = MaterialTheme.colorScheme.onSecondary ) } IconButton(onClick = { onMonthChange(currentMonth.minusMonths(1)) }) { Icon( imageVector = Icons.AutoMirrored.Outlined.KeyboardArrowLeft, contentDescription = "上个月", tint = MaterialTheme.colorScheme.onSecondary ) } Text( text = currentMonth.format(formatter), color = MaterialTheme.colorScheme.onPrimary, fontSize = 18.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f), textAlign = TextAlign.Center ) IconButton(onClick = { onMonthChange(currentMonth.plusMonths(1)) }) { Icon( imageVector = Icons.AutoMirrored.Outlined.KeyboardArrowRight, contentDescription = "下个月", tint = MaterialTheme.colorScheme.onSecondary ) } IconButton(onClick = { onMonthChange(currentMonth.plusYears(1)) }) { Icon( imageVector = Icons.Outlined.KeyboardDoubleArrowRight, contentDescription = "下一年", tint = MaterialTheme.colorScheme.onSecondary ) } } } @Composable private fun WeekDaysBar() { val weekDays = remember { arrayOf("日", "一", "二", "三", "四", "五", "六") } Row { weekDays.forEach { Box( modifier = Modifier .weight(1f) .padding(vertical = 20.dp), contentAlignment = Alignment.Center ) { Text( text = it, color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp ) } } } } @OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class) @Composable private fun DaysGrid(pagerState: PagerState) { HorizontalPager(state = pagerState) { page -> val offset = page - InitialPage // 当前月份 val date = Today.plusMonths(offset.toLong()) // 当月总天数 val daysOfMonth = date.lengthOfMonth() // 当月第一天是星期几 val firstDayOfWeek = date.withDayOfMonth(1).dayOfWeek.value - 1 Box(contentAlignment = Alignment.Center) { // 月份背景 Text( text = date.monthValue.toString(), color = MaterialTheme.colorScheme.primary.copy(0.2f), fontSize = 160.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Cursive ) // 日期网格 FlowRow( maxItemsInEachRow = 7, modifier = Modifier .fillMaxWidth() .padding(vertical = 10.dp) ) { repeat(7 * 6) { index -> Box( modifier = Modifier .weight(1f) .aspectRatio(1f), contentAlignment = Alignment.Center ) { when { // 上月的日期 index <= firstDayOfWeek -> { val lastMonth = date.minusMonths(1) val day = lastMonth.lengthOfMonth() - (firstDayOfWeek - index) DayItem( date = date.minusMonths(1).withDayOfMonth(day), outInMonth = true ) } // 下月的日期 index - firstDayOfWeek > daysOfMonth -> { val day = index - (daysOfMonth + firstDayOfWeek) DayItem( date = date.plusMonths(1).withDayOfMonth(day), outInMonth = true ) } // 本月的日期 else -> { val isToday = Today == date.withDayOfMonth(index - firstDayOfWeek) val day = index - firstDayOfWeek DayItem( date = date.withDayOfMonth(day), isToday ) } } } } } } } } @Composable private fun DayItem( date: LocalDate, isToday: Boolean = false, outInMonth: Boolean = false ) { Column( modifier = if (outInMonth) Modifier.alpha(0.4f) else Modifier, horizontalAlignment = Alignment.CenterHorizontally ) { // 公历日期 Text( text = date.dayOfMonth.toString(), color = if (isToday) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.onPrimary }, fontSize = 18.sp, fontWeight = if (!outInMonth) FontWeight.Bold else FontWeight.Normal ) // 农历日期 val lunarDate = Lunar(Solar(date.year, date.monthValue, date.dayOfMonth)) val lunarDay = if (lunarDate.festivals.isNotEmpty()) { lunarDate.festivals.first() } else if (lunarDate.day == 1) { lunarDate.monthInChinese + "月" } else { lunarDate.dayInChinese } Text( text = lunarDay, color = if (isToday) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.onSecondary }, fontSize = 11.sp ) } } @Stable interface CalendarState { /** * 当前月份 */ val currentMonth: LocalDate @OptIn(ExperimentalFoundationApi::class) val pagerState: PagerState /** * 设置月份 */ fun setMonth(month: LocalDate, scrollToPage: Boolean = true) /** * 回到今天 */ fun toToday() { setMonth(Today) } } @OptIn(ExperimentalFoundationApi::class) @Composable fun rememberCalendarState(initialDate: LocalDate = Today): CalendarState { val coroutineScope = rememberCoroutineScope() val pagerState = rememberPagerState(initialPage = InitialPage) { TotalPage } val state = remember { CalendarStateImpl(initialDate, pagerState, coroutineScope) } LaunchedEffect(Unit) { snapshotFlow { pagerState.currentPage }.collect { page -> val diff = page - InitialPage state.setMonth(month = Today.plusMonths(diff.toLong()), scrollToPage = false) } } return state } @OptIn(ExperimentalFoundationApi::class) private class CalendarStateImpl( initialDate: LocalDate, override val pagerState: PagerState, val coroutineScope: CoroutineScope ) : CalendarState { override val currentMonth: LocalDate get() = _currentMonth override fun setMonth(month: LocalDate, scrollToPage: Boolean) { _currentMonth = month if (scrollToPage) { coroutineScope.launch { val page = ChronoUnit.MONTHS.between(initialMonth, YearMonth.from(month)).toInt() pagerState.scrollToPage(page) } } } private val initialMonth = YearMonth.now().minusMonths(InitialPage.toLong()) private var _currentMonth by mutableStateOf(initialDate) } private val Today = LocalDate.now() private const val TotalPage = 2000 private const val InitialPage = 1000
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/Calendar.kt
4103385918
package top.chengdongqing.weui.feature.samples.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Add import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.utils.clickableWithoutRipple data class OrgNode(val label: String, val children: List<OrgNode> = emptyList()) @Composable fun WeOrgTree(dataSource: List<OrgNode>, isTopLevel: Boolean = true) { val spacing = 20.dp val lineColor = MaterialTheme.orgTreeColorScheme.lineColor val layoutCoordinates = remember { mutableMapOf<Int, Pair<Float, Float>>() } Row( modifier = Modifier .onGloballyPositioned { layoutCoordinates.clear() } .drawHorizontalLine(dataSource, layoutCoordinates, lineColor, spacing) ) { dataSource.forEachIndexed { index, item -> var expended by rememberSaveable { mutableStateOf(item.children.isEmpty()) } Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.onGloballyPositioned { coordinates -> layoutCoordinates[index] = Pair( coordinates.positionInParent().x, coordinates.size.width.toFloat() ) } ) { Box( modifier = Modifier .then( if (item.children.isNotEmpty()) { Modifier } else { Modifier.width(28.dp) } ) .drawVerticalLine( isTopLevel, lineColor, spacing, expended, hasChildren = item.children.isNotEmpty() ) .clip(RoundedCornerShape(2.dp)) .setStyle(expended) .clickableWithoutRipple { if (item.children.isNotEmpty()) { expended = !expended } } .padding(horizontal = 6.dp, vertical = 4.dp), contentAlignment = Alignment.Center ) { Text( text = item.label, color = if (expended) { MaterialTheme.colorScheme.onPrimary } else { Color.White }, fontSize = 14.sp, textAlign = TextAlign.Center ) } if (item.children.isNotEmpty()) { if (expended) { Spacer(modifier = Modifier.height(spacing * 2)) WeOrgTree(item.children, false) } else { Spacer(modifier = Modifier.height(5.dp)) ExpandableIcon { expended = true } } } } if (index < dataSource.lastIndex) { Spacer(modifier = Modifier.width(spacing)) } } } } @Composable private fun ExpandableIcon(onClick: () -> Unit) { Box( modifier = Modifier .border( 1.dp, MaterialTheme.colorScheme.onSecondary, CircleShape ) ) { Icon( imageVector = Icons.Outlined.Add, contentDescription = "展开", tint = MaterialTheme.colorScheme.onSecondary, modifier = Modifier .size(20.dp) .clickableWithoutRipple { onClick() } ) } } @Composable private fun Modifier.setStyle(expended: Boolean): Modifier { return if (expended) { this .border( width = 0.8.dp, color = MaterialTheme.orgTreeColorScheme.borderColor, shape = RoundedCornerShape(2.dp) ) .background(MaterialTheme.colorScheme.onBackground) } else { this.background(MaterialTheme.colorScheme.primary) } } private fun Modifier.drawVerticalLine( isTopLevel: Boolean, lineColor: Color, space: Dp, expended: Boolean, hasChildren: Boolean ) = this.drawBehind { // 绘制顶部连接线 if (!isTopLevel) { drawLine( color = lineColor, start = Offset(size.width / 2, -space.toPx()), end = Offset(size.width / 2, 0.dp.toPx()), strokeWidth = 0.5.dp.toPx() ) } // 绘制底部连接线 if (expended && hasChildren) { drawLine( color = lineColor, start = Offset(size.width / 2, size.height), end = Offset(size.width / 2, size.height + space.toPx()), strokeWidth = 0.5.dp.toPx() ) } } private fun Modifier.drawHorizontalLine( dataSource: List<OrgNode>, layoutCoordinates: Map<Int, Pair<Float, Float>>, lineColor: Color, space: Dp ) = this.drawBehind { // 确保至少有两个子元素才绘制水平线 if (dataSource.size > 1) { layoutCoordinates.values .firstOrNull() ?.let { first -> layoutCoordinates.values .lastOrNull() ?.let { last -> drawLine( color = lineColor, start = Offset( first.first + (first.second / 2), -space.toPx() ), end = Offset(last.first + (last.second / 2), -space.toPx()), strokeWidth = 0.5.dp.toPx() ) } } } } private data class OrgTreeColors( val lineColor: Color, val borderColor: Color ) private val MaterialTheme.orgTreeColorScheme: OrgTreeColors @Composable get() = OrgTreeColors( lineColor = if (isSystemInDarkTheme()) { colorScheme.outline } else { Color.Black }, borderColor = if (isSystemInDarkTheme()) { colorScheme.outline } else { colorScheme.onPrimary } )
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/OrgTree.kt
1677026356
package top.chengdongqing.weui.feature.samples.components.indexedlist import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.loading.WeLoading import top.chengdongqing.weui.core.utils.PinyinUtils.groupByFirstLetter @Composable fun WeIndexedList(labels: List<String>) { val listState = rememberLazyListState() var loading by remember { mutableStateOf(false) } val groups by produceState<Map<Char, List<String>>>(initialValue = emptyMap(), key1 = labels) { loading = true value = groupByFirstLetter(labels).toSortedMap { a, b -> if (a != '#') a - b else 1 } loading = false } if (loading) { WeLoading() } Box(modifier = Modifier.fillMaxSize()) { LazyColumn( state = listState, contentPadding = PaddingValues(bottom = 60.dp) ) { indexGroups(groups) } IndexBar(listState, groups) } } @OptIn(ExperimentalFoundationApi::class) private fun LazyListScope.indexGroups(groups: Map<Char, List<String>>) { groups.forEach { (letter, list) -> stickyHeader { Text( text = letter.toString(), color = MaterialTheme.colorScheme.onSecondary, fontSize = 13.sp, modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) .padding(horizontal = 16.dp, vertical = 8.dp) ) } itemsIndexed(list) { index, item -> Column(modifier = Modifier.background(MaterialTheme.colorScheme.onBackground)) { Text( text = item, color = MaterialTheme.colorScheme.onPrimary, fontSize = 15.sp, modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.onBackground) .clickable { } .padding(horizontal = 16.dp, vertical = 16.dp) ) if (index < list.lastIndex) { WeDivider(modifier = Modifier.padding(start = 16.dp, end = 30.dp)) } } } } }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/indexedlist/IndexedList.kt
1941066141
package top.chengdongqing.weui.feature.samples.components.indexedlist import android.view.MotionEvent import androidx.compose.foundation.background import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInteropFilter import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay import kotlinx.coroutines.launch import top.chengdongqing.weui.core.utils.clickableWithoutRipple import kotlin.math.roundToInt @Composable fun BoxScope.IndexBar(listState: LazyListState, groups: Map<Char, List<String>>) { val density = LocalDensity.current val coroutineScope = rememberCoroutineScope() var heightPerIndex by remember { mutableFloatStateOf(0f) } val dpHeightPerIndex = with(density) { heightPerIndex.toDp() } val indexes = remember { ('A'..'Z').toList() + '#' } var current by remember { mutableStateOf<Pair<Char, Int>?>(null) } Box( modifier = Modifier .fillMaxHeight() .align(Alignment.TopEnd) .clickableWithoutRipple { }, contentAlignment = Alignment.Center ) { Box { Column( modifier = Modifier .align(Alignment.TopEnd) .padding(horizontal = 4.dp) .onGloballyPositioned { layoutCoordinates -> heightPerIndex = layoutCoordinates.size.height / indexes.size.toFloat() } .pointerInput(indexes, groups, heightPerIndex) { detectVerticalDragGestures( onDragEnd = { current = null } ) { change, _ -> val index = (change.position.y / heightPerIndex) .roundToInt() .coerceIn(indexes.indices) val title = indexes[index] current = title to index coroutineScope.launch { scrollToIndex(title, groups, listState) } } }, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { indexes.forEachIndexed { index, title -> IndexBarItem( title, index, current, groups, listState ) { current = it } } } current?.let { (title, index) -> DrawIndicator(title, index, dpHeightPerIndex) } } } } @OptIn(ExperimentalComposeUiApi::class) @Composable private fun IndexBarItem( title: Char, index: Int, current: Pair<Char, Int>?, groups: Map<Char, List<String>>, listState: LazyListState, setCurrent: (Pair<Char, Int>?) -> Unit ) { val coroutineScope = rememberCoroutineScope() val selected = title == current?.first Box( modifier = Modifier .size(20.dp) .background( if (selected) { MaterialTheme.colorScheme.primary } else { Color.Transparent }, CircleShape ), contentAlignment = Alignment.Center ) { Text( text = title.toString(), color = if (selected) Color.White else MaterialTheme.colorScheme.onPrimary, fontSize = 11.sp, modifier = Modifier .pointerInteropFilter { motionEvent -> when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { setCurrent(title to index) coroutineScope.launch { scrollToIndex(title, groups, listState) } true } MotionEvent.ACTION_UP -> { coroutineScope.launch { delay(300) setCurrent(null) } true } else -> false // 对于其他事件,返回false表示未消费事件 } } ) } } @Composable private fun BoxScope.DrawIndicator(title: Char, index: Int, dpHeightPerIndex: Dp) { val color = MaterialTheme.colorScheme.background Box( modifier = Modifier .size(60.dp) .align(Alignment.TopStart) .offset( x = (-60).dp, y = (-30 + dpHeightPerIndex.value * index + dpHeightPerIndex.value / 2).dp ) .drawWithCache { val circlePath = Path().apply { addOval(Rect(Offset(0f, 0f), Size(size.width, size.height))) } val trianglePath = Path().apply { moveTo( size.width - 14.dp.toPx(), size.height / 2 - 25.dp.toPx() ) lineTo(size.width + 16.dp.toPx(), size.height / 2) // 尖角顶点 lineTo( size.width - 14.dp.toPx(), size.height / 2 + 25.dp.toPx() ) close() } onDrawBehind { drawPath(circlePath, color) drawPath(trianglePath, color) } }, contentAlignment = Alignment.Center ) { Text(text = title.toString(), color = Color.White, fontSize = 30.sp) } } private suspend fun scrollToIndex( title: Char, groups: Map<Char, List<String>>, listState: LazyListState ) { val index = calculateIndexForTitle(title, groups, listState.layoutInfo.totalItemsCount) if (index >= 0) { listState.scrollToItem(index) } } private fun calculateIndexForTitle( title: Char, groups: Map<Char, List<String>>, totalCount: Int ): Int { if (title == '#') return totalCount - 1 var cumulativeIndex = 0 groups.forEach { (groupTitle, items) -> if (groupTitle == title) return cumulativeIndex cumulativeIndex += items.size + 1 } return -1 }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/indexedlist/IndexBar.kt
898378199
package top.chengdongqing.weui.feature.samples.components import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextMeasurer import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun WeDividingRule( range: IntProgression = 0..100 step 2, colors: DividingRuleColors = MaterialTheme.dividingRuleColorScheme, onChange: (Float) -> Unit ) { val density = LocalDensity.current var halfWidth by remember { mutableStateOf(0.dp) } Box( modifier = Modifier .fillMaxWidth() .height(80.dp) .background(colors.containerColor) .onSizeChanged { halfWidth = density.run { (it.width / 2).toDp() } } ) { Rule(range, colors.contentColor, halfWidth, onChange) Indicator(colors.indicatorColor, halfWidth) } } @Composable private fun Rule( range: IntProgression, color: Color, horizontalPadding: Dp, onChange: (Float) -> Unit ) { val textMeasurer = rememberTextMeasurer() val scrollState = rememberScrollState() val start = range.first val end = range.last val step = range.step val count = (end - start) / step val widthDp = (80 * count).dp val density = LocalDensity.current LaunchedEffect(scrollState, widthDp) { val widthPx = density.run { widthDp.toPx() } val scaleCount = count * 10 val valuePerScale = (end - start) / scaleCount val widthPerScale = widthPx / scaleCount snapshotFlow { scrollState.value }.collect { offset -> val value = start + offset / widthPerScale * valuePerScale onChange(value) } } Box(modifier = Modifier.horizontalScroll(scrollState)) { Canvas( modifier = Modifier .padding(horizontal = horizontalPadding) .width(widthDp) .height(80.dp) ) { repeat(count) { index -> drawRuleUnit( value = (start + (step * index)).toString(), color, offset = index, textMeasurer ) } drawRuleClosureScale( value = end.toString(), color, offset = count, textMeasurer ) } } } private fun DrawScope.drawRuleUnit( value: String, color: Color, offset: Int, textMeasurer: TextMeasurer ) { val offsetX = offset * 80.dp.toPx() val spacing = 8.dp.toPx() repeat(10) { index -> val x = index * spacing + offsetX val endY = when (index) { 0 -> 40.dp.toPx() 5 -> 30.dp.toPx() else -> 20.dp.toPx() } drawLine( color, start = Offset(x, 0f), end = Offset(x, endY), strokeWidth = 1.dp.toPx() ) } val textLayoutResult = textMeasurer.measure( value, TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Bold) ) drawText( textLayoutResult, color, Offset( x = -(textLayoutResult.size.width / 2f) + offsetX, y = 42.dp.toPx() ) ) } private fun DrawScope.drawRuleClosureScale( value: String, color: Color, offset: Int, textMeasurer: TextMeasurer ) { val offsetX = offset * 80.dp.toPx() drawLine( color, start = Offset(offsetX, 0f), end = Offset(offsetX, 40.dp.toPx()), strokeWidth = 1.dp.toPx() ) val textLayoutResult = textMeasurer.measure( value, TextStyle(fontSize = 16.sp, fontWeight = FontWeight.Bold) ) drawText( textLayoutResult, color, Offset( x = -(textLayoutResult.size.width / 2f) + offsetX, y = 42.dp.toPx() ) ) } @Composable private fun Indicator(color: Color, offsetX: Dp) { Canvas(modifier = Modifier.offset(x = offsetX - (12 / 2).dp, y = (-12).dp)) { val path = Path().apply { val size = 12.dp.toPx() moveTo(0f, 0f) lineTo(size, 0f) lineTo(size, size) lineTo(size / 2, size * 2) lineTo(0f, size) lineTo(0f, 0f) close() } drawPath(path, color) } } data class DividingRuleColors( val containerColor: Color, val contentColor: Color, val indicatorColor: Color ) val MaterialTheme.dividingRuleColorScheme: DividingRuleColors @Composable get() = DividingRuleColors( containerColor = colorScheme.onBackground, contentColor = colorScheme.onPrimary, indicatorColor = colorScheme.primary )
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/DividingRule.kt
1525180788
package top.chengdongqing.weui.feature.samples.components import androidx.compose.foundation.DefaultMarqueeVelocity import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MarqueeSpacing import androidx.compose.foundation.background import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp enum class NotificationBarEffect { ELLIPSIS, SCROLL, WRAP } @OptIn(ExperimentalFoundationApi::class) @Composable fun WeNotificationBar( content: String, effect: NotificationBarEffect = NotificationBarEffect.SCROLL, scrollSpacingFraction: Float = 1f, scrollVelocity: Dp = DefaultMarqueeVelocity, colors: NotificationBarColors = MaterialTheme.notificationBarColorScheme, padding: PaddingValues = if (effect == NotificationBarEffect.SCROLL) { PaddingValues(vertical = 12.dp) } else { PaddingValues(horizontal = 16.dp, vertical = 12.dp) } ) { Row( modifier = Modifier .fillMaxWidth() .background(colors.containerColor) .padding(padding), verticalAlignment = Alignment.CenterVertically ) { Text( text = content, color = colors.contentColor, fontSize = 13.sp, maxLines = if (effect == NotificationBarEffect.WRAP) Int.MAX_VALUE else 1, softWrap = effect == NotificationBarEffect.WRAP, overflow = if (effect == NotificationBarEffect.ELLIPSIS) TextOverflow.Ellipsis else TextOverflow.Visible, modifier = if (effect == NotificationBarEffect.SCROLL) { Modifier.basicMarquee( iterations = Int.MAX_VALUE, delayMillis = 0, initialDelayMillis = 0, spacing = MarqueeSpacing.fractionOfContainer(scrollSpacingFraction), velocity = scrollVelocity ) } else { Modifier } ) } } data class NotificationBarColors( val containerColor: Color, val contentColor: Color ) val MaterialTheme.notificationBarColorScheme: NotificationBarColors @Composable get() = NotificationBarColors( containerColor = colorScheme.errorContainer, contentColor = colorScheme.error )
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/NotificationBar.kt
890684594
package top.chengdongqing.weui.feature.samples.components.dropcard import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.tween import androidx.compose.foundation.gestures.detectDragGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.offset import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import kotlinx.coroutines.launch import kotlin.math.abs @Composable fun <T> WeDropCard( items: List<T>, modifier: Modifier = Modifier, animationSpec: AnimationSpec<DropCardAnimationState> = tween(durationMillis = 300), onDrop: (T) -> Unit, content: @Composable BoxScope.(T) -> Unit ) { val animatedItems = remember { mutableStateMapOf<T, Animatable<DropCardAnimationState, AnimationVector2D>>() } items.forEach { item -> if (!animatedItems.containsKey(item)) { animatedItems[item] = Animatable( DropCardAnimationState(0f, 0.5f), cardAnimationStateConverter ) } } val keysToRemove = animatedItems.keys - items.toSet() keysToRemove.forEach { key -> animatedItems.remove(key) } Box { items.reversed().forEachIndexed { index, item -> val isInTopThree = index > items.lastIndex - 3 val current = if (items.lastIndex >= 3) index - 3 else index val animatedItem = animatedItems[item]!! LaunchedEffect(item) { if (isInTopThree) { launch { animatedItem.animateTo( targetValue = DropCardAnimationState( offsetY = 64f - current * 32f, scale = 1f - 0.05f * (2 - current) ), animationSpec = animationSpec ) } } } CardItem( key = item, modifier = modifier .offset(y = animatedItem.value.offsetY.dp) .scale(animatedItem.value.scale), onDrop = { onDrop(item) } ) { content(item) } } } } @Composable private fun <T> CardItem( key: T, modifier: Modifier, onDrop: () -> Unit, content: @Composable () -> Unit ) { val screenWidth = LocalConfiguration.current.screenWidthDp val targetOffset = (screenWidth * 3) val animatedOffset = remember(key) { Animatable(Offset(0f, 0f), offsetConverter) } val coroutineScope = rememberCoroutineScope() if (abs(animatedOffset.value.x) < targetOffset - 50f) { Box( modifier = modifier .graphicsLayer { translationX = animatedOffset.value.x translationY = animatedOffset.value.y rotationZ = (animatedOffset.value.x / screenWidth * 12).coerceIn(-40f, 40f) } .pointerInput(Unit) { detectDragGestures( onDragCancel = { coroutineScope.launch { animatedOffset.snapTo(Offset(0f, 0f)) } }, onDragEnd = { coroutineScope.launch { if (abs(animatedOffset.targetValue.x) < abs(targetOffset) / 4) { animatedOffset.animateTo(Offset(0f, 0f), tween(400)) } else { val endValue = if (animatedOffset.targetValue.x > 0) { targetOffset.toFloat() } else { -targetOffset.toFloat() } animatedOffset.animateTo( Offset(endValue, animatedOffset.value.y), tween(200) ) onDrop() } } } ) { _, dragAmount -> coroutineScope.launch { animatedOffset.snapTo( Offset( animatedOffset.targetValue.x + dragAmount.x, animatedOffset.targetValue.y + dragAmount.y ) ) } } } .clip(RoundedCornerShape(16.dp)) ) { content() } } }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/dropcard/DropCard.kt
1595336377
package top.chengdongqing.weui.feature.samples.components.dropcard import androidx.compose.animation.core.AnimationVector2D import androidx.compose.animation.core.TwoWayConverter import androidx.compose.ui.geometry.Offset data class DropCardAnimationState(val offsetY: Float, val scale: Float) internal val cardAnimationStateConverter = TwoWayConverter<DropCardAnimationState, AnimationVector2D>( convertToVector = { state -> AnimationVector2D(state.offsetY, state.scale) }, convertFromVector = { vector -> DropCardAnimationState(vector.v1, vector.v2) } ) internal val offsetConverter = TwoWayConverter<Offset, AnimationVector2D>( convertToVector = { offset -> AnimationVector2D(offset.x, offset.y) }, convertFromVector = { vector -> Offset(vector.v1, vector.v2) } )
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/dropcard/AnimationConverter.kt
3908648101
package top.chengdongqing.weui.feature.samples.components import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.size import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextMeasurer import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import top.chengdongqing.weui.core.utils.polarToCartesian import java.time.Instant import java.time.ZoneId import kotlin.math.cos import kotlin.math.sin @Composable fun WeClock( zoneId: ZoneId = ZoneId.systemDefault(), borderColor: Color = MaterialTheme.colorScheme.outline, scale: Float = 1f ) { val (currentTime, setCurrentTime) = remember { mutableLongStateOf(System.currentTimeMillis()) } LaunchedEffect(Unit) { while (isActive) { delay(1000) setCurrentTime(System.currentTimeMillis()) } } val textMeasurer = rememberTextMeasurer() val colors = MaterialTheme.clockColorScheme Canvas( modifier = Modifier .size(300.dp) .scale(scale) ) { val canvasSize = size.minDimension val radius = canvasSize / 2 val center = Offset(x = radius, y = radius) drawClockFace(radius, borderColor, colors) drawClockScales(radius, center, textMeasurer, colors) drawClockIndicators(radius, center, currentTime, zoneId, colors) drawIndicatorsLock(colors) } } // 绘制圆盘和边框 private fun DrawScope.drawClockFace(radius: Float, borderColor: Color, colors: ClockColors) { // 绘制圆盘 drawCircle(colors.containerColor) // 绘制边框 val borderWidth = 6.dp.toPx() drawCircle( color = borderColor, radius = radius - borderWidth / 2, style = Stroke(width = borderWidth) ) } // 绘制刻度和数字 private fun DrawScope.drawClockScales( radius: Float, center: Offset, textMeasurer: TextMeasurer, colors: ClockColors ) { val localRadius = radius - 10.dp.toPx() for (i in 0 until 60) { val angle = (i * 6).toFloat() val startRadius = if (i % 5 == 0) { localRadius - 10.dp.toPx() } else { localRadius - 8.dp.toPx() } // 绘制刻度 drawLine( color = if (i % 5 == 0) colors.scalePrimaryColor else colors.scaleSecondaryColor, start = Offset( x = center.x + cos(Math.toRadians(angle.toDouble())).toFloat() * startRadius, y = center.y + sin(Math.toRadians(angle.toDouble())).toFloat() * startRadius ), end = Offset( x = center.x + cos(Math.toRadians(angle.toDouble())).toFloat() * localRadius, y = center.y + sin(Math.toRadians(angle.toDouble())).toFloat() * localRadius ), strokeWidth = if (i % 5 == 0) 6f else 2f ) // 绘制数字 if (i % 5 == 0) { val angleRadians = Math.toRadians(angle.toDouble() - 90) val text = AnnotatedString( (i / 5).let { if (it == 0) 12 else it }.toString(), SpanStyle(fontSize = 24.sp) ) val textLayoutResult = textMeasurer.measure(text) val textRadius = radius - 40.dp.toPx() val (degreeX, degreeY) = polarToCartesian(center, textRadius, angleRadians) drawText( textLayoutResult, color = colors.fontColor, topLeft = Offset( x = degreeX - textLayoutResult.size.width / 2, y = degreeY - textLayoutResult.size.height / 2 ) ) } } } // 绘制指针 private fun DrawScope.drawClockIndicators( radius: Float, center: Offset, currentTime: Long, zoneId: ZoneId, colors: ClockColors ) { val time = Instant.ofEpochMilli(currentTime).atZone(zoneId).toLocalTime() val hours = time.hour % 12 val minutes = time.minute val seconds = time.second val hourAngle = (hours + minutes / 60f) * 30f - 90 val minuteAngle = minutes * 6f - 90 val secondAngle = seconds * 6f - 90 // 绘制时针 drawLine( color = colors.fontColor, start = center, end = Offset( x = center.x + cos(Math.toRadians(hourAngle.toDouble())).toFloat() * radius / 2, y = center.y + sin(Math.toRadians(hourAngle.toDouble())).toFloat() * radius / 2 ), strokeWidth = 10f, cap = StrokeCap.Round ) // 绘制分针 drawLine( color = colors.fontColor, start = center, end = Offset( x = center.x + cos(Math.toRadians(minuteAngle.toDouble())).toFloat() * radius / 1.6f, y = center.y + sin(Math.toRadians(minuteAngle.toDouble())).toFloat() * radius / 1.6f ), strokeWidth = 6f, cap = StrokeCap.Round ) // 绘制秒针 drawLine( color = Color.Red, start = center, end = Offset( x = center.x + cos(Math.toRadians(secondAngle.toDouble())).toFloat() * radius / 1.2f, y = center.y + sin(Math.toRadians(secondAngle.toDouble())).toFloat() * radius / 1.2f ), strokeWidth = 2f ) } // 绘制指针锁 private fun DrawScope.drawIndicatorsLock(colors: ClockColors) { drawCircle(colors.fontColor, 5.dp.toPx()) drawCircle(colors.containerColor, 3.dp.toPx()) } private data class ClockColors( val containerColor: Color, val fontColor: Color, val scalePrimaryColor: Color, val scaleSecondaryColor: Color ) private val MaterialTheme.clockColorScheme: ClockColors @Composable get() = ClockColors( containerColor = colorScheme.onBackground, fontColor = colorScheme.onPrimary, scalePrimaryColor = colorScheme.onSecondary, scaleSecondaryColor = colorScheme.outline )
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/components/Clock.kt
2270162294
package top.chengdongqing.weui.feature.samples.data import top.chengdongqing.weui.feature.samples.components.OrgNode internal object GovernmentDataProvider { val governmentMap = listOf( OrgNode( "全国人民代表大会", listOf( OrgNode( "国务院", listOf( OrgNode( "外交部", listOf( OrgNode( "礼宾司", listOf( OrgNode("接待处"), OrgNode("国际会议处"), OrgNode("外交礼宾处"), OrgNode("国际礼宾处"), OrgNode("国事访问处") ) ), OrgNode("国际司"), OrgNode("新闻司"), OrgNode("驻外使领馆") ) ), OrgNode( "财政部", listOf( OrgNode("国家税务总局"), OrgNode("国家统计局"), OrgNode("中国人民银行"), OrgNode("中国外汇管理局"), OrgNode("中国国家发展和改革委员会"), OrgNode("中国证券监督管理委员会"), OrgNode("中国银行保险监督管理委员会") ) ), OrgNode( "民政部", listOf( OrgNode("民政局"), OrgNode("社会组织管理局"), OrgNode("慈善事业促进会") ) ), OrgNode( "工信部", listOf( OrgNode("工业司"), OrgNode("信息化和软件服务业司"), OrgNode("国际合作司"), OrgNode("电子政务和信息化促进司"), OrgNode("电子商务和信息化促进司") ) ), OrgNode( "教育部", listOf( OrgNode("教育司"), OrgNode("科技发展中心"), OrgNode("考试中心"), OrgNode("留学服务中心"), OrgNode("职业教育与成人教育司") ) ), OrgNode( "公安部", listOf( OrgNode("治安管理局"), OrgNode("移民管理局"), OrgNode("消防局"), OrgNode("刑事侦查局"), OrgNode("交通管理局") ) ), OrgNode( "海关总署", listOf( OrgNode("海关监管局"), OrgNode("海关技术监管局"), OrgNode("进出口税务局"), OrgNode("口岸管理局"), OrgNode("综合管理局") ) ), OrgNode( "农业农村部", listOf( OrgNode("农业发展局"), OrgNode("农村经济管理局"), OrgNode("农产品质量安全局"), OrgNode("农村改革局"), OrgNode("国土资源局") ) ), OrgNode( "退役军人事务部", listOf( OrgNode("军人离退休服务管理局"), OrgNode("退役军人事务局"), OrgNode("军休服务保障局"), OrgNode("社会保障保险局"), OrgNode("就业安置服务局") ) ) ) ), OrgNode( "最高人民法院", listOf( OrgNode("审判委员会"), OrgNode("法官学院"), OrgNode("执行局"), OrgNode("研究室"), OrgNode("信息中心") ) ), OrgNode( "最高人民检察院", listOf( OrgNode("检察委员会"), OrgNode("反贪局"), OrgNode("刑事执行局"), OrgNode("国家检察官学院"), OrgNode("国家检察院检察技术中心") ) ), OrgNode( "中央军事委员会", listOf( OrgNode("军委联合参谋部"), OrgNode("军委政治工作部"), OrgNode("军委后勤保障部"), OrgNode("军委装备发展部"), OrgNode("军委训练管理部") ) ) ) ) ) }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/data/GovernmentDataProvider.kt
2405549660
package top.chengdongqing.weui.feature.samples.data internal object CityDataProvider { val cities = listOf( "北京", "天津", "上海", "重庆", "哈尔滨", "长春", "沈阳", "呼和浩特", "石家庄", "乌鲁木齐", "兰州", "西宁", "西安", "银川", "郑州", "济南", "太原", "合肥", "武汉", "长沙", "南京", "成都", "贵阳", "昆明", "南宁", "拉萨", "杭州", "南昌", "广州", "福州", "海口", "潍坊", "厦门", "邯郸", "洛阳", "秦皇岛", "吉林", "贵港", "湛江", "邵阳", "许昌", "丹东", "包头", "济源", "常德", "邢台", "阳泉", "东营", "绵阳", "九江", "廊坊", "齐齐哈尔", "唐山", "莆田", "汕头", "常州", "岳阳", "漳州", "柳州", "铁岭", "阜阳", "徐州", "湘潭", "茂名", "大连", "揭阳", "南通", "东莞", "宁波", "泉州", "咸阳", "盐城", "株洲", "赣州", "泰州", "荆州", "绍兴", "梅州", "宜昌", "扬州", "湖州", "渭南", "宿迁", "中山", "临沂", "南平", "信阳", "珠海", "潮州", "淄博", "抚顺", "佛山", "玉林", "新乡", "日照", "漯河", "绥化", "菏泽", "马鞍山", "黄石", "阜新", "威海", "清远", "*测试其它专用*" ) }
WeUI/feature/samples/src/main/kotlin/top/chengdongqing/weui/feature/samples/data/CityDataProvider.kt
19739392
package top.chengdongqing.weui.feature.system 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("top.chengdongqing.weui.feature.system.test", appContext.packageName) } }
WeUI/feature/system/src/androidTest/java/top/chengdongqing/weui/feature/system/ExampleInstrumentedTest.kt
593513332
package top.chengdongqing.weui.feature.system 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) } }
WeUI/feature/system/src/test/java/top/chengdongqing/weui/feature/system/ExampleUnitTest.kt
3914247394
package top.chengdongqing.weui.feature.system.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.system.address.AddressFormScreen import top.chengdongqing.weui.feature.system.screens.CalendarEventsScreen import top.chengdongqing.weui.feature.system.screens.ClipboardScreen import top.chengdongqing.weui.feature.system.screens.ContactsScreen import top.chengdongqing.weui.feature.system.screens.DatabaseScreen import top.chengdongqing.weui.feature.system.screens.DeviceInfoScreen import top.chengdongqing.weui.feature.system.screens.DownloaderScreen import top.chengdongqing.weui.feature.system.screens.InstalledAppsScreen import top.chengdongqing.weui.feature.system.screens.KeyboardScreen import top.chengdongqing.weui.feature.system.screens.NotificationScreen import top.chengdongqing.weui.feature.system.screens.SmsScreen import top.chengdongqing.weui.feature.system.screens.SystemStatusScreen fun NavGraphBuilder.addSystemGraph(navController: NavController) { composable("device_info") { DeviceInfoScreen() } composable("system_status") { SystemStatusScreen() } composable("installed_apps") { InstalledAppsScreen() } composable("downloader") { DownloaderScreen() } composable("database") { DatabaseScreen { addressId -> navController.navigate(buildString { append("address_form") if (addressId != null) { append("?id=${addressId}") } }) } } composable("address_form?id={id}") { val id = it.arguments?.getString("id")?.toInt() AddressFormScreen(navController, id) } composable("clipboard") { ClipboardScreen() } composable("contacts") { ContactsScreen() } composable("sms") { SmsScreen() } composable("keyboard") { KeyboardScreen() } composable("calendar_events") { CalendarEventsScreen() } composable("notification") { NotificationScreen() } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/navigation/SystemGraph.kt
1941524973
package top.chengdongqing.weui.feature.system.screens import android.Manifest import android.content.ContentValues import android.content.Context import android.provider.CalendarContract import android.text.format.DateFormat import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.picker.WeDatePicker import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import java.time.LocalDate import java.time.ZoneId import java.util.Date import java.util.TimeZone @Composable fun CalendarEventsScreen() { WeScreen(title = "CalendarEvents", description = "日历事件") { AddCalendarEvent() Spacer(modifier = Modifier.height(20.dp)) CalendarEvents() } } @OptIn(ExperimentalPermissionsApi::class) @Composable fun AddCalendarEvent() { val context = LocalContext.current val calendarPermissionState = rememberPermissionState(Manifest.permission.WRITE_CALENDAR) var title by remember { mutableStateOf("") } val toast = rememberToastState() WeInput( value = title, label = "事件名称", placeholder = "请输入" ) { title = it } var date by remember { mutableStateOf<LocalDate?>(null) } var visible by remember { mutableStateOf(false) } WeInput( value = date?.toString(), label = "事件日期", placeholder = "请选择", disabled = true, onClick = { visible = true } ) WeDatePicker( visible, value = date, start = LocalDate.now(), end = LocalDate.now().plusYears(3), onCancel = { visible = false }, onChange = { date = it } ) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "添加日历事件") { if (calendarPermissionState.status.isGranted) { if (title.isNotEmpty() && date != null) { val values = ContentValues().apply { put(CalendarContract.Events.TITLE, title) val mills = date!!.atTime(10, 0) .atZone(ZoneId.systemDefault()).toInstant() .toEpochMilli() put(CalendarContract.Events.DTSTART, mills) put(CalendarContract.Events.DTEND, mills) put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id) put(CalendarContract.Events.CALENDAR_ID, 1) } context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values) toast.show("已添加", icon = ToastIcon.SUCCESS) } else { toast.show("请正确输入", ToastIcon.FAIL) } } else { calendarPermissionState.launchPermissionRequest() } } } @OptIn(ExperimentalPermissionsApi::class) @Composable fun CalendarEvents() { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val calendarPermissionState = rememberPermissionState(Manifest.permission.READ_CALENDAR) var loading by remember { mutableStateOf(false) } var events by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) } var visible by remember { mutableStateOf(false) } WeButton(text = "读取日历事件", type = ButtonType.PLAIN, loading = loading) { if (calendarPermissionState.status.isGranted) { coroutineScope.launch { loading = true events = loadCalendarEvents(context) loading = false visible = true } } else { calendarPermissionState.launchPermissionRequest() } } WePopup(visible, title = "日历事件", onClose = { visible = false }) { LazyColumn( modifier = Modifier .cartList() .fillMaxHeight(0.5f) ) { items(events) { WeCardListItem(label = it.first, value = it.second) } if (events.isEmpty()) { item { WeLoadMore( type = LoadMoreType.EMPTY_DATA, modifier = Modifier.height(300.dp) ) } } } } } private suspend fun loadCalendarEvents(context: Context): List<Pair<String, String>> = withContext(Dispatchers.IO) { val events = mutableListOf<Pair<String, String>>() context.contentResolver.query( CalendarContract.Events.CONTENT_URI, arrayOf( CalendarContract.Events._ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART ), null, null, CalendarContract.Events.DTSTART + " DESC" )?.use { cursor -> val titleCol = cursor.getColumnIndex(CalendarContract.Events.TITLE) val startCol = cursor.getColumnIndex(CalendarContract.Events.DTSTART) while (cursor.moveToNext()) { val title = cursor.getString(titleCol) val start = DateFormat.format("yyyy年MM月dd日", Date(cursor.getLong(startCol))).toString() events.add(Pair(title, start)) } } events }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/CalendarEvents.kt
4022789519
package top.chengdongqing.weui.feature.system.screens import android.content.Context import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.SetupStatusBarStyle @Composable fun SystemStatusScreen() { WeScreen(title = "SystemStatus", description = "系统状态,动态更新", scrollEnabled = false) { LazyColumn(modifier = Modifier.cartList()) { item { NetworkInfoRows() WeCardListItem("系统主题", if (isSystemInDarkTheme()) "深色" else "浅色") } } Spacer(modifier = Modifier.height(40.dp)) StatusBarAction() } } @Composable private fun NetworkInfoRows() { val network = rememberNetworkObserver() WeCardListItem("网络类型", network.type) WeCardListItem("VPN", if (network.isVpnConnected) "已启用" else "未启用") } @Composable private fun rememberNetworkObserver(): NetworkInfo { val context = LocalContext.current val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager var networkType by remember { mutableStateOf(getNetworkType(connectivityManager)) } var isVpnConnected by remember { mutableStateOf(isVpnConnected(connectivityManager)) } DisposableEffect(Unit) { val callbackHandler = object : ConnectivityManager.NetworkCallback() { override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities ) { getNetworkStatus() } override fun onLost(network: Network) { getNetworkStatus() } private fun getNetworkStatus() { networkType = getNetworkType(connectivityManager) isVpnConnected = isVpnConnected(connectivityManager) } } connectivityManager.registerDefaultNetworkCallback(callbackHandler) onDispose { connectivityManager.unregisterNetworkCallback(callbackHandler) } } return NetworkInfo(networkType, isVpnConnected) } @Composable private fun StatusBarAction() { var isDark by remember { mutableStateOf(true) } SetupStatusBarStyle(isDark) WeButton(text = "切换状态栏样式", type = ButtonType.PLAIN) { isDark = !isDark } } private data class NetworkInfo( val type: String, val isVpnConnected: Boolean ) private fun getNetworkType(connectivityManager: ConnectivityManager): String { val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) return capabilities?.let { when { it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "WiFi" it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "移动网络" it.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> "蓝牙" it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "以太网" it.hasTransport(NetworkCapabilities.TRANSPORT_USB) -> "USB" else -> "未知网络" } } ?: "网络未连接" } private fun isVpnConnected(connectivityManager: ConnectivityManager): Boolean { return connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) ?: false }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/SystemStatus.kt
3017580751
package top.chengdongqing.weui.feature.system.screens import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.provider.Telephony.Sms import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.rememberToastState @Composable fun SmsScreen() { WeScreen(title = "SMS", description = "短信") { WritingSms() Spacer(modifier = Modifier.height(20.dp)) ReadingSms() } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun WritingSms() { val context = LocalContext.current val smsPermissionState = rememberPermissionState(Manifest.permission.SEND_SMS) var number by remember { mutableStateOf("") } var content by remember { mutableStateOf("") } val toast = rememberToastState() WeInput( value = number, placeholder = "请输入号码", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone) ) { number = it } WeTextarea(content, placeholder = "请输入内容", max = 200) { content = it } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "发送短信") { if (smsPermissionState.status.isGranted) { if (number.isEmpty() || content.isEmpty()) { toast.show("请正确输入") } else { val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:$number")).apply { putExtra("sms_body", content) } context.startActivity(intent) } } else { smsPermissionState.launchPermissionRequest() } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun ReadingSms() { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val readSmsPermissionState = rememberPermissionState(Manifest.permission.READ_SMS) var loading by remember { mutableStateOf(false) } var messages by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) } var visible by remember { mutableStateOf(false) } WeButton(text = "读取短信", type = ButtonType.PLAIN, loading = loading) { if (readSmsPermissionState.status.isGranted) { coroutineScope.launch { loading = true messages = loadSmsMessages(context) loading = false visible = true } } else { readSmsPermissionState.launchPermissionRequest() } } WePopup(visible, title = "短信", onClose = { visible = false }) { LazyColumn(modifier = Modifier .cartList() .fillMaxHeight(0.5f)) { items(messages) { WeCardListItem(label = it.first, value = it.second) } if (messages.isEmpty()) { item { WeLoadMore( type = LoadMoreType.EMPTY_DATA, modifier = Modifier.height(300.dp) ) } } } } } private suspend fun loadSmsMessages(context: Context): List<Pair<String, String>> = withContext(Dispatchers.IO) { val messages = mutableListOf<Pair<String, String>>() context.contentResolver.query( Sms.Inbox.CONTENT_URI, arrayOf( Sms.Inbox._ID, Sms.Inbox.ADDRESS, Sms.Inbox.BODY, Sms.Inbox.DATE ), null, null, null )?.use { cursor -> val addressIndex = cursor.getColumnIndex(Sms.Inbox.ADDRESS) val bodyIndex = cursor.getColumnIndex(Sms.Inbox.BODY) while (cursor.moveToNext()) { val item = Pair(cursor.getString(addressIndex), cursor.getString(bodyIndex)) messages.add(item) } } messages }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Sms.kt
3716380704
package top.chengdongqing.weui.feature.system.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.core.utils.rememberKeyboardHeight @Composable fun KeyboardScreen() { WeScreen(title = "Keyboard", description = "键盘") { val keyboardController = LocalSoftwareKeyboardController.current val keyboardHeight = rememberKeyboardHeight() val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { focusRequester.requestFocus() } WeInput( value = null, placeholder = "键盘高度: ${keyboardHeight.value.format()}(dp)", modifier = Modifier.focusRequester(focusRequester) ) Spacer(modifier = Modifier.height(40.dp)) WeButton(text = "弹出键盘") { keyboardController?.show() } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "收起键盘", type = ButtonType.PLAIN) { keyboardController?.hide() } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Keyboard.kt
1226039390
package top.chengdongqing.weui.feature.system.screens import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.dialog.rememberDialogState import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.utils.getClipboardData import top.chengdongqing.weui.core.utils.setClipboardData @Composable fun ClipboardScreen() { WeScreen(title = "Clipboard", description = "剪贴板") { var data by remember { mutableStateOf("") } val context = LocalContext.current val dialog = rememberDialogState() val toast = rememberToastState() WeTextarea(data, placeholder = "请输入内容", max = 200, topBorder = true) { data = it } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "设置剪贴板内容") { if (data.isEmpty()) { toast.show("内容不能为空", ToastIcon.FAIL) } else { context.setClipboardData(data) toast.show("已复制", ToastIcon.SUCCESS) } } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "读取剪贴板内容", type = ButtonType.PLAIN) { context.getClipboardData()?.let { dialog.show( title = "剪贴板内容", content = it, onCancel = null ) } ?: toast.show("获取失败", ToastIcon.FAIL) } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Clipboard.kt
1317890653
package top.chengdongqing.weui.feature.system.screens import android.bluetooth.BluetoothManager import android.content.Context import android.content.res.Configuration import android.location.LocationManager import android.net.wifi.WifiManager import android.nfc.NfcManager import android.os.Build import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.core.utils.rememberBatteryInfo import top.chengdongqing.weui.core.utils.rememberStatusBarHeight @Composable fun DeviceInfoScreen() { WeScreen(title = "DeviceInfo", description = "设备信息", scrollEnabled = false) { val context = LocalContext.current val density = LocalDensity.current val configuration = LocalConfiguration.current val statusBarHeight = rememberStatusBarHeight() val battery = rememberBatteryInfo() val deviceInfoItems = remember { mutableListOf( Pair("设备品牌", Build.BRAND), Pair("设备型号", Build.MODEL), Pair("系统版本", "Android ${Build.VERSION.RELEASE}"), Pair("系统语言", configuration.locales.toLanguageTags()), Pair("字体缩放", configuration.fontScale.toString()), Pair("电量", "${battery.level}%"), Pair("充电中", battery.isCharging.format()) ).apply { addScreenItems(context, density, configuration, statusBarHeight) addHardwareItems(context) } } LazyColumn(modifier = Modifier.cartList()) { items(deviceInfoItems) { WeCardListItem(it.first, it.second) } } } } private fun MutableList<Pair<String, String>>.addScreenItems( context: Context, density: Density, configuration: Configuration, statusBarHeight: Dp ) { add( Pair( "屏幕宽高", "${configuration.screenWidthDp}x${configuration.screenHeightDp}(dp)" ) ) val displayMetrics = context.resources.displayMetrics add( Pair( "屏幕分辨率", "${displayMetrics.widthPixels}x${displayMetrics.heightPixels}(px)" ) ) add(Pair("屏幕像素比", density.density.toString())) val isLandscape = configuration.orientation == Configuration.ORIENTATION_LANDSCAPE add(Pair("屏幕方向", if (isLandscape) "横屏" else "竖屏")) add(Pair("状态栏高度", "${statusBarHeight.value.format()}(dp)")) } private fun MutableList<Pair<String, String>>.addHardwareItems(context: Context) { (context.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.let { add(Pair("WiFi", it.isWifiEnabled.formatEnable())) } (context.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter?.let { add(Pair("蓝牙", it.isEnabled.formatEnable())) } (context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager)?.let { val isGpsEnabled = it.isProviderEnabled(LocationManager.GPS_PROVIDER) add(Pair("GPS", isGpsEnabled.formatEnable())) } (context.getSystemService(Context.NFC_SERVICE) as? NfcManager)?.defaultAdapter?.let { add(Pair("NFC", it.isEnabled.formatEnable())) } } private fun Boolean.formatEnable() = this.format("开", "关")
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/DeviceInfo.kt
964875011
package top.chengdongqing.weui.feature.system.screens import android.Manifest import android.content.Context import android.content.Intent import android.net.Uri import android.provider.CallLog import android.provider.ContactsContract import android.text.format.DateFormat import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.cardlist.cartList import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.utils.DefaultDateTimeFormatter import top.chengdongqing.weui.core.utils.formatChinese import java.util.Date import kotlin.time.Duration.Companion.seconds @Composable fun ContactsScreen() { WeScreen( title = "Contacts", description = "拨号与通讯录", verticalArrangement = Arrangement.spacedBy(20.dp) ) { PhoneCall() Spacer(modifier = Modifier.height(20.dp)) PhoneContactList() PhoneCallLogList() } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun PhoneCall() { val context = LocalContext.current val callPermissionState = rememberPermissionState(Manifest.permission.CALL_PHONE) var number by remember { mutableStateOf("") } val toast = rememberToastState() WeInput( value = number, placeholder = "请输入号码", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone) ) { number = it } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround ) { WeButton( text = "打电话(直接拨打)", type = ButtonType.PLAIN, size = ButtonSize.MEDIUM ) { if (callPermissionState.status.isGranted) { if (number.isEmpty()) { toast.show("请输入号码") } else { val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:${number}")) context.startActivity(intent) } } else { callPermissionState.launchPermissionRequest() } } Spacer(modifier = Modifier.width(16.dp)) WeButton( text = "打电话(系统拨号盘)", type = ButtonType.PLAIN, size = ButtonSize.MEDIUM ) { if (number.isEmpty()) { toast.show("请输入号码") } else { val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:${number}")) context.startActivity(intent) } } } } @OptIn(ExperimentalPermissionsApi::class) @Composable private fun PhoneContactList() { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val contactsPermissionState = rememberPermissionState(Manifest.permission.READ_CONTACTS) var loading by remember { mutableStateOf(false) } var contacts by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) } var visible by remember { mutableStateOf(false) } WeButton(text = "读取通讯录", loading = loading) { if (contactsPermissionState.status.isGranted) { coroutineScope.launch { loading = true contacts = loadContacts(context).map { it.first to it.second.joinToString("\n") } loading = false visible = true } } else { contactsPermissionState.launchPermissionRequest() } } WePopup(visible, title = "通讯录", onClose = { visible = false }) { LazyColumn( modifier = Modifier .cartList() .fillMaxHeight(0.5f) ) { items(contacts) { WeCardListItem(label = it.first, value = it.second) } if (contacts.isEmpty()) { item { WeLoadMore( type = LoadMoreType.EMPTY_DATA, modifier = Modifier.height(300.dp) ) } } } } } private suspend fun loadContacts(context: Context): (List<Pair<String, List<String>>>) = withContext(Dispatchers.IO) { val contacts = mutableListOf<Pair<String, String>>() context.contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null )?.use { cursor -> val nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME) val numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) while (cursor.moveToNext()) { val name = cursor.getString(nameIndex) val number = cursor.getString(numberIndex) contacts.add(Pair(name, number)) } } contacts.groupBy({ it.first }, { it.second }).map { Pair(it.key, it.value) } } @OptIn(ExperimentalPermissionsApi::class) @Composable fun PhoneCallLogList() { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val callLogPermissionState = rememberPermissionState(Manifest.permission.READ_CALL_LOG) var loading by remember { mutableStateOf(false) } var logs by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) } var visible by remember { mutableStateOf(false) } WeButton(text = "读取通话记录", type = ButtonType.PLAIN, loading = loading) { if (callLogPermissionState.status.isGranted) { coroutineScope.launch { loading = true logs = loadCallLogs(context).map { it.first to it.second.joinToString("\n") } loading = false visible = true } } else { callLogPermissionState.launchPermissionRequest() } } WePopup(visible, title = "通话记录", onClose = { visible = false }) { LazyColumn( modifier = Modifier .cartList() .fillMaxHeight(0.5f) ) { items(logs) { WeCardListItem(label = it.first, value = it.second) } if (logs.isEmpty()) { item { WeLoadMore( type = LoadMoreType.EMPTY_DATA, modifier = Modifier.height(300.dp) ) } } } } } private suspend fun loadCallLogs(context: Context): (List<Pair<String, List<String>>>) = withContext(Dispatchers.IO) { val logs = mutableListOf<Pair<String, List<String>>>() context.contentResolver.query( CallLog.Calls.CONTENT_URI, null, null, null, null )?.use { cursor -> val numberIndex = cursor.getColumnIndex(CallLog.Calls.NUMBER) val dateIndex = cursor.getColumnIndex(CallLog.Calls.DATE) val durationIndex = cursor.getColumnIndex(CallLog.Calls.DURATION) val typeIndex = cursor.getColumnIndex(CallLog.Calls.TYPE) while (cursor.moveToNext()) { val number = cursor.getString(numberIndex) val date = DateFormat.format( DefaultDateTimeFormatter, Date(cursor.getLong(dateIndex)) ).toString() val type = when (cursor.getInt(typeIndex)) { CallLog.Calls.OUTGOING_TYPE -> "呼出" CallLog.Calls.INCOMING_TYPE -> "呼入" CallLog.Calls.MISSED_TYPE -> "未接通" else -> "未知" } val duration = cursor.getInt(durationIndex) logs.add( Pair( number, listOf(date, type + duration.seconds.formatChinese()) ) ) } } logs }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Contacts.kt
1730745173
package top.chengdongqing.weui.feature.system.screens import android.annotation.SuppressLint import android.app.DownloadManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.Uri import android.os.Environment import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.showToast @Composable fun DownloaderScreen() { WeScreen(title = "Downloader", description = "系统下载") { val context = LocalContext.current var name by remember { mutableStateOf("su7.jpg") } var url by remember { mutableStateOf("https://s1.xiaomiev.com/activity-outer-assets/web/home/section1.jpg") } WeInput(value = name, label = "文件名称", placeholder = "请输入") { name = it } WeTextarea(value = url, label = "下载地址", placeholder = "请输入") { url = it } Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "下载") { download(context, name, url) } } } private fun download(context: Context, name: String, url: String) { val request = DownloadManager.Request(Uri.parse(url)).apply { setTitle(name) setDescription(url) // 设置保存位置 setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name) // 设置网络类型为任何网络 setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE) // 设置通知栏是否可见 setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) } // 加入下载队列 val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager val downloadId = downloadManager.enqueue(request) context.showToast("开始下载") // 注册广播接收器 val receiver = DownloadBroadcastReceiver(downloadManager, downloadId) val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE) ContextCompat.registerReceiver( context, receiver, filter, ContextCompat.RECEIVER_EXPORTED ) } private class DownloadBroadcastReceiver( val downloadManager: DownloadManager, val downloadId: Long ) : BroadcastReceiver() { @SuppressLint("Range") override fun onReceive(context: Context, intent: Intent) { val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) if (downloadId == id) { val query = DownloadManager.Query().setFilterById(id) val cursor = downloadManager.query(query) if (cursor.moveToFirst()) { val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) if (status == DownloadManager.STATUS_SUCCESSFUL) { context.showToast("下载完成") val uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)) if (uri.endsWith(".apk")) { installApk(context, uri) } } } cursor.close() } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Downloader.kt
910441311
package top.chengdongqing.weui.feature.system.screens import android.content.ContentValues import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.core.graphics.drawable.toBitmap import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.formatFileSize import top.chengdongqing.weui.core.utils.formatTime import top.chengdongqing.weui.core.utils.openFile import top.chengdongqing.weui.core.utils.showToast import java.io.File @Composable fun InstalledAppsScreen() { WeScreen( title = "InstalledApps", description = "已安装的应用", padding = PaddingValues(0.dp), scrollEnabled = false ) { val context = LocalContext.current val appList = rememberInstalledApps() LazyColumn(verticalArrangement = Arrangement.spacedBy(20.dp)) { item { if (appList.isNotEmpty()) { ActionBar(context) } else { WeLoadMore() } Spacer(modifier = Modifier.height(20.dp)) } items(appList) { app -> AppItem(app, context) } } } } @Composable private fun ActionBar(context: Context) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceAround ) { WeButton( text = "打开地图", type = ButtonType.PLAIN, size = ButtonSize.MEDIUM, width = 140.dp ) { val latitude = "37.7749" val longitude = "-122.4194" val intent = Intent(Intent.ACTION_VIEW, Uri.parse("geo:$latitude,$longitude")) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } else { context.showToast("未安装地图应用") } } WeButton( text = "打开浏览器", type = ButtonType.PLAIN, size = ButtonSize.MEDIUM, width = 140.dp ) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://weui.io")) context.startActivity(intent) } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun AppItem(app: AppItem, context: Context) { Row(verticalAlignment = Alignment.CenterVertically) { Column( modifier = Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally ) { Box(modifier = Modifier.size(56.dp)) { produceState<ImageBitmap?>(initialValue = null) { value = withContext(Dispatchers.IO) { app.icon.toBitmap().asImageBitmap() } }.value?.let { Image( bitmap = it, contentDescription = null, modifier = Modifier.matchParentSize(), contentScale = ContentScale.Crop ) } } Text( app.name, color = MaterialTheme.colorScheme.onPrimary, textAlign = TextAlign.Center ) Text( "v${app.versionName}", color = MaterialTheme.colorScheme.onSecondary, fontSize = 12.sp, textAlign = TextAlign.Center ) } Spacer(modifier = Modifier.width(20.dp)) Column(modifier = Modifier.weight(2f)) { Text( buildString { appendLine("包名: ${app.packageName}") appendLine("最后更新: ${app.lastModified}") append("APK大小: ${app.apkSize}") }, color = MaterialTheme.colorScheme.onPrimary, fontSize = 12.sp ) Spacer(modifier = Modifier.height(10.dp)) FlowRow( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp) ) { WeButton(text = "打开APP", size = ButtonSize.SMALL) { val intent = context.packageManager .getLaunchIntentForPackage(app.packageName) context.startActivity(intent) } WeButton( text = "复制到下载目录", type = ButtonType.PLAIN, size = ButtonSize.SMALL ) { fileToPublicDirectory( context, app.apkPath, "${app.name}-v${app.versionName}.apk" ) } WeButton( text = "安装APK", type = ButtonType.PLAIN, size = ButtonSize.SMALL ) { installApk(context, app.apkPath) } } } } } fun installApk(context: Context, apkPath: String) { val tempFile = File.createTempFile("app_", ".apk").apply { deleteOnExit() } File(apkPath).copyTo(tempFile, true) context.openFile(tempFile, "application/vnd.android.package-archive") } private fun fileToPublicDirectory( context: Context, sourceFilePath: String, destinationFileName: String, targetDirectory: String = Environment.DIRECTORY_DOWNLOADS ) { val sourceFile = File(sourceFilePath) val resolver = context.contentResolver context.showToast("开始复制") try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { val values = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, destinationFileName) put( MediaStore.MediaColumns.MIME_TYPE, "application/vnd.android.package-archive" ) put(MediaStore.MediaColumns.RELATIVE_PATH, targetDirectory) } resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)?.let { resolver.openOutputStream(it)?.use { outputStream -> sourceFile.inputStream().use { input -> input.copyTo(outputStream) context.showToast("已复制") } } } } else { val destinationFile = File( Environment.getExternalStoragePublicDirectory(targetDirectory), destinationFileName ) sourceFile.inputStream().use { input -> destinationFile.outputStream().use { output -> input.copyTo(output) context.showToast("复制成功") } } } } catch (e: Exception) { context.showToast("复制失败: ${e.message}") } } @Composable private fun rememberInstalledApps(): List<AppItem> { val context = LocalContext.current val packageManager = context.packageManager val appList by produceState(initialValue = emptyList()) { value = withContext(Dispatchers.IO) { val intent = Intent(Intent.ACTION_MAIN, null).apply { addCategory(Intent.CATEGORY_LAUNCHER) } packageManager.queryIntentActivities(intent, 0).map { resolveInfo -> val name = resolveInfo.loadLabel(packageManager).toString() val icon = resolveInfo.loadIcon(packageManager) val packageName = resolveInfo.activityInfo.packageName val packageInfo = packageManager.getPackageInfo(packageName, 0) val versionName = packageInfo.versionName val lastModified = formatTime(packageInfo.lastUpdateTime) val apkPath = packageInfo.applicationInfo.sourceDir val apkSize = formatFileSize(File(apkPath)) AppItem( name, icon, packageName, versionName, lastModified, apkPath, apkSize ) }.sortedByDescending { it.lastModified } } } return appList } private data class AppItem( val name: String, val icon: Drawable, val packageName: String, val versionName: String, val lastModified: String, val apkPath: String, val apkSize: String )
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/InstalledApps.kt
2389981206
package top.chengdongqing.weui.feature.system.screens import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.theme.R import top.chengdongqing.weui.core.utils.isTrue @OptIn(ExperimentalPermissionsApi::class) @Composable fun NotificationScreen() { WeScreen(title = "Notification", description = "系统通知") { val context = LocalContext.current val permissionState = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { rememberPermissionState(permission = Manifest.permission.POST_NOTIFICATIONS) } else { null } val channelId = "test_channel_id" val channelName = "Test Channel Name" WeButton(text = "发送通知") { if (permissionState?.status?.isGranted.isTrue() || permissionState == null) { createNotificationChannel(context, channelId, channelName) sendNotification(context, channelId, "测试标题", "测试内容") } else { permissionState.launchPermissionRequest() } } } } @SuppressLint("MissingPermission") private fun sendNotification(context: Context, channelId: String, title: String, content: String) { val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_logo) // 设置通知小图标 .setContentTitle(title) // 设置通知标题 .setContentText(content) // 设置通知内容 .setPriority(NotificationCompat.PRIORITY_DEFAULT) NotificationManagerCompat.from(context).apply { notify(System.currentTimeMillis().toInt(), builder.build()) } } private fun createNotificationChannel(context: Context, channelId: String, channelName: String) { val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(channelId, channelName, importance).apply { description = "测试通道" } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Notification.kt
3038751510
package top.chengdongqing.weui.feature.system.screens import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.feature.system.address.AddressList @Composable fun DatabaseScreen(onNavigateToAddressForm: (id: Int?) -> Unit) { WeScreen( title = "Database", description = "数据库(SQLite+Room)", padding = PaddingValues(0.dp), scrollEnabled = false ) { AddressList(onNavigateToAddressForm) } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/screens/Database.kt
199308148
package top.chengdongqing.weui.feature.system.address.repository import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [Address::class], version = 1) abstract class AddressDatabase : RoomDatabase() { abstract fun addressDao(): AddressDao companion object { /*@Volatile关键字用于标记INSTANCE变量,确保其值不会被本地线程缓存,所有的读写都直接在主内存中进行。 这意味着,当一个线程修改了INSTANCE变量的值,这个改变对其他所有线程来说是立即可见的。 这有助于保持INSTANCE的值在多线程环境中的一致性和可见性。*/ @Volatile private var INSTANCE: AddressDatabase? = null fun getInstance(context: Context): AddressDatabase { synchronized(this) { var instance = INSTANCE if (instance == null) { instance = Room.databaseBuilder( context.applicationContext, AddressDatabase::class.java, "address_database" ) //.fallbackToDestructiveMigration() // 如果发现版本不一致(即实体结构与数据库中的结构不符),将重新创建数据库表,这意味着原有数据会丢失 .build() INSTANCE = instance } return instance } } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/repository/AddressDatabase.kt
3819345692
package top.chengdongqing.weui.feature.system.address.repository import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update import kotlinx.coroutines.flow.Flow @Dao interface AddressDao { @get:Query("SELECT * FROM address") val addressList: Flow<List<Address>> @Query("select * from address where id = :id") suspend fun loadById(id: Int): Address? @Insert suspend fun insert(address: Address) @Update suspend fun update(address: Address) @Delete suspend fun delete(address: Address) }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/repository/AddressDao.kt
3587544259
package top.chengdongqing.weui.feature.system.address.repository import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.withContext class AddressRepositoryImpl(context: Context) : AddressRepository { private val database by lazy { AddressDatabase.getInstance(context) } override val addressList: Flow<List<Address>> get() = database.addressDao().addressList override suspend fun loadById(id: Int): Address? { return withContext(Dispatchers.IO) { database.addressDao().loadById(id) } } override suspend fun insert(address: Address) { withContext(Dispatchers.IO) { database.addressDao().insert(address) } } override suspend fun update(address: Address) { withContext(Dispatchers.IO) { database.addressDao().update(address) } } override suspend fun delete(address: Address) { withContext(Dispatchers.IO) { database.addressDao().delete(address) } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/repository/AddressRepositoryImpl.kt
3014240555
package top.chengdongqing.weui.feature.system.address.repository import kotlinx.coroutines.flow.Flow interface AddressRepository { val addressList: Flow<List<Address>> suspend fun loadById(id: Int): Address? suspend fun insert(address: Address) suspend fun update(address: Address) suspend fun delete(address: Address) }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/repository/AddressRepository.kt
2959766835
package top.chengdongqing.weui.feature.system.address.repository import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "address") data class Address( @PrimaryKey(autoGenerate = true) val id: Int = 0, val name: String, val phone: String, @ColumnInfo(name = "address_detail") val addressDetail: String )
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/repository/Address.kt
4273651452
package top.chengdongqing.weui.feature.system.address import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.AddCircleOutline import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState import top.chengdongqing.weui.core.ui.components.dialog.rememberDialogState import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.ui.theme.FontLinkColor import top.chengdongqing.weui.core.utils.setClipboardData import top.chengdongqing.weui.feature.system.address.repository.Address @Composable fun AddressList( onNavigateToAddressForm: (id: Int?) -> Unit, addressViewModel: AddressViewModel = viewModel() ) { val context = LocalContext.current val addressList by addressViewModel.addressList.collectAsState(emptyList()) val coroutineScope = rememberCoroutineScope() val dialog = rememberDialogState() val toast = rememberToastState() val actionSheet = rememberActionSheetState() val actions = remember { listOf( ActionSheetItem("编辑"), ActionSheetItem("删除"), ActionSheetItem("复制") ) } LazyColumn { items(addressList) { item -> AddressListItem(item, onLongClick = { actionSheet.show(actions) { action -> when (action) { 0 -> { onNavigateToAddressForm(item.id) } 1 -> { dialog.show(title = "确定删除该地址吗?") { coroutineScope.launch { addressViewModel.delete(item) toast.show("删除成功", ToastIcon.SUCCESS) } } } 2 -> { context.setClipboardData(buildString { appendLine("联系人: ${item.name}") appendLine("手机号: ${item.phone}") append("详细地址: ${item.addressDetail}") }) toast.show("已复制", ToastIcon.SUCCESS) } } } } ) { onNavigateToAddressForm(item.id) } } item { AddAddressButton { onNavigateToAddressForm(null) } } } } @OptIn(ExperimentalFoundationApi::class) @Composable private fun AddressListItem(address: Address, onLongClick: () -> Unit, onClick: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .combinedClickable( onClick = onClick, onLongClick = onLongClick ) .padding(vertical = 14.dp, horizontal = 26.dp) ) { Text( text = "${address.name} ${address.phone}", color = MaterialTheme.colorScheme.onPrimary, fontSize = 17.sp ) Spacer(modifier = Modifier.height(6.dp)) Text( text = address.addressDetail, color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp, overflow = TextOverflow.Ellipsis ) } WeDivider(Modifier.padding(horizontal = 26.dp)) } @Composable private fun AddAddressButton(onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .clickable { onClick() } .padding(vertical = 18.dp, horizontal = 26.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Outlined.AddCircleOutline, contentDescription = null, modifier = Modifier.size(27.dp), tint = FontLinkColor ) Spacer(modifier = Modifier.width(8.dp)) Text(text = "添加地址", color = FontLinkColor, fontSize = 17.sp) } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/AddressList.kt
2813963392
package top.chengdongqing.weui.feature.system.address import android.app.Application import androidx.lifecycle.AndroidViewModel import top.chengdongqing.weui.feature.system.address.repository.Address import top.chengdongqing.weui.feature.system.address.repository.AddressRepositoryImpl class AddressViewModel(application: Application) : AndroidViewModel(application) { private val addressRepository = AddressRepositoryImpl(application) val addressList = addressRepository.addressList suspend fun insert(address: Address) { return addressRepository.insert(address) } suspend fun update(address: Address) { return addressRepository.update(address) } suspend fun delete(address: Address) { return addressRepository.delete(address) } suspend fun loadById(id: Int): Address? { return addressRepository.loadById(id) } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/AddressViewModel.kt
984973385
package top.chengdongqing.weui.feature.system.address import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import kotlinx.coroutines.delay import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.input.WeTextarea import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.feature.system.address.repository.Address @Composable fun AddressFormScreen( navController: NavController, id: Int?, addressViewModel: AddressViewModel = viewModel() ) { WeScreen( title = "AddressForm", description = "${if (id == null) "新增" else "编辑"}收货地址" ) { val address = remember { mutableStateMapOf<String, String>() } val isAllFilled by remember { derivedStateOf { address.filter { it.value.isNotEmpty() }.size == 3 } } LaunchedEffect(id) { if (id != null) { addressViewModel.loadById(id)?.let { address["name"] = it.name address["phone"] = it.phone address["addressDetail"] = it.addressDetail } } } Column(modifier = Modifier.padding(horizontal = 16.dp)) { WeInput( value = address["name"], label = "联系人", placeholder = "请输入" ) { address["name"] = it } WeInput( value = address["phone"], label = "手机号", placeholder = "请输入", keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone) ) { address["phone"] = it } WeTextarea( value = address["addressDetail"], label = "详细地址", placeholder = "请输入" ) { address["addressDetail"] = it } Spacer(modifier = Modifier.height(20.dp)) val coroutineScope = rememberCoroutineScope() val toast = rememberToastState() WeButton( text = "确定", modifier = Modifier.align(alignment = Alignment.CenterHorizontally), disabled = !isAllFilled ) { val value = Address( name = address["name"]!!, phone = address["phone"]!!, addressDetail = address["addressDetail"]!! ) coroutineScope.launch { if (id == null) { addressViewModel.insert(value) toast.show("添加成功", ToastIcon.SUCCESS) } else { addressViewModel.update(value.copy(id = id)) toast.show("修改成功", ToastIcon.SUCCESS) } delay(1000) navController.navigateUp() } } } } }
WeUI/feature/system/src/main/kotlin/top/chengdongqing/weui/feature/system/address/AddressForm.kt
3071385427
package top.chengdongqing.weui.feature.media 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("top.chengdongqing.weui.feature.media.test", appContext.packageName) } }
WeUI/feature/media/src/androidTest/java/top/chengdongqing/weui/feature/media/ExampleInstrumentedTest.kt
3748127863
package top.chengdongqing.weui.feature.media 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) } }
WeUI/feature/media/src/test/java/top/chengdongqing/weui/feature/media/ExampleUnitTest.kt
1450794256
package top.chengdongqing.weui.feature.media.audioplayer import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Pause import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.R import top.chengdongqing.weui.core.ui.components.slider.WeSlider import top.chengdongqing.weui.core.utils.format import kotlin.math.roundToInt import kotlin.time.Duration.Companion.milliseconds @Composable fun WeAudioPlayer(state: AudioPlayerState) { Column(horizontalAlignment = Alignment.CenterHorizontally) { PrimaryDuration(state) Spacer(modifier = Modifier.height(40.dp)) ProgressControl(state) Spacer(modifier = Modifier.height(60.dp)) PlayControl(state) } } @Composable private fun PrimaryDuration(state: AudioPlayerState) { Text( text = state.currentDuration.milliseconds.format(isFull = true), color = MaterialTheme.colorScheme.onPrimary, fontSize = 30.sp, fontWeight = FontWeight.Bold ) } @Composable private fun ProgressControl(state: AudioPlayerState) { WeSlider( value = state.currentDuration.toFloat(), range = 0f..state.totalDuration.toFloat() ) { state.seekTo(it.roundToInt()) } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = state.currentDuration.milliseconds.format(), color = MaterialTheme.colorScheme.onSecondary ) Text( text = state.totalDuration.milliseconds.format(), color = MaterialTheme.colorScheme.onSecondary ) } } @Composable private fun PlayControl(state: AudioPlayerState) { Box( modifier = Modifier .size(66.dp) .clip(CircleShape) .background(MaterialTheme.colorScheme.onBackground) .clickable { if (state.isPlaying) { state.pause() } else { state.play() } }, contentAlignment = Alignment.Center ) { if (state.isPlaying) { Icon( imageVector = Icons.Outlined.Pause, contentDescription = "暂停", modifier = Modifier .size(44.dp), tint = MaterialTheme.colorScheme.onSecondary ) } else { Icon( painter = painterResource(id = R.drawable.ic_play_arrow), contentDescription = "播放", modifier = Modifier .size(66.dp), tint = MaterialTheme.colorScheme.onSecondary ) } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/audioplayer/AudioPlayer.kt
2081086067
package top.chengdongqing.weui.feature.media.audioplayer import android.content.Context import android.media.MediaPlayer import android.net.Uri import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @Stable interface AudioPlayerState { /** * 播放器实例 */ val player: MediaPlayer /** * 是否播放中 */ val isPlaying: Boolean /** * 总时长 */ val totalDuration: Int /** * 已播放时长 */ val currentDuration: Int /** * 设置音源 */ fun setSource(path: String) fun setSource(uri: Uri) /** * 开始播放 */ fun play() /** * 暂停播放 */ fun pause() /** * 跳转到指定时长 */ fun seekTo(milliseconds: Int) } @Composable fun rememberAudioPlayerState(path: String): AudioPlayerState { val state = rememberAudioPlayerState() LaunchedEffect(path) { state.setSource(path) } return state } @Composable fun rememberAudioPlayerState(uri: Uri): AudioPlayerState { val state = rememberAudioPlayerState() LaunchedEffect(uri) { state.setSource(uri) } return state } @Composable fun rememberAudioPlayerState(): AudioPlayerState { val player = remember { MediaPlayer() } MediaPlayerLifecycle(player) val context = LocalContext.current val coroutineScope = rememberCoroutineScope() return remember { AudioPlayerStateImpl(player, context, coroutineScope) } } private class AudioPlayerStateImpl( override val player: MediaPlayer, private val context: Context, private val coroutineScope: CoroutineScope ) : AudioPlayerState { override val isPlaying: Boolean get() = _isPlaying override var totalDuration by mutableIntStateOf(0) override var currentDuration by mutableIntStateOf(0) override fun setSource(path: String) { reset() player.setDataSource(path) prepare() } override fun setSource(uri: Uri) { reset() player.setDataSource(context, uri) prepare() } override fun play() { if (!player.isPlaying) { player.start() updateProgress() } _isPlaying = true } override fun pause() { if (player.isPlaying) { player.pause() stopUpdatingProgress() } _isPlaying = false } override fun seekTo(milliseconds: Int) { if (milliseconds <= totalDuration) { currentDuration = milliseconds player.seekTo(milliseconds) if (!player.isPlaying) { play() } } } private fun updateProgress() { stopUpdatingProgress() progressJob = coroutineScope.launch { while (isActive) { currentDuration = player.currentPosition delay(500) } } } private fun stopUpdatingProgress() { progressJob?.cancel() progressJob = null } private fun reset() { player.reset() _isPlaying = false currentDuration = 0 stopUpdatingProgress() } private fun prepare() { player.apply { prepareAsync() setOnPreparedListener { totalDuration = it.duration } setOnCompletionListener { _isPlaying = false } } } private var _isPlaying by mutableStateOf(player.isPlaying) private var progressJob: Job? = null } @Composable private fun MediaPlayerLifecycle(player: MediaPlayer) { val lifecycle = LocalLifecycleOwner.current.lifecycle val previousPlayingState = remember { mutableStateOf(false) } DisposableEffect(player) { val lifecycleObserver = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_PAUSE -> { previousPlayingState.value = player.isPlaying if (player.isPlaying) { player.pause() } } Lifecycle.Event.ON_RESUME -> { if (previousPlayingState.value) { player.start() } } else -> {} } } lifecycle.addObserver(lifecycleObserver) onDispose { lifecycle.removeObserver(lifecycleObserver) } } DisposableEffect(Unit) { onDispose { player.release() } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/audioplayer/AudioPlayerState.kt
597890783
package top.chengdongqing.weui.feature.media.navigation import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import top.chengdongqing.weui.feature.media.screens.audio.AudioPlayerScreen import top.chengdongqing.weui.feature.media.screens.audio.AudioRecorderScreen import top.chengdongqing.weui.feature.media.screens.camera.CameraScreen import top.chengdongqing.weui.feature.media.screens.gallery.GalleryScreen import top.chengdongqing.weui.feature.media.screens.image.ImageCropperScreen import top.chengdongqing.weui.feature.media.screens.image.PanoramicImageScreen import top.chengdongqing.weui.feature.media.screens.live.LivePlayerScreen import top.chengdongqing.weui.feature.media.screens.live.LivePusherScreen import top.chengdongqing.weui.feature.media.screens.picker.MediaPickerScreen fun NavGraphBuilder.addMediaGraph(navController: NavController) { composable("camera") { CameraScreen() } composable("live_pusher") { LivePusherScreen() } composable("live_player") { LivePlayerScreen() } composable("media_picker") { MediaPickerScreen() } composable("audio_player") { AudioPlayerScreen() } composable("audio_recorder") { AudioRecorderScreen() } composable("gallery") { GalleryScreen(navController) } composable("image_cropper") { ImageCropperScreen() } composable("panoramic_image") { PanoramicImageScreen() } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/navigation/MediaGraph.kt
2179694808
package top.chengdongqing.weui.feature.media.screens.picker import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.DeleteSweep import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableFloatState import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.MutableState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.compose.AsyncImage import org.burnoutcrew.reorderable.ReorderableItem import org.burnoutcrew.reorderable.ReorderableLazyGridState import org.burnoutcrew.reorderable.detectReorderAfterLongPress import org.burnoutcrew.reorderable.rememberReorderableLazyGridState import org.burnoutcrew.reorderable.reorderable import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.VisualMediaType import top.chengdongqing.weui.core.ui.components.mediapicker.rememberPickMediasLauncher import top.chengdongqing.weui.core.ui.components.mediapreview.previewMedias import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.theme.DangerColorLight import top.chengdongqing.weui.core.utils.detectDragGesturesAfterLongPressWithoutConsume import top.chengdongqing.weui.feature.media.R @Composable fun MediaPickerScreen() { WeScreen( title = "MediaPicker", description = "媒体选择器", containerColor = MaterialTheme.colorScheme.surface, padding = PaddingValues(0.dp), scrollEnabled = false ) { val data = rememberSaveable { mutableStateOf<List<MediaItem>>(emptyList()) } val state = rememberReorderableLazyGridState(onMove = { from, to -> data.value = data.value.toMutableList().apply { add(to.index, removeAt(from.index)) } }, canDragOver = { p1, _ -> p1.key != -1 }) val pickMedia = rememberPickMediasLauncher { it.forEach { item -> if (!data.value.contains(item)) { data.value += item } } } val density = LocalDensity.current val configuration = LocalConfiguration.current val screenHeight = density.run { configuration.screenHeightDp.dp.toPx() } val bottomBarHeight = remember { mutableIntStateOf(0) } val currentItemHeight = remember { mutableIntStateOf(0) } val currentPositionY = remember { mutableFloatStateOf(0f) } Box { PictureGrid( state, data, screenHeight, currentItemHeight, currentPositionY, bottomBarHeight, pickMedia ) val isReady by remember { derivedStateOf { screenHeight - currentPositionY.floatValue - currentItemHeight.intValue <= bottomBarHeight.intValue } } BottomDeleteBar( visible = state.draggingItemIndex != null, isReady ) { bottomBarHeight.intValue = it } } } } @Composable private fun PictureGrid( state: ReorderableLazyGridState, data: MutableState<List<MediaItem>>, screenHeight: Float, currentItemHeight: MutableIntState, currentPositionY: MutableFloatState, bottomBarHeight: MutableIntState, onChooseMedia: (type: VisualMediaType, count: Int) -> Unit ) { val context = LocalContext.current LazyVerticalGrid( state = state.gridState, columns = GridCells.Fixed(3), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier .fillMaxSize() .reorderable(state) ) { itemsIndexed(data.value, key = { _, item -> item.uri }) { index, item -> ReorderableItem(state, key = item.uri) { isDragging -> val elevation by animateDpAsState(if (isDragging) 16.dp else 0.dp, label = "") var positionY by remember { mutableFloatStateOf(0f) } Box( modifier = Modifier .aspectRatio(1f) .onSizeChanged { if (currentItemHeight.intValue == 0) { currentItemHeight.intValue = it.height } } .onGloballyPositioned { positionY = it.positionInRoot().y } .shadow(elevation) .background(MaterialTheme.colorScheme.onSurface) .detectReorderAfterLongPress(state) .pointerInput(Unit) { detectDragGesturesAfterLongPressWithoutConsume(onDragEnd = { if (positionY >= screenHeight - currentItemHeight.intValue - bottomBarHeight.intValue) { data.value -= item } }) { _, _ -> currentPositionY.floatValue = positionY } } .clickable { context.previewMedias(data.value, index) } ) { AsyncImage( model = item.uri, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize() ) } } } if (data.value.size < 9) { item(key = -1) { PlusButton { onChooseMedia(VisualMediaType.IMAGE, 9 - data.value.size) } } } } } @Composable private fun BoxScope.BottomDeleteBar( visible: Boolean, isReady: Boolean, onHeightChange: (Int) -> Unit ) { AnimatedVisibility( visible, modifier = Modifier.align(Alignment.BottomCenter), enter = slideInVertically( animationSpec = tween(150), initialOffsetY = { it } ), exit = slideOutVertically( animationSpec = tween(150), targetOffsetY = { it } ) ) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .background(DangerColorLight.copy(alpha = 0.8f)) .padding(top = 8.dp, bottom = 12.dp) .onSizeChanged { onHeightChange(it.height) }, ) { Icon( imageVector = if (isReady) { Icons.Outlined.DeleteSweep } else { Icons.Outlined.Delete }, contentDescription = null, tint = Color.White, modifier = Modifier.size(24.dp) ) Spacer(modifier = Modifier.height(4.dp)) Text( text = if (isReady) "松开即可删除" else "拖动到此处删除", color = Color.White, fontSize = 12.sp ) } } } @Composable private fun PlusButton(onClick: () -> Unit) { Box( modifier = Modifier .aspectRatio(1f) .background(MaterialTheme.colorScheme.background) .clickable { onClick() }, contentAlignment = Alignment.Center ) { Icon( painter = painterResource(id = R.drawable.ic_plus), contentDescription = "添加", tint = MaterialTheme.colorScheme.onSecondary, modifier = Modifier.size(40.dp) ) } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/picker/MediaPicker.kt
2078884185
package top.chengdongqing.weui.feature.media.screens.camera import android.net.Uri import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import top.chengdongqing.weui.core.data.model.VisualMediaType import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.camera.rememberCameraLauncher import top.chengdongqing.weui.core.ui.components.input.WeInput import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.ui.components.videoplayer.WeVideoPlayer import top.chengdongqing.weui.core.ui.components.videoplayer.rememberVideoPlayerState import top.chengdongqing.weui.core.ui.theme.WeUITheme @Composable fun CameraScreen() { WeScreen(title = "Camera", description = "相机") { val options = remember { listOf( ActionSheetItem(label = "照片", value = VisualMediaType.IMAGE), ActionSheetItem(label = "视频", value = VisualMediaType.VIDEO), ActionSheetItem(label = "照片或视频", value = VisualMediaType.IMAGE_AND_VIDEO) ) } var current by remember { mutableIntStateOf(2) } val actionSheet = rememberActionSheetState() var uri by remember { mutableStateOf<Uri?>(null) } var type by remember { mutableStateOf<VisualMediaType?>(null) } var visible by remember { mutableStateOf(false) } val launchCamera = rememberCameraLauncher { uri1, type1 -> uri = uri1 type = type1 visible = true } WeInput( label = "媒体类型", value = options[current].label, onClick = { actionSheet.show(options) { current = it } }) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "拍摄") { launchCamera(options[current].value as VisualMediaType) } WeUITheme(darkTheme = true, darkStatusBar = true) { WePopup(visible, onClose = { visible = false }) { uri?.let { if (type == VisualMediaType.IMAGE) { AsyncImage( model = it, contentDescription = null ) } else { WeVideoPlayer( state = rememberVideoPlayerState(videoSource = it) ) } } } } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/camera/Camera.kt
1802360357
package top.chengdongqing.weui.feature.media.screens.gallery import android.content.Context import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.launch import top.chengdongqing.core.data.repository.LocalMediaRepositoryImpl import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.MediaType import java.time.Instant import java.time.LocalDate import java.time.ZoneId @Stable interface GalleryState { /** * 根据日期分组的媒体数据 */ val mediaGroups: Map<LocalDate, List<MediaItem>> /** * 是否加载中 */ val isLoading: Boolean /** * 刷新数据 */ suspend fun refresh(types: Array<MediaType> = arrayOf(MediaType.IMAGE, MediaType.VIDEO)) /** * 滚动到指定日期 */ suspend fun LazyGridState.scrollToDate(targetDate: LocalDate) } @Composable fun rememberGalleryState(): GalleryState { val context = LocalContext.current val coroutineScope = rememberCoroutineScope() return remember { GalleryStateImpl(context).apply { coroutineScope.launch { refresh() } } } } private class GalleryStateImpl(context: Context) : GalleryState { override var mediaGroups by mutableStateOf<Map<LocalDate, List<MediaItem>>>(emptyMap()) override var isLoading by mutableStateOf(true) override suspend fun refresh(types: Array<MediaType>) { isLoading = true mediaGroups = mediaRepository.loadMediaList(types) .groupBy { Instant.ofEpochSecond(it.date).atZone(ZoneId.systemDefault()).toLocalDate() } .toSortedMap(compareByDescending { it }) .mapValues { (_, value) -> value.sortedByDescending { it.date } } calculateTitleIndexMap() isLoading = false } private fun calculateTitleIndexMap() { var currentIndex = 0 mediaGroups.forEach { (date, items) -> dateToIndexMap[date] = currentIndex currentIndex += 1 + items.size } } override suspend fun LazyGridState.scrollToDate(targetDate: LocalDate) { val targetIndex = dateToIndexMap[targetDate] ?: run { if (targetDate.isAfter(mediaGroups.keys.first())) 0 else layoutInfo.totalItemsCount } scrollToItem(targetIndex) } private val mediaRepository = LocalMediaRepositoryImpl(context) private val dateToIndexMap = mutableMapOf<LocalDate, Int>() }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/gallery/GalleryState.kt
3192656519
package top.chengdongqing.weui.feature.media.screens.gallery import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.itemsIndexed import androidx.compose.foundation.lazy.grid.rememberLazyGridState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import coil.compose.AsyncImage import top.chengdongqing.weui.core.data.model.MediaItem import top.chengdongqing.weui.core.data.model.isVideo import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore import top.chengdongqing.weui.core.ui.components.mediapreview.previewMedias import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.ChineseDateWeekFormatter import top.chengdongqing.weui.core.utils.RequestMediaPermission import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.core.utils.loadMediaThumbnail import java.time.format.DateTimeFormatter import kotlin.time.Duration.Companion.milliseconds @Composable fun GalleryScreen(navController: NavController) { WeScreen( title = "Gallery", description = "相册", padding = PaddingValues(0.dp), scrollEnabled = false ) { RequestMediaPermission(onRevoked = { navController.navigateUp() }) { Gallery() } } } @Composable private fun Gallery() { val context = LocalContext.current val state = rememberGalleryState() val gridState = rememberLazyGridState() if (state.isLoading) { WeLoadMore() } FilterBar(gridState, state) LazyVerticalGrid( state = gridState, columns = GridCells.Adaptive(100.dp), contentPadding = PaddingValues(bottom = 60.dp), horizontalArrangement = Arrangement.spacedBy(2.dp), verticalArrangement = Arrangement.spacedBy(2.dp), modifier = Modifier.background(MaterialTheme.colorScheme.surface) ) { state.mediaGroups.forEach { (date, items) -> val title = date.format(DateTimeFormatter.ofPattern(ChineseDateWeekFormatter)) item( key = date, span = { GridItemSpan(maxLineSpan) } ) { MediaGroupTitle(title) } itemsIndexed(items) { index, item -> MediaItem(item) { context.previewMedias(items, index) } } } } } @Composable private fun MediaGroupTitle(title: String) { Text( text = title, color = MaterialTheme.colorScheme.onPrimary, fontSize = 14.sp, fontWeight = FontWeight.Bold, modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp, horizontal = 12.dp) ) } @Composable private fun MediaItem(media: MediaItem, onClick: () -> Unit) { Box( modifier = Modifier .aspectRatio(1f) .background(MaterialTheme.colorScheme.outline) .clickable { onClick() } ) { val context = LocalContext.current val thumbnail by produceState<Any?>(initialValue = null) { value = context.loadMediaThumbnail(media) } AsyncImage( model = thumbnail, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize() ) if (media.isVideo()) { Box( modifier = Modifier .align(Alignment.BottomEnd) .padding(6.dp) .background(Color(0f, 0f, 0f, 0.3f), RoundedCornerShape(16.dp)) .padding(vertical = 3.dp, horizontal = 6.dp) ) { Text( text = media.duration.milliseconds.format(), color = Color.White, fontSize = 10.sp ) } } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/gallery/Gallery.kt
949581349
package top.chengdongqing.weui.feature.media.screens.gallery import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.LazyGridState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.KeyboardArrowDown import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import top.chengdongqing.weui.core.ui.components.divider.WeDivider import top.chengdongqing.weui.core.ui.components.picker.rememberDatePickerState import top.chengdongqing.weui.core.utils.ChineseDateFormatter import top.chengdongqing.weui.core.utils.clickableWithoutRipple import java.time.LocalDate import java.time.format.DateTimeFormatter @Composable internal fun FilterBar(gridState: LazyGridState, state: GalleryState) { val picker = rememberDatePickerState() var value by remember { mutableStateOf(LocalDate.now()) } val coroutineScope = rememberCoroutineScope() LaunchedEffect(Unit) { snapshotFlow { gridState.layoutInfo.visibleItemsInfo.firstOrNull()?.key }.filter { it is LocalDate }.map { it as LocalDate }.collect { value = it } } Column { WeDivider() Row( modifier = Modifier .fillMaxWidth() .clickableWithoutRipple { picker.show( value, start = state.mediaGroups.keys.last(), end = LocalDate.now() ) { value = it with(state) { coroutineScope.launch { gridState.scrollToDate(it) } } } } .padding(horizontal = 12.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = value.format(DateTimeFormatter.ofPattern(ChineseDateFormatter)), color = MaterialTheme.colorScheme.onPrimary, fontSize = 16.sp, fontWeight = FontWeight.Bold ) Icon( imageVector = Icons.Outlined.KeyboardArrowDown, contentDescription = null, tint = MaterialTheme.colorScheme.onSecondary, modifier = Modifier.size(20.dp) ) } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/gallery/FilterBar.kt
1250578076
package top.chengdongqing.weui.feature.media.screens.image import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.res.imageResource import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.rememberToggleState import top.chengdongqing.weui.feature.media.R import top.chengdongqing.weui.feature.media.panoramicimage.WePanoramicImage @Composable fun PanoramicImageScreen() { WeScreen( title = "PanoramicImage", description = "全景图片", padding = PaddingValues(0.dp) ) { val image = ImageBitmap.imageResource(id = R.drawable.panoramic_yosemite_park) val (scrollStep, toggleScrollStep) = rememberToggleState( defaultValue = 0.75f, reverseValue = 5f ) WePanoramicImage(image, scrollStep.value) Spacer(modifier = Modifier.height(40.dp)) WeButton(text = "切换滚动速度", type = ButtonType.PLAIN) { toggleScrollStep() } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/image/PanoramicImage.kt
2290215947
package top.chengdongqing.weui.feature.media.screens.image import android.graphics.BitmapFactory import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.data.model.VisualMediaType import top.chengdongqing.weui.core.ui.components.button.ButtonType import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.mediapicker.rememberPickMediasLauncher import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.feature.media.imagecropper.rememberImageCropperLauncher @Composable fun ImageCropperScreen() { WeScreen(title = "ImageCropper", description = "图片裁剪") { var croppedImage by remember { mutableStateOf<ImageBitmap?>(null) } val context = LocalContext.current val launchImageCropper = rememberImageCropperLauncher { uri -> context.contentResolver.openInputStream(uri)?.use { inputStream -> BitmapFactory.decodeStream(inputStream)?.asImageBitmap()?.let { imageBitmap -> croppedImage = imageBitmap } } } val pickMedia = rememberPickMediasLauncher { val uri = it.first().uri launchImageCropper(uri) } croppedImage?.let { Image(bitmap = it, contentDescription = null) Spacer(modifier = Modifier.height(20.dp)) WeButton(text = "清除图片", type = ButtonType.DANGER) { croppedImage = null } Spacer(modifier = Modifier.height(20.dp)) } WeButton(text = "选择图片") { pickMedia(VisualMediaType.IMAGE, 1) } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/image/ImageCropper.kt
396526534
package top.chengdongqing.weui.feature.media.screens.audio import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.button.WeButton import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.core.utils.rememberToggleState import top.chengdongqing.weui.feature.media.audioplayer.WeAudioPlayer import top.chengdongqing.weui.feature.media.audioplayer.rememberAudioPlayerState @Composable fun AudioPlayerScreen() { WeScreen(title = "AudioPlayer", description = "音频播放", padding = PaddingValues(24.dp)) { val (audioSource, toggleSource) = rememberToggleState( defaultValue = "https://mp3.haoge500.com/upload/rank/20211219/6de3b8453a39588fbe4c83cdcf8594c4.mp3", reverseValue = "https://room.ylzmjd.com/shiting/校长-带你去旅行.mp3" ) val state = rememberAudioPlayerState(audioSource.value) WeAudioPlayer(state) Spacer(modifier = Modifier.height(60.dp)) WeButton(text = "切换音源") { toggleSource() } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/audio/AudioPlayer.kt
1745620359
package top.chengdongqing.weui.feature.media.screens.audio import android.net.Uri import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.screen.WeScreen import top.chengdongqing.weui.feature.media.audioplayer.WeAudioPlayer import top.chengdongqing.weui.feature.media.audioplayer.rememberAudioPlayerState import top.chengdongqing.weui.feature.media.audiorecorder.WeAudioRecorder @Composable fun AudioRecorderScreen() { WeScreen(title = "AudioRecorder", description = "音频录制") { var uri by remember { mutableStateOf<Uri?>(null) } var visible by remember { mutableStateOf(false) } WeAudioRecorder { uri = it visible = true } WePopup( visible, onClose = { visible = false } ) { uri?.let { Box(modifier = Modifier.padding(horizontal = 24.dp, vertical = 48.dp)) { WeAudioPlayer(rememberAudioPlayerState(it)) } } } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/audio/AudioRecorder.kt
3278170943
package top.chengdongqing.weui.feature.media.screens.live import androidx.compose.runtime.Composable import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun LivePusherScreen() { WeScreen(title = "LivePusher", description = "直播推流,待完善") { } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/live/LivePusher.kt
1155135626
package top.chengdongqing.weui.feature.media.screens.live import androidx.compose.runtime.Composable import top.chengdongqing.weui.core.ui.components.screen.WeScreen @Composable fun LivePlayerScreen() { WeScreen(title = "LivePlayer", description = "直播拉流,待完善") { } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/screens/live/LivePlayer.kt
259013043
package top.chengdongqing.weui.feature.media.audiorecorder import android.content.Context import android.media.MediaRecorder import android.net.Uri import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import top.chengdongqing.weui.core.utils.getFileProviderUri import java.io.File @Stable interface AudioRecorderState { /** * 是否在录制中 */ val isRecording: Boolean /** * 已录制的时长 */ val duration: Int /** * 开始录音 */ fun start() /** * 结束录音 */ fun stop(): Uri } @Composable fun rememberAudioRecorderState(): AudioRecorderState { val context = LocalContext.current val recorder = remember { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { MediaRecorder(context) } else { @Suppress("DEPRECATION") MediaRecorder() } } val coroutineScope = rememberCoroutineScope() val state = remember { AudioRecorderStateImpl(recorder, coroutineScope, context) } DisposableEffect(Unit) { onDispose { recorder.release() } } return state } private class AudioRecorderStateImpl( val recorder: MediaRecorder, private val coroutineScope: CoroutineScope, private val context: Context ) : AudioRecorderState { override var isRecording by mutableStateOf(false) override var duration by mutableIntStateOf(0) override fun start() { prepare() // 重置计时 duration = 0 // 开始录音 recorder.start() isRecording = true // 开始计时 coroutineScope.launch { while (isActive && isRecording) { delay(1000) duration += 1 } } } override fun stop(): Uri { recorder.stop() isRecording = false return context.getFileProviderUri(tempFile!!) } private fun prepare() { // 初始化参数 recorder.apply { reset() setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setAudioEncoder(MediaRecorder.AudioEncoder.HE_AAC) } // 保存到临时文件 tempFile = File.createTempFile("RCD_", ".aac").apply { deleteOnExit() } recorder.setOutputFile(tempFile) recorder.prepare() } private var tempFile: File? = null }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/audiorecorder/AudioRecorderState.kt
517029035
package top.chengdongqing.weui.feature.media.audiorecorder import android.Manifest import android.net.Uri import android.os.Build import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Circle import androidx.compose.material.icons.filled.Mic import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme 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.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import top.chengdongqing.weui.core.utils.format import kotlin.time.Duration.Companion.seconds @OptIn(ExperimentalPermissionsApi::class) @Composable fun WeAudioRecorder( state: AudioRecorderState = rememberAudioRecorderState(), onRecord: (Uri) -> Unit ) { val permissionState = rememberMultiplePermissionsState( buildList { add(Manifest.permission.RECORD_AUDIO) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { add(Manifest.permission.WRITE_EXTERNAL_STORAGE) } } ) Text( text = state.duration.seconds.format(isFull = true), color = MaterialTheme.colorScheme.onPrimary, fontSize = 30.sp, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(60.dp)) Box( modifier = Modifier.size(84.dp), contentAlignment = Alignment.Center ) { Box( modifier = Modifier .clip(CircleShape) .background(MaterialTheme.colorScheme.onBackground) .clickable { if (permissionState.allPermissionsGranted) { if (state.isRecording) { state .stop() .also(onRecord) } else { state.start() } } else { permissionState.launchMultiplePermissionRequest() } } .padding(12.dp) ) { RecordIcon(state.isRecording) } } } @Composable private fun RecordIcon(isRecording: Boolean) { if (!isRecording) { Icon( imageVector = Icons.Filled.Mic, contentDescription = "开始录音", modifier = Modifier.size(50.dp), tint = MaterialTheme.colorScheme.onSecondary ) } else { val transition = rememberInfiniteTransition(label = "") val animatedSize by transition.animateFloat( initialValue = 30f, targetValue = 40f, animationSpec = infiniteRepeatable( tween(durationMillis = 1500, easing = LinearEasing), RepeatMode.Reverse ), label = "AudioRecorderStopIconAnimation" ) Icon( imageVector = Icons.Filled.Circle, contentDescription = "停止录音", modifier = Modifier.size(animatedSize.dp), tint = Color.Red ) } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/audiorecorder/AudioRecorder.kt
2218913756
package top.chengdongqing.weui.feature.media.panoramicimage import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.withFrameNanos import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.unit.IntSize import kotlinx.coroutines.isActive import top.chengdongqing.weui.core.utils.toIntOffset import top.chengdongqing.weui.core.utils.toIntSize @Composable fun WePanoramicImage(image: ImageBitmap, scrollStep: Float = 0.75f) { var size by remember { mutableStateOf(IntSize.Zero) } var x by remember { mutableFloatStateOf(0f) } val scale = remember(size, image) { size.height / image.height.toFloat() } val imgW = image.width * scale val imgH = image.height * scale // 设置图片初始位置 LaunchedEffect(size) { x = size.width.toFloat() } // 图片循环滚动 LaunchedEffect(imgW, scrollStep) { while (isActive) { withFrameNanos { x += scrollStep // 完全滚动完后重置位置 if (x >= imgW) x = 0f } } } Canvas( modifier = Modifier .fillMaxWidth() .aspectRatio(2f / 1f) .clipToBounds() .onSizeChanged { size = it } ) { // 默认图片 drawImage( image = image, dstOffset = Offset(x, 0f).toIntOffset(), dstSize = Size(imgW, imgH).toIntSize() ) // 辅助图片,当图片宽度不足以填满容器宽度时用于补充 if (x + imgW > size.width) { drawImage( image = image, dstOffset = Offset(x - imgW, 0f).toIntOffset(), dstSize = Size(imgW, imgH).toIntSize() ) } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/panoramicimage/PanoramicImage.kt
875309437
package top.chengdongqing.weui.feature.media.imagecropper import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import top.chengdongqing.weui.core.ui.theme.WeUITheme import top.chengdongqing.weui.core.utils.SetupStatusBarStyle class ImageCropperActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra("uri", Uri::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra("uri") }!! SetupStatusBarStyle(isDark = false) WeUITheme(darkTheme = true) { WeImageCropper(uri, onCancel = { finish() }) { val intent = Intent().apply { putExtra("uri", it) } setResult(RESULT_OK, intent) finish() } } } } companion object { fun newIntent(context: Context) = Intent(context, ImageCropperActivity::class.java) } } @Composable fun rememberImageCropperLauncher(onChange: (Uri) -> Unit): (Uri) -> Unit { val context = LocalContext.current val launcher = rememberLauncherForActivityResult( contract = ActivityResultContracts.StartActivityForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { result.data?.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { getParcelableExtra("uri", Uri::class.java) } else { @Suppress("DEPRECATION") (getParcelableExtra("uri") as? Uri) }?.let(onChange) } } } return { val intent = ImageCropperActivity.newIntent(context).apply { putExtra("uri", it) } launcher.launch(intent) } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ImageCropperActivity.kt
2677167803
package top.chengdongqing.weui.feature.media.imagecropper import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.BoxScope import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Paint import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.unit.dp @Composable internal fun BoxScope.CropperMask(onSizeChange: (Size) -> Unit) { Canvas(modifier = Modifier.matchParentSize()) { val spacing = 25.dp.toPx() val width = size.width - spacing * 2 onSizeChange(Size(width, width)) drawIntoCanvas { canvas -> canvas.saveLayer(bounds = Rect(offset = Offset.Zero, size = size), Paint()) // 绘制遮罩 drawRect(color = Color(0f, 0f, 0f, 0.4f)) // 露出裁剪框 canvas.saveLayer( bounds = Rect( offset = Offset(x = spacing, y = (size.height - width) / 2), size = Size(width, width) ), paint = Paint().apply { blendMode = BlendMode.Clear } ) canvas.restore() } // 绘制四个角 drawCorners(spacing, width) } } private fun DrawScope.drawCorners(space: Float, width: Float) { val cornerSize = 10.dp.toPx() val strokeWidth = 2.dp.toPx() val cornerPaths = listOf( // 左上角 Path().apply { moveTo(space, size.height / 2 - width / 2 + cornerSize) lineTo(space, size.height / 2 - width / 2) lineTo(space + cornerSize, size.height / 2 - width / 2) }, // 右上角 Path().apply { moveTo(size.width - space, size.height / 2 - width / 2 + cornerSize) lineTo(size.width - space, size.height / 2 - width / 2) lineTo(size.width - space - cornerSize, size.height / 2 - width / 2) }, // 左下角 Path().apply { moveTo(space, size.height / 2 + width / 2 - cornerSize) lineTo(space, size.height / 2 + width / 2) lineTo(space + cornerSize, size.height / 2 + width / 2) }, // 右下角 Path().apply { moveTo(size.width - space, size.height / 2 + width / 2 - cornerSize) lineTo(size.width - space, size.height / 2 + width / 2) lineTo(size.width - space - cornerSize, size.height / 2 + width / 2) } ) cornerPaths.forEach { path -> drawPath(path, color = Color.White, style = Stroke(width = strokeWidth)) } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/CropperMask.kt
2130247068
package top.chengdongqing.weui.feature.media.imagecropper data class ImageTransform( val scale: Float = 1f, val rotation: Float = 0f, val offsetX: Float = 0f, val offsetY: Float = 0f )
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ImageTransform.kt
766596832
package top.chengdongqing.weui.feature.media.imagecropper import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.rotate import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.center import androidx.compose.ui.unit.toOffset import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.utils.getFileProviderUri import top.chengdongqing.weui.core.utils.toIntOffset import top.chengdongqing.weui.core.utils.toIntSize import java.io.File import java.io.FileOutputStream import kotlin.math.max import kotlin.time.Duration @Composable fun WeImageCropper(uri: Uri, onCancel: () -> Unit, onConfirm: (Uri) -> Unit) { val context = LocalContext.current val imageBitmap by context.loadImageBitmap(uri) var screenSize by remember { mutableStateOf(IntSize.Zero) } var boxSize by remember { mutableStateOf(IntSize.Zero) } val transform = remember { mutableStateOf(ImageTransform()) } var initialTransform by remember { mutableStateOf<ImageTransform?>(null) } val animatedRotation by animateFloatAsState(targetValue = transform.value.rotation, label = "") val coroutineScope = rememberCoroutineScope() val toast = rememberToastState() TransformInitializeEffect( screenSize, boxSize, imageBitmap, transform ) { initialTransform = it } Box { Canvas( modifier = Modifier .fillMaxSize() .background(Color.Black) .onSizeChanged { screenSize = it } .transformable(rememberTransformableState { zoomChange, panChange, _ -> imageBitmap?.let { image -> transform.value = transform.value.createNewTransform( zoomChange, panChange, boxSize, image ) } }) ) { imageBitmap?.let { transform.value.apply { rotate(degrees = animatedRotation) { scale(scale) { drawImage( it, dstOffset = Offset(offsetX, offsetY).toIntOffset() ) } } } } } CropperMask { boxSize = it.toIntSize() } ActionBar( transform, onCancel = onCancel, onReset = { initialTransform?.let { transform.value = it } } ) { imageBitmap?.let { toast.show( "处理中...", ToastIcon.LOADING, duration = Duration.INFINITE, mask = true ) coroutineScope.launch(Dispatchers.IO) { val bitmap = it.drawToNativeCanvas(screenSize, boxSize, transform.value) context.createImageUri(bitmap).apply(onConfirm) } } } } } @Composable private fun TransformInitializeEffect( screenSize: IntSize, boxSize: IntSize, image: ImageBitmap?, transform: MutableState<ImageTransform>, onInit: (ImageTransform) -> Unit ) { LaunchedEffect(boxSize, image) { if (screenSize != IntSize.Zero && boxSize != IntSize.Zero && image != null) { val scale = max( boxSize.width / image.width.toFloat(), boxSize.height / image.height.toFloat() ) val offsetX = (screenSize.width - image.width) / 2f val offsetY = (screenSize.height - image.height) / 2f transform.value = ImageTransform( scale = scale, offsetX = offsetX, offsetY = offsetY ).also(onInit) } } } @Composable private fun Context.loadImageBitmap(uri: Uri): State<ImageBitmap?> { val context = this return produceState<ImageBitmap?>(initialValue = null) { value = withContext(Dispatchers.IO) { context.contentResolver.openInputStream(uri)?.use { inputStream -> BitmapFactory.decodeStream(inputStream).asImageBitmap() } } } } private fun ImageTransform.createNewTransform( zoomChange: Float, panChange: Offset, boxSize: IntSize, image: ImageBitmap ): ImageTransform { val minScale = max( boxSize.width / image.width.toFloat(), boxSize.height / image.height.toFloat() ) val newScale = (scale * zoomChange).coerceIn(minScale, 5f) return copy( scale = newScale, offsetX = offsetX + panChange.x, offsetY = offsetY + panChange.y ) } private fun ImageBitmap.drawToNativeCanvas( screenSize: IntSize, boxSize: IntSize, transform: ImageTransform ): Bitmap { val bitmap = Bitmap.createBitmap( screenSize.width, screenSize.height, Bitmap.Config.ARGB_8888 ) val canvas = android.graphics.Canvas(bitmap) transform.apply { val offset = screenSize.center.toOffset() val matrix = Matrix().apply { postTranslate(offsetX, offsetY) postRotate(rotation, offset.x, offset.y) postScale(scale, scale, offset.x, offset.y) } canvas.drawBitmap(asAndroidBitmap(), matrix, null) } val offset = IntSize( width = screenSize.width - boxSize.width, height = screenSize.height - boxSize.height ).center return Bitmap.createBitmap( bitmap, offset.x, offset.y, boxSize.width, boxSize.height ) } private fun Context.createImageUri(bitmap: Bitmap): Uri { val tempFile = File.createTempFile("cropped_", ".png").apply { deleteOnExit() } FileOutputStream(tempFile).use { outputStream -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) } return getFileProviderUri(tempFile) }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ImageCropper.kt
2811085800
package top.chengdongqing.weui.feature.media.imagecropper import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Replay import androidx.compose.material.icons.outlined.Rotate90DegreesCcw import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import top.chengdongqing.weui.core.ui.components.button.ButtonSize import top.chengdongqing.weui.core.ui.components.button.WeButton @Composable internal fun BoxScope.ActionBar( transform: MutableState<ImageTransform>, onCancel: () -> Unit, onReset: () -> Unit, onConfirm: () -> Unit ) { Row( modifier = Modifier .align(Alignment.BottomCenter) .fillMaxWidth() .padding(24.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = "取消", color = Color.White, fontSize = 16.sp, modifier = Modifier.clickable { onCancel() } ) IconButton(onClick = onReset) { Icon( imageVector = Icons.Outlined.Replay, contentDescription = "恢复", tint = Color.White, modifier = Modifier.size(28.dp) ) } IconButton(onClick = { transform.value = transform.value.copy( rotation = transform.value.rotation - 90f ) }) { Icon( imageVector = Icons.Outlined.Rotate90DegreesCcw, contentDescription = "旋转", tint = Color.White, modifier = Modifier.size(28.dp) ) } WeButton(text = "确定", size = ButtonSize.SMALL) { onConfirm() } } }
WeUI/feature/media/src/main/kotlin/top/chengdongqing/weui/feature/media/imagecropper/ActionBar.kt
3114885375
package com.evgeny.aiLandmarkRecognition.data import android.graphics.Bitmap import android.view.Surface import com.evgeny.aiLandmarkRecognition.TfLiteLandmarksClassifier import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.model.Classification import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.support.image.TensorImage import org.tensorflow.lite.task.core.vision.ImageProcessingOptions import org.tensorflow.lite.task.vision.classifier.ImageClassifier import javax.inject.Inject internal class TfLiteLandmarkClassifier @Inject constructor( @TfLiteLandmarksClassifier private val classifier: ImageClassifier, private val imageProcessor: ImageProcessor, ) : LandmarkClassifier { override fun classify(bitmap: Bitmap, rotation: Int): List<Classification> { val tensorImage = imageProcessor.process(TensorImage.fromBitmap(bitmap)) val imageProcessingOptions = ImageProcessingOptions.builder() .setOrientation(getOrientationFromRotation(rotation)) .build() val results = classifier.classify(tensorImage, imageProcessingOptions) return results.asSequence() .map { it.categories.map { Classification( name = it.displayName, score = it.score, ) } } .flatten() .distinctBy { it.name } .toList() } private fun getOrientationFromRotation(rotation: Int): ImageProcessingOptions.Orientation { return when (rotation) { Surface.ROTATION_270 -> ImageProcessingOptions.Orientation.BOTTOM_RIGHT Surface.ROTATION_90 -> ImageProcessingOptions.Orientation.TOP_LEFT Surface.ROTATION_180 -> ImageProcessingOptions.Orientation.RIGHT_BOTTOM else -> ImageProcessingOptions.Orientation.RIGHT_TOP } } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/data/TfLiteLandmarkClassifier.kt
2332230200
package com.evgeny.aiLandmarkRecognition.domain import android.graphics.Bitmap import com.evgeny.aiLandmarkRecognition.domain.model.Classification internal interface LandmarkClassifier { fun classify(bitmap: Bitmap, rotation: Int): List<Classification> }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/domain/LandmarkClassifier.kt
1610334792
package com.evgeny.aiLandmarkRecognition.domain.model internal data class Classification( val name: String, val score: Float, )
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/domain/model/Classification.kt
771703642
package com.evgeny.aiLandmarkRecognition.presentation import android.content.Context import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asExecutor import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel internal class AiLandmarkRecognitionViewModel @Inject constructor( @ApplicationContext context: Context, private val landmarkImageAnalyzer: LandmarkImageAnalyzer, ) : ViewModel() { val cameraController = LifecycleCameraController(context).apply { setEnabledUseCases(CameraController.IMAGE_ANALYSIS) setImageAnalysisAnalyzer(Dispatchers.Default.asExecutor(), landmarkImageAnalyzer) } val imageAnalyzerResults = landmarkImageAnalyzer.results.stateIn( scope = viewModelScope, initialValue = emptyList(), started = SharingStarted.Lazily ) }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/AiLandmarkRecognitionViewModel.kt
3127445414
package com.evgeny.aiLandmarkRecognition.presentation import androidx.activity.compose.BackHandler import androidx.camera.view.PreviewView import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width 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.platform.LocalLifecycleOwner import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavController import com.evgeny.aiLandmarkRecognition.domain.model.Classification import com.evgeny.archBase.compose.DisposableEffectWithLifeCycle @Composable fun AiLandmarkRecognitionPage( navController: NavController?, ) { val viewModel = hiltViewModel<AiLandmarkRecognitionViewModel>() val lifecycleOwner = LocalLifecycleOwner.current val results by viewModel.imageAnalyzerResults.collectAsStateWithLifecycle() Box(modifier = Modifier.fillMaxSize()) { AndroidView( factory = { PreviewView(it).apply { controller = viewModel.cameraController } }, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) .align(Alignment.Center) ) Column( modifier = Modifier.align(Alignment.BottomCenter) ) { results.forEach { ClassificationItem(it) } } } DisposableEffectWithLifeCycle( onCreate = { viewModel.cameraController.bindToLifecycle(lifecycleOwner) }, onDestroy = { viewModel.cameraController.unbind() } ) BackHandler { navController?.popBackStack() } } @Composable private fun ClassificationItem(item: Classification) { Row(modifier = Modifier.fillMaxWidth()) { Text(text = item.name, modifier = Modifier.weight(1f)) Spacer(modifier = Modifier.width(10.dp)) Text(text = String.format("%.2f", item.score)) } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/AiLandmarkRecognitionPage.kt
2739138046
package com.evgeny.aiLandmarkRecognition.presentation import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import com.evgeny.aiLandmarkRecognition.DefaultCoroutineScope import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.model.Classification import com.evgeny.archBase.graphics.centerCrop import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject internal class LandmarkImageAnalyzer @Inject constructor( private val landmarkClassifier: LandmarkClassifier, @DefaultCoroutineScope private val coroutineScope: CoroutineScope, ) : ImageAnalysis.Analyzer { private val _results = MutableSharedFlow<List<Classification>>() val results = _results.asSharedFlow() private val frameSkipCounter = AtomicLong(0) override fun analyze(image: ImageProxy) { coroutineScope.launch { if (frameSkipCounter.getAndIncrement() % 20 == 0L) { val results = landmarkClassifier.classify( bitmap = image.toBitmap().centerCrop(321, 321), rotation = image.imageInfo.rotationDegrees, ) _results.emit(results) } image.close() } } }
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/presentation/LandmarkImageAnalyzer.kt
215038598
package com.evgeny.aiLandmarkRecognition import android.content.Context import androidx.camera.core.ImageAnalysis import com.evgeny.aiLandmarkRecognition.data.TfLiteLandmarkClassifier import com.evgeny.aiLandmarkRecognition.domain.LandmarkClassifier import com.evgeny.aiLandmarkRecognition.presentation.LandmarkImageAnalyzer import dagger.Binds import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import org.tensorflow.lite.support.image.ImageProcessor import org.tensorflow.lite.task.core.BaseOptions import org.tensorflow.lite.task.vision.classifier.ImageClassifier import org.tensorflow.lite.task.vision.classifier.ImageClassifier.ImageClassifierOptions import javax.inject.Qualifier import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal interface AiLandmarkRecognitionModule { @Binds @Singleton fun bindLandmarkClassifier(impl: TfLiteLandmarkClassifier): LandmarkClassifier @Binds fun bindImageAnalyzer(impl: LandmarkImageAnalyzer): ImageAnalysis.Analyzer companion object { @Provides @Singleton @TfLiteLandmarksClassifier fun provideImageClassifier( @ApplicationContext context: Context, ): ImageClassifier { val baseOptions = BaseOptions.builder() .setNumThreads(2) .build() val options = ImageClassifierOptions.builder() .setBaseOptions(baseOptions) .setMaxResults(3) .setScoreThreshold(0.5f) .build() return ImageClassifier.createFromFileAndOptions( context, "landmarks.tflite", options, ) } @Provides @Singleton fun provideImageProcessor(): ImageProcessor = ImageProcessor.Builder().build() @Provides @Singleton @DefaultCoroutineScope fun provideDefaultCoroutineScope(): CoroutineScope = CoroutineScope(Dispatchers.Default) } } @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class TfLiteLandmarksClassifier @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class DefaultCoroutineScope
tensorflow-lite-samples/ai-landmark-recognition/src/main/java/com/evgeny/aiLandmarkRecognition/AiLandmarkRecognitionModule.kt
2706180829
package com.evgeny.tensorflowlitesamples.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)
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Color.kt
3396599453
package com.evgeny.tensorflowlitesamples.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 TensorFlowLiteSamplesTheme( 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 ) }
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Theme.kt
1188667527
package com.evgeny.tensorflowlitesamples.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 ) */ )
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/ui/theme/Type.kt
4230523347
package com.evgeny.tensorflowlitesamples 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.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.evgeny.aiLandmarkRecognition.presentation.AiLandmarkRecognitionPage import com.evgeny.tensorflowlitesamples.feature.home.MainPage import com.evgeny.tensorflowlitesamples.ui.theme.TensorFlowLiteSamplesTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TensorFlowLiteSamplesTheme { val navController = rememberNavController() Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { NavHost(navController = navController, startDestination = "main") { composable("main") { MainPage(navController = navController) } composable("aiLandmarkRecognition") { AiLandmarkRecognitionPage(navController = navController) } } } } } } }
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/MainActivity.kt
2909621611
package com.evgeny.tensorflowlitesamples.app import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class App : Application()
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/app/App.kt
3982841646
package com.evgeny.tensorflowlitesamples.feature.home import androidx.compose.foundation.clickable 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.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.evgeny.tensorflowlitesamples.R import com.evgeny.tensorflowlitesamples.ui.theme.TensorFlowLiteSamplesTheme import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState @OptIn(ExperimentalPermissionsApi::class, ExperimentalMaterial3Api::class) @Composable internal fun MainPage( navController: NavController?, ) { val cameraPermission = rememberPermissionState(permission = "android.permission.CAMERA") if (cameraPermission.status.isGranted) { Column(modifier = Modifier.fillMaxSize()) { TopAppBar(title = { Text(text = "TensorFlowLite Samples") }) Item(title = "AI Landmark Recognition") { navController?.navigate("aiLandmarkRecognition") } } } else { Box(modifier = Modifier.fillMaxSize()) { Text( text = "Enable camera permission", modifier = Modifier.align(Alignment.Center) ) } } if (cameraPermission.status.isGranted.not()) { LaunchedEffect(Unit) { cameraPermission.launchPermissionRequest() } } } @Composable private fun Item(title: String, onClick: () -> Unit) { Row( modifier = Modifier .fillMaxWidth() .clickable { onClick() } .padding(horizontal = 16.dp, vertical = 20.dp) ) { Text(text = title, modifier = Modifier .weight(1f) .align(Alignment.CenterVertically)) Icon( painter = painterResource(id = R.drawable.ic_arrow_forward_24), contentDescription = null, modifier = Modifier .weight(0.1f) .align(Alignment.CenterVertically) ) } } @Composable @Preview internal fun MainPagePreview() { TensorFlowLiteSamplesTheme { MainPage(navController = null) } }
tensorflow-lite-samples/app/src/main/java/com/evgeny/tensorflowlitesamples/feature/home/MainPage.kt
3237260791
package com.evgeny.archBase.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver @Composable fun DisposableEffectWithLifeCycle( onResume: () -> Unit = {}, onPause: () -> Unit = {}, onStop: () -> Unit = {}, onStart: () -> Unit = {}, onCreate: () -> Unit = {}, onDestroy: () -> Unit = {}, ) { // Safely update the current lambdas when a new one is provided val lifecycleOwner = LocalLifecycleOwner.current val currentOnResume by rememberUpdatedState(onResume) val currentOnPause by rememberUpdatedState(onPause) val currentOnStop by rememberUpdatedState(onStop) val currentOnStart by rememberUpdatedState(onStart) val currentOnCreate by rememberUpdatedState(onCreate) val currentOnDestroy by rememberUpdatedState(onDestroy) // If `lifecycleOwner` changes, dispose and reset the effect DisposableEffect(lifecycleOwner) { // Create an observer that triggers our remembered callbacks // for lifecycle events val observer = LifecycleEventObserver { _, event -> when (event) { Lifecycle.Event.ON_CREATE -> { currentOnCreate() } Lifecycle.Event.ON_START -> { currentOnStart() } Lifecycle.Event.ON_RESUME -> { currentOnResume() } Lifecycle.Event.ON_PAUSE -> { currentOnPause() } Lifecycle.Event.ON_STOP -> { currentOnStop() } Lifecycle.Event.ON_DESTROY -> { currentOnDestroy() } else -> {} } } // Add the observer to the lifecycle lifecycleOwner.lifecycle.addObserver(observer) // When the effect leaves the Composition, remove the observer onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } }
tensorflow-lite-samples/arch-base/src/main/java/com/evgeny/archBase/compose/Extensions.kt
2573930353
package com.evgeny.archBase.graphics import android.graphics.Bitmap fun Bitmap.centerCrop(desiredWidth: Int, desiredHeight: Int): Bitmap { val xStart = (width - desiredWidth) / 2 val yStart = (height - desiredHeight) / 2 return Bitmap.createBitmap(this, xStart, yStart, desiredHeight, desiredHeight) }
tensorflow-lite-samples/arch-base/src/main/java/com/evgeny/archBase/graphics/Extensions.kt
1476518077
package com.example.holamundoanyi 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.holamundoanyi", appContext.packageName) } }
HelloWorldAnyi/app/src/androidTest/java/com/example/holamundoanyi/ExampleInstrumentedTest.kt
423884862
package com.example.holamundoanyi 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) } }
HelloWorldAnyi/app/src/test/java/com/example/holamundoanyi/ExampleUnitTest.kt
2136297204
package com.example.holamundoanyi import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
HelloWorldAnyi/app/src/main/java/com/example/holamundoanyi/MainActivity.kt
1435216404
package vn.hunghd.example; import io.flutter.embedding.android.FlutterActivity; class MainActivity : FlutterActivity()
webview_download_test/flutter_downloader/example/android/app/src/main/kotlin/vn/hunghd/example/MainActivity.kt
809020230
package vn.hunghd.flutterdownloader import android.content.ContentResolver import android.content.ContentUris import android.content.Context import android.content.Intent import android.net.Uri import android.provider.MediaStore import android.util.Log import androidx.core.app.NotificationManagerCompat import androidx.work.BackoffPolicy import androidx.work.Constraints import androidx.work.Data import androidx.work.NetworkType import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager import androidx.work.WorkRequest import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import java.io.File import java.util.UUID import java.util.concurrent.TimeUnit private const val invalidTaskId = "invalid_task_id" private const val invalidStatus = "invalid_status" private const val invalidData = "invalid_data" class FlutterDownloaderPlugin : MethodChannel.MethodCallHandler, FlutterPlugin { private var flutterChannel: MethodChannel? = null private var taskDao: TaskDao? = null private var context: Context? = null private var callbackHandle: Long = 0 private var step = 0 private var debugMode = 0 private var ignoreSsl = 0 private val initializationLock = Any() private fun onAttachedToEngine(applicationContext: Context?, messenger: BinaryMessenger) { synchronized(initializationLock) { if (flutterChannel != null) { return } context = applicationContext flutterChannel = MethodChannel(messenger, CHANNEL) flutterChannel?.setMethodCallHandler(this) val dbHelper: TaskDbHelper = TaskDbHelper.getInstance(context) taskDao = TaskDao(dbHelper) } } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { when (call.method) { "initialize" -> initialize(call, result) "registerCallback" -> registerCallback(call, result) "enqueue" -> enqueue(call, result) "loadTasks" -> loadTasks(result) "loadTasksWithRawQuery" -> loadTasksWithRawQuery(call, result) "cancel" -> cancel(call, result) "cancelAll" -> cancelAll(result) "pause" -> pause(call, result) "resume" -> resume(call, result) "retry" -> retry(call, result) "open" -> open(call, result) "remove" -> remove(call, result) else -> result.notImplemented() } } override fun onAttachedToEngine(binding: FlutterPluginBinding) { onAttachedToEngine(binding.applicationContext, binding.binaryMessenger) } override fun onDetachedFromEngine(binding: FlutterPluginBinding) { context = null flutterChannel?.setMethodCallHandler(null) flutterChannel = null } private fun requireContext() = requireNotNull(context) private fun buildRequest( url: String?, savedDir: String?, filename: String?, headers: String?, showNotification: Boolean, openFileFromNotification: Boolean, isResume: Boolean, requiresStorageNotLow: Boolean, saveInPublicStorage: Boolean, timeout: Int, allowCellular: Boolean ): WorkRequest { return OneTimeWorkRequest.Builder(DownloadWorker::class.java) .setConstraints( Constraints.Builder() .setRequiresStorageNotLow(requiresStorageNotLow) .setRequiredNetworkType(if (allowCellular) NetworkType.CONNECTED else NetworkType.UNMETERED) .build() ) .addTag(TAG) .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS) .setInputData( Data.Builder() .putString(DownloadWorker.ARG_URL, url) .putString(DownloadWorker.ARG_SAVED_DIR, savedDir) .putString(DownloadWorker.ARG_FILE_NAME, filename) .putString(DownloadWorker.ARG_HEADERS, headers) .putBoolean(DownloadWorker.ARG_SHOW_NOTIFICATION, showNotification) .putBoolean( DownloadWorker.ARG_OPEN_FILE_FROM_NOTIFICATION, openFileFromNotification ) .putBoolean(DownloadWorker.ARG_IS_RESUME, isResume) .putLong(DownloadWorker.ARG_CALLBACK_HANDLE, callbackHandle) .putInt(DownloadWorker.ARG_STEP, step) .putBoolean(DownloadWorker.ARG_DEBUG, debugMode == 1) .putBoolean(DownloadWorker.ARG_IGNORESSL, ignoreSsl == 1) .putBoolean( DownloadWorker.ARG_SAVE_IN_PUBLIC_STORAGE, saveInPublicStorage ) .putInt(DownloadWorker.ARG_TIMEOUT, timeout) .build() ) .build() } private fun sendUpdateProgress(id: String, status: DownloadStatus, progress: Int) { val args: MutableMap<String, Any> = HashMap() args["task_id"] = id args["status"] = status.ordinal args["progress"] = progress flutterChannel?.invokeMethod("updateProgress", args) } private fun initialize(call: MethodCall, result: MethodChannel.Result) { val args = call.arguments as List<*> val callbackHandle = args[0].toString().toLong() debugMode = args[1].toString().toInt() ignoreSsl = args[2].toString().toInt() val pref = context?.getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE) pref?.edit()?.putLong(CALLBACK_DISPATCHER_HANDLE_KEY, callbackHandle)?.apply() result.success(null) } private fun registerCallback(call: MethodCall, result: MethodChannel.Result) { val args = call.arguments as List<*> callbackHandle = args[0].toString().toLong() step = args[1].toString().toInt() result.success(null) } private fun <T> MethodCall.requireArgument(key: String): T = requireNotNull(argument(key)) { "Required key '$key' was null" } private fun enqueue(call: MethodCall, result: MethodChannel.Result) { val url: String = call.requireArgument("url") val savedDir: String = call.requireArgument("saved_dir") val filename: String? = call.argument("file_name") val headers: String = call.requireArgument("headers") val timeout: Int = call.requireArgument("timeout") val showNotification: Boolean = call.requireArgument("show_notification") val openFileFromNotification: Boolean = call.requireArgument("open_file_from_notification") val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") val saveInPublicStorage: Boolean = call.requireArgument("save_in_public_storage") val allowCellular: Boolean = call.requireArgument("allow_cellular") val request: WorkRequest = buildRequest( url, savedDir, filename, headers, showNotification, openFileFromNotification, false, requiresStorageNotLow, saveInPublicStorage, timeout, allowCellular = allowCellular ) WorkManager.getInstance(requireContext()).enqueue(request) val taskId: String = request.id.toString() result.success(taskId) sendUpdateProgress(taskId, DownloadStatus.ENQUEUED, 0) taskDao!!.insertOrUpdateNewTask( taskId, url, DownloadStatus.ENQUEUED, 0, filename, savedDir, headers, showNotification, openFileFromNotification, saveInPublicStorage, allowCellular = allowCellular ) } private fun loadTasks(result: MethodChannel.Result) { val tasks = taskDao!!.loadAllTasks() val array: MutableList<Map<*, *>> = ArrayList() for (task in tasks) { val item: MutableMap<String, Any?> = HashMap() item["task_id"] = task.taskId item["status"] = task.status.ordinal item["progress"] = task.progress item["url"] = task.url item["file_name"] = task.filename item["saved_dir"] = task.savedDir item["time_created"] = task.timeCreated item["allow_cellular"] = task.allowCellular array.add(item) } result.success(array) } private fun loadTasksWithRawQuery(call: MethodCall, result: MethodChannel.Result) { val query: String = call.requireArgument("query") val tasks = taskDao!!.loadTasksWithRawQuery(query) val array: MutableList<Map<*, *>> = ArrayList() for (task in tasks) { val item: MutableMap<String, Any?> = HashMap() item["task_id"] = task.taskId item["status"] = task.status.ordinal item["progress"] = task.progress item["url"] = task.url item["file_name"] = task.filename item["saved_dir"] = task.savedDir item["time_created"] = task.timeCreated item["allow_cellular"] = task.allowCellular array.add(item) } result.success(array) } private fun cancel(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) result.success(null) } private fun cancelAll(result: MethodChannel.Result) { WorkManager.getInstance(requireContext()).cancelAllWorkByTag(TAG) result.success(null) } private fun pause(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") // mark the current task is cancelled to process pause request // the worker will depends on this flag to prepare data for resume request taskDao!!.updateTask(taskId, true) // cancel running task, this method causes WorkManager.isStopped() turning true and the download loop will be stopped WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) result.success(null) } private fun resume(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") var timeout: Int = call.requireArgument("timeout") if (task != null) { if (task.status == DownloadStatus.PAUSED) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } val partialFilePath = task.savedDir + File.separator + filename val partialFile = File(partialFilePath) if (partialFile.exists()) { val request: WorkRequest = buildRequest( task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, true, requiresStorageNotLow, task.saveInPublicStorage, timeout, allowCellular = task.allowCellular ) val newTaskId: String = request.id.toString() result.success(newTaskId) sendUpdateProgress(newTaskId, DownloadStatus.RUNNING, task.progress) taskDao!!.updateTask( taskId, newTaskId, DownloadStatus.RUNNING, task.progress, false ) WorkManager.getInstance(requireContext()).enqueue(request) } else { taskDao!!.updateTask(taskId, false) result.error( invalidData, "not found partial downloaded data, this task cannot be resumed", null ) } } else { result.error(invalidStatus, "only paused task can be resumed", null) } } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun retry(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) val requiresStorageNotLow: Boolean = call.requireArgument("requires_storage_not_low") var timeout: Int = call.requireArgument("timeout") if (task != null) { if (task.status == DownloadStatus.FAILED || task.status == DownloadStatus.CANCELED) { val request: WorkRequest = buildRequest( task.url, task.savedDir, task.filename, task.headers, task.showNotification, task.openFileFromNotification, false, requiresStorageNotLow, task.saveInPublicStorage, timeout, allowCellular = task.allowCellular ) val newTaskId: String = request.id.toString() result.success(newTaskId) sendUpdateProgress(newTaskId, DownloadStatus.ENQUEUED, task.progress) taskDao!!.updateTask( taskId, newTaskId, DownloadStatus.ENQUEUED, task.progress, false ) WorkManager.getInstance(requireContext()).enqueue(request) } else { result.error(invalidStatus, "only failed and canceled task can be retried", null) } } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun open(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val task = taskDao!!.loadTask(taskId) if (task == null) { result.error(invalidTaskId, "not found task with id $taskId", null) return } if (task.status != DownloadStatus.COMPLETE) { result.error(invalidStatus, "only completed tasks can be opened", null) return } val fileURL = task.url val savedDir = task.savedDir var filename = task.filename if (filename == null) { filename = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length) } val saveFilePath = savedDir + File.separator + filename val intent: Intent? = IntentUtils.validatedFileIntent(requireContext(), saveFilePath, task.mimeType) if (intent != null) { requireContext().startActivity(intent) result.success(true) } else { result.success(false) } } private fun remove(call: MethodCall, result: MethodChannel.Result) { val taskId: String = call.requireArgument("task_id") val shouldDeleteContent: Boolean = call.requireArgument("should_delete_content") val task = taskDao!!.loadTask(taskId) if (task != null) { if (task.status == DownloadStatus.ENQUEUED || task.status == DownloadStatus.RUNNING) { WorkManager.getInstance(requireContext()).cancelWorkById(UUID.fromString(taskId)) } if (shouldDeleteContent) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } val saveFilePath = task.savedDir + File.separator + filename val tempFile = File(saveFilePath) if (tempFile.exists()) { try { deleteFileInMediaStore(tempFile) } catch (e: SecurityException) { Log.d( "FlutterDownloader", "Failed to delete file in media store, will fall back to normal delete()" ) } tempFile.delete() } } taskDao!!.deleteTask(taskId) NotificationManagerCompat.from(requireContext()).cancel(task.primaryId) result.success(null) } else { result.error(invalidTaskId, "not found task corresponding to given task id", null) } } private fun deleteFileInMediaStore(file: File) { // Set up the projection (we only need the ID) val projection = arrayOf(MediaStore.Images.Media._ID) // Match on the file path val imageSelection: String = MediaStore.Images.Media.DATA + " = ?" val selectionArgs = arrayOf<String>(file.absolutePath) // Query for the ID of the media matching the file path val imageQueryUri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI val contentResolver: ContentResolver = requireContext().contentResolver // search the file in image store first val imageCursor = contentResolver.query(imageQueryUri, projection, imageSelection, selectionArgs, null) if (imageCursor != null && imageCursor.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file val id: Long = imageCursor.getLong(imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)) val deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) contentResolver.delete(deleteUri, null, null) } else { // File not found in image store DB, try to search in video store val videoCursor = contentResolver.query(imageQueryUri, projection, imageSelection, selectionArgs, null) if (videoCursor != null && videoCursor.moveToFirst()) { // We found the ID. Deleting the item via the content provider will also remove the file val id: Long = videoCursor.getLong(videoCursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)) val deleteUri: Uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id) contentResolver.delete(deleteUri, null, null) } else { // can not find the file in media store DB at all } videoCursor?.close() } imageCursor?.close() } companion object { private const val CHANNEL = "vn.hunghd/downloader" private const val TAG = "flutter_download_task" const val SHARED_PREFERENCES_KEY = "vn.hunghd.downloader.pref" const val CALLBACK_DISPATCHER_HANDLE_KEY = "callback_dispatcher_handle_key" } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/FlutterDownloaderPlugin.kt
2159191128
package vn.hunghd.flutterdownloader import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import androidx.core.content.FileProvider import java.io.File import java.io.FileInputStream import java.io.IOException import java.lang.Exception import java.net.URLConnection import kotlin.jvm.Synchronized object IntentUtils { private fun buildIntent(context: Context, file: File, mime: String?): Intent { val intent = Intent(Intent.ACTION_VIEW) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val uri = FileProvider.getUriForFile( context, context.packageName + ".flutter_downloader.provider", file ) intent.setDataAndType(uri, mime) } else { intent.setDataAndType(Uri.fromFile(file), mime) } intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) return intent } @Synchronized fun validatedFileIntent(context: Context, path: String, contentType: String?): Intent? { val file = File(path) var intent = buildIntent(context, file, contentType) if (canBeHandled(context, intent)) { return intent } var mime: String? = null var inputFile: FileInputStream? = null try { inputFile = FileInputStream(path) mime = URLConnection.guessContentTypeFromStream(inputFile) // fails sometimes } catch (e: Exception) { e.printStackTrace() } finally { if (inputFile != null) { try { inputFile.close() } catch (e: IOException) { e.printStackTrace() } } } if (mime == null) { mime = URLConnection.guessContentTypeFromName(path) // fallback to check file extension } if (mime != null) { intent = buildIntent(context, file, mime) if (canBeHandled(context, intent)) return intent } return null } private fun canBeHandled(context: Context, intent: Intent): Boolean { val manager = context.packageManager val results = manager.queryIntentActivities(intent, 0) // return if there is at least one app that can handle this intent return results.size > 0 } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/IntentUtils.kt
3181690995
package vn.hunghd.flutterdownloader enum class DownloadStatus { UNDEFINED, ENQUEUED, RUNNING, COMPLETE, FAILED, CANCELED, PAUSED }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadStatus.kt
492954288
package vn.hunghd.flutterdownloader import android.provider.BaseColumns object TaskEntry : BaseColumns { const val TABLE_NAME = "task" const val COLUMN_NAME_TASK_ID = "task_id" const val COLUMN_NAME_STATUS = "status" const val COLUMN_NAME_PROGRESS = "progress" const val COLUMN_NAME_URL = "url" const val COLUMN_NAME_SAVED_DIR = "saved_dir" const val COLUMN_NAME_FILE_NAME = "file_name" const val COLUMN_NAME_MIME_TYPE = "mime_type" const val COLUMN_NAME_RESUMABLE = "resumable" const val COLUMN_NAME_HEADERS = "headers" const val COLUMN_NAME_SHOW_NOTIFICATION = "show_notification" const val COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION = "open_file_from_notification" const val COLUMN_NAME_TIME_CREATED = "time_created" const val COLUMN_SAVE_IN_PUBLIC_STORAGE = "save_in_public_storage" const val COLUMN_ALLOW_CELLULAR = "allow_cellular" }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskEntry.kt
3733632638
package vn.hunghd.flutterdownloader import android.content.ComponentName import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.content.pm.PackageManager import android.content.pm.PackageManager.NameNotFoundException import android.net.Uri import android.util.Log import androidx.work.Configuration import androidx.work.WorkManager import java.util.concurrent.Executors class FlutterDownloaderInitializer : ContentProvider() { companion object { private const val TAG = "DownloaderInitializer" private const val DEFAULT_MAX_CONCURRENT_TASKS = 3 } override fun onCreate(): Boolean { val context = requireNotNull(this.context) { "Cannot find context from the provider." } val maximumConcurrentTask = getMaxConcurrentTaskMetadata(context) WorkManager.initialize( context, Configuration.Builder() .setExecutor(Executors.newFixedThreadPool(maximumConcurrentTask)) .build() ) return true } override fun query(uri: Uri, strings: Array<String>?, s: String?, strings1: Array<String>?, s1: String?): Nothing? = null override fun getType(uri: Uri): Nothing? = null override fun insert(uri: Uri, contentValues: ContentValues?): Uri? = null override fun delete(uri: Uri, s: String?, strings: Array<String>?) = 0 override fun update(uri: Uri, contentValues: ContentValues?, s: String?, strings: Array<String>?) = 0 private fun getMaxConcurrentTaskMetadata(context: Context): Int { try { val providerInfo = context.packageManager.getProviderInfo( ComponentName(context, "vn.hunghd.flutterdownloader.FlutterDownloaderInitializer"), PackageManager.GET_META_DATA ) val bundle = providerInfo.metaData val max = bundle.getInt( "vn.hunghd.flutterdownloader.MAX_CONCURRENT_TASKS", DEFAULT_MAX_CONCURRENT_TASKS ) Log.d(TAG, "MAX_CONCURRENT_TASKS = $max") return max } catch (e: NameNotFoundException) { Log.e(TAG, "Failed to load meta-data, NameNotFound: " + e.message) } catch (e: NullPointerException) { Log.e(TAG, "Failed to load meta-data, NullPointer: " + e.message) } return DEFAULT_MAX_CONCURRENT_TASKS } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/FlutterDownloaderInitializer.kt
3756968175
package vn.hunghd.flutterdownloader data class DownloadTask( var primaryId: Int, var taskId: String, var status: DownloadStatus, var progress: Int, var url: String, var filename: String?, var savedDir: String, var headers: String, var mimeType: String, var resumable: Boolean, var showNotification: Boolean, var openFileFromNotification: Boolean, var timeCreated: Long, var saveInPublicStorage: Boolean, var allowCellular: Boolean )
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadTask.kt
1531714841
package vn.hunghd.flutterdownloader import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.provider.BaseColumns class TaskDbHelper private constructor(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.execSQL(SQL_CREATE_ENTRIES) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { if (newVersion == 4) { db.execSQL("ALTER TABLE ${TaskEntry.TABLE_NAME} ADD COLUMN ${TaskEntry.COLUMN_ALLOW_CELLULAR} TINYINT DEFAULT 1") } else if (oldVersion == 2 && newVersion == 3) { db.execSQL("ALTER TABLE " + TaskEntry.TABLE_NAME + " ADD COLUMN " + TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE + " TINYINT DEFAULT 0") } else { db.execSQL(SQL_DELETE_ENTRIES) onCreate(db) } } override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { onUpgrade(db, oldVersion, newVersion) } companion object { const val DATABASE_VERSION = 4 const val DATABASE_NAME = "download_tasks.db" private var instance: TaskDbHelper? = null private const val SQL_CREATE_ENTRIES = ( "CREATE TABLE " + TaskEntry.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY," + TaskEntry.COLUMN_NAME_TASK_ID + " VARCHAR(256), " + TaskEntry.COLUMN_NAME_URL + " TEXT, " + TaskEntry.COLUMN_NAME_STATUS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_PROGRESS + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_NAME_FILE_NAME + " TEXT, " + TaskEntry.COLUMN_NAME_SAVED_DIR + " TEXT, " + TaskEntry.COLUMN_NAME_HEADERS + " TEXT, " + TaskEntry.COLUMN_NAME_MIME_TYPE + " VARCHAR(128), " + TaskEntry.COLUMN_NAME_RESUMABLE + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_NAME_TIME_CREATED + " INTEGER DEFAULT 0, " + TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE + " TINYINT DEFAULT 0, " + TaskEntry.COLUMN_ALLOW_CELLULAR + " TINYINT DEFAULT 1" + ")" ) private const val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS ${TaskEntry.TABLE_NAME}" fun getInstance(ctx: Context?): TaskDbHelper { // Use the application context, which will ensure that you // don't accidentally leak an Activity's context. // See this article for more information: http://bit.ly/6LRzfx if (instance == null) { instance = TaskDbHelper(ctx!!.applicationContext) } return instance!! } } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskDbHelper.kt
3400468753
package vn.hunghd.flutterdownloader import androidx.core.content.FileProvider class DownloadedFileProvider : FileProvider()
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadedFileProvider.kt
949855946
package vn.hunghd.flutterdownloader import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentValues import android.content.Context import android.content.SharedPreferences import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Environment import android.os.Handler import android.provider.MediaStore import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import androidx.work.Worker import androidx.work.WorkerParameters import io.flutter.FlutterInjector import io.flutter.embedding.engine.FlutterEngine import io.flutter.embedding.engine.dart.DartExecutor import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.view.FlutterCallbackInformation import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.io.UnsupportedEncodingException import java.net.HttpURLConnection import java.net.URL import java.net.URLDecoder import java.security.SecureRandom import java.security.cert.X509Certificate import java.util.ArrayDeque import java.util.Locale import java.util.concurrent.atomic.AtomicBoolean import java.util.regex.Pattern import javax.net.ssl.HostnameVerifier import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLContext import javax.net.ssl.TrustManager import javax.net.ssl.X509TrustManager class DownloadWorker(context: Context, params: WorkerParameters) : Worker(context, params), MethodChannel.MethodCallHandler { private val charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)") private val filenameStarPattern = Pattern.compile("(?i)\\bfilename\\*=([^']+)'([^']*)'\"?([^\"]+)\"?") private val filenamePattern = Pattern.compile("(?i)\\bfilename=\"?([^\"]+)\"?") private var backgroundChannel: MethodChannel? = null private var dbHelper: TaskDbHelper? = null private var taskDao: TaskDao? = null private var showNotification = false private var clickToOpenDownloadedFile = false private var debug = false private var ignoreSsl = false private var lastProgress = 0 private var primaryId = 0 private var msgStarted: String? = null private var msgInProgress: String? = null private var msgCanceled: String? = null private var msgFailed: String? = null private var msgPaused: String? = null private var msgComplete: String? = null private var lastCallUpdateNotification: Long = 0 private var step = 0 private var saveInPublicStorage = false private fun startBackgroundIsolate(context: Context) { synchronized(isolateStarted) { if (backgroundFlutterEngine == null) { val pref: SharedPreferences = context.getSharedPreferences( FlutterDownloaderPlugin.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE ) val callbackHandle: Long = pref.getLong( FlutterDownloaderPlugin.CALLBACK_DISPATCHER_HANDLE_KEY, 0 ) backgroundFlutterEngine = FlutterEngine(applicationContext, null, false) // We need to create an instance of `FlutterEngine` before looking up the // callback. If we don't, the callback cache won't be initialized and the // lookup will fail. val flutterCallback: FlutterCallbackInformation? = FlutterCallbackInformation.lookupCallbackInformation(callbackHandle) if (flutterCallback == null) { log("Fatal: failed to find callback") return } val appBundlePath: String = FlutterInjector.instance().flutterLoader().findAppBundlePath() val assets = applicationContext.assets backgroundFlutterEngine?.dartExecutor?.executeDartCallback( DartExecutor.DartCallback( assets, appBundlePath, flutterCallback ) ) } } backgroundChannel = MethodChannel( backgroundFlutterEngine!!.dartExecutor, "vn.hunghd/downloader_background" ) backgroundChannel?.setMethodCallHandler(this) } override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { if (call.method.equals("didInitializeDispatcher")) { synchronized(isolateStarted) { while (!isolateQueue.isEmpty()) { backgroundChannel?.invokeMethod("", isolateQueue.remove()) } isolateStarted.set(true) result.success(null) } } else { result.notImplemented() } } override fun onStopped() { val context: Context = applicationContext dbHelper = TaskDbHelper.getInstance(context) taskDao = TaskDao(dbHelper!!) val url: String? = inputData.getString(ARG_URL) val filename: String? = inputData.getString(ARG_FILE_NAME) val task = taskDao?.loadTask(id.toString()) if (task != null && task.status == DownloadStatus.ENQUEUED) { updateNotification(context, filename ?: url, DownloadStatus.CANCELED, -1, null, true) taskDao?.updateTask(id.toString(), DownloadStatus.CANCELED, lastProgress) } } override fun doWork(): Result { dbHelper = TaskDbHelper.getInstance(applicationContext) taskDao = TaskDao(dbHelper!!) val url: String = inputData.getString(ARG_URL) ?: throw IllegalArgumentException("Argument '$ARG_URL' should not be null") val filename: String? = inputData.getString(ARG_FILE_NAME) // ?: throw IllegalArgumentException("Argument '$ARG_FILE_NAME' should not be null") val savedDir: String = inputData.getString(ARG_SAVED_DIR) ?: throw IllegalArgumentException("Argument '$ARG_SAVED_DIR' should not be null") val headers: String = inputData.getString(ARG_HEADERS) ?: throw IllegalArgumentException("Argument '$ARG_HEADERS' should not be null") var isResume: Boolean = inputData.getBoolean(ARG_IS_RESUME, false) val timeout: Int = inputData.getInt(ARG_TIMEOUT, 15000) debug = inputData.getBoolean(ARG_DEBUG, false) step = inputData.getInt(ARG_STEP, 10) ignoreSsl = inputData.getBoolean(ARG_IGNORESSL, false) val res = applicationContext.resources msgStarted = res.getString(R.string.flutter_downloader_notification_started) msgInProgress = res.getString(R.string.flutter_downloader_notification_in_progress) msgCanceled = res.getString(R.string.flutter_downloader_notification_canceled) msgFailed = res.getString(R.string.flutter_downloader_notification_failed) msgPaused = res.getString(R.string.flutter_downloader_notification_paused) msgComplete = res.getString(R.string.flutter_downloader_notification_complete) val task = taskDao?.loadTask(id.toString()) log( "DownloadWorker{url=$url,filename=$filename,savedDir=$savedDir,header=$headers,isResume=$isResume,status=" + ( task?.status ?: "GONE" ) ) // Task has been deleted or cancelled if (task == null || task.status == DownloadStatus.CANCELED) { return Result.success() } showNotification = inputData.getBoolean(ARG_SHOW_NOTIFICATION, false) clickToOpenDownloadedFile = inputData.getBoolean(ARG_OPEN_FILE_FROM_NOTIFICATION, false) saveInPublicStorage = inputData.getBoolean(ARG_SAVE_IN_PUBLIC_STORAGE, false) primaryId = task.primaryId setupNotification(applicationContext) updateNotification( applicationContext, filename ?: url, DownloadStatus.RUNNING, task.progress, null, false ) taskDao?.updateTask(id.toString(), DownloadStatus.RUNNING, task.progress) // automatic resume for partial files. (if the workmanager unexpectedly quited in background) val saveFilePath = savedDir + File.separator + filename val partialFile = File(saveFilePath) if (partialFile.exists()) { isResume = true log("exists file for " + filename + "automatic resuming...") } return try { downloadFile(applicationContext, url, savedDir, filename, headers, isResume, timeout) cleanUp() dbHelper = null taskDao = null Result.success() } catch (e: Exception) { updateNotification(applicationContext, filename ?: url, DownloadStatus.FAILED, -1, null, true) taskDao?.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress) e.printStackTrace() dbHelper = null taskDao = null Result.failure() } } private fun setupHeaders(conn: HttpURLConnection, headers: String) { if (headers.isNotEmpty()) { log("Headers = $headers") try { val json = JSONObject(headers) val it: Iterator<String> = json.keys() while (it.hasNext()) { val key = it.next() conn.setRequestProperty(key, json.getString(key)) } conn.doInput = true } catch (e: JSONException) { e.printStackTrace() } } } private fun setupPartialDownloadedDataHeader( conn: HttpURLConnection, filename: String?, savedDir: String ): Long { val saveFilePath = savedDir + File.separator + filename val partialFile = File(saveFilePath) val downloadedBytes: Long = partialFile.length() log("Resume download: Range: bytes=$downloadedBytes-") conn.setRequestProperty("Accept-Encoding", "identity") conn.setRequestProperty("Range", "bytes=$downloadedBytes-") conn.doInput = true return downloadedBytes } private fun downloadFile( context: Context, fileURL: String, savedDir: String, filename: String?, headers: String, isResume: Boolean, timeout: Int ) { var actualFilename = filename var url = fileURL var resourceUrl: URL var base: URL? var next: URL val visited: MutableMap<String, Int> var httpConn: HttpURLConnection? = null var inputStream: InputStream? = null var outputStream: OutputStream? = null var location: String var downloadedBytes: Long = 0 var responseCode: Int var times: Int visited = HashMap() try { val task = taskDao?.loadTask(id.toString()) if (task != null) { lastProgress = task.progress } // handle redirection logic while (true) { if (!visited.containsKey(url)) { times = 1 visited[url] = times } else { times = visited[url]!! + 1 } if (times > 3) throw IOException("Stuck in redirect loop") resourceUrl = URL(url) httpConn = if (ignoreSsl) { trustAllHosts() if (resourceUrl.protocol.lowercase(Locale.US) == "https") { val https: HttpsURLConnection = resourceUrl.openConnection() as HttpsURLConnection https.hostnameVerifier = DO_NOT_VERIFY https } else { resourceUrl.openConnection() as HttpURLConnection } } else { if (resourceUrl.protocol.lowercase(Locale.US) == "https") { resourceUrl.openConnection() as HttpsURLConnection } else { resourceUrl.openConnection() as HttpURLConnection } } log("Open connection to $url") httpConn.connectTimeout = timeout httpConn.readTimeout = timeout httpConn.instanceFollowRedirects = false // Make the logic below easier to detect redirections httpConn.setRequestProperty("User-Agent", "Mozilla/5.0...") // setup request headers if it is set setupHeaders(httpConn, headers) // try to continue downloading a file from its partial downloaded data. if (isResume) { downloadedBytes = setupPartialDownloadedDataHeader(httpConn, actualFilename, savedDir) } responseCode = httpConn.responseCode when (responseCode) { HttpURLConnection.HTTP_MOVED_PERM, HttpURLConnection.HTTP_SEE_OTHER, HttpURLConnection.HTTP_MOVED_TEMP, 307, 308 -> { log("Response with redirection code") location = httpConn.getHeaderField("Location") log("Location = $location") base = URL(url) next = URL(base, location) // Deal with relative URLs url = next.toExternalForm() log("New url: $url") continue } } break } httpConn!!.connect() val contentType: String if ((responseCode == HttpURLConnection.HTTP_OK || isResume && responseCode == HttpURLConnection.HTTP_PARTIAL) && !isStopped) { contentType = httpConn.contentType val contentLength: Long = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) httpConn.contentLengthLong else httpConn.contentLength.toLong() log("Content-Type = $contentType") log("Content-Length = $contentLength") val charset = getCharsetFromContentType(contentType) log("Charset = $charset") if (!isResume) { // try to extract filename from HTTP headers if it is not given by user if (actualFilename == null) { val disposition: String? = httpConn.getHeaderField("Content-Disposition") log("Content-Disposition = $disposition") if (!disposition.isNullOrEmpty()) { actualFilename = getFileNameFromContentDisposition(disposition, charset) } if (actualFilename.isNullOrEmpty()) { actualFilename = url.substring(url.lastIndexOf("/") + 1) try { actualFilename = URLDecoder.decode(actualFilename, "UTF-8") } catch (e: IllegalArgumentException) { /* ok, just let filename be not encoded */ e.printStackTrace() } } } } log("fileName = $actualFilename") taskDao?.updateTask(id.toString(), actualFilename, contentType) // opens input stream from the HTTP connection inputStream = httpConn.inputStream val savedFilePath: String? // opens an output stream to save into file // there are two case: if (isResume) { // 1. continue downloading (append data to partial downloaded file) savedFilePath = savedDir + File.separator + actualFilename outputStream = FileOutputStream(savedFilePath, true) } else { // 2. new download, create new file // there are two case according to Android SDK version and save path // From Android 11 onwards, file is only downloaded to app-specific directory (internal storage) // or public shared download directory (external storage). // The second option will ignore `savedDir` parameter. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && saveInPublicStorage) { val uri = createFileInPublicDownloadsDir(actualFilename, contentType) savedFilePath = getMediaStoreEntryPathApi29(uri!!) outputStream = context.contentResolver.openOutputStream(uri, "w") } else { val file = createFileInAppSpecificDir(actualFilename!!, savedDir) savedFilePath = file!!.path outputStream = FileOutputStream(file, false) } } var count = downloadedBytes var bytesRead: Int val buffer = ByteArray(BUFFER_SIZE) // using isStopped to monitor canceling task while (inputStream.read(buffer).also { bytesRead = it } != -1 && !isStopped) { count += bytesRead.toLong() val progress = (count * 100 / (contentLength + downloadedBytes)).toInt() outputStream?.write(buffer, 0, bytesRead) if ((lastProgress == 0 || progress > lastProgress + step || progress == 100) && progress != lastProgress ) { lastProgress = progress // This line possibly causes system overloaded because of accessing to DB too many ?!!! // but commenting this line causes tasks loaded from DB missing current downloading progress, // however, this missing data should be temporary and it will be updated as soon as // a new bunch of data fetched and a notification sent taskDao!!.updateTask(id.toString(), DownloadStatus.RUNNING, progress) updateNotification( context, actualFilename, DownloadStatus.RUNNING, progress, null, false ) } } val loadedTask = taskDao?.loadTask(id.toString()) val progress = if (isStopped && loadedTask!!.resumable) lastProgress else 100 val status = if (isStopped) if (loadedTask!!.resumable) DownloadStatus.PAUSED else DownloadStatus.CANCELED else DownloadStatus.COMPLETE val storage: Int = ContextCompat.checkSelfPermission( applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE ) var pendingIntent: PendingIntent? = null if (status == DownloadStatus.COMPLETE) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { if (isImageOrVideoFile(contentType) && isExternalStoragePath(savedFilePath)) { addImageOrVideoToGallery( actualFilename, savedFilePath, getContentTypeWithoutCharset(contentType) ) } } if (clickToOpenDownloadedFile) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && storage != PackageManager.PERMISSION_GRANTED) return val intent = IntentUtils.validatedFileIntent( applicationContext, savedFilePath!!, contentType ) if (intent != null) { log("Setting an intent to open the file $savedFilePath") val flags: Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE else PendingIntent.FLAG_CANCEL_CURRENT pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, flags) } else { log("There's no application that can open the file $savedFilePath") } } } taskDao!!.updateTask(id.toString(), status, progress) updateNotification(context, actualFilename, status, progress, pendingIntent, true) log(if (isStopped) "Download canceled" else "File downloaded") } else { val loadedTask = taskDao!!.loadTask(id.toString()) val status = if (isStopped) if (loadedTask!!.resumable) DownloadStatus.PAUSED else DownloadStatus.CANCELED else DownloadStatus.FAILED taskDao!!.updateTask(id.toString(), status, lastProgress) updateNotification(context, actualFilename ?: fileURL, status, -1, null, true) log(if (isStopped) "Download canceled" else "Server replied HTTP code: $responseCode") } } catch (e: IOException) { taskDao!!.updateTask(id.toString(), DownloadStatus.FAILED, lastProgress) updateNotification(context, actualFilename ?: fileURL, DownloadStatus.FAILED, -1, null, true) e.printStackTrace() } finally { if (outputStream != null) { outputStream.flush() try { outputStream.close() } catch (e: IOException) { e.printStackTrace() } } if (inputStream != null) { try { inputStream.close() } catch (e: IOException) { e.printStackTrace() } } httpConn?.disconnect() } } /** * Create a file using java.io API */ private fun createFileInAppSpecificDir(filename: String, savedDir: String): File? { val newFile = File(savedDir, filename) try { val rs: Boolean = newFile.createNewFile() if (rs) { return newFile } else { logError("It looks like you are trying to save file in public storage but not setting 'saveInPublicStorage' to 'true'") } } catch (e: IOException) { e.printStackTrace() logError("Create a file using java.io API failed ") } return null } /** * Create a file inside the Download folder using MediaStore API */ @RequiresApi(Build.VERSION_CODES.Q) private fun createFileInPublicDownloadsDir(filename: String?, mimeType: String): Uri? { val collection: Uri = MediaStore.Downloads.EXTERNAL_CONTENT_URI val values = ContentValues() values.put(MediaStore.Downloads.DISPLAY_NAME, filename) values.put(MediaStore.Downloads.MIME_TYPE, mimeType) values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) val contentResolver = applicationContext.contentResolver try { return contentResolver.insert(collection, values) } catch (e: Exception) { e.printStackTrace() logError("Create a file using MediaStore API failed.") } return null } /** * Get a path for a MediaStore entry as it's needed when calling MediaScanner */ private fun getMediaStoreEntryPathApi29(uri: Uri): String? { try { applicationContext.contentResolver.query( uri, arrayOf(MediaStore.Files.FileColumns.DATA), null, null, null ).use { cursor -> if (cursor == null) return null return if (!cursor.moveToFirst()) { null } else { cursor.getString( cursor.getColumnIndexOrThrow( MediaStore.Files.FileColumns.DATA ) ) } } } catch (e: IllegalArgumentException) { e.printStackTrace() logError("Get a path for a MediaStore failed") return null } } private fun cleanUp() { val task = taskDao!!.loadTask(id.toString()) if (task != null && task.status != DownloadStatus.COMPLETE && !task.resumable) { var filename = task.filename if (filename == null) { filename = task.url.substring(task.url.lastIndexOf("/") + 1, task.url.length) } // check and delete uncompleted file val saveFilePath = task.savedDir + File.separator + filename val tempFile = File(saveFilePath) if (tempFile.exists()) { tempFile.delete() } } } private val notificationIconRes: Int get() { try { val applicationInfo: ApplicationInfo = applicationContext.packageManager .getApplicationInfo( applicationContext.packageName, PackageManager.GET_META_DATA ) val appIconResId: Int = applicationInfo.icon return applicationInfo.metaData.getInt( "vn.hunghd.flutterdownloader.NOTIFICATION_ICON", appIconResId ) } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return 0 } private fun setupNotification(context: Context) { if (!showNotification) return // Make a channel if necessary if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel val res = applicationContext.resources val channelName: String = res.getString(R.string.flutter_downloader_notification_channel_name) val channelDescription: String = res.getString(R.string.flutter_downloader_notification_channel_description) val importance: Int = NotificationManager.IMPORTANCE_LOW val channel = NotificationChannel(CHANNEL_ID, channelName, importance) channel.description = channelDescription channel.setSound(null, null) // Add the channel val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(context) notificationManager.createNotificationChannel(channel) } } private fun updateNotification( context: Context, title: String?, status: DownloadStatus, progress: Int, intent: PendingIntent?, finalize: Boolean ) { sendUpdateProcessEvent(status, progress) // Show the notification if (showNotification) { // Create the notification val builder = NotificationCompat.Builder(context, CHANNEL_ID).setContentTitle(title) .setContentIntent(intent) .setOnlyAlertOnce(true) .setAutoCancel(true) .setPriority(NotificationCompat.PRIORITY_LOW) when (status) { DownloadStatus.RUNNING -> { if (progress <= 0) { builder.setContentText(msgStarted) .setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(notificationIconRes) } else if (progress < 100) { builder.setContentText(msgInProgress) .setProgress(100, progress, false) builder.setOngoing(true) .setSmallIcon(android.R.drawable.stat_sys_download) } else { builder.setContentText(msgComplete).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } } DownloadStatus.CANCELED -> { builder.setContentText(msgCanceled).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.FAILED -> { builder.setContentText(msgFailed).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.PAUSED -> { builder.setContentText(msgPaused).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } DownloadStatus.COMPLETE -> { builder.setContentText(msgComplete).setProgress(0, 0, false) builder.setOngoing(false) .setSmallIcon(android.R.drawable.stat_sys_download_done) } else -> { builder.setProgress(0, 0, false) builder.setOngoing(false).setSmallIcon(notificationIconRes) } } // Note: Android applies a rate limit when updating a notification. // If you post updates to a notification too frequently (many in less than one second), // the system might drop some updates. (https://developer.android.com/training/notify-user/build-notification#Updating) // // If this is progress update, it's not much important if it is dropped because there're still incoming updates later // If this is the final update, it must be success otherwise the notification will be stuck at the processing state // In order to ensure the final one is success, we check and sleep a second if need. if (System.currentTimeMillis() - lastCallUpdateNotification < 1000) { if (finalize) { log("Update too frequently!!!!, but it is the final update, we should sleep a second to ensure the update call can be processed") try { Thread.sleep(1000) } catch (e: InterruptedException) { e.printStackTrace() } } else { log("Update too frequently!!!!, this should be dropped") return } } log("Update notification: {notificationId: $primaryId, title: $title, status: $status, progress: $progress}") NotificationManagerCompat.from(context).notify(primaryId, builder.build()) lastCallUpdateNotification = System.currentTimeMillis() } } private fun sendUpdateProcessEvent(status: DownloadStatus, progress: Int) { val args: MutableList<Any> = ArrayList() val callbackHandle: Long = inputData.getLong(ARG_CALLBACK_HANDLE, 0) args.add(callbackHandle) args.add(id.toString()) args.add(status.ordinal) args.add(progress) synchronized(isolateStarted) { if (!isolateStarted.get()) { isolateQueue.add(args) } else { Handler(applicationContext.mainLooper).post { backgroundChannel?.invokeMethod("", args) } } } } private fun getCharsetFromContentType(contentType: String?): String? { if (contentType == null) return null val m = charsetPattern.matcher(contentType) return if (m.find()) { m.group(1)?.trim { it <= ' ' }?.uppercase(Locale.US) } else { null } } @Throws(UnsupportedEncodingException::class) private fun getFileNameFromContentDisposition( disposition: String?, contentCharset: String? ): String? { if (disposition == null) return null var name: String? = null var charset = contentCharset // first, match plain filename, and then replace it with star filename, to follow the spec val plainMatcher = filenamePattern.matcher(disposition) if (plainMatcher.find()) name = plainMatcher.group(1) val starMatcher = filenameStarPattern.matcher(disposition) if (starMatcher.find()) { name = starMatcher.group(3) charset = starMatcher.group(1)?.uppercase(Locale.US) } return if (name == null) { null } else { URLDecoder.decode( name, charset ?: "ISO-8859-1" ) } } private fun getContentTypeWithoutCharset(contentType: String?): String? { return contentType?.split(";")?.toTypedArray()?.get(0)?.trim { it <= ' ' } } private fun isImageOrVideoFile(contentType: String): Boolean { val newContentType = getContentTypeWithoutCharset(contentType) return newContentType != null && (newContentType.startsWith("image/") || newContentType.startsWith("video")) } private fun isExternalStoragePath(filePath: String?): Boolean { val externalStorageDir: File = Environment.getExternalStorageDirectory() return filePath != null && filePath.startsWith( externalStorageDir.path ) } private fun addImageOrVideoToGallery( fileName: String?, filePath: String?, contentType: String? ) { if (contentType != null && filePath != null && fileName != null) { if (contentType.startsWith("image/")) { val values = ContentValues() values.put(MediaStore.Images.Media.TITLE, fileName) values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName) values.put(MediaStore.Images.Media.DESCRIPTION, "") values.put(MediaStore.Images.Media.MIME_TYPE, contentType) values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Images.Media.DATA, filePath) log("insert $values to MediaStore") val contentResolver = applicationContext.contentResolver contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } else if (contentType.startsWith("video")) { val values = ContentValues() values.put(MediaStore.Video.Media.TITLE, fileName) values.put(MediaStore.Video.Media.DISPLAY_NAME, fileName) values.put(MediaStore.Video.Media.DESCRIPTION, "") values.put(MediaStore.Video.Media.MIME_TYPE, contentType) values.put(MediaStore.Video.Media.DATE_ADDED, System.currentTimeMillis()) values.put(MediaStore.Video.Media.DATE_TAKEN, System.currentTimeMillis()) values.put(MediaStore.Video.Media.DATA, filePath) log("insert $values to MediaStore") val contentResolver = applicationContext.contentResolver contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values) } } } private fun log(message: String) { if (debug) { Log.d(TAG, message) } } private fun logError(message: String) { if (debug) { Log.e(TAG, message) } } companion object { const val ARG_URL = "url" const val ARG_FILE_NAME = "file_name" const val ARG_SAVED_DIR = "saved_file" const val ARG_HEADERS = "headers" const val ARG_IS_RESUME = "is_resume" const val ARG_TIMEOUT = "timeout" const val ARG_SHOW_NOTIFICATION = "show_notification" const val ARG_OPEN_FILE_FROM_NOTIFICATION = "open_file_from_notification" const val ARG_CALLBACK_HANDLE = "callback_handle" const val ARG_DEBUG = "debug" const val ARG_STEP = "step" const val ARG_SAVE_IN_PUBLIC_STORAGE = "save_in_public_storage" const val ARG_IGNORESSL = "ignoreSsl" private val TAG = DownloadWorker::class.java.simpleName private const val BUFFER_SIZE = 4096 private const val CHANNEL_ID = "FLUTTER_DOWNLOADER_NOTIFICATION" private val isolateStarted = AtomicBoolean(false) private val isolateQueue = ArrayDeque<List<Any>>() private var backgroundFlutterEngine: FlutterEngine? = null val DO_NOT_VERIFY = HostnameVerifier { _, _ -> true } /** * Trust every server - dont check for any certificate */ private fun trustAllHosts() { val tag = "trustAllHosts" // Create a trust manager that does not validate certificate chains val trustManagers: Array<TrustManager> = arrayOf( @SuppressLint("CustomX509TrustManager") object : X509TrustManager { override fun checkClientTrusted( chain: Array<X509Certificate>, authType: String ) { Log.i(tag, "checkClientTrusted") } override fun checkServerTrusted( chain: Array<X509Certificate>, authType: String ) { Log.i(tag, "checkServerTrusted") } override fun getAcceptedIssuers(): Array<out X509Certificate> = emptyArray() } ) // Install the all-trusting trust manager try { val sslContent: SSLContext = SSLContext.getInstance("TLS") sslContent.init(null, trustManagers, SecureRandom()) HttpsURLConnection.setDefaultSSLSocketFactory(sslContent.socketFactory) } catch (e: Exception) { e.printStackTrace() } } } init { Handler(context.mainLooper).post { startBackgroundIsolate(context) } } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/DownloadWorker.kt
1466250551
package vn.hunghd.flutterdownloader import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.provider.BaseColumns class TaskDao(private val dbHelper: TaskDbHelper) { private val projection = arrayOf( BaseColumns._ID, TaskEntry.COLUMN_NAME_TASK_ID, TaskEntry.COLUMN_NAME_PROGRESS, TaskEntry.COLUMN_NAME_STATUS, TaskEntry.COLUMN_NAME_URL, TaskEntry.COLUMN_NAME_FILE_NAME, TaskEntry.COLUMN_NAME_SAVED_DIR, TaskEntry.COLUMN_NAME_HEADERS, TaskEntry.COLUMN_NAME_MIME_TYPE, TaskEntry.COLUMN_NAME_RESUMABLE, TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION, TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION, TaskEntry.COLUMN_NAME_TIME_CREATED, TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE, TaskEntry.COLUMN_ALLOW_CELLULAR ) fun insertOrUpdateNewTask( taskId: String?, url: String?, status: DownloadStatus, progress: Int, fileName: String?, savedDir: String?, headers: String?, showNotification: Boolean, openFileFromNotification: Boolean, saveInPublicStorage: Boolean, allowCellular: Boolean ) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_TASK_ID, taskId) values.put(TaskEntry.COLUMN_NAME_URL, url) values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) values.put(TaskEntry.COLUMN_NAME_FILE_NAME, fileName) values.put(TaskEntry.COLUMN_NAME_SAVED_DIR, savedDir) values.put(TaskEntry.COLUMN_NAME_HEADERS, headers) values.put(TaskEntry.COLUMN_NAME_MIME_TYPE, "unknown") values.put(TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION, if (showNotification) 1 else 0) values.put( TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION, if (openFileFromNotification) 1 else 0 ) values.put(TaskEntry.COLUMN_NAME_RESUMABLE, 0) values.put(TaskEntry.COLUMN_NAME_TIME_CREATED, System.currentTimeMillis()) values.put(TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE, if (saveInPublicStorage) 1 else 0) values.put(TaskEntry.COLUMN_ALLOW_CELLULAR, if (allowCellular) 1 else 0) db.beginTransaction() try { db.insertWithOnConflict( TaskEntry.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_REPLACE ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun loadAllTasks(): List<DownloadTask> { val db = dbHelper.readableDatabase val cursor = db.query( TaskEntry.TABLE_NAME, projection, null, null, null, null, null ) val result: MutableList<DownloadTask> = ArrayList() while (cursor.moveToNext()) { result.add(parseCursor(cursor)) } cursor.close() return result } fun loadTasksWithRawQuery(query: String?): List<DownloadTask> { val db = dbHelper.readableDatabase val cursor = db.rawQuery(query, null) val result: MutableList<DownloadTask> = ArrayList() while (cursor.moveToNext()) { result.add(parseCursor(cursor)) } cursor.close() return result } fun loadTask(taskId: String): DownloadTask? { val db = dbHelper.readableDatabase val whereClause = TaskEntry.COLUMN_NAME_TASK_ID + " = ?" val whereArgs = arrayOf(taskId) val cursor = db.query( TaskEntry.TABLE_NAME, projection, whereClause, whereArgs, null, null, BaseColumns._ID + " DESC", "1" ) var result: DownloadTask? = null while (cursor.moveToNext()) { result = parseCursor(cursor) } cursor.close() return result } fun updateTask(taskId: String, status: DownloadStatus, progress: Int) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask( currentTaskId: String, newTaskId: String?, status: DownloadStatus, progress: Int, resumable: Boolean ) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_TASK_ID, newTaskId) values.put(TaskEntry.COLUMN_NAME_STATUS, status.ordinal) values.put(TaskEntry.COLUMN_NAME_PROGRESS, progress) values.put(TaskEntry.COLUMN_NAME_RESUMABLE, if (resumable) 1 else 0) values.put(TaskEntry.COLUMN_NAME_TIME_CREATED, System.currentTimeMillis()) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(currentTaskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask(taskId: String, resumable: Boolean) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_RESUMABLE, if (resumable) 1 else 0) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun updateTask(taskId: String, filename: String?, mimeType: String?) { val db = dbHelper.writableDatabase val values = ContentValues() values.put(TaskEntry.COLUMN_NAME_FILE_NAME, filename) values.put(TaskEntry.COLUMN_NAME_MIME_TYPE, mimeType) db.beginTransaction() try { db.update( TaskEntry.TABLE_NAME, values, TaskEntry.COLUMN_NAME_TASK_ID + " = ?", arrayOf(taskId) ) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } fun deleteTask(taskId: String) { val db = dbHelper.writableDatabase db.beginTransaction() try { val whereClause = TaskEntry.COLUMN_NAME_TASK_ID + " = ?" val whereArgs = arrayOf(taskId) db.delete(TaskEntry.TABLE_NAME, whereClause, whereArgs) db.setTransactionSuccessful() } catch (e: Exception) { e.printStackTrace() } finally { db.endTransaction() } } private fun parseCursor(cursor: Cursor): DownloadTask { val primaryId = cursor.getInt(cursor.getColumnIndexOrThrow(BaseColumns._ID)) val taskId = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_TASK_ID)) val status = cursor.getInt(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_STATUS)) val progress = cursor.getInt(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_PROGRESS)) val url = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_URL)) val filename = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_FILE_NAME)) val savedDir = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_SAVED_DIR)) val headers = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_HEADERS)) val mimeType = cursor.getString(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_MIME_TYPE)) val resumable = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_RESUMABLE)).toInt() val showNotification = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_SHOW_NOTIFICATION)).toInt() val clickToOpenDownloadedFile = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_OPEN_FILE_FROM_NOTIFICATION)).toInt() val timeCreated = cursor.getLong(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_NAME_TIME_CREATED)) val saveInPublicStorage = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_SAVE_IN_PUBLIC_STORAGE)).toInt() val allowCelluar = cursor.getShort(cursor.getColumnIndexOrThrow(TaskEntry.COLUMN_ALLOW_CELLULAR)).toInt() return DownloadTask( primaryId, taskId, DownloadStatus.values()[status], progress, url, filename, savedDir, headers, mimeType, resumable == 1, showNotification == 1, clickToOpenDownloadedFile == 1, timeCreated, saveInPublicStorage == 1, allowCellular = allowCelluar == 1 ) } }
webview_download_test/flutter_downloader/android/src/main/kotlin/vn/hunghd/flutterdownloader/TaskDao.kt
803343808
package com.example.webview_test import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
webview_download_test/android/app/src/main/kotlin/com/example/webview_test/MainActivity.kt
2228203775
package com.bacancy.focusonunittesting 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.bacancy.focusonunittesting", appContext.packageName) } }
FocusOnUnitTesting/app/src/androidTest/java/com/bacancy/focusonunittesting/ExampleInstrumentedTest.kt
1649104909
package com.bacancy.focusonunittesting 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) } }
FocusOnUnitTesting/app/src/test/java/com/bacancy/focusonunittesting/ExampleUnitTest.kt
761966399
package com.bacancy.focusonunittesting import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
FocusOnUnitTesting/app/src/main/java/com/bacancy/focusonunittesting/MainActivity.kt
634803765
package com.refridev.bankapp 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.bankapp", appContext.packageName) } }
bank-app_google-assistant/app/src/androidTest/java/com/refridev/bankapp/ExampleInstrumentedTest.kt
156556775
package com.refridev.bankapp 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) } }
bank-app_google-assistant/app/src/test/java/com/refridev/bankapp/ExampleUnitTest.kt
3346757455
package com.refridev.bankapp.ui import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainViewModel.kt
2493786221
package com.refridev.bankapp.ui class MainRepository { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/MainRepository.kt
3856117416
package com.refridev.bankapp.ui.transaction interface TransactionSuccessContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/TransactionSuccessContract.kt
2576391578
package com.refridev.bankapp.ui.transaction.pin interface InputPinContract { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinContract.kt
3383427541
package com.refridev.bankapp.ui.transaction.pin import androidx.lifecycle.ViewModel class InputPinViewModel : ViewModel() { }
bank-app_google-assistant/app/src/main/java/com/refridev/bankapp/ui/transaction/pin/InputPinViewModel.kt
2889500703