repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/posts/EditorBloggingPromptsViewModel.kt
1
1679
package org.wordpress.android.ui.posts import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.first import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.store.bloggingprompts.BloggingPromptsStore import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named class EditorBloggingPromptsViewModel @Inject constructor( private val bloggingPromptsStore: BloggingPromptsStore, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : ScopedViewModel(bgDispatcher) { private val _onBloggingPromptLoaded = MutableLiveData<Event<EditorLoadedPrompt>>() val onBloggingPromptLoaded: LiveData<Event<EditorLoadedPrompt>> = _onBloggingPromptLoaded private var isStarted = false fun start(site: SiteModel, bloggingPromptId: Int) { if (bloggingPromptId < 0) { return } if (isStarted) { return } isStarted = true loadPrompt(site, bloggingPromptId) } private fun loadPrompt(site: SiteModel, promptId: Int) = launch { val prompt = bloggingPromptsStore.getPromptById(site, promptId).first().model prompt?.let { _onBloggingPromptLoaded.postValue(Event(EditorLoadedPrompt(promptId, it.content, BLOGGING_PROMPT_TAG))) } } data class EditorLoadedPrompt(val promptId: Int, val content: String, val tag: String) } internal const val BLOGGING_PROMPT_TAG = "dailyprompt"
gpl-2.0
a8978c155be9286c165e7ab7fa01d8ad
35.5
115
0.754616
4.50134
false
false
false
false
ianhanniballake/ContractionTimer
mobile/src/main/java/com/ianhanniballake/contractiontimer/notification/NotificationUpdateReceiver.kt
1
15093
package com.ianhanniballake.contractiontimer.notification import android.app.AlarmManager import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build import android.preference.PreferenceManager import android.provider.BaseColumns import android.text.format.DateUtils import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.RemoteInput import androidx.core.content.ContextCompat import com.ianhanniballake.contractiontimer.BuildConfig import com.ianhanniballake.contractiontimer.R import com.ianhanniballake.contractiontimer.appwidget.AppWidgetToggleReceiver import com.ianhanniballake.contractiontimer.extensions.goAsync import com.ianhanniballake.contractiontimer.provider.ContractionContract import com.ianhanniballake.contractiontimer.ui.MainActivity import com.ianhanniballake.contractiontimer.ui.Preferences import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * BroadcastReceiver which updates the ongoing notification */ class NotificationUpdateReceiver : BroadcastReceiver() { companion object { private const val TAG = "NotificationUpdate" private const val NOTIFICATION_ID = 0 private const val NOTIFICATION_CHANNEL = "timing" fun updateNotification(context: Context) { GlobalScope.launch { update(context) } } private suspend fun update(context: Context) = withContext(Dispatchers.IO) { NoteTranslucentActivity.checkServiceState(context) val notificationManager = NotificationManagerCompat.from(context) val preferences = PreferenceManager.getDefaultSharedPreferences(context) val notificationsEnabled = preferences.getBoolean( Preferences.NOTIFICATION_ENABLE_PREFERENCE_KEY, context.resources.getBoolean(R.bool.pref_notification_enable_default)) if (!notificationsEnabled) { if (BuildConfig.DEBUG) Log.d(TAG, "Notifications disabled, cancelling notification") notificationManager.cancel(NOTIFICATION_ID) return@withContext } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(context) } val projection = arrayOf(BaseColumns._ID, ContractionContract.Contractions.COLUMN_NAME_START_TIME, ContractionContract.Contractions.COLUMN_NAME_END_TIME, ContractionContract.Contractions.COLUMN_NAME_NOTE) val selection = ContractionContract.Contractions.COLUMN_NAME_START_TIME + ">?" val averagesTimeFrame = preferences.getString( Preferences.AVERAGE_TIME_FRAME_PREFERENCE_KEY, context.getString(R.string.pref_average_time_frame_default))!!.toLong() val timeCutoff = System.currentTimeMillis() - averagesTimeFrame val selectionArgs = arrayOf(timeCutoff.toString()) val data = context.contentResolver.query( ContractionContract.Contractions.CONTENT_URI, projection, selection, selectionArgs, null) if (data == null || !data.moveToFirst()) { if (BuildConfig.DEBUG) Log.d(TAG, "No data found, cancelling notification") notificationManager.cancel(NOTIFICATION_ID) data?.close() return@withContext } // Set an alarm to update the notification after first start time + average time frame amount of time // This ensures that if no contraction has started since then (likely, otherwise we would have been called in // the mean time) we will fail the above check as there will be no contractions within the average time period // and the notification will be cancelled val startTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_START_TIME) val lastStartTime = data.getLong(startTimeColumnIndex) val autoCancelIntent = Intent(context, NotificationUpdateReceiver::class.java) val autoCancelPendingIntent = PendingIntent.getBroadcast(context, 0, autoCancelIntent, 0) val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmManager.cancel(autoCancelPendingIntent) // We don't need to wake up the device as it doesn't matter if the notification is cancelled until the device // is woken up alarmManager.set( AlarmManager.RTC, lastStartTime + averagesTimeFrame, autoCancelPendingIntent ) // Build the notification if (BuildConfig.DEBUG) Log.d(TAG, "Building Notification") val builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) val publicBuilder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) builder.setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(context, R.color.primary)) .setCategory(NotificationCompat.CATEGORY_ALARM) publicBuilder.setSmallIcon(R.drawable.ic_notification) .setColor(ContextCompat.getColor(context, R.color.primary)) .setCategory(NotificationCompat.CATEGORY_ALARM) val contentIntent = Intent(context, MainActivity::class.java).apply { addFlags( Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME ) putExtra(MainActivity.LAUNCHED_FROM_NOTIFICATION_EXTRA, true) } val pendingIntent = PendingIntent.getActivity(context, 0, contentIntent, PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(pendingIntent) publicBuilder.setContentIntent(pendingIntent) val wearableExtender = NotificationCompat.WearableExtender() // Determine whether a contraction is currently ongoing val endTimeColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_END_TIME) val contractionOngoing = data.isNull(endTimeColumnIndex) val startStopIntent = Intent(context, AppWidgetToggleReceiver::class.java) startStopIntent.putExtra(AppWidgetToggleReceiver.WIDGET_NAME_EXTRA, "notification") val startStopPendingIntent = PendingIntent.getBroadcast(context, 0, startStopIntent, PendingIntent.FLAG_UPDATE_CURRENT) if (contractionOngoing) { builder.setContentTitle(context.getString(R.string.notification_timing)) publicBuilder.setContentTitle(context.getString(R.string.notification_timing)) builder.addAction(R.drawable.ic_notif_action_stop, context.getString(R.string.appwidget_contraction_stop), startStopPendingIntent) wearableExtender.addAction(NotificationCompat.Action(R.drawable.ic_wear_action_stop, context.getString(R.string.appwidget_contraction_stop), startStopPendingIntent)) } else { builder.setContentTitle(context.getString(R.string.app_name)) publicBuilder.setContentTitle(context.getString(R.string.app_name)) builder.addAction(R.drawable.ic_notif_action_start, context.getString(R.string.appwidget_contraction_start), startStopPendingIntent) wearableExtender.addAction(NotificationCompat.Action(R.drawable.ic_wear_action_start, context.getString(R.string.appwidget_contraction_start), startStopPendingIntent)) } // See if there is a note and build a page if it exists val noteColumnIndex = data.getColumnIndex(ContractionContract.Contractions.COLUMN_NAME_NOTE) val note = data.getString(noteColumnIndex) val hasNote = note?.isNotBlank() == true // Fill in the 'when', which will be used to show live progress via the chronometer feature val time = if (contractionOngoing) data.getLong(startTimeColumnIndex) else data.getLong(endTimeColumnIndex) builder.setWhen(time) publicBuilder.setWhen(time) builder.setUsesChronometer(true) publicBuilder.setUsesChronometer(true) // Get the average duration and frequency var averageDuration = 0.0 var averageFrequency = 0.0 var numDurations = 0 var numFrequencies = 0 while (!data.isAfterLast) { val startTime = data.getLong(startTimeColumnIndex) if (!data.isNull(endTimeColumnIndex)) { val endTime = data.getLong(endTimeColumnIndex) val curDuration = endTime - startTime averageDuration = (curDuration + numDurations * averageDuration) / (numDurations + 1) numDurations++ } if (data.moveToNext()) { val prevContractionStartTime = data.getLong(startTimeColumnIndex) val curFrequency = startTime - prevContractionStartTime averageFrequency = (curFrequency + numFrequencies * averageFrequency) / (numFrequencies + 1) numFrequencies++ } } val averageDurationInSeconds = (averageDuration / 1000).toLong() val formattedAverageDuration = DateUtils.formatElapsedTime(averageDurationInSeconds) val averageFrequencyInSeconds = (averageFrequency / 1000).toLong() val formattedAverageFrequency = DateUtils.formatElapsedTime(averageFrequencyInSeconds) val contentText = context.getString(R.string.notification_content_text, formattedAverageDuration, formattedAverageFrequency) val bigTextWithoutNote = context.getString(R.string.notification_big_text, formattedAverageDuration, formattedAverageFrequency) val bigText = if (hasNote) { context.getString(R.string.notification_big_text_with_note, formattedAverageDuration, formattedAverageFrequency, note) } else { bigTextWithoutNote } builder.setContentText(contentText) .setStyle(NotificationCompat.BigTextStyle().bigText(bigText)) publicBuilder.setContentText(contentText) .setStyle(NotificationCompat.BigTextStyle().bigText(bigTextWithoutNote)) // Close the cursor data.close() // Create a separate page for the averages as the big text is not shown on Android Wear in chronometer mode val averagePage = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setContentTitle(context.getString(R.string.notification_second_page_title)) .setStyle( NotificationCompat.InboxStyle() .setBigContentTitle(context.getString(R.string.notification_second_page_title)) .addLine( context.getString( R.string.notification_second_page_duration, formattedAverageDuration ) ) .addLine( context.getString( R.string.notification_second_page_frequency, formattedAverageFrequency ) ) ) .build() wearableExtender.addPage(averagePage) if (hasNote) { val notePage = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setContentTitle(context.getString(R.string.detail_note_label)) .setContentText(note) .setStyle( NotificationCompat.BigTextStyle() .setBigContentTitle(context.getString(R.string.detail_note_label)) .bigText(note) ) .build() wearableExtender.addPage(notePage) } // Add 'Add Note'/'Edit Note' action val noteIconResId = if (hasNote) R.drawable.ic_notif_action_edit else R.drawable.ic_notif_action_add val wearIconResId = if (hasNote) R.drawable.ic_wear_action_edit else R.drawable.ic_wear_action_add val noteTitle = if (hasNote) context.getString(R.string.note_dialog_title_edit) else context.getString(R.string.note_dialog_title_add) val noteIntent = Intent(context, NoteTranslucentActivity::class.java) val notePendingIntent = PendingIntent.getActivity(context, 0, noteIntent, 0) val remoteInput = RemoteInput.Builder(Intent.EXTRA_TEXT).setLabel(noteTitle).build() builder.addAction(noteIconResId, noteTitle, notePendingIntent) wearableExtender.addAction(NotificationCompat.Action.Builder(wearIconResId, noteTitle, notePendingIntent).addRemoteInput(remoteInput).build()) val publicNotification = publicBuilder.build() builder.setPublicVersion(publicNotification) val notification = builder.extend(wearableExtender).build() notificationManager.notify(NOTIFICATION_ID, notification) } @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(context: Context) { val notificationManager = context.getSystemService( NotificationManager::class.java) val channel = NotificationChannel(NOTIFICATION_CHANNEL, context.getString(R.string.notification_timing), NotificationManager.IMPORTANCE_LOW) channel.setShowBadge(false) notificationManager.createNotificationChannel(channel) } } override fun onReceive(context: Context, intent: Intent?) = goAsync { update(context) } }
bsd-3-clause
700ebdfe06d0fae0b73de4b0a1b38afa
54.083942
122
0.635063
5.536684
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/gridLayout/impl/GridImpl.kt
2
22250
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.gridLayout.impl import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.checkTrue import com.intellij.ui.dsl.gridLayout.* import org.jetbrains.annotations.ApiStatus import java.awt.Dimension import java.awt.Insets import java.awt.Rectangle import java.util.* import javax.swing.JComponent import kotlin.math.max import kotlin.math.min @ApiStatus.Internal internal class GridImpl : Grid { override val resizableColumns = mutableSetOf<Int>() override val resizableRows = mutableSetOf<Int>() override val columnsGaps = mutableListOf<HorizontalGaps>() override val rowsGaps = mutableListOf<VerticalGaps>() val visible: Boolean get() = cells.any { it.visible } private val layoutData = LayoutData() private val cells = mutableListOf<Cell>() fun register(component: JComponent, constraints: Constraints) { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } cells.add(ComponentCell(constraints, component)) } fun registerSubGrid(constraints: Constraints): Grid { if (!isEmpty(constraints)) { throw UiDslException("Some cells are occupied already: $constraints") } val result = GridImpl() cells.add(GridCell(constraints, result)) return result } fun unregister(component: JComponent): Boolean { val iterator = cells.iterator() for (cell in iterator) { when (cell) { is ComponentCell -> { if (cell.component == component) { iterator.remove() return true } } is GridCell -> { if (cell.content.unregister(component)) { return true } } } } return false } fun getPreferredSizeData(parentInsets: Insets): PreferredSizeData { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) return PreferredSizeData(Dimension(layoutData.preferredWidth + outsideGaps.width, layoutData.preferredHeight + outsideGaps.height), outsideGaps ) } /** * Calculates [layoutData] and layouts all components */ fun layout(width: Int, height: Int, parentInsets: Insets) { calculatePreferredLayoutData() val outsideGaps = layoutData.getOutsideGaps(parentInsets) // Recalculate LayoutData for requested size with corrected insets calculateLayoutDataStep2(width - outsideGaps.width) calculateLayoutDataStep3() calculateLayoutDataStep4(height - outsideGaps.height) layout(outsideGaps.left, outsideGaps.top) } /** * Layouts components */ fun layout(x: Int, y: Int) { for (layoutCellData in layoutData.visibleCellsData) { val bounds = calculateBounds(layoutCellData, x, y) when (val cell = layoutCellData.cell) { is ComponentCell -> { cell.component.bounds = bounds } is GridCell -> { cell.content.layout(bounds.x, bounds.y) } } } } /** * Collects PreCalculationData for all components (including sub-grids) and applies size groups */ private fun collectPreCalculationData(): Map<JComponent, PreCalculationData> { val result = mutableMapOf<JComponent, PreCalculationData>() collectPreCalculationData(result) val widthGroups = result.values.groupBy { it.constraints.widthGroup } for ((widthGroup, preCalculationDataList) in widthGroups) { if (widthGroup == null) { continue } val maxWidth = preCalculationDataList.maxOf { it.calculatedPreferredSize.width } for (preCalculationData in preCalculationDataList) { preCalculationData.calculatedPreferredSize.width = maxWidth } } return result } private fun collectPreCalculationData(preCalculationDataMap: MutableMap<JComponent, PreCalculationData>) { for (cell in cells) { when (cell) { is ComponentCell -> { val component = cell.component if (!component.isVisible) { continue } val componentMinimumSize = component.minimumSize val componentPreferredSize = component.preferredSize preCalculationDataMap[component] = PreCalculationData(componentMinimumSize, componentPreferredSize, cell.constraints) } is GridCell -> { cell.content.collectPreCalculationData(preCalculationDataMap) } } } } /** * Calculates [layoutData] for preferred size */ private fun calculatePreferredLayoutData() { val preCalculationDataMap = collectPreCalculationData() calculateLayoutDataStep1(preCalculationDataMap) calculateLayoutDataStep2(layoutData.preferredWidth) calculateLayoutDataStep3() calculateLayoutDataStep4(layoutData.preferredHeight) calculateOutsideGaps(layoutData.preferredWidth, layoutData.preferredHeight) } /** * Step 1 of [layoutData] calculations */ private fun calculateLayoutDataStep1(preCalculationDataMap: Map<JComponent, PreCalculationData>) { layoutData.columnsSizeCalculator.reset() val visibleCellsData = mutableListOf<LayoutCellData>() var columnsCount = 0 var rowsCount = 0 for (cell in cells) { val preferredSize: Dimension when (cell) { is ComponentCell -> { val component = cell.component if (!component.isVisible) { continue } val preCalculationData = preCalculationDataMap[component] preferredSize = preCalculationData!!.calculatedPreferredSize } is GridCell -> { val grid = cell.content if (!grid.visible) { continue } grid.calculateLayoutDataStep1(preCalculationDataMap) preferredSize = Dimension(grid.layoutData.preferredWidth, 0) } } val layoutCellData: LayoutCellData with(cell.constraints) { layoutCellData = LayoutCellData(cell = cell, preferredSize = preferredSize, columnGaps = HorizontalGaps( left = columnsGaps.getOrNull(x)?.left ?: 0, right = columnsGaps.getOrNull(x + width - 1)?.right ?: 0), rowGaps = VerticalGaps( top = rowsGaps.getOrNull(y)?.top ?: 0, bottom = rowsGaps.getOrNull(y + height - 1)?.bottom ?: 0) ) columnsCount = max(columnsCount, x + width) rowsCount = max(rowsCount, y + height) } visibleCellsData.add(layoutCellData) layoutData.columnsSizeCalculator.addConstraint(cell.constraints.x, cell.constraints.width, layoutCellData.cellPaddedWidth) } layoutData.visibleCellsData = visibleCellsData layoutData.preferredWidth = layoutData.columnsSizeCalculator.calculatePreferredSize() layoutData.dimension.setSize(columnsCount, rowsCount) } /** * Step 2 of [layoutData] calculations */ private fun calculateLayoutDataStep2(width: Int) { layoutData.columnsCoord = layoutData.columnsSizeCalculator.calculateCoords(width, resizableColumns) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { cell.content.calculateLayoutDataStep2(layoutData.getFullPaddedWidth(layoutCellData)) } } } /** * Step 3 of [layoutData] calculations */ private fun calculateLayoutDataStep3() { layoutData.rowsSizeCalculator.reset() layoutData.baselineData.reset() for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints layoutCellData.baseline = null when (val cell = layoutCellData.cell) { is ComponentCell -> { if (!isSupportedBaseline(constraints)) { continue } val componentWidth = layoutData.getPaddedWidth(layoutCellData) + constraints.visualPaddings.width val baseline: Int if (componentWidth >= 0) { baseline = cell.constraints.componentHelper?.getBaseline(componentWidth, layoutCellData.preferredSize.height) ?: cell.component.getBaseline(componentWidth, layoutCellData.preferredSize.height) // getBaseline changes preferredSize, at least for JLabel layoutCellData.preferredSize.height = cell.component.preferredSize.height } else { baseline = -1 } if (baseline >= 0) { layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } is GridCell -> { val grid = cell.content grid.calculateLayoutDataStep3() layoutCellData.preferredSize.height = grid.layoutData.preferredHeight if (grid.layoutData.dimension.height == 1 && isSupportedBaseline(constraints)) { // Calculate baseline for grid val gridBaselines = VerticalAlign.values() .mapNotNull { var result: Pair<VerticalAlign, RowBaselineData>? = null if (it != VerticalAlign.FILL) { val baselineData = grid.layoutData.baselineData.get(it) if (baselineData != null) { result = Pair(it, baselineData) } } result } if (gridBaselines.size == 1) { val (verticalAlign, gridBaselineData) = gridBaselines[0] val baseline = calculateBaseline(layoutCellData.preferredSize.height, verticalAlign, gridBaselineData) layoutCellData.baseline = baseline layoutData.baselineData.registerBaseline(layoutCellData, baseline) } } } } } for (layoutCellData in layoutData.visibleCellsData) { val constraints = layoutCellData.cell.constraints val height = if (layoutCellData.baseline == null) layoutCellData.gapHeight - layoutCellData.cell.constraints.visualPaddings.height + layoutCellData.preferredSize.height else { val rowBaselineData = layoutData.baselineData.get(layoutCellData) rowBaselineData!!.height } // Cell height including gaps and excluding visualPaddings layoutData.rowsSizeCalculator.addConstraint(constraints.y, constraints.height, height) } layoutData.preferredHeight = layoutData.rowsSizeCalculator.calculatePreferredSize() } /** * Step 4 of [layoutData] calculations */ private fun calculateLayoutDataStep4(height: Int) { layoutData.rowsCoord = layoutData.rowsSizeCalculator.calculateCoords(height, resizableRows) for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell if (cell is GridCell) { val subGridHeight = if (cell.constraints.verticalAlign == VerticalAlign.FILL) layoutData.getFullPaddedHeight(layoutCellData) else cell.content.layoutData.preferredHeight cell.content.calculateLayoutDataStep4(subGridHeight) } } } private fun calculateOutsideGaps(width: Int, height: Int) { var left = 0 var right = 0 var top = 0 var bottom = 0 for (layoutCellData in layoutData.visibleCellsData) { val cell = layoutCellData.cell // Update visualPaddings val component = (cell as? ComponentCell)?.component val layout = component?.layout as? GridLayout if (layout != null && component.getClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS) != false) { val preferredSizeData = layout.getPreferredSizeData(component) cell.constraints.visualPaddings = preferredSizeData.outsideGaps } val bounds = calculateBounds(layoutCellData, 0, 0) when (cell) { is ComponentCell -> { left = min(left, bounds.x) top = min(top, bounds.y) right = max(right, bounds.x + bounds.width - width) bottom = max(bottom, bounds.y + bounds.height - height) } is GridCell -> { cell.content.calculateOutsideGaps(bounds.width, bounds.height) val outsideGaps = cell.content.layoutData.outsideGaps left = min(left, bounds.x - outsideGaps.left) top = min(top, bounds.y - outsideGaps.top) right = max(right, bounds.x + bounds.width + outsideGaps.right - width) bottom = max(bottom, bounds.y + bounds.height + outsideGaps.bottom - height) } } } layoutData.outsideGaps = Gaps(top = -top, left = -left, bottom = bottom, right = right) } fun getConstraints(component: JComponent): Constraints? { for (cell in cells) { when(cell) { is ComponentCell -> { if (cell.component == component) { return cell.constraints } } is GridCell -> { val constraints = cell.content.getConstraints(component) if (constraints != null) { return constraints } } } } return null } /** * Calculate bounds for [layoutCellData] */ private fun calculateBounds(layoutCellData: LayoutCellData, offsetX: Int, offsetY: Int): Rectangle { val cell = layoutCellData.cell val constraints = cell.constraints val visualPaddings = constraints.visualPaddings val paddedWidth = layoutData.getPaddedWidth(layoutCellData) val fullPaddedWidth = layoutData.getFullPaddedWidth(layoutCellData) val x = layoutData.columnsCoord[constraints.x] + constraints.gaps.left + layoutCellData.columnGaps.left - visualPaddings.left + when (constraints.horizontalAlign) { HorizontalAlign.LEFT -> 0 HorizontalAlign.CENTER -> (fullPaddedWidth - paddedWidth) / 2 HorizontalAlign.RIGHT -> fullPaddedWidth - paddedWidth HorizontalAlign.FILL -> 0 } val fullPaddedHeight = layoutData.getFullPaddedHeight(layoutCellData) val paddedHeight = if (constraints.verticalAlign == VerticalAlign.FILL) fullPaddedHeight else min(fullPaddedHeight, layoutCellData.preferredSize.height - visualPaddings.height) val y: Int val baseline = layoutCellData.baseline if (baseline == null) { y = layoutData.rowsCoord[constraints.y] + layoutCellData.rowGaps.top + constraints.gaps.top - visualPaddings.top + when (constraints.verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (fullPaddedHeight - paddedHeight) / 2 VerticalAlign.BOTTOM -> fullPaddedHeight - paddedHeight VerticalAlign.FILL -> 0 } } else { val rowBaselineData = layoutData.baselineData.get(layoutCellData)!! val rowHeight = layoutData.getHeight(layoutCellData) y = layoutData.rowsCoord[constraints.y] + calculateBaseline(rowHeight, constraints.verticalAlign, rowBaselineData) - baseline } return Rectangle(offsetX + x, offsetY + y, paddedWidth + visualPaddings.width, paddedHeight + visualPaddings.height) } /** * Calculates baseline for specified [height] */ private fun calculateBaseline(height: Int, verticalAlign: VerticalAlign, rowBaselineData: RowBaselineData): Int { return rowBaselineData.maxAboveBaseline + when (verticalAlign) { VerticalAlign.TOP -> 0 VerticalAlign.CENTER -> (height - rowBaselineData.height) / 2 VerticalAlign.BOTTOM -> height - rowBaselineData.height VerticalAlign.FILL -> 0 } } private fun isEmpty(constraints: Constraints): Boolean { for (cell in cells) { with(cell.constraints) { if (constraints.x + constraints.width > x && x + width > constraints.x && constraints.y + constraints.height > y && y + height > constraints.y ) { return false } } } return true } } /** * Data that collected before layout/preferred size calculations */ private class LayoutData { // // Step 1 // var visibleCellsData = emptyList<LayoutCellData>() val columnsSizeCalculator = ColumnsSizeCalculator() var preferredWidth = 0 /** * Maximum indexes of occupied cells excluding hidden components */ val dimension = Dimension() // // Step 2 // var columnsCoord = emptyArray<Int>() // // Step 3 // val rowsSizeCalculator = ColumnsSizeCalculator() var preferredHeight = 0 val baselineData = BaselineData() // // Step 4 // var rowsCoord = emptyArray<Int>() // // After Step 4 (for preferred size only) // /** * Extra gaps that guarantee no visual clippings (like focus rings). * Calculated for preferred size and this value is used for enlarged container as well. * [GridLayout] takes into account [outsideGaps] for in following cases: * 1. Preferred size is increased when needed to avoid clipping * 2. Layout content can be moved a little from left/top corner to avoid clipping * 3. In parents that also use [GridLayout]: aligning by visual padding is corrected according [outsideGaps] together with insets, * so components in parent and this container are aligned together */ var outsideGaps = Gaps.EMPTY fun getPaddedWidth(layoutCellData: LayoutCellData): Int { val fullPaddedWidth = getFullPaddedWidth(layoutCellData) return if (layoutCellData.cell.constraints.horizontalAlign == HorizontalAlign.FILL) fullPaddedWidth else min(fullPaddedWidth, layoutCellData.preferredSize.width - layoutCellData.cell.constraints.visualPaddings.width) } fun getFullPaddedWidth(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return columnsCoord[constraints.x + constraints.width] - columnsCoord[constraints.x] - layoutCellData.gapWidth } fun getHeight(layoutCellData: LayoutCellData): Int { val constraints = layoutCellData.cell.constraints return rowsCoord[constraints.y + constraints.height] - rowsCoord[constraints.y] } fun getFullPaddedHeight(layoutCellData: LayoutCellData): Int { return getHeight(layoutCellData) - layoutCellData.gapHeight } fun getOutsideGaps(parentInsets: Insets): Gaps { return Gaps( top = max(outsideGaps.top, parentInsets.top), left = max(outsideGaps.left, parentInsets.left), bottom = max(outsideGaps.bottom, parentInsets.bottom), right = max(outsideGaps.right, parentInsets.right), ) } } /** * For sub-grids height of [preferredSize] calculated on late steps of [LayoutData] calculations */ private data class LayoutCellData(val cell: Cell, val preferredSize: Dimension, val columnGaps: HorizontalGaps, val rowGaps: VerticalGaps) { /** * Calculated on step 3 */ var baseline: Int? = null val gapWidth: Int get() = cell.constraints.gaps.width + columnGaps.width val gapHeight: Int get() = cell.constraints.gaps.height + rowGaps.height /** * Cell width including gaps and excluding visualPaddings */ val cellPaddedWidth: Int get() = preferredSize.width + gapWidth - cell.constraints.visualPaddings.width } private sealed class Cell(val constraints: Constraints) { abstract val visible: Boolean } private class ComponentCell(constraints: Constraints, val component: JComponent) : Cell(constraints) { override val visible: Boolean get() = component.isVisible } private class GridCell(constraints: Constraints, val content: GridImpl) : Cell(constraints) { override val visible: Boolean get() = content.visible } /** * Contains baseline data for rows, see [Constraints.baselineAlign] */ private class BaselineData { private val rowBaselineData = mutableMapOf<Int, MutableMap<VerticalAlign, RowBaselineData>>() fun reset() { rowBaselineData.clear() } fun registerBaseline(layoutCellData: LayoutCellData, baseline: Int) { val constraints = layoutCellData.cell.constraints checkTrue(isSupportedBaseline(constraints)) val rowBaselineData = getOrCreate(layoutCellData) rowBaselineData.maxAboveBaseline = max(rowBaselineData.maxAboveBaseline, baseline + layoutCellData.rowGaps.top + constraints.gaps.top - constraints.visualPaddings.top) rowBaselineData.maxBelowBaseline = max(rowBaselineData.maxBelowBaseline, layoutCellData.preferredSize.height - baseline + layoutCellData.rowGaps.bottom + constraints.gaps.bottom - constraints.visualPaddings.bottom) } /** * Returns data for single available row */ fun get(verticalAlign: VerticalAlign): RowBaselineData? { checkTrue(rowBaselineData.size <= 1) return rowBaselineData.firstNotNullOfOrNull { it.value }?.get(verticalAlign) } fun get(layoutCellData: LayoutCellData): RowBaselineData? { val constraints = layoutCellData.cell.constraints return rowBaselineData[constraints.y]?.get(constraints.verticalAlign) } private fun getOrCreate(layoutCellData: LayoutCellData): RowBaselineData { val constraints = layoutCellData.cell.constraints val mapByAlign = rowBaselineData.getOrPut(constraints.y) { EnumMap(VerticalAlign::class.java) } return mapByAlign.getOrPut(constraints.verticalAlign) { RowBaselineData() } } } /** * Max sizes for a row which include all gaps and exclude paddings */ private data class RowBaselineData(var maxAboveBaseline: Int = 0, var maxBelowBaseline: Int = 0) { val height: Int get() = maxAboveBaseline + maxBelowBaseline } private fun isSupportedBaseline(constraints: Constraints): Boolean { return constraints.baselineAlign && constraints.verticalAlign != VerticalAlign.FILL && constraints.height == 1 } @ApiStatus.Internal internal class PreCalculationData(val minimumSize: Dimension, val preferredSize: Dimension, val constraints: Constraints) { /** * Preferred size based on minimum/preferred sizes and size groups */ var calculatedPreferredSize = Dimension(max(minimumSize.width, preferredSize.width), max(minimumSize.height, preferredSize.height)) } @ApiStatus.Internal internal data class PreferredSizeData(val preferredSize: Dimension, val outsideGaps: Gaps)
apache-2.0
59bb4747da12610c528d380c55c26347
33.657321
158
0.685618
4.972067
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MergeElseIfIntention.kt
3
1484
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.psi.* class MergeElseIfIntention : SelfTargetingIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("merge.else.if") ) { override fun isApplicableTo(element: KtIfExpression, caretOffset: Int): Boolean { val elseBody = element.`else` ?: return false val nestedIf = elseBody.nestedIf() ?: return false return nestedIf.`else` == null } override fun applyTo(element: KtIfExpression, editor: Editor?) { val nestedIf = element.`else`?.nestedIf() ?: return val condition = nestedIf.condition ?: return val nestedBody = nestedIf.then ?: return val factory = KtPsiFactory(element) element.`else`?.replace( factory.createExpressionByPattern("if ($0) $1", condition, nestedBody) ) } companion object { private fun KtExpression.nestedIf() = if (this is KtBlockExpression) { this.statements.singleOrNull() as? KtIfExpression } else { null } } }
apache-2.0
9b4e43159c0f5cc20f465894ea9df420
36.125
158
0.681941
4.652038
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/DeleteNamedLayoutActionGroup.kt
2
1086
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAware import com.intellij.toolWindow.ToolWindowDefaultLayoutManager class DeleteNamedLayoutActionGroup : ActionGroup(), DumbAware { private val childrenCache = NamedLayoutListBasedCache<AnAction> { name -> if ( name != ToolWindowDefaultLayoutManager.DEFAULT_LAYOUT_NAME && name != ToolWindowDefaultLayoutManager.getInstance().activeLayoutName ) { DeleteNamedLayoutAction(name) } else { null } }.apply { dependsOnActiveLayout = true } override fun getChildren(e: AnActionEvent?): Array<AnAction> = childrenCache.getCachedOrUpdatedArray(AnAction.EMPTY_ARRAY) override fun getActionUpdateThread() = ActionUpdateThread.BGT }
apache-2.0
ae2b7a2e2b9e4e7ff542a241f0718940
37.821429
124
0.791897
4.681034
false
false
false
false
ledboot/Toffee
app/src/main/java/com/ledboot/toffee/widget/refreshLoadView/BaseViewHolder.kt
1
1547
package com.ledboot.toffee.widget.refreshLoadView import android.util.SparseArray import android.view.View import android.widget.Adapter import android.widget.AdapterView import androidx.annotation.IdRes import androidx.databinding.ViewDataBinding import androidx.databinding.library.baseAdapters.BR import androidx.recyclerview.widget.RecyclerView /** * Created by Gwynn on 17/10/16. */ class BaseViewHolder<T> : RecyclerView.ViewHolder { constructor(binding: ViewDataBinding) : this(binding.root) { this.binding = binding } constructor(itemView: View) : super(itemView) protected var binding: ViewDataBinding? = null private var views: SparseArray<View> = SparseArray() var mAdapter: BaseQuickAdapter<*, *>? = null public fun setVisible(@IdRes viewId: Int, visible: Boolean): BaseViewHolder<T> { var view: View = getView(viewId) view.visibility = if (visible) View.VISIBLE else View.INVISIBLE return this } public fun <T : View> getView(@IdRes viewId: Int): T { var view = views.get(viewId) if (view == null) { view = itemView.findViewById(viewId) views.put(viewId, view) } return view as T } public fun setAdapter(@IdRes viewId: Int, adapter: Adapter): BaseViewHolder<T> { val view = getView<AdapterView<*>>(viewId) view.adapter = adapter return this } fun bind(data: T) { binding!!.setVariable(BR.item, data) binding!!.executePendingBindings() } }
apache-2.0
7bec4b4cef9db005bb364fdaf2fc97d7
28.207547
84
0.678087
4.394886
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/forge/inspections/sideonly/LocalVariableDeclarationSideOnlyInspection.kt
1
4830
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.forge.inspections.sideonly import com.demonwav.mcdev.util.findContainingClass import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiLocalVariable import com.siyeh.ig.BaseInspection import com.siyeh.ig.BaseInspectionVisitor import com.siyeh.ig.InspectionGadgetsFix import org.jetbrains.annotations.Nls class LocalVariableDeclarationSideOnlyInspection : BaseInspection() { @Nls override fun getDisplayName() = "Invalid usage of local variable declaration annotated with @SideOnly" override fun buildErrorString(vararg infos: Any): String { val error = infos[0] as Error return error.getErrorString(*SideOnlyUtil.getSubArray(infos)) } override fun getStaticDescription() = "A variable whose class declaration is annotated with @SideOnly for one side cannot be declared in a class" + " or method that does not match the same side." override fun buildFix(vararg infos: Any): InspectionGadgetsFix? { val variableClass = infos[3] as PsiClass return if (variableClass.isWritable) { RemoveAnnotationInspectionGadgetsFix(variableClass, "Remove @SideOnly annotation from variable class declaration") } else { null } } override fun buildVisitor(): BaseInspectionVisitor { return object : BaseInspectionVisitor() { override fun visitLocalVariable(variable: PsiLocalVariable) { val psiClass = variable.findContainingClass() ?: return if (!SideOnlyUtil.beginningCheck(variable)) { return } val type = variable.type as? PsiClassType ?: return val variableClass = type.resolve() ?: return val variableSide = SideOnlyUtil.getSideForClass(variableClass) if (variableSide === Side.NONE || variableSide === Side.INVALID) { return } val containingClassSide = SideOnlyUtil.getSideForClass(psiClass) val methodSide = SideOnlyUtil.checkElementInMethod(variable) var classAnnotated = false if (containingClassSide !== Side.NONE && containingClassSide !== Side.INVALID) { if (variableSide !== containingClassSide) { registerVariableError( variable, Error.VAR_CROSS_ANNOTATED_CLASS, variableSide.annotation, containingClassSide.annotation, variableClass ) } classAnnotated = true } if (methodSide === Side.INVALID) { return } if (variableSide !== methodSide) { if (methodSide === Side.NONE) { if (!classAnnotated) { registerVariableError( variable, Error.VAR_UNANNOTATED_METHOD, variableSide.annotation, methodSide.annotation, variableClass ) } } else { registerVariableError( variable, Error.VAR_CROSS_ANNOTATED_METHOD, variableSide.annotation, methodSide.annotation, variableClass ) } } } } } enum class Error { VAR_CROSS_ANNOTATED_CLASS { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in a class annotated with ${infos[1]}" } }, VAR_CROSS_ANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in a method annotated with ${infos[1]}" } }, VAR_UNANNOTATED_METHOD { override fun getErrorString(vararg infos: Any): String { return "A local variable whose class is annotated with ${infos[0]} cannot be used in an un-annotated method." } }; abstract fun getErrorString(vararg infos: Any): String } }
mit
1306c439bb8cfc2937e41b98e6b6a3b5
36.153846
137
0.548861
5.883069
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/OutflowSlicer.kt
6
12480
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.slicer import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector.Access import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.util.parentOfType import com.intellij.slicer.SliceUsage import com.intellij.usageView.UsageInfo import com.intellij.util.Processor import org.jetbrains.kotlin.builtins.isExtensionFunctionType import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.cfg.pseudocode.PseudoValue import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction import org.jetbrains.kotlin.cfg.pseudocode.instructions.eval.* import org.jetbrains.kotlin.cfg.pseudocode.instructions.jumps.ReturnValueInstruction import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingElement import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReadWriteAccessDetector import org.jetbrains.kotlin.idea.util.actualsForExpected import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class OutflowSlicer( element: KtElement, processor: Processor<in SliceUsage>, parentUsage: KotlinSliceUsage ) : Slicer(element, processor, parentUsage) { override fun processChildren(forcedExpressionMode: Boolean) { if (forcedExpressionMode) { (element as? KtExpression)?.let { processExpression(it) } return } when (element) { is KtProperty -> processVariable(element) is KtParameter -> processVariable(element) is KtFunction -> processFunction(element) is KtPropertyAccessor -> { if (element.isGetter) { processVariable(element.property) } } is KtTypeReference -> { val declaration = element.parent require(declaration is KtCallableDeclaration) require(element == declaration.receiverTypeReference) if (declaration.isExpectDeclaration()) { declaration.resolveToDescriptorIfAny() ?.actualsForExpected() ?.forEach { val actualDeclaration = (it as? DeclarationDescriptorWithSource)?.toPsi() (actualDeclaration as? KtCallableDeclaration)?.receiverTypeReference?.passToProcessor() } } when (declaration) { is KtFunction -> { processExtensionReceiverUsages(declaration, declaration.bodyExpression, mode) } is KtProperty -> { //TODO: process only one of them or both depending on the usage type processExtensionReceiverUsages(declaration, declaration.getter?.bodyExpression, mode) processExtensionReceiverUsages(declaration, declaration.setter?.bodyExpression, mode) } } } is KtExpression -> processExpression(element) } } private fun processVariable(variable: KtCallableDeclaration) { val withDereferences = parentUsage.params.showInstanceDereferences val accessKind = if (withDereferences) AccessKind.READ_OR_WRITE else AccessKind.READ_ONLY fun processVariableAccess(usageInfo: UsageInfo) { val refElement = usageInfo.element ?: return if (refElement !is KtExpression) { if (refElement.parentOfType<PsiComment>() == null) { refElement.passToProcessor() } return } if (refElement.parent is KtValueArgumentName) return // named argument reference is not a read or write val refExpression = KtPsiUtil.safeDeparenthesize(refElement) if (withDereferences) { refExpression.processDereferences() } if (!withDereferences || KotlinReadWriteAccessDetector.INSTANCE.getExpressionAccess(refExpression) == Access.Read) { refExpression.passToProcessor() } } var searchScope = analysisScope if (variable is KtParameter) { if (!canProcessParameter(variable)) return //TODO val callable = variable.ownerFunction as? KtCallableDeclaration if (callable != null) { if (callable.isExpectDeclaration()) { variable.resolveToDescriptorIfAny() ?.actualsForExpected() ?.forEach { (it as? DeclarationDescriptorWithSource)?.toPsi()?.passToProcessor() } } val parameterIndex = variable.parameterIndex() callable.forEachOverridingElement(scope = analysisScope) { _, overridingMember -> when (overridingMember) { is KtCallableDeclaration -> { val parameters = overridingMember.valueParameters check(parameters.size == callable.valueParameters.size) parameters[parameterIndex].passToProcessor() } is PsiMethod -> { val parameters = overridingMember.parameterList.parameters val shift = if (callable.receiverTypeReference != null) 1 else 0 check(parameters.size == callable.valueParameters.size + shift) parameters[parameterIndex + shift].passToProcessor() } else -> { // not supported } } true } if (callable is KtNamedFunction) { // references to parameters of inline function can be outside analysis scope searchScope = LocalSearchScope(callable) } } } processVariableAccesses(variable, searchScope, accessKind, ::processVariableAccess) } private fun processFunction(function: KtFunction) { processCalls(function, includeOverriders = false, CallSliceProducer) } private fun processExpression(expression: KtExpression) { val expressionWithValue = when (expression) { is KtFunctionLiteral -> expression.parent as KtLambdaExpression else -> expression } expressionWithValue.processPseudocodeUsages { pseudoValue, instruction -> when (instruction) { is WriteValueInstruction -> { if (!pseudoValue.processIfReceiverValue(instruction, mode)) { instruction.target.accessedDescriptor?.toPsi()?.passToProcessor() } } is ReadValueInstruction -> { pseudoValue.processIfReceiverValue(instruction, mode) } is CallInstruction -> { if (!pseudoValue.processIfReceiverValue(instruction, mode)) { val parameterDescriptor = instruction.arguments[pseudoValue] ?: return@processPseudocodeUsages val parameter = parameterDescriptor.toPsi() if (parameter != null) { parameter.passToProcessorInCallMode(instruction.element) } else { val function = parameterDescriptor.containingDeclaration as? FunctionDescriptor ?: return@processPseudocodeUsages if (function.isImplicitInvokeFunction()) { processImplicitInvokeCall(instruction, parameterDescriptor) } } } } is ReturnValueInstruction -> { val subroutine = instruction.subroutine if (subroutine is KtNamedFunction) { val (newMode, callElement) = mode.popInlineFunctionCall(subroutine) if (newMode != null) { callElement?.passToProcessor(newMode) return@processPseudocodeUsages } } subroutine.passToProcessor() } is MagicInstruction -> { when (instruction.kind) { MagicKind.NOT_NULL_ASSERTION, MagicKind.CAST -> instruction.outputValue.element?.passToProcessor() else -> { } } } } } } private fun processImplicitInvokeCall(instruction: CallInstruction, parameterDescriptor: ValueParameterDescriptor) { val receiverPseudoValue = instruction.receiverValues.entries.singleOrNull()?.key ?: return val receiverExpression = receiverPseudoValue.element as? KtExpression ?: return val bindingContext = receiverExpression.analyze(BodyResolveMode.PARTIAL) var receiverType = bindingContext.getType(receiverExpression) var receiver: PsiElement = receiverExpression if (receiverType == null && receiverExpression is KtReferenceExpression) { val targetDescriptor = bindingContext[BindingContext.REFERENCE_TARGET, receiverExpression] if (targetDescriptor is CallableDescriptor) { receiverType = targetDescriptor.returnType receiver = targetDescriptor.toPsi() ?: return } } if (receiverType == null || !receiverType.isFunctionType) return val isExtension = receiverType.isExtensionFunctionType val shift = if (isExtension) 1 else 0 val parameterIndex = parameterDescriptor.index - shift val newMode = if (parameterIndex >= 0) mode.withBehaviour(LambdaParameterInflowBehaviour(parameterIndex)) else mode.withBehaviour(LambdaReceiverInflowBehaviour) receiver.passToProcessor(newMode) } private fun processDereferenceIfNeeded( expression: KtExpression, pseudoValue: PseudoValue, instr: InstructionWithReceivers ) { if (!parentUsage.params.showInstanceDereferences) return val receiver = instr.receiverValues[pseudoValue] val resolvedCall = when (instr) { is CallInstruction -> instr.resolvedCall is ReadValueInstruction -> (instr.target as? AccessTarget.Call)?.resolvedCall else -> null } ?: return if (receiver != null && resolvedCall.dispatchReceiver == receiver) { processor.process(KotlinSliceDereferenceUsage(expression, parentUsage, mode)) } } private fun KtExpression.processPseudocodeUsages(processor: (PseudoValue, Instruction) -> Unit) { val pseudocode = pseudocodeCache[this] ?: return val pseudoValue = pseudocode.getElementValue(this) ?: return pseudocode.getUsages(pseudoValue).forEach { processor(pseudoValue, it) } } private fun KtExpression.processDereferences() { processPseudocodeUsages { pseudoValue, instr -> when (instr) { is ReadValueInstruction -> processDereferenceIfNeeded(this, pseudoValue, instr) is CallInstruction -> processDereferenceIfNeeded(this, pseudoValue, instr) } } } }
apache-2.0
75ac8c74ba3d4c9c28caf12acad476eb
43.412811
158
0.61266
6.190476
false
false
false
false
dahlstrom-g/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedDiffPreview.kt
1
7775
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.actions.diff import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.tools.combined.* import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper import com.intellij.openapi.vcs.changes.DiffPreviewUpdateProcessor import com.intellij.openapi.vcs.changes.DiffRequestProcessorWithProducers import com.intellij.openapi.vcs.changes.EditorTabPreviewBase import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreviewModel.Companion.prepareCombinedDiffModelRequests import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ExpandableItemsHandler import com.intellij.util.containers.isEmpty import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.Delegates import org.jetbrains.annotations.NonNls import java.util.stream.Stream import javax.swing.JComponent import javax.swing.JTree.TREE_MODEL_PROPERTY import kotlin.streams.toList @JvmField internal val COMBINED_DIFF_PREVIEW_TAB_NAME = Key.create<() -> @NlsContexts.TabTitle String>("combined_diff_preview_tab_name") class CombinedDiffPreviewVirtualFile(sourceId: String) : CombinedDiffVirtualFile(sourceId, "") abstract class CombinedDiffPreview(protected val tree: ChangesTree, targetComponent: JComponent, isOpenEditorDiffPreviewWithSingleClick: Boolean, needSetupOpenPreviewListeners: Boolean, parentDisposable: Disposable) : EditorTabPreviewBase(tree.project, parentDisposable) { constructor(tree: ChangesTree, parentDisposable: Disposable) : this(tree, tree, false, false, parentDisposable) override val previewFile: VirtualFile by lazy { CombinedDiffPreviewVirtualFile(tree.id) } override val updatePreviewProcessor get() = model protected val model by lazy { createModel().also { model -> model.context.putUserData(COMBINED_DIFF_PREVIEW_TAB_NAME, ::getCombinedDiffTabTitle) project.service<CombinedDiffModelRepository>().registerModel(tree.id, model) } } override fun updatePreview(fromModelRefresh: Boolean) { super.updatePreview(fromModelRefresh) if (isPreviewOpen()) { FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(previewFile) } } init { escapeHandler = Runnable { closePreview() returnFocusToTree() } if (needSetupOpenPreviewListeners) { installListeners(tree, isOpenEditorDiffPreviewWithSingleClick) installNextDiffActionOn(targetComponent) } UIUtil.putClientProperty(tree, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) installCombinedDiffModelListener() } private fun installCombinedDiffModelListener() { tree.addPropertyChangeListener(TREE_MODEL_PROPERTY) { if (model.ourDisposable.isDisposed) return@addPropertyChangeListener val changes = model.getSelectedOrAllChangesStream().toList() if (changes.isNotEmpty()) { model.refresh(true) model.reset(prepareCombinedDiffModelRequests(project, changes)) } } } open fun returnFocusToTree() = Unit override fun isPreviewOnDoubleClickAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnDoubleClickAllowed() override fun isPreviewOnEnterAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnEnterAllowed() protected abstract fun createModel(): CombinedDiffPreviewModel protected abstract fun getCombinedDiffTabTitle(): String override fun updateDiffAction(event: AnActionEvent) { event.presentation.isVisible = event.isFromActionToolbar || event.presentation.isEnabled } override fun getCurrentName(): String? = model.selected?.presentableName override fun hasContent(): Boolean = model.requests.isNotEmpty() internal fun getFileSize(): Int = model.requests.size protected val ChangesTree.id: @NonNls String get() = javaClass.name + "@" + Integer.toHexString(hashCode()) private fun isCombinedPreviewAllowed() = Registry.`is`("enable.combined.diff") } abstract class CombinedDiffPreviewModel(protected val tree: ChangesTree, requests: Map<CombinedBlockId, DiffRequestProducer>, parentDisposable: Disposable) : CombinedDiffModelImpl(tree.project, requests, parentDisposable), DiffPreviewUpdateProcessor, DiffRequestProcessorWithProducers { var selected by Delegates.equalVetoingObservable<Wrapper?>(null) { change -> if (change != null) { selectChangeInTree(change) scrollToChange(change) } } companion object { @JvmStatic fun prepareCombinedDiffModelRequests(project: Project, changes: List<Wrapper>): Map<CombinedBlockId, DiffRequestProducer> { return changes .asSequence() .mapNotNull { wrapper -> wrapper.createProducer(project) ?.let { CombinedPathBlockId(wrapper.filePath, wrapper.fileStatus, wrapper.tag) to it } }.toMap() } } override fun collectDiffProducers(selectedOnly: Boolean): ListSelection<DiffRequestProducer> { return ListSelection.create(requests.values.toList(), selected?.createProducer(project)) } abstract fun getAllChanges(): Stream<out Wrapper> protected abstract fun getSelectedChanges(): Stream<out Wrapper> protected open fun showAllChangesForEmptySelection(): Boolean { return true } override fun clear() { init() } override fun refresh(fromModelRefresh: Boolean) { if (ourDisposable.isDisposed) return val selectedChanges = getSelectedOrAllChangesStream().toList() val selectedChange = selected?.let { prevSelected -> selectedChanges.find { it == prevSelected } } if (fromModelRefresh && selectedChange == null && selected != null && context.isWindowFocused && context.isFocusedInWindow) { // Do not automatically switch focused viewer if (selectedChanges.size == 1 && getAllChanges().anyMatch { it: Wrapper -> selected == it }) { selected?.run(::selectChangeInTree) // Restore selection if necessary } return } val newSelected = when { selectedChanges.isEmpty() -> null selectedChange == null -> selectedChanges[0] else -> selectedChange } newSelected?.let { context.putUserData(COMBINED_DIFF_SCROLL_TO_BLOCK, CombinedPathBlockId(it.filePath, it.fileStatus, it.tag)) } selected = newSelected } internal fun getSelectedOrAllChangesStream(): Stream<out Wrapper> { return if (getSelectedChanges().isEmpty() && showAllChangesForEmptySelection()) getAllChanges() else getSelectedChanges() } private fun scrollToChange(change: Wrapper) { context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, false) } open fun selectChangeInTree(change: Wrapper) { ChangesBrowserBase.selectObjectWithTag(tree, change.userObject, change.tag) } override fun getComponent(): JComponent = throw UnsupportedOperationException() //only for splitter preview }
apache-2.0
938a72393ef21e91a321c79ed83e0f80
38.668367
132
0.750997
4.767014
false
false
false
false
sanjoydesk/FrameworkBenchmarks
frameworks/Kotlin/hexagon/src/main/kotlin/co/there4/hexagon/Benchmark.kt
1
2812
package co.there4.hexagon import co.there4.hexagon.rest.crud import co.there4.hexagon.serialization.convertToMap import co.there4.hexagon.serialization.serialize import co.there4.hexagon.web.* import co.there4.hexagon.web.servlet.ServletServer import kotlinx.html.* import java.net.InetAddress.getByName as address import java.time.LocalDateTime.now import java.util.concurrent.ThreadLocalRandom import javax.servlet.annotation.WebListener // DATA CLASSES internal data class Message(val message: String = "Hello, World!") internal data class Fortune(val _id: Int, val message: String) internal data class World(val _id: Int, val id: Int = _id, val randomNumber: Int = rnd()) // CONSTANTS private val CONTENT_TYPE_JSON = "application/json" private val QUERIES_PARAM = "queries" // UTILITIES internal fun rnd() = ThreadLocalRandom.current().nextInt(DB_ROWS) + 1 private fun World.strip(): Map<*, *> = this.convertToMap().filterKeys { it != "_id" } private fun World.toJson(): String = this.strip().serialize() private fun List<World>.toJson(): String = this.map(World::strip).serialize() private fun Exchange.hasQueryCount() = request[QUERIES_PARAM] == null private fun Exchange.getDb() { val worlds = (1..getQueries()).map { findWorld() }.filterNotNull() ok(if (hasQueryCount()) worlds[0].toJson() else worlds.toJson(), CONTENT_TYPE_JSON) } private fun listFortunes() = (findFortunes() + Fortune(0, "Additional fortune added at request time.")) .sortedBy { it.message } // HANDLERS private fun Exchange.getUpdates() { val worlds = (1..getQueries()).map { val id = rnd() val newWorld = World(id, id) replaceWorld(newWorld) newWorld } ok(if (hasQueryCount()) worlds[0].toJson() else worlds.toJson(), CONTENT_TYPE_JSON) } private fun Exchange.getQueries() = try { val queries = request[QUERIES_PARAM]?.toInt() ?: 1 when { queries < 1 -> 1 queries > 500 -> 500 else -> queries } } catch (ex: NumberFormatException) { 1 } fun benchmarkRoutes(srv: Router = server) { srv.before { response.addHeader("Server", "Servlet/3.1") response.addHeader("Transfer-Encoding", "chunked") response.addHeader("Date", httpDate(now())) } srv.get("/plaintext") { ok("Hello, World!", "text/plain") } srv.get("/json") { ok(Message().serialize(), CONTENT_TYPE_JSON) } srv.get("/fortunes") { template("fortunes.html", "fortunes" to listFortunes()) } srv.get("/db") { getDb() } srv.get("/query") { getDb() } srv.get("/update") { getUpdates() } } @WebListener class Web : ServletServer () { override fun init() { benchmarkRoutes(this) } } fun main(args: Array<String>) { benchmarkRoutes() run() }
bsd-3-clause
f5694706c128c2d14535e1cc4b85ab65
29.565217
89
0.662873
3.724503
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter7/7.9.KClass.kt
1
421
package com.packt.chapter7 import kotlin.reflect.KClass fun gettingAKClass() { val name = "George" val kclass: KClass<String> = name::class val kclass2: KClass<String> = String::class val kclass3 = Class.forName("com.packt.MyType").kotlin } fun oneKClassPerType() { val kclass1: KClass<String> = "harry"::class val kclass2: KClass<String> = "victoria"::class val kclass3: KClass<String> = String::class }
mit
66dde8e37628ef8aeb373f1670d92046
25.375
56
0.71734
3.289063
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/models/Thumbnail.kt
1
2851
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.shared.models import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.drawable.Drawable import android.media.ThumbnailUtils import android.os.Parcelable import androidx.annotation.DrawableRes import de.dreier.mytargets.shared.utils.RoundedAvatarDrawable import de.dreier.mytargets.shared.utils.toByteArray import kotlinx.android.parcel.IgnoredOnParcel import kotlinx.android.parcel.Parcelize import timber.log.Timber import java.io.File import java.util.* @Parcelize class Thumbnail(val data: ByteArray) : Parcelable { @IgnoredOnParcel val roundDrawable: Drawable by lazy { val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size) if (bitmap == null) { Timber.w("Invalid bitmap data provided: %s", Arrays.asList(data).toString()) val dummyBitmap = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888) return@lazy RoundedAvatarDrawable(dummyBitmap) } RoundedAvatarDrawable(bitmap) } companion object { /** * Constant used to indicate the dimension of micro thumbnail. */ private const val TARGET_SIZE_MICRO_THUMBNAIL = 96 fun from(bitmap: Bitmap): Thumbnail { val thumbnail = ThumbnailUtils.extractThumbnail( bitmap, TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL, ThumbnailUtils.OPTIONS_RECYCLE_INPUT ) return Thumbnail(thumbnail.toByteArray()) } fun from(imageFile: File): Thumbnail { val thumbnail = ThumbnailUtils .extractThumbnail( BitmapFactory.decodeFile(imageFile.path), TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL ) ?: Bitmap.createBitmap( TARGET_SIZE_MICRO_THUMBNAIL, TARGET_SIZE_MICRO_THUMBNAIL, Bitmap.Config.RGB_565 ) return Thumbnail(thumbnail.toByteArray()) } fun from(context: Context, @DrawableRes resId: Int): Thumbnail { return from(BitmapFactory.decodeResource(context.resources, resId)) } } }
gpl-2.0
c2590a8f50d71498945378a7d243b24f
34.197531
88
0.659769
4.848639
false
false
false
false
DroidsOnRoids/DroidsMap
app/src/main/java/pl/droidsonroids/droidsmap/feature/office/business_logic/OfficeEntity.kt
1
485
package pl.droidsonroids.droidsmap.feature.office.business_logic import pl.droidsonroids.droidsmap.model.Entity data class OfficeEntity( val centerLatitude: Double = 0.0, val centerLongitude: Double = 0.0, val topLeftCornerLatitude: Double = 0.0, val topLeftCornerLongitude: Double = 0.0, val mapViewportBearing: Double = 0.0, val translatedMapViewportBearing: Double = 0.0, val mapViewportConstraint: Double = 0.0 ) : Entity()
mit
1f140733e1028585d6e7d9b273fbeff9
36.384615
64
0.703093
4.041667
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/textField.kt
1
4412
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder import com.intellij.openapi.Disposable import com.intellij.openapi.observable.properties.ObservableMutableProperty import com.intellij.openapi.observable.util.* import com.intellij.openapi.ui.validation.DialogValidation import com.intellij.openapi.ui.validation.forTextComponent import com.intellij.openapi.ui.validation.trimParameter import com.intellij.ui.dsl.ValidationException import com.intellij.ui.dsl.builder.impl.CellImpl.Companion.installValidationRequestor import com.intellij.ui.dsl.catchValidationException import com.intellij.ui.dsl.stringToInt import com.intellij.ui.dsl.validateIntInRange import com.intellij.ui.layout.* import com.intellij.util.containers.map2Array import org.jetbrains.annotations.ApiStatus import javax.swing.JTextField import javax.swing.text.JTextComponent import kotlin.reflect.KMutableProperty0 import com.intellij.openapi.observable.util.whenTextChangedFromUi as whenTextChangedFromUiImpl /** * Columns for text components with tiny width. Used for [Row.intTextField] by default */ const val COLUMNS_TINY = 6 /** * Columns for text components with short width */ const val COLUMNS_SHORT = 18 /** * Columns for text components with medium width */ const val COLUMNS_MEDIUM = 25 const val COLUMNS_LARGE = 36 fun <T : JTextComponent> Cell<T>.bindText(property: ObservableMutableProperty<String>): Cell<T> { installValidationRequestor(property) return applyToComponent { bind(property) } } fun <T : JTextComponent> Cell<T>.bindText(prop: KMutableProperty0<String>): Cell<T> { return bindText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindText(getter: () -> String, setter: (String) -> Unit): Cell<T> { return bindText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.bindText(prop: MutableProperty<String>): Cell<T> { return bind(JTextComponent::getText, JTextComponent::setText, prop) } fun <T : JTextComponent> Cell<T>.bindIntText(property: ObservableMutableProperty<Int>): Cell<T> { installValidationRequestor(property) val stringProperty = property .backwardFilter { component.isIntInRange(it) } .toStringIntProperty() return applyToComponent { bind(stringProperty) } } fun <T : JTextComponent> Cell<T>.bindIntText(prop: MutableProperty<Int>): Cell<T> { return bindText({ prop.get().toString() }, { value -> catchValidationException { prop.set(component.getValidatedIntValue(value)) } }) } fun <T : JTextComponent> Cell<T>.bindIntText(prop: KMutableProperty0<Int>): Cell<T> { return bindIntText(prop.toMutableProperty()) } fun <T : JTextComponent> Cell<T>.bindIntText(getter: () -> Int, setter: (Int) -> Unit): Cell<T> { return bindIntText(MutableProperty(getter, setter)) } fun <T : JTextComponent> Cell<T>.text(text: String): Cell<T> { component.text = text return this } /** * Minimal width of text field in chars * * @see COLUMNS_TINY * @see COLUMNS_SHORT * @see COLUMNS_MEDIUM * @see COLUMNS_LARGE */ fun <T : JTextField> Cell<T>.columns(columns: Int) = apply { component.columns(columns) } fun <T : JTextField> T.columns(columns: Int) = apply { this.columns = columns } @Throws(ValidationException::class) private fun JTextComponent.getValidatedIntValue(value: String): Int { val result = stringToInt(value) val range = getClientProperty(DSL_INT_TEXT_RANGE_PROPERTY) as? IntRange range?.let { validateIntInRange(result, it) } return result } private fun JTextComponent.isIntInRange(value: Int): Boolean { val range = getClientProperty(DSL_INT_TEXT_RANGE_PROPERTY) as? IntRange return range == null || value in range } fun <T : JTextComponent> Cell<T>.trimmedTextValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = textValidation(*validations.map2Array { it.trimParameter() }) fun <T : JTextComponent> Cell<T>.textValidation(vararg validations: DialogValidation.WithParameter<() -> String>) = validation(*validations.map2Array { it.forTextComponent() }) @ApiStatus.Experimental fun <T: JTextComponent> Cell<T>.whenTextChangedFromUi(parentDisposable: Disposable? = null, listener: (String) -> Unit): Cell<T> { return applyToComponent { whenTextChangedFromUiImpl(parentDisposable, listener) } }
apache-2.0
c61f00ba89774d7325e52b6daf8b0eec
34.878049
158
0.761786
3.911348
false
false
false
false
JetBrains/intellij-community
java/java-impl-refactorings/src/com/intellij/refactoring/extractMethod/newImpl/MethodExtractor.kt
1
14174
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.refactoring.extractMethod.newImpl import com.intellij.codeInsight.Nullability import com.intellij.codeInsight.highlighting.HighlightManager import com.intellij.ide.util.PropertiesComponent import com.intellij.java.refactoring.JavaRefactoringBundle import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.WriteAction import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.wm.WindowManager import com.intellij.psi.* import com.intellij.psi.util.PsiEditorUtil import com.intellij.refactoring.HelpID import com.intellij.refactoring.JavaRefactoringSettings import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.ExtractMethodDialog import com.intellij.refactoring.extractMethod.ExtractMethodHandler import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.addSiblingAfter import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.guessMethodName import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.replacePsiRange import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.findAllOptionsToExtract import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.selectOptionWithTargetClass import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodPipeline.withFilteredAnnotations import com.intellij.refactoring.extractMethod.newImpl.inplace.ExtractMethodPopupProvider import com.intellij.refactoring.extractMethod.newImpl.inplace.InplaceMethodExtractor import com.intellij.refactoring.extractMethod.newImpl.inplace.extractInDialog import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.refactoring.listeners.RefactoringEventListener import com.intellij.refactoring.util.CommonRefactoringUtil import com.intellij.refactoring.util.ConflictsUtil import com.intellij.util.containers.MultiMap import org.jetbrains.annotations.NonNls import java.util.concurrent.CompletableFuture data class ExtractedElements(val callElements: List<PsiElement>, val method: PsiMethod) class MethodExtractor { fun doExtract(file: PsiFile, range: TextRange) { val editor = PsiEditorUtil.findEditor(file) ?: return if (EditorSettingsExternalizable.getInstance().isVariableInplaceRenameEnabled) { val activeExtractor = InplaceMethodExtractor.getActiveExtractor(editor) if (activeExtractor != null) { activeExtractor.restartInDialog() } else { findAndSelectExtractOption(editor, file, range)?.thenApply { options -> runInplaceExtract(editor, range, options) } } } else { findAndSelectExtractOption(editor, file, range)?.thenApply { options -> extractInDialog(options.targetClass, options.elements, "", JavaRefactoringSettings.getInstance().EXTRACT_STATIC_METHOD) } } } private fun findAndSelectExtractOption(editor: Editor, file: PsiFile, range: TextRange): CompletableFuture<ExtractOptions>? { try { if (!CommonRefactoringUtil.checkReadOnlyStatus(file.project, file)) return null val elements = ExtractSelector().suggestElementsToExtract(file, range) if (elements.isEmpty()) { throw ExtractException(RefactoringBundle.message("selected.block.should.represent.a.set.of.statements.or.an.expression"), file) } val allOptionsToExtract: List<ExtractOptions> = computeWithAnalyzeProgress<List<ExtractOptions>, ExtractException>(file.project) { findAllOptionsToExtract(elements) } return selectOptionWithTargetClass(editor, allOptionsToExtract) } catch (e: ExtractException) { val message = JavaRefactoringBundle.message("extract.method.error.prefix") + " " + (e.message ?: "") CommonRefactoringUtil.showErrorHint(file.project, editor, message, ExtractMethodHandler.getRefactoringName(), HelpID.EXTRACT_METHOD) showError(editor, e.problems) return null } } private fun <T, E: Exception> computeWithAnalyzeProgress(project: Project, throwableComputable: ThrowableComputable<T, E>): T { return ProgressManager.getInstance().run(object : Task.WithResult<T, E>(project, JavaRefactoringBundle.message("dialog.title.analyze.code.fragment.to.extract"), true) { override fun compute(indicator: ProgressIndicator): T { return ReadAction.compute(throwableComputable) } }) } private fun runInplaceExtract(editor: Editor, range: TextRange, options: ExtractOptions){ val project = options.project val popupSettings = createInplaceSettingsPopup(options) val guessedNames = suggestSafeMethodNames(options) val methodName = guessedNames.first() val suggestedNames = guessedNames.takeIf { it.size > 1 }.orEmpty() executeRefactoringCommand(project) { val inplaceExtractor = InplaceMethodExtractor(editor, range, options.targetClass, popupSettings, methodName) inplaceExtractor.extractAndRunTemplate(LinkedHashSet(suggestedNames)) } } val ExtractOptions.targetClass: PsiClass get() = anchor.containingClass ?: throw IllegalStateException() private fun suggestSafeMethodNames(options: ExtractOptions): List<String> { val unsafeNames = guessMethodName(options) val safeNames = unsafeNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) } if (safeNames.isNotEmpty()) return safeNames val baseName = unsafeNames.firstOrNull() ?: "extracted" val generatedNames = sequenceOf(baseName) + generateSequence(1) { seed -> seed + 1 }.map { number -> "$baseName$number" } return generatedNames.filterNot { name -> hasConflicts(options.copy(methodName = name)) }.take(1).toList() } private fun hasConflicts(options: ExtractOptions): Boolean { val (_, method) = prepareRefactoringElements(options) val conflicts = MultiMap<PsiElement, String>() ConflictsUtil.checkMethodConflicts(options.anchor.containingClass, null, method, conflicts) return ! conflicts.isEmpty } private fun createInplaceSettingsPopup(options: ExtractOptions): ExtractMethodPopupProvider { val analyzer = CodeFragmentAnalyzer(options.elements) val optionsWithStatic = ExtractMethodPipeline.withForcedStatic(analyzer, options) val makeStaticAndPassFields = optionsWithStatic?.inputParameters?.size != options.inputParameters.size val showStatic = !options.isStatic && optionsWithStatic != null val defaultStatic = if (!makeStaticAndPassFields) JavaRefactoringSettings.getInstance().EXTRACT_STATIC_METHOD else false val hasAnnotation = options.dataOutput.nullability != Nullability.UNKNOWN && options.dataOutput.type !is PsiPrimitiveType val annotationAvailable = ExtractMethodHelper.isNullabilityAvailable(options) return ExtractMethodPopupProvider( annotateDefault = if (hasAnnotation && annotationAvailable) needsNullabilityAnnotations(options.project) else null, makeStaticDefault = if (showStatic) defaultStatic else null, staticPassFields = makeStaticAndPassFields ) } fun executeRefactoringCommand(project: Project, command: () -> Unit) { CommandProcessor.getInstance().executeCommand(project, command, ExtractMethodHandler.getRefactoringName(), null) } fun replaceElements(sourceElements: List<PsiElement>, callElements: List<PsiElement>, anchor: PsiMember, method: PsiMethod): ExtractedElements { return WriteAction.compute<ExtractedElements, Throwable> { val addedMethod = anchor.addSiblingAfter(method) as PsiMethod val replacedCallElements = replacePsiRange(sourceElements, callElements) ExtractedElements(replacedCallElements, addedMethod) } } fun extractMethod(extractOptions: ExtractOptions): ExtractedElements { val elementsToExtract = prepareRefactoringElements(extractOptions) return replaceElements(extractOptions.elements, elementsToExtract.callElements, extractOptions.anchor, elementsToExtract.method) } fun doTestExtract( doRefactor: Boolean, editor: Editor, isConstructor: Boolean?, isStatic: Boolean?, returnType: PsiType?, newNameOfFirstParam: String?, targetClass: PsiClass?, @PsiModifier.ModifierConstant visibility: String?, vararg disabledParameters: Int ): Boolean { val project = editor.project ?: return false val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.document) ?: return false val range = ExtractMethodHelper.findEditorSelection(editor) ?: return false val elements = ExtractSelector().suggestElementsToExtract(file, range) if (elements.isEmpty()) throw ExtractException("Nothing to extract", file) val analyzer = CodeFragmentAnalyzer(elements) val allOptionsToExtract = findAllOptionsToExtract(elements) var options = allOptionsToExtract.takeIf { targetClass != null }?.find { option -> option.anchor.containingClass == targetClass } ?: allOptionsToExtract.find { option -> option.anchor.containingClass !is PsiAnonymousClass } ?: allOptionsToExtract.first() options = options.copy(methodName = "newMethod") if (isConstructor != options.isConstructor){ options = ExtractMethodPipeline.asConstructor(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (! options.isStatic && isStatic == true) { options = ExtractMethodPipeline.withForcedStatic(analyzer, options) ?: throw ExtractException("Fail", elements.first()) } if (newNameOfFirstParam != null) { options = options.copy( inputParameters = listOf(options.inputParameters.first().copy(name = newNameOfFirstParam)) + options.inputParameters.drop(1) ) } if (returnType != null) { options = options.copy(dataOutput = options.dataOutput.withType(returnType)) } if (disabledParameters.isNotEmpty()) { options = options.copy( disabledParameters = options.inputParameters.filterIndexed { index, _ -> index in disabledParameters }, inputParameters = options.inputParameters.filterIndexed { index, _ -> index !in disabledParameters } ) } if (visibility != null) { options = options.copy(visibility = visibility) } if (options.anchor.containingClass?.isInterface == true) { options = ExtractMethodPipeline.adjustModifiersForInterface(options.copy(visibility = PsiModifier.PRIVATE)) } if (doRefactor) { extractMethod(options) } return true } fun showError(editor: Editor, ranges: List<TextRange>) { val project = editor.project ?: return if (ranges.isEmpty()) return val highlightManager = HighlightManager.getInstance(project) ranges.forEach { textRange -> highlightManager.addRangeHighlight(editor, textRange.startOffset, textRange.endOffset, EditorColors.SEARCH_RESULT_ATTRIBUTES, true, null) } WindowManager.getInstance().getStatusBar(project).info = RefactoringBundle.message("press.escape.to.remove.the.highlighting") } fun prepareRefactoringElements(extractOptions: ExtractOptions): ExtractedElements { val dependencies = withFilteredAnnotations(extractOptions) val factory = PsiElementFactory.getInstance(dependencies.project) val codeBlock = BodyBuilder(factory) .build( dependencies.elements, dependencies.flowOutput, dependencies.dataOutput, dependencies.inputParameters, dependencies.disabledParameters, dependencies.requiredVariablesInside ) val method = SignatureBuilder(dependencies.project) .build( dependencies.anchor.context, dependencies.elements, dependencies.isStatic, dependencies.visibility, dependencies.typeParameters, dependencies.dataOutput.type.takeIf { !dependencies.isConstructor }, dependencies.methodName, dependencies.inputParameters, dependencies.dataOutput.annotations, dependencies.thrownExceptions, dependencies.anchor ) method.body?.replace(codeBlock) if (needsNullabilityAnnotations(dependencies.project) && ExtractMethodHelper.isNullabilityAvailable(dependencies)) { updateMethodAnnotations(method, dependencies.inputParameters) } val callElements = CallBuilder(dependencies.elements.first()).createCall(method, dependencies) return ExtractedElements(callElements, method) } private fun needsNullabilityAnnotations(project: Project): Boolean { return PropertiesComponent.getInstance(project).getBoolean(ExtractMethodDialog.EXTRACT_METHOD_GENERATE_ANNOTATIONS, true) } companion object { private val LOG = Logger.getInstance(MethodExtractor::class.java) @NonNls const val refactoringId: String = "refactoring.extract.method" internal fun sendRefactoringDoneEvent(extractedMethod: PsiMethod) { val data = RefactoringEventData() data.addElement(extractedMethod) extractedMethod.project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) .refactoringDone(refactoringId, data) } internal fun sendRefactoringStartedEvent(elements: Array<PsiElement>) { val project = elements.firstOrNull()?.project ?: return val data = RefactoringEventData() data.addElements(elements) val publisher = project.messageBus.syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) publisher.refactoringStarted(refactoringId, data) } } }
apache-2.0
f49be40ba9017704ae6b73150687cc29
48.390244
146
0.767673
4.933519
false
false
false
false
raybritton/json-query
lib/src/main/kotlin/com/raybritton/jsonquery/ext/String+Misc.kt
1
360
package com.raybritton.jsonquery.ext fun String.replaceLast(oldValue: String, newValue: String, ignoreCase: Boolean = false): String { val index = lastIndexOf(oldValue, ignoreCase = ignoreCase) return if (index < 0) this else this.replaceRange(index, index + oldValue.length, newValue) } fun String?.wrap() = if (this == null) "null" else "\"$this\""
apache-2.0
538d16619242fa941bb1d15693fc8f5f
44.125
97
0.722222
3.956044
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/PatternStoreScreen.kt
2
10883
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.utils.Align import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.editor.Editor import io.github.chrislo27.rhre3.entity.Entity import io.github.chrislo27.rhre3.entity.model.ModelEntity import io.github.chrislo27.rhre3.entity.model.special.TextureEntity import io.github.chrislo27.rhre3.patternstorage.FileStoredPattern import io.github.chrislo27.rhre3.patternstorage.PatternStorage import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.track.Remix import io.github.chrislo27.rhre3.util.JsonHandler import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.Button import io.github.chrislo27.toolboks.ui.ImageLabel import io.github.chrislo27.toolboks.ui.TextField import io.github.chrislo27.toolboks.ui.TextLabel import java.io.ByteArrayOutputStream import java.nio.charset.Charset import java.util.* class PatternStoreScreen(main: RHRE3Application, val editor: Editor, val pattern: FileStoredPattern?, val entities: List<Entity>?) : ToolboksScreen<RHRE3Application, PatternStoreScreen>(main) { companion object { private const val ALLOW_SAME_NAMES = true private val JSON_SERIALIZER: ObjectMapper by lazy { JsonHandler.createObjectMapper(failOnUnknown = false, prettyPrinted = false) } fun entitiesToJson(remix: Remix, entities: List<Entity>, prettyPrinted: Boolean = true): String { val array = JsonHandler.OBJECT_MAPPER.createArrayNode() val oldBounds: Map<Entity, Rectangle> = entities.associateWith { Rectangle(it.bounds) } val baseX: Float = entities.minByOrNull { it.bounds.x }?.bounds?.x ?: 0f val baseY: Int = entities.minByOrNull { it.bounds.y }?.bounds?.y?.toInt() ?: 0 entities.forEach { it.updateBounds { it.bounds.x -= baseX it.bounds.y -= baseY } } val texturesStored: MutableSet<String> = mutableSetOf() entities.forEach { entity -> val node = array.addObject() node.put("type", entity.jsonType) if (entity is TextureEntity) { val hash = entity.textureHash if (hash != null && hash !in texturesStored) { val texture = remix.textureCache[hash] if (texture != null) { node.put("_textureData_hash", hash) node.put("_textureData_data", Base64.getEncoder().encode(ByteArrayOutputStream().also { baos -> Remix.writeTexture(baos, texture) }.toByteArray()).toString(Charset.forName("UTF-8"))) texturesStored += hash } } } entity.saveData(node) } // Restore bounds entities.forEach { it.updateBounds { it.bounds.set(oldBounds[it]) } } return if (prettyPrinted) JsonHandler.toJson(array) else JSON_SERIALIZER.writeValueAsString(array) } fun jsonToEntities(remix: Remix, json: String): List<Entity> { return (JsonHandler.OBJECT_MAPPER.readTree(json) as ArrayNode).map { node -> Entity.getEntityFromType(node["type"]?.asText(null) ?: return@map null, node as ObjectNode, remix)?.also { it.readData(node) // Load textures if necessary val texHashNode = node["_textureData_hash"] val texDataNode = node["_textureData_data"] if (texHashNode != null && texDataNode != null) { val texHash = texHashNode.asText() if (!remix.textureCache.containsKey(texHash)) { try { val bytes = Base64.getDecoder().decode(texDataNode.asText().toByteArray(Charset.forName("UTF-8"))) remix.textureCache[texHash] = Texture(Pixmap(bytes, 0, bytes.size)) } catch (e: Exception) { e.printStackTrace() } } } } ?: Remix.createMissingEntitySubtitle(remix, node[ModelEntity.JSON_DATAMODEL]?.textValue() ?: "null", node["beat"]?.floatValue() ?: 0f, node["track"]?.floatValue() ?: 0f, node["width"]?.floatValue() ?: 1f, node["height"]?.floatValue()?.coerceAtLeast(1f) ?: 1f) }.filterNotNull() } } override val stage: GenericStage<PatternStoreScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val button: Button<PatternStoreScreen> private lateinit var textField: TextField<PatternStoreScreen> init { stage.titleLabel.text = if (pattern != null) "screen.patternStore.edit.title" else "screen.patternStore.title" stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_pattern_store")) stage.backButton.visible = true stage.onBackButtonClick = { main.screen = ScreenRegistry["editor"] } val palette = main.uiPalette stage.centreStage.elements += TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(screenY = 0.75f, screenHeight = 0.15f) this.isLocalizationKey = true this.text = "screen.patternStore.enterName" } val alreadyExists = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.location.set(screenY = 0.15f, screenHeight = 0.15f) this.isLocalizationKey = true this.text = "screen.patternStore.alreadyExists" this.visible = false } stage.centreStage.elements += alreadyExists if (pattern != null) { stage.bottomStage.elements += Button(palette.copy(highlightedBackColor = Color(1f, 0f, 0f, 0.5f), clickedBackColor = Color(1f, 0.5f, 0.5f, 0.5f)), stage.bottomStage, stage.bottomStage).apply { val backBtnLoc = [email protected] this.location.set(1f - backBtnLoc.screenX - backBtnLoc.screenWidth, backBtnLoc.screenY, backBtnLoc.screenWidth, backBtnLoc.screenHeight) this.addLabel(ImageLabel(palette, this, this.stage).apply { this.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_x")) }) this.leftClickAction = { _, _ -> main.screen = PatternDeleteScreen(main, editor, pattern, this@PatternStoreScreen) } } } button = Button(palette, stage.bottomStage, stage.bottomStage).apply { this.location.set(screenX = 0.25f, screenWidth = 0.5f) this.addLabel(TextLabel(palette, this, this.stage).apply { this.isLocalizationKey = true this.text = "screen.patternStore.button" }) this.leftClickAction = { _, _ -> if (pattern == null) { val entities = entities!! PatternStorage.addPattern(FileStoredPattern(UUID.randomUUID(), textField.text.trim(), entitiesToJson(entities.first().remix, entities))) .persist() } else { PatternStorage.deletePattern(pattern) .addPattern(FileStoredPattern(pattern.uuid, textField.text.trim(), pattern.data)) .persist() } editor.stage.updateSelected() main.screen = ScreenRegistry["editor"] } this.enabled = false } val charsRemaining = TextLabel(palette, stage.centreStage, stage.centreStage).apply { this.isLocalizationKey = false this.text = "0 / ?" this.textAlign = Align.right this.fontScaleMultiplier = 0.75f this.location.set(screenX = 0.25f, screenWidth = 0.5f, screenY = 0.4125f, screenHeight = 0.1f) } stage.centreStage.elements += charsRemaining textField = object : TextField<PatternStoreScreen>(palette, stage.centreStage, stage.centreStage) { init { characterLimit = PatternStorage.MAX_PATTERN_NAME_SIZE } override fun onEnterPressed(): Boolean { if (text.isNotBlank()) { button.onLeftClick(0f, 0f) return true } return false } override fun onRightClick(xPercent: Float, yPercent: Float) { super.onRightClick(xPercent, yPercent) text = "" } override fun onTextChange(oldText: String) { super.onTextChange(oldText) val trimmed = text.trim() val already = PatternStorage.patterns.values.any { it !== pattern && it.name == trimmed } button.enabled = trimmed.isNotEmpty() && (ALLOW_SAME_NAMES || !already) alreadyExists.visible = already charsRemaining.text = "${trimmed.length} / ${PatternStorage.MAX_PATTERN_NAME_SIZE}" } }.apply { this.location.set(screenY = 0.5f, screenHeight = 0.1f, screenX = 0.25f, screenWidth = 0.5f) this.canPaste = true this.canInputNewlines = false this.background = true this.hasFocus = true onTextChange("") } stage.centreStage.elements += textField stage.bottomStage.elements += button if (entities?.size == 0) error("Entities are empty") stage.updatePositions() textField.apply { if (pattern != null) { text = pattern.name this.caret = text.length + 1 } } } override fun tickUpdate() { } override fun dispose() { } }
gpl-3.0
a19982b51718cb813a9740621b236922
43.420408
156
0.585776
4.688927
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/classstore/ClassDefinition.kt
10
6296
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.classstore import com.intellij.diagnostic.hprof.parser.Type import org.jetbrains.annotations.NonNls import java.util.function.LongUnaryOperator class ClassDefinition(val name: String, val id: Long, val superClassId: Long, val classLoaderId: Long, val instanceSize: Int, val superClassOffset: Int, val refInstanceFields: Array<InstanceField>, private val primitiveInstanceFields: Array<InstanceField>, val constantFields: LongArray, val objectStaticFields: Array<StaticField>, val primitiveStaticFields: Array<StaticField>) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ClassDefinition if (id != other.id) return false if (id == 0L && other.id == 0L) { return name == other.name } return true } val prettyName: String get() = computePrettyName(name) companion object { const val OBJECT_PREAMBLE_SIZE = 8 const val ARRAY_PREAMBLE_SIZE = 12 @NonNls fun computePrettyName(name: String): String { if (!name.startsWith('[')) return name var arraySymbolsCount = 0 while (name.length > arraySymbolsCount && name[arraySymbolsCount] == '[') arraySymbolsCount++ if (name.length <= arraySymbolsCount) { // Malformed name return name } val arrayType: Char = name[arraySymbolsCount] val arrayString: String = "[]".repeat(arraySymbolsCount) return when (arrayType) { 'B' -> "byte$arrayString" 'C' -> "char$arrayString" 'D' -> "double$arrayString" 'F' -> "float$arrayString" 'I' -> "int$arrayString" 'J' -> "long$arrayString" 'L' -> "${name.substring(arraySymbolsCount + 1, name.length - 1)}$arrayString" 'S' -> "short$arrayString" 'Z' -> "boolean$arrayString" else -> name } } val CLASS_FIELD = InstanceField("<class>", -1, Type.OBJECT) } fun getSuperClass(classStore: ClassStore): ClassDefinition? { return when (superClassId) { 0L -> null else -> classStore[superClassId.toInt()] } } override fun hashCode(): Int = id.hashCode() fun isArray(): Boolean = name[0] == '[' fun isPrimitiveArray(): Boolean = isArray() && name.length == 2 fun copyWithRemappedIDs(remappingFunction: LongUnaryOperator): ClassDefinition { fun map(id: Long): Long = remappingFunction.applyAsLong(id) val newConstantFields = LongArray(constantFields.size) { map(constantFields[it]) } val newStaticObjectFields = Array(objectStaticFields.size) { val oldStaticField = objectStaticFields[it] StaticField(oldStaticField.name, map(oldStaticField.value)) } return ClassDefinition( name, map(id), map(superClassId), map(classLoaderId), instanceSize, superClassOffset, refInstanceFields, primitiveInstanceFields, newConstantFields, newStaticObjectFields, primitiveStaticFields ) } fun allRefFieldNames(classStore: ClassStore): List<String> { val result = mutableListOf<String>() var currentClass = this do { result.addAll(currentClass.refInstanceFields.map { it.name }) currentClass = currentClass.getSuperClass(classStore) ?: break } while (true) return result } fun getRefField(classStore: ClassStore, index: Int): InstanceField { var currentIndex = index var currentClass = this do { val size = currentClass.refInstanceFields.size if (currentIndex < size) { return currentClass.refInstanceFields[currentIndex] } currentIndex -= size currentClass = currentClass.getSuperClass(classStore) ?: break } while (true) if (currentIndex == 0) { return CLASS_FIELD } throw IndexOutOfBoundsException("$index on class $name") } fun getClassFieldName(index: Int): String { if (index in constantFields.indices) { return "<constant>" } if (index in constantFields.size until constantFields.size + objectStaticFields.size) { return objectStaticFields[index - constantFields.size].name } if (index == constantFields.size + objectStaticFields.size) { return "<loader>" } throw IndexOutOfBoundsException("$index on class $name") } fun getPrimitiveStaticFieldValue(name: String): Long? { return primitiveStaticFields.find { it.name == name }?.value } /** * Computes offset of a given field in the class (including superclasses) * @return Offset of the field, or -1 if the field doesn't exist. */ fun computeOffsetOfField(fieldName: String, classStore: ClassStore): Int { var classOffset = 0 var currentClass = this do { var field = currentClass.refInstanceFields.find { it.name == fieldName } if (field == null) { field = currentClass.primitiveInstanceFields.find { it.name == fieldName } } if (field != null) { return classOffset + field.offset } classOffset += currentClass.superClassOffset currentClass = currentClass.getSuperClass(classStore) ?: return -1 } while (true) } fun copyWithName(newName: String): ClassDefinition { return ClassDefinition(newName, id, superClassId, classLoaderId, instanceSize, superClassOffset, refInstanceFields, primitiveInstanceFields, constantFields, objectStaticFields, primitiveStaticFields) } }
apache-2.0
e6c207680e7542654dd2f621a6b74c04
32.668449
144
0.658196
4.452617
false
false
false
false
aconsuegra/algorithms-playground
src/main/kotlin/me/consuegra/algorithms/KPalindromeNumber.kt
1
436
package me.consuegra.algorithms /** * Determine whether an integer is a palindrome. Do this without extra space. */ class KPalindromeNumber { fun isPalindrome(x: Int) : Boolean { if (x < 0) { return false } var input = x var reverse = 0 while (input > 0) { reverse = reverse * 10 + input % 10 input /= 10 } return reverse == x } }
mit
1f8402a500037d9a58669425090a9098
19.761905
77
0.520642
4.27451
false
false
false
false
vanniktech/lint-rules
lint-rules-rxjava2-lint/src/main/java/com/vanniktech/lintrules/rxjava2/RxJava2SchedulersFactoryCallDetector.kt
1
2704
@file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final. package com.vanniktech.lintrules.rxjava2 import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Detector.UastScanner import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope.JAVA_FILE import com.android.tools.lint.detector.api.Severity.WARNING import com.intellij.psi.PsiMethod import org.jetbrains.uast.UAnnotated import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.getContainingUMethod import java.util.EnumSet val ISSUE_RAW_SCHEDULER_CALL = Issue.create( "RxJava2SchedulersFactoryCall", "Instead of calling the Schedulers factory methods directly inject the Schedulers.", "Injecting the Schedulers instead of accessing them via the factory methods has the benefit that unit testing is way easier. Instead of overriding them via the Plugin mechanism we can just pass a custom Scheduler.", CORRECTNESS, PRIORITY, WARNING, Implementation(RxJava2SchedulersFactoryCallDetector::class.java, EnumSet.of(JAVA_FILE)), ) private val schedulersMethods = listOf("io", "computation", "newThread", "single", "from") private val androidSchedulersMethods = listOf("mainThread") class RxJava2SchedulersFactoryCallDetector : Detector(), UastScanner { override fun getApplicableMethodNames() = schedulersMethods + androidSchedulersMethods override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) { val evaluator = context.evaluator val isInSchedulers = evaluator.isMemberInClass(method, "io.reactivex.schedulers.Schedulers") val isInAndroidSchedulers = evaluator.isMemberInClass(method, "io.reactivex.android.schedulers.AndroidSchedulers") val isSchedulersMatch = schedulersMethods.contains(node.methodName) && isInSchedulers val isAndroidSchedulersMatch = androidSchedulersMethods.contains(node.methodName) && isInAndroidSchedulers val containingMethod = node.getContainingUMethod() val shouldIgnore = containingMethod != null && context.evaluator.getAllAnnotations(containingMethod as UAnnotated, false) .any { annotation -> listOf("dagger.Provides", "io.reactivex.annotations.SchedulerSupport").any { it == annotation.qualifiedName } } if ((isSchedulersMatch || isAndroidSchedulersMatch) && !shouldIgnore) { context.report(ISSUE_RAW_SCHEDULER_CALL, node, context.getNameLocation(node), "Inject this Scheduler instead of calling it directly") } } }
apache-2.0
f239c822c31861c34c1e2a5949772026
53.08
217
0.803624
4.506667
false
false
false
false
leafclick/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/CommonCheckinFilesAction.kt
1
3369
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.actions import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil.pluralize import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ChangeListManagerImpl import com.intellij.openapi.vcs.changes.LocalChangeList import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil.intersects import com.intellij.vcsUtil.VcsUtil.getVcsFor import kotlin.streams.asSequence private fun VcsContext.getRoots(): Sequence<FilePath> = selectedFilePathsStream.asSequence() private fun VcsContext.getCommonVcs(): AbstractVcs? { val project = project ?: return null return getRoots().mapNotNull { getVcsFor(project, it) }.distinct().singleOrNull() } open class CommonCheckinFilesAction : AbstractCommonCheckinAction() { override fun getActionName(dataContext: VcsContext): String { val actionName = dataContext.getCommonVcs()?.checkinEnvironment?.checkinOperationName return appendSubject(dataContext, actionName ?: message("vcs.command.name.checkin")) } private fun appendSubject(dataContext: VcsContext, checkinActionName: String): String { val roots = dataContext.getRoots().take(2).toList() if (roots.isEmpty()) return checkinActionName val messageKey = if (roots[0].isDirectory) "action.name.checkin.directory" else "action.name.checkin.file" return message(pluralize(messageKey, roots.size), checkinActionName) } override fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList { val manager = ChangeListManager.getInstance(project) val defaultChangeList = manager.defaultChangeList var result: LocalChangeList? = null for (root in getRoots(context)) { if (root.virtualFile == null) continue val changes = manager.getChangesIn(root) if (intersects(changes, defaultChangeList.changes)) return defaultChangeList result = changes.firstOrNull()?.let { manager.getChangeList(it) } } return result ?: defaultChangeList } override fun approximatelyHasRoots(dataContext: VcsContext): Boolean = dataContext.getRoots().any { isApplicableRoot(it, dataContext) } protected open fun isApplicableRoot(path: FilePath, dataContext: VcsContext): Boolean { val manager = ChangeListManagerImpl.getInstanceImpl(dataContext.project!!) val status = manager.getStatus(path) @Suppress("DEPRECATION") return (path.isDirectory || status != FileStatus.NOT_CHANGED) && status != FileStatus.IGNORED && path.virtualFile?.let { isApplicableRoot(it, status, dataContext) } != false } @Deprecated("Use `isApplicableRoot(FilePath, VcsContext)` instead", ReplaceWith("isApplicableRoot()")) protected open fun isApplicableRoot(file: VirtualFile, status: FileStatus, dataContext: VcsContext): Boolean = true override fun getRoots(dataContext: VcsContext): Array<FilePath> = dataContext.selectedFilePaths override fun isForceUpdateCommitStateFromContext(): Boolean = true }
apache-2.0
72569b160d67d247a0a5ec57fa97d72f
43.92
140
0.778569
4.705307
false
false
false
false
siosio/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonFileProviderIndexStatistics.kt
1
1621
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing.diagnostic.dto import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) data class JsonFileProviderIndexStatistics( val providerName: String = "", val totalNumberOfIndexedFiles: Int = 0, val totalNumberOfFilesFullyIndexedByExtensions: Int = 0, val totalIndexingTime: JsonDuration = JsonDuration(0), val contentLoadingTime: JsonDuration = JsonDuration(0), val numberOfTooLargeForIndexingFiles: Int = 0, val slowIndexedFiles: List<JsonSlowIndexedFile> = emptyList(), // Available only if [com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles] is enabled. val indexedFiles: List<JsonIndexedFile>? = null ) { @JsonIgnoreProperties(ignoreUnknown = true) data class JsonSlowIndexedFile( val fileName: String = "", val processingTime: JsonDuration = JsonDuration(0), val indexingTime: JsonDuration = JsonDuration(0), val contentLoadingTime: JsonDuration = JsonDuration(0) ) @JsonIgnoreProperties(ignoreUnknown = true) data class JsonIndexedFile( val path: PortableFilePath = PortableFilePath.AbsolutePath(""), @JsonProperty("wfibe") val wasFullyIndexedByExtensions: Boolean = false ) }
apache-2.0
00cc448729f7cafbcd556a910077c40d
44.055556
140
0.792721
4.579096
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt
1
3576
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.util.Ref import com.intellij.psi.SmartPsiElementPointer import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode abstract class KotlinSingleIntentionActionFactoryWithDelegate<E : KtElement, D : Any>( private val actionPriority: IntentionActionPriority = IntentionActionPriority.NORMAL ) : KotlinIntentionActionFactoryWithDelegate<E, D>() { protected abstract fun createFix(originalElement: E, data: D): IntentionAction? final override fun createFixes( originalElementPointer: SmartPsiElementPointer<E>, diagnostic: Diagnostic, quickFixDataFactory: () -> D? ): List<QuickFixWithDelegateFactory> = QuickFixWithDelegateFactory(actionPriority) factory@{ val originalElement = originalElementPointer.element ?: return@factory null val data = quickFixDataFactory() ?: return@factory null createFix(originalElement, data) }.let(::listOf) } abstract class KotlinIntentionActionFactoryWithDelegate<E : KtElement, D : Any> : KotlinIntentionActionsFactory() { abstract fun getElementOfInterest(diagnostic: Diagnostic): E? protected abstract fun createFixes( originalElementPointer: SmartPsiElementPointer<E>, diagnostic: Diagnostic, quickFixDataFactory: () -> D? ): List<QuickFixWithDelegateFactory> abstract fun extractFixData(element: E, diagnostic: Diagnostic): D? final override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val diagnosticMessage = DefaultErrorMessages.render(diagnostic) val diagnosticElementPointer = diagnostic.psiElement.createSmartPointer() val originalElement = getElementOfInterest(diagnostic) ?: return emptyList() val originalElementPointer = originalElement.createSmartPointer() val file = originalElement.containingFile val project = file.project // Cache data so that it can be shared between quick fixes bound to the same element & diagnostic // Cache null values val cachedData: Ref<D> = Ref.create(extractFixData(originalElement, diagnostic)) return try { createFixes(originalElementPointer, diagnostic) factory@{ val element = originalElementPointer.element ?: return@factory null val diagnosticElement = diagnosticElementPointer.element ?: return@factory null if (!diagnosticElement.isValid || !element.isValid) return@factory null val currentDiagnostic = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) .diagnostics .forElement(diagnosticElement) .firstOrNull { DefaultErrorMessages.render(it) == diagnosticMessage } ?: return@factory null cachedData.get() ?: extractFixData(element, currentDiagnostic) }.filter { it.isAvailable(project, null, file) } } finally { cachedData.set(null) // Do not keep cache after all actions are initialized } } }
apache-2.0
84f901eafaec61ceea869cb226b1957f
47.986301
158
0.732383
5.552795
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/ConvertCallChainIntoSequenceInspection.kt
1
10917
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LabeledComponent import com.intellij.psi.PsiWhiteSpace import com.intellij.ui.EditorTextField import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.replaced import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import java.awt.BorderLayout import javax.swing.JPanel class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() { private val defaultCallChainLength = 5 private var callChainLength = defaultCallChainLength var callChainLengthText = defaultCallChainLength.toString() set(value) { field = value callChainLength = value.toIntOrNull() ?: defaultCallChainLength } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = qualifiedExpressionVisitor(fun(expression) { val (qualified, firstCall, callChainLength) = expression.findCallChain() ?: return val rangeInElement = firstCall.calleeExpression?.textRange?.shiftRight(-qualified.startOffset) ?: return val highlightType = if (callChainLength >= this.callChainLength) ProblemHighlightType.GENERIC_ERROR_OR_WARNING else ProblemHighlightType.INFORMATION holder.registerProblemWithoutOfflineInformation( qualified, KotlinBundle.message("call.chain.on.collection.could.be.converted.into.sequence.to.improve.performance"), isOnTheFly, highlightType, rangeInElement, ConvertCallChainIntoSequenceFix() ) }) override fun createOptionsPanel(): JPanel = OptionsPanel(this) private class OptionsPanel(owner: ConvertCallChainIntoSequenceInspection) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(owner.callChainLengthText).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { owner.callChainLengthText = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("call.chain.length.to.transform"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } } private class ConvertCallChainIntoSequenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.call.chain.into.sequence.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtQualifiedExpression ?: return val context = expression.analyze(BodyResolveMode.PARTIAL) val calls = expression.collectCallExpression(context).reversed() val firstCall = calls.firstOrNull() ?: return val lastCall = calls.lastOrNull() ?: return val first = firstCall.getQualifiedExpressionForSelector() ?: firstCall val last = lastCall.getQualifiedExpressionForSelector() ?: return val endWithTermination = lastCall.isTermination(context) val psiFactory = KtPsiFactory(expression) val dot = buildString { if (first is KtQualifiedExpression && first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') } ) append("\n") if (first is KtSafeQualifiedExpression) append("?") append(".") } val firstCommentSaver = CommentSaver(first) val firstReplaced = first.replaced( psiFactory.buildExpression { if (first is KtQualifiedExpression) { appendExpression(first.receiverExpression) appendFixedText(dot) } appendExpression(psiFactory.createExpression("asSequence()")) appendFixedText(dot) appendExpression(firstCall) } ) firstCommentSaver.restore(firstReplaced) if (!endWithTermination) { val lastCommentSaver = CommentSaver(last) val lastReplaced = last.replace( psiFactory.buildExpression { appendExpression(last) appendFixedText(dot) appendExpression(psiFactory.createExpression("toList()")) } ) lastCommentSaver.restore(lastReplaced) } } } private data class CallChain( val qualified: KtQualifiedExpression, val firstCall: KtCallExpression, val callChainLength: Int ) private fun KtQualifiedExpression.findCallChain(): CallChain? { if (parent is KtQualifiedExpression) return null val context = analyze(BodyResolveMode.PARTIAL) val calls = collectCallExpression(context) if (calls.isEmpty()) return null val lastCall = calls.last() val receiverType = lastCall.receiverType(context) if (receiverType?.isIterable(DefaultBuiltIns.Instance) != true) return null val firstCall = calls.first() val qualified = firstCall.getQualifiedExpressionForSelector() ?: firstCall.getQualifiedExpressionForReceiver() ?: return null return CallChain(qualified, lastCall, calls.size) } private fun KtQualifiedExpression.collectCallExpression(context: BindingContext): List<KtCallExpression> { val calls = mutableListOf<KtCallExpression>() fun collect(qualified: KtQualifiedExpression) { val call = qualified.callExpression ?: return calls.add(call) val receiver = qualified.receiverExpression if (receiver is KtCallExpression && receiver.implicitReceiver(context) != null) { calls.add(receiver) return } if (receiver is KtQualifiedExpression) collect(receiver) } collect(this) if (calls.size < 2) return emptyList() val transformationCalls = calls .asSequence() .dropWhile { !it.isTransformationOrTermination(context) } .takeWhile { it.isTransformationOrTermination(context) && !it.hasReturn() } .toList() .dropLastWhile { it.isLazyTermination(context) } if (transformationCalls.size < 2) return emptyList() return transformationCalls } private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg -> arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null } } private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean { val fqName = transformationAndTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isTermination(context: BindingContext): Boolean { val fqName = terminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } private fun KtCallExpression.isLazyTermination(context: BindingContext): Boolean { val fqName = lazyTerminations[calleeExpression?.text] ?: return false return isCalling(fqName, context) } internal val collectionTransformationFunctionNames = listOf( "chunked", "distinct", "distinctBy", "drop", "dropWhile", "filter", "filterIndexed", "filterIsInstance", "filterNot", "filterNotNull", "flatten", "map", "mapIndexed", "mapIndexedNotNull", "mapNotNull", "minus", "minusElement", "onEach", "onEachIndexed", "plus", "plusElement", "requireNoNulls", "sorted", "sortedBy", "sortedByDescending", "sortedDescending", "sortedWith", "take", "takeWhile", "windowed", "withIndex", "zipWithNext" ) @NonNls private val transformations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.collections.$it") } internal val collectionTerminationFunctionNames = listOf( "all", "any", "asIterable", "asSequence", "associate", "associateBy", "associateByTo", "associateTo", "average", "contains", "count", "elementAt", "elementAtOrElse", "elementAtOrNull", "filterIndexedTo", "filterIsInstanceTo", "filterNotNullTo", "filterNotTo", "filterTo", "find", "findLast", "first", "firstNotNullOf", "firstNotNullOfOrNull", "firstOrNull", "fold", "foldIndexed", "groupBy", "groupByTo", "groupingBy", "indexOf", "indexOfFirst", "indexOfLast", "joinTo", "joinToString", "last", "lastIndexOf", "lastOrNull", "mapIndexedNotNullTo", "mapIndexedTo", "mapNotNullTo", "mapTo", "maxOrNull", "maxByOrNull", "maxWithOrNull", "maxOf", "maxOfOrNull", "maxOfWith", "maxOfWithOrNull", "minOrNull", "minByOrNull", "minWithOrNull", "minOf", "minOfOrNull", "minOfWith", "minOfWithOrNull", "none", "partition", "reduce", "reduceIndexed", "reduceIndexedOrNull", "reduceOrNull", "runningFold", "runningFoldIndexed", "runningReduce", "runningReduceIndexed", "scan", "scanIndexed", "single", "singleOrNull", "sum", "sumBy", "sumByDouble", "sumOf", "toCollection", "toHashSet", "toList", "toMutableList", "toMutableSet", "toSet", "toSortedSet", "unzip" ) @NonNls private val terminations = collectionTerminationFunctionNames.associateWith { val pkg = if (it in listOf("contains", "indexOf", "lastIndexOf")) "kotlin.collections.List" else "kotlin.collections" FqName("$pkg.$it") } private val lazyTerminations = terminations.filter { (key, _) -> key == "groupingBy" } private val transformationAndTerminations = transformations + terminations
apache-2.0
86f3467d22fcc0bb6978ebb15e966575
31.981873
158
0.682514
5.09426
false
false
false
false
BijoySingh/Quick-Note-Android
scarlet/src/main/java/com/bijoysingh/quicknote/firebase/data/FirebaseNote.kt
1
1353
package com.bijoysingh.quicknote.firebase.data import com.google.firebase.database.Exclude import com.maubis.scarlet.base.core.note.INoteContainer import com.maubis.scarlet.base.core.note.NoteState import java.util.* // TODO: Remove this on Firebase deprecation class FirebaseNote( val uuid: String, val description: String, val timestamp: Long, val updateTimestamp: Long, val color: Int, val state: String, val tags: String, val locked: Boolean, val pinned: Boolean, val folder: String) : INoteContainer { @Exclude override fun uuid(): String = uuid @Exclude override fun description(): String = description @Exclude override fun timestamp(): Long = timestamp @Exclude override fun updateTimestamp(): Long = updateTimestamp @Exclude override fun color(): Int = color @Exclude override fun state(): String = state @Exclude override fun tags(): String = tags @Exclude override fun meta(): Map<String, Any> = emptyMap() @Exclude override fun locked(): Boolean = locked @Exclude override fun pinned(): Boolean = pinned @Exclude override fun folder(): String = folder constructor() : this( "invalid", "", Calendar.getInstance().timeInMillis, Calendar.getInstance().timeInMillis, -0xff8695, NoteState.DEFAULT.name, "", false, false, "") }
gpl-3.0
18319d2edc2c68e13cb05d0c782867db
19.830769
56
0.699926
4.214953
false
false
false
false
androidx/androidx
work/work-testing/src/main/java/androidx/work/testing/TestScheduler.kt
3
9547
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) package androidx.work.testing import android.content.Context import androidx.annotation.GuardedBy import androidx.annotation.RestrictTo import androidx.work.Worker import androidx.work.impl.ExecutionListener import androidx.work.impl.Scheduler import androidx.work.impl.WorkDatabase import androidx.work.impl.model.WorkGenerationalId import androidx.work.impl.WorkManagerImpl import androidx.work.impl.StartStopTokens import androidx.work.impl.model.generationalId import androidx.work.impl.model.WorkSpec import androidx.work.impl.model.WorkSpecDao import java.util.UUID /** * A test scheduler that schedules unconstrained, non-timed workers. It intentionally does * not acquire any WakeLocks, instead trying to brute-force them as time allows before the process * gets killed. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class TestScheduler(private val context: Context) : Scheduler, ExecutionListener { @GuardedBy("lock") private val pendingWorkStates = mutableMapOf<String, InternalWorkState>() @GuardedBy("lock") private val terminatedWorkIds = mutableSetOf<String>() private val lock = Any() private val mStartStopTokens = StartStopTokens() override fun hasLimitedSchedulingSlots() = true override fun schedule(vararg workSpecs: WorkSpec) { if (workSpecs.isEmpty()) { return } val toSchedule = mutableMapOf<WorkSpec, InternalWorkState>() synchronized(lock) { workSpecs.forEach { val state = pendingWorkStates.getOrPut(it.generationalId().workSpecId) { InternalWorkState(it) } toSchedule[it] = state } } toSchedule.forEach { (originalSpec, state) -> // this spec is attempted to run for the first time // so we have to rewind the time, because we have to override flex. val spec = if (originalSpec.isPeriodic && state.periodDelayMet) { WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(originalSpec.id) } else originalSpec // don't even try to run a worker that WorkerWrapper won't execute anyway. // similar to logic in WorkerWrapper if ((spec.isPeriodic || spec.isBackedOff) && (spec.calculateNextRunTime() > System.currentTimeMillis())) { return@forEach } scheduleInternal(spec.generationalId(), state) } } override fun cancel(workSpecId: String) { // We don't need to keep track of cancelled workSpecs. This is because subsequent calls // to enqueue() will no-op because insertWorkSpec in WorkDatabase has a conflict // policy of @Ignore. So TestScheduler will _never_ be asked to schedule those // WorkSpecs. val tokens = mStartStopTokens.remove(workSpecId) tokens.forEach { WorkManagerImpl.getInstance(context).stopWork(it) } synchronized(lock) { val internalWorkState = pendingWorkStates[workSpecId] if (internalWorkState != null && !internalWorkState.isPeriodic) { // Don't remove PeriodicWorkRequests from the list of pending work states. // This is because we keep track of mPeriodDelayMet for PeriodicWorkRequests. // `mPeriodDelayMet` is set to `false` when `onExecuted()` is called as a result of a // successful run or a cancellation. That way subsequent calls to schedule() no-op // until a developer explicitly calls setPeriodDelayMet(). pendingWorkStates.remove(workSpecId) } } } /** * Tells the [TestScheduler] to pretend that all constraints on the [Worker] with * the given `workSpecId` are met. * * @param workSpecId The [Worker]'s id * @throws IllegalArgumentException if `workSpecId` is not enqueued */ fun setAllConstraintsMet(workSpecId: UUID) { val id = workSpecId.toString() val state: InternalWorkState synchronized(lock) { if (id in terminatedWorkIds) return val oldState = pendingWorkStates[id] ?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!") state = oldState.copy(constraintsMet = true) pendingWorkStates[id] = state } scheduleInternal(WorkGenerationalId(id, state.generation), state) } /** * Tells the [TestScheduler] to pretend that the initial delay on the [Worker] with * the given `workSpecId` are met. * * @param workSpecId The [Worker]'s id * @throws IllegalArgumentException if `workSpecId` is not enqueued */ fun setInitialDelayMet(workSpecId: UUID) { val id = workSpecId.toString() val state: InternalWorkState synchronized(lock) { if (id in terminatedWorkIds) return val oldState = pendingWorkStates[id] ?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!") state = oldState.copy(initialDelayMet = true) pendingWorkStates[id] = state } WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(id) scheduleInternal(WorkGenerationalId(id, state.generation), state) } /** * Tells the [TestScheduler] to pretend that the periodic delay on the [Worker] with * the given `workSpecId` are met. * * @param workSpecId The [Worker]'s id * @throws IllegalArgumentException if `workSpecId` is not enqueued */ fun setPeriodDelayMet(workSpecId: UUID) { val id = workSpecId.toString() val state: InternalWorkState synchronized(lock) { val oldState = pendingWorkStates[id] ?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!") state = oldState.copy(periodDelayMet = true) pendingWorkStates[id] = state } WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(id) scheduleInternal(WorkGenerationalId(id, state.generation), state) } override fun onExecuted(id: WorkGenerationalId, needsReschedule: Boolean) { synchronized(lock) { val workSpecId = id.workSpecId val internalWorkState = pendingWorkStates[workSpecId] ?: return if (internalWorkState.isPeriodic) { pendingWorkStates[workSpecId] = internalWorkState.copy( periodDelayMet = !internalWorkState.isPeriodic, constraintsMet = !internalWorkState.hasConstraints, ) } else { pendingWorkStates.remove(workSpecId) terminatedWorkIds.add(workSpecId) } mStartStopTokens.remove(workSpecId) } } private fun scheduleInternal(generationalId: WorkGenerationalId, state: InternalWorkState) { if (state.isRunnable) { val wm = WorkManagerImpl.getInstance(context) wm.startWork(mStartStopTokens.tokenFor(generationalId)) } } } internal data class InternalWorkState( val generation: Int, val constraintsMet: Boolean, val initialDelayMet: Boolean, val periodDelayMet: Boolean, val hasConstraints: Boolean, val isPeriodic: Boolean, ) internal val InternalWorkState.isRunnable: Boolean get() = constraintsMet && initialDelayMet && periodDelayMet internal fun InternalWorkState(spec: WorkSpec): InternalWorkState = InternalWorkState( generation = spec.generation, constraintsMet = !spec.hasConstraints(), initialDelayMet = spec.initialDelay == 0L, periodDelayMet = true, hasConstraints = spec.hasConstraints(), isPeriodic = spec.isPeriodic ) private fun WorkManagerImpl.rewindLastEnqueueTime(id: String): WorkSpec { // We need to pass check that mWorkSpec.calculateNextRunTime() < now // so we reset "rewind" enqueue time to pass the check // we don't reuse available internalWorkState.mWorkSpec, because it // is not update with period_count and last_enqueue_time // More proper solution would be to abstract away time instead of just using // System.currentTimeMillis() in WM val workDatabase: WorkDatabase = workDatabase val dao: WorkSpecDao = workDatabase.workSpecDao() val workSpec: WorkSpec = dao.getWorkSpec(id) ?: throw IllegalStateException("WorkSpec is already deleted from WM's db") val now = System.currentTimeMillis() val timeOffset = workSpec.calculateNextRunTime() - now if (timeOffset > 0) { dao.setLastEnqueuedTime(id, workSpec.lastEnqueueTime - timeOffset) } return dao.getWorkSpec(id) ?: throw IllegalStateException("WorkSpec is already deleted from WM's db") }
apache-2.0
f4de19921d9f88ea95a44aef371ecf1d
41.061674
101
0.673091
4.625484
false
false
false
false
androidx/androidx
core/uwb/uwb/src/androidTest/java/androidx/core/uwb/impl/UwbClientSessionScopeImplTest.kt
3
10166
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.uwb.impl import androidx.core.uwb.RangingResult import androidx.core.uwb.RangingResult.RangingResultPeerDisconnected import androidx.core.uwb.RangingResult.RangingResultPosition import androidx.core.uwb.common.TestCommons.Companion.COMPLEX_CHANNEL import androidx.core.uwb.common.TestCommons.Companion.LOCAL_ADDRESS import androidx.core.uwb.common.TestCommons.Companion.RANGING_CAPABILITIES import androidx.core.uwb.common.TestCommons.Companion.RANGING_PARAMETERS import androidx.core.uwb.common.TestCommons.Companion.UWB_DEVICE import androidx.core.uwb.mock.TestUwbClient import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.cancellable import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Test class UwbClientSessionScopeImplTest { private val uwbClient = TestUwbClient( COMPLEX_CHANNEL, LOCAL_ADDRESS, RANGING_CAPABILITIES, isAvailable = true, isController = false ) private val uwbClientSession = UwbClientSessionScopeImpl( uwbClient, androidx.core.uwb.RangingCapabilities( RANGING_CAPABILITIES.supportsDistance(), RANGING_CAPABILITIES.supportsAzimuthalAngle(), RANGING_CAPABILITIES.supportsElevationAngle() ), androidx.core.uwb.UwbAddress(LOCAL_ADDRESS.address) ) @Test public fun testInitSession_singleConsumer() { val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) var rangingResult: RangingResult? = null val job = sessionFlow .cancellable() .onEach { rangingResult = it } .launchIn(CoroutineScope(Dispatchers.Main.immediate)) runBlocking { // wait for the coroutines for UWB to get launched. delay(500) } // a non-null RangingResult should return from the TestUwbClient. if (rangingResult != null) { assertThat(rangingResult is RangingResultPosition).isTrue() } else { job.cancel() Assert.fail() } // cancel and wait for the job to terminate. job.cancel() runBlocking { job.join() } // StopRanging should have been called after the coroutine scope completed. assertThat(uwbClient.stopRangingCalled).isTrue() } @Test public fun testInitSession_multipleSharedConsumers() { var passed1 = false var passed2 = false val sharedFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) .shareIn(CoroutineScope(Dispatchers.Main.immediate), SharingStarted.WhileSubscribed(), replay = 1) val job = CoroutineScope(Dispatchers.Main.immediate).launch { sharedFlow .onEach { if (it is RangingResultPosition) { passed1 = true } } .collect() } val job2 = CoroutineScope(Dispatchers.Main.immediate).launch { sharedFlow .onEach { if (it is RangingResultPosition) { passed2 = true } } .collect() } runBlocking { // wait for coroutines for flow to start. delay(500) } // a non-null RangingResult should return from the TestUwbClient. assertThat(passed1).isTrue() assertThat(passed2).isTrue() // cancel and wait for the first job to terminate. job.cancel() runBlocking { job.join() } // StopRanging should not have been called because not all consumers have finished. assertThat(uwbClient.stopRangingCalled).isFalse() // cancel and wait for the second job to terminate. job2.cancel() runBlocking { job2.join() } // StopRanging should have been called because all consumers have finished. assertThat(uwbClient.stopRangingCalled).isTrue() } @Test public fun testInitSession_singleConsumer_disconnectPeerDevice() { val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) var peerDisconnected = false val job = CoroutineScope(Dispatchers.Main.immediate).launch { sessionFlow .cancellable() .onEach { if (it is RangingResultPeerDisconnected) { peerDisconnected = true } } .collect() } runBlocking { // wait for coroutines for flow to start. delay(500) uwbClient.disconnectPeer(com.google.android.gms.nearby.uwb.UwbDevice.createForAddress( UWB_DEVICE.address.address)) // wait for rangingResults to get filled. delay(500) } // a peer disconnected event should have occurred. assertThat(peerDisconnected).isTrue() // cancel and wait for the job to terminate. job.cancel() runBlocking { job.join() } // StopRanging should have been called after the coroutine scope completed. assertThat(uwbClient.stopRangingCalled).isTrue() } @Test public fun testInitSession_multipleSharedConsumers_disconnectPeerDevice() { val sharedFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) .shareIn(CoroutineScope(Dispatchers.Main.immediate), SharingStarted.WhileSubscribed()) var peerDisconnected = false var peerDisconnected2 = false val job = CoroutineScope(Dispatchers.Main.immediate).launch { sharedFlow .onEach { if (it is RangingResultPeerDisconnected) { peerDisconnected = true } } .collect() } val job2 = CoroutineScope(Dispatchers.Main.immediate).launch { sharedFlow .onEach { if (it is RangingResultPeerDisconnected) { peerDisconnected2 = true } } .collect() } runBlocking { // wait for coroutines for flow to start. delay(500) uwbClient.disconnectPeer(com.google.android.gms.nearby.uwb.UwbDevice.createForAddress( UWB_DEVICE.address.address)) // wait for rangingResults to get filled. delay(500) } // a peer disconnected event should have occurred. assertThat(peerDisconnected).isTrue() assertThat(peerDisconnected2).isTrue() // cancel and wait for the job to terminate. job.cancel() runBlocking { job.join() } // StopRanging should not have been called because not all consumers have finished. assertThat(uwbClient.stopRangingCalled).isFalse() // cancel and wait for the job to terminate. job2.cancel() runBlocking { job2.join() } // StopRanging should have been called because all consumers have finished. assertThat(uwbClient.stopRangingCalled).isTrue() } @Test public fun testInitSession_multipleSessions_throwsUwbApiException() { val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) val sessionFlow2 = uwbClientSession.prepareSession(RANGING_PARAMETERS) val job = CoroutineScope(Dispatchers.Main.immediate).launch { sessionFlow.collect() } runBlocking { // wait for coroutines for flow to start. delay(500) } val job2 = CoroutineScope(Dispatchers.Main.immediate).launch { try { sessionFlow2.collect() Assert.fail() } catch (e: IllegalStateException) { // verified the exception was thrown. } } job.cancel() job2.cancel() } @Test public fun testInitSession_reusingSession_throwsUwbApiException() { val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS) val job = CoroutineScope(Dispatchers.Main.immediate).launch { sessionFlow.collect() } runBlocking { // wait for coroutines for flow to start. delay(500) } // cancel and wait for the job to terminate. job.cancel() runBlocking { job.join() } // StopRanging should not have been called because not all consumers have finished. assertThat(uwbClient.stopRangingCalled).isTrue() val job2 = CoroutineScope(Dispatchers.Main.immediate).launch { try { // Reuse the same session after it was closed. sessionFlow.collect() Assert.fail() } catch (e: IllegalStateException) { // verified the exception was thrown. } } job2.cancel() } }
apache-2.0
29f39fb6a8c7ef4434742199dd868870
34.425087
98
0.618631
5.085543
false
true
false
false
androidx/androidx
room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_internalVisibility.kt
3
3373
import android.database.Cursor import androidx.room.EntityInsertionAdapter import androidx.room.RoomDatabase import androidx.room.RoomSQLiteQuery import androidx.room.RoomSQLiteQuery.Companion.acquire import androidx.room.util.getColumnIndexOrThrow import androidx.room.util.query import androidx.sqlite.db.SupportSQLiteStatement import java.lang.Class import javax.`annotation`.processing.Generated import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Suppress import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmStatic @Generated(value = ["androidx.room.RoomProcessor"]) @Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"]) public class MyDao_Impl( __db: RoomDatabase, ) : MyDao { private val __db: RoomDatabase private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity> init { this.__db = __db this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) { public override fun createQuery(): String = "INSERT OR ABORT INTO `MyEntity` (`pk`,`internalVal`,`internalVar`,`internalSetterVar`) VALUES (?,?,?,?)" public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit { statement.bindLong(1, entity.pk.toLong()) statement.bindLong(2, entity.internalVal) statement.bindLong(3, entity.internalVar) statement.bindLong(4, entity.internalSetterVar) } } } public override fun addEntity(item: MyEntity): Unit { __db.assertNotSuspendingTransaction() __db.beginTransaction() try { __insertionAdapterOfMyEntity.insert(item) __db.setTransactionSuccessful() } finally { __db.endTransaction() } } public override fun getEntity(): MyEntity { val _sql: String = "SELECT * FROM MyEntity" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, false, null) try { val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk") val _cursorIndexOfInternalVal: Int = getColumnIndexOrThrow(_cursor, "internalVal") val _cursorIndexOfInternalVar: Int = getColumnIndexOrThrow(_cursor, "internalVar") val _cursorIndexOfInternalSetterVar: Int = getColumnIndexOrThrow(_cursor, "internalSetterVar") val _result: MyEntity if (_cursor.moveToFirst()) { val _tmpPk: Int _tmpPk = _cursor.getInt(_cursorIndexOfPk) val _tmpInternalVal: Long _tmpInternalVal = _cursor.getLong(_cursorIndexOfInternalVal) _result = MyEntity(_tmpPk,_tmpInternalVal) _result.internalVar = _cursor.getLong(_cursorIndexOfInternalVar) _result.internalSetterVar = _cursor.getLong(_cursorIndexOfInternalSetterVar) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } public companion object { @JvmStatic public fun getRequiredConverters(): List<Class<*>> = emptyList() } }
apache-2.0
802b8d2863eea71fc7d8371ae5184c36
38.232558
121
0.648681
4.818571
false
false
false
false
androidx/androidx
resourceinspection/resourceinspection-processor/src/main/kotlin/androidx/resourceinspection/processor/LayoutInspectionStep.kt
3
20929
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.resourceinspection.processor import com.google.auto.common.AnnotationMirrors.getAnnotationValue import com.google.auto.common.BasicAnnotationProcessor import com.google.auto.common.GeneratedAnnotationSpecs.generatedAnnotationSpec import com.google.auto.common.MoreElements.asExecutable import com.google.auto.common.MoreElements.asType import com.google.auto.common.MoreElements.getPackage import com.google.auto.common.Visibility import com.google.auto.common.Visibility.effectiveVisibilityOfElement import com.google.common.collect.ImmutableSetMultimap import com.squareup.javapoet.AnnotationSpec import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.Processor import javax.lang.model.element.AnnotationMirror import javax.lang.model.element.AnnotationValue import javax.lang.model.element.Element import javax.lang.model.element.ExecutableElement import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.tools.Diagnostic /** Processing step for generating layout inspection companions from `Attribute` annotations. */ internal class LayoutInspectionStep( private val processingEnv: ProcessingEnvironment, processorClass: Class<out Processor> ) : BasicAnnotationProcessor.Step { private val generatedAnnotation: AnnotationSpec? = generatedAnnotationSpec( processingEnv.elementUtils, processingEnv.sourceVersion, processorClass ).orElse(null) override fun annotations(): Set<String> { return setOf(ATTRIBUTE, APP_COMPAT_SHADOWED_ATTRIBUTES) } override fun process( elementsByAnnotation: ImmutableSetMultimap<String, Element> ): Set<Element> { if (!isViewInspectorApiPresent()) { printError( "View inspector (android.view.inspector) API is not present. " + "Please ensure compile SDK is 29 or greater." ) return emptySet() } val views = mergeViews( elementsByAnnotation[ATTRIBUTE] .groupBy({ asType(it.enclosingElement) }, { asExecutable(it) }), elementsByAnnotation[APP_COMPAT_SHADOWED_ATTRIBUTES] .mapTo(mutableSetOf()) { asType(it) } ) val filer = processingEnv.filer views.forEach { generateInspectionCompanion(it, generatedAnnotation).writeTo(filer) } // We don't defer elements for later rounds in this processor return emptySet() } /** Checks if the view inspector API is present in the compile class path */ private fun isViewInspectorApiPresent(): Boolean { return VIEW_INSPECTOR_CLASSES.all { className -> processingEnv.elementUtils.getTypeElement(className) != null } } /** Merge shadowed and regular attributes into [View] models. */ private fun mergeViews( viewsWithGetters: Map<TypeElement, List<ExecutableElement>>, viewsWithShadowedAttributes: Set<TypeElement> ): List<View> { return (viewsWithGetters.keys + viewsWithShadowedAttributes).mapNotNull { viewType -> val getterAttributes = viewsWithGetters[viewType].orEmpty().map(::parseGetter) if (viewType in viewsWithShadowedAttributes) { inferShadowedAttributes(viewType)?.let { shadowedAttributes -> createView(viewType, getterAttributes + shadowedAttributes) } } else { createView(viewType, getterAttributes) } } } /** Parse the annotated getters of a view class into a [View]. */ private fun createView(type: TypeElement, attributes: Collection<Attribute?>): View? { val duplicateAttributes = attributes .filterNotNull() .groupBy { it.qualifiedName } .values .filter { it.size > 1 } if (duplicateAttributes.any()) { duplicateAttributes.forEach { duplicates -> duplicates.forEach { attribute -> val qualifiedName = attribute.qualifiedName val otherGetters = duplicates .filter { it.invocation != attribute.invocation } .joinToString { it.invocation } printError( "Duplicate attribute $qualifiedName is also present on $otherGetters", (attribute as? GetterAttribute)?.getter, (attribute as? GetterAttribute)?.annotation ) } } return null } if (attributes.isEmpty() || attributes.any { it == null }) { return null } return View(type, attributes = attributes.filterNotNull().sortedBy { it.qualifiedName }) } /** Get an [Attribute] from a method known to have an `Attribute` annotation. */ private fun parseGetter(getter: ExecutableElement): Attribute? { val annotation = getter.getAnnotationMirror(ATTRIBUTE)!! val annotationValue = getAnnotationValue(annotation, "value") val value = annotationValue.value as String var hasError = false if (getter.parameters.isNotEmpty() || getter.returnType.kind == TypeKind.VOID) { printError("@Attribute must annotate a getter", getter, annotation) hasError = true } if (effectiveVisibilityOfElement(getter) != Visibility.PUBLIC) { printError("@Attribute getter must be public", getter, annotation) hasError = true } if (!getter.enclosingElement.asType().isAssignableTo(VIEW)) { printError("@Attribute must be on a subclass of android.view.View", getter, annotation) hasError = true } val intMapping = parseIntMapping(annotation) if (!validateIntMapping(getter, intMapping)) { hasError = true } val match = ATTRIBUTE_VALUE.matchEntire(value) if (match == null) { if (!value.contains(':')) { printError("@Attribute must include namespace", getter, annotation, annotationValue) } else { printError("Invalid attribute name", getter, annotation, annotationValue) } return null // Returning here since there's no more checks we can do } if (hasError) { return null } val (namespace, name) = match.destructured val type = inferAttributeType(getter, intMapping) if (!isAttributeInRFile(namespace, name)) { printError("Attribute $namespace:$name not found", getter, annotation) return null } return GetterAttribute(getter, annotation, namespace, name, type, intMapping) } /** Parse `Attribute.intMapping`. */ private fun parseIntMapping(annotation: AnnotationMirror): List<IntMap> { return (getAnnotationValue(annotation, "intMapping").value as List<*>).map { entry -> val intMapAnnotation = (entry as AnnotationValue).value as AnnotationMirror IntMap( name = getAnnotationValue(intMapAnnotation, "name").value as String, value = getAnnotationValue(intMapAnnotation, "value").value as Int, mask = getAnnotationValue(intMapAnnotation, "mask").value as Int, annotation = intMapAnnotation ) }.sortedBy { it.value } } /** Check that int mapping is valid and consistent */ private fun validateIntMapping(element: Element, intMapping: List<IntMap>): Boolean { if (intMapping.isEmpty()) { return true // Return early for the common case of no int mapping } var result = true val isEnum = intMapping.all { it.mask == 0 } // Check for duplicate names for both flags and enums val duplicateNames = intMapping.groupBy { it.name }.values.filter { it.size > 1 } duplicateNames.flatten().forEach { intMap -> printError( "Duplicate int ${if (isEnum) "enum" else "flag"} entry name: \"${intMap.name}\"", element, intMap.annotation, intMap.annotation?.let { getAnnotationValue(it, "name") } ) } if (duplicateNames.isNotEmpty()) { result = false } if (isEnum) { // Check for duplicate enum values val duplicateValues = intMapping.groupBy { it.value }.values.filter { it.size > 1 } duplicateValues.forEach { group -> group.forEach { intMap -> val others = (group - intMap).joinToString { "\"${it.name}\"" } printError( "Int enum value ${intMap.value} is duplicated on entries $others", element, intMap.annotation, intMap.annotation?.let { getAnnotationValue(it, "value") } ) } } if (duplicateValues.isNotEmpty()) { result = false } } else { // Check for invalid flags, with masks that obscure part of the value. Note that a mask // of 0 is a special case which implies that the mask is equal to the value as in enums. intMapping.forEach { intMap -> if (intMap.mask and intMap.value != intMap.value && intMap.mask != 0) { printError( "Int flag mask 0x${intMap.mask.toString(16)} does not reveal value " + "0x${intMap.value.toString(16)}", element, intMap.annotation ) result = false } } // Check for duplicate flags val duplicatePairs = intMapping .groupBy { Pair(if (it.mask != 0) it.mask else it.value, it.value) } .values .filter { it.size > 1 } duplicatePairs.forEach { group -> group.forEach { intMap -> val others = (group - intMap).joinToString { "\"${it.name}\"" } val mask = if (intMap.mask != 0) intMap.mask else intMap.value printError( "Int flag mask 0x${mask.toString(16)} and value " + "0x${intMap.value.toString(16)} is duplicated on entries $others", element, intMap.annotation ) } } if (duplicatePairs.isNotEmpty()) { result = false } } return result } /** Map the getter's annotations and return type to the internal attribute type. */ private fun inferAttributeType( getter: ExecutableElement, intMapping: List<IntMap> ): AttributeType { return when (getter.returnType.kind) { TypeKind.BOOLEAN -> AttributeType.BOOLEAN TypeKind.BYTE -> AttributeType.BYTE TypeKind.CHAR -> AttributeType.CHAR TypeKind.DOUBLE -> AttributeType.DOUBLE TypeKind.FLOAT -> AttributeType.FLOAT TypeKind.SHORT -> AttributeType.SHORT TypeKind.INT -> when { getter.isAnnotationPresent(COLOR_INT) -> AttributeType.COLOR getter.isAnnotationPresent(GRAVITY_INT) -> AttributeType.GRAVITY getter.hasResourceIdAnnotation() -> AttributeType.RESOURCE_ID intMapping.any { it.mask != 0 } -> AttributeType.INT_FLAG intMapping.isNotEmpty() -> AttributeType.INT_ENUM else -> AttributeType.INT } TypeKind.LONG -> if (getter.isAnnotationPresent(COLOR_LONG)) { AttributeType.COLOR } else { AttributeType.LONG } TypeKind.DECLARED, TypeKind.ARRAY -> if (getter.returnType.isAssignableTo(COLOR)) { AttributeType.COLOR } else { AttributeType.OBJECT } else -> throw IllegalArgumentException("Unexpected attribute type") } } /** Determines shadowed attributes based on interfaces present on the view. */ private fun inferShadowedAttributes(viewType: TypeElement): List<ShadowedAttribute>? { if (!viewType.asType().isAssignableTo(VIEW)) { printError( "@AppCompatShadowedAttributes must be on a subclass of android.view.View", viewType, viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES) ) return null } if (!getPackage(viewType).qualifiedName.startsWith("androidx.appcompat.")) { printError( "@AppCompatShadowedAttributes is only supported in the androidx.appcompat package", viewType, viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES) ) return null } val attributes = viewType.interfaces.flatMap { APP_COMPAT_INTERFACE_MAP[it.toString()].orEmpty() } if (attributes.isEmpty()) { printError( "@AppCompatShadowedAttributes is present on this view, but it does not implement " + "any interfaces that indicate it has shadowed attributes.", viewType, viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES) ) return null } return attributes } /** Check if an R.java file exists for [namespace] and that it contains attribute [name] */ private fun isAttributeInRFile(namespace: String, name: String): Boolean { return processingEnv.elementUtils.getTypeElement("$namespace.R") ?.enclosedElements?.find { it.simpleName.contentEquals("attr") } ?.enclosedElements?.find { it.simpleName.contentEquals(name) } != null } private fun Element.hasResourceIdAnnotation(): Boolean { return this.annotationMirrors.any { asType(it.annotationType.asElement()).qualifiedName matches RESOURCE_ID_ANNOTATION } } private fun TypeMirror.isAssignableTo(typeName: String): Boolean { val assignableType = requireNotNull(processingEnv.elementUtils.getTypeElement(typeName)) { "Expected $typeName to exist" } return processingEnv.typeUtils.isAssignable(this, assignableType.asType()) } /** Convenience wrapper for [javax.annotation.processing.Messager.printMessage]. */ private fun printError( message: String, element: Element? = null, annotation: AnnotationMirror? = null, value: AnnotationValue? = null ) { processingEnv.messager.printMessage( Diagnostic.Kind.ERROR, message, element, annotation, value ) } /** Find an annotation mirror by its qualified name */ private fun Element.getAnnotationMirror(qualifiedName: String): AnnotationMirror? { return this.annotationMirrors.firstOrNull { annotation -> asType(annotation.annotationType.asElement()) .qualifiedName.contentEquals(qualifiedName) } } /** True if the supplied annotation name is present on the element */ private fun Element.isAnnotationPresent(qualifiedName: String): Boolean { return getAnnotationMirror(qualifiedName) != null } private companion object { /** Regex for validating and parsing attribute name and namespace. */ val ATTRIBUTE_VALUE = """(\w+(?:\.\w+)*):(\w+)""".toRegex() /** Regex for matching resource ID annotations. */ val RESOURCE_ID_ANNOTATION = """androidx?\.annotation\.[A-Z]\w+Res""".toRegex() /** Fully qualified name of the `Attribute` annotation */ const val ATTRIBUTE = "androidx.resourceinspection.annotation.Attribute" /** Fully qualified name of the `AppCompatShadowedAttributes` annotation */ const val APP_COMPAT_SHADOWED_ATTRIBUTES = "androidx.resourceinspection.annotation.AppCompatShadowedAttributes" /** Fully qualified name of the platform's `Color` class */ const val COLOR = "android.graphics.Color" /** Fully qualified name of `ColorInt` */ const val COLOR_INT = "androidx.annotation.ColorInt" /** Fully qualified name of `ColorLong` */ const val COLOR_LONG = "androidx.annotation.ColorLong" /** Fully qualified name of `GravityInt` */ const val GRAVITY_INT = "androidx.annotation.GravityInt" /** Fully qualified name of the platform's View class */ const val VIEW = "android.view.View" /** Fully qualified names of the view inspector classes introduced in API 29 */ val VIEW_INSPECTOR_CLASSES = listOf( "android.view.inspector.InspectionCompanion", "android.view.inspector.PropertyReader", "android.view.inspector.PropertyMapper" ) /** * Map of compat interface names in `androidx.core` to the AppCompat attributes they * shadow. These virtual attributes are added to the inspection companion for views within * AppCompat with the `@AppCompatShadowedAttributes` annotation. * * As you can tell, this is brittle. The good news is these are established platform APIs * from API <= 29 (the minimum for app inspection) and are unlikely to change in the * future. If you update this list, please update the documentation comment in * [androidx.resourceinspection.annotation.AppCompatShadowedAttributes] as well. */ val APP_COMPAT_INTERFACE_MAP: Map<String, List<ShadowedAttribute>> = mapOf( "androidx.core.view.TintableBackgroundView" to listOf( ShadowedAttribute("backgroundTint", "getBackgroundTintList()"), ShadowedAttribute("backgroundTintMode", "getBackgroundTintMode()") ), "androidx.core.widget.AutoSizeableTextView" to listOf( ShadowedAttribute( "autoSizeTextType", "getAutoSizeTextType()", AttributeType.INT_ENUM, listOf( IntMap("none", 0 /* TextView.AUTO_SIZE_TEXT_TYPE_NONE */), IntMap("uniform", 1 /* TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM */), ) ), ShadowedAttribute( "autoSizeStepGranularity", "getAutoSizeStepGranularity()", AttributeType.INT ), ShadowedAttribute( "autoSizeMinTextSize", "getAutoSizeMinTextSize()", AttributeType.INT ), ShadowedAttribute( "autoSizeMaxTextSize", "getAutoSizeMaxTextSize()", AttributeType.INT ) ), "androidx.core.widget.TintableCheckedTextView" to listOf( ShadowedAttribute("checkMarkTint", "getCheckMarkTintList()"), ShadowedAttribute("checkMarkTintMode", "getCheckMarkTintMode()") ), "androidx.core.widget.TintableCompoundButton" to listOf( ShadowedAttribute("buttonTint", "getButtonTintList()"), ShadowedAttribute("buttonTintMode", "getButtonTintMode()") ), "androidx.core.widget.TintableCompoundDrawablesView" to listOf( ShadowedAttribute("drawableTint", "getCompoundDrawableTintList()"), ShadowedAttribute("drawableTintMode", "getCompoundDrawableTintMode()") ), "androidx.core.widget.TintableImageSourceView" to listOf( ShadowedAttribute("tint", "getImageTintList()"), ShadowedAttribute("tintMode", "getImageTintMode()"), ) ) } }
apache-2.0
da194cfe3aa500145355add6930347d9
41.026104
100
0.605571
5.29446
false
false
false
false
alt236/Bluetooth-LE-Library---Android
sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/IBeaconHolder.kt
1
854
package uk.co.alt236.btlescan.ui.details.recyclerview.holder import android.view.View import android.widget.TextView import uk.co.alt236.btlescan.R import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder import uk.co.alt236.btlescan.ui.details.recyclerview.model.IBeaconItem class IBeaconHolder(itemView: View) : BaseViewHolder<IBeaconItem>(itemView) { val companyId: TextView = itemView.findViewById<View>(R.id.companyId) as TextView val advert: TextView = itemView.findViewById<View>(R.id.advertisement) as TextView val uuid: TextView = itemView.findViewById<View>(R.id.uuid) as TextView val major: TextView = itemView.findViewById<View>(R.id.major) as TextView val minor: TextView = itemView.findViewById<View>(R.id.minor) as TextView val txPower: TextView = itemView.findViewById<View>(R.id.txpower) as TextView }
apache-2.0
037695a61c0f4dc722f4be3cfafab588
52.4375
86
0.789227
3.69697
false
false
false
false
siosio/intellij-community
platform/util/ui/src/com/intellij/ui/svg/SvgTranscoder.kt
1
12972
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:Suppress("UndesirableClassUsage") package com.intellij.ui.svg import com.intellij.openapi.diagnostic.Logger import com.intellij.util.ImageLoader import org.apache.batik.anim.dom.SVGOMDocument import org.apache.batik.bridge.* import org.apache.batik.bridge.svg12.SVG12BridgeContext import org.apache.batik.ext.awt.RenderingHintsKeyExt import org.apache.batik.gvt.CanvasGraphicsNode import org.apache.batik.gvt.CompositeGraphicsNode import org.apache.batik.gvt.GraphicsNode import org.apache.batik.transcoder.TranscoderException import org.apache.batik.util.ParsedURL import org.apache.batik.util.SVGConstants import org.apache.batik.util.SVGFeatureStrings import org.jetbrains.annotations.ApiStatus import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.svg.SVGAElement import org.w3c.dom.svg.SVGDocument import java.awt.* import java.awt.geom.AffineTransform import java.awt.image.BufferedImage import java.lang.ref.WeakReference import kotlin.math.max import kotlin.math.min private fun logger() = Logger.getInstance(SvgTranscoder::class.java) private val identityTransform = AffineTransform() private val supportedFeatures = HashSet<String>() @ApiStatus.Internal class SvgTranscoder private constructor(private var width: Float, private var height: Float) : UserAgent { companion object { // An SVG tag custom attribute, optional for @2x SVG icons. // When provided and is set to "true" the document size should be treated as double-scaled of the base size. // See https://youtrack.jetbrains.com/issue/IDEA-267073 const val DATA_SCALED_ATTR = "data-scaled" init { SVGFeatureStrings.addSupportedFeatureStrings(supportedFeatures) } @JvmStatic val iconMaxSize: Float by lazy { var maxSize = Integer.MAX_VALUE.toFloat() if (!GraphicsEnvironment.isHeadless()) { val device = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice val bounds = device.defaultConfiguration.bounds val tx = device.defaultConfiguration.defaultTransform maxSize = max(bounds.width * tx.scaleX, bounds.height * tx.scaleY).toInt().toFloat() } maxSize } @JvmStatic fun getDocumentSize(scale: Float, document: Document): ImageLoader.Dimension2DDouble { val transcoder = SvgTranscoder(16f, 16f) val bridgeContext = if ((document as SVGOMDocument).isSVG12) { SVG12BridgeContext(transcoder) } else { BridgeContext(transcoder) } GVTBuilder().build(bridgeContext, document) val size = bridgeContext.documentSize return ImageLoader.Dimension2DDouble(size.width * scale, size.height * scale) } @Throws(TranscoderException::class) @JvmStatic @JvmOverloads fun createImage(scale: Float, document: Document, outDimensions: ImageLoader.Dimension2DDouble? /*OUT*/, overriddenWidth: Float = -1f, overriddenHeight: Float = -1f): BufferedImage { val transcoder = SvgTranscoder(if (overriddenWidth == -1f) 16f else overriddenWidth, if (overriddenHeight == -1f) 16f else overriddenHeight) val iconMaxSize = iconMaxSize val bridgeContext = if ((document as SVGOMDocument).isSVG12) { SVG12BridgeContext(transcoder) } else { BridgeContext(transcoder) } try { // build the GVT tree - it will set bridgeContext.documentSize val gvtRoot = GVTBuilder().build(bridgeContext, document)!! // get the 'width' and 'height' attributes of the SVG document val docWidth = bridgeContext.documentSize.width.toFloat() val docHeight = bridgeContext.documentSize.height.toFloat() var normalizingScale = 1f if ((document.url?.contains("@2x") == true) and document.rootElement?.attributes?.getNamedItem(DATA_SCALED_ATTR)?.nodeValue?.toLowerCase().equals("true")) { normalizingScale = 2f } val imageScale = scale / normalizingScale transcoder.setImageSize(docWidth * imageScale, docHeight * imageScale, overriddenWidth, overriddenHeight, iconMaxSize) val transform = computeTransform(document, gvtRoot, bridgeContext, docWidth, docHeight, transcoder.width, transcoder.height) transcoder.currentTransform = transform val image = render((transcoder.width + 0.5f).toInt(), (transcoder.height + 0.5f).toInt(), transform, gvtRoot) // Take into account the image size rounding and correct the original user size in order to compensate the inaccuracy. val effectiveUserWidth = image.width / scale; val effectiveUserHeight = image.height / scale; // outDimensions should contain the base size outDimensions?.setSize(effectiveUserWidth.toDouble() / normalizingScale, effectiveUserHeight.toDouble() / normalizingScale) return image } catch (e: TranscoderException) { throw e } catch (e: Exception) { throw TranscoderException(e) } finally { bridgeContext.dispose() } } } private var currentTransform: AffineTransform? = null private fun setImageSize(docWidth: Float, docHeight: Float, overriddenWidth: Float, overriddenHeight: Float, iconMaxSize: Float) { if (overriddenWidth > 0 && overriddenHeight > 0) { width = overriddenWidth height = overriddenHeight } else if (overriddenHeight > 0) { width = docWidth * overriddenHeight / docHeight height = overriddenHeight } else if (overriddenWidth > 0) { width = overriddenWidth height = docHeight * overriddenWidth / docWidth } else { width = docWidth height = docHeight } // limit image size according to the maximum size hints if (iconMaxSize > 0 && height > iconMaxSize) { width = docWidth * iconMaxSize / docHeight height = iconMaxSize } if (iconMaxSize > 0 && width > iconMaxSize) { width = iconMaxSize height = docHeight * iconMaxSize / docWidth } } override fun getMedia() = "screen" override fun getBrokenLinkDocument(e: Element, url: String, message: String): SVGDocument { logger().warn("$url $message") val fallbackIcon = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\">\n" + " <rect x=\"1\" y=\"1\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"red\" stroke-width=\"2\"/>\n" + " <line x1=\"1\" y1=\"1\" x2=\"15\" y2=\"15\" stroke=\"red\" stroke-width=\"2\"/>\n" + " <line x1=\"1\" y1=\"15\" x2=\"15\" y2=\"1\" stroke=\"red\" stroke-width=\"2\"/>\n" + "</svg>\n" return createSvgDocument(null, fallbackIcon.byteInputStream()) as SVGDocument } override fun getTransform() = currentTransform!! override fun setTransform(value: AffineTransform) = throw IllegalStateException() override fun getViewportSize() = Dimension(width.toInt(), height.toInt()) override fun displayError(e: Exception) { logger().debug(e) } override fun displayMessage(message: String) { logger().debug(message) } override fun getScriptSecurity(scriptType: String?, scriptUrl: ParsedURL?, documentUrl: ParsedURL?) = NoLoadScriptSecurity(scriptType) override fun getExternalResourceSecurity(resourceUrl: ParsedURL, documentUrl: ParsedURL?): ExternalResourceSecurity { return ExternalResourceSecurity { checkLoadExternalResource(resourceUrl, documentUrl) } } override fun showAlert(message: String?) {} override fun showPrompt(message: String?) = null override fun showPrompt(message: String?, defaultValue: String?) = null override fun showConfirm(message: String?) = false override fun getPixelUnitToMillimeter(): Float = 0.26458333333333333333333333333333f // 96dpi override fun getPixelToMM() = pixelUnitToMillimeter override fun getDefaultFontFamily() = "Arial, Helvetica, sans-serif" // 9pt (72pt = 1in) override fun getMediumFontSize(): Float = 9f * 25.4f / (72f * pixelUnitToMillimeter) override fun getLighterFontWeight(f: Float) = getStandardLighterFontWeight(f) override fun getBolderFontWeight(f: Float) = getStandardBolderFontWeight(f) override fun getLanguages() = "en" override fun getAlternateStyleSheet() = null override fun getUserStyleSheetURI() = null override fun getXMLParserClassName() = null override fun isXMLParserValidating() = false override fun getEventDispatcher() = null override fun openLink(elt: SVGAElement?) {} override fun setSVGCursor(cursor: Cursor?) {} override fun setTextSelection(start: Mark?, end: Mark?) {} override fun deselectAll() {} override fun getClientAreaLocationOnScreen() = Point() override fun hasFeature(s: String?) = supportedFeatures.contains(s) override fun supportExtension(s: String?) = false override fun registerExtension(ext: BridgeExtension) { } override fun handleElement(elt: Element?, data: Any?) {} override fun checkLoadScript(scriptType: String?, scriptURL: ParsedURL, docURL: ParsedURL?) { throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED") } override fun checkLoadExternalResource(resourceUrl: ParsedURL, documentUrl: ParsedURL?) { // make sure that the archives comes from the same host as the document itself if (documentUrl == null) { throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED") } val docHost = documentUrl.host val externalResourceHost: String = resourceUrl.host if (docHost != externalResourceHost && (docHost == null || docHost != externalResourceHost) && "data" != resourceUrl.protocol) { throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED") } } override fun loadDocument(url: String?) { } override fun getFontFamilyResolver(): FontFamilyResolver = DefaultFontFamilyResolver.SINGLETON } private fun computeTransform(document: SVGOMDocument, gvtRoot: GraphicsNode, context: BridgeContext, docWidth: Float, docHeight: Float, width: Float, height: Float): AffineTransform { // compute the preserveAspectRatio matrix val preserveAspectRatioMatrix: AffineTransform val root = document.rootElement val viewBox = root.getAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE) if (viewBox != null && viewBox.isNotEmpty()) { val aspectRatio = root.getAttributeNS(null, SVGConstants.SVG_PRESERVE_ASPECT_RATIO_ATTRIBUTE) preserveAspectRatioMatrix = ViewBox.getPreserveAspectRatioTransform(root, viewBox, aspectRatio, width, height, context) } else { // no viewBox has been specified, create a scale transform val scale = min(width / docWidth, height / docHeight) preserveAspectRatioMatrix = AffineTransform.getScaleInstance(scale.toDouble(), scale.toDouble()) } val cgn = (gvtRoot as? CompositeGraphicsNode)?.children?.firstOrNull() as? CanvasGraphicsNode if (cgn == null) { return preserveAspectRatioMatrix } else { cgn.viewingTransform = preserveAspectRatioMatrix return AffineTransform() } } private fun render(offScreenWidth: Int, offScreenHeight: Int, usr2dev: AffineTransform, gvtRoot: GraphicsNode): BufferedImage { val image = BufferedImage(offScreenWidth, offScreenHeight, BufferedImage.TYPE_INT_ARGB) val g = image.createGraphics() g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR) g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE) g.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, WeakReference(image)) g.transform = identityTransform g.setClip(0, 0, offScreenWidth, offScreenHeight) g.composite = AlphaComposite.Clear g.fillRect(0, 0, offScreenWidth, offScreenHeight) g.composite = AlphaComposite.SrcOver g.transform(usr2dev) gvtRoot.paint(g) g.dispose() return image } private fun getStandardLighterFontWeight(f: Float): Float { // Round f to nearest 100... return when (((f + 50) / 100).toInt() * 100) { 100, 200 -> 100f 300 -> 200f 400 -> 300f 500, 600, 700, 800, 900 -> 400f else -> throw IllegalArgumentException("Bad Font Weight: $f") } } private fun getStandardBolderFontWeight(f: Float): Float { // Round f to nearest 100... return when (((f + 50) / 100).toInt() * 100) { 100, 200, 300, 400, 500 -> 600f 600 -> 700f 700 -> 800f 800 -> 900f 900 -> 900f else -> throw IllegalArgumentException("Bad Font Weight: $f") } }
apache-2.0
278a9bb4d7b36d48d9dd77977ad71ef7
36.932749
140
0.698504
4.247544
false
false
false
false
josecefe/Rueda
src/es/um/josecefe/rueda/resolutor/ResolutorV7.kt
1
10745
/* * Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.um.josecefe.rueda.resolutor import es.um.josecefe.rueda.modelo.AsignacionDia import es.um.josecefe.rueda.modelo.Dia import es.um.josecefe.rueda.modelo.Horario import java.util.* /** * ResolutorV7 * * * Se trata de un resolutor que aplica la tecnica de Ramificación y poda (B&B). * * @author josecefe */ class ResolutorV7 : ResolutorAcotado() { override var estrategia = Estrategia.EQUILIBRADO private val estGlobal = EstadisticasV7() override fun resolver(horarios: Set<Horario>): Map<Dia, AsignacionDia> { return resolver(horarios, Integer.MAX_VALUE - 1) } override fun resolver(horarios: Set<Horario>, cotaInfCorte: Int): Map<Dia, AsignacionDia> { if (horarios.isEmpty()) { return emptyMap() } if (ESTADISTICAS) { estGlobal.inicia() } var ultMilisEst: Long = 0 // La ultima vez que se hizo estadística continuar = true val contex = ContextoResolucionHeuristico(horarios) contex.estrategia = estrategia solucionFinal = emptyMap() val tamanosNivel = contex.ordenExploracionDias.map { i -> contex.solucionesCandidatas[contex.dias[i]]!!.size }.toIntArray() val totalPosiblesSoluciones = tamanosNivel.map { i -> i.toDouble() }.fold(1.0) { a, b -> a * b } val nPosiblesSoluciones = DoubleArray(tamanosNivel.size) if (ESTADISTICAS) { if (DEBUG) { println("Nº de posibles soluciones: " + tamanosNivel.joinToString(separator = " * ") { it.toDouble().toString() } + " = " + totalPosiblesSoluciones) } var acum = 1.0 for (i in tamanosNivel.indices.reversed()) { nPosiblesSoluciones[i] = acum acum *= tamanosNivel[i] } estGlobal.totalPosiblesSoluciones = totalPosiblesSoluciones estGlobal.actualizaProgreso() if (DEBUG) { System.out.format("Tiempo inicializar =%s\n", estGlobal.tiempoString) } } // Preparamos el algoritmo val raiz = Nodo(contex) var actual = raiz var mejor = actual var cotaInferiorCorte = if (cotaInfCorte < Integer.MAX_VALUE) cotaInfCorte + 1 else cotaInfCorte var lnv: MutableCollection<Nodo> var opPull: () -> Nodo contex.pesoCotaInferiorNum = PESO_COTA_INFERIOR_NUM_DEF_INI //Primero buscamos en profundidad contex.pesoCotaInferiorDen = PESO_COTA_INFERIOR_DEN_DEF_INI //Primero buscamos en profundidad if (CON_CAMBIO_DE_ESTRATEGIA) { val pilaNodosVivos = ArrayDeque<Nodo>() // Inicialmente es una cola LIFO (pila) lnv = pilaNodosVivos opPull = { pilaNodosVivos.removeLast() } //Para controlar si es pila o cola, inicialmente pila } else { val colaNodosVivos = PriorityQueue<Nodo>() lnv = colaNodosVivos opPull = { colaNodosVivos.poll() } } lnv.add(actual) // Bucle principal do { actual = opPull() if (ESTADISTICAS && estGlobal.incExpandidos() % CADA_EXPANDIDOS == 0L && System.currentTimeMillis() - ultMilisEst > CADA_MILIS_EST) { ultMilisEst = System.currentTimeMillis() estGlobal.fitness = cotaInferiorCorte estGlobal.actualizaProgreso() if (DEBUG) { System.out.format("> LNV=%,d, ", lnv.size) println(estGlobal) println("-- Trabajando con $actual") } } if (actual.cotaInferior < cotaInferiorCorte) { //Estrategia de poda: si la cotaInferior >= C no seguimos if (ESTADISTICAS) { estGlobal.addGenerados(tamanosNivel[actual.nivel + 1].toDouble()) } if (actual.nivel + 2 == contex.dias.size) { // Los hijos son terminales if (ESTADISTICAS) { estGlobal.addTerminales(tamanosNivel[actual.nivel + 1].toDouble()) } val mejorHijo = actual.generaHijos().min() if (mejorHijo!=null && mejorHijo < mejor) { if (mejor === raiz) { // Cambiamos los pesos contex.pesoCotaInferiorNum = PESO_COTA_INFERIOR_NUM_DEF_FIN //Después buscamos más equilibrado contex.pesoCotaInferiorDen = PESO_COTA_INFERIOR_DEN_DEF_FIN //Después buscamos más equilibrado lnv.forEach{ it.calculaCosteEstimado() }// Hay que forzar el calculo de nuevo de los costes de los nodos val colaNodosVivos: PriorityQueue<Nodo> = PriorityQueue(lnv.size) colaNodosVivos.addAll(lnv) if (DEBUG) { println("---- ACTUALIZANDO LA LNV POR CAMBIO DE PESOS") } opPull = { colaNodosVivos.poll() } lnv = colaNodosVivos } mejor = mejorHijo if (DEBUG) { System.out.format("$$$$ A partir del padre=%s\n -> mejoramos con el hijo=%s\n", actual, mejor) } if (mejor.costeEstimado < cotaInferiorCorte) { if (DEBUG) { System.out.format("** Nuevo C: Anterior=%,d, Nuevo=%,d\n", cotaInferiorCorte, mejor.costeEstimado) } cotaInferiorCorte = mejor.costeEstimado val fC = cotaInferiorCorte // Limpiamos la lista de nodos vivos de los que no cumplan... val antes = lnv.size if (ESTADISTICAS) { estGlobal.addDescartados(lnv.filter { n -> n.cotaInferior >= fC }.map { n -> nPosiblesSoluciones[n.nivel] }.sum()) estGlobal.fitness = cotaInferiorCorte estGlobal.actualizaProgreso() } val removeIf = lnv.removeAll { n -> n.cotaInferior >= fC } if (ESTADISTICAS && DEBUG && removeIf) { System.out.format("** Hemos eliminado %,d nodos de la LNV\n", antes - lnv.size) } } } } else { // Es un nodo intermedio val corte = cotaInferiorCorte val lNF = actual.generaHijos().filter { n -> n.cotaInferior < corte }.toMutableList() val menorCotaSuperior = lNF.map{ it.cotaSuperior }.min() if (menorCotaSuperior!=null && menorCotaSuperior < cotaInferiorCorte) { // Mejora de C if (DEBUG) { System.out.format("** Nuevo C: Anterior=%,d, Nuevo=%,d\n", cotaInferiorCorte, menorCotaSuperior) } cotaInferiorCorte = menorCotaSuperior //Actualizamos C val fC = cotaInferiorCorte lNF.removeAll { n -> n.cotaInferior >= fC } //Recalculamos lNF // Limpiamos la LNV val antes = lnv.size if (ESTADISTICAS) { estGlobal.addDescartados(lnv.filter { n -> n.cotaInferior >= fC }.map { n -> nPosiblesSoluciones[n.nivel] }.sum()) estGlobal.fitness = cotaInferiorCorte estGlobal.actualizaProgreso() } val removeIf = lnv.removeAll { n -> n.cotaInferior >= fC } if (ESTADISTICAS && DEBUG && removeIf) { System.out.format("## Hemos eliminado %,d nodos de la LNV\n", antes - lnv.size) } } if (ESTADISTICAS) { estGlobal.addDescartados((tamanosNivel[actual.nivel + 1] - lNF.size) * nPosiblesSoluciones[actual.nivel + 1]) } lnv.addAll(lNF) } } else if (ESTADISTICAS) { estGlobal.addDescartados(nPosiblesSoluciones[actual.nivel]) } } while (!lnv.isEmpty() && continuar) //Estadisticas finales if (ESTADISTICAS) { estGlobal.fitness = cotaInferiorCorte estGlobal.actualizaProgreso() if (DEBUG) { println("====================") println("Estadísticas finales") println("====================") println(estGlobal) println("Solución final=$mejor") println("-----------------------------------------------") } } // Construimos la solución final solucionFinal = if (mejor.costeEstimado < cotaInfCorte) { mejor.solucion } else { emptyMap() } return solucionFinal } override var solucionFinal: Map<Dia, AsignacionDia> = emptyMap() private set override val estadisticas: Estadisticas get() = estGlobal companion object { private const val DEBUG = false //private const val PARALELO = false private const val ESTADISTICAS = true private const val CADA_EXPANDIDOS = 1000 private const val CADA_MILIS_EST = 1000 private const val CON_CAMBIO_DE_ESTRATEGIA = false private const val PESO_COTA_INFERIOR_NUM_DEF_INI = 1 private const val PESO_COTA_INFERIOR_DEN_DEF_INI = 8 private const val PESO_COTA_INFERIOR_NUM_DEF_FIN = 1 private const val PESO_COTA_INFERIOR_DEN_DEF_FIN = 2 } }
gpl-3.0
b1c9417508c35aa0d896f7873b8180fe
46.290749
242
0.535911
3.971513
false
false
false
false
PaleoCrafter/VanillaImmersion
src/main/kotlin/de/mineformers/vanillaimmersion/client/renderer/AnvilRenderer.kt
1
5355
package de.mineformers.vanillaimmersion.client.renderer import de.mineformers.vanillaimmersion.block.Anvil import de.mineformers.vanillaimmersion.client.gui.AnvilTextGui import de.mineformers.vanillaimmersion.tileentity.AnvilLogic import de.mineformers.vanillaimmersion.tileentity.AnvilLogic.Companion.Slot import net.minecraft.client.Minecraft import net.minecraft.client.renderer.GlStateManager.color import net.minecraft.client.renderer.GlStateManager.disableRescaleNormal import net.minecraft.client.renderer.GlStateManager.enableRescaleNormal import net.minecraft.client.renderer.GlStateManager.popMatrix import net.minecraft.client.renderer.GlStateManager.pushMatrix import net.minecraft.client.renderer.GlStateManager.rotate import net.minecraft.client.renderer.GlStateManager.scale import net.minecraft.client.renderer.GlStateManager.translate import net.minecraft.client.renderer.OpenGlHelper import net.minecraft.client.renderer.RenderHelper import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType.FIXED import net.minecraft.client.renderer.texture.TextureMap import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.client.resources.I18n import net.minecraft.item.ItemBlock import org.apache.commons.lang3.StringUtils /** * Renders the items on top of an anvil. */ open class AnvilRenderer : TileEntitySpecialRenderer<AnvilLogic>() { // TODO: Maybe switch to FastTESR? override fun render(te: AnvilLogic, x: Double, y: Double, z: Double, partialTicks: Float, destroyStage: Int, partialAlpha: Float) { if (te.blockState.block !is Anvil) return pushMatrix() color(1f, 1f, 1f, 1f) // Use the brightness of the block above the anvil for lighting val light = te.world.getCombinedLight(te.pos.add(0, 1, 0), 0) val bX = light % 65536 val bY = light / 65536 OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, bX.toFloat(), bY.toFloat()) // Translate to the anvil's center and rotate according to its orientation translate(x + 0.5, y + 1.0, z + 0.5) rotate(180f - te.facing.horizontalAngle, 0f, 1f, 0f) enableRescaleNormal() RenderHelper.enableStandardItemLighting() Minecraft.getMinecraft().textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE) // Render both inputs // TODO: Achieve this with baked models renderItem(te, Slot.INPUT_OBJECT, .0, .33) renderItem(te, Slot.INPUT_MATERIAL, .0, -.03) // Render the hammer, if present val hammer = te[Slot.HAMMER] if (!hammer.isEmpty) { pushMatrix() // Magic numbers, but this appears to be the perfect offset translate(.0, .05, -.32) rotate(-90f, 0f, 1f, 0f) rotate(85f, 1f, 0f, 0f) rotate(6f, 0f, 0f, 1f) scale(0.5f, 0.5f, 0.5f) Minecraft.getMinecraft().renderItem.renderItem(hammer, FIXED) popMatrix() } RenderHelper.disableStandardItemLighting() disableRescaleNormal() // Render the text on the front of the anvil translate(0f, -0.05f, 0f) rotate(90f, 0f, 1f, 0f) translate(0f, 0f, 0.32f) scale(0.00625f, -0.00625f, 0.00625f) val font = Minecraft.getMinecraft().fontRenderer val activeScreen = Minecraft.getMinecraft().currentScreen if (StringUtils.isNotEmpty(te.itemName)) { val label = I18n.format("vimmersion.anvil.itemName") font.drawString(label, -font.getStringWidth(label) / 2, 25 - font.FONT_HEIGHT - 2, 0xFFFFFF) if (activeScreen is AnvilTextGui && activeScreen.anvil == te) { activeScreen.nameField.x = -font.getStringWidth(te.itemName) / 2 activeScreen.nameField.y = 25 activeScreen.nameField.drawTextBox() } else { font.drawString(te.itemName, -font.getStringWidth(te.itemName) / 2, 25, 0xFFFFFF) } } else if (activeScreen is AnvilTextGui && activeScreen.anvil == te) { val label = I18n.format("vimmersion.anvil.itemName") font.drawString(label, -font.getStringWidth(label) / 2, 25 - font.FONT_HEIGHT - 2, 0xFFFFFF) activeScreen.nameField.x = -font.getStringWidth(activeScreen.nameField.text) / 2 activeScreen.nameField.y = 25 activeScreen.nameField.drawTextBox() } popMatrix() } /** * Renders an item on top of the anvil. */ private fun renderItem(te: AnvilLogic, slot: Slot, x: Double, z: Double) { pushMatrix() // Magic numbers, but this appears to be the perfect offset translate(x, 0.015, z) rotate(-90f, 0f, 1f, 0f) val stack = te[slot] // Most blocks use a block model which requires special treatment if (stack.item is ItemBlock) { translate(0.0, 0.135, 0.0) scale(2f, 2f, 2f) } else { // Rotate items to lie down flat on the anvil rotate(90f, 1f, 0f, 0f) rotate(180f, 0f, 1f, 0f) } scale(0.3, 0.3, 0.3) Minecraft.getMinecraft().renderItem.renderItem(stack, FIXED) popMatrix() } }
mit
261a97cc31092415f39eee04c22d5a07
42.193548
104
0.664799
3.940397
false
false
false
false
zhiayang/pew
core/src/main/kotlin/Utilities/DelayComponent.kt
1
617
// Copyright (c) 2014 Orion Industries, [email protected] // Licensed under the Apache License version 2.0 package Utilities public data class DelayComponent(public val delay: Float) { private var running: Float = this.delay public var elapsed: Boolean = false private set get() { if (this.$elapsed) { this.$elapsed = false return true } else return false } public fun tick(delta: Float) { this.running += delta if (this.running >= this.delay) { this.running = 0.0f this.elapsed = true } } public fun reset() { this.running = 0f this.elapsed = false } }
apache-2.0
92d41ed1b8142445ee49ec9befc7e2ba
15.675676
58
0.658023
3.039409
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/NullCommitWorkflowHandler.kt
13
1045
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.openapi.Disposable import com.intellij.openapi.vcs.changes.CommitExecutor object NullCommitWorkflowHandler : CommitWorkflowHandler { override val amendCommitHandler: AmendCommitHandler = NullAmendCommitHandler override fun getExecutor(executorId: String): CommitExecutor? = null override fun isExecutorEnabled(executor: CommitExecutor): Boolean = false override fun execute(executor: CommitExecutor) = Unit } @Suppress("UNUSED_PARAMETER") object NullAmendCommitHandler : AmendCommitHandler { override var isAmendCommitMode: Boolean get() = false set(value) = Unit override var isAmendCommitModeTogglingEnabled: Boolean get() = false set(value) = Unit override fun isAmendCommitModeSupported(): Boolean = false override fun addAmendCommitModeListener(listener: AmendCommitModeListener, parent: Disposable) = Unit }
apache-2.0
919cd65e2a7369f4ce7ac6169122ad68
36.357143
140
0.795215
4.793578
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/project-model/src/org/jetbrains/kotlin/idea/projectModel/KotlinCompilation.kt
3
1999
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.projectModel interface KotlinCompilation : KotlinComponent { @Deprecated("Use allSourceSets or declaredSourceSets instead", ReplaceWith("declaredSourceSets")) val sourceSets: Collection<KotlinSourceSet> get() = declaredSourceSets /** * All source sets participated in this compilation, including those available * via dependsOn. */ val allSourceSets: Collection<KotlinSourceSet> /** * Only directly declared source sets of this compilation, i.e. those which are included * into compilations directly. * * Usually, those are automatically created source sets for automatically created * compilations (like jvmMain for JVM compilations) or manually included source sets * (like 'jvm().compilations["main"].source(mySourceSet)' ) */ val declaredSourceSets: Collection<KotlinSourceSet> val output: KotlinCompilationOutput @Suppress("DEPRECATION_ERROR") @Deprecated( "Raw compiler arguments are not available anymore", ReplaceWith("cachedArgsInfo#currentCompilerArguments or cachedArgsInfo#defaultCompilerArguments"), level = DeprecationLevel.ERROR ) val arguments: KotlinCompilationArguments @Deprecated( "Raw dependency classpath is not available anymore", ReplaceWith("cachedArgsInfo#dependencyClasspath"), level = DeprecationLevel.ERROR ) val dependencyClasspath: Array<String> val cachedArgsInfo: CachedArgsInfo<*> val disambiguationClassifier: String? val platform: KotlinPlatform val kotlinTaskProperties: KotlinTaskProperties val nativeExtensions: KotlinNativeCompilationExtensions? companion object { const val MAIN_COMPILATION_NAME = "main" const val TEST_COMPILATION_NAME = "test" } }
apache-2.0
7c69448b1a35446cb2671036163510e0
36.716981
158
0.729865
5.711429
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/codeInsight/daemon/impl/HintRenderer.kt
1
12349
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInsight.daemon.impl import com.intellij.codeInsight.hints.HintWidthAdjustment import com.intellij.ide.ui.AntialiasingType import com.intellij.ide.ui.UISettings import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorCustomElementRenderer import com.intellij.openapi.editor.Inlay import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.FocusModeModel import com.intellij.openapi.editor.impl.FontInfo import com.intellij.openapi.editor.markup.EffectType import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.util.Key import com.intellij.ui.paint.EffectPainter import com.intellij.util.ui.GraphicsUtil import com.intellij.util.ui.StartupUiUtil import org.intellij.lang.annotations.JdkConstants import java.awt.* import java.awt.font.FontRenderContext import javax.swing.UIManager import kotlin.math.ceil import kotlin.math.max import kotlin.math.roundToInt open class HintRenderer(var text: String?) : EditorCustomElementRenderer { var widthAdjustment: HintWidthAdjustment? = null override fun calcWidthInPixels(inlay: Inlay<*>): Int { return calcWidthInPixels(inlay.editor, text, widthAdjustment, useEditorFont()) } protected open fun getTextAttributes(editor: Editor): TextAttributes? { return editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT) } override fun paint(inlay: Inlay<*>, g: Graphics, r: Rectangle, textAttributes: TextAttributes) { val editor = inlay.editor if (editor !is EditorImpl) return val focusModeRange = editor.focusModeRange val attributes = if (focusModeRange != null && (inlay.offset <= focusModeRange.startOffset || focusModeRange.endOffset <= inlay.offset)) { editor.getUserData(FocusModeModel.FOCUS_MODE_ATTRIBUTES) ?: getTextAttributes(editor) } else { getTextAttributes(editor) } paintHint(g, editor, r, text, attributes, attributes ?: textAttributes, widthAdjustment, useEditorFont()) } /** * @deprecated * @see calcHintTextWidth */ protected fun doCalcWidth(text: String?, fontMetrics: FontMetrics): Int { return calcHintTextWidth(text, fontMetrics) } protected open fun useEditorFont() = useEditorFontFromSettings() companion object { @JvmStatic fun calcWidthInPixels(editor: Editor, text: String?, widthAdjustment: HintWidthAdjustment?): Int { return calcWidthInPixels(editor, text, widthAdjustment, useEditorFontFromSettings()) } @JvmStatic fun calcWidthInPixels(editor: Editor, text: String?, widthAdjustment: HintWidthAdjustment?, useEditorFont: Boolean): Int { val fontMetrics = getFontMetrics(editor, useEditorFont).metrics return calcHintTextWidth(text, fontMetrics) + calcWidthAdjustment(text, editor, fontMetrics, widthAdjustment) } @JvmStatic fun paintHint(g: Graphics, editor: EditorImpl, r: Rectangle, text: String?, attributes: TextAttributes?, textAttributes: TextAttributes, widthAdjustment: HintWidthAdjustment?) { paintHint(g, editor, r, text, attributes, textAttributes, widthAdjustment, useEditorFontFromSettings()) } @JvmStatic fun paintHint(g: Graphics, editor: EditorImpl, r: Rectangle, text: String?, attributes: TextAttributes?, textAttributes: TextAttributes, widthAdjustment: HintWidthAdjustment?, useEditorFont: Boolean) { val ascent = editor.ascent val descent = editor.descent val g2d = g as Graphics2D if (text != null && attributes != null) { val fontMetrics = getFontMetrics(editor, useEditorFont) val gap = if (r.height < fontMetrics.lineHeight + 2) 1 else 2 val backgroundColor = attributes.backgroundColor if (backgroundColor != null) { val alpha = if (isInsufficientContrast(attributes, textAttributes)) 1.0f else BACKGROUND_ALPHA val config = GraphicsUtil.setupAAPainting(g) GraphicsUtil.paintWithAlpha(g, alpha) g.setColor(backgroundColor) g.fillRoundRect(r.x + 2, r.y + gap, r.width - 4, r.height - gap * 2, 8, 8) config.restore() } val foregroundColor = attributes.foregroundColor if (foregroundColor != null) { val savedHint = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING) val savedClip = g.getClip() g.setColor(foregroundColor) g.setFont(getFont(editor, useEditorFont)) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false)) g.clipRect(r.x + 3, r.y + 2, r.width - 6, r.height - 4) val metrics = fontMetrics.metrics val startX = r.x + 7 val startY = r.y + max(ascent, (r.height + metrics.ascent - metrics.descent) / 2) - 1 val adjustment = calcWidthAdjustment(text, editor, g.fontMetrics, widthAdjustment) if (adjustment == 0) { g.drawString(text, startX, startY) } else { val adjustmentPosition = widthAdjustment!!.adjustmentPosition val firstPart = text.substring(0, adjustmentPosition) val secondPart = text.substring(adjustmentPosition) g.drawString(firstPart, startX, startY) g.drawString(secondPart, startX + g.getFontMetrics().stringWidth(firstPart) + adjustment, startY) } g.setClip(savedClip) g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedHint) } } val effectColor = textAttributes.effectColor val effectType = textAttributes.effectType if (effectColor != null) { g.setColor(effectColor) val xStart = r.x val xEnd = r.x + r.width val y = r.y + ascent val font = editor.getColorsScheme().getFont(EditorFontType.PLAIN) @Suppress("NON_EXHAUSTIVE_WHEN") when (effectType) { EffectType.LINE_UNDERSCORE -> EffectPainter.LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) EffectType.BOLD_LINE_UNDERSCORE -> EffectPainter.BOLD_LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) EffectType.STRIKEOUT -> EffectPainter.STRIKE_THROUGH.paint(g2d, xStart, y, xEnd - xStart, editor.charHeight, font) EffectType.WAVE_UNDERSCORE -> EffectPainter.WAVE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) EffectType.BOLD_DOTTED_LINE -> EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font) } } } private fun isInsufficientContrast( attributes: TextAttributes, surroundingAttributes: TextAttributes ): Boolean { val backgroundUnderHint = surroundingAttributes.backgroundColor if (backgroundUnderHint != null && attributes.foregroundColor != null) { val backgroundBlended = srcOverBlend(attributes.backgroundColor, backgroundUnderHint, BACKGROUND_ALPHA) val backgroundBlendedGrayed = backgroundBlended.toGray() val textGrayed = attributes.foregroundColor.toGray() val delta = Math.abs(backgroundBlendedGrayed - textGrayed) return delta < 10 } return false } private fun Color.toGray(): Double { return (0.30 * red) + (0.59 * green) + (0.11 * blue) } private fun srcOverBlend(foreground: Color, background: Color, foregroundAlpha: Float): Color { val r = foreground.red * foregroundAlpha + background.red * (1.0f - foregroundAlpha) val g = foreground.green * foregroundAlpha + background.green * (1.0f - foregroundAlpha) val b = foreground.blue * foregroundAlpha + background.blue * (1.0f - foregroundAlpha) return Color(r.roundToInt(), g.roundToInt(), b.roundToInt()) } private fun calcWidthAdjustment(text: String?, editor: Editor, fontMetrics: FontMetrics, widthAdjustment: HintWidthAdjustment?): Int { if (widthAdjustment == null || editor !is EditorImpl) return 0 val editorTextWidth = editor.getFontMetrics(Font.PLAIN).stringWidth(widthAdjustment.editorTextToMatch) return max(0, editorTextWidth + calcHintTextWidth(widthAdjustment.hintTextToMatch, fontMetrics) - calcHintTextWidth(text, fontMetrics)) } class MyFontMetrics internal constructor(editor: Editor, size: Int, @JdkConstants.FontStyle fontType: Int, useEditorFont: Boolean) { val metrics: FontMetrics val lineHeight: Int val font: Font get() = metrics.font init { val font = if (useEditorFont) { val editorFont = EditorUtil.getEditorFont() editorFont.deriveFont(fontType, size.toFloat()) } else { val familyName = UIManager.getFont("Label.font").family StartupUiUtil.getFontWithFallback(familyName, fontType, size) } val context = getCurrentContext(editor) metrics = FontInfo.getFontMetrics(font, context) // We assume this will be a better approximation to a real line height for a given font lineHeight = ceil(font.createGlyphVector(context, "Ap").visualBounds.height).toInt() } fun isActual(editor: Editor, size: Int, fontType: Int, familyName: String): Boolean { val font = metrics.font if (familyName != font.family || size != font.size || fontType != font.style) return false val currentContext = getCurrentContext(editor) return currentContext.equals(metrics.fontRenderContext) } private fun getCurrentContext(editor: Editor): FontRenderContext { val editorContext = FontInfo.getFontRenderContext(editor.contentComponent) return FontRenderContext(editorContext.transform, AntialiasingType.getKeyForCurrentScope(false), UISettings.editorFractionalMetricsHint) } } @JvmStatic protected fun getFontMetrics(editor: Editor, useEditorFont: Boolean): MyFontMetrics { val size = max(1, editor.colorsScheme.editorFontSize - 1) var metrics = editor.getUserData(HINT_FONT_METRICS) val attributes = editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT) val fontType = attributes.fontType val familyName = if (useEditorFont) { EditorColorsManager.getInstance().globalScheme.editorFontName } else { StartupUiUtil.getLabelFont().family } if (metrics != null && !metrics.isActual(editor, size, fontType, familyName)) { metrics = null } if (metrics == null) { metrics = MyFontMetrics(editor, size, fontType, useEditorFont) editor.putUserData(HINT_FONT_METRICS, metrics) } return metrics } @JvmStatic fun useEditorFontFromSettings() = EditorSettingsExternalizable.getInstance().isUseEditorFontInInlays private fun getFont(editor: Editor, useEditorFont: Boolean): Font { return getFontMetrics(editor, useEditorFont).font } @JvmStatic protected fun calcHintTextWidth(text: String?, fontMetrics: FontMetrics): Int { return if (text == null) 0 else fontMetrics.stringWidth(text) + 14 } private val HINT_FONT_METRICS = Key.create<MyFontMetrics>("ParameterHintFontMetrics") private const val BACKGROUND_ALPHA = 0.55f } // workaround for KT-12063 "IllegalAccessError when accessing @JvmStatic protected member of a companion object from a subclass" @JvmSynthetic @JvmName("getFontMetrics$") protected fun getFontMetrics(editor: Editor, useEditorFont: Boolean): MyFontMetrics = Companion.getFontMetrics(editor, useEditorFont) }
apache-2.0
98103c625334e3efa6577174c2aa88d7
43.581227
142
0.694712
4.513523
false
false
false
false
WYKCode/WYK-Android
app/src/main/java/college/wyk/app/ui/feed/FeedFragment.kt
1
3976
package college.wyk.app.ui.feed import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentStatePagerAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import college.wyk.app.R import college.wyk.app.commons.inflate import college.wyk.app.commons.landingActivity import college.wyk.app.ui.feed.directus.DirectusFeedFragment import college.wyk.app.ui.feed.sns.SnsFeedFragment import com.astuetz.PagerSlidingTabStrip import com.github.florent37.materialviewpager.header.HeaderDesign import kotlinx.android.synthetic.main.fragment_feed.* class FeedFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_feed, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Do not use saved instance state; view pager may crash // set up toolbar val toolbar = view_pager.toolbar toolbar.title = "What's New" landingActivity.updateToolbar(toolbar) // set up view pager view_pager.viewPager.adapter = FeedAdapter(childFragmentManager) // use child fragment manager view_pager.setMaterialViewPagerListener { page -> when (page) { indices["School"] -> HeaderDesign.fromColorResAndUrl(R.color.school, "http://wyk.tigerhix.me/cover/feed.jpg") indices["CampusTV"] -> HeaderDesign.fromColorResAndUrl(R.color.campus_tv, "http://wyk.tigerhix.me/cover/campus_tv.jpg") indices["SA"] -> HeaderDesign.fromColorResAndUrl(R.color.sa, "http://wyk.tigerhix.me/cover/sa.png") indices["MA"] -> HeaderDesign.fromColorResAndUrl(R.color.ma, "http://wyk.tigerhix.me/cover/ma.jpg") else -> null } } view_pager.pagerTitleStrip.setViewPager(view_pager.viewPager) view_pager.viewPager.currentItem = indices["School"]!! } } class FeedAdapter(supportFragmentManager: FragmentManager) : FragmentStatePagerAdapter(supportFragmentManager), PagerSlidingTabStrip.CustomTabProvider { override fun getItem(position: Int) = when (position) { indices["School"] -> DirectusFeedFragment() indices["CampusTV"] -> SnsFeedFragment.newInstance("CampusTV") indices["SA"] -> SnsFeedFragment.newInstance("SA") indices["MA"] -> SnsFeedFragment.newInstance("MA") else -> SnsFeedFragment.newInstance(position.toString()) } override fun getCount() = 4 override fun getPageTitle(position: Int) = when (position) { indices["School"] -> "School" indices["CampusTV"] -> "Campus TV" indices["SA"] -> "SA" indices["MA"] -> "MA" else -> "" } override fun getCustomTabView(parent: ViewGroup, position: Int): View { val view = parent.inflate(R.layout.tab, false) val imageView = view.findViewById(R.id.tab_icon) as ImageView imageView.setImageResource(when (position) { indices["School"] -> R.drawable.ic_school_white_48dp indices["CampusTV"] -> R.drawable.ic_videocam_white_48dp indices["SA"] -> R.drawable.ic_group_white_48dp indices["MA"] -> R.drawable.ic_music_note_white_48dp else -> R.drawable.ic_school_white_48dp }) return view } override fun tabUnselected(tab: View) { val imageView = tab.findViewById(R.id.tab_icon) as ImageView imageView.alpha = .6f } override fun tabSelected(tab: View) { val imageView = tab.findViewById(R.id.tab_icon) as ImageView imageView.alpha = 1.0f } } val indices = mapOf( "MA" to 3, "SA" to 2, "School" to 1, "CampusTV" to 0 )
mit
6a5f6575d26c98d6ad44d4e83d0f9f57
38.376238
152
0.677565
4.004028
false
false
false
false
hitting1024/IndexedListViewForAndroid
library/src/main/kotlin/jp/hitting/android/indexedlist/IndexedListView.kt
1
6498
package jp.hitting.android.indexedlist import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.graphics.drawable.Drawable import android.util.AttributeSet import android.util.Pair import android.util.SparseBooleanArray import android.view.Gravity import android.view.View import android.widget.* import android.widget.AdapterView.* class IndexedListView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) { companion object { private var indexTextColor: Int = Color.WHITE private var indexTextSize: Float = 12f } private var indexList: List<Pair<String, Int>>? = null private val listView: ListView private val indexLayout: LinearLayout init { val typedAry = context.obtainStyledAttributes(attrs, R.styleable.IndexedListView) indexTextColor = typedAry.getColor(R.styleable.IndexedListView_index_color, Color.WHITE) indexTextSize = typedAry.getDimension(R.styleable.IndexedListView_index_size, 12f) typedAry.recycle() this.listView = ListView(this.context) this.addView(this.listView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) this.indexLayout = LinearLayout(this.context) this.indexLayout.setPadding(10, 5, 10, 5) this.indexLayout.orientation = LinearLayout.VERTICAL this.indexLayout.setHorizontalGravity(ALIGN_PARENT_RIGHT) val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT) params.addRule(ALIGN_PARENT_RIGHT) this.indexLayout.setOnTouchListener { view, motionEvent -> this.moveSection(motionEvent.getX(), motionEvent.getY()) return@setOnTouchListener true } this.addView(this.indexLayout, params) } /** * @param indexList the pair of (index key, jump position) list. */ fun setIndex(indexList: List<Pair<String, Int>>) { this.indexList = indexList this.indexLayout.removeAllViews() for (index in this.indexList!!) { val textView = TextView(this.context) textView.text = index.first textView.gravity = Gravity.CENTER textView.textSize = indexTextSize textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD) textView.setTextColor(indexTextColor) textView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f) this.indexLayout.addView(textView) } } fun setIndexVisibility(visibility: Int) { this.indexLayout.visibility = visibility } private fun moveSection(x: Float, y: Float) { val size = this.indexList!!.size var position = (y / (this.listView.height / size)).toInt() if (position < 0) { position = 0 } else if (position >= size) { position = size - 1 } val sectionPosition = this.indexList!![position].second this.listView.setSelection(sectionPosition) } // // ListView // // method val maxScrollAmount: Int get() = this.listView.maxScrollAmount fun addHeaderView(v: View, data: Any, isSelectable: Boolean) { this.listView.addHeaderView(v, data, isSelectable) } fun addHeaderView(v: View) { this.listView.addHeaderView(v) } val headerViewsCount: Int get() = this.listView.headerViewsCount fun removeHeaderView(v: View): Boolean { return this.listView.removeHeaderView(v) } fun addFooterView(v: View, data: Any, isSelectable: Boolean) { this.listView.addFooterView(v, data, isSelectable) } fun addFooterView(v: View) { this.listView.addFooterView(v) } val footerViewsCount: Int get() = this.listView.footerViewsCount fun removeFooterView(v: View): Boolean { return this.listView.removeFooterView(v) } var adapter: ListAdapter get() = this.listView.adapter set(adapter) { this.listView.adapter = adapter } fun setSelection(position: Int) { this.listView.setSelection(position) } fun setSelectionFromTop(position: Int, y: Int) { this.listView.setSelectionFromTop(position, y) } fun setSelectionAfterHeaderView() { this.listView.setSelectionAfterHeaderView() } var itemsCanFocus: Boolean get() = this.listView.itemsCanFocus set(itemsCanFocus) { this.listView.itemsCanFocus = itemsCanFocus } fun setCacheColorHint(color: Int) { this.listView.cacheColorHint = color } var divider: Drawable get() = this.listView.divider set(divider) { this.listView.divider = divider } var dividerHeight: Int get() = this.listView.dividerHeight set(height) { this.listView.dividerHeight = height } fun setHeaderDividersEnabled(headerDividersEnabled: Boolean) { this.listView.setHeaderDividersEnabled(headerDividersEnabled) } fun setFooterDividersEnabled(footerDividersEnabled: Boolean) { this.listView.setFooterDividersEnabled(footerDividersEnabled) } var choiceMode: Int get() = this.listView.choiceMode set(choiceMode) { this.listView.choiceMode = choiceMode } fun performItemClick(view: View, position: Int, id: Long): Boolean { return this.listView.performItemClick(view, position, id) } fun setItemChecked(position: Int, value: Boolean) { this.listView.setItemChecked(position, value) } fun isItemChecked(position: Int): Boolean { return this.listView.isItemChecked(position) } val checkedItemPosition: Int get() = this.listView.checkedItemPosition val checkedItemPositions: SparseBooleanArray get() = this.listView.checkedItemPositions fun clearChoices() { this.listView.clearChoices() } // listener fun setOnItemClickListener(listener: OnItemClickListener) { this.listView.onItemClickListener = listener } fun setOnItemLongClickListener(listener: OnItemLongClickListener) { this.listView.onItemLongClickListener = listener } fun setOnItemSelectedListener(listener: OnItemSelectedListener) { this.listView.onItemSelectedListener = listener } }
mit
4ae4b820395a485dcd2147ec451177e6
29.65566
145
0.672053
4.601983
false
false
false
false
mike-plummer/KotlinCalendar
src/main/kotlin/com/objectpartners/plummer/kotlin/calendar/input/handler/CalendarEntryInputHandler.kt
1
1562
package com.objectpartners.plummer.kotlin.calendar.input.handler import com.objectpartners.plummer.kotlin.calendar.entry.CalendarEntry import com.objectpartners.plummer.kotlin.calendar.parseHMS import java.io.BufferedReader import java.time.Duration import java.time.LocalDateTime import java.time.format.DateTimeFormatter abstract class CalendarEntryInputHandler<out T: CalendarEntry>(): InputHandler<CalendarEntry> { abstract val type: String private final val pattern: String = "yyyy-MM-dd HH:mm:ss"; private final val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern) override fun handle(source: BufferedReader): T { println("-- $type entry --") // Read a dttm from the source, if none found then use current dttm print("\tStart time ($pattern): ") val startString = source.readLine() // Kotlin has no ternary operator so we use a succinct if-else instead val start = if (startString.isBlank()) LocalDateTime.now() else LocalDateTime.from(formatter.parse(startString)) // Parse hours, minutes, and seconds from the source print("\tDuration (HH:mm:ss): ") val duration = Duration.ZERO.parseHMS(source.readLine()) // Build object and populate val entry: T = buildInstance() return entry.apply { this.start = start this.duration = duration } } /** * Construct a new instance of the type of [CalendarEntry] this handler manages ([T]). */ abstract fun buildInstance() : T }
mit
5ea0e55a1ac62a6c0906718b92b380a4
38.075
120
0.696543
4.4375
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/extensions/ViewExtensions.kt
1
6951
/* * Copyright (C) 2017-2020 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.utils.extensions import android.app.NotificationManager import android.app.PendingIntent import android.content.ContentValues import android.content.Context import android.os.Build import android.provider.MediaStore import androidx.core.app.NotificationCompat import androidx.documentfile.provider.DocumentFile import jp.hazuki.yuzubrowser.core.MIME_TYPE_MHTML import jp.hazuki.yuzubrowser.core.utility.extensions.getWritableFileOrNull import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport import jp.hazuki.yuzubrowser.core.utility.utils.getMimeType import jp.hazuki.yuzubrowser.core.utility.utils.ui import jp.hazuki.yuzubrowser.download.NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY import jp.hazuki.yuzubrowser.download.core.data.DownloadFile import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo import jp.hazuki.yuzubrowser.download.core.data.MetaData import jp.hazuki.yuzubrowser.download.createFileOpenIntent import jp.hazuki.yuzubrowser.download.repository.DownloadsDao import jp.hazuki.yuzubrowser.legacy.R import jp.hazuki.yuzubrowser.ui.widget.toast import jp.hazuki.yuzubrowser.webview.CustomWebView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import java.io.File import java.io.IOException fun CustomWebView.saveArchive(downloadsDao: DownloadsDao, root: DocumentFile, file: DownloadFile) { ui { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { val outFile = root.uri.getWritableFileOrNull() if (outFile != null && outFile.exists()) { val downloadedFile = File(outFile, file.name!!) saveWebArchiveMethod(downloadedFile.toString()) onDownload(webView.context, downloadsDao, root, file, DocumentFile.fromFile(downloadedFile), true, downloadedFile.length()) return@ui } } val context = webView.context val tmpFile = File(context.cacheDir, "page.tmp") saveWebArchiveMethod(tmpFile.absolutePath) delay(1000) var success = tmpFile.exists() if (success) { val size = withContext(Dispatchers.IO) { var size = 0L do { delay(500) val oldSize = size size = tmpFile.length() } while (size == 0L || oldSize != size) return@withContext size } val name = file.name!! if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && root.uri.scheme == "file") { context.copyArchive(downloadsDao, tmpFile, name, file) return@ui } val saveTo = root.createFile(MIME_TYPE_MHTML, name) if (saveTo == null) { context.toast(R.string.failed) return@ui } withContext(Dispatchers.IO) { tmpFile.inputStream().use { input -> context.contentResolver.openOutputStream(saveTo.uri, "w")!!.use { out -> input.copyTo(out) } } tmpFile.delete() } success = saveTo.exists() onDownload(context, downloadsDao, root, file, saveTo, success, size) } } } private suspend fun Context.copyArchive(downloadsDao: DownloadsDao, tmpFile: File, name: String, file: DownloadFile) { val values = ContentValues().apply { put(MediaStore.Downloads.DISPLAY_NAME, name) put(MediaStore.Downloads.MIME_TYPE, getMimeType(name)) put(MediaStore.Downloads.IS_DOWNLOAD, 1) put(MediaStore.Downloads.IS_PENDING, 1) } val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) val uri = contentResolver.insert(collection, values) if (uri == null) { tmpFile.delete() return } val result = withContext(Dispatchers.IO) { try { contentResolver.openOutputStream(uri)?.use { os -> tmpFile.inputStream().use { it.copyTo(os) values.apply { clear() put(MediaStore.Downloads.IS_PENDING, 0) } val dFile = DocumentFile.fromSingleUri(this@copyArchive, uri)!! val size = dFile.length() val info = DownloadFileInfo(uri, file, MetaData(name, MIME_TYPE_MHTML, size, false)) info.state = DownloadFileInfo.STATE_DOWNLOADED downloadsDao.insert(info) contentResolver.update(uri, values, null, null) return@withContext true } } } catch (e: IOException) { ErrorReport.printAndWriteLog(e) } finally { tmpFile.delete() } return@withContext false } if (!result) { contentResolver.delete(uri, null, null) } } private suspend fun onDownload( context: Context, dao: DownloadsDao, root: DocumentFile, file: DownloadFile, downloadedFile: DocumentFile, success: Boolean, size: Long ) { val name = file.name!! val info = DownloadFileInfo(root.uri, file, MetaData(name, MIME_TYPE_MHTML, size, false)).also { it.state = if (success) { DownloadFileInfo.STATE_DOWNLOADED } else { DownloadFileInfo.STATE_UNKNOWN_ERROR } it.id = dao.insertAsync(it) } if (success) { context.toast(context.getString(R.string.saved_file) + name) val notify = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(name) .setContentText(context.getText(R.string.download_success)) .setSmallIcon(android.R.drawable.stat_sys_download_done) .setContentIntent(PendingIntent.getActivity(context.applicationContext, 0, info.createFileOpenIntent(context, downloadedFile), 0)) .build() val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.notify(info.id.toInt(), notify) } }
apache-2.0
f696d158b96449dcb1a9b4c0b0dd84d0
36.171123
142
0.638038
4.588119
false
false
false
false
geeniuss01/PWM
app/src/main/java/me/samen/pwm/setup/SetupActivity.kt
1
1727
package me.samen.pwm.setup import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import kotlinx.android.synthetic.main.activity_setup.* import me.samen.pwm.common.PWMApp import me.samen.pwm.R import me.samen.pwm.common.Data class SetupActivity : AppCompatActivity() { var appData: Data? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_setup) val toolBar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolBar) appData = (application as PWMApp).appData editTextPin.setOnEditorActionListener { textView, i, keyEvent -> checkPinAndFinish(textView.text.toString()) } editTextPin.post { Runnable { editTextPin.requestFocus() } } if (appData?.getPin() == null) { textViewInstruction.visibility = View.VISIBLE textViewInstruction.text=resources.getString(R.string.setup_choose_pin) } } fun checkPinAndFinish(pin: String): Boolean { textViewInstruction.text="" if (appData?.getPin() == null && editTextPin.text.toString().length == 4) { appData?.savePin(editTextPin.text.toString()) finish() } else if (pin.equals(appData?.getPin())) { appData?.authenticated = true finish() } else { textViewInstruction.visibility = View.VISIBLE textViewInstruction.text=resources.getString(R.string.setup_wrong_pin) } return true } }
apache-2.0
3695d5525984c97452760828e72c84a0
34.244898
83
0.65084
4.394402
false
false
false
false
juanavelez/crabzilla
crabzilla-pg-client/src/main/java/io/github/crabzilla/pgc/PgcUowRepo.kt
1
10235
package io.github.crabzilla.pgc import io.github.crabzilla.framework.* import io.github.crabzilla.framework.UnitOfWork.JsonMetadata.EVENTS_JSON_CONTENT import io.github.crabzilla.framework.UnitOfWork.JsonMetadata.EVENT_NAME import io.github.crabzilla.internal.RangeOfEvents import io.github.crabzilla.internal.UnitOfWorkEvents import io.github.crabzilla.internal.UnitOfWorkRepository import io.vertx.core.Promise import io.vertx.core.json.JsonArray import io.vertx.core.json.JsonObject import io.vertx.pgclient.PgPool import io.vertx.sqlclient.Tuple import org.slf4j.LoggerFactory import java.util.* internal class PgcUowRepo<E: Entity>(private val pgPool: PgPool, private val jsonFunctions: EntityJsonAware<E>) : UnitOfWorkRepository { companion object { internal val log = LoggerFactory.getLogger(PgcUowRepo::class.java) private const val UOW_ID = "uow_id" private const val UOW_EVENTS = "uow_events" private const val CMD_ID = "cmd_id" private const val CMD_DATA = "cmd_data" private const val CMD_NAME = "cmd_name" private const val AR_ID = "ar_id" private const val AR_NAME = "ar_name" private const val VERSION = "version" private const val SQL_SELECT_FIELDS = "select uow_id, uow_events, cmd_id, cmd_data, cmd_name, ar_id, ar_name, version" const val SQL_SELECT_UOW_BY_CMD_ID = "$SQL_SELECT_FIELDS from units_of_work where cmd_id = $1" const val SQL_SELECT_UOW_BY_UOW_ID = "$SQL_SELECT_FIELDS from units_of_work where uow_id = $1" const val SQL_SELECT_UOW_BY_ENTITY_ID = "$SQL_SELECT_FIELDS from units_of_work where ar_id = $1 order by version" const val SQL_SELECT_AFTER_VERSION = "select uow_events, version from units_of_work " + "where ar_id = $1 and ar_name = $2 and version > $3 order by version" } override fun getUowByCmdId(cmdId: UUID): Promise<Pair<UnitOfWork, Long>> { val promise = Promise.promise<Pair<UnitOfWork, Long>>() val params = Tuple.of(cmdId) pgPool.preparedQuery(SQL_SELECT_UOW_BY_CMD_ID, params) { ar -> if (ar.failed()) { promise.fail(ar.cause()) return@preparedQuery } val rows = ar.result() if (rows.size() == 0) { promise.complete(null) return@preparedQuery } val row = rows.first() val commandName = row.getString(CMD_NAME) val commandAsJson = row.get(JsonObject::class.java, 3) val command = try { jsonFunctions.cmdFromJson(commandName, commandAsJson) } catch (e: Exception) { null } if (command == null) { promise.fail("error when getting command $commandName from json ") return@preparedQuery } val jsonArray = row.get(JsonArray::class.java, 1) val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = jsonArray.getJsonObject(index) val eventName = jsonObject.getString(EVENT_NAME) val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT) val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson) domainEvent } val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair) val uowId = row.getLong(UOW_ID) val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID), row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events) promise.complete(Pair(uow, uowId)) } return promise } override fun getUowByUowId(uowId: Long): Promise<UnitOfWork> { val promise = Promise.promise<UnitOfWork>() val params = Tuple.of(uowId) pgPool.preparedQuery(SQL_SELECT_UOW_BY_UOW_ID, params) { ar -> if (ar.failed()) { promise.fail(ar.cause()) return@preparedQuery } val rows = ar.result() if (rows.size() == 0) { promise.complete(null) return@preparedQuery } val row = rows.first() val commandName = row.getString(CMD_NAME) val commandAsJson = row.get(JsonObject::class.java, 3) val command = try { jsonFunctions.cmdFromJson(commandName, commandAsJson) } catch (e: Exception) { null } if (command == null) { promise.fail("error when getting command $commandName from json ") return@preparedQuery } val jsonArray = row.get(JsonArray::class.java, 1) val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = jsonArray.getJsonObject(index) val eventName = jsonObject.getString(EVENT_NAME) val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT) val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson) domainEvent } val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair) val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID), row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events) promise.complete(uow) } return promise } override fun getAllUowByEntityId(id: Int): Promise<List<UnitOfWork>> { val promise = Promise.promise<List<UnitOfWork>>() val params = Tuple.of(id) pgPool.preparedQuery(SQL_SELECT_UOW_BY_ENTITY_ID, params) { ar -> if (ar.failed()) { promise.fail(ar.cause()) return@preparedQuery } val result = ArrayList<UnitOfWork>() val rows = ar.result() for (row in rows) { val commandName = row.getString(CMD_NAME) val commandAsJson = row.get(JsonObject::class.java, 3) val command = try { jsonFunctions.cmdFromJson(commandName, commandAsJson) } catch (e: Exception) { null } if (command == null) { promise.fail("error when getting command $commandName from json ") return@preparedQuery } val jsonArray = row.get(JsonArray::class.java, 1) val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = jsonArray.getJsonObject(index) val eventName = jsonObject.getString(EVENT_NAME) val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT) val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson) domainEvent } val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair) val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID), row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events) result.add(uow) } promise.complete(result) } return promise } override fun selectAfterVersion(id: Int, version: Version, aggregateRootName: String): Promise<RangeOfEvents> { val promise = Promise.promise<RangeOfEvents>() log.trace("will load id [{}] after version [{}]", id, version) pgPool.getConnection { ar0 -> if (ar0.failed()) { promise.fail(ar0.cause()) return@getConnection } val conn = ar0.result() conn.prepare(SQL_SELECT_AFTER_VERSION) { ar1 -> if (ar1.failed()) { promise.fail(ar1.cause()) } else { val pq = ar1.result() // Fetch 100 rows at a time val tuple = Tuple.of( id, aggregateRootName, version) val stream = pq.createStream(100, tuple) val list = ArrayList<RangeOfEvents>() // Use the stream stream.handler { row -> val eventsArray = row.get(JsonArray::class.java, 0) val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = eventsArray.getJsonObject(index) val eventName = jsonObject.getString(EVENT_NAME) val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT) jsonFunctions.eventFromJson(eventName, eventJson) } val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair) val snapshotData = RangeOfEvents(version, row.getInteger(1)!!, events) list.add(snapshotData) } stream.endHandler { log.trace("found {} units of work for id {} and version > {}", list.size, id, version) val finalVersion = if (list.size == 0) 0 else list[list.size - 1].untilVersion val flatMappedToEvents = list.flatMap { sd -> sd.events } promise.complete(RangeOfEvents(version, finalVersion, flatMappedToEvents)) } stream.exceptionHandler { err -> log.error(err.message) promise.fail(err) } } } } return promise } override fun selectAfterUowId(uowId: Long, maxRows: Int): Promise<List<UnitOfWorkEvents>> { val promise = Promise.promise<List<UnitOfWorkEvents>>() log.trace("will load after uowId [{}]", uowId) val selectAfterUowIdSql = "select uow_id, ar_id, uow_events " + " from units_of_work " + " where uow_id > $1 " + " order by uow_id " + " limit " + maxRows val list = ArrayList<UnitOfWorkEvents>() pgPool.preparedQuery(selectAfterUowIdSql, Tuple.of(uowId)) { ar -> if (ar.failed()) { promise.fail(ar.cause().message) return@preparedQuery } val rows = ar.result() if (rows.size() == 0) { promise.complete(list) return@preparedQuery } for (row in rows) { val uowSeq = row.getLong("uow_id") val targetId = row.getInteger("ar_id") val eventsArray = row.get(JsonArray::class.java, 2) val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index -> val jsonObject = eventsArray.getJsonObject(index) val eventName = jsonObject.getString(EVENT_NAME) val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT) jsonFunctions.eventFromJson(eventName, eventJson) } val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair) val projectionData = UnitOfWorkEvents(uowSeq.toLong(), targetId, events) list.add(projectionData) } promise.complete(list) } return promise } }
apache-2.0
b55e69f61ea0ff033868b7616a2f4ba5
34.786713
117
0.643185
3.859351
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/items/ItemMFTool.kt
1
3588
package szewek.mcflux.items import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.EnumActionResult import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.util.text.TextComponentTranslation import net.minecraft.util.text.TextFormatting import net.minecraft.world.World import szewek.fl.FLU import szewek.mcflux.U import szewek.mcflux.fluxable.FluxableCapabilities import szewek.mcflux.fluxcompat.FluxCompat import szewek.mcflux.tileentities.TileEntityEnergyMachine class ItemMFTool : ItemMCFlux() { private val textBlock = TextComponentTranslation("mcflux.blockcompat.start") private val textEntity = TextComponentTranslation("mcflux.entitycompat.start") private val textIsCompat = TextComponentTranslation("mcflux.iscompat") private val textNoCompat = TextComponentTranslation("mcflux.nocompat") private val textEnergyUnknown = TextComponentTranslation("mcflux.energystatunknown") private val textWorldChunk = TextComponentTranslation("mcflux.worldchunk") init { setMaxStackSize(1) textIsCompat.style.setColor(TextFormatting.GREEN).bold = true textNoCompat.style.setColor(TextFormatting.RED).bold = true } override fun onItemUse(p: EntityPlayer, w: World, pos: BlockPos, h: EnumHand, f: EnumFacing, x: Float, y: Float, z: Float): EnumActionResult { if (!w.isRemote) { val te = w.getTileEntity(pos) if (te != null) { if (te is TileEntityEnergyMachine) { val teem = te as TileEntityEnergyMachine? if (teem!!.moduleId < 2) p.sendMessage(TextComponentTranslation("mcflux.transfer", te.getTransferSide(f))) return EnumActionResult.SUCCESS } val ie = FLU.getEnergySafely(te, f) val tcb = textBlock.createCopy() tcb.appendSibling(if (ie != null) textIsCompat else textNoCompat).appendSibling(TextComponentTranslation("mcflux.blockcompat.end", f)) p.sendMessage(tcb) if (ie != null) p.sendMessage(TextComponentTranslation("mcflux.energystat", U.formatMF(ie))) if (ie is FluxCompat.Convert) p.sendMessage(TextComponentTranslation("mcflux.fluxcompat.type", (ie as FluxCompat.Convert).energyType.name)) } else { val wce = w.getCapability(FluxableCapabilities.CAP_WCE, null) if (wce != null) { val bat = wce.getEnergyChunk(p.posX.toInt(), (p.posY + 0.5).toInt(), p.posZ.toInt()) val tcb = textWorldChunk.createCopy() tcb.appendSibling(TextComponentTranslation("mcflux.energystat", U.formatMF(bat))) p.sendMessage(tcb) } else { return EnumActionResult.PASS } } return EnumActionResult.SUCCESS } else if (p.isSneaking) { return EnumActionResult.SUCCESS } return EnumActionResult.PASS } override fun itemInteractionForEntity(stk: ItemStack, p: EntityPlayer, elb: EntityLivingBase, h: EnumHand): Boolean { if (!elb.world.isRemote) { val ie = FLU.getEnergySafely(elb, EnumFacing.UP) // FIXME: SET TO null val tcb = textEntity.createCopy() tcb.appendSibling(if (ie != null) textIsCompat else textNoCompat) tcb.appendSibling(TextComponentTranslation("mcflux.entitycompat.end")) p.sendMessage(tcb) if (ie != null) { val nc = ie.energyCapacity p.sendMessage(if (nc == 1L) textEnergyUnknown else TextComponentTranslation("mcflux.energystat", U.formatMF(ie))) } if (ie is FluxCompat.Convert) p.sendMessage(TextComponentTranslation("mcflux.fluxcompat.type", (ie as FluxCompat.Convert).energyType.name)) return true } return false } }
mit
647975217eb72c860e1e5d2556758b4a
40.241379
143
0.756689
3.613293
false
false
false
false
ykode/android-kotlin-rxsample
src/main/kotlin/MainActivity.kt
1
2745
package com.ykode.research.RxKotlinSample import android.app.Activity import android.app.Fragment import android.os.Bundle import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.view.View import android.widget.EditText import android.widget.Button import android.graphics.Color import rx.Observable import rx.Subscription import rx.subscriptions.CompositeSubscription import com.jakewharton.rxbinding.widget.* import kotlinx.android.synthetic.fragment_main.* import kotlin.text.Regex var View.enabled: Boolean get() = this.isEnabled() set(value) = this.setEnabled(value) val Fragment.ctx:Context? get() = this.activity class MainActivity : Activity() { override fun onCreate(savedInstanceState:Bundle?) { super<Activity>.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (null == savedInstanceState) { fragmentManager.beginTransaction() .add(R.id.container, MainFragment()) .commit() } } } abstract class ReactiveFragment : Fragment() { private var _compoSub = CompositeSubscription() private val compoSub: CompositeSubscription get() { if (_compoSub.isUnsubscribed()) { _compoSub = CompositeSubscription() } return _compoSub } protected final fun manageSub(s: Subscription) = compoSub.add(s) override fun onDestroyView() { compoSub.unsubscribe() super<Fragment>.onDestroyView() } } internal class MainFragment : ReactiveFragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater?.inflate(R.layout.fragment_main, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { val emailPattern = Regex("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})${'$'}") val userNameValid = edtUserName.textChanges().map { t -> t.length > 4 } val emailValid = edtEmail.textChanges().map { t -> emailPattern in t } manageSub(emailValid.distinctUntilChanged() .map{ b -> if (b) Color.WHITE else Color.RED } .subscribe{ color -> edtEmail.setTextColor(color) }) manageSub(userNameValid.distinctUntilChanged() .map{ b -> if (b) Color.WHITE else Color.RED } .subscribe{ color -> edtUserName.setTextColor(color) }) val registerEnabled = Observable.combineLatest(userNameValid, emailValid, {a, b -> a && b}) manageSub(registerEnabled.distinctUntilChanged() .subscribe{ enabled -> buttonRegister.enabled = enabled }) } }
bsd-2-clause
fa2d6954ba146b956423ae0cb1b84b37
28.836957
95
0.67796
4.12782
false
false
false
false
AK-47-D/cms
src/main/kotlin/com/ak47/cms/cms/entity/TechArticle.kt
1
629
package com.ak47.cms.cms.entity import java.util.* import javax.persistence.* @Entity @Table(indexes = arrayOf( Index(name = "idx_url", unique = true, columnList = "url"))) open class TechArticle { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long = -1 var url = "URL" var title = "Kotlin 使用 Spring WebFlux 实现响应式编程" @Lob var simpleContent = "文章摘要" @Lob var showContent = "文章内容" // TechArticleTag 表中的 tagId var tagId = -1 var category = "编程语言" var gmtCreate = Date() var gmtModified = Date() }
apache-2.0
d526ab678797b961478705442454abc1
19.785714
68
0.636833
3.32
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/placeholder/RPKPlayersPlaceholderExpansion.kt
1
1868
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.players.bukkit.placeholder import com.rpkit.core.service.Services import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import me.clip.placeholderapi.expansion.PlaceholderExpansion import org.bukkit.entity.Player class RPKPlayersPlaceholderExpansion(private val plugin: RPKPlayersBukkit) : PlaceholderExpansion() { override fun persist() = true override fun canRegister() = true override fun getIdentifier() = "rpkplayers" override fun getAuthor() = plugin.description.authors.joinToString() override fun getVersion() = plugin.description.version override fun onPlaceholderRequest(player: Player, params: String): String? { val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return null val minecraftProfile = player.let { minecraftProfileService.getPreloadedMinecraftProfile(it) } val profile = minecraftProfile?.profile as? RPKProfile return when (params.lowercase()) { "minecraftusername" -> minecraftProfile?.name "profile" -> profile?.name?.plus(profile.discriminator) else -> null } } }
apache-2.0
8aaddd750336bed357abbf6da5a27734
40.533333
102
0.747323
4.693467
false
false
false
false
itachi1706/CheesecakeUtilities
app/src/main/java/com/itachi1706/cheesecakeutilities/modules/listApplications/objects/RestoreAppsItemsHeader.kt
1
1737
package com.itachi1706.cheesecakeutilities.modules.listApplications.objects import android.content.Context import android.graphics.drawable.Drawable import androidx.core.content.ContextCompat import com.itachi1706.cheesecakeutilities.R /** * Created by Kenneth on 3/12/2016. * for com.itachi1706.cheesecakeutilities.modules.AppRestore.Objects in CheesecakeUtilities */ data class RestoreAppsItemsHeader(var appName: String? = null, var count: Int = 0, var icon: Drawable? = null, private var child: List<RestoreAppsItemsFooter>? = null) : RestoreAppsItemsBase() { constructor(appName: String, context: Context) : this(appName = appName, icon = ContextCompat.getDrawable(context, R.mipmap.ic_launcher), child = ArrayList<RestoreAppsItemsFooter>()) { this.count = this.child!!.size } constructor(appName: String, appIcon: Drawable) : this(appName = appName, icon = appIcon, child = ArrayList<RestoreAppsItemsFooter>()) { this.count = this.child!!.size } constructor(appName: String, child: List<RestoreAppsItemsFooter>, context: Context) : this(appName = appName, child = child, icon = ContextCompat.getDrawable(context, R.mipmap.ic_launcher)) { this.count = this.child!!.size } constructor(appName: String, child: List<RestoreAppsItemsFooter>, appIcon: Drawable) : this(appName = appName, child = child, icon = appIcon) { this.count = this.child!!.size } fun getChild(): List<RestoreAppsItemsFooter>? { return child } fun setChild(child: List<RestoreAppsItemsFooter>) { this.child = child this.count = this.child!!.size } fun hasChild(): Boolean { return this.child != null && this.child!!.isNotEmpty() } }
mit
0694285b0e23994aa26ffe0634cc7c48
41.365854
195
0.712723
4.116114
false
false
false
false
googlearchive/background-tasks-samples
WorkManager/app/src/main/java/com/example/background/FilterActivity.kt
1
5532
/* * * * Copyright (C) 2018 The Android Open Source Project * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.example.background import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.Button import android.widget.Checkable import android.widget.ImageView import android.widget.ProgressBar import androidx.activity.viewModels import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import com.bumptech.glide.Glide /** * The [android.app.Activity] where the user picks filters to be applied on an * image. */ class FilterActivity : AppCompatActivity() { private val mViewModel: FilterViewModel by viewModels() private var mImageUri: Uri? = null private var mOutputImageUri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_processing) // Don't enable upload to Imgur, unless the developer specifies their own clientId. val enableUpload = !TextUtils.isEmpty(Constants.IMGUR_CLIENT_ID) findViewById<View>(R.id.upload).isEnabled = enableUpload val intent = intent val imageUriExtra = intent.getStringExtra(Constants.KEY_IMAGE_URI) if (!TextUtils.isEmpty(imageUriExtra)) { mImageUri = Uri.parse(imageUriExtra) val imageView = findViewById<ImageView>(R.id.imageView) Glide.with(this).load(mImageUri).into(imageView) } findViewById<View>(R.id.go).setOnClickListener { val applyWaterColor = isChecked(R.id.filter_watercolor) val applyGrayScale = isChecked(R.id.filter_grayscale) val applyBlur = isChecked(R.id.filter_blur) val save = isChecked(R.id.save) val upload = isChecked(R.id.upload) val imageOperations = ImageOperations.Builder(applicationContext, mImageUri!!) .setApplyWaterColor(applyWaterColor) .setApplyGrayScale(applyGrayScale) .setApplyBlur(applyBlur) .setApplySave(save) .setApplyUpload(upload) .build() mViewModel.apply(imageOperations) } findViewById<View>(R.id.output).setOnClickListener { if (mOutputImageUri != null) { val actionView = Intent(Intent.ACTION_VIEW, mOutputImageUri) if (actionView.resolveActivity(packageManager) != null) { startActivity(actionView) } } } findViewById<View>(R.id.cancel).setOnClickListener { mViewModel.cancel() } // Check to see if we have output. mViewModel.outputStatus.observe(this, Observer { listOfInfos -> if (listOfInfos == null || listOfInfos.isEmpty()) { return@Observer } // We only care about the one output status. // Every continuation has only one worker tagged TAG_OUTPUT val info = listOfInfos[0] val finished = info.state.isFinished val progressBar = findViewById<ProgressBar>(R.id.progressBar) val go = findViewById<Button>(R.id.go) val cancel = findViewById<Button>(R.id.cancel) val output = findViewById<Button>(R.id.output) if (!finished) { progressBar.visibility = View.VISIBLE cancel.visibility = View.VISIBLE go.visibility = View.GONE output.visibility = View.GONE } else { progressBar.visibility = View.GONE cancel.visibility = View.GONE go.visibility = View.VISIBLE val outputData = info.outputData val outputImageUri = outputData.getString(Constants.KEY_IMAGE_URI) if (!TextUtils.isEmpty(outputImageUri)) { mOutputImageUri = Uri.parse(outputImageUri) output.visibility = View.VISIBLE } } }) } private fun isChecked(@IdRes resourceId: Int): Boolean { val view = findViewById<View>(resourceId) return view is Checkable && (view as Checkable).isChecked } companion object { /** * Creates a new intent which can be used to start [FilterActivity]. * * @param context the application [Context]. * @param imageUri the input image [Uri]. * @return the instance of [Intent]. */ internal fun newIntent(context: Context, imageUri: Uri): Intent { val intent = Intent(context, FilterActivity::class.java) intent.putExtra(Constants.KEY_IMAGE_URI, imageUri.toString()) return intent } } }
apache-2.0
85a47a53ce45312b6f90afded0cf2c46
36.632653
91
0.630152
4.696095
false
false
false
false
alexmonthy/lttng-scope
lttng-scope/src/main/kotlin/org/lttng/scope/common/jfx/Logo.kt
2
2601
/* * Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.lttng.scope.common.jfx import javafx.animation.Animation import javafx.animation.Interpolator import javafx.animation.RotateTransition import javafx.application.Application import javafx.application.Application.launch import javafx.scene.Group import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.shape.Rectangle import javafx.stage.Stage import javafx.util.Duration fun main(args: Array<String>) { launch(Logo::class.java, *args) } class Logo : Application() { companion object { private const val BACKGROUND_STYLE = "-fx-background-color: rgba(255, 255, 255, 255);" private val LTTNG_PURPLE: Color = Color.web("#996ABC") private val LTTNG_LIGHT_BLUE: Color = Color.web("#C3DEF4") } override fun start(stage: Stage?) { stage ?: return val clipRect1 = Rectangle(-130.0, -130.0, 115.0, 115.0) val clipRect2 = Rectangle(15.0, -130.0, 115.0, 115.0) val clipRect3 = Rectangle(-130.0, 15.0, 115.0, 115.0) val clipRect4 = Rectangle(15.0, 15.0, 115.0, 115.0) val clip = Group(clipRect1, clipRect2, clipRect3, clipRect4) val spinnanCircle = Circle(100.0) spinnanCircle.setFill(null); spinnanCircle.setStrokeWidth(30.0); spinnanCircle.setStroke(LTTNG_PURPLE); spinnanCircle.setClip(clip); val magCircle = Circle(60.0); magCircle.setFill(null); magCircle.setStrokeWidth(25.0); magCircle.setStroke(LTTNG_LIGHT_BLUE); val magHandle = Rectangle(-12.5, 60.0, 25.0, 110.0); magHandle.setFill(LTTNG_LIGHT_BLUE); val mag = Group(magCircle, magHandle); val root = Group(spinnanCircle, mag); root.setRotate(30.0) root.relocate(0.0, 0.0) val pane = Pane(root); pane.setStyle(BACKGROUND_STYLE); val spinnan = RotateTransition(Duration.seconds(4.0), spinnanCircle); spinnan.setByAngle(360.0); spinnan.setCycleCount(Animation.INDEFINITE); spinnan.setInterpolator(Interpolator.LINEAR); val scene = Scene(pane); stage.setScene(scene); stage.show(); spinnan.play(); } }
epl-1.0
0cda18b1988f2dbbe3f7d3cd5a3a1150
30.719512
94
0.678585
3.563014
false
false
false
false
lijunzz/LongChuanGang
app/src/main/kotlin/net/junzz/app/lcg/ListAdapter.kt
1
1088
package net.junzz.app.lcg import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import net.junzz.app.ui.widget.RoundAvatar class ListAdapter(val data: List<ListItemDO>) : RecyclerView.Adapter<ListAdapter.ListHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ListHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)) override fun getItemCount() = data.size override fun onBindViewHolder(holder: ListHolder, position: Int) { holder.avatarView.setImageAvatar(data[position].avatar) holder.titleView.text = data[position].title } class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val categoryView = itemView.findViewById<TextView>(R.id.tv_list_item_category) val avatarView = itemView.findViewById<RoundAvatar>(R.id.ra_list_item_avatar) val titleView = itemView.findViewById<TextView>(R.id.tv_list_item_title) } }
gpl-3.0
083253e6aff5d11ce7f0da788c4482b7
39.333333
104
0.752757
4.074906
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/VaporQualidadeCommand.kt
1
1526
package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun` import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.escapeMentions import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.common.utils.text.VaporwaveUtils import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import net.perfectdreams.loritta.morenitta.LorittaBot class VaporQualidadeCommand(loritta: LorittaBot) : AbstractCommand(loritta, "vaporqualidade", category = net.perfectdreams.loritta.common.commands.CommandCategory.FUN) { override fun getDescriptionKey() = LocaleKeyData("commands.command.vaporquality.description") override fun getExamplesKey() = LocaleKeyData("commands.command.vaporquality.examples") // TODO: Fix Usage // TODO: Fix Detailed Usage override suspend fun run(context: CommandContext,locale: BaseLocale) { OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "text vaporquality") if (context.args.isNotEmpty()) { val qualidade = VaporwaveUtils.vaporwave(context.args.joinToString(" ").toCharArray().joinToString(" ")).toUpperCase() .escapeMentions() context.reply( LorittaReply(message = qualidade, prefix = "✍") ) } else { this.explain(context) } } }
agpl-3.0
0258cfd123452aa76ea8311636567cac
43.852941
169
0.802493
4.198347
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/api/v1/user/GetMutualGuildsRoute.kt
1
1369
package net.perfectdreams.loritta.morenitta.website.routes.api.v1.user import com.github.salomonbrys.kotson.jsonArray import com.github.salomonbrys.kotson.jsonObject import com.github.salomonbrys.kotson.toJsonArray import io.ktor.server.application.ApplicationCall import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.website.routes.api.v1.RequiresAPIAuthenticationRoute import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondJson class GetMutualGuildsRoute(loritta: LorittaBot) : RequiresAPIAuthenticationRoute(loritta, "/api/v1/users/{userId}/mutual-guilds") { override suspend fun onAuthenticatedRequest(call: ApplicationCall) { val userId = call.parameters["userId"] ?: return val user = loritta.lorittaShards.getUserById(userId) if (user == null) { call.respondJson( jsonObject( "guilds" to jsonArray() ) ) return } val mutualGuilds = loritta.lorittaShards.getMutualGuilds(user) call.respondJson( jsonObject( "guilds" to mutualGuilds.map { val member = it.getMember(user) jsonObject( "id" to it.id, "name" to it.name, "iconUrl" to it.iconUrl, "memberCount" to it.memberCount, "timeJoined" to member?.timeJoined?.toInstant()?.toEpochMilli() ) }.toJsonArray() ) ) } }
agpl-3.0
51c00cf243660c186720fb3a563dc910
30.136364
131
0.72973
3.750685
false
false
false
false
MaibornWolff/codecharta
analysis/import/GitLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/input/Modification.kt
1
1377
package de.maibornwolff.codecharta.importer.gitlogparser.input class Modification( val currentFilename: String, val oldFilename: String, val additions: Long, val deletions: Long, val type: Type ) { private var initialAdd = false constructor(filename: String, type: Type) : this(filename, 0, 0, type) constructor(filename: String, oldFilename: String, type: Type) : this(filename, oldFilename, 0, 0, type) @JvmOverloads constructor(filename: String, additions: Long = 0, deletions: Long = 0, type: Type = Type.UNKNOWN) : this( filename, "", additions, deletions, type ) enum class Type { ADD, DELETE, MODIFY, RENAME, UNKNOWN } fun isTypeDelete(): Boolean { return type == Type.DELETE } fun isTypeAdd(): Boolean { return type == Type.ADD } fun isTypeModify(): Boolean { return type == Type.MODIFY } fun isTypeRename(): Boolean { return type == Type.RENAME } fun getTrackName(): String { return if (oldFilename.isNotEmpty()) oldFilename else currentFilename } fun markInitialAdd() { initialAdd = true } fun isInitialAdd(): Boolean { return initialAdd } companion object { val EMPTY = Modification("") } }
bsd-3-clause
046d5fe638b16ea2d86e8a68fef447a8
19.863636
110
0.595497
4.470779
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/viewgroup/DriftLayout.kt
1
9379
package com.angcyo.uiview.viewgroup import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.abs import com.angcyo.uiview.kotlin.density import java.util.* /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:浮动布局, 一个中心View, 其他View在周边浮动旋转 * 创建人员:Robi * 创建时间:2018/02/23 10:44 * 修改人员:Robi * 修改时间:2018/02/23 10:44 * 修改备注: * Version: 1.0.0 */ class DriftLayout(context: Context, attributeSet: AttributeSet? = null) : FrameLayout(context, attributeSet) { // init { // val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.DriftLayout) // typedArray.recycle() // } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) updateLayout() } private fun updateLayout() { driftCenterView?.let { //修正布局坐标 for (i in 0 until childCount) { val childAt = getChildAt(i) if (childAt.visibility != View.VISIBLE) { continue } val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (childAt != it) { //围绕的中心点坐标 val cx = it.left + it.measuredWidth / 2 val cy = it.top + it.measuredHeight / 2 //计算出的布局点的坐标 val r = Math.max(childAt.measuredWidth, childAt.measuredHeight) / 2 + layoutParams.driftROffset //距离中心点的半径 val x: Int = (cx + Math.cos(Math.toRadians(layoutParams.animDriftAngle.toDouble())) * r + layoutParams.animDriftXOffset * density).toInt() val y: Int = (cy + Math.sin(Math.toRadians(layoutParams.animDriftAngle.toDouble())) * r + layoutParams.animDriftYOffset * density).toInt() childAt.layout(x - childAt.measuredWidth / 2, y - childAt.measuredHeight / 2, x + childAt.measuredWidth / 2, y + childAt.measuredHeight / 2) } } } } } private var isOnAttachedToWindow = false override fun onAttachedToWindow() { super.onAttachedToWindow() isOnAttachedToWindow = true checkStartDrift() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() isOnAttachedToWindow = false checkStartDrift() } override fun onVisibilityChanged(changedView: View?, visibility: Int) { super.onVisibilityChanged(changedView, visibility) checkStartDrift() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) checkStartDrift() } private fun checkStartDrift() { //检查是否需要浮动 if (isOnAttachedToWindow && visibility == View.VISIBLE && measuredWidth > 0 && measuredHeight > 0 && !driftAnimator.isStarted) { driftAnimator.start() } else { driftAnimator.cancel() } } /**动画*/ private val driftAnimator: ValueAnimator by lazy { ObjectAnimator.ofInt(0, 360).apply { repeatMode = ValueAnimator.RESTART repeatCount = ValueAnimator.INFINITE duration = 1000 addUpdateListener { driftCenterView?.let { //修正布局坐标 for (i in 0 until childCount) { val childAt = getChildAt(i) val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (childAt != it) { if (layoutParams.enableDrift) { layoutParams.animDriftAngle += layoutParams.animDriftAngleStep } if (layoutParams.enableShake) { if (layoutParams.animDriftIsOffsetX) { layoutParams.animDriftXOffset += layoutParams.animDriftXOffsetStep } else { layoutParams.animDriftYOffset += layoutParams.animDriftYOffsetStep } } } } } updateLayout() postInvalidateOnAnimation() } } } } override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams { return LayoutParams(context, attrs) } override fun generateLayoutParams(lp: ViewGroup.LayoutParams?): ViewGroup.LayoutParams { return LayoutParams(lp) } override fun generateDefaultLayoutParams(): LayoutParams { return LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) } //居中定位的View private val driftCenterView: View? get() { var view: View? = null for (i in 0 until childCount) { val childAt = getChildAt(i) val layoutParams = childAt.layoutParams if (layoutParams is LayoutParams) { if (layoutParams.isDriftCenterView) { view = childAt break } } } return view } class LayoutParams : FrameLayout.LayoutParams { var isDriftCenterView = false var driftAngle = 0 var driftROffset = 0 var enableDrift = true var enableShake = true //每帧旋转的角度 var animDriftAngleStep = 0.1f private val random: Random by lazy { Random(System.nanoTime()) } var animDriftIsOffsetX = true var animDriftXOffsetMax = 10 + random.nextInt(10) //每帧x轴抖动的距离 var animDriftXOffsetStep = 0.15f var animDriftXOffset = 0f //px 自动转换为dp set(value) { field = value if (value > animDriftXOffsetMax) { animDriftXOffsetStep = -animDriftXOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } else if (value < -animDriftXOffsetMax) { animDriftXOffsetStep = animDriftXOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } } var animDriftYOffsetMax = 10 + random.nextInt(10) var animDriftYOffsetStep = animDriftXOffsetStep var animDriftYOffset = 0f set(value) { field = value if (value > animDriftYOffsetMax) { animDriftYOffsetStep = -animDriftYOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } else if (value < -animDriftYOffsetMax) { animDriftYOffsetStep = animDriftYOffsetStep.abs() animDriftIsOffsetX = random.nextBoolean() } } //动画执行中的角度保存变量 var animDriftAngle = 0f set(value) { field = if (value > 360) { 0f } else { value } } constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) { val a = c.obtainStyledAttributes(attrs, R.styleable.DriftLayout) isDriftCenterView = a.getBoolean(R.styleable.DriftLayout_r_is_drift_center, isDriftCenterView) driftAngle = a.getInt(R.styleable.DriftLayout_r_drift_angle, driftAngle) animDriftAngleStep = a.getFloat(R.styleable.DriftLayout_r_drift_angle_step, animDriftAngleStep) animDriftAngle = driftAngle.toFloat() driftROffset = a.getDimensionPixelOffset(R.styleable.DriftLayout_r_drift_r_offset, driftROffset) enableDrift = a.getBoolean(R.styleable.DriftLayout_r_enable_drift, enableDrift) enableShake = a.getBoolean(R.styleable.DriftLayout_r_enable_shake, enableShake) a.recycle() } constructor(width: Int, height: Int) : super(width, height) constructor(width: Int, height: Int, gravity: Int) : super(width, height, gravity) constructor(source: ViewGroup.LayoutParams?) : super(source) constructor(source: MarginLayoutParams?) : super(source) } }
apache-2.0
90750f8bd20bb9ac6cac3632b7abe52b
35.5
162
0.541708
4.788918
false
false
false
false
ansman/kotshi
tests/src/main/kotlin/se/ansman/kotshi/DefaultValues.kt
1
1028
package se.ansman.kotshi @JsonSerializable data class ClassWithDefaultValues( val v1: Byte = Byte.MAX_VALUE, val v2: Char = Char.MAX_VALUE, val v3: Short = Short.MAX_VALUE, val v4: Int = Int.MAX_VALUE, val v5: Long = Long.MAX_VALUE, val v6: Float = Float.MAX_VALUE, val v7: Double = Double.MAX_VALUE, val v8: String = "n/a", val v9: List<String> = emptyList(), val v10: String ) @JsonSerializable data class WithCompanionFunction(val v: String?) @JsonSerializable data class WithStaticFunction(val v: String?) @JsonSerializable data class WithCompanionProperty(val v: String?) @JsonSerializable data class WithStaticProperty(val v: String?) @JsonSerializable data class GenericClassWithDefault<out T>(val v: T?) @JsonSerializable data class ClassWithConstructorAsDefault(val v: String?) { constructor() : this("ClassWithConstructorAsDefault") } @JsonSerializable data class GenericClassWithConstructorAsDefault<T : CharSequence>(val v: T?) { constructor() : this(null) }
apache-2.0
935b5e51cc4b4b59334a9648e208c8af
24.073171
78
0.730545
3.619718
false
false
false
false
RyanAndroidTaylor/Rapido
rapidosqlite/src/androidTest/java/com/izeni/rapidosqlite/util/Toy.kt
1
1136
package com.izeni.rapidosqlite.util import android.content.ContentValues import android.database.Cursor import com.izeni.rapidosqlite.DataConnection import com.izeni.rapidosqlite.addAll import com.izeni.rapidosqlite.get import com.izeni.rapidosqlite.item_builder.ItemBuilder import com.izeni.rapidosqlite.table.Column import com.izeni.rapidosqlite.table.DataTable /** * Created by ner on 2/8/17. */ data class Toy(val uuid: String, val name: String) : DataTable { companion object { val TABLE_NAME = "Toy" val UUID = Column(String::class.java, "Uuid", notNull = true, unique = true) val NAME = Column(String::class.java, "Name") val COLUMNS = arrayOf(UUID, NAME) val BUILDER = Builder() } override fun tableName() = TABLE_NAME override fun id() = uuid override fun idColumn() = UUID override fun contentValues() = ContentValues().addAll(COLUMNS, uuid, name) class Builder : ItemBuilder<Toy> { override fun buildItem(cursor: Cursor, dataConnection: DataConnection): Toy { return Toy(cursor.get(UUID), cursor.get(NAME)) } } }
mit
07aa00264a41ec6ee1ec9cbf304a7402
26.731707
85
0.695423
4.071685
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/util/TagsAdapter.kt
1
2632
package com.newsblur.util import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.newsblur.R import com.newsblur.databinding.RowSavedTagBinding import com.newsblur.domain.StarredCount class TagsAdapter(private val type: Type, private val listener: OnTagClickListener) : RecyclerView.Adapter<TagsAdapter.ViewHolder>() { private val tags = ArrayList<StarredCount>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.row_saved_tag, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val tag = tags[position] holder.binding.containerRow.setBackgroundResource(android.R.color.transparent) holder.binding.rowTagName.text = tag.tag holder.binding.rowSavedTagSum.text = tag.count.toString() holder.binding.root.setOnClickListener { listener.onTagClickListener(tag, type) } } override fun getItemCount(): Int = tags.size fun replaceAll(tags: MutableCollection<StarredCount>) { val diffCallback = TagDiffCallback(this.tags, tags.toList()) val diffResult = DiffUtil.calculateDiff(diffCallback) this.tags.clear() this.tags.addAll(tags) diffResult.dispatchUpdatesTo(this) } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = RowSavedTagBinding.bind(view) } enum class Type { OTHER, SAVED } interface OnTagClickListener { fun onTagClickListener(starredTag: StarredCount, type: Type) } class TagDiffCallback(private val oldList: List<StarredCount>, private val newList: List<StarredCount>) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = oldList[oldItemPosition].tag == newList[newItemPosition].tag && oldList[oldItemPosition].count == newList[newItemPosition].count override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = oldList[oldItemPosition].tag == newList[newItemPosition].tag && oldList[oldItemPosition].count == newList[newItemPosition].count override fun getOldListSize(): Int = oldList.size override fun getNewListSize(): Int = newList.size } }
mit
c700603121b02c1f3b41a0e102df35fc
35.569444
110
0.694529
4.919626
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/fragment/AddSocialFragment.kt
1
2401
package com.newsblur.fragment import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.newsblur.R import com.newsblur.activity.AddFacebook import com.newsblur.activity.AddTwitter import com.newsblur.databinding.FragmentAddsocialBinding import com.newsblur.network.APIManager import com.newsblur.util.executeAsyncTask import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class AddSocialFragment : Fragment() { @Inject lateinit var apiManager: APIManager private lateinit var binding: FragmentAddsocialBinding private var twitterAuthed = false private var facebookAuthed = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } fun setTwitterAuthed() { twitterAuthed = true authCheck() } fun setFacebookAuthed() { facebookAuthed = true authCheck() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_addsocial, null) binding = FragmentAddsocialBinding.bind(view) binding.addsocialTwitter.setOnClickListener { val i = Intent(activity, AddTwitter::class.java) startActivityForResult(i, 0) } binding.addsocialFacebook.setOnClickListener { val i = Intent(activity, AddFacebook::class.java) startActivityForResult(i, 0) } authCheck() binding.addsocialAutofollowCheckbox.setOnCheckedChangeListener { _, checked -> lifecycleScope.executeAsyncTask( doInBackground = { apiManager.setAutoFollow(checked) } ) } return view } private fun authCheck() { if (twitterAuthed) { binding.addsocialTwitterText.text = "Added Twitter friends!" binding.addsocialTwitter.isEnabled = false } if (facebookAuthed) { binding.addsocialFacebookText.text = "Added Facebook friends!" binding.addsocialFacebook.isEnabled = false } } }
mit
e24158c5ccab3081166224674412c02a
30.194805
116
0.684298
4.9
false
false
false
false
spark/photon-tinker-android
meshui/src/main/java/io/particle/mesh/ui/setup/barcodescanning/barcode/BarcodeScanningProcessor.kt
1
3131
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package io.particle.mesh.ui.setup.barcodescanning.barcode import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetector import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcodeDetectorOptions.Builder import com.google.firebase.ml.vision.common.FirebaseVisionImage import io.particle.mesh.common.android.livedata.setOnMainThread import io.particle.mesh.ui.setup.barcodescanning.FrameMetadata import io.particle.mesh.ui.setup.barcodescanning.GraphicOverlay import io.particle.mesh.ui.setup.barcodescanning.VisionProcessorBase import mu.KotlinLogging import java.io.IOException class BarcodeScanningProcessor : VisionProcessorBase<List<FirebaseVisionBarcode>>() { val foundBarcodes: LiveData<List<FirebaseVisionBarcode>> get() = mutableFoundBarcodes private val mutableFoundBarcodes = MutableLiveData<List<FirebaseVisionBarcode>>() private val detector: FirebaseVisionBarcodeDetector private val log = KotlinLogging.logger {} init { // Note that if you know which format of barcode your app is dealing with, detection will be // faster to specify the supported barcode formats val options = Builder() .setBarcodeFormats(FirebaseVisionBarcode.FORMAT_DATA_MATRIX) .build() detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options) } override fun stop() { try { detector.close() } catch (e: IOException) { log.error(e) { "Exception thrown while trying to close Barcode Detector" } } } override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionBarcode>> { return detector.detectInImage(image) } override fun onSuccess( barcodes: List<FirebaseVisionBarcode>, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay) { graphicOverlay.clear() for (i in barcodes.indices) { // val barcode = barcodes[i] // val barcodeGraphic = BarcodeGraphic(graphicOverlay, barcode) // graphicOverlay.add(barcodeGraphic) } mutableFoundBarcodes.setOnMainThread(barcodes) } override fun onFailure(e: Exception) { log.error(e) { "Barcode detection failed" } } }
apache-2.0
7f84b01826f2e2082b37ea6ad55654ec
36.722892
100
0.731076
4.617994
false
false
false
false
google/horologist
base-ui/src/debug/java/com/google/android/horologist/base/ui/components/SecondaryChipPreview.kt
1
8469
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistBaseUiApi::class) package com.google.android.horologist.base.ui.components import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Image import androidx.compose.material.icons.materialPath import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi import com.google.android.horologist.base.ui.util.rememberVectorPainter @Preview( group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreview() { StandardChip( label = "Primary label", onClick = { }, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabel() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", chipType = StandardChipType.Secondary ) } @Preview( name = "With icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon32dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndIcon() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and large icon", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndLargeIcon() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icon32dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "Disabled", group = "Variants", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewDisabled() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = Icons.Default.Image, chipType = StandardChipType.Secondary, enabled = false ) } @Preview( name = "With long text", group = "Long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLongText() { StandardChip( label = "Primary label very very very very very very very very very very very very very very very very very long text", onClick = { }, chipType = StandardChipType.Secondary ) } @Preview( name = "With secondary label and long text", group = "Long text", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithSecondaryLabelAndLongText() { StandardChip( label = "Primary label very very very very very very very very long text", onClick = { }, secondaryLabel = "Secondary label very very very very very very very very very long text", icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "Using icon smaller than 24dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewUsingSmallIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon12dp, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon, using icon smaller than 32dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIconUsingSmallIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon12dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "Using icon larger than 24dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewUsingExtraLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon48dp, chipType = StandardChipType.Secondary ) } @Preview( name = "With large icon, using icon larger than 32dp", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithLargeIconUsingExtraLargeIcon() { StandardChip( label = "Primary label", onClick = { }, icon = Icon48dp, largeIcon = true, chipType = StandardChipType.Secondary ) } @Preview( name = "With icon placeholder ", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewWithIconPlaceholder() { StandardChip( label = "Primary label", onClick = { }, icon = Icons.Default.Image, chipType = StandardChipType.Secondary ) } @Preview( name = "Disabled with icon placeholder", group = "Icon check", backgroundColor = 0xff000000, showBackground = true ) @Composable fun SecondaryChipPreviewDisabledWithIconPlaceholder() { StandardChip( label = "Primary label", onClick = { }, secondaryLabel = "Secondary label", icon = "iconUri", placeholder = rememberVectorPainter( image = Icons.Default.Image, tintColor = Color.White ), chipType = StandardChipType.Secondary, enabled = false ) } private val Icon12dp: ImageVector get() = ImageVector.Builder( name = "Icon Small", defaultWidth = 12f.dp, defaultHeight = 12f.dp, viewportWidth = 12f, viewportHeight = 12f ) .materialPath { horizontalLineToRelative(12.0f) verticalLineToRelative(12.0f) horizontalLineTo(0.0f) close() } .build() private val Icon32dp: ImageVector get() = ImageVector.Builder( name = "Icon Large", defaultWidth = 32f.dp, defaultHeight = 32f.dp, viewportWidth = 32f, viewportHeight = 32f ) .materialPath { horizontalLineToRelative(32.0f) verticalLineToRelative(32.0f) horizontalLineTo(0.0f) close() } .build() private val Icon48dp: ImageVector get() = ImageVector.Builder( name = "Icon Extra Large", defaultWidth = 48f.dp, defaultHeight = 48f.dp, viewportWidth = 48f, viewportHeight = 48f ) .materialPath { horizontalLineToRelative(48.0f) verticalLineToRelative(48.0f) horizontalLineTo(0.0f) close() } .build()
apache-2.0
1ef630f017f1c7b0dc50c55365e9fc31
24.663636
127
0.64742
4.514392
false
false
false
false
android/camera-samples
CameraXVideo/app/src/main/java/com/example/android/camerax/video/fragments/CaptureFragment.kt
1
22606
/** * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Simple app to demonstrate CameraX Video capturing with Recorder ( to local files ), with the * following simple control follow: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ package com.example.android.camerax.video.fragments import android.annotation.SuppressLint import android.content.ContentValues import android.content.res.Configuration import java.text.SimpleDateFormat import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.Navigation import com.example.android.camerax.video.R import com.example.android.camerax.video.databinding.FragmentCaptureBinding import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.video.* import androidx.concurrent.futures.await import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.util.Consumer import androidx.core.view.updateLayoutParams import androidx.lifecycle.MutableLiveData import androidx.lifecycle.whenCreated import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.camera.utils.GenericListAdapter import com.example.android.camerax.video.extensions.getAspectRatio import com.example.android.camerax.video.extensions.getAspectRatioString import com.example.android.camerax.video.extensions.getNameString import kotlinx.coroutines.* import java.util.* class CaptureFragment : Fragment() { // UI with ViewBinding private var _captureViewBinding: FragmentCaptureBinding? = null private val captureViewBinding get() = _captureViewBinding!! private val captureLiveStatus = MutableLiveData<String>() /** Host's navigation controller */ private val navController: NavController by lazy { Navigation.findNavController(requireActivity(), R.id.fragment_container) } private val cameraCapabilities = mutableListOf<CameraCapability>() private lateinit var videoCapture: VideoCapture<Recorder> private var currentRecording: Recording? = null private lateinit var recordingState:VideoRecordEvent // Camera UI states and inputs enum class UiState { IDLE, // Not recording, all UI controls are active. RECORDING, // Camera is recording, only display Pause/Resume & Stop button. FINALIZED, // Recording just completes, disable all RECORDING UI controls. RECOVERY // For future use. } private var cameraIndex = 0 private var qualityIndex = DEFAULT_QUALITY_IDX private var audioEnabled = false private val mainThreadExecutor by lazy { ContextCompat.getMainExecutor(requireContext()) } private var enumerationDeferred:Deferred<Unit>? = null // main cameraX capture functions /** * Always bind preview + video capture use case combinations in this sample * (VideoCapture can work on its own). The function should always execute on * the main thread. */ private suspend fun bindCaptureUsecase() { val cameraProvider = ProcessCameraProvider.getInstance(requireContext()).await() val cameraSelector = getCameraSelector(cameraIndex) // create the user required QualitySelector (video resolution): we know this is // supported, a valid qualitySelector will be created. val quality = cameraCapabilities[cameraIndex].qualities[qualityIndex] val qualitySelector = QualitySelector.from(quality) captureViewBinding.previewView.updateLayoutParams<ConstraintLayout.LayoutParams> { val orientation = [email protected] dimensionRatio = quality.getAspectRatioString(quality, (orientation == Configuration.ORIENTATION_PORTRAIT)) } val preview = Preview.Builder() .setTargetAspectRatio(quality.getAspectRatio(quality)) .build().apply { setSurfaceProvider(captureViewBinding.previewView.surfaceProvider) } // build a recorder, which can: // - record video/audio to MediaStore(only shown here), File, ParcelFileDescriptor // - be used create recording(s) (the recording performs recording) val recorder = Recorder.Builder() .setQualitySelector(qualitySelector) .build() videoCapture = VideoCapture.withOutput(recorder) try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle( viewLifecycleOwner, cameraSelector, videoCapture, preview ) } catch (exc: Exception) { // we are on main thread, let's reset the controls on the UI. Log.e(TAG, "Use case binding failed", exc) resetUIandState("bindToLifecycle failed: $exc") } enableUI(true) } /** * Kick start the video recording * - config Recorder to capture to MediaStoreOutput * - register RecordEvent Listener * - apply audio request from user * - start recording! * After this function, user could start/pause/resume/stop recording and application listens * to VideoRecordEvent for the current recording status. */ @SuppressLint("MissingPermission") private fun startRecording() { // create MediaStoreOutputOptions for our recorder: resulting our recording! val name = "CameraX-recording-" + SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) + ".mp4" val contentValues = ContentValues().apply { put(MediaStore.Video.Media.DISPLAY_NAME, name) } val mediaStoreOutput = MediaStoreOutputOptions.Builder( requireActivity().contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() // configure Recorder and Start recording to the mediaStoreOutput. currentRecording = videoCapture.output .prepareRecording(requireActivity(), mediaStoreOutput) .apply { if (audioEnabled) withAudioEnabled() } .start(mainThreadExecutor, captureListener) Log.i(TAG, "Recording started") } /** * CaptureEvent listener. */ private val captureListener = Consumer<VideoRecordEvent> { event -> // cache the recording state if (event !is VideoRecordEvent.Status) recordingState = event updateUI(event) if (event is VideoRecordEvent.Finalize) { // display the captured video lifecycleScope.launch { navController.navigate( CaptureFragmentDirections.actionCaptureToVideoViewer( event.outputResults.outputUri ) ) } } } /** * Retrieve the asked camera's type(lens facing type). In this sample, only 2 types: * idx is even number: CameraSelector.LENS_FACING_BACK * odd number: CameraSelector.LENS_FACING_FRONT */ private fun getCameraSelector(idx: Int) : CameraSelector { if (cameraCapabilities.size == 0) { Log.i(TAG, "Error: This device does not have any camera, bailing out") requireActivity().finish() } return (cameraCapabilities[idx % cameraCapabilities.size].camSelector) } data class CameraCapability(val camSelector: CameraSelector, val qualities:List<Quality>) /** * Query and cache this platform's camera capabilities, run only once. */ init { enumerationDeferred = lifecycleScope.async { whenCreated { val provider = ProcessCameraProvider.getInstance(requireContext()).await() provider.unbindAll() for (camSelector in arrayOf( CameraSelector.DEFAULT_BACK_CAMERA, CameraSelector.DEFAULT_FRONT_CAMERA )) { try { // just get the camera.cameraInfo to query capabilities // we are not binding anything here. if (provider.hasCamera(camSelector)) { val camera = provider.bindToLifecycle(requireActivity(), camSelector) QualitySelector .getSupportedQualities(camera.cameraInfo) .filter { quality -> listOf(Quality.UHD, Quality.FHD, Quality.HD, Quality.SD) .contains(quality) }.also { cameraCapabilities.add(CameraCapability(camSelector, it)) } } } catch (exc: java.lang.Exception) { Log.e(TAG, "Camera Face $camSelector is not supported") } } } } } /** * One time initialize for CameraFragment (as a part of fragment layout's creation process). * This function performs the following: * - initialize but disable all UI controls except the Quality selection. * - set up the Quality selection recycler view. * - bind use cases to a lifecycle camera, enable UI controls. */ private fun initCameraFragment() { initializeUI() viewLifecycleOwner.lifecycleScope.launch { if (enumerationDeferred != null) { enumerationDeferred!!.await() enumerationDeferred = null } initializeQualitySectionsUI() bindCaptureUsecase() } } /** * Initialize UI. Preview and Capture actions are configured in this function. * Note that preview and capture are both initialized either by UI or CameraX callbacks * (except the very 1st time upon entering to this fragment in onCreateView() */ @SuppressLint("ClickableViewAccessibility", "MissingPermission") private fun initializeUI() { captureViewBinding.cameraButton.apply { setOnClickListener { cameraIndex = (cameraIndex + 1) % cameraCapabilities.size // camera device change is in effect instantly: // - reset quality selection // - restart preview qualityIndex = DEFAULT_QUALITY_IDX initializeQualitySectionsUI() enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } isEnabled = false } // audioEnabled by default is disabled. captureViewBinding.audioSelection.isChecked = audioEnabled captureViewBinding.audioSelection.setOnClickListener { audioEnabled = captureViewBinding.audioSelection.isChecked } // React to user touching the capture button captureViewBinding.captureButton.apply { setOnClickListener { if (!this@CaptureFragment::recordingState.isInitialized || recordingState is VideoRecordEvent.Finalize) { enableUI(false) // Our eventListener will turn on the Recording UI. startRecording() } else { when (recordingState) { is VideoRecordEvent.Start -> { currentRecording?.pause() captureViewBinding.stopButton.visibility = View.VISIBLE } is VideoRecordEvent.Pause -> currentRecording?.resume() is VideoRecordEvent.Resume -> currentRecording?.pause() else -> throw IllegalStateException("recordingState in unknown state") } } } isEnabled = false } captureViewBinding.stopButton.apply { setOnClickListener { // stopping: hide it after getting a click before we go to viewing fragment captureViewBinding.stopButton.visibility = View.INVISIBLE if (currentRecording == null || recordingState is VideoRecordEvent.Finalize) { return@setOnClickListener } val recording = currentRecording if (recording != null) { recording.stop() currentRecording = null } captureViewBinding.captureButton.setImageResource(R.drawable.ic_start) } // ensure the stop button is initialized disabled & invisible visibility = View.INVISIBLE isEnabled = false } captureLiveStatus.observe(viewLifecycleOwner) { captureViewBinding.captureStatus.apply { post { text = it } } } captureLiveStatus.value = getString(R.string.Idle) } /** * UpdateUI according to CameraX VideoRecordEvent type: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ private fun updateUI(event: VideoRecordEvent) { val state = if (event is VideoRecordEvent.Status) recordingState.getNameString() else event.getNameString() when (event) { is VideoRecordEvent.Status -> { // placeholder: we update the UI with new status after this when() block, // nothing needs to do here. } is VideoRecordEvent.Start -> { showUI(UiState.RECORDING, event.getNameString()) } is VideoRecordEvent.Finalize-> { showUI(UiState.FINALIZED, event.getNameString()) } is VideoRecordEvent.Pause -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_resume) } is VideoRecordEvent.Resume -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_pause) } } val stats = event.recordingStats val size = stats.numBytesRecorded / 1000 val time = java.util.concurrent.TimeUnit.NANOSECONDS.toSeconds(stats.recordedDurationNanos) var text = "${state}: recorded ${size}KB, in ${time}second" if(event is VideoRecordEvent.Finalize) text = "${text}\nFile saved to: ${event.outputResults.outputUri}" captureLiveStatus.value = text Log.i(TAG, "recording event: $text") } /** * Enable/disable UI: * User could select the capture parameters when recording is not in session * Once recording is started, need to disable able UI to avoid conflict. */ private fun enableUI(enable: Boolean) { arrayOf(captureViewBinding.cameraButton, captureViewBinding.captureButton, captureViewBinding.stopButton, captureViewBinding.audioSelection, captureViewBinding.qualitySelection).forEach { it.isEnabled = enable } // disable the camera button if no device to switch if (cameraCapabilities.size <= 1) { captureViewBinding.cameraButton.isEnabled = false } // disable the resolution list if no resolution to switch if (cameraCapabilities[cameraIndex].qualities.size <= 1) { captureViewBinding.qualitySelection.apply { isEnabled = false } } } /** * initialize UI for recording: * - at recording: hide audio, qualitySelection,change camera UI; enable stop button * - otherwise: show all except the stop button */ private fun showUI(state: UiState, status:String = "idle") { captureViewBinding.let { when(state) { UiState.IDLE -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE it.cameraButton.visibility= View.VISIBLE it.audioSelection.visibility = View.VISIBLE it.qualitySelection.visibility=View.VISIBLE } UiState.RECORDING -> { it.cameraButton.visibility = View.INVISIBLE it.audioSelection.visibility = View.INVISIBLE it.qualitySelection.visibility = View.INVISIBLE it.captureButton.setImageResource(R.drawable.ic_pause) it.captureButton.isEnabled = true it.stopButton.visibility = View.VISIBLE it.stopButton.isEnabled = true } UiState.FINALIZED -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE } else -> { val errorMsg = "Error: showUI($state) is not supported" Log.e(TAG, errorMsg) return } } it.captureStatus.text = status } } /** * ResetUI (restart): * in case binding failed, let's give it another change for re-try. In future cases * we might fail and user get notified on the status */ private fun resetUIandState(reason: String) { enableUI(true) showUI(UiState.IDLE, reason) cameraIndex = 0 qualityIndex = DEFAULT_QUALITY_IDX audioEnabled = false captureViewBinding.audioSelection.isChecked = audioEnabled initializeQualitySectionsUI() } /** * initializeQualitySectionsUI(): * Populate a RecyclerView to display camera capabilities: * - one front facing * - one back facing * User selection is saved to qualityIndex, will be used * in the bindCaptureUsecase(). */ private fun initializeQualitySectionsUI() { val selectorStrings = cameraCapabilities[cameraIndex].qualities.map { it.getNameString() } // create the adapter to Quality selection RecyclerView captureViewBinding.qualitySelection.apply { layoutManager = LinearLayoutManager(context) adapter = GenericListAdapter( selectorStrings, itemLayoutId = R.layout.video_quality_item ) { holderView, qcString, position -> holderView.apply { findViewById<TextView>(R.id.qualityTextView)?.text = qcString // select the default quality selector isSelected = (position == qualityIndex) } holderView.setOnClickListener { view -> if (qualityIndex == position) return@setOnClickListener captureViewBinding.qualitySelection.let { // deselect the previous selection on UI. it.findViewHolderForAdapterPosition(qualityIndex) ?.itemView ?.isSelected = false } // turn on the new selection on UI. view.isSelected = true qualityIndex = position // rebind the use cases to put the new QualitySelection in action. enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } } isEnabled = false } } // System function implementations override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _captureViewBinding = FragmentCaptureBinding.inflate(inflater, container, false) return captureViewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCameraFragment() } override fun onDestroyView() { _captureViewBinding = null super.onDestroyView() } companion object { // default Quality selection if no input from UI const val DEFAULT_QUALITY_IDX = 0 val TAG:String = CaptureFragment::class.java.simpleName private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" } }
apache-2.0
7acf53df8bb06fbe20a0592b51d2fead
39.95471
99
0.613996
5.427611
false
false
false
false
xfournet/intellij-community
plugins/git4idea/src/git4idea/GitApplyChangesProcess.kt
1
19590
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.pluralize import com.intellij.openapi.vcs.AbstractVcsHelper import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.merge.MergeDialogCustomizer import com.intellij.openapi.vcs.update.RefreshVFsSynchronously import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.Hash import com.intellij.vcs.log.VcsFullCommitDetails import com.intellij.vcs.log.util.VcsUserUtil import com.intellij.vcsUtil.VcsUtil import git4idea.commands.* import git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT import git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK import git4idea.merge.GitConflictResolver import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.util.GitUntrackedFilesHelper import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import javax.swing.event.HyperlinkEvent /** * Applies the given Git operation (e.g. cherry-pick or revert) to the current working tree, * waits for the [ChangeListManager] update, shows the commit dialog and removes the changelist after commit, * if the commit was successful. */ class GitApplyChangesProcess(private val project: Project, private val commits: List<VcsFullCommitDetails>, private val autoCommit: Boolean, private val operationName: String, private val appliedWord: String, private val command: (GitRepository, Hash, Boolean, List<GitLineHandlerListener>) -> GitCommandResult, private val emptyCommitDetector: (GitCommandResult) -> Boolean, private val defaultCommitMessageGenerator: (VcsFullCommitDetails) -> String, private val preserveCommitMetadata: Boolean, private val cleanupBeforeCommit: (GitRepository) -> Unit = {}) { private val LOG = logger<GitApplyChangesProcess>() private val git = Git.getInstance() private val repositoryManager = GitRepositoryManager.getInstance(project) private val vcsNotifier = VcsNotifier.getInstance(project) private val changeListManager = ChangeListManager.getInstance(project) as ChangeListManagerEx private val vcsHelper = AbstractVcsHelper.getInstance(project) fun execute() { val commitsInRoots = DvcsUtil.groupCommitsByRoots<GitRepository>(repositoryManager, commits) LOG.info("${operationName}ing commits: " + toString(commitsInRoots)) val successfulCommits = mutableListOf<VcsFullCommitDetails>() val skippedCommits = mutableListOf<VcsFullCommitDetails>() DvcsUtil.workingTreeChangeStarted(project, operationName).use { for ((repository, value) in commitsInRoots) { val result = executeForRepo(repository, value, successfulCommits, skippedCommits) repository.update() if (!result) { return } } notifyResult(successfulCommits, skippedCommits) } } // return true to continue with other roots, false to break execution private fun executeForRepo(repository: GitRepository, commits: List<VcsFullCommitDetails>, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { for (commit in commits) { val conflictDetector = GitSimpleEventDetector(CHERRY_PICK_CONFLICT) val localChangesOverwrittenDetector = GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK) val untrackedFilesDetector = GitUntrackedFilesOverwrittenByOperationDetector(repository.root) val commitMessage = defaultCommitMessageGenerator(commit) val changeList = createChangeList(commitMessage, commit) val previousDefaultChangelist = changeListManager.defaultChangeList try { changeListManager.defaultChangeList = changeList val result = command(repository, commit.id, autoCommit, listOf(conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector)) if (result.success()) { if (autoCommit) { successfulCommits.add(commit) } else { refreshVfsAndMarkDirty(repository) waitForChangeListManagerUpdate() val committed = commit(repository, commit, commitMessage, changeList, successfulCommits, alreadyPicked) if (!committed) return false } } else if (conflictDetector.hasHappened()) { val mergeCompleted = ConflictResolver(project, git, repository.root, commit.id.asString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject, operationName).merge() refreshVfsAndMarkDirty(repository) waitForChangeListManagerUpdate() if (mergeCompleted) { LOG.debug("All conflicts resolved, will show commit dialog. Current default changelist is [$changeList]") val committed = commit(repository, commit, commitMessage, changeList, successfulCommits, alreadyPicked) if (!committed) return false } else { notifyConflictWarning(repository, commit, successfulCommits) return false } } else if (untrackedFilesDetector.wasMessageDetected()) { var description = getSuccessfulCommitDetailsIfAny(successfulCommits) GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, repository.root, untrackedFilesDetector.relativeFilePaths, operationName, description) return false } else if (localChangesOverwrittenDetector.hasHappened()) { notifyError("Your local changes would be overwritten by $operationName.<br/>Commit your changes or stash them to proceed.", commit, successfulCommits) return false } else if (emptyCommitDetector(result)) { alreadyPicked.add(commit) } else { notifyError(result.errorOutputAsHtmlString, commit, successfulCommits) return false } } finally { changeListManager.defaultChangeList = previousDefaultChangelist removeChangeListIfEmpty(changeList) } } return true } private fun createChangeList(commitMessage: String, commit: VcsFullCommitDetails): LocalChangeList { val changeListName = createNameForChangeList(project, commitMessage) val changeListData = if (preserveCommitMetadata) createChangeListData(commit) else null return changeListManager.addChangeList(changeListName, commitMessage, changeListData) } private fun commit(repository: GitRepository, commit: VcsFullCommitDetails, commitMessage: String, changeList: LocalChangeList, successfulCommits: MutableList<VcsFullCommitDetails>, alreadyPicked: MutableList<VcsFullCommitDetails>): Boolean { val actualList = changeListManager.getChangeList(changeList.id) if (actualList == null) { LOG.error("Couldn't find the changelist with id ${changeList.id} and name ${changeList.name} among " + changeListManager.changeLists.joinToString { "${it.id} ${it.name}" }) return false } val changes = actualList.changes if (changes.isEmpty()) { LOG.debug("No changes in the $actualList. All changes in the CLM: ${getAllChangesInLogFriendlyPresentation(changeListManager)}") alreadyPicked.add(commit) return true } LOG.debug("Showing commit dialog for changes: ${changes}") val committed = showCommitDialogAndWaitForCommit(repository, changeList, commitMessage, changes) if (committed) { refreshVfsAndMarkDirty(changes) waitForChangeListManagerUpdate() successfulCommits.add(commit) return true } else { notifyCommitCancelled(commit, successfulCommits) return false } } private fun getAllChangesInLogFriendlyPresentation(changeListManagerEx: ChangeListManagerEx) = changeListManagerEx.changeLists.map { it -> "[${it.name}] ${it.changes}" } private fun waitForChangeListManagerUpdate() { val waiter = CountDownLatch(1) changeListManager.invokeAfterUpdate({ waiter.countDown() }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, operationName.capitalize(), ModalityState.NON_MODAL) var success = false while (!success) { ProgressManager.checkCanceled() try { success = waiter.await(50, TimeUnit.MILLISECONDS) } catch (e: InterruptedException) { LOG.warn(e) throw ProcessCanceledException(e) } } } private fun refreshVfsAndMarkDirty(repository: GitRepository) { VfsUtil.markDirtyAndRefresh(false, true, false, repository.root) VcsDirtyScopeManager.getInstance(project).filePathsDirty(null, listOf(VcsUtil.getFilePath(repository.root))) } private fun refreshVfsAndMarkDirty(changes: Collection<Change>) { RefreshVFsSynchronously.updateChanges(changes) VcsDirtyScopeManager.getInstance(project).filePathsDirty(ChangesUtil.getPaths(changes), null) } private fun removeChangeListIfEmpty(changeList: LocalChangeList) { val actualList = changeListManager.getChangeList(changeList.id) if (actualList != null && actualList.changes.isEmpty()) { LOG.debug("Changelist $actualList is empty, removing. " + "All changes in the CLM: ${getAllChangesInLogFriendlyPresentation(changeListManager)}") changeListManager.removeChangeList(actualList) } } private fun showCommitDialogAndWaitForCommit(repository: GitRepository, changeList: LocalChangeList, commitMessage: String, changes: Collection<Change>): Boolean { val commitSucceeded = AtomicBoolean() val sem = Semaphore(0) ApplicationManager.getApplication().invokeAndWait({ try { cleanupBeforeCommit(repository) val commitNotCancelled = vcsHelper.commitChanges(changes, changeList, commitMessage, object : CommitResultHandler { override fun onSuccess(commitMessage1: String) { commitSucceeded.set(true) sem.release() } override fun onFailure() { commitSucceeded.set(false) sem.release() } }) if (!commitNotCancelled) { commitSucceeded.set(false) sem.release() } } catch (t: Throwable) { LOG.error(t) commitSucceeded.set(false) sem.release() } }, ModalityState.NON_MODAL) // need additional waiting, because commitChanges is asynchronous try { sem.acquire() } catch (e: InterruptedException) { LOG.error(e) return false } return commitSucceeded.get() } private fun createChangeListData(commit: VcsFullCommitDetails) = ChangeListData(commit.author, Date(commit.authorTime)) private fun notifyResult(successfulCommits: List<VcsFullCommitDetails>, skipped: List<VcsFullCommitDetails>) { if (skipped.isEmpty()) { vcsNotifier.notifySuccess("${operationName.capitalize()} successful", getCommitsDetails(successfulCommits)) } else if (!successfulCommits.isEmpty()) { val title = String.format("${operationName.capitalize()}ed %d commits from %d", successfulCommits.size, successfulCommits.size + skipped.size) val description = getCommitsDetails(successfulCommits) + "<hr/>" + formSkippedDescription(skipped, true) vcsNotifier.notifySuccess(title, description) } else { vcsNotifier.notifyImportantWarning("Nothing to $operationName", formSkippedDescription(skipped, false)) } } private fun notifyConflictWarning(repository: GitRepository, commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { val resolveLinkListener = ResolveLinkListener(repository.root, commit.id.toShortString(), VcsUserUtil.getShortPresentation(commit.author), commit.subject) var description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>" description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyImportantWarning("${operationName.capitalize()}ed with conflicts", description, resolveLinkListener) } private fun notifyCommitCancelled(commit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { if (successfulCommits.isEmpty()) { // don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue. return } var description = commitDetails(commit) description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyMinorWarning("${operationName.capitalize()} cancelled", description, null) } private fun notifyError(content: String, failedCommit: VcsFullCommitDetails, successfulCommits: List<VcsFullCommitDetails>) { var description = commitDetails(failedCommit) + "<br/>" + content description += getSuccessfulCommitDetailsIfAny(successfulCommits) vcsNotifier.notifyError("${operationName.capitalize()} Failed", description) } private fun getSuccessfulCommitDetailsIfAny(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" if (!successfulCommits.isEmpty()) { description += "<hr/>However ${operationName} succeeded for the following " + pluralize("commit", successfulCommits.size) + ":<br/>" description += getCommitsDetails(successfulCommits) } return description } private fun formSkippedDescription(skipped: List<VcsFullCommitDetails>, but: Boolean): String { val hashes = StringUtil.join(skipped, { commit -> commit.id.toShortString() }, ", ") if (but) { val was = if (skipped.size == 1) "was" else "were" val it = if (skipped.size == 1) "it" else "them" return String.format("%s %s skipped, because all changes have already been ${appliedWord}.", hashes, was, it) } return String.format("All changes from %s have already been ${appliedWord}", hashes) } private fun getCommitsDetails(successfulCommits: List<VcsFullCommitDetails>): String { var description = "" for (commit in successfulCommits) { description += commitDetails(commit) + "<br/>" } return description.substring(0, description.length - "<br/>".length) } private fun commitDetails(commit: VcsFullCommitDetails): String { return commit.id.toShortString() + " " + StringUtil.escapeXml(commit.subject) } private fun toString(commitsInRoots: Map<GitRepository, List<VcsFullCommitDetails>>): String { return commitsInRoots.entries.joinToString("; ") { entry -> val commits = entry.value.joinToString { it.id.asString() } getShortRepositoryName(entry.key) + ": [" + commits + "]" } } private inner class ResolveLinkListener(private val root: VirtualFile, private val hash: String, private val author: String, private val message: String) : NotificationListener { override fun hyperlinkUpdate(notification: Notification, event: HyperlinkEvent) { if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) { if (event.description == "resolve") { GitApplyChangesProcess.ConflictResolver(project, git, root, hash, author, message, operationName).mergeNoProceed() } } } } class ConflictResolver(project: Project, git: Git, root: VirtualFile, commitHash: String, commitAuthor: String, commitMessage: String, operationName: String ) : GitConflictResolver(project, git, setOf(root), makeParams(commitHash, commitAuthor, commitMessage, operationName)) { override fun notifyUnresolvedRemain() {/* we show a [possibly] compound notification after applying all commits.*/ } } } private fun makeParams(commitHash: String, commitAuthor: String, commitMessage: String, operationName: String): GitConflictResolver.Params { val params = GitConflictResolver.Params() params.setErrorNotificationTitle("${operationName.capitalize()}ed with conflicts") params.setMergeDialogCustomizer(MergeDialogCustomizer(commitHash, commitAuthor, commitMessage, operationName)) return params } private class MergeDialogCustomizer(private val commitHash: String, private val commitAuthor: String, private val commitMessage: String, private val operationName: String) : MergeDialogCustomizer() { override fun getMultipleFileMergeDescription(files: Collection<VirtualFile>) = "<html>Conflicts during ${operationName}ing commit <code>$commitHash</code> " + "made by $commitAuthor<br/><code>\"$commitMessage\"</code></html>" override fun getLeftPanelTitle(file: VirtualFile) = "Local changes" override fun getRightPanelTitle(file: VirtualFile, revisionNumber: VcsRevisionNumber?) = "<html>Changes from $operationName <code>$commitHash</code>" }
apache-2.0
f7cc5abb9b7a2f251b218e6e480d48f7
44.138249
140
0.681827
5.294595
false
false
false
false
Commit451/LabCoat
app/src/main/java/com/commit451/gitlab/ssl/CustomTrustManager.kt
2
2592
package com.commit451.gitlab.ssl import com.commit451.gitlab.api.X509TrustManagerProvider import java.security.cert.CertificateException import java.security.cert.X509Certificate import javax.net.ssl.* /** * Allows for custom configurations, such as custom trusted hostnames, custom trusted certificates, * and private keys */ class CustomTrustManager : X509TrustManager { private var trustedCertificate: String? = null private var trustedHostname: String? = null private var sslSocketFactory: SSLSocketFactory? = null private var hostnameVerifier: HostnameVerifier? = null fun setTrustedCertificate(trustedCertificate: String) { this.trustedCertificate = trustedCertificate sslSocketFactory = null } fun setTrustedHostname(trustedHostname: String) { this.trustedHostname = trustedHostname hostnameVerifier = null } @Throws(CertificateException::class) override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) { X509TrustManagerProvider.x509TrustManager.checkClientTrusted(chain, authType) } @Throws(CertificateException::class) override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) { val cause: CertificateException try { X509TrustManagerProvider.x509TrustManager.checkServerTrusted(chain, authType) return } catch (e: CertificateException) { cause = e } if (trustedCertificate != null && trustedCertificate == X509Util.getFingerPrint(chain[0])) { return } throw X509CertificateException(cause.message!!, cause, chain) } override fun getAcceptedIssuers(): Array<X509Certificate> { return X509TrustManagerProvider.x509TrustManager.acceptedIssuers } fun getSSLSocketFactory(): SSLSocketFactory { if (sslSocketFactory != null) { return sslSocketFactory!! } val keyManagers: Array<KeyManager>? = null try { val sslContext = SSLContext.getInstance("TLS") sslContext.init(keyManagers, arrayOf<TrustManager>(this), null) sslSocketFactory = CustomSSLSocketFactory(sslContext.socketFactory) } catch (e: Exception) { throw IllegalStateException(e) } return sslSocketFactory!! } fun getHostnameVerifier(): HostnameVerifier { if (hostnameVerifier == null) { hostnameVerifier = CustomHostnameVerifier(trustedHostname) } return hostnameVerifier!! } }
apache-2.0
11c9685f50a5e2d6fdf7f3656da15395
31.4
100
0.691358
5.236364
false
false
false
false
google/ksp
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/kotlin/KSTypeReferenceImpl.kt
1
6220
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.symbol.impl.kotlin import com.google.devtools.ksp.ExceptionMessage import com.google.devtools.ksp.KSObjectCache import com.google.devtools.ksp.memoized import com.google.devtools.ksp.processing.impl.ResolverImpl import com.google.devtools.ksp.symbol.KSAnnotation import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.KSReferenceElement import com.google.devtools.ksp.symbol.KSType import com.google.devtools.ksp.symbol.KSTypeReference import com.google.devtools.ksp.symbol.KSVisitor import com.google.devtools.ksp.symbol.Location import com.google.devtools.ksp.symbol.Modifier import com.google.devtools.ksp.symbol.Origin import com.google.devtools.ksp.symbol.impl.toLocation import com.google.devtools.ksp.toKSModifiers import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDynamicType import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtFunctionType import org.jetbrains.kotlin.psi.KtNullableType import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtTypeAlias import org.jetbrains.kotlin.psi.KtTypeParameter import org.jetbrains.kotlin.psi.KtTypeProjection import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.KtUserType class KSTypeReferenceImpl private constructor(val ktTypeReference: KtTypeReference) : KSTypeReference { companion object : KSObjectCache<KtTypeReference, KSTypeReferenceImpl>() { fun getCached(ktTypeReference: KtTypeReference) = cache.getOrPut(ktTypeReference) { KSTypeReferenceImpl(ktTypeReference) } } override val origin = Origin.KOTLIN override val location: Location by lazy { ktTypeReference.toLocation() } override val parent: KSNode? by lazy { var parentPsi = ktTypeReference.parent while ( parentPsi != null && parentPsi !is KtAnnotationEntry && parentPsi !is KtFunctionType && parentPsi !is KtClassOrObject && parentPsi !is KtFunction && parentPsi !is KtUserType && parentPsi !is KtProperty && parentPsi !is KtTypeAlias && parentPsi !is KtTypeProjection && parentPsi !is KtTypeParameter && parentPsi !is KtParameter ) { parentPsi = parentPsi.parent } when (parentPsi) { is KtAnnotationEntry -> KSAnnotationImpl.getCached(parentPsi) is KtFunctionType -> KSCallableReferenceImpl.getCached(parentPsi) is KtClassOrObject -> KSClassDeclarationImpl.getCached(parentPsi) is KtFunction -> KSFunctionDeclarationImpl.getCached(parentPsi) is KtUserType -> KSClassifierReferenceImpl.getCached(parentPsi) is KtProperty -> KSPropertyDeclarationImpl.getCached(parentPsi) is KtTypeAlias -> KSTypeAliasImpl.getCached(parentPsi) is KtTypeProjection -> KSTypeArgumentKtImpl.getCached(parentPsi) is KtTypeParameter -> KSTypeParameterImpl.getCached(parentPsi) is KtParameter -> KSValueParameterImpl.getCached(parentPsi) else -> null } } // Parenthesized type in grammar seems to be implemented as KtNullableType. private fun visitNullableType(visit: (KtNullableType) -> Unit) { var typeElement = ktTypeReference.typeElement while (typeElement is KtNullableType) { visit(typeElement) typeElement = typeElement.innerType } } // Annotations and modifiers are only allowed in one of the parenthesized type. // https://github.com/JetBrains/kotlin/blob/50e12239ef8141a45c4dca2bf0544be6191ecfb6/compiler/frontend/src/org/jetbrains/kotlin/diagnostics/rendering/DefaultErrorMessages.java#L608 override val annotations: Sequence<KSAnnotation> by lazy { fun List<KtAnnotationEntry>.toKSAnnotations(): Sequence<KSAnnotation> = asSequence().map { KSAnnotationImpl.getCached(it) } val innerAnnotations = mutableListOf<Sequence<KSAnnotation>>() visitNullableType { innerAnnotations.add(it.annotationEntries.toKSAnnotations()) } (ktTypeReference.annotationEntries.toKSAnnotations() + innerAnnotations.asSequence().flatten()).memoized() } override val modifiers: Set<Modifier> by lazy { val innerModifiers = mutableSetOf<Modifier>() visitNullableType { innerModifiers.addAll(it.modifierList.toKSModifiers()) } ktTypeReference.toKSModifiers() + innerModifiers } override val element: KSReferenceElement by lazy { var typeElement = ktTypeReference.typeElement while (typeElement is KtNullableType) typeElement = typeElement.innerType when (typeElement) { is KtFunctionType -> KSCallableReferenceImpl.getCached(typeElement) is KtUserType -> KSClassifierReferenceImpl.getCached(typeElement) is KtDynamicType -> KSDynamicReferenceImpl.getCached(this) else -> throw IllegalStateException("Unexpected type element ${typeElement?.javaClass}, $ExceptionMessage") } } override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitTypeReference(this, data) } override fun resolve(): KSType = ResolverImpl.instance!!.resolveUserType(this) override fun toString(): String { return element.toString() } }
apache-2.0
d8b966716bf22a39ba2507c3700c78ae
43.428571
184
0.729904
4.886096
false
false
false
false
beyama/winter
winter/src/main/kotlin/io/jentz/winter/TypeKey.kt
1
2193
package io.jentz.winter import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Interface for all type keys. */ interface TypeKey<out R : Any> { val qualifier: Any? /** * Test if [other] has the same type. * Like [equals] without looking onto the [qualifier]. */ fun typeEquals(other: TypeKey<*>): Boolean } class ClassTypeKey<R : Any> @JvmOverloads constructor( val type: Class<R>, override val qualifier: Any? = null ) : TypeKey<R> { private var _hashCode = 0 override fun typeEquals(other: TypeKey<*>): Boolean { if (other === this) return true if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) if (other !is ClassTypeKey) return false return other.type == type } override fun equals(other: Any?): Boolean { return other is TypeKey<*> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type, qualifier) } return _hashCode } override fun toString(): String = "ClassTypeKey($type qualifier = $qualifier)" } abstract class GenericClassTypeKey<R : Any> @JvmOverloads constructor( override val qualifier: Any? = null ) : TypeKey<R> { private var _hashCode = 0 val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] override fun typeEquals(other: TypeKey<*>): Boolean { if (other === this) return true if (other is ClassTypeKey) return Types.equals(other.type, type) if (other is GenericClassTypeKey<*>) return Types.equals(type, other.type) return false } override fun equals(other: Any?): Boolean { return other is TypeKey<*> && other.qualifier == qualifier && typeEquals(other) } override fun hashCode(): Int { if (_hashCode == 0) { _hashCode = Types.hashCode(type) _hashCode = 31 * _hashCode + (qualifier?.hashCode() ?: 0) } return _hashCode } override fun toString(): String = "GenericClassTypeKey($type qualifier = $qualifier)" }
apache-2.0
a0a7c188787533b7509570b605a5a76c
27.115385
94
0.632011
4.266537
false
false
false
false
chrisbanes/tivi
data/src/main/java/app/tivi/data/entities/RecommendedShowEntry.kt
1
1438
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.data.entities import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import app.tivi.data.PaginatedEntry @Entity( tableName = "recommended_entries", indices = [ Index(value = ["show_id"], unique = true) ], foreignKeys = [ ForeignKey( entity = TiviShow::class, parentColumns = arrayOf("id"), childColumns = arrayOf("show_id"), onUpdate = ForeignKey.CASCADE, onDelete = ForeignKey.CASCADE ) ] ) data class RecommendedShowEntry( @PrimaryKey(autoGenerate = true) override val id: Long = 0, @ColumnInfo(name = "show_id") override val showId: Long, @ColumnInfo(name = "page") override val page: Int ) : PaginatedEntry
apache-2.0
9a85ed1814f6aa366d176c7ae3d852db
30.955556
75
0.690542
4.241888
false
false
false
false
wuseal/JsonToKotlinClass
src/main/kotlin/wu/seal/jsontokotlin/interceptor/annotations/jackson/AddJacksonAnnotationInterceptor.kt
1
1058
package wu.seal.jsontokotlin.interceptor.annotations.jackson import wu.seal.jsontokotlin.model.classscodestruct.DataClass import wu.seal.jsontokotlin.model.codeannotations.JacksonPropertyAnnotationTemplate import wu.seal.jsontokotlin.model.codeelements.KPropertyName import wu.seal.jsontokotlin.interceptor.IKotlinClassInterceptor import wu.seal.jsontokotlin.model.classscodestruct.KotlinClass class AddJacksonAnnotationInterceptor : IKotlinClassInterceptor<KotlinClass> { override fun intercept(kotlinClass: KotlinClass): KotlinClass { if (kotlinClass is DataClass) { val addMoshiCodeGenAnnotationProperties = kotlinClass.properties.map { val camelCaseName = KPropertyName.makeLowerCamelCaseLegalName(it.originName) it.copy(annotations = JacksonPropertyAnnotationTemplate(it.originName).getAnnotations(),name = camelCaseName) } return kotlinClass.copy(properties = addMoshiCodeGenAnnotationProperties) } else { return kotlinClass } } }
gpl-3.0
9d957bb5b4ec7ba44a5d758f1f2551ed
38.185185
126
0.765595
5.263682
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/client/Java8HttpClient.kt
1
3226
package org.http4k.client import org.http4k.core.Body import org.http4k.core.HttpHandler import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status import org.http4k.core.Status.Companion.CLIENT_TIMEOUT import org.http4k.core.Status.Companion.CONNECTION_REFUSED import org.http4k.core.Status.Companion.UNKNOWN_HOST import java.io.ByteArrayInputStream import java.net.ConnectException import java.net.HttpURLConnection import java.net.SocketTimeoutException import java.net.URL import java.net.UnknownHostException import java.nio.ByteBuffer import java.time.Duration import java.time.Duration.ZERO /** * Use this legacy Java client when you're not yet on Java 11. */ object Java8HttpClient { @JvmStatic @JvmName("create") operator fun invoke(): HttpHandler = invoke(ZERO) @JvmStatic @JvmName("createWithTimeouts") operator fun invoke( readTimeout: Duration = ZERO, connectionTimeout: Duration = ZERO ): HttpHandler = { request: Request -> try { val connection = (URL(request.uri.toString()).openConnection() as HttpURLConnection).apply { this.readTimeout = readTimeout.toMillis().toInt() this.connectTimeout = connectionTimeout.toMillis().toInt() instanceFollowRedirects = false requestMethod = request.method.name doOutput = true doInput = true request.headers.forEach { addRequestProperty(it.first, it.second) } request.body.apply { if (this != Body.EMPTY) { val content = if (stream.available() == 0) payload.array().inputStream() else stream content.copyTo(outputStream) } } } val status = Status(connection.responseCode, connection.responseMessage.orEmpty()) val baseResponse = Response(status).body(connection.body(status)) connection.headerFields .filterKeys { it != null } // because response status line comes as a header with null key (*facepalm*) .map { header -> header.value.map { header.key to it } } .flatten() .fold(baseResponse) { acc, next -> acc.header(next.first, next.second) } } catch (e: UnknownHostException) { Response(UNKNOWN_HOST.toClientStatus(e)) } catch (e: ConnectException) { Response(CONNECTION_REFUSED.toClientStatus(e)) } catch (e: SocketTimeoutException) { Response(CLIENT_TIMEOUT.toClientStatus(e)) } } // Because HttpURLConnection closes the stream if a new request is made, we are forced to consume it straight away private fun HttpURLConnection.body(status: Status) = Body(resolveStream(status).readBytes().let { ByteBuffer.wrap(it) }) private fun HttpURLConnection.resolveStream(status: Status) = when { status.serverError || status.clientError -> errorStream else -> inputStream } ?: EMPTY_STREAM private val EMPTY_STREAM = ByteArrayInputStream(ByteArray(0)) }
apache-2.0
2a0a3c5dfab797e8f78ea471b0b0cd7a
38.82716
119
0.642591
4.668596
false
false
false
false
http4k/http4k
src/docs/guide/howto/typesafe_your_api_with_lenses/example.kt
1
2262
package guide.howto.typesafe_your_api_with_lenses import org.http4k.core.Body import org.http4k.core.ContentType.Companion.TEXT_PLAIN import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.then import org.http4k.core.with import org.http4k.filter.ServerFilters import org.http4k.lens.Header import org.http4k.lens.Query import org.http4k.lens.boolean import org.http4k.lens.composite import org.http4k.lens.int import org.http4k.lens.string fun main() { data class Child(val name: String) data class Pageable(val sortAscending: Boolean, val page: Int, val maxResults: Int) val nameHeader = Header.required("name") val ageQuery = Query.int().optional("age") val childrenBody = Body.string(TEXT_PLAIN) .map({ it.split(",").map(::Child) }, { it.joinToString { it.name } }) .toLens() val pageable = Query.composite { Pageable( boolean().defaulted("sortAscending", true)(it), int().defaulted("page", 1)(it), int().defaulted("maxResults", 20)(it) ) } val endpoint = { request: Request -> val name: String = nameHeader(request) val age: Int? = ageQuery(request) val children: List<Child> = childrenBody(request) val pagination = pageable(request) val msg = """ $name is ${age ?: "unknown"} years old and has ${children.size} children (${children.joinToString { it.name }}) Pagination: $pagination """ Response(OK).with( Body.string(TEXT_PLAIN).toLens() of msg ) } val app = ServerFilters.CatchLensFailure.then(endpoint) val goodRequest = Request(GET, "http://localhost:9000").with( nameHeader of "Jane Doe", ageQuery of 25, childrenBody of listOf(Child("Rita"), Child("Sue")) ) println(listOf("", "Request:", goodRequest, app(goodRequest)).joinToString("\n")) val badRequest = Request(GET, "http://localhost:9000") .with(nameHeader of "Jane Doe") .query("age", "some illegal age!") println(listOf("", "Request:", badRequest, app(badRequest)).joinToString("\n")) }
apache-2.0
9ad109c0e3bed88c207e9e152684e553
31.782609
87
0.646773
3.745033
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/ui/topic/Reply.kt
1
1508
package im.fdx.v2ex.ui.topic import android.os.Parcelable import im.fdx.v2ex.ui.member.Member import kotlinx.parcelize.Parcelize /** * Created by a708 on 15-9-8. * 评论模型,用于传递从JSON获取到的数据。 * 以后将加入添加评论功能。 */ //{ // "id" : 2826846, // "thanks" : 0, // "content" : "关键你是男还是女?", // "content_rendered" : "关键你是男还是女?", // "member" : { // "id" : 27619, // "username" : "hengzhang", // "tagline" : "我白天是个民工,晚上就是个有抱负的IT人士。", // "avatar_mini" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_mini.png?m=1413707431", // "avatar_normal" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_normal.png?m=1413707431", // "avatar_large" : "//cdn.v2ex.co/avatar/d165/7a2a/27619_large.png?m=1413707431" // }, // "created" : 1453030169, // "last_modified" : 1453030169 // } @Parcelize data class Reply(var id: String = "", var content: String = "", var content_rendered: String = "", var thanks: Int = 0, var created: Long = 0, var isThanked: Boolean = false, var member: Member? = null, var isLouzu: Boolean = false, var showTime: String = "", var rowNum: Int = 0, ) : Parcelable { override fun toString() = "Reply{content='$content_rendered}" }
apache-2.0
5bfc14f65e901dda725582250f455617
30.227273
91
0.534207
2.850622
false
false
false
false
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/RuleSet.kt
1
1498
package io.gitlab.arturbosch.detekt.api import io.gitlab.arturbosch.detekt.api.internal.BaseRule import io.gitlab.arturbosch.detekt.api.internal.PathFilters import io.gitlab.arturbosch.detekt.api.internal.absolutePath import io.gitlab.arturbosch.detekt.api.internal.validateIdentifier import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.BindingContext import java.nio.file.Paths typealias RuleSetId = String /** * A rule set is a collection of rules and must be defined within a rule set provider implementation. */ class RuleSet(val id: RuleSetId, val rules: List<BaseRule>) { init { validateIdentifier(id) } /** * Is used to determine if a given [KtFile] should be analyzed at all. */ @Deprecated("Exposes detekt-core implementation details.") var pathFilters: PathFilters? = null /** * Visits given file with all rules of this rule set, returning a list * of all code smell findings. */ @Deprecated("Exposes detekt-core implementation details.") fun accept(file: KtFile, bindingContext: BindingContext = BindingContext.EMPTY): List<Finding> = if (isFileIgnored(file)) { emptyList() } else { rules.flatMap { it.visitFile(file, bindingContext) it.findings } } @Suppress("DEPRECATION") private fun isFileIgnored(file: KtFile) = pathFilters?.isIgnored(Paths.get(file.absolutePath())) == true }
apache-2.0
41f62fa839a9a4f4c097258ca81f1cf4
31.565217
101
0.690254
4.292264
false
false
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/core/util/Util.kt
1
8202
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin.core.util import io.javalin.http.Context import io.javalin.http.InternalServerErrorResponse import java.io.ByteArrayInputStream import java.io.File import java.net.URL import java.net.URLEncoder import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.* import java.util.zip.Adler32 import java.util.zip.CheckedInputStream object Util { @JvmStatic fun normalizeContextPath(contextPath: String) = ("/$contextPath").replace("/{2,}".toRegex(), "/").removeSuffix("/") @JvmStatic fun prefixContextPath(contextPath: String, path: String) = if (path == "*") path else ("$contextPath/$path").replace("/{2,}".toRegex(), "/") fun classExists(className: String) = try { Class.forName(className) true } catch (e: ClassNotFoundException) { false } private fun serviceImplementationExists(className: String) = try { val serviceClass = Class.forName(className) val loader = ServiceLoader.load(serviceClass) loader.any() } catch (e: ClassNotFoundException) { false } fun dependencyIsPresent(dependency: OptionalDependency) = try { ensureDependencyPresent(dependency) true } catch (e: Exception) { false } private val dependencyCheckCache = HashMap<String, Boolean>() fun ensureDependencyPresent(dependency: OptionalDependency, startupCheck: Boolean = false) { if (dependencyCheckCache[dependency.testClass] == true) { return } if (!classExists(dependency.testClass)) { val message = missingDependencyMessage(dependency) if (startupCheck) { throw IllegalStateException(message) } else { JavalinLogger.warn(message) throw InternalServerErrorResponse(message) } } dependencyCheckCache[dependency.testClass] = true } internal fun missingDependencyMessage(dependency: OptionalDependency) = """| |------------------------------------------------------------------- |Missing dependency '${dependency.displayName}'. Add the dependency. | |pom.xml: |<dependency> | <groupId>${dependency.groupId}</groupId> | <artifactId>${dependency.artifactId}</artifactId> | <version>${dependency.version}</version> |</dependency> | |build.gradle: |implementation group: '${dependency.groupId}', name: '${dependency.artifactId}', version: '${dependency.version}' | |Find the latest version here: |https://search.maven.org/search?q=${URLEncoder.encode("g:" + dependency.groupId + " AND a:" + dependency.artifactId, "UTF-8")} |-------------------------------------------------------------------""".trimMargin() fun pathToList(pathString: String): List<String> = pathString.split("/").filter { it.isNotEmpty() } @JvmStatic fun printHelpfulMessageIfLoggerIsMissing() { if (!loggingLibraryExists()) { System.err.println(""" |------------------------------------------------------------------- |${missingDependencyMessage(OptionalDependency.SLF4JSIMPLE)} |------------------------------------------------------------------- |OR |------------------------------------------------------------------- |${missingDependencyMessage(OptionalDependency.SLF4J_PROVIDER_API)} and |${missingDependencyMessage(OptionalDependency.SLF4J_PROVIDER_SIMPLE)} |------------------------------------------------------------------- |Visit https://javalin.io/documentation#logging if you need more help""".trimMargin()) } } fun loggingLibraryExists(): Boolean { return classExists(OptionalDependency.SLF4JSIMPLE.testClass) || serviceImplementationExists(OptionalDependency.SLF4J_PROVIDER_API.testClass) } @JvmStatic fun logJavalinBanner(showBanner: Boolean) { if (showBanner) JavalinLogger.info("\n" + """ | __ __ _ __ __ | / /____ _ _ __ ____ _ / /(_)____ / // / | __ / // __ `/| | / // __ `// // // __ \ / // /_ |/ /_/ // /_/ / | |/ // /_/ // // // / / / /__ __/ |\____/ \__,_/ |___/ \__,_//_//_//_/ /_/ /_/ | | https://javalin.io/documentation |""".trimMargin()) } @JvmStatic fun logJavalinVersion() = try { val properties = Properties().also { val propertiesPath = "META-INF/maven/io.javalin/javalin/pom.properties" it.load(this.javaClass.classLoader.getResourceAsStream(propertiesPath)) } val (version, buildTime) = listOf(properties.getProperty("version")!!, properties.getProperty("buildTime")!!) JavalinLogger.startup("You are running Javalin $version (released ${formatBuildTime(buildTime)}).") } catch (e: Exception) { // it's not that important } private fun formatBuildTime(buildTime: String): String? = try { val (release, now) = listOf(Instant.parse(buildTime), Instant.now()) val formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy").withLocale(Locale.US).withZone(ZoneId.of("Z")) formatter.format(release) + if (now.isAfter(release.plus(90, ChronoUnit.DAYS))) { ". Your Javalin version is ${ChronoUnit.DAYS.between(release, now)} days old. Consider checking for a newer version." } else "" } catch (e: Exception) { null // it's not that important } fun getChecksumAndReset(inputStream: ByteArrayInputStream): String { inputStream.mark(Int.MAX_VALUE) //it's all in memory so there is no readAheadLimit val cis = CheckedInputStream(inputStream, Adler32()) var byte = cis.read() while (byte > -1) { byte = cis.read() } inputStream.reset() return cis.checksum.value.toString() } @JvmStatic fun getResourceUrl(path: String): URL? = this.javaClass.classLoader.getResource(path) @JvmStatic fun getWebjarPublicPath(ctx: Context, dependency: OptionalDependency): String { return "${ctx.contextPath()}/webjars/${dependency.artifactId}/${dependency.version}" } @JvmStatic fun assertWebjarInstalled(dependency: OptionalDependency) = try { getWebjarResourceUrl(dependency) } catch (e: Exception) { JavalinLogger.warn(missingDependencyMessage(dependency)) } @JvmStatic fun getWebjarResourceUrl(dependency: OptionalDependency): URL? { val webjarBaseUrl = "META-INF/resources/webjars" return getResourceUrl("$webjarBaseUrl/${dependency.artifactId}/${dependency.version}") } fun getFileUrl(path: String): URL? = if (File(path).exists()) File(path).toURI().toURL() else null fun isKotlinClass(clazz: Class<*>): Boolean { try { for (annotation in clazz.declaredAnnotations) { // Note: annotation.simpleClass can be used if kotlin-reflect is available. if (annotation.annotationClass.toString().contains("kotlin.Metadata")) { return true } } } catch (ignored: Exception) { } return false } @JvmStatic fun getPort(e: Exception) = e.message!!.takeLastWhile { it != ':' } fun <T : Any?> findByClass(map: Map<Class<out Exception>, T>, exceptionClass: Class<out Exception>): T? = map.getOrElse(exceptionClass) { var superclass = exceptionClass.superclass while (superclass != null) { if (map.containsKey(superclass)) { return map[superclass] } superclass = superclass.superclass } return null } }
apache-2.0
370e8738c5e1b11568428ff7a6c06ca7
38.427885
144
0.575905
4.734988
false
false
false
false
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/payload/ExternalBackupManager.kt
1
11451
package com.samourai.wallet.payload import android.Manifest import android.app.Activity import android.app.Activity.RESULT_OK import android.app.Application import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Environment import androidx.core.content.ContextCompat import androidx.core.net.toUri import androidx.documentfile.provider.DocumentFile import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.samourai.wallet.BuildConfig import com.samourai.wallet.R import com.samourai.wallet.util.PrefsUtil import kotlinx.coroutines.* import java.io.File /** * samourai-wallet-android * * Utility for managing android scope storage and legacy storage for external backups * * Refs: * https://developer.android.com/about/versions/11/privacy/storage * https://developer.android.com/guide/topics/permissions/overview */ object ExternalBackupManager { private lateinit var appContext: Application private const val strOptionalBackupDir = "/samourai" private const val STORAGE_REQ_CODE = 4866 private const val READ_WRITE_EXTERNAL_PERMISSION_CODE = 2009 private var backUpDocumentFile: DocumentFile? = null private const val strBackupFilename = "samourai.txt" private val permissionState = MutableLiveData(false) private val scope = CoroutineScope(Dispatchers.Main) + SupervisorJob() /** * Shows proper dialog for external storage permission * * Invokes API specific storage requests. * scoped storage for API 29 * normal external storage request for API below 29 */ @JvmStatic fun askPermission(activity: Activity) { fun ask() { if (requireScoped()) { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply { flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION } activity.startActivityForResult(intent, STORAGE_REQ_CODE) } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity.requestPermissions( arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE ), READ_WRITE_EXTERNAL_PERMISSION_CODE ) } } } var titleId = R.string.permission_alert_dialog_title_external var message = appContext.getString(R.string.permission_dialog_message_external) if (requireScoped()) { titleId = R.string.permission_alert_dialog_title_external_scoped message = appContext.getString(R.string.permission_dialog_scoped) } val builder = MaterialAlertDialogBuilder(activity) builder.setTitle(titleId) .setMessage(message) .setPositiveButton(if (requireScoped()) R.string.choose else R.string.ok) { dialog, _ -> dialog.dismiss() ask() }.setNegativeButton(R.string.cancel) { dialog, _ -> dialog.dismiss() }.show() } /** * Attach to root application object to retrieve context * Ref: [com.samourai.wallet.SamouraiApplication] onCreate */ @JvmStatic fun attach(application: Application) { this.appContext = application if (requireScoped()) { this.initScopeStorage() } } @JvmStatic fun write(content: String) { scope.launch(Dispatchers.IO) { try { if (requireScoped()) { writeScopeStorage(content) } else { writeLegacyStorage(content) } } catch (e: Exception) { throw CancellationException(e.message) } } } @JvmStatic fun read(): String? = if (requireScoped()) { readScoped() } else { readLegacy() } private fun initScopeStorage() { if (PrefsUtil.getInstance(appContext).has(PrefsUtil.BACKUP_FILE_PATH)) { val path: String = PrefsUtil.getInstance(appContext).getValue(PrefsUtil.BACKUP_FILE_PATH, ""); if (path.isNotEmpty()) { if (DocumentFile.fromTreeUri(appContext, path.toUri()) == null) { permissionState.postValue(false) return } val documentsTree = DocumentFile.fromTreeUri(appContext, path.toUri())!! var hasPerm = false appContext.contentResolver.persistedUriPermissions.forEach { uri -> if (uri.uri.toString() == path) { permissionState.postValue(true) hasPerm = true } } if (!hasPerm) { return } documentsTree.listFiles().forEach { doc -> if (BuildConfig.FLAVOR == "staging") { if (doc.isDirectory && doc.name == "staging") { doc.findFile(strBackupFilename)?.let { backUpDocumentFile = it } } } else { if (doc.isFile && doc.name == strBackupFilename) { backUpDocumentFile = doc } } } if (backUpDocumentFile == null) { backUpDocumentFile = if (BuildConfig.FLAVOR == "staging") { val stagingDir = documentsTree.createDirectory("staging") stagingDir?.createFile("text/plain ", strBackupFilename) } else { documentsTree.createFile("text/plain ", strBackupFilename) } } } } } @JvmStatic private fun writeScopeStorage(content: String) { if (backUpDocumentFile == null) { throw Exception("Backup file not available") } if (!backUpDocumentFile!!.canRead()) { throw Exception("Backup file is not readable") } val stream = appContext.contentResolver.openOutputStream(backUpDocumentFile!!.uri) stream?.write(content.encodeToByteArray()) } @JvmStatic private fun writeLegacyStorage(content: String) { if (hasPermission()) { if (!getLegacyBackupFile().exists()) { getLegacyBackupFile().createNewFile() } getLegacyBackupFile().writeText(content) } else { throw Exception("Backup file not available") } } @JvmStatic fun readScoped(): String? { if (backUpDocumentFile == null) { throw Exception("Backup file not available") } if (!backUpDocumentFile!!.canRead()) { throw Exception("Backup file is not readable") } val stream = appContext.contentResolver.openInputStream(backUpDocumentFile!!.uri) return stream?.readBytes()?.decodeToString() } private fun readLegacy(): String? { return if (hasPermission()) { getLegacyBackupFile().readText() } else { null } } @JvmStatic fun lastUpdated(): Long? { return if (requireScoped()) { backUpDocumentFile?.lastModified() } else { if (hasPermission() && getLegacyBackupFile().exists()) { getLegacyBackupFile().lastModified() } else { null } } } /** * Checks both scoped and non-scoped storage permissions * * For scoped storage method will use persistedUriPermissions array from * contentResolver to compare allowed path that store in the prefs * */ @JvmStatic fun hasPermissions(): Boolean { if (requireScoped()) { if (backUpDocumentFile == null) { return false } val path: String = PrefsUtil.getInstance(appContext).getValue(PrefsUtil.BACKUP_FILE_PATH, ""); appContext.contentResolver.persistedUriPermissions.forEach { uri -> if (uri.uri.toString() == path) { return true } } return false } else { return hasPermission() } } @JvmStatic fun backupAvailable(): Boolean { if (requireScoped()) { if (backUpDocumentFile == null ) { return false } if (backUpDocumentFile!!.canRead()) { return backUpDocumentFile!!.exists() } return false } else { return getLegacyBackupFile().exists() } } /** * Handles permission result that received in an activity * * Any Activity that using this class should invoke this method in onActivityResult */ @JvmStatic fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent?, application: Application ) { val directoryUri = data?.data ?: return if (requestCode == STORAGE_REQ_CODE && resultCode == RESULT_OK) { PrefsUtil.getInstance(application) .setValue(PrefsUtil.BACKUP_FILE_PATH, directoryUri.toString()) this.appContext.contentResolver.takePersistableUriPermission( directoryUri, Intent.FLAG_GRANT_READ_URI_PERMISSION ) this.attach(application) permissionState.postValue(true) } } /** * For older api's ( below API 29) */ @Suppress("DEPRECATION") private fun getLegacyBackupFile(): File { val directory = Environment.DIRECTORY_DOCUMENTS val dir: File? = if (appContext.packageName.contains("staging")) { Environment.getExternalStoragePublicDirectory("$directory$strOptionalBackupDir/staging") } else { Environment.getExternalStoragePublicDirectory("$directory$strOptionalBackupDir") } if (!dir?.exists()!!) { dir.mkdirs() dir.setWritable(true) dir.setReadable(true) } val backupFile = File(dir, strBackupFilename); return backupFile } private fun hasPermission(): Boolean { val readPerm = ContextCompat.checkSelfPermission( appContext, Manifest.permission.READ_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED val writePerm = ContextCompat.checkSelfPermission( appContext, Manifest.permission.WRITE_EXTERNAL_STORAGE ) == PackageManager.PERMISSION_GRANTED return (readPerm && writePerm) } private fun requireScoped() = Build.VERSION.SDK_INT >= 29 @JvmStatic fun getPermissionStateLiveData(): LiveData<Boolean> { return permissionState } @JvmStatic fun dispose() { if (scope.isActive) { scope.cancel() } } }
unlicense
011054ea9be5932cb66fe900bb0ecc82
32.002882
100
0.569732
5.279391
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/mapdata/ElementDao.kt
1
3411
package de.westnordost.streetcomplete.data.osm.mapdata import javax.inject.Inject import de.westnordost.streetcomplete.data.osm.mapdata.ElementType.* /** Stores OSM elements. Actually, stores nothing, but delegates the work to a NodeDao, WayDao and * a RelationDao. :-P */ class ElementDao @Inject constructor( private val nodeDao: NodeDao, private val wayDao: WayDao, private val relationDao: RelationDao ) { fun put(element: Element) { when (element) { is Node -> nodeDao.put(element) is Way -> wayDao.put(element) is Relation -> relationDao.put(element) } } fun get(type: ElementType, id: Long): Element? { return when (type) { NODE -> nodeDao.get(id) WAY -> wayDao.get(id) RELATION -> relationDao.get(id) } } fun delete(type: ElementType, id: Long) { when (type) { NODE -> nodeDao.delete(id) WAY -> wayDao.delete(id) RELATION -> relationDao.delete(id) } } fun putAll(elements: Iterable<Element>) { nodeDao.putAll(elements.filterIsInstance<Node>()) wayDao.putAll(elements.filterIsInstance<Way>()) relationDao.putAll(elements.filterIsInstance<Relation>()) } fun getAll(keys: Iterable<ElementKey>): List<Element> { val elementIds = keys.toElementIds() if (elementIds.size == 0) return emptyList() val result = ArrayList<Element>(elementIds.size) result.addAll(nodeDao.getAll(elementIds.nodes)) result.addAll(wayDao.getAll(elementIds.ways)) result.addAll(relationDao.getAll(elementIds.relations)) return result } fun deleteAll(keys: Iterable<ElementKey>): Int { val elementIds = keys.toElementIds() if (elementIds.size == 0) return 0 // delete first relations, then ways, then nodes because relations depend on ways depend on nodes return relationDao.deleteAll(elementIds.relations) + wayDao.deleteAll(elementIds.ways) + nodeDao.deleteAll(elementIds.nodes) } fun clear() { relationDao.clear() wayDao.clear() nodeDao.clear() } fun getIdsOlderThan(timestamp: Long, limit: Int? = null): List<ElementKey> { val result = mutableListOf<ElementKey>() // get relations first, then ways, then nodes because relations depend on ways depend on nodes. result.addAll(relationDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(RELATION, it) }) result.addAll(wayDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(WAY, it) }) result.addAll(nodeDao.getIdsOlderThan(timestamp, limit?.minus(result.size)).map { ElementKey(NODE, it) }) return result } } private data class ElementIds(val nodes: List<Long>, val ways: List<Long>, val relations: List<Long>) { val size: Int get() = nodes.size + ways.size + relations.size } private fun Iterable<ElementKey>.toElementIds(): ElementIds { val nodes = ArrayList<Long>() val ways = ArrayList<Long>() val relations = ArrayList<Long>() for (key in this) { when(key.type) { NODE -> nodes.add(key.id) WAY -> ways.add(key.id) RELATION -> relations.add(key.id) } } return ElementIds(nodes, ways, relations) }
gpl-3.0
5e361d2cfca33fe4649ef9a078377c65
33.806122
121
0.637936
4.055886
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CollectionFragment.kt
1
24465
package com.boardgamegeek.ui import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.content.res.ColorStateList import android.os.Bundle import android.util.SparseBooleanArray import android.view.* import android.widget.LinearLayout import androidx.annotation.StringRes import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.content.pm.ShortcutManagerCompat import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.core.view.updatePadding import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentCollectionBinding import com.boardgamegeek.databinding.RowCollectionBinding import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.extensions.* import com.boardgamegeek.filterer.CollectionFilterer import com.boardgamegeek.filterer.CollectionStatusFilterer import com.boardgamegeek.pref.SettingsActivity import com.boardgamegeek.pref.SyncPrefs import com.boardgamegeek.pref.noPreviousCollectionSync import com.boardgamegeek.provider.BggContract import com.boardgamegeek.sorter.CollectionSorter import com.boardgamegeek.sorter.CollectionSorterFactory import com.boardgamegeek.ui.CollectionFragment.CollectionAdapter.CollectionItemViewHolder import com.boardgamegeek.ui.dialog.* import com.boardgamegeek.ui.viewmodel.CollectionViewViewModel import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration.SectionCallback import com.boardgamegeek.util.HttpUtils.encodeForUrl import com.google.android.material.chip.Chip import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase import timber.log.Timber import java.text.NumberFormat class CollectionFragment : Fragment(), ActionMode.Callback { private var _binding: FragmentCollectionBinding? = null private val binding get() = _binding!! private var viewId = CollectionView.DEFAULT_DEFAULT_ID private var viewName = "" private var sorter: CollectionSorter? = null private val filters = mutableListOf<CollectionFilterer>() private var isCreatingShortcut = false private var changingGamePlayId: Long = 0 private var actionMode: ActionMode? = null private lateinit var firebaseAnalytics: FirebaseAnalytics private val viewModel by activityViewModels<CollectionViewViewModel>() private val adapter by lazy { CollectionAdapter() } private val prefs: SharedPreferences by lazy { requireContext().preferences() } private val collectionSorterFactory: CollectionSorterFactory by lazy { CollectionSorterFactory(requireContext()) } private val numberFormat = NumberFormat.getInstance() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) firebaseAnalytics = Firebase.analytics isCreatingShortcut = arguments?.getBoolean(KEY_IS_CREATING_SHORTCUT) ?: false changingGamePlayId = arguments?.getLong(KEY_CHANGING_GAME_PLAY_ID, BggContract.INVALID_ID.toLong()) ?: BggContract.INVALID_ID.toLong() setHasOptionsMenu(true) } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentCollectionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.listView.adapter = adapter if (isCreatingShortcut) { binding.swipeRefreshLayout.longSnackbar(R.string.msg_shortcut_create) } else if (changingGamePlayId != BggContract.INVALID_ID.toLong()) { binding.swipeRefreshLayout.longSnackbar(R.string.msg_change_play_game) } binding.footerToolbar.inflateMenu(R.menu.collection_fragment) binding.footerToolbar.setOnMenuItemClickListener(footerMenuListener) binding.footerToolbar.menu.apply { if (isCreatingShortcut || changingGamePlayId != BggContract.INVALID_ID.toLong()) { findItem(R.id.menu_collection_random_game)?.isVisible = false findItem(R.id.menu_create_shortcut)?.isVisible = false findItem(R.id.menu_collection_view_save)?.isVisible = false findItem(R.id.menu_collection_view_delete)?.isVisible = false findItem(R.id.menu_share)?.isVisible = false } else { findItem(R.id.menu_collection_random_game)?.isVisible = true findItem(R.id.menu_create_shortcut)?.isVisible = true findItem(R.id.menu_collection_view_save)?.isVisible = true findItem(R.id.menu_collection_view_delete)?.isVisible = true findItem(R.id.menu_share)?.isVisible = true } } setEmptyText() binding.emptyButton.setOnClickListener { startActivity(Intent(context, SettingsActivity::class.java)) } binding.swipeRefreshLayout.setBggColors() binding.swipeRefreshLayout.setOnRefreshListener { binding.swipeRefreshLayout.isRefreshing = viewModel.refresh() } binding.progressBar.show() viewModel.selectedViewId.observe(viewLifecycleOwner) { binding.progressBar.show() binding.listView.isVisible = false viewId = it binding.footerToolbar.menu.findItem(R.id.menu_create_shortcut)?.isEnabled = it > 0 } viewModel.selectedViewName.observe(viewLifecycleOwner) { viewName = it } viewModel.views.observe(viewLifecycleOwner) { binding.footerToolbar.menu.findItem(R.id.menu_collection_view_delete)?.isEnabled = it?.isNotEmpty() == true } viewModel.effectiveSortType.observe(viewLifecycleOwner) { sortType: Int -> sorter = collectionSorterFactory.create(sortType) binding.sortDescriptionView.text = if (sorter == null) "" else requireActivity().getString(R.string.by_prefix, sorter?.description.orEmpty()) val hasFiltersApplied = filters.size > 0 val hasSortApplied = sorter?.let { it.type != CollectionSorterFactory.TYPE_DEFAULT } ?: false binding.footerToolbar.menu.findItem(R.id.menu_collection_view_save)?.isEnabled = hasFiltersApplied || hasSortApplied } viewModel.effectiveFilters.observe(viewLifecycleOwner) { filterList -> filters.clear() filterList?.let { filters.addAll(filterList) } setEmptyText() bindFilterButtons() val hasFiltersApplied = filters.size > 0 val hasSortApplied = sorter?.let { it.type != CollectionSorterFactory.TYPE_DEFAULT } ?: false binding.footerToolbar.menu.findItem(R.id.menu_collection_view_save)?.isEnabled = hasFiltersApplied || hasSortApplied } viewModel.items.observe(viewLifecycleOwner) { it?.let { showData(it) } } viewModel.isFiltering.observe(viewLifecycleOwner) { it?.let { if (it) binding.progressBar.show() else binding.progressBar.hide() } } viewModel.isRefreshing.observe(viewLifecycleOwner) { it?.let { binding.swipeRefreshLayout.isRefreshing = it } } viewModel.refresh() } private fun showData(items: List<CollectionItemEntity>) { adapter.items = items binding.footerToolbar.menu.apply { findItem(R.id.menu_collection_random_game)?.isEnabled = items.isNotEmpty() findItem(R.id.menu_share)?.isEnabled = items.isNotEmpty() } binding.listView.addHeader(adapter) binding.rowCountView.text = numberFormat.format(items.size) binding.emptyContainer.isVisible = items.isEmpty() binding.listView.isVisible = items.isNotEmpty() binding.progressBar.hide() } private val footerMenuListener = Toolbar.OnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_collection_random_game -> { firebaseAnalytics.logEvent("RandomGame", null) adapter.items.random().let { GameActivity.start(requireContext(), it.gameId, it.gameName, it.thumbnailUrl, it.heroImageUrl) } return@OnMenuItemClickListener true } R.id.menu_create_shortcut -> if (viewId > 0) { viewModel.createShortcut() return@OnMenuItemClickListener true } R.id.menu_collection_view_save -> { val name = if (viewId <= 0) "" else viewName val dialog = SaveViewDialogFragment.newInstance(name, createViewDescription(sorter, filters)) dialog.show([email protected], "view_save") return@OnMenuItemClickListener true } R.id.menu_collection_view_delete -> { DeleteViewDialogFragment.newInstance().show([email protected], "view_delete") return@OnMenuItemClickListener true } R.id.menu_share -> { shareCollection() return@OnMenuItemClickListener true } R.id.menu_collection_sort -> { CollectionSortDialogFragment.newInstance(sorter?.type ?: CollectionSorterFactory.TYPE_DEFAULT) .show([email protected], "collection_sort") return@OnMenuItemClickListener true } R.id.menu_collection_filter -> { CollectionFilterDialogFragment.newInstance(filters.map { it.type }) .show([email protected], "collection_filter") return@OnMenuItemClickListener true } } launchFilterDialog(item.itemId) } private fun shareCollection() { val description: String = when { viewId > 0 && viewName.isNotEmpty() -> viewName filters.size > 0 -> getString(R.string.title_filtered_collection) else -> getString(R.string.title_collection) } val text = StringBuilder(description) .append("\n") .append("-".repeat(description.length)) .append("\n") val maxGames = 10 adapter.items.take(maxGames).map { text.append("\u2022 ${formatGameLink(it.gameId, it.collectionName)}") } val leftOverCount = adapter.itemCount - maxGames if (leftOverCount > 0) text.append(getString(R.string.and_more, leftOverCount)).append("\n") val username = prefs[AccountPreferences.KEY_USERNAME, ""] text.append("\n") .append(createViewDescription(sorter, filters)) .append("\n") .append("\n") .append(getString(R.string.share_collection_complete_footer, "https://www.boardgamegeek.com/collection/user/${username.encodeForUrl()}")) val fullName = prefs[AccountPreferences.KEY_FULL_NAME, ""] requireActivity().share(getString(R.string.share_collection_subject, fullName, username), text, R.string.title_share_collection) } private fun setEmptyText() { val syncedStatuses = prefs.getStringSet(PREFERENCES_KEY_SYNC_STATUSES, null).orEmpty() if (syncedStatuses.isEmpty()) { setEmptyStateForSettingsAction(R.string.empty_collection_sync_off) } else { if (SyncPrefs.getPrefs(requireContext()).noPreviousCollectionSync()) { setEmptyStateForNoAction(R.string.empty_collection_sync_never) } else if (filters.isNotEmpty()) { val appliedStatuses = filters.filterIsInstance<CollectionStatusFilterer>().firstOrNull()?.getSelectedStatusesSet().orEmpty() if (syncedStatuses.containsAll(appliedStatuses)) { setEmptyStateForNoAction(R.string.empty_collection_filter_on) } else { setEmptyStateForSettingsAction(R.string.empty_collection_filter_on_sync_partial) } } else { setEmptyStateForSettingsAction(R.string.empty_collection) } } } private fun setEmptyStateForSettingsAction(@StringRes textResId: Int) { binding.emptyTextView.setText(textResId) binding.emptyButton.isVisible = true } private fun setEmptyStateForNoAction(@StringRes textResId: Int) { binding.emptyTextView.setText(textResId) binding.emptyButton.isVisible = false } private fun bindFilterButtons() { binding.chipGroup.removeAllViews() for (filter in filters) { if (filter.isValid) { binding.chipGroup.addView(Chip(requireContext(), null, R.style.Widget_MaterialComponents_Chip_Filter).apply { layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) text = filter.chipText() if (filter.iconResourceId != CollectionFilterer.INVALID_ICON) { chipIcon = AppCompatResources.getDrawable(requireContext(), filter.iconResourceId) chipIconTint = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), R.color.primary_dark)) } setOnClickListener { launchFilterDialog(filter.type) } setOnLongClickListener { viewModel.removeFilter(filter.type) true } }) } } val show = binding.chipGroup.childCount > 0 if (show) { binding.chipGroupScrollView.slideUpIn() } else { binding.chipGroupScrollView.slideDownOut() } binding.swipeRefreshLayout.updatePadding( bottom = if (show) resources.getDimensionPixelSize(R.dimen.chip_group_height) else 0 ) } fun launchFilterDialog(filterType: Int): Boolean { val dialog = CollectionFilterDialogFactory().create(requireContext(), filterType) return if (dialog != null) { dialog.createDialog(requireActivity(), filters.firstOrNull { it.type == filterType }) true } else { Timber.w("Couldn't find a filter dialog of type %s", filterType) false } } inner class CollectionAdapter : RecyclerView.Adapter<CollectionItemViewHolder>(), SectionCallback { var items: List<CollectionItemEntity> = emptyList() @SuppressLint("NotifyDataSetChanged") set(value) { field = value notifyDataSetChanged() } init { setHasStableIds(true) } private val selectedItems = SparseBooleanArray() fun getItem(position: Int) = items.getOrNull(position) val selectedItemCount: Int get() = selectedItems.filterTrue().size val selectedItemPositions: List<Int> get() = selectedItems.filterTrue() fun getSelectedItems() = selectedItemPositions.mapNotNull { items.getOrNull(it) } @SuppressLint("NotifyDataSetChanged") fun toggleSelection(position: Int) { selectedItems.toggle(position) notifyDataSetChanged() // I'd prefer to call notifyItemChanged(position), but that causes the section header to appear briefly actionMode?.let { if (selectedItemCount == 0) { it.finish() } else { it.invalidate() } } } fun clearSelection() { val oldSelectedItems = selectedItems.clone() selectedItems.clear() oldSelectedItems.filterTrue().forEach { notifyItemChanged(it) } } override fun getItemCount() = items.size override fun getItemId(position: Int) = getItem(position)?.internalId ?: RecyclerView.NO_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CollectionItemViewHolder { return CollectionItemViewHolder(parent.inflate(R.layout.row_collection)) } override fun onBindViewHolder(holder: CollectionItemViewHolder, position: Int) { holder.bindView(getItem(position), position) } inner class CollectionItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { val binding = RowCollectionBinding.bind(itemView) fun bindView(item: CollectionItemEntity?, position: Int) { if (item == null) return binding.nameView.text = item.collectionName binding.yearView.text = item.yearPublished.asYear(context) binding.timestampView.timestamp = sorter?.getTimestamp(item) ?: 0L binding.favoriteView.isVisible = item.isFavorite val ratingText = sorter?.getRatingText(item).orEmpty() binding.ratingView.setTextOrHide(ratingText) if (ratingText.isNotEmpty()) { sorter?.getRating(item)?.let { binding.ratingView.setTextViewBackground(it.toColor(BggColors.ratingColors)) } binding.infoView.isVisible = false } else { binding.infoView.setTextOrHide(sorter?.getDisplayInfo(item)) } binding.thumbnailView.loadThumbnail(item.thumbnailUrl) itemView.isActivated = selectedItems[position, false] itemView.setOnClickListener { when { isCreatingShortcut -> { GameActivity.createShortcutInfo(requireContext(), item.gameId, item.gameName)?.let { val intent = ShortcutManagerCompat.createShortcutResultIntent(requireContext(), it) requireActivity().setResult(Activity.RESULT_OK, intent) requireActivity().finish() } } changingGamePlayId != BggContract.INVALID_ID.toLong() -> { LogPlayActivity.changeGame( requireContext(), changingGamePlayId, item.gameId, item.gameName, item.thumbnailUrl, item.imageUrl, item.heroImageUrl ) requireActivity().finish() // don't want to come back to collection activity in "pick a new game" mode } actionMode == null -> GameActivity.start(requireContext(), item.gameId, item.gameName, item.thumbnailUrl, item.heroImageUrl) else -> adapter.toggleSelection(position) } } itemView.setOnLongClickListener { if (isCreatingShortcut) return@setOnLongClickListener false if (changingGamePlayId != BggContract.INVALID_ID.toLong()) return@setOnLongClickListener false if (actionMode != null) return@setOnLongClickListener false actionMode = requireActivity().startActionMode(this@CollectionFragment) if (actionMode == null) return@setOnLongClickListener false toggleSelection(position) true } } } override fun isSection(position: Int): Boolean { if (position == RecyclerView.NO_POSITION) return false if (items.isEmpty()) return false if (position == 0) return true if (position < 0 || position >= items.size) return false val thisLetter = getSectionHeader(position) val lastLetter = getSectionHeader(position - 1) return thisLetter != lastLetter } override fun getSectionHeader(position: Int): CharSequence { val item = items.getOrNull(position) ?: return "-" return sorter?.getHeaderText(item) ?: return "-" } } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.game_context, menu) adapter.clearSelection() return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val count = adapter.selectedItemCount mode.title = resources.getQuantityString(R.plurals.msg_games_selected, count, count) menu.findItem(R.id.menu_log_play_form)?.isVisible = count == 1 menu.findItem(R.id.menu_log_play_wizard)?.isVisible = count == 1 menu.findItem(R.id.menu_link)?.isVisible = count == 1 return true } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null adapter.clearSelection() } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val items = adapter.getSelectedItems() if (items.isEmpty()) return false when (item.itemId) { R.id.menu_log_play_form -> { items.firstOrNull()?.let { LogPlayActivity.logPlay( requireContext(), it.gameId, it.gameName, it.thumbnailUrl, it.imageUrl, it.heroImageUrl, it.arePlayersCustomSorted ) } } R.id.menu_log_play_quick -> { items.forEach { viewModel.logQuickPlay(it.gameId, it.gameName) } toast(resources.getQuantityString(R.plurals.msg_logging_plays, items.size)) } R.id.menu_log_play_wizard -> { items.firstOrNull()?.let { NewPlayActivity.start(requireContext(), it.gameId, it.gameName) } } R.id.menu_share -> { val shareMethod = "Collection" if (items.size == 1) { items.firstOrNull()?.let { requireActivity().shareGame(it.gameId, it.gameName, shareMethod, firebaseAnalytics) } } else { requireActivity().shareGames(items.map { it.gameId to it.gameName }, shareMethod, firebaseAnalytics) } } R.id.menu_link -> { items.firstOrNull()?.gameId?.let { activity.linkBgg(it) } } else -> return false } mode.finish() return true } private fun createViewDescription(sort: CollectionSorter?, filters: List<CollectionFilterer>): String { val text = StringBuilder() if (filters.isNotEmpty()) { text.append(getString(R.string.filtered_by)) filters.map { "\n\u2022 ${it.description()}" }.forEach { text.append(it) } } text.append("\n\n") sort?.let { if (it.type != CollectionSorterFactory.TYPE_DEFAULT) text.append(getString(R.string.sort_description, it.description)) } return text.trim().toString() } companion object { private const val KEY_IS_CREATING_SHORTCUT = "IS_CREATING_SHORTCUT" private const val KEY_CHANGING_GAME_PLAY_ID = "KEY_CHANGING_GAME_PLAY_ID" fun newInstance(isCreatingShortcut: Boolean): CollectionFragment { return CollectionFragment().apply { arguments = bundleOf(KEY_IS_CREATING_SHORTCUT to isCreatingShortcut) } } fun newInstanceForPlayGameChange(playId: Long): CollectionFragment { return CollectionFragment().apply { arguments = bundleOf(KEY_CHANGING_GAME_PLAY_ID to playId) } } } }
gpl-3.0
5eefc79f75e7b1733e0ffa7aa376b668
44.986842
149
0.628449
5.148359
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/shows/SyncAnticipatedShows.kt
1
3071
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.shows import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import net.simonvt.cathode.actions.CallAction import net.simonvt.cathode.api.entity.AnticipatedItem import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.ShowsService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.ShowColumns import net.simonvt.cathode.provider.ProviderSchematic.Shows import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.ShowDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.settings.SuggestionsTimestamps import retrofit2.Call import javax.inject.Inject class SyncAnticipatedShows @Inject constructor( private val context: Context, private val showHelper: ShowDatabaseHelper, private val showsService: ShowsService ) : CallAction<Unit, List<AnticipatedItem>>() { override fun key(params: Unit): String = "SyncAnticipatedShows" override fun getCall(params: Unit): Call<List<AnticipatedItem>> = showsService.getAnticipatedShows(LIMIT, Extended.FULL) override suspend fun handleResponse(params: Unit, response: List<AnticipatedItem>) { val ops = arrayListOf<ContentProviderOperation>() val showIds = mutableListOf<Long>() val localShows = context.contentResolver.query(Shows.SHOWS_ANTICIPATED) localShows.forEach { cursor -> showIds.add(cursor.getLong(ShowColumns.ID)) } localShows.close() response.forEachIndexed { index, anticipatedItem -> val show = anticipatedItem.show!! val showId = showHelper.partialUpdate(show) showIds.remove(showId) val values = ContentValues() values.put(ShowColumns.ANTICIPATED_INDEX, index) val op = ContentProviderOperation.newUpdate(Shows.withId(showId)).withValues(values).build() ops.add(op) } for (showId in showIds) { val op = ContentProviderOperation.newUpdate(Shows.withId(showId)) .withValue(ShowColumns.ANTICIPATED_INDEX, -1) .build() ops.add(op) } context.contentResolver.batch(ops) SuggestionsTimestamps.get(context) .edit() .putLong(SuggestionsTimestamps.SHOWS_ANTICIPATED, System.currentTimeMillis()) .apply() } companion object { private const val LIMIT = 50 } }
apache-2.0
2df77b53e61e4dc6648f1ea2a3add83b
35.559524
98
0.763595
4.218407
false
false
false
false
googlecast/CastVideos-android
app-kotlin/src/main/kotlin/com/google/sample/cast/refplayer/utils/CustomVolleyRequest.kt
1
2574
/* * Copyright 2022 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.cast.refplayer.utils import android.content.Context import com.android.volley.toolbox.ImageLoader import kotlin.jvm.Synchronized import com.android.volley.RequestQueue import com.android.volley.toolbox.ImageLoader.ImageCache import android.graphics.Bitmap import androidx.collection.LruCache import com.android.volley.Cache import com.android.volley.Network import com.android.volley.toolbox.DiskBasedCache import com.android.volley.toolbox.BasicNetwork import com.android.volley.toolbox.HurlStack class CustomVolleyRequest private constructor(context: Context) { private var requestQueue: RequestQueue? val imageLoader: ImageLoader private var context: Context init { this.context = context requestQueue = getRequestQueue() imageLoader = ImageLoader(requestQueue, object : ImageCache { private val cache: LruCache<String, Bitmap> = LruCache(20) override fun getBitmap(url: String): Bitmap? { return cache.get(url) } override fun putBitmap(url: String, bitmap: Bitmap) { cache.put(url, bitmap) } }) } private fun getRequestQueue(): RequestQueue { if (requestQueue == null) { val cache: Cache = DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024) val network: Network = BasicNetwork(HurlStack()) requestQueue = RequestQueue(cache, network) requestQueue!!.start() } return requestQueue!! } companion object { private var customVolleyRequest: CustomVolleyRequest? = null @Synchronized fun getInstance(context: Context): CustomVolleyRequest? { if (customVolleyRequest == null) { customVolleyRequest = CustomVolleyRequest(context) } return customVolleyRequest } } }
apache-2.0
840566c4e9787969a1b2b32c5e028328
34.273973
86
0.677156
4.740331
false
false
false
false
didi/DoraemonKit
Android/dokit-mc/src/main/java/com/didichuxing/doraemonkit/kit/mc/oldui/client/DoKitMcClientFragment.kt
1
2253
package com.didichuxing.doraemonkit.kit.mc.oldui.client import android.os.Bundle import android.view.View import android.widget.TextView import androidx.lifecycle.lifecycleScope import com.didichuxing.doraemonkit.DoKit import com.didichuxing.doraemonkit.kit.test.TestMode import com.didichuxing.doraemonkit.kit.core.BaseFragment import com.didichuxing.doraemonkit.kit.mc.oldui.DoKitMcManager import com.didichuxing.doraemonkit.kit.mc.ui.DoKitMcActivity import com.didichuxing.doraemonkit.kit.mc.ui.adapter.McClientHistory import com.didichuxing.doraemonkit.kit.mc.net.DoKitMcClient import com.didichuxing.doraemonkit.kit.mc.net.DokitMcConnectManager import com.didichuxing.doraemonkit.kit.mc.ui.McPages import com.didichuxing.doraemonkit.mc.R import kotlinx.coroutines.launch /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2020/12/10-10:52 * 描 述: * 修订历史: * ================================================ */ class DoKitMcClientFragment : BaseFragment() { private var history: McClientHistory? = null override fun onRequestLayout(): Int { return R.layout.dk_fragment_mc_client } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) history = DokitMcConnectManager.itemHistory findViewById<TextView>(R.id.tv_host_info).text = "当前设备已连接主机:ws://${history?.host}:${history?.port}/${history?.path}" findViewById<View>(R.id.btn_close).setOnClickListener { lifecycleScope.launch { DoKitMcManager.WS_MODE = TestMode.UNKNOWN DoKit.removeFloating(ClientDoKitView::class) DoKitMcClient.close() if (activity is DoKitMcActivity) { (activity as DoKitMcActivity).onBackPressed() } } } findViewById<View>(R.id.btn_history).setOnClickListener { lifecycleScope.launch { if (activity is DoKitMcActivity) { (activity as DoKitMcActivity).pushFragment(McPages.CLIENT_HISTORY) } } } } }
apache-2.0
74a6c5a33f41e67cfeeb0b1f78f49890
33.203125
86
0.653723
4.317554
false
false
false
false
AoEiuV020/PaNovel
api/src/main/java/cc/aoeiuv020/panovel/api/site/yllxs.kt
1
3554
package cc.aoeiuv020.panovel.api.site import cc.aoeiuv020.base.jar.ownTextListSplitWhitespace import cc.aoeiuv020.panovel.api.base.DslJsoupNovelContext import cc.aoeiuv020.panovel.api.firstThreeIntPattern /** * Created by AoEiuV020 on 2018.06.02-20:54:12. */ class Yllxs : DslJsoupNovelContext() {init { reason = "官方搜索不可用," hide = true site { name = "166小说" baseUrl = "http://www.166xs.com" logo = "http://m.166xs.com/system/logo.png" } search { get { charset = "GBK" url = "/modules/article/search.php" data { "searchkey" to it // 加上&page=1可以避开搜索时间间隔的限制, // 也可以通过不加载cookies避开搜索时间间隔的限制, "page" to "1" } } document { if (root.ownerDocument().location().endsWith(".html")) { // "http://www.166xs.com/116732.html" single { name("#book_left_a > div.book > div.book_info > div.title > h2") { it.ownText() } author("#book_left_a > div.book > div.book_info > div.title > h2 > address", block = pickString("作\\s*者:(\\S*)")) } } else { items("#Updates_list > ul > li") { name("> div.works > a.name") author("> div.author > a", block = pickString("([^ ]*) 作品集")) } } } } // "http://www.166xs.com/116732.html" // "http://www.166xs.com/xiaoshuo/116/116732/" // "http://www.166xs.com/xiaoshuo/121/121623/34377467.html" // http://www.166xs.com/xiaoshuo/0/121/59420.html // 主要就是这个详情页,和其他网站比,这个详情页地址没有取bookId一部分分隔, bookIdRegex = "(/xiaoshuo/\\d*)?/(\\d+)" bookIdIndex = 1 detailPageTemplate = "/%s.html" detail { document { novel { /* <h2>超品相师<address>作者:西域刀客</address></h2> */ name("#book_left_a > div.book > div.book_info > div.title > h2") { it.ownText() } author("#book_left_a > div.book > div.book_info > div.title > h2 > address", block = pickString("作\\s*者:(\\S*)")) } image("#book_left_a > div.book > div.pic > img") update("#book_left_a > div.book > div.book_info > div.info > p > span:nth-child(8)", format = "yyyy-MM-dd", block = pickString("更新时间:(.*)")) introduction("#book_left_a > div.book > div.book_info > div.intro > p") } } chapterDivision = 1000 chaptersPageTemplate = "/xiaoshuo/%d/%s" chapters { // 七个多余的, // 三个class="book_btn", // 一个最新章, // 三个功能按钮, document { items("body > dl > dd > a") }.drop(3) } // http://www.166xs.com/xiaoshuo/121/121623/34377471.html // http://www.166xs.com/xiaoshuo/31/31008/6750409.html bookIdWithChapterIdRegex = firstThreeIntPattern contentPageTemplate = "/xiaoshuo/%s.html" content { document { items("p.Book_Text") { it.ownTextListSplitWhitespace().dropLastWhile { it == "166小说阅读网" } } } } } }
gpl-3.0
2e81ba2042e647cf3014111200d696fa
33.291667
152
0.496962
3.528403
false
false
false
false
Light-Team/ModPE-IDE-Source
app/src/main/kotlin/com/brackeys/ui/utils/extensions/ViewExtensions2.kt
1
2639
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.utils.extensions import android.content.res.ColorStateList import android.util.TypedValue import android.view.View import android.widget.ImageView import androidx.annotation.ColorRes import androidx.annotation.IdRes import androidx.annotation.MenuRes import androidx.appcompat.app.ActionBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.customview.widget.ViewDragHelper import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.navigation.NavController fun Fragment.setSupportActionBar(toolbar: Toolbar) { val parentActivity = activity as AppCompatActivity parentActivity.setSupportActionBar(toolbar) } val Fragment.supportActionBar: ActionBar? get() = (activity as? AppCompatActivity)?.supportActionBar @Suppress("UNCHECKED_CAST") fun <T : Fragment> FragmentManager.fragment(@IdRes id: Int): T { return findFragmentById(id) as T } fun NavController.popBackStack(n: Int) { for (index in 0 until n) { popBackStack() } } fun ImageView.setTint(@ColorRes colorRes: Int) { imageTintList = ColorStateList.valueOf( context.getColour(colorRes) ) } fun View.setSelectableBackground() = with(TypedValue()) { context.theme.resolveAttribute(android.R.attr.selectableItemBackground, this, true) setBackgroundResource(resourceId) } fun Toolbar.replaceMenu(@MenuRes menuRes: Int) { menu.clear() inflateMenu(menuRes) } /** * https://stackoverflow.com/a/17802569/4405457 */ fun DrawerLayout.multiplyDraggingEdgeSizeBy(n: Int) { val leftDragger = javaClass.getDeclaredField("mLeftDragger") leftDragger.isAccessible = true val viewDragHelper = leftDragger.get(this) as ViewDragHelper val edgeSize = viewDragHelper.javaClass.getDeclaredField("mEdgeSize") edgeSize.isAccessible = true val edge = edgeSize.getInt(viewDragHelper) edgeSize.setInt(viewDragHelper, edge * n) }
apache-2.0
a957759dfb7d59d9614075388e45298e
30.807229
87
0.772641
4.263328
false
false
false
false
juxeii/dztools
java/dzjforex/src/main/kotlin/com/jforex/dzjforex/misc/Context.kt
1
1830
package com.jforex.dzjforex.misc import arrow.effects.ForIO import com.dukascopy.api.* import com.jforex.dzjforex.zorro.lotScale lateinit var contextApi: ContextDependencies<ForIO> fun initContextApi(context: IContext) { contextApi = ContextDependencies(context, pluginApi) } interface ContextDependencies<F> : PluginDependencies<F> { val jfContext: IContext val engine: IEngine val account: IAccount val history: IHistory fun Int.toAmount() = Math.abs(this) / lotScale fun Double.toContracts() = (this * lotScale).toInt() fun Double.toSignedContracts(command: IEngine.OrderCommand) = if (command == IEngine.OrderCommand.BUY) toContracts() else -toContracts() fun IOrder.toSignedContracts() = amount.toSignedContracts(orderCommand) fun IOrder.zorroId() = id.toInt() fun IOrder.isFromZorro()= label.startsWith(pluginSettings.labelPrefix()) companion object { operator fun <F> invoke( context: IContext, pluginDependencies: PluginDependencies<F> ): ContextDependencies<F> = object : ContextDependencies<F>, PluginDependencies<F> by pluginDependencies { override val jfContext = context override val engine = context.engine override val account = context.account override val history = context.history } } } object ContextApi { fun <F> ContextDependencies<F>.getSubscribedInstruments() = delay { jfContext.subscribedInstruments } fun <F> ContextDependencies<F>.setSubscribedInstruments(instrumentsToSubscribe: Set<Instrument>) = getSubscribedInstruments().map { subscribedInstruments -> jfContext.setSubscribedInstruments(subscribedInstruments + instrumentsToSubscribe, false) } }
mit
9e77f8ddf9ffff7aa6f0e588781366d4
30.568966
105
0.696721
4.316038
false
false
false
false
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/utils/SupportUtils.kt
1
4369
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.utils import android.annotation.TargetApi import android.app.Activity import android.content.ActivityNotFoundException import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.provider.Settings import mozilla.components.browser.session.Session import org.mozilla.focus.ext.components import org.mozilla.focus.locale.Locales import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.util.Locale object SupportUtils { const val HELP_URL = "https://support.mozilla.org/kb/what-firefox-focus-android" const val DEFAULT_BROWSER_URL = "https://support.mozilla.org/kb/set-firefox-focus-default-browser-android" const val REPORT_SITE_ISSUE_URL = "https://webcompat.com/issues/new?url=%s&label=browser-focus-geckoview" const val PRIVACY_NOTICE_URL = "https://www.mozilla.org/privacy/firefox-focus/" const val PRIVACY_NOTICE_KLAR_URL = "https://www.mozilla.org/de/privacy/firefox-klar/" const val OPEN_WITH_DEFAULT_BROWSER_URL = "https://www.mozilla.org/openGeneralSettings" // Fake URL val manifestoURL: String get() { val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://www.mozilla.org/$langTag/about/manifesto/" } enum class SumoTopic( /** The final path segment for a SUMO URL - see {@see #getSumoURLForTopic} */ internal val topicStr: String ) { ADD_SEARCH_ENGINE("add-search-engine"), AUTOCOMPLETE("autofill-domain-android"), TRACKERS("trackers"), USAGE_DATA("usage-data"), WHATS_NEW("whats-new-focus-android-8"), SEARCH_SUGGESTIONS("search-suggestions-focus-android"), ALLOWLIST("focus-android-allowlist") } fun getSumoURLForTopic(context: Context, topic: SumoTopic): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) val appVersion = getAppVersion(context) val osTarget = "Android" val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://support.mozilla.org/1/mobile/$appVersion/$osTarget/$langTag/$escapedTopic" } // For some reason this URL has a different format than the other SUMO URLs fun getSafeBrowsingURL(): String { val langTag = Locales.getLanguageTag(Locale.getDefault()) return "https://support.mozilla.org/$langTag/kb/how-does-phishing-and-malware-protection-work" } private fun getEncodedTopicUTF8(topic: String): String { try { return URLEncoder.encode(topic, "UTF-8") } catch (e: UnsupportedEncodingException) { throw IllegalStateException("utf-8 should always be available", e) } } private fun getAppVersion(context: Context): String { try { return context.packageManager.getPackageInfo(context.packageName, 0).versionName } catch (e: PackageManager.NameNotFoundException) { // This should be impossible - we should always be able to get information about ourselves: throw IllegalStateException("Unable find package details for Focus", e) } } fun openDefaultBrowserSumoPage(context: Context) { val session = Session(SupportUtils.DEFAULT_BROWSER_URL, source = Session.Source.MENU) context.components.sessionManager.add(session, selected = true) if (context is Activity) { context.finish() } else { openDefaultBrowserSumoPage((context as ContextWrapper).baseContext) } } @TargetApi(Build.VERSION_CODES.N) fun openDefaultAppsSettings(context: Context) { try { val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS) context.startActivity(intent) } catch (e: ActivityNotFoundException) { // In some cases, a matching Activity may not exist (according to the Android docs). openDefaultBrowserSumoPage(context) } } }
mpl-2.0
2d7e10c872be43730483b86bc687e2cd
41.417476
110
0.693523
4.209056
false
false
false
false
genobis/tornadofx
src/main/java/tornadofx/EventBus.kt
1
4488
@file:Suppress("UNCHECKED_CAST") package tornadofx import javafx.application.Platform import tornadofx.EventBus.RunOn.ApplicationThread import java.util.* import java.util.concurrent.atomic.AtomicLong import kotlin.concurrent.thread import kotlin.reflect.KClass open class FXEvent( open val runOn: EventBus.RunOn = ApplicationThread, open val scope: Scope? = null ) class EventContext { internal var unsubscribe = false fun unsubscribe() { unsubscribe = true } } class FXEventRegistration(val eventType: KClass<out FXEvent>, val owner: Component?, val maxCount: Long? = null, val action: EventContext.(FXEvent) -> Unit) { val count = AtomicLong() override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as FXEventRegistration if (eventType != other.eventType) return false if (owner != other.owner) return false if (action != other.action) return false return true } override fun hashCode(): Int { var result = eventType.hashCode() result = 31 * result + (owner?.hashCode() ?: 0) result = 31 * result + action.hashCode() return result } fun unsubscribe() { FX.eventbus.unsubscribe(this) } } class EventBus { enum class RunOn { ApplicationThread, BackgroundThread } private val subscriptions = HashMap<KClass<out FXEvent>, HashSet<FXEventRegistration>>() private val eventScopes = HashMap<EventContext.(FXEvent) -> Unit, Scope>() inline fun <reified T: FXEvent> subscribe(scope: Scope, registration : FXEventRegistration) = subscribe(T::class, scope, registration) fun <T : FXEvent> subscribe(event: KClass<T>, scope: Scope, registration : FXEventRegistration) { subscriptions.getOrPut(event, { HashSet() }).add(registration) eventScopes[registration.action] = scope } inline fun <reified T:FXEvent> subscribe(owner: Component? = null, times: Long? = null, scope: Scope, noinline action: (T) -> Unit) = subscribe(owner, times, T::class, scope, action) fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: KClass<T>, scope: Scope, action: (T) -> Unit) { subscribe(event, scope, FXEventRegistration(event, owner, times, action as EventContext.(FXEvent) -> Unit)) } fun <T : FXEvent> subscribe(owner: Component? = null, times: Long? = null, event: Class<T>, scope: Scope, action: (T) -> Unit) = subscribe(event.kotlin, scope, FXEventRegistration(event.kotlin, owner, times, action as EventContext.(FXEvent) -> Unit)) inline fun <reified T: FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) = unsubscribe(T::class, action) fun <T : FXEvent> unsubscribe(event: Class<T>, action: EventContext.(T) -> Unit) = unsubscribe(event.kotlin, action) fun <T : FXEvent> unsubscribe(event: KClass<T>, action: EventContext.(T) -> Unit) { subscriptions[event]?.removeAll { it.action == action } eventScopes.remove(action) } fun unsubscribe(registration: FXEventRegistration) { unsubscribe(registration.eventType, registration.action) registration.owner?.subscribedEvents?.get(registration.eventType)?.remove(registration) } fun fire(event: FXEvent) { fun fireEvents() { subscriptions[event.javaClass.kotlin]?.toTypedArray()?.forEach { if (event.scope == null || event.scope == eventScopes[it.action]) { val count = it.count.andIncrement if (it.maxCount == null || count < it.maxCount) { val context = EventContext() it.action.invoke(context, event) if (context.unsubscribe) unsubscribe(it) } else { unsubscribe(it) } } } } if (Platform.isFxApplicationThread()) { if (event.runOn == ApplicationThread) { fireEvents() } else { thread(true) { fireEvents() } } } else { if (event.runOn == ApplicationThread) { Platform.runLater { fireEvents() } } else { fireEvents() } } } }
apache-2.0
9e96d82e4880fc0fb9f1f31f3eefe8a7
35.495935
158
0.608066
4.533333
false
false
false
false
sinnerschrader/account-tool
src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/messaging/GlobalMessageFactory.kt
1
1818
package com.sinnerschrader.s2b.accounttool.presentation.messaging import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.MessageSource import org.springframework.stereotype.Component import java.util.* import javax.servlet.http.HttpServletRequest @Deprecated("remove") @Component(value = "globalMessageFactory") class GlobalMessageFactory { @Autowired private val messageSource: MessageSource? = null fun create(type: GlobalMessageType, messageKey: String, vararg args: String): GlobalMessage { return GlobalMessage(messageKey, messageSource!!.getMessage(messageKey, args, Locale.ENGLISH), type) } fun createError(messageKey: String, vararg args: String): GlobalMessage { return create(GlobalMessageType.ERROR, messageKey, *args) } fun createInfo(messageKey: String, vararg args: String): GlobalMessage { return create(GlobalMessageType.INFO, messageKey, *args) } fun store(request: HttpServletRequest, message: GlobalMessage) { val session = request.session if (session.getAttribute(SESSION_KEY) == null) { session.setAttribute(SESSION_KEY, LinkedList<GlobalMessage>()) } val messages = session.getAttribute(SESSION_KEY) as MutableList<GlobalMessage> messages.add(message) } fun pop(request: HttpServletRequest): List<GlobalMessage> { val session = request.session if (session.getAttribute(SESSION_KEY) == null) { return ArrayList() } val messages = session.getAttribute(SESSION_KEY) as List<GlobalMessage> session.removeAttribute(SESSION_KEY) return messages } companion object { private val SESSION_KEY = GlobalMessageFactory::class.java.name } }
mit
e1ecf9fe7a0703ce278645534b7933da
33.961538
97
0.710671
4.697674
false
false
false
false
Setekh/Gleipnir-Graphics
src/main/kotlin/eu/corvus/corax/graphics/material/MatcapMaterial.kt
1
4017
/** * Copyright (c) 2013-2019 Corvus Corax Entertainment * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of Corvus Corax Entertainment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.corvus.corax.graphics.material import eu.corvus.corax.graphics.context.RendererContext import eu.corvus.corax.graphics.material.shaders.MatcapShader import eu.corvus.corax.graphics.material.textures.Texture import eu.corvus.corax.scene.Camera import eu.corvus.corax.scene.assets.AssetManager import eu.corvus.corax.scene.geometry.Geometry import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import org.joml.Matrix3f import org.joml.Matrix4f import org.koin.core.KoinComponent /** * @author Vlad Ravenholm on 1/6/2020 */ class MatcapMaterial(val matcapTexture: MatcapTexture = MatcapTexture.MatcapBlue): Material(), KoinComponent { enum class MatcapTexture(val texturePath: String) { MatcapBlue("textures/matcap.png"), MatcapBrown("textures/matcap2.png"), Matcap3("textures/matcap3.png") } override val shader = MatcapShader() var texture: Texture? = null var isLoadingTexture = false private val normalMatrix = Matrix4f() override fun applyParams( renderContext: RendererContext, camera: Camera, geometry: Geometry ) { shader.setUniformValue(shader.viewProjection, camera.viewProjectionMatrix) shader.setUniformValue(shader.modelMatrix, geometry.worldMatrix) shader.setUniformValue(shader.eye, camera.dir) normalMatrix.set(camera.viewMatrix).mul(geometry.worldMatrix).invert().transpose() shader.setUniformValue(shader.normalMatrix, normalMatrix) val texture = texture ?: return shader.setUniformValue(shader.texture, 0) renderContext.useTexture(texture, 0) } override fun cleanRender(renderContext: RendererContext) { val texture = texture ?: return renderContext.unbindTexture(texture) } override fun prepareUpload(assetManager: AssetManager, rendererContext: RendererContext) { super.prepareUpload(assetManager, rendererContext) val texture = texture if (texture == null && !isLoadingTexture) { isLoadingTexture = true scope.launch { [email protected] = assetManager.loadTexture(matcapTexture.texturePath) } } if (texture != null && !texture.isUploaded) { rendererContext.createTexture(texture) } } override fun free() { super.free() texture?.free() } }
bsd-3-clause
b8598e0c490feac963c4a4bfbe9185ed
37.266667
110
0.731641
4.503363
false
false
false
false
valeter/difk
src/test/kotlin/ru/anisimov/difk/DifkInjectorTest.kt
1
8091
/* * Copyright 2017 Ivan Anisimov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ru.anisimov.difk import org.junit.Assert.* import org.junit.Test import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger /** * @author Ivan Anisimov * * [email protected] * * 11.06.17 */ class DifkInjectorTest { @Test fun loadProperties() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.init() assertEquals("my_url", injector.getProperty("db.url")) } @Test(expected = RuntimeException::class) fun loadPropertiesAfterInit() { val injector = DifkInjector() injector.init() injector.loadPropertiesFromClasspath("test.properties") } @Test fun setProperty() { val injector = DifkInjector() injector.setProperty("db.url.2", "my_url_2") injector.init() assertEquals("my_url_2", injector.getProperty("db.url.2")) } @Test(expected = RuntimeException::class) fun setPropertyAfterInit() { val injector = DifkInjector() injector.init() injector.setProperty("my.property", "my_value") } @Test fun getPropertyOrNull() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.init() assertEquals(null, injector.getPropertyOrNull("db.url.2")) } /*@Test fun getInstances() { val injector = DifkInjector() val first = Any() val second = Any() injector.addSingleton("first", { first }) injector.addSingleton("second", { second }) injector.init() val instances: List<Any> = injector.getInstances(Any::class) assertEquals(2, instances.size) assertTrue(first === instances[0]) assertTrue(second === instances[1]) }*/ @Test fun singletonIsAlwaysTheSame() { val injector = DifkInjector() injector.addSingleton("single", { Any() }) injector.init() val instance: Any = injector.getInstance("single") for (i in 99 downTo 0) { assertEquals(instance, injector.getInstance("single")) } } @Test fun prototypeIsAlwaysNew() { val injector = DifkInjector() injector.addPrototype("proto", { Any() }) injector.init() val set: MutableSet<Any> = HashSet() for (i in 99 downTo 0) { set.add(injector.getInstance("proto")) } assertEquals(100, set.size) } @Test fun destructorRunOnClose() { val injector = DifkInjector() val destructed = AtomicBoolean(false) injector.addDestructor { destructed.set(true) } injector.init() injector.close() assertTrue(destructed.get()) } @Test fun registerShutdownHookRegisterHookForDestructors() { val injector = DifkInjector() val destructed = AtomicBoolean(false) injector.addDestructor { destructed.set(true) } assertNull(injector.shutdownHook) injector.registerShutdownHook() assertNotNull(injector.shutdownHook) assertFalse(destructed.get()) injector.shutdownHook!!.start() injector.shutdownHook!!.join() assertTrue(destructed.get()) } @Test fun registerShutdownHookRegistersInRuntime() { val injector = DifkInjector() injector.registerShutdownHook() assertTrue(Runtime.getRuntime().removeShutdownHook(injector.shutdownHook)) } @Test fun notExistingBeanReturnsNull() { val injector = DifkInjector() injector.init() assertNull(injector.getInstanceOrNull("not_existing")) } @Test(expected = RuntimeException::class) fun notExistingBeanThrowsException() { val injector = DifkInjector() injector.init() assertNull(injector.getInstance("not_existing")) } @Test fun threadLocalIsUniqueForEachThread() { val injector = DifkInjector() val counter = AtomicInteger(-1) injector.addThreadLocal("counter", { counter.incrementAndGet() }) injector.init() val values = Array(100, { 0 }) val threads = ArrayList<Thread>() (99 downTo 0).mapTo(threads) { object : Thread() { override fun run() { values[it] = injector.getInstance("counter") } } } threads.forEach { it.start() it.join() } assertEquals(99, counter.get()) values.sort() for(i in 99 downTo 0) { assertEquals(i, values[i]) } } @Test fun threadLocalIsSingletonInsideThread() { val injector = DifkInjector() val counter = AtomicInteger(-1) injector.addThreadLocal("counter", { counter.incrementAndGet() }) injector.init() for (i in 99 downTo 0) { assertEquals(0, injector.getInstance("counter")) } } @Test fun simpleScenario() { val injector = DifkInjector() injector.loadPropertiesFromClasspath("test.properties") injector.addSingleton("dataSource", { DataSource( injector.getProperty("db.url"), injector.getProperty("db.driver.class.name"), injector.getProperty("db.username"), injector.getProperty("db.password") ) }) injector.addSingleton("dao", { Dao(injector.getInstance("dataSource")) }) injector.addSingleton("service", { val s = Service(injector.getInstance("dao")); s.init(); s }) injector.addDestructor { val service: Service = injector.getInstance("service") service.close() } injector.init() val service: Service = injector.getInstance("service") assertFalse(service.closed!!) val difkService: Service = injector.getInstance("service") assertTrue(service === difkService) assertEquals("my_url", difkService.dao.dataSource.url) assertEquals("my_class", difkService.dao.dataSource.driverClassName) assertEquals("my_user", difkService.dao.dataSource.username) assertEquals("my_password", difkService.dao.dataSource.password) injector.close() assertTrue(service.closed!!) } @Test fun sortRelations() { val injector = DifkInjector() val graph: MutableMap<String, MutableSet<String>> = HashMap() graph.put("1", HashSet(listOf("2", "3"))) graph.put("2", HashSet(listOf("4", "5"))) graph.put("3", HashSet(listOf("6", "7"))) assertEquals("1234567".split("").subList(1, 8), injector.sortRelations(graph)) } @Test(expected = RuntimeException::class) fun sortRelationsWithCycle() { val injector = DifkInjector() val graph: MutableMap<String, MutableSet<String>> = HashMap() graph.put("1", HashSet(listOf("2", "3"))) graph.put("2", HashSet(listOf("4", "5"))) graph.put("3", HashSet(listOf("6", "1"))) injector.sortRelations(graph) } class DataSource(val url: String, val driverClassName: String, val username: String, val password: String) class Dao(val dataSource: DataSource) class Service(val dao: Dao) { var closed: Boolean? = null fun init() { closed = false } fun close() { closed = true } } }
apache-2.0
fb22f3048770a5a2b8ceb9bbd2704189
30.854331
110
0.613027
4.392508
false
true
false
false
samtstern/quickstart-android
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/LivePreviewActivity.kt
1
13113
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.samples.apps.mlkit.kotlin import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.hardware.Camera import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.CompoundButton import com.google.android.gms.common.annotation.KeepName import com.google.firebase.ml.common.FirebaseMLException import com.google.firebase.samples.apps.mlkit.R import com.google.firebase.samples.apps.mlkit.common.CameraSource import com.google.firebase.samples.apps.mlkit.kotlin.barcodescanning.BarcodeScanningProcessor import com.google.firebase.samples.apps.mlkit.kotlin.custommodel.CustomImageClassifierProcessor import com.google.firebase.samples.apps.mlkit.kotlin.facedetection.FaceContourDetectorProcessor import com.google.firebase.samples.apps.mlkit.kotlin.facedetection.FaceDetectionProcessor import com.google.firebase.samples.apps.mlkit.kotlin.imagelabeling.ImageLabelingProcessor import com.google.firebase.samples.apps.mlkit.kotlin.textrecognition.TextRecognitionProcessor import java.io.IOException import com.google.firebase.samples.apps.mlkit.kotlin.objectdetection.ObjectDetectorProcessor import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions import com.google.firebase.samples.apps.mlkit.common.preference.SettingsActivity import com.google.firebase.samples.apps.mlkit.common.preference.SettingsActivity.LaunchSource import com.google.firebase.samples.apps.mlkit.databinding.ActivityLivePreviewBinding import com.google.firebase.samples.apps.mlkit.kotlin.automl.AutoMLImageLabelerProcessor import com.google.firebase.samples.apps.mlkit.kotlin.automl.AutoMLImageLabelerProcessor.Mode /** Demo app showing the various features of ML Kit for Firebase. This class is used to * set up continuous frame processing on frames from a camera source. */ @KeepName class LivePreviewActivity : AppCompatActivity(), OnRequestPermissionsResultCallback, OnItemSelectedListener, CompoundButton.OnCheckedChangeListener { private var cameraSource: CameraSource? = null private var selectedModel = FACE_CONTOUR private lateinit var binding: ActivityLivePreviewBinding private val requiredPermissions: Array<String?> get() { return try { val info = this.packageManager .getPackageInfo(this.packageName, PackageManager.GET_PERMISSIONS) val ps = info.requestedPermissions if (ps != null && ps.isNotEmpty()) { ps } else { arrayOfNulls(0) } } catch (e: Exception) { arrayOfNulls(0) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") binding = ActivityLivePreviewBinding.inflate(layoutInflater) setContentView(binding.root) val options = arrayListOf( FACE_CONTOUR, FACE_DETECTION, OBJECT_DETECTION, AUTOML_IMAGE_LABELING, TEXT_DETECTION, BARCODE_DETECTION, IMAGE_LABEL_DETECTION, CLASSIFICATION_QUANT, CLASSIFICATION_FLOAT ) // Creating adapter for spinner val dataAdapter = ArrayAdapter(this, R.layout.spinner_style, options) // Drop down layout style - list view with radio button dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // attaching data adapter to spinner with(binding) { spinner.adapter = dataAdapter spinner.onItemSelectedListener = this@LivePreviewActivity facingSwitch.setOnCheckedChangeListener(this@LivePreviewActivity) // Hide the toggle button if there is only 1 camera if (Camera.getNumberOfCameras() == 1) { facingSwitch.visibility = View.GONE } } if (allPermissionsGranted()) { createCameraSource(selectedModel) } else { getRuntimePermissions() } } @Synchronized override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) selectedModel = parent.getItemAtPosition(pos).toString() Log.d(TAG, "Selected model: $selectedModel") binding.firePreview.stop() if (allPermissionsGranted()) { createCameraSource(selectedModel) startCameraSource() } else { getRuntimePermissions() } } override fun onNothingSelected(parent: AdapterView<*>) { // Do nothing. } override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { Log.d(TAG, "Set facing") cameraSource?.let { if (isChecked) { it.setFacing(CameraSource.CAMERA_FACING_FRONT) } else { it.setFacing(CameraSource.CAMERA_FACING_BACK) } } binding.firePreview.stop() startCameraSource() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.live_preview_menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.settings) { val intent = Intent(this, SettingsActivity::class.java) intent.putExtra(SettingsActivity.EXTRA_LAUNCH_SOURCE, LaunchSource.LIVE_PREVIEW) startActivity(intent) return true } return super.onOptionsItemSelected(item) } private fun createCameraSource(model: String) { // If there's no existing cameraSource, create one. if (cameraSource == null) { cameraSource = CameraSource(this, binding.fireFaceOverlay) } try { when (model) { CLASSIFICATION_QUANT -> { Log.i(TAG, "Using Custom Image Classifier (quant) Processor") cameraSource?.setMachineLearningFrameProcessor( CustomImageClassifierProcessor( this, true ) ) } CLASSIFICATION_FLOAT -> { Log.i(TAG, "Using Custom Image Classifier (float) Processor") cameraSource?.setMachineLearningFrameProcessor( CustomImageClassifierProcessor( this, false ) ) } TEXT_DETECTION -> { Log.i(TAG, "Using Text Detector Processor") cameraSource?.setMachineLearningFrameProcessor(TextRecognitionProcessor()) } FACE_DETECTION -> { Log.i(TAG, "Using Face Detector Processor") cameraSource?.setMachineLearningFrameProcessor(FaceDetectionProcessor(resources)) } OBJECT_DETECTION -> { Log.i(TAG, "Using Object Detector Processor") val objectDetectorOptions = FirebaseVisionObjectDetectorOptions.Builder() .setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE) .enableClassification().build() cameraSource?.setMachineLearningFrameProcessor( ObjectDetectorProcessor(objectDetectorOptions) ) } AUTOML_IMAGE_LABELING -> { cameraSource?.setMachineLearningFrameProcessor(AutoMLImageLabelerProcessor(this, Mode.LIVE_PREVIEW)) } BARCODE_DETECTION -> { Log.i(TAG, "Using Barcode Detector Processor") cameraSource?.setMachineLearningFrameProcessor(BarcodeScanningProcessor()) } IMAGE_LABEL_DETECTION -> { Log.i(TAG, "Using Image Label Detector Processor") cameraSource?.setMachineLearningFrameProcessor(ImageLabelingProcessor()) } FACE_CONTOUR -> { Log.i(TAG, "Using Face Contour Detector Processor") cameraSource?.setMachineLearningFrameProcessor(FaceContourDetectorProcessor()) } else -> Log.e(TAG, "Unknown model: $model") } } catch (e: FirebaseMLException) { Log.e(TAG, "can not create camera source: $model") } } /** * Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet * (e.g., because onResume was called before the camera source was created), this will be called * again when the camera source is created. */ private fun startCameraSource() { cameraSource?.let { try { binding.firePreview.start(cameraSource, binding.fireFaceOverlay) } catch (e: IOException) { Log.e(TAG, "Unable to start camera source.", e) cameraSource?.release() cameraSource = null } } } public override fun onResume() { super.onResume() Log.d(TAG, "onResume") startCameraSource() } /** Stops the camera. */ override fun onPause() { super.onPause() binding.firePreview.stop() } public override fun onDestroy() { super.onDestroy() cameraSource?.release() } private fun allPermissionsGranted(): Boolean { for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission!!)) { return false } } return true } private fun getRuntimePermissions() { val allNeededPermissions = arrayListOf<String>() for (permission in requiredPermissions) { if (!isPermissionGranted(this, permission!!)) { allNeededPermissions.add(permission) } } if (allNeededPermissions.isNotEmpty()) { ActivityCompat.requestPermissions( this, allNeededPermissions.toTypedArray(), PERMISSION_REQUESTS ) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { Log.i(TAG, "Permission granted!") if (allPermissionsGranted()) { createCameraSource(selectedModel) } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } companion object { private const val FACE_DETECTION = "Face Detection" private const val TEXT_DETECTION = "Text Detection" private const val OBJECT_DETECTION = "Object Detection" private const val AUTOML_IMAGE_LABELING = "AutoML Vision Edge" private const val BARCODE_DETECTION = "Barcode Detection" private const val IMAGE_LABEL_DETECTION = "Label Detection" private const val CLASSIFICATION_QUANT = "Classification (quantized)" private const val CLASSIFICATION_FLOAT = "Classification (float)" private const val FACE_CONTOUR = "Face Contour" private const val TAG = "LivePreviewActivity" private const val PERMISSION_REQUESTS = 1 private fun isPermissionGranted(context: Context, permission: String): Boolean { if (ContextCompat.checkSelfPermission( context, permission ) == PackageManager.PERMISSION_GRANTED ) { Log.i(TAG, "Permission granted: $permission") return true } Log.i(TAG, "Permission NOT granted: $permission") return false } } }
apache-2.0
239fa834a79b82224ff2aaed1d67630e
38.978659
120
0.63235
5.174822
false
false
false
false
cicakhq/potato
contrib/rqjava/src/com/dhsdevelopments/rqjava/PotatoConnection.kt
1
2414
package com.dhsdevelopments.rqjava import com.google.gson.Gson import com.rabbitmq.client.* import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.InputStreamReader import java.nio.charset.Charset import java.util.logging.Level import java.util.logging.Logger class PotatoConnection(val host: String, val virtualHost: String, val username: String, val password: String) { companion object { val SEND_MESSAGE_EXCHANGE_NAME = "chat-image-response-ex" } private var conn: Connection? = null val amqpConn: Connection get() = conn!! fun connect() { val fac = ConnectionFactory() fac.virtualHost = virtualHost fac.username = username fac.password = password fac.host = host conn = fac.newConnection() } fun disconnect() { val connCopy = synchronized(this) { conn.apply { conn = null } } if (connCopy == null) { throw IllegalStateException("Already disconnected") } connCopy.close() } fun subscribeChannel(cid: String, callback: (Message) -> Unit): ChannelSubscription { return ChannelSubscription(this, cid, callback) } fun registerCmd(cmd: String, callback: (Command) -> Unit): CmdRegistration { return CmdRegistration(this, cmd, callback) } fun sendMessage(sender: String, cid: String, text: String, extraHtml: String? = null) { val channel = amqpConn.createChannel() try { val content = StringBuilder() content.append("(:POST (\"") content.append(cid) content.append("\" :SENDER \"") content.append(sender) content.append("\" :TEXT \"") content.append(escapeSexpString(text)) content.append("\"") if(extraHtml != null) { content.append(" :EXTRA-HTML \"") content.append(escapeSexpString(extraHtml)) content.append("\"") } content.append("))") channel.basicPublish(SEND_MESSAGE_EXCHANGE_NAME, cid, null, content.toString().toByteArray(CHARSET_NAME_UTF8)) } finally { channel.close() } } private fun escapeSexpString(text: String) = text.replace("\"", "\\\"") }
apache-2.0
e41b861abeddad9208fd3abfcc6134b0
28.802469
122
0.586164
4.546139
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/data/collector/phonedata/collector/ClientAppVersionCollector.kt
1
1576
package com.telenav.osv.data.collector.phonedata.collector import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Handler import com.telenav.osv.data.collector.datatype.datatypes.ClientAppVersionObject import com.telenav.osv.data.collector.datatype.util.LibraryUtil import com.telenav.osv.data.collector.phonedata.manager.PhoneDataListener import timber.log.Timber /** * Collects the version of the client application */ class ClientAppVersionCollector(phoneDataListener: PhoneDataListener?, notifyHandler: Handler?) : PhoneCollector(phoneDataListener, notifyHandler) { /** * Retrieve the client app name */ fun sendClientVersion(context: Context?) { var pinfo: PackageInfo? = null var clientVersion: String? = null try { if (context != null && context.packageManager != null && context.packageName != null) { pinfo = context.packageManager.getPackageInfo(context.packageName, 0) } if (pinfo != null) { clientVersion = pinfo.versionName } } catch (e: PackageManager.NameNotFoundException) { Timber.tag("ClientVersionCollector").e(e) } if (clientVersion != null && !clientVersion.isEmpty()) { onNewSensorEvent(ClientAppVersionObject(clientVersion, LibraryUtil.PHONE_SENSOR_READ_SUCCESS)) } else { onNewSensorEvent(ClientAppVersionObject(clientVersion, LibraryUtil.PHONE_SENSOR_NOT_AVAILABLE)) } } }
lgpl-3.0
d07592b51f87edfe23911d92d980a2b1
40.5
148
0.700508
4.718563
false
false
false
false
ivaneye/kt-jvm
src/com/ivaneye/ktjvm/model/FieldInfo.kt
1
690
package com.ivaneye.ktjvm.model import com.ivaneye.ktjvm.model.attr.Attribute import com.ivaneye.ktjvm.type.U2 /** * Created by wangyifan on 2017/5/17. */ class FieldInfo(val accFlag: U2, val nameIdx: U2, val descIdx: U2, val attrCount: U2, val attrs: Array<Attribute>, val classInfo: ClassInfo) { override fun toString(): String { var str = "" for(attr in attrs){ str += attr.toString() } return "FieldInfo(accFlag=${accFlag.toHexString()},name=${classInfo.cpInfos[nameIdx.toInt()]!!.value()}," + "desc=${classInfo.cpInfos[descIdx.toInt()]!!.value()},attrCount=${attrCount.toInt() },attrs=[$str])" } }
apache-2.0
23e5a00c2245a7f9356ab0f0e85f03a3
35.368421
142
0.626087
3.612565
false
false
false
false
exponent/exponent
android/expoview/src/main/java/host/exp/exponent/di/NativeModuleDepsProvider.kt
2
3340
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.di import android.app.Application import android.content.Context import android.os.Handler import android.os.Looper import com.facebook.proguard.annotations.DoNotStrip import expo.modules.updates.db.DatabaseHolder import expo.modules.updates.db.UpdatesDatabase import host.exp.exponent.ExpoHandler import host.exp.exponent.ExponentManifest import host.exp.exponent.analytics.EXL import host.exp.exponent.kernel.services.ExpoKernelServiceRegistry import host.exp.exponent.network.ExponentNetwork import host.exp.exponent.storage.ExponentSharedPreferences import java.lang.reflect.Field import javax.inject.Inject class NativeModuleDepsProvider(application: Application) { @Inject @DoNotStrip val mContext: Context = application @Inject @DoNotStrip val mApplicationContext: Application = application @Inject @DoNotStrip val mExpoHandler: ExpoHandler = ExpoHandler(Handler(Looper.getMainLooper())) @Inject @DoNotStrip val mExponentSharedPreferences: ExponentSharedPreferences = ExponentSharedPreferences(mContext) @Inject @DoNotStrip val mExponentNetwork: ExponentNetwork = ExponentNetwork(mContext, mExponentSharedPreferences) @Inject @DoNotStrip var mExponentManifest: ExponentManifest = ExponentManifest(mContext, mExponentSharedPreferences) @Inject @DoNotStrip var mKernelServiceRegistry: ExpoKernelServiceRegistry = ExpoKernelServiceRegistry(mContext, mExponentSharedPreferences) @Inject @DoNotStrip val mUpdatesDatabaseHolder: DatabaseHolder = DatabaseHolder(UpdatesDatabase.getInstance(mContext)) private val classToInstanceMap = mutableMapOf<Class<*>, Any>() fun add(clazz: Class<*>, instance: Any) { classToInstanceMap[clazz] = instance } fun inject(clazz: Class<*>, target: Any) { for (field in clazz.declaredFields) { injectFieldInTarget(target, field) } } private fun injectFieldInTarget(target: Any, field: Field) { if (field.isAnnotationPresent(Inject::class.java)) { val fieldClazz = field.type if (!classToInstanceMap.containsKey(fieldClazz)) { throw RuntimeException("NativeModuleDepsProvider could not find object for class $fieldClazz") } val instance = classToInstanceMap[fieldClazz] try { field.isAccessible = true field[target] = instance } catch (e: IllegalAccessException) { EXL.e(TAG, e.toString()) } } } companion object { private val TAG = NativeModuleDepsProvider::class.java.simpleName @JvmStatic lateinit var instance: NativeModuleDepsProvider private set private var useTestInstance = false fun initialize(application: Application) { if (!useTestInstance) { instance = NativeModuleDepsProvider(application) } } // Only for testing! fun setTestInstance(instance: NativeModuleDepsProvider) { Companion.instance = instance useTestInstance = true } } init { for (field in NativeModuleDepsProvider::class.java.declaredFields) { if (field.isAnnotationPresent(Inject::class.java)) { try { classToInstanceMap[field.type] = field[this] } catch (e: IllegalAccessException) { EXL.e(TAG, e.toString()) } } } } }
bsd-3-clause
30258e14644515b557f134361b60e5ae
28.557522
121
0.741018
4.737589
false
false
false
false
AndroidX/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/impl/UseCaseManager.kt
3
13265
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.camera2.pipe.integration.impl import android.media.MediaCodec import android.os.Build import androidx.annotation.GuardedBy import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.core.Log import androidx.camera.camera2.pipe.integration.adapter.CameraStateAdapter import androidx.camera.camera2.pipe.integration.config.CameraConfig import androidx.camera.camera2.pipe.integration.config.CameraScope import androidx.camera.camera2.pipe.integration.config.UseCaseCameraComponent import androidx.camera.camera2.pipe.integration.config.UseCaseCameraConfig import androidx.camera.camera2.pipe.integration.interop.Camera2CameraControl import androidx.camera.camera2.pipe.integration.interop.ExperimentalCamera2Interop import androidx.camera.core.UseCase import androidx.camera.core.impl.DeferrableSurface import androidx.camera.core.impl.SessionConfig.ValidatingBuilder import javax.inject.Inject import kotlinx.coroutines.Job import kotlinx.coroutines.joinAll /** * This class keeps track of the currently attached and active [UseCase]'s for a specific camera. * A [UseCase] during its lifetime, can be: * * - Attached: This happens when a use case is bound to a CameraX Lifecycle, and signals that the * camera should be opened, and a camera capture session should be created to include the * stream corresponding to the use case. In the integration layer here, we'll recreate a * CameraGraph when a use case is attached. * - Detached: This happens when a use case is unbound from a CameraX Lifecycle, and signals that * we no longer need this specific use case and therefore its corresponding stream in our * current capture session. In the integration layer, we'll also recreate a CameraGraph when * a use case is detached, though it might not be strictly necessary. * - Active: This happens when the use case is considered "ready", meaning that the use case is * ready to have frames delivered to it. In the case of the integration layer, this means we * can start submitting the capture requests corresponding to the use case. An important note * here is that a use case can actually become "active" before it is "attached", and thus we * should only take action when a use case is both "attached" and "active". * - Inactive: This happens when use case no longer needs frames delivered to it. This is can be * seen as an optimization signal, as we technically are allowed to continue submitting * capture requests, but we no longer need to. An example of this is when you clear the * analyzer during ImageAnalysis. * * In this class, we also define a new term - "Running". A use case is considered running when it's * both "attached" and "active". This means we should have a camera opened, a capture session with * the streams created and have capture requests submitting. */ @OptIn(ExperimentalCamera2Interop::class) @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java @CameraScope class UseCaseManager @Inject constructor( private val cameraConfig: CameraConfig, private val builder: UseCaseCameraComponent.Builder, @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") // Java version required for Dagger private val controls: java.util.Set<UseCaseCameraControl>, private val camera2CameraControl: Camera2CameraControl, private val cameraStateAdapter: CameraStateAdapter, cameraProperties: CameraProperties, displayInfoManager: DisplayInfoManager, ) { private val lock = Any() @GuardedBy("lock") private val attachedUseCases = mutableSetOf<UseCase>() @GuardedBy("lock") private val activeUseCases = mutableSetOf<UseCase>() private val meteringRepeating by lazy { MeteringRepeating.Builder( cameraProperties, displayInfoManager ).build() } @Volatile private var _activeComponent: UseCaseCameraComponent? = null val camera: UseCaseCamera? get() = _activeComponent?.getUseCaseCamera() private val closingCameraJobs = mutableListOf<Job>() private val allControls = controls.toMutableSet().apply { add(camera2CameraControl) } /** * This attaches the specified [useCases] to the current set of attached use cases. When any * changes are identified (i.e., a new use case is added), the subsequent actions would trigger * a recreation of the current CameraGraph if there is one. */ fun attach(useCases: List<UseCase>) = synchronized(lock) { if (useCases.isEmpty()) { Log.warn { "Attach [] from $this (Ignored)" } return } Log.debug { "Attaching $useCases from $this" } // Notify state attached to use cases for (useCase in useCases) { if (!attachedUseCases.contains(useCase)) { useCase.onStateAttached() } } if (attachedUseCases.addAll(useCases)) { if (shouldAddRepeatingUseCase(getRunningUseCases())) { addRepeatingUseCase() return } refreshAttachedUseCases(attachedUseCases) } } /** * This detaches the specified [useCases] from the current set of attached use cases. When any * changes are identified (i.e., an existing use case is removed), the subsequent actions would * trigger a recreation of the current CameraGraph. */ fun detach(useCases: List<UseCase>) = synchronized(lock) { if (useCases.isEmpty()) { Log.warn { "Detaching [] from $this (Ignored)" } return } Log.debug { "Detaching $useCases from $this" } // When use cases are detached, they should be considered inactive as well. Also note that // we remove the use cases from our set directly because the subsequent cleanup actions from // detaching the use cases should suffice here. activeUseCases.removeAll(useCases) // Notify state detached to use cases for (useCase in useCases) { if (attachedUseCases.contains(useCase)) { useCase.onStateDetached() } } // TODO: We might only want to tear down when the number of attached use cases goes to // zero. If a single UseCase is removed, we could deactivate it? if (attachedUseCases.removeAll(useCases)) { if (shouldRemoveRepeatingUseCase(getRunningUseCases())) { removeRepeatingUseCase() return } refreshAttachedUseCases(attachedUseCases) } } /** * This marks the specified [useCase] as active ("activate"). This refreshes the current set of * active use cases, and if any changes are identified, we update [UseCaseCamera] with the * latest set of "running" (attached and active) use cases, which will in turn trigger actions * for SessionConfig updates. */ fun activate(useCase: UseCase) = synchronized(lock) { if (activeUseCases.add(useCase)) { refreshRunningUseCases() } } /** * This marks the specified [useCase] as inactive ("deactivate"). This refreshes the current set * of active use cases, and if any changes are identified, we update [UseCaseCamera] with the * latest set of "running" (attached and active) use cases, which will in turn trigger actions * for SessionConfig updates. */ fun deactivate(useCase: UseCase) = synchronized(lock) { if (activeUseCases.remove(useCase)) { refreshRunningUseCases() } } fun update(useCase: UseCase) = synchronized(lock) { if (attachedUseCases.contains(useCase)) { refreshRunningUseCases() } } fun reset(useCase: UseCase) = synchronized(lock) { if (attachedUseCases.contains(useCase)) { refreshAttachedUseCases(attachedUseCases) } } suspend fun close() { val closingJobs = synchronized(lock) { if (attachedUseCases.isNotEmpty()) { detach(attachedUseCases.toList()) } meteringRepeating.onDetached() closingCameraJobs.toList() } closingJobs.joinAll() } override fun toString(): String = "UseCaseManager<${cameraConfig.cameraId}>" @GuardedBy("lock") private fun refreshRunningUseCases() { val runningUseCases = getRunningUseCases() when { shouldAddRepeatingUseCase(runningUseCases) -> addRepeatingUseCase() shouldRemoveRepeatingUseCase(runningUseCases) -> removeRepeatingUseCase() else -> camera?.runningUseCases = runningUseCases } } @GuardedBy("lock") private fun refreshAttachedUseCases(newUseCases: Set<UseCase>) { val useCases = newUseCases.toList() // Close prior camera graph camera.let { _activeComponent = null it?.close()?.let { closingJob -> closingCameraJobs.add(closingJob) closingJob.invokeOnCompletion { synchronized(lock) { closingCameraJobs.remove(closingJob) } } } } // Update list of active useCases if (useCases.isEmpty()) { for (control in allControls) { control.useCaseCamera = null control.reset() } return } // Create and configure the new camera component. _activeComponent = builder.config(UseCaseCameraConfig(useCases, cameraStateAdapter)).build() for (control in allControls) { control.useCaseCamera = camera } refreshRunningUseCases() } @GuardedBy("lock") private fun getRunningUseCases(): Set<UseCase> { return attachedUseCases.intersect(activeUseCases) } @GuardedBy("lock") private fun shouldAddRepeatingUseCase(runningUseCases: Set<UseCase>): Boolean { val meteringRepeatingEnabled = attachedUseCases.contains(meteringRepeating) val coreLibraryUseCases = runningUseCases.filterNot { it is MeteringRepeating } val onlyVideoCapture = coreLibraryUseCases.onlyVideoCapture() val requireMeteringRepeating = coreLibraryUseCases.requireMeteringRepeating() return !meteringRepeatingEnabled && (onlyVideoCapture || requireMeteringRepeating) } @GuardedBy("lock") private fun addRepeatingUseCase() { meteringRepeating.setupSession() attach(listOf(meteringRepeating)) activate(meteringRepeating) } @GuardedBy("lock") private fun shouldRemoveRepeatingUseCase(runningUseCases: Set<UseCase>): Boolean { val meteringRepeatingEnabled = runningUseCases.contains(meteringRepeating) val coreLibraryUseCases = runningUseCases.filterNot { it is MeteringRepeating } val onlyVideoCapture = coreLibraryUseCases.onlyVideoCapture() val requireMeteringRepeating = coreLibraryUseCases.requireMeteringRepeating() return meteringRepeatingEnabled && !onlyVideoCapture && !requireMeteringRepeating } @GuardedBy("lock") private fun removeRepeatingUseCase() { deactivate(meteringRepeating) detach(listOf(meteringRepeating)) meteringRepeating.onDetached() } private fun Collection<UseCase>.onlyVideoCapture(): Boolean { return isNotEmpty() && checkSurfaces { _, sessionSurfaces -> sessionSurfaces.isNotEmpty() && sessionSurfaces.all { it.containerClass == MediaCodec::class.java } } } private fun Collection<UseCase>.requireMeteringRepeating(): Boolean { return isNotEmpty() && checkSurfaces { repeatingSurfaces, sessionSurfaces -> // There is no repeating UseCases sessionSurfaces.isNotEmpty() && repeatingSurfaces.isEmpty() } } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) private fun Collection<UseCase>.checkSurfaces( predicate: ( repeatingSurfaces: List<DeferrableSurface>, sessionSurfaces: List<DeferrableSurface> ) -> Boolean ): Boolean = ValidatingBuilder().let { validatingBuilder -> forEach { useCase -> validatingBuilder.add(useCase.sessionConfig) } val sessionConfig = validatingBuilder.build() val captureConfig = sessionConfig.repeatingCaptureConfig return predicate(captureConfig.surfaces, sessionConfig.surfaces) } }
apache-2.0
cdf1faadf353a9dc2b49834184099087
39.815385
100
0.680136
4.889421
false
true
false
false
android/xAnd11
core/src/main/java/com/monksanctum/xand11/core/input/XKeyboardManager.kt
1
2633
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.monksanctum.xand11.input import org.monksanctum.xand11.core.KeyEvent import org.monksanctum.xand11.core.getMaxKeyCode import org.monksanctum.xand11.core.initCharMap class XKeyboardManager { val keysPerSym: Int val keyboardMap: IntArray val modifiers = byteArrayOf(KeyEvent.KEYCODE_SHIFT_LEFT.toByte(), KeyEvent.KEYCODE_SHIFT_RIGHT.toByte(), 0, 0, 0, 0, KeyEvent.KEYCODE_ALT_LEFT.toByte(), KeyEvent.KEYCODE_ALT_RIGHT.toByte(), 0, 0, 0, 0, 0, 0, 0, 0) private val mState = BooleanArray(modifiers.size) val state: Int get() { var state = 0 for (i in mState.indices) { if (mState[i]) { state = state or (1 shl i / 2) } } return state } init { val modifiers = intArrayOf(0, KeyEvent.META_SHIFT_ON, KeyEvent.META_ALT_ON) keysPerSym = modifiers.size val maxKeyCode = getMaxKeyCode() keyboardMap = IntArray(modifiers.size * maxKeyCode) initCharMap(keyboardMap, modifiers) keyboardMap[keysPerSym * KeyEvent.KEYCODE_DEL] = 127 for (i in this.modifiers.indices) { this.modifiers[i] = translate(this.modifiers[i].toInt()).toByte() } } fun translate(keyCode: Int): Int { return keyCode + 8 } private fun modIndex(keyCode: Int): Int { for (i in modifiers.indices) { if (modifiers[i].toInt() == keyCode) { return i } } return -1 } fun onKeyDown(keyCode: Int) { val modIndex = modIndex(translate(keyCode)) if (modIndex < 0) return mState[modIndex] = true } fun onKeyUp(keyCode: Int) { val modIndex = modIndex(translate(keyCode)) if (modIndex < 0) return mState[modIndex] = false } }
apache-2.0
18875fe16960e65a8db6cfa6ec190352
27.010638
83
0.584504
4.20607
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/layers/LinearGaugeLayer.kt
1
1810
package com.teamwizardry.librarianlib.facade.layers import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.value.IMValue import com.teamwizardry.librarianlib.facade.value.IMValueDouble import com.teamwizardry.librarianlib.math.Direction2d import com.teamwizardry.librarianlib.core.util.rect import kotlin.math.roundToInt public open class LinearGaugeLayer: GuiLayer { public constructor(): super() public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) /** * @see fillFraction */ public val fillFraction_im: IMValueDouble = imDouble(1.0) /** * How full the gauge is. Ranges from 0–1 */ public var fillFraction: Double by fillFraction_im /** * The direction to expand (e.g. [UP][Direction2d.UP] means the gauge will sit at the bottom and rise up) */ public var direction: Direction2d = Direction2d.UP /** * The contents of the gauge. This is the layer that is resized based on [fillFraction]. */ public val contents: GuiLayer = GuiLayer() init { this.add(contents) } override fun prepareLayout() { val fillFraction = fillFraction val totalSize = direction.axis.get(this.size) val fullSize = (totalSize * fillFraction).roundToInt() val emptySize = (totalSize * (1 - fillFraction)).roundToInt() contents.frame = when (direction) { Direction2d.UP -> rect(0, emptySize, width, fullSize) Direction2d.DOWN -> rect(0, 0, width, fullSize) Direction2d.LEFT -> rect(emptySize, 0, fullSize, height) Direction2d.RIGHT -> rect(0, 0, fullSize, height) } } }
lgpl-3.0
3f14999f4f92de37931c566e4a9f5008
33.788462
109
0.677544
3.956236
false
false
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/app/BaseApp.kt
2
3235
package com.ddu.app import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import java.lang.ref.WeakReference import java.util.* import kotlin.properties.Delegates open class BaseApp : Application(), Application.ActivityLifecycleCallbacks { companion object { var instance by Delegates.notNull<BaseApp>() lateinit var mApp: Application lateinit var mContext: Context var mainHandler = Handler(Looper.getMainLooper()) fun post(r: Runnable) { mainHandler.post(r) } fun postDelayed(r: Runnable, delayMillis: Long) { mainHandler.postDelayed(r, delayMillis) } fun getContext(): Application { return mApp } } lateinit var currentActivity: WeakReference<Activity> private val sCacheActivities: MutableMap<Int, WeakReference<Activity>> by lazy { mutableMapOf<Int, WeakReference<Activity>>() } val cacheActivities: Map<Int, WeakReference<Activity>>? get() = sCacheActivities override fun onCreate() { super.onCreate() mApp = this mContext = applicationContext } open fun addActivity(activity: Activity) { currentActivity = WeakReference(activity) val hashCode = activity.hashCode() if (sCacheActivities.containsKey(hashCode)) { sCacheActivities.remove(hashCode) } sCacheActivities.put(hashCode, WeakReference(activity)) } open fun removeActivity(activity: Activity) { val hashCode = activity.hashCode() if (sCacheActivities.containsKey(hashCode)) { sCacheActivities.remove(hashCode) } } open fun getCacheActivity(hashCode: Int): Activity? { val weakReference = sCacheActivities[hashCode] ?: return null return weakReference.get() } open fun finishAllActivity(): Int { var finishCount = 0 if (sCacheActivities != null && !sCacheActivities.isEmpty()) { val activities = ArrayList(sCacheActivities.values) for (activity in activities) { val tempActivity = activity.get() ?: continue sCacheActivities.remove(tempActivity.hashCode()) if (tempActivity !== currentActivity.get()) { if (tempActivity != null && !tempActivity.isFinishing) { tempActivity.finish() finishCount++ } } } } return finishCount } override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { addActivity(activity) } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityDestroyed(activity: Activity) { removeActivity(activity) } }
apache-2.0
5e0e5e41531679c36193116871fc5e3d
26.649573
85
0.637094
5.143084
false
false
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/ui/fragment/MeFragment.kt
2
8668
package com.ddu.ui.fragment import android.app.PendingIntent import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.SystemClock import android.util.Log import androidx.fragment.app.DialogFragment import com.ddu.R import com.ddu.app.BaseApp import com.ddu.icore.callback.InConsumer3 import com.ddu.icore.common.ext.act import com.ddu.icore.common.ext.ctx import com.ddu.icore.dialog.AlertDialogFragment import com.ddu.icore.dialog.BottomDialogFragment import com.ddu.icore.dialog.DefaultGridBottomDialogFragment import com.ddu.icore.entity.BottomItem import com.ddu.icore.entity.BottomItemEntity import com.ddu.icore.ui.fragment.DefaultFragment import com.ddu.icore.ui.help.ShapeInject import com.ddu.ui.fragment.person.PhoneInfoFragment import com.ddu.ui.fragment.person.SettingFragment import com.ddu.util.NotificationUtils import kotlinx.android.synthetic.main.fragment_me.* /** * Created by yzbzz on 2018/1/17. */ class MeFragment : DefaultFragment() { var mHits = LongArray(COUNTS) var dialog: AlertDialogFragment? = null var nid = 0 override fun initData(savedInstanceState: Bundle?) { dialog = AlertDialogFragment().apply { title = "彩蛋" msg = "逗你玩" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() } } } override fun getLayoutId(): Int { return R.layout.fragment_me } override fun initView() { setTitle(R.string.main_tab_me) tv_usr_name.text = "yzbzz" tv_usr_number.text = "186-xxxx-xxx" oiv_buddha.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2ffff00")) oiv_friend_link.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2fdbc40")) oiv_friend_link.setOnClickListener { showShareDialog() } oiv_plan.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b200ff00")) oiv_fav.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2ff0000")) oiv_eggs.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b2437fda")) oiv_eggs.setOnClickListener { System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1) mHits[mHits.size - 1] = SystemClock.uptimeMillis() if (mHits[0] >= SystemClock.uptimeMillis() - DURATION) { dialog?.let { if (!it.isVisible) { it.show(childFragmentManager, "") } } } } oiv_setting.setLefText(ShapeInject.TYPE_ROUND, Color.parseColor("#b234c749")) oiv_setting.setOnClickListener { startFragment(SettingFragment::class.java) } oiv_phone_info.enableDefaultLeftText(Color.parseColor("#b24897fa")) oiv_phone_info.setOnClickListener { startFragment(PhoneInfoFragment::class.java) } oiv_notification.enableDefaultLeftText(Color.parseColor("#b2ff4141")) oiv_notification.setOnClickListener { val intent = Intent("cn.android.intent.user.click") val pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) val builder = NotificationUtils.instance.getPrimaryNotification(ctx, "hello", "hello world") val builder1 = NotificationUtils.instance.getSecondNotification(ctx, "hello", "hello world") NotificationUtils.instance.notify(nid++, builder1) // NotificationUtils.instance.notify(2, builder1) } oiv_show_dialog.enableDefaultLeftText(Color.parseColor("#b234c749")) oiv_show_dialog.setOnClickListener { val dialog = AlertDialogFragment().apply { title = "彩蛋" msg = "逗你玩" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() } } dialog.show(parentFragmentManager, "") BaseApp.postDelayed(Runnable { val sb = StringBuilder() sb.append("isadd: ${dialog.isAdded} ") sb.append("isDetached: ${dialog.isDetached} ") sb.append("isHidden: ${dialog.isHidden} ") sb.append("isRemoving: ${dialog.isRemoving} ") sb.append("isVisible: ${dialog.isVisible} ") Log.v("lhz", sb.toString()) dialog.dismissAllowingStateLoss() }, 2000) } oiv_show_bottom_dialog.enableDefaultLeftText(Color.parseColor("#b2ff00ff")) oiv_show_bottom_dialog.setOnClickListener { showBottomDialog() } rl_person_info.setOnClickListener { val i = 5 / 0 } } companion object { internal const val COUNTS = 10//点击次数 internal const val DURATION = (3 * 1000).toLong()//规定有效时间 fun newInstance(): MeFragment { val fragment = MeFragment() val args = Bundle() fragment.arguments = args return fragment } } private fun showBottomDialog() { var shareEntities = mutableListOf<BottomItem>() val github = BottomItem() github.id = 0 github.icon = resources.getDrawable(R.drawable.me_friend_link_github) github.title = "GitHub" val blog = BottomItem() blog.id = 1 blog.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog.title = "Blog" val blog1 = BottomItem() blog1.id = 1 blog1.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog1.title = "Blog" val blog2 = BottomItem() blog2.id = 1 blog2.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog2.title = "Blog" val blog3 = BottomItem() blog3.id = 1 blog3.icon = resources.getDrawable(R.drawable.me_friend_link_blog) blog3.title = "Blog" shareEntities.add(github) shareEntities.add(blog) shareEntities.add(blog1) shareEntities.add(blog2) shareEntities.add(blog3) val dialogFragment = BottomDialogFragment.Builder() .setItems(shareEntities) .setTitle("分享") .gridLayout() .setItemClickListener(object : InConsumer3<DialogFragment, BottomItem, Int> { override fun accept(a: DialogFragment, d: BottomItem, p: Int) { a.dismissAllowingStateLoss() Log.v("lhz", "d: " + d.title + " p: " + p) } }).create() dialogFragment.showDialog(act) } private fun showShareDialog() { var shareEntities = mutableListOf<BottomItemEntity>() val github = BottomItemEntity() github.name = "GitHub" github.resId = R.drawable.me_friend_link_github github.data = "https://github.com/yzbzz" val blog = BottomItemEntity() blog.name = "Blog" blog.resId = R.drawable.me_friend_link_blog blog.data = "http://yzbzz.github.io" shareEntities.add(github) shareEntities.add(blog) val shareDialog = DefaultGridBottomDialogFragment.newInstance(list = shareEntities, cb = { data, _, shareDialog -> data?.apply { shareDialog.dismissAllowingStateLoss() val dialog = AlertDialogFragment().apply { title = "即将前往" msg = "${data.data}" leftText = "取消" rightText = "确定" mLeftClickListener = { _, _ -> dismissAllowingStateLoss() } mRightClickListener = { _, _ -> dismissAllowingStateLoss() val args = Bundle() args.putString("title", name) args.putString("url", data.data) startFragment(WebFragment::class.java, args) } } dialog.show(parentFragmentManager, "") } }) shareDialog.show(parentFragmentManager, "") } }
apache-2.0
2bac11a483aa12e3f7122b7d4c3c10b1
33.789474
122
0.582053
4.408415
false
false
false
false
androidx/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazyGridSpanLayoutProvider.kt
3
9773
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.foundation.ExperimentalFoundationApi import kotlin.math.min import kotlin.math.sqrt @Suppress("IllegalExperimentalApiUsage") // TODO (b/233188423): Address before moving to beta @OptIn(ExperimentalFoundationApi::class) internal class LazyGridSpanLayoutProvider(private val itemProvider: LazyGridItemProvider) { class LineConfiguration(val firstItemIndex: Int, val spans: List<TvGridItemSpan>) /** Caches the bucket info on lines 0, [bucketSize], 2 * [bucketSize], etc. */ private val buckets = ArrayList<Bucket>().apply { add(Bucket(0)) } /** * The interval at each we will store the starting element of lines. These will be then * used to calculate the layout of arbitrary lines, by starting from the closest * known "bucket start". The smaller the bucketSize, the smaller cost for calculating layout * of arbitrary lines but the higher memory usage for [buckets]. */ private val bucketSize get() = sqrt(1.0 * totalSize / slotsPerLine).toInt() + 1 /** Caches the last calculated line index, useful when scrolling in main axis direction. */ private var lastLineIndex = 0 /** Caches the starting item index on [lastLineIndex]. */ private var lastLineStartItemIndex = 0 /** Caches the span of [lastLineStartItemIndex], if this was already calculated. */ private var lastLineStartKnownSpan = 0 /** * Caches a calculated bucket, this is useful when scrolling in reverse main axis * direction. We cannot only keep the last element, as we would not know previous max span. */ private var cachedBucketIndex = -1 /** * Caches layout of [cachedBucketIndex], this is useful when scrolling in reverse main axis * direction. We cannot only keep the last element, as we would not know previous max span. */ private val cachedBucket = mutableListOf<Int>() /** * List of 1x1 spans if we do not have custom spans. */ private var previousDefaultSpans = emptyList<TvGridItemSpan>() private fun getDefaultSpans(currentSlotsPerLine: Int) = if (currentSlotsPerLine == previousDefaultSpans.size) { previousDefaultSpans } else { List(currentSlotsPerLine) { TvGridItemSpan(1) }.also { previousDefaultSpans = it } } val totalSize get() = itemProvider.itemCount /** The number of slots on one grid line e.g. the number of columns of a vertical grid. */ var slotsPerLine = 0 set(value) { if (value != field) { field = value invalidateCache() } } fun getLineConfiguration(lineIndex: Int): LineConfiguration { if (!itemProvider.hasCustomSpans) { // Quick return when all spans are 1x1 - in this case we can easily calculate positions. val firstItemIndex = lineIndex * slotsPerLine return LineConfiguration( firstItemIndex, getDefaultSpans(slotsPerLine.coerceAtMost(totalSize - firstItemIndex) .coerceAtLeast(0)) ) } val bucketIndex = min(lineIndex / bucketSize, buckets.size - 1) // We can calculate the items on the line from the closest cached bucket start item. var currentLine = bucketIndex * bucketSize var currentItemIndex = buckets[bucketIndex].firstItemIndex var knownCurrentItemSpan = buckets[bucketIndex].firstItemKnownSpan // ... but try using the more localised cached values. if (lastLineIndex in currentLine..lineIndex) { // The last calculated value is a better start point. Common when scrolling main axis. currentLine = lastLineIndex currentItemIndex = lastLineStartItemIndex knownCurrentItemSpan = lastLineStartKnownSpan } else if (bucketIndex == cachedBucketIndex && lineIndex - currentLine < cachedBucket.size ) { // It happens that the needed line start is fully cached. Common when scrolling in // reverse main axis, as we decided to cacheThisBucket previously. currentItemIndex = cachedBucket[lineIndex - currentLine] currentLine = lineIndex knownCurrentItemSpan = 0 } val cacheThisBucket = currentLine % bucketSize == 0 && lineIndex - currentLine in 2 until bucketSize if (cacheThisBucket) { cachedBucketIndex = bucketIndex cachedBucket.clear() } check(currentLine <= lineIndex) while (currentLine < lineIndex && currentItemIndex < totalSize) { if (cacheThisBucket) { cachedBucket.add(currentItemIndex) } var spansUsed = 0 while (spansUsed < slotsPerLine && currentItemIndex < totalSize) { val span = if (knownCurrentItemSpan == 0) { spanOf(currentItemIndex, slotsPerLine - spansUsed) } else { knownCurrentItemSpan.also { knownCurrentItemSpan = 0 } } if (spansUsed + span > slotsPerLine) { knownCurrentItemSpan = span break } currentItemIndex++ spansUsed += span } ++currentLine if (currentLine % bucketSize == 0 && currentItemIndex < totalSize) { val currentLineBucket = currentLine / bucketSize // This should happen, as otherwise this should have been used as starting point. check(buckets.size == currentLineBucket) buckets.add(Bucket(currentItemIndex, knownCurrentItemSpan)) } } lastLineIndex = lineIndex lastLineStartItemIndex = currentItemIndex lastLineStartKnownSpan = knownCurrentItemSpan val firstItemIndex = currentItemIndex val spans = mutableListOf<TvGridItemSpan>() var spansUsed = 0 while (spansUsed < slotsPerLine && currentItemIndex < totalSize) { val span = if (knownCurrentItemSpan == 0) { spanOf(currentItemIndex, slotsPerLine - spansUsed) } else { knownCurrentItemSpan.also { knownCurrentItemSpan = 0 } } if (spansUsed + span > slotsPerLine) break currentItemIndex++ spans.add(TvGridItemSpan(span)) spansUsed += span } return LineConfiguration(firstItemIndex, spans) } /** * Calculate the line of index [itemIndex]. */ fun getLineIndexOfItem(itemIndex: Int): LineIndex { if (totalSize <= 0) { return LineIndex(0) } require(itemIndex < totalSize) if (!itemProvider.hasCustomSpans) { return LineIndex(itemIndex / slotsPerLine) } val lowerBoundBucket = buckets.binarySearch { it.firstItemIndex - itemIndex }.let { if (it >= 0) it else -it - 2 } var currentLine = lowerBoundBucket * bucketSize var currentItemIndex = buckets[lowerBoundBucket].firstItemIndex require(currentItemIndex <= itemIndex) var spansUsed = 0 while (currentItemIndex < itemIndex) { val span = spanOf(currentItemIndex++, slotsPerLine - spansUsed) if (spansUsed + span < slotsPerLine) { spansUsed += span } else if (spansUsed + span == slotsPerLine) { ++currentLine spansUsed = 0 } else { // spansUsed + span > slotsPerLine ++currentLine spansUsed = span } if (currentLine % bucketSize == 0) { val currentLineBucket = currentLine / bucketSize if (currentLineBucket >= buckets.size) { buckets.add(Bucket(currentItemIndex - if (spansUsed > 0) 1 else 0)) } } } if (spansUsed + spanOf(itemIndex, slotsPerLine - spansUsed) > slotsPerLine) { ++currentLine } return LineIndex(currentLine) } private fun spanOf(itemIndex: Int, maxSpan: Int) = with(itemProvider) { with(TvLazyGridItemSpanScopeImpl) { maxCurrentLineSpan = maxSpan maxLineSpan = slotsPerLine getSpan(itemIndex).currentLineSpan.coerceIn(1, slotsPerLine) } } private fun invalidateCache() { buckets.clear() buckets.add(Bucket(0)) lastLineIndex = 0 lastLineStartItemIndex = 0 cachedBucketIndex = -1 cachedBucket.clear() } private class Bucket( /** Index of the first item in the bucket */ val firstItemIndex: Int, /** Known span of the first item. Not zero only if this item caused "line break". */ val firstItemKnownSpan: Int = 0 ) private object TvLazyGridItemSpanScopeImpl : TvLazyGridItemSpanScope { override var maxCurrentLineSpan = 0 override var maxLineSpan = 0 } }
apache-2.0
f311da82ce37669384c339f4afcb7da8
39.222222
100
0.624271
5.092757
false
false
false
false
androidx/androidx
bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothManager.kt
3
7248
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.bluetooth.core import android.bluetooth.BluetoothDevice as FwkBluetoothDevice import android.bluetooth.BluetoothGattServer as FwkBluetoothGattServer import android.bluetooth.BluetoothGattServerCallback as FwkBluetoothGattServerCallback import android.bluetooth.BluetoothManager as FwkBluetoothManager import android.bluetooth.BluetoothProfile as FwkBluetoothProfile import android.Manifest import android.content.Context import android.content.pm.PackageManager import androidx.annotation.RequiresFeature import androidx.annotation.RequiresPermission /** * High level manager used to obtain an instance of an {@link BluetoothAdapter} * and to conduct overall Bluetooth Management. * <p> * Use {@link android.content.Context#getSystemService(java.lang.String)} * with {@link Context#BLUETOOTH_SERVICE} to create an {@link BluetoothManager}, * then call {@link #getAdapter} to obtain the {@link BluetoothAdapter}. * </p> * <div class="special reference"> * <h3>Developer Guides</h3> * <p> * For more information about using BLUETOOTH, read the <a href= * "{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer * guide. * </p> * </div> * * @see Context#getSystemService * @see BluetoothAdapter#getDefaultAdapter() * * @hide */ // @SystemService(Context.BLUETOOTH_SERVICE) @RequiresFeature( name = PackageManager.FEATURE_BLUETOOTH, enforcement = "android.content.pm.PackageManager#hasSystemFeature" ) class BluetoothManager(context: Context) { companion object { private const val TAG = "BluetoothManager" private const val DBG = false } private val fwkBluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as FwkBluetoothManager /** * Get the BLUETOOTH Adapter for this device. * * @return the BLUETOOTH Adapter */ fun getAdapter(): BluetoothAdapter? { return BluetoothAdapter(fwkBluetoothManager.adapter ?: return null) } /** * Get the current connection state of the profile to the remote device. * * * This is not specific to any application configuration but represents * the connection state of the local Bluetooth adapter for certain profile. * This can be used by applications like status bar which would just like * to know the state of Bluetooth. * * @param device Remote bluetooth device. * @param profile GATT or GATT_SERVER * @return State of the profile connection. One of [FwkBluetoothProfile.STATE_CONNECTED], * [FwkBluetoothProfile.STATE_CONNECTING], [FwkBluetoothProfile.STATE_DISCONNECTED], * [FwkBluetoothProfile.STATE_DISCONNECTING] * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getConnectionState(device: FwkBluetoothDevice, profile: Int): Int { return fwkBluetoothManager.getConnectionState(device, profile) } /** * Get connected devices for the specified profile. * * * Return the set of devices which are in state [FwkBluetoothProfile.STATE_CONNECTED] * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available * * * This is not specific to any application configuration but represents * the connection state of Bluetooth for this profile. * This can be used by applications like status bar which would just like * to know the state of Bluetooth. * * @param profile GATT or GATT_SERVER * @return List of devices. The list will be empty on error. */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getConnectedDevices(profile: Int): List<FwkBluetoothDevice> { return fwkBluetoothManager.getConnectedDevices(profile) } /** * Get a list of devices that match any of the given connection * states. * * * If none of the devices match any of the given states, * an empty list will be returned. * * * This is not specific to any application configuration but represents * the connection state of the local Bluetooth adapter for this profile. * This can be used by applications like status bar which would just like * to know the state of the local adapter. * * @param profile GATT or GATT_SERVER * @param states Array of states. States can be one of [FwkBluetoothProfile.STATE_CONNECTED], * [FwkBluetoothProfile.STATE_CONNECTING], [FwkBluetoothProfile.STATE_DISCONNECTED], * [FwkBluetoothProfile.STATE_DISCONNECTING], * // TODO(ofy) Change FwkBluetoothProfile to core.BluetoothProfile when it is available * @return List of devices. The list will be empty on error. */ // @RequiresLegacyBluetoothPermission // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothDevice to core.BluetoothDevice when it is available fun getDevicesMatchingConnectionStates( profile: Int, states: IntArray ): List<FwkBluetoothDevice> { return fwkBluetoothManager.getDevicesMatchingConnectionStates(profile, states) } /** * Open a GATT Server * The callback is used to deliver results to Caller, such as connection status as well * as the results of any other GATT server operations. * The method returns a BluetoothGattServer instance. You can use BluetoothGattServer * to conduct GATT server operations. * * @param context App context * @param callback GATT server callback handler that will receive asynchronous callbacks. * @return BluetoothGattServer instance */ // @RequiresBluetoothConnectPermission @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) // TODO(ofy) Change FwkBluetoothGattServerCallback to core.BluetoothGattServerCallback when it is available // TODO(ofy) Change FwkBluetoothGattServer to core.BluetoothGattServer when it is available fun openGattServer( context: Context, callback: FwkBluetoothGattServerCallback ): FwkBluetoothGattServer { return fwkBluetoothManager.openGattServer(context, callback) } }
apache-2.0
2e87d2281c70ea030a2aee97dad84d7e
39.49162
111
0.733858
4.712614
false
false
false
false
jean79/yested
src/main/kotlin/net/yested/layout/containers/horizontal.kt
2
3071
package net.yested.layout.containers import jquery.jq import net.yested.* import net.yested.utils.css import net.yested.utils.registerResizeHandler import org.w3c.dom.HTMLElement class HorizontalContainer(width: Dimension, val height: Dimension? = null, val gap:Int = 0) : Component { private val items = arrayListOf<ContainerItem>() override val element = createElement("div") with { setAttribute("style", "position: relative; width: ${width.toHtml()}; height: ${height?.toHtml() ?: ""};") } init { element.whenAddedToDom { recalculatePositions() registerResizeHandler(element.parentNode as HTMLElement) { x, y -> recalculatePositions() } } } private fun needToCalculateHeight() = height == null fun column(width: Dimension, height: Dimension? = null, init: HTMLComponent.() -> Unit) { val child = Div() with { style = "position: absolute; overflow-x: hidden; height: ${height?.toHtml()};" init() } if (items.size > 0 && gap > 0) { val gap = createElement("div") with { setAttribute("style", "width: ${gap}px;")} element.appendChild(gap) } items.add(ContainerItem(child, width)) element.appendChild(child.element) recalculatePositions() if (needToCalculateHeight()) { recalculateHeight() registerResizeHandler(child.element) { x, y -> recalculateHeight() } } } private fun recalculatePositions() { val gaps = (items.size - 1) * gap val totalDimension = jq(element).width() val totalFixed = items.filter { it.dimension is Pixels }.map { (it.dimension as Pixels).value }.sum() val totalPercents = items.filter { it.dimension is Percent }.map { (it.dimension as Percent).value }.sum() val dimensionAvailableToPct = totalDimension.toInt() - totalFixed - gaps var position = 0 items.forEach { item -> val calculatedDimension: Int = if (item.dimension is Pixels) { item.dimension.value } else if (item.dimension is Percent) { (item.dimension.value / totalPercents * dimensionAvailableToPct).toInt() } else { throw Exception("Unsupported dimension type for horizontal column width: ${item.dimension}") } jq(item.div.element).css("left", "${position}px") jq(item.div.element).css("width", "${calculatedDimension}px") position += calculatedDimension + gap } } private fun recalculateHeight() { val maxHeightOfChildren = items.map { jq(it.div.element).height().toInt() }.max() jq(element).css("height", "$maxHeightOfChildren") } } fun HTMLComponent.horizontalContainer(width: Dimension, height: Dimension? = null, gap: Int = 0, init: HorizontalContainer.() -> Unit) { +(HorizontalContainer(width = width, height = height, gap = gap) with { init() }) }
mit
0dccd634c47506c7b1c873d12a642dd5
36.91358
137
0.608922
4.412356
false
false
false
false