repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| 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/localcontentmigration/UserFlagsProviderHelper.kt
|
1
|
3905
|
package org.wordpress.android.localcontentmigration
import com.yarolegovich.wellsql.WellSql
import org.wordpress.android.fluxc.model.QuickStartStatusModel
import org.wordpress.android.fluxc.model.QuickStartTaskModel
import org.wordpress.android.localcontentmigration.LocalContentEntityData.UserFlagsData
import org.wordpress.android.ui.prefs.AppPrefs.DeletablePrefKey
import org.wordpress.android.ui.prefs.AppPrefs.UndeletablePrefKey
import org.wordpress.android.ui.prefs.AppPrefsWrapper
import javax.inject.Inject
class UserFlagsProviderHelper @Inject constructor(
private val appPrefsWrapper: AppPrefsWrapper,
): LocalDataProviderHelper {
override fun getData(localEntityId: Int?): LocalContentEntityData =
UserFlagsData(
flags = appPrefsWrapper.getAllPrefs().filter(::shouldInclude),
quickStartStatusList = getAllQuickStartStatus(),
quickStartTaskList = getAllQuickStartTask(),
)
private fun shouldInclude(flag: Map.Entry<String, Any?>) =
userFlagsKeysSet.contains(flag.key) || userFlagsCompositeKeysSet.any { flag.key.startsWith(it) }
private val userFlagsCompositeKeysSet: Set<String> = setOf(
DeletablePrefKey.LAST_SELECTED_QUICK_START_TYPE.name,
DeletablePrefKey.SHOULD_SHOW_WEEKLY_ROUNDUP_NOTIFICATION.name,
)
private fun getAllQuickStartTask() = checkNotNull(WellSql.select(QuickStartTaskModel::class.java).asModel) {
"Provider failed because QuickStart task list was null."
}
private fun getAllQuickStartStatus() = checkNotNull(WellSql.select(QuickStartStatusModel::class.java).asModel) {
"Provider failed because QuickStart status list was null."
}
private val userFlagsKeysSet: Set<String> = setOf(
DeletablePrefKey.MAIN_PAGE_INDEX.name,
DeletablePrefKey.IMAGE_OPTIMIZE_ENABLED.name,
DeletablePrefKey.IMAGE_OPTIMIZE_WIDTH.name,
DeletablePrefKey.IMAGE_OPTIMIZE_QUALITY.name,
DeletablePrefKey.VIDEO_OPTIMIZE_ENABLED.name,
DeletablePrefKey.VIDEO_OPTIMIZE_WIDTH.name,
DeletablePrefKey.VIDEO_OPTIMIZE_QUALITY.name,
DeletablePrefKey.STRIP_IMAGE_LOCATION.name,
DeletablePrefKey.SUPPORT_EMAIL.name,
DeletablePrefKey.SUPPORT_NAME.name,
DeletablePrefKey.GUTENBERG_DEFAULT_FOR_NEW_POSTS.name,
DeletablePrefKey.USER_IN_GUTENBERG_ROLLOUT_GROUP.name,
DeletablePrefKey.SHOULD_AUTO_ENABLE_GUTENBERG_FOR_THE_NEW_POSTS.name,
DeletablePrefKey.SHOULD_AUTO_ENABLE_GUTENBERG_FOR_THE_NEW_POSTS_PHASE_2.name,
DeletablePrefKey.GUTENBERG_OPT_IN_DIALOG_SHOWN.name,
DeletablePrefKey.GUTENBERG_FOCAL_POINT_PICKER_TOOLTIP_SHOWN.name,
DeletablePrefKey.IS_QUICK_START_NOTICE_REQUIRED.name,
DeletablePrefKey.LAST_SKIPPED_QUICK_START_TASK.name,
DeletablePrefKey.POST_LIST_AUTHOR_FILTER.name,
DeletablePrefKey.POST_LIST_VIEW_LAYOUT_TYPE.name,
DeletablePrefKey.AZTEC_EDITOR_DISABLE_HW_ACC_KEYS.name,
DeletablePrefKey.READER_DISCOVER_WELCOME_BANNER_SHOWN.name,
DeletablePrefKey.SHOULD_SCHEDULE_CREATE_SITE_NOTIFICATION.name,
DeletablePrefKey.SELECTED_SITE_LOCAL_ID.name,
UndeletablePrefKey.THEME_IMAGE_SIZE_WIDTH.name,
UndeletablePrefKey.BOOKMARKS_SAVED_LOCALLY_DIALOG_SHOWN.name,
UndeletablePrefKey.IMAGE_OPTIMIZE_PROMO_REQUIRED.name,
UndeletablePrefKey.SWIPE_TO_NAVIGATE_NOTIFICATIONS.name,
UndeletablePrefKey.SWIPE_TO_NAVIGATE_READER.name,
UndeletablePrefKey.IS_MAIN_FAB_TOOLTIP_DISABLED.name,
UndeletablePrefKey.SHOULD_SHOW_STORIES_INTRO.name,
UndeletablePrefKey.SHOULD_SHOW_STORAGE_WARNING.name,
UndeletablePrefKey.LAST_USED_USER_ID.name
)
}
|
gpl-2.0
|
cef165d03f49701b09958520bce2b39c
| 52.493151 | 116 | 0.721895 | 4.3534 | false | false | false | false |
RedMadRobot/input-mask-android
|
inputmask/src/main/kotlin/com/redmadrobot/inputmask/model/state/ValueState.kt
|
1
|
3242
|
package com.redmadrobot.inputmask.model.state
import com.redmadrobot.inputmask.model.Next
import com.redmadrobot.inputmask.model.State
/**
* ### ValueState
*
* Represents mandatory characters in square brackets [].
*
* Accepts only characters of own type (see ```StateType```). Puts accepted characters into the
* result string.
*
* Returns accepted characters as an extracted value.
*
* @see ```ValueState.StateType```
*
* @author taflanidi
*/
class ValueState : State {
/**
* ### StateType
*
* ```Numeric``` stands for [9] characters
* ```Literal``` stands for [a] characters
* ```AlphaNumeric``` stands for [-] characters
* ```Ellipsis``` stands for […] characters
*/
sealed class StateType {
class Numeric : StateType()
class Literal : StateType()
class AlphaNumeric : StateType()
class Ellipsis(val inheritedType: StateType) : StateType()
class Custom(val character: Char, val characterSet: String) : StateType()
}
val type: StateType
/**
* Constructor for elliptical ```ValueState```
*/
constructor(inheritedType: StateType) : super(null) {
this.type = StateType.Ellipsis(inheritedType)
}
constructor(child: State?, type: StateType) : super(child) {
this.type = type
}
private fun accepts(character: Char): Boolean {
return when (this.type) {
is StateType.Numeric -> character.isDigit()
is StateType.Literal -> character.isLetter()
is StateType.AlphaNumeric -> character.isLetterOrDigit()
is StateType.Ellipsis -> when (this.type.inheritedType) {
is StateType.Numeric -> character.isDigit()
is StateType.Literal -> character.isLetter()
is StateType.AlphaNumeric -> character.isLetterOrDigit()
is StateType.Custom -> this.type.inheritedType.characterSet.contains(character)
else -> false
}
is StateType.Custom -> this.type.characterSet.contains(character)
}
}
override fun accept(character: Char): Next? {
if (!this.accepts(character)) return null
return Next(
this.nextState(),
character,
true,
character
)
}
val isElliptical: Boolean
get() = when (this.type) {
is StateType.Ellipsis -> true
else -> false
}
override fun nextState(): State = when (this.type) {
is StateType.Ellipsis -> this
else -> super.nextState()
}
override fun toString(): String {
return when (this.type) {
is StateType.Literal -> "[A] -> " + if (null == this.child) "null" else child.toString()
is StateType.Numeric -> "[0] -> " + if (null == this.child) "null" else child.toString()
is StateType.AlphaNumeric -> "[_] -> " + if (null == this.child) "null" else child.toString()
is StateType.Ellipsis -> "[…] -> " + if (null == this.child) "null" else child.toString()
is StateType.Custom -> "[" + this.type.character + "] -> " + if (null == this.child) "null" else child.toString()
}
}
}
|
mit
|
f83abd58ea81e88dced6a134bb50b0c0
| 31.707071 | 125 | 0.58987 | 4.387534 | false | false | false | false |
Applandeo/Material-Calendar-View
|
library/src/main/java/com/applandeo/materialcalendarview/CalendarView.kt
|
1
|
17685
|
package com.applandeo.materialcalendarview
import android.content.Context
import android.content.res.TypedArray
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.LayoutRes
import com.applandeo.materialcalendarview.adapters.CalendarPageAdapter
import com.applandeo.materialcalendarview.exceptions.ErrorsMessages
import com.applandeo.materialcalendarview.exceptions.OutOfDateRangeException
import com.applandeo.materialcalendarview.listeners.OnCalendarPageChangeListener
import com.applandeo.materialcalendarview.listeners.OnDayClickListener
import com.applandeo.materialcalendarview.listeners.OnDayLongClickListener
import com.applandeo.materialcalendarview.utils.*
import kotlinx.android.synthetic.main.calendar_view.view.*
import java.util.*
/**
* This class represents a view, displays to user as calendar. It allows to work in date picker
* mode or like a normal calendar. In a normal calendar mode it can displays an image under the day
* number. In both modes it marks today day. It also provides click on day events using
* OnDayClickListener which returns an EventDay object.
*
* @see EventDay
*
* @see OnDayClickListener
*
* XML attributes:
* - Set calendar type: type="classic or one_day_picker or many_days_picker or range_picker"
* - Set calendar header color: headerColor="@color/[color]"
* - Set calendar header label color: headerLabelColor="@color/[color]"
* - Set previous button resource: previousButtonSrc="@drawable/[drawable]"
* - Ser forward button resource: forwardButtonSrc="@drawable/[drawable]"
* - Set today label color: todayLabelColor="@color/[color]"
* - Set selection color: selectionColor="@color/[color]"
*
*
* Created by Applandeo Team.
*/
class CalendarView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private lateinit var calendarPageAdapter: CalendarPageAdapter
private lateinit var calendarProperties: CalendarProperties
private var currentPage: Int = 0
init {
initControl(CalendarProperties(context)) {
setAttributes(attrs)
}
}
//internal constructor to create CalendarView for the dialog date picker
internal constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
properties: CalendarProperties
) : this(context, attrs, defStyleAttr) {
initControl(properties, ::initAttributes)
}
private fun initControl(calendarProperties: CalendarProperties, onUiCreate: () -> Unit) {
this.calendarProperties = calendarProperties
LayoutInflater.from(context).inflate(R.layout.calendar_view, this)
initUiElements()
onUiCreate()
initCalendar()
}
/**
* This method set xml values for calendar elements
*
* @param attrs A set of xml attributes
*/
private fun setAttributes(attrs: AttributeSet?) {
context.obtainStyledAttributes(attrs, R.styleable.CalendarView).run {
initCalendarProperties(this)
initAttributes()
recycle()
}
}
private fun initCalendarProperties(typedArray: TypedArray) = with(calendarProperties) {
headerColor = typedArray.getColor(R.styleable.CalendarView_headerColor, 0)
headerLabelColor = typedArray.getColor(R.styleable.CalendarView_headerLabelColor, 0)
abbreviationsBarColor = typedArray.getColor(R.styleable.CalendarView_abbreviationsBarColor, 0)
abbreviationsLabelsColor = typedArray.getColor(R.styleable.CalendarView_abbreviationsLabelsColor, 0)
abbreviationsLabelsSize = typedArray.getDimension(R.styleable.CalendarView_abbreviationsLabelsSize, 0F)
pagesColor = typedArray.getColor(R.styleable.CalendarView_pagesColor, 0)
daysLabelsColor = typedArray.getColor(R.styleable.CalendarView_daysLabelsColor, 0)
anotherMonthsDaysLabelsColor = typedArray.getColor(R.styleable.CalendarView_anotherMonthsDaysLabelsColor, 0)
todayLabelColor = typedArray.getColor(R.styleable.CalendarView_todayLabelColor, 0)
selectionColor = typedArray.getColor(R.styleable.CalendarView_selectionColor, 0)
selectionLabelColor = typedArray.getColor(R.styleable.CalendarView_selectionLabelColor, 0)
disabledDaysLabelsColor = typedArray.getColor(R.styleable.CalendarView_disabledDaysLabelsColor, 0)
highlightedDaysLabelsColor = typedArray.getColor(R.styleable.CalendarView_highlightedDaysLabelsColor, 0)
calendarType = typedArray.getInt(R.styleable.CalendarView_type, CLASSIC)
maximumDaysRange = typedArray.getInt(R.styleable.CalendarView_maximumDaysRange, 0)
if (typedArray.hasValue(R.styleable.CalendarView_firstDayOfWeek)) {
firstDayOfWeek = typedArray.getInt(R.styleable.CalendarView_firstDayOfWeek, Calendar.MONDAY)
}
eventsEnabled = typedArray.getBoolean(R.styleable.CalendarView_eventsEnabled, calendarType == CLASSIC)
swipeEnabled = typedArray.getBoolean(R.styleable.CalendarView_swipeEnabled, true)
selectionDisabled = typedArray.getBoolean(R.styleable.CalendarView_selectionDisabled, false)
selectionBetweenMonthsEnabled = typedArray.getBoolean(R.styleable.CalendarView_selectionBetweenMonthsEnabled, false)
previousButtonSrc = typedArray.getDrawable(R.styleable.CalendarView_previousButtonSrc)
forwardButtonSrc = typedArray.getDrawable(R.styleable.CalendarView_forwardButtonSrc)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
typeface = typedArray.getFont(R.styleable.CalendarView_typeface)
todayTypeface = typedArray.getFont(R.styleable.CalendarView_todayTypeface)
}
}
private fun initAttributes() {
with(calendarProperties) {
rootView.setHeaderColor(headerColor)
rootView.setHeaderTypeface(typeface)
rootView.setHeaderVisibility(headerVisibility)
rootView.setAbbreviationsBarVisibility(abbreviationsBarVisibility)
rootView.setNavigationVisibility(navigationVisibility)
rootView.setHeaderLabelColor(headerLabelColor)
rootView.setAbbreviationsBarColor(abbreviationsBarColor)
rootView.setAbbreviationsLabels(abbreviationsLabelsColor, firstDayOfWeek)
rootView.setAbbreviationsLabelsSize(abbreviationsLabelsSize)
rootView.setPagesColor(pagesColor)
rootView.setTypeface(typeface)
rootView.setPreviousButtonImage(previousButtonSrc)
rootView.setForwardButtonImage(forwardButtonSrc)
calendarViewPager.swipeEnabled = swipeEnabled
}
setCalendarRowLayout()
}
/**
* This method set a first day of week, default is monday or sunday depending on user location
*/
fun setFirstDayOfWeek(weekDay: CalendarWeekDay) = with(calendarProperties) {
firstDayOfWeek = weekDay.value
rootView.setAbbreviationsLabels(abbreviationsLabelsColor, firstDayOfWeek)
}
fun setHeaderColor(@ColorRes color: Int) = with(calendarProperties) {
headerColor = color
rootView.setHeaderColor(headerColor)
}
fun setHeaderVisibility(visibility: Int) = with(calendarProperties) {
headerVisibility = visibility
rootView.setHeaderVisibility(headerVisibility)
}
fun setAbbreviationsBarVisibility(visibility: Int) = with(calendarProperties) {
abbreviationsBarVisibility = visibility
rootView.setAbbreviationsBarVisibility(abbreviationsBarVisibility)
}
fun setHeaderLabelColor(@ColorRes color: Int) = with(calendarProperties) {
headerLabelColor = color
rootView.setHeaderLabelColor(headerLabelColor)
}
fun setPreviousButtonImage(drawable: Drawable) = with(calendarProperties) {
previousButtonSrc = drawable
rootView.setPreviousButtonImage(previousButtonSrc)
}
fun setForwardButtonImage(drawable: Drawable) = with(calendarProperties) {
forwardButtonSrc = drawable
rootView.setForwardButtonImage(forwardButtonSrc)
}
fun setCalendarDayLayout(@LayoutRes layout: Int) {
calendarProperties.itemLayoutResource = layout
}
fun setSelectionBackground(@DrawableRes drawable: Int) {
calendarProperties.selectionBackground = drawable
}
private fun setCalendarRowLayout() {
if (calendarProperties.itemLayoutResource != R.layout.calendar_view_day) return
with(calendarProperties) {
itemLayoutResource = if (eventsEnabled) {
R.layout.calendar_view_day
} else {
R.layout.calendar_view_picker_day
}
}
}
private fun initUiElements() {
previousButton.setOnClickListener {
calendarViewPager.currentItem = calendarViewPager.currentItem - 1
}
forwardButton.setOnClickListener {
calendarViewPager.currentItem = calendarViewPager.currentItem + 1
}
}
private fun initCalendar() {
calendarPageAdapter = CalendarPageAdapter(context, calendarProperties)
calendarViewPager.adapter = calendarPageAdapter
calendarViewPager.onCalendarPageChangedListener(::renderHeader)
setUpCalendarPosition(Calendar.getInstance())
}
/**
* This method set calendar header label
*
* @param position Current calendar page number
*/
private fun renderHeader(position: Int) {
val calendar = calendarProperties.firstPageCalendarDate.clone() as Calendar
calendar.add(Calendar.MONTH, position)
if (!isScrollingLimited(calendar, position)) {
setHeaderName(calendar, position)
}
}
private fun setUpCalendarPosition(calendar: Calendar) {
calendar.setMidnight()
if (calendarProperties.calendarType == ONE_DAY_PICKER) {
calendarProperties.setSelectedDay(calendar)
}
with(calendarProperties.firstPageCalendarDate) {
time = calendar.time
this.add(Calendar.MONTH, -CalendarProperties.FIRST_VISIBLE_PAGE)
}
calendarViewPager.currentItem = CalendarProperties.FIRST_VISIBLE_PAGE
}
fun setOnPreviousPageChangeListener(listener: OnCalendarPageChangeListener) {
calendarProperties.onPreviousPageChangeListener = listener
}
fun setOnForwardPageChangeListener(listener: OnCalendarPageChangeListener) {
calendarProperties.onForwardPageChangeListener = listener
}
private fun isScrollingLimited(calendar: Calendar, position: Int): Boolean {
fun scrollTo(position: Int): Boolean {
calendarViewPager.currentItem = position
return true
}
return when {
calendarProperties.minimumDate.isMonthBefore(calendar) -> scrollTo(position + 1)
calendarProperties.maximumDate.isMonthAfter(calendar) -> scrollTo(position - 1)
else -> false
}
}
private fun setHeaderName(calendar: Calendar, position: Int) {
currentDateLabel.text = calendar.getMonthAndYearDate(context)
callOnPageChangeListeners(position)
}
// This method calls page change listeners after swipe calendar or click arrow buttons
private fun callOnPageChangeListeners(position: Int) {
when {
position > currentPage -> calendarProperties.onForwardPageChangeListener?.onChange()
position < currentPage -> calendarProperties.onPreviousPageChangeListener?.onChange()
}
currentPage = position
}
/**
* @param onDayClickListener OnDayClickListener interface responsible for handle clicks on calendar cells
* @see OnDayClickListener
*/
fun setOnDayClickListener(onDayClickListener: OnDayClickListener) {
calendarProperties.onDayClickListener = onDayClickListener
}
/**
* @param onDayLongClickListener OnDayClickListener interface responsible for handle long clicks on calendar cells
* @see OnDayLongClickListener
*/
fun setOnDayLongClickListener(onDayLongClickListener: OnDayLongClickListener) {
calendarProperties.onDayLongClickListener = onDayLongClickListener
}
/**
* This method set a current date of the calendar using Calendar object.
*
* @param date A Calendar object representing a date to which the calendar will be set
*
* Throws exception when set date is not between minimum and maximum date
*/
@Throws(OutOfDateRangeException::class)
fun setDate(date: Calendar) {
if (calendarProperties.minimumDate != null && date.before(calendarProperties.minimumDate)) {
throw OutOfDateRangeException(ErrorsMessages.OUT_OF_RANGE_MIN)
}
if (calendarProperties.maximumDate != null && date.after(calendarProperties.maximumDate)) {
throw OutOfDateRangeException(ErrorsMessages.OUT_OF_RANGE_MAX)
}
setUpCalendarPosition(date)
currentDateLabel.text = date.getMonthAndYearDate(context)
calendarPageAdapter.notifyDataSetChanged()
}
/**
* This method set a current and selected date of the calendar using Date object.
*
* @param currentDate A date to which the calendar will be set
*/
fun setDate(currentDate: Date) {
val calendar = Calendar.getInstance().apply { time = currentDate }
setDate(calendar)
}
/**
* This method is used to set a list of events displayed in calendar cells,
* visible as images under the day number.
*
* @param eventDays List of EventDay objects
* @see EventDay
*/
fun setEvents(eventDays: List<EventDay>) {
if (calendarProperties.eventsEnabled) {
calendarProperties.eventDays = eventDays
calendarPageAdapter.notifyDataSetChanged()
}
}
fun setCalendarDays(calendarDayProperties: List<CalendarDay>) {
calendarProperties.calendarDayProperties = calendarDayProperties.toMutableList()
calendarPageAdapter.notifyDataSetChanged()
}
/**
* List of Calendar objects representing a selected dates
*/
var selectedDates: List<Calendar>
get() = calendarPageAdapter.selectedDays
.map { it.calendar }
.sorted().toList()
set(selectedDates) {
calendarProperties.setSelectDays(selectedDates)
calendarPageAdapter.notifyDataSetChanged()
}
/**
* @return Calendar object representing a selected date
*/
@Deprecated("Use getFirstSelectedDate()", ReplaceWith("firstSelectedDate"))
val selectedDate: Calendar
get() = firstSelectedDate
/**
* @return Calendar object representing a selected date
*/
val firstSelectedDate: Calendar
get() = calendarPageAdapter.selectedDays.map { it.calendar }.first()
/**
* @return Calendar object representing a date of current calendar page
*/
val currentPageDate: Calendar
get() = (calendarProperties.firstPageCalendarDate.clone() as Calendar).apply {
set(Calendar.DAY_OF_MONTH, 1)
add(Calendar.MONTH, calendarViewPager.currentItem)
}
/**
* This method set a minimum available date in calendar
*
* @param calendar Calendar object representing a minimum date
*/
fun setMinimumDate(calendar: Calendar) {
calendarProperties.minimumDate = calendar
calendarPageAdapter.notifyDataSetChanged()
}
/**
* This method set a maximum available date in calendar
*
* @param calendar Calendar object representing a maximum date
*/
fun setMaximumDate(calendar: Calendar) {
calendarProperties.maximumDate = calendar
calendarPageAdapter.notifyDataSetChanged()
}
/**
* This method is used to return to current month page
*/
fun showCurrentMonthPage() {
val page = calendarViewPager.currentItem - midnightCalendar.getMonthsToDate(currentPageDate)
calendarViewPager.setCurrentItem(page, true)
}
/**
* This method removes all selected days from calendar
*/
fun clearSelectedDays() {
calendarProperties.selectedDays.clear()
calendarPageAdapter.notifyDataSetChanged()
}
fun setDisabledDays(disabledDays: List<Calendar>) {
calendarProperties.disabledDays = disabledDays
calendarPageAdapter.notifyDataSetChanged()
}
@Deprecated("Use setCalendarDays(List<CalendarDay>) with specific labelColor")
fun setHighlightedDays(highlightedDays: List<Calendar>) {
calendarProperties.highlightedDays = highlightedDays
calendarPageAdapter.notifyDataSetChanged()
}
fun setSwipeEnabled(swipeEnabled: Boolean) {
calendarProperties.swipeEnabled = swipeEnabled
calendarViewPager.swipeEnabled = calendarProperties.swipeEnabled
}
fun setSelectionBetweenMonthsEnabled(enabled: Boolean) {
calendarProperties.selectionBetweenMonthsEnabled = enabled
}
fun setOnPagePrepareListener(listener: OnPagePrepareListener) {
calendarProperties.onPagePrepareListener = listener
}
companion object {
const val CLASSIC = 0
const val ONE_DAY_PICKER = 1
const val MANY_DAYS_PICKER = 2
const val RANGE_PICKER = 3
}
}
|
apache-2.0
|
773d5cc7ebc8abdf489108e370c69995
| 37.87033 | 124 | 0.710206 | 5.081897 | false | false | false | false |
ingokegel/intellij-community
|
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/deft/meta/impl/fields.kt
|
1
|
1717
|
// 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.workspaceModel.codegen.deft.meta.impl
import com.intellij.workspaceModel.codegen.deft.meta.*
private val fieldObjType = ObjTypeImpl<ObjProperty<*, *>>()
sealed class ObjPropertyBase<T : Obj, V>(
override val receiver: ObjClass<T>,
override val name: String,
override val valueType: ValueType<V>,
override val valueKind: ObjProperty.ValueKind,
override val open: Boolean,
override val content: Boolean
) : ObjProperty<T, V> {
private val mutableOverrides: MutableList<ObjProperty<T, V>> = ArrayList()
private val mutableOverriddenBy: MutableList<ObjProperty<T, V>> = ArrayList()
override val suspend: Boolean
get() = false
override val objType: ObjType<*>
get() = fieldObjType
}
class OwnPropertyImpl<T : Obj, V>(
receiver: ObjClass<T>,
name: String,
valueType: ValueType<V>,
valueKind: ObjProperty.ValueKind,
open: Boolean,
content: Boolean,
override val constructorParameter: Boolean,
override val classLocalId: Int,
override val isKey: Boolean,
) : ObjPropertyBase<T, V>(receiver, name, valueType, valueKind, open, content), OwnProperty<T, V> {
override fun toString(): String = "$name (${receiver.name})"
}
class ExtPropertyImpl<T : Obj, V>(
receiver: ObjClass<T>,
name: String,
valueType: ValueType<V>,
valueKind: ObjProperty.ValueKind,
open: Boolean,
content: Boolean,
override val module: ObjModule,
override val moduleLocalId: Int
) : ObjPropertyBase<T, V>(receiver, name, valueType, valueKind, open, content), ExtProperty<T, V> {
override fun toString(): String = "$name (${receiver.name})"
}
|
apache-2.0
|
7107b57762ad76d50feeaf794e8bcd8f
| 31.415094 | 120 | 0.729179 | 3.858427 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/live/AHeavyInspectionsPerformanceTest.kt
|
4
|
3282
|
// 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.perf.live
import com.intellij.codeHighlighting.Pass
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.idea.perf.util.ExternalProject
import org.jetbrains.kotlin.idea.perf.util.lastPathSegment
import org.jetbrains.kotlin.idea.perf.suite.suite
import org.jetbrains.kotlin.idea.test.JUnit3RunnerWithInners
import org.junit.runner.RunWith
/**
* Run the only specified exceptions on the selected files in Kotlin project.
*
* Used for 'The Kotlin sources: kt files heavy inspections' graph.
*
* @TODO Should be run before typing tests as the testing project becomes unusable afterwards.
*/
@RunWith(JUnit3RunnerWithInners::class)
class AHeavyInspectionsPerformanceTest : UsefulTestCase() {
private val listOfFiles = arrayOf(
"libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/NewMultiplatformIT.kt",
"compiler/psi/src/org/jetbrains/kotlin/psi/KtElement.kt",
"compiler/psi/src/org/jetbrains/kotlin/psi/KtFile.kt",
"compiler/psi/src/org/jetbrains/kotlin/psi/KtImportInfo.kt"
)
private val listOfInspections = arrayOf(
"UnusedSymbol",
"MemberVisibilityCanBePrivate"
)
private val passesToIgnore = ((1 until 100) - Pass.LOCAL_INSPECTIONS - Pass.WHOLE_FILE_LOCAL_INSPECTIONS).toIntArray()
fun testLocalInspection() {
suite {
app {
project(ExternalProject.KOTLIN_GRADLE) {
for (inspection in listOfInspections) {
enableSingleInspection(inspection)
for (file in listOfFiles) {
val editorFile = editor(file)
measure<List<HighlightInfo>>(inspection, file.lastPathSegment()) {
test = {
highlight(editorFile, passesToIgnore)
}
}
}
}
}
}
}
}
fun testUnusedSymbolLocalInspection() {
suite {
with(config) {
warmup = 1
iterations = 2
//profilerConfig.enabled = true
//profilerConfig.tracing = true
}
app {
project(ExternalProject.KOTLIN_AUTO) {
for (inspection in listOfInspections.sliceArray(0 until 1)) {
enableSingleInspection(inspection)
for (file in listOfFiles.sliceArray(0 until 1)) {
val editorFile = editor(file)
measure<List<HighlightInfo>>(inspection, file.lastPathSegment()) {
test = {
highlight(editorFile, passesToIgnore)
}
}
}
}
}
}
}
}
}
|
apache-2.0
|
8bdcc6f8b610202b050bd7032c1174d5
| 38.542169 | 158 | 0.570384 | 5.176656 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/framework/JavaFrameworkSupportProvider.kt
|
4
|
3950
|
// 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.framework
import com.intellij.framework.FrameworkTypeEx
import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable
import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider
import com.intellij.ide.util.frameworkSupport.FrameworkSupportModel
import com.intellij.openapi.module.JavaModuleType
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.roots.ModifiableModelsProvider
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.roots.ui.configuration.FacetsProvider
import com.intellij.openapi.roots.ui.configuration.libraries.CustomLibraryDescription
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.projectConfiguration.JavaRuntimeLibraryDescription
import org.jetbrains.kotlin.idea.configuration.BuildSystemType
import org.jetbrains.kotlin.idea.configuration.buildSystemType
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.formatter.ProjectCodeStyleImporter
import org.jetbrains.kotlin.idea.projectConfiguration.JSLibraryStdDescription
import org.jetbrains.kotlin.idea.statistics.WizardStatsService
import org.jetbrains.kotlin.idea.statistics.WizardStatsService.ProjectCreationStats
import javax.swing.JComponent
class JavaFrameworkSupportProvider : FrameworkSupportInModuleProvider() {
override fun getFrameworkType(): FrameworkTypeEx = JavaFrameworkType.instance
override fun createConfigurable(model: FrameworkSupportModel): FrameworkSupportInModuleConfigurable {
return object : FrameworkSupportInModuleConfigurable() {
private var description: JavaRuntimeLibraryDescription? = null
override fun createLibraryDescription(): CustomLibraryDescription? {
description = JavaRuntimeLibraryDescription(model.project)
return description
}
override fun createComponent(): JComponent? = null
override fun isOnlyLibraryAdded(): Boolean = true
override fun addSupport(
module: Module,
rootModel: ModifiableRootModel,
modifiableModelsProvider: ModifiableModelsProvider
) {
FrameworksCompatibilityUtils.suggestRemoveIncompatibleFramework(
rootModel,
JSLibraryStdDescription.SUITABLE_LIBRARY_KINDS,
KotlinJvmBundle.message("presentable.name.kotlin.js")
)
description!!.finishLibConfiguration(module, rootModel, false)
val isNewProject = model.project == null
if (isNewProject) {
ProjectCodeStyleImporter.apply(module.project, KotlinStyleGuideCodeStyle.INSTANCE)
}
val projectCreationStats = ProjectCreationStats("Java", "Kotlin/JVM", "jps")
WizardStatsService.logDataOnProjectGenerated(session = null, module.project, projectCreationStats)
}
override fun onFrameworkSelectionChanged(selected: Boolean) {
if (selected) {
val providerId = "kotlin-js-framework-id"
if (model.isFrameworkSelected(providerId)) {
model.setFrameworkComponentEnabled(providerId, false)
}
}
}
}
}
override fun isEnabledForModuleType(moduleType: ModuleType<*>): Boolean = moduleType is JavaModuleType
override fun canAddSupport(module: Module, facetsProvider: FacetsProvider): Boolean {
return super.canAddSupport(module, facetsProvider) && module.buildSystemType == BuildSystemType.JPS
}
}
|
apache-2.0
|
c051cf634e174c3e935d0615341ad0e4
| 47.765432 | 158 | 0.72962 | 5.65093 | false | true | false | false |
ftomassetti/kolasu
|
core/src/test/kotlin/com/strumenta/kolasu/cli/CLITestStatsCommand.kt
|
1
|
11479
|
package com.strumenta.kolasu.cli
import com.strumenta.kolasu.parsing.ParsingResult
import org.junit.Test
import java.io.File
import kotlin.io.path.createTempDirectory
import kotlin.io.path.createTempFile
import kotlin.test.assertEquals
class CLITestStatsCommand {
@Test
fun runStatsOnSimpleFile() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", myFile.toString()))
assertEquals(
"""== Stats ==
[Did processing complete?]
files processed : 1
processing failed : 0
processing completed : 1
[Did processing complete successfully?]
processing completed with errors : 0
processing completed without errors : 1
total number of errors : 0""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
}
@Test
fun runStatsOnSimpleFileCsv() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", myFile.toString(), "--csv"))
assertEquals(
"""Saving Global Stats to global-stats.csv""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
val globalStatsFile = File("global-stats.csv")
assert(globalStatsFile.exists())
assertEquals(
"""Key,Value
filesProcessed,1
filesWithExceptions,0
filesProcessedSuccessfully,1
filesWithErrors,0
filesWithoutErrors,1
totalErrors,0
""".lines(),
globalStatsFile.readText().lines()
)
globalStatsFile.delete()
}
@Test
fun runStatsOnSimpleFileNoStats() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", "--no-stats", myFile.toString()))
assertEquals("""""", console.stdOutput.trim())
assertEquals("", console.errOutput)
}
@Test
fun runStatsOnSimpleFileNodeStats() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", "--no-stats", "--node-stats", myFile.toString()))
assertEquals(
"""== Node Stats ==
com.strumenta.kolasu.cli.MyCompilationUnit : 1
com.strumenta.kolasu.cli.MyEntityDecl : 2
com.strumenta.kolasu.cli.MyFieldDecl : 3
total number of nodes : 6""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
}
@Test
fun runNodeStatsOnSimpleFileCsv() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", myFile.toString(), "--no-stats", "--node-stats", "--csv"))
assertEquals(
"""Saving Node Stats to node-stats.csv""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
val nodeStatsFile = File("node-stats.csv")
assert(nodeStatsFile.exists())
assertEquals(
"""Key,Value
com.strumenta.kolasu.cli.MyCompilationUnit,1
com.strumenta.kolasu.cli.MyEntityDecl,2
com.strumenta.kolasu.cli.MyFieldDecl,3
total,6
""".lines(),
nodeStatsFile.readText().lines()
)
nodeStatsFile.delete()
}
@Test
fun runNodeStatsOnSimpleFileCsvWithSimpleNames() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", myFile.toString(), "--no-stats", "--node-stats", "--simple-names", "--csv"))
assertEquals(
"""Saving Node Stats to node-stats.csv""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
val nodeStatsFile = File("node-stats.csv")
assert(nodeStatsFile.exists())
assertEquals(
"""Key,Value
MyCompilationUnit,1
MyEntityDecl,2
MyFieldDecl,3
total,6
""".lines(),
nodeStatsFile.readText().lines()
)
nodeStatsFile.delete()
}
@Test
fun runStatsOnSimpleFileNodeStatsSimpleNames() {
val myDir = createTempDirectory()
val myFile = createTempFile(myDir, "myfile.mylang")
myDir.toFile().deleteOnExit()
myFile.toFile().deleteOnExit()
val parserInstantiator = { file: File ->
MyDummyParser().apply {
expectedResults[myFile.toFile()] = ParsingResult(
emptyList(),
MyCompilationUnit(
mutableListOf(
MyEntityDecl("Entity1", mutableListOf()),
MyEntityDecl(
"Entity2",
mutableListOf(
MyFieldDecl("f1"),
MyFieldDecl("f2"),
MyFieldDecl("f3"),
)
)
)
)
)
}
}
val console = CapturingCliktConsole()
val cliTool = CLITool(parserInstantiator, console)
cliTool.parse(arrayOf("stats", "--no-stats", "--node-stats", "-sn", myFile.toString()))
assertEquals(
"""== Node Stats ==
MyCompilationUnit : 1
MyEntityDecl : 2
MyFieldDecl : 3
total number of nodes : 6""",
console.stdOutput.trim()
)
assertEquals("", console.errOutput)
}
}
|
apache-2.0
|
662137336697489728623609e2f0f635
| 33.890578 | 115 | 0.463978 | 5.713788 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/emoji/JumboEmoji.kt
|
2
|
5574
|
package org.thoughtcrime.securesms.emoji
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.SystemClock
import androidx.annotation.MainThread
import org.signal.core.util.ThreadUtil
import org.signal.core.util.concurrent.SignalExecutors
import org.signal.core.util.concurrent.SimpleTask
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.components.emoji.parsing.EmojiDrawInfo
import org.thoughtcrime.securesms.emoji.protos.JumbomojiPack
import org.thoughtcrime.securesms.jobmanager.impl.AutoDownloadEmojiConstraint
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.ListenableFutureTask
import org.thoughtcrime.securesms.util.SoftHashMap
import java.io.IOException
import java.util.UUID
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
private val TAG = Log.tag(JumboEmoji::class.java)
/**
* For Jumbo Emojis, will download, add to in-memory cache, and load from disk.
*/
object JumboEmoji {
private val executor = ThreadUtil.trace(SignalExecutors.newCachedSingleThreadExecutor("jumbo-emoji"))
const val MAX_JUMBOJI_COUNT = 5
private const val JUMBOMOJI_SUPPORTED_VERSION = 5
private val cache: MutableMap<String, Bitmap> = SoftHashMap(16)
private val versionToFormat: MutableMap<UUID, String?> = hashMapOf()
private val downloadedJumbos: MutableSet<String> = mutableSetOf()
private val networkCheckThrottle: Long = TimeUnit.MINUTES.toMillis(1)
private var lastNetworkCheck: Long = 0
private var canDownload: Boolean = false
@Volatile
private var currentVersion: Int = -1
@JvmStatic
@MainThread
fun updateCurrentVersion(context: Context) {
SignalExecutors.BOUNDED.execute {
val version: EmojiFiles.Version = EmojiFiles.Version.readVersion(context, true) ?: return@execute
if (EmojiFiles.getLatestEmojiData(context, version)?.format != null) {
currentVersion = version.version
ThreadUtil.runOnMain { downloadedJumbos.addAll(SignalStore.emojiValues().getJumboEmojiSheets(version.version)) }
}
}
}
@JvmStatic
@MainThread
fun canDownloadJumbo(context: Context): Boolean {
val now = SystemClock.elapsedRealtime()
if (now - networkCheckThrottle > lastNetworkCheck) {
canDownload = AutoDownloadEmojiConstraint.canAutoDownloadJumboEmoji(context)
lastNetworkCheck = now
}
return canDownload && currentVersion >= JUMBOMOJI_SUPPORTED_VERSION
}
@JvmStatic
@MainThread
fun hasJumboEmoji(drawInfo: EmojiDrawInfo): Boolean {
return downloadedJumbos.contains(drawInfo.jumboSheet)
}
@Suppress("FoldInitializerAndIfToElvis")
@JvmStatic
@MainThread
fun loadJumboEmoji(context: Context, drawInfo: EmojiDrawInfo): LoadResult {
val applicationContext: Context = context.applicationContext
val archiveName = "jumbo/${drawInfo.jumboSheet}.proto"
val emojiName: String = drawInfo.rawEmoji!!
val bitmap: Bitmap? = cache[emojiName]
if (bitmap != null) {
return LoadResult.Immediate(bitmap)
}
val newTask = ListenableFutureTask<Bitmap> {
val version: EmojiFiles.Version? = EmojiFiles.Version.readVersion(applicationContext, true)
if (version == null) {
throw NoVersionData()
}
val format: String? = versionToFormat.getOrPut(version.uuid) {
EmojiFiles.getLatestEmojiData(context, version)?.format
}
if (format == null) {
throw NoVersionData()
}
currentVersion = version.version
var jumbos: EmojiFiles.JumboCollection = EmojiFiles.JumboCollection.read(applicationContext, version)
val uuid = jumbos.getUUIDForName(emojiName)
if (uuid == null) {
if (!AutoDownloadEmojiConstraint.canAutoDownloadJumboEmoji(applicationContext)) {
throw CannotAutoDownload()
}
Log.i(TAG, "No file for emoji, downloading jumbo")
EmojiDownloader.streamFileFromRemote(version, version.density, archiveName) { stream ->
stream.use { remote ->
val jumbomojiPack = JumbomojiPack.parseFrom(remote)
jumbomojiPack.itemsList.forEach { jumbo ->
val emojiNameEntry = EmojiFiles.Name(jumbo.name, UUID.randomUUID())
val outputStream = EmojiFiles.openForWriting(applicationContext, version, emojiNameEntry.uuid)
outputStream.use { jumbo.image.writeTo(it) }
jumbos = EmojiFiles.JumboCollection.append(applicationContext, jumbos, emojiNameEntry)
}
}
}
SignalStore.emojiValues().addJumboEmojiSheet(version.version, drawInfo.jumboSheet)
}
EmojiFiles.openForReadingJumbo(applicationContext, version, jumbos, emojiName).use { BitmapFactory.decodeStream(it, null, BitmapFactory.Options()) }
}
SimpleTask.run(executor, newTask::run) {
try {
val newBitmap: Bitmap? = newTask.get()
if (newBitmap == null) {
Log.w(TAG, "Failed to load jumbo emoji")
} else {
cache[emojiName] = newBitmap
downloadedJumbos.add(drawInfo.jumboSheet!!)
}
} catch (e: ExecutionException) {
// do nothing, emoji provider will log the exception
}
}
return LoadResult.Async(newTask)
}
class NoVersionData : Throwable()
class CannotAutoDownload : IOException()
sealed class LoadResult {
data class Immediate(val bitmap: Bitmap) : LoadResult()
data class Async(val task: ListenableFutureTask<Bitmap>) : LoadResult()
}
}
|
gpl-3.0
|
67c86746efa63a4bc5235c0992d32740
| 33.407407 | 154 | 0.724435 | 4.248476 | false | false | false | false |
CzBiX/v2ex-android
|
app/src/main/kotlin/com/czbix/v2ex/network/GlideConfig.kt
|
1
|
3905
|
package com.czbix.v2ex.network
import android.content.Context
import android.graphics.Bitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.Key
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
import com.bumptech.glide.module.AppGlideModule
import com.czbix.v2ex.model.loader.GooglePhotoUrlLoader
import timber.log.Timber
import java.io.InputStream
import java.security.MessageDigest
import kotlin.math.min
@GlideModule
class GlideConfig : AppGlideModule() {
override fun applyOptions(context: Context, builder: GlideBuilder) {
val diskCacheSize: Long = 32 * 1024 * 1024
builder.apply {
setDiskCache(InternalCacheDiskCacheFactory(context, diskCacheSize))
}
}
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.replace(GlideUrl::class.java, InputStream::class.java,
OkHttpUrlLoader.Factory(RequestHelper.client))
registry.prepend(String::class.java, InputStream::class.java, GooglePhotoUrlLoader.Factory())
}
class AtWidthMostStrategy(private val maxWidth: Int) : DownsampleStrategy() {
override fun getScaleFactor(sourceWidth: Int, sourceHeight: Int, requestedWidth: Int, requestedHeight: Int): Float {
val maxWidth = if (maxWidth == 0) requestedWidth else maxWidth
val fitWidth = min(sourceWidth, maxWidth)
return fitWidth.toFloat() / sourceWidth
}
override fun getSampleSizeRounding(sourceWidth: Int, sourceHeight: Int, requestedWidth: Int, requestedHeight: Int): SampleSizeRounding {
return SampleSizeRounding.QUALITY
}
}
class AtWidthMostTransformation(private val strategy: DownsampleStrategy) : BitmapTransformation() {
override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int,
outHeight: Int): Bitmap {
val srcWidth = toTransform.width
val srcHeight = toTransform.height
val scaleFactor = strategy.getScaleFactor(srcWidth, srcHeight, outWidth, outHeight)
if (scaleFactor == 1f) {
return toTransform
}
return Bitmap.createScaledBitmap(
toTransform,
(srcWidth * scaleFactor).toInt(),
(srcHeight * scaleFactor).toInt(),
true
)
}
override fun equals(other: Any?): Boolean {
return other is AtWidthMostTransformation
}
override fun hashCode(): Int {
return ID.hashCode()
}
override fun updateDiskCacheKey(messageDigest: MessageDigest) {
messageDigest.update(ID_BYTES)
}
companion object {
private val ID = AtWidthMostTransformation::class.java.canonicalName!!
private val ID_BYTES = ID.toByteArray(Key.CHARSET)
}
}
companion object {
private var lastMaxWidth = -1
private lateinit var lastStrategy : DownsampleStrategy
fun atWidthMost(maxWidth: Int = 0): DownsampleStrategy {
if (maxWidth != lastMaxWidth) {
Timber.v("Downsample strategy cache missed. Changed from %d to %d.", lastMaxWidth, maxWidth)
lastMaxWidth = maxWidth
lastStrategy = AtWidthMostStrategy(maxWidth)
}
return lastStrategy
}
}
}
|
apache-2.0
|
3fa84f35382d8ac9ad9b63c8bce5a25f
| 36.912621 | 144 | 0.675032 | 4.863014 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/util/chapter/ChapterRecognition.kt
|
2
|
4642
|
package eu.kanade.tachiyomi.util.chapter
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
/**
* -R> = regex conversion.
*/
object ChapterRecognition {
/**
* All cases with Ch.xx
* Mokushiroku Alice Vol.1 Ch. 4: Misrepresentation -R> 4
*/
private val basic = Regex("""(?<=ch\.) *([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""")
/**
* Regex used when only one number occurrence
* Example: Bleach 567: Down With Snowwhite -R> 567
*/
private val occurrence = Regex("""([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""")
/**
* Regex used when manga title removed
* Example: Solanin 028 Vol. 2 -> 028 Vol.2 -> 028Vol.2 -R> 028
*/
private val withoutManga = Regex("""^([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?""")
/**
* Regex used to remove unwanted tags
* Example Prison School 12 v.1 vol004 version1243 volume64 -R> Prison School 12
*/
private val unwanted = Regex("""(?<![a-z])(v|ver|vol|version|volume|season|s).?[0-9]+""")
/**
* Regex used to remove unwanted whitespace
* Example One Piece 12 special -R> One Piece 12special
*/
private val unwantedWhiteSpace = Regex("""(\s)(extra|special|omake)""")
fun parseChapterNumber(chapter: SChapter, manga: SManga) {
// If chapter number is known return.
if (chapter.chapter_number == -2f || chapter.chapter_number > -1f) {
return
}
// Get chapter title with lower case
var name = chapter.name.lowercase()
// Remove comma's from chapter.
name = name.replace(',', '.')
// Remove unwanted white spaces.
unwantedWhiteSpace.findAll(name).let {
it.forEach { occurrence -> name = name.replace(occurrence.value, occurrence.value.trim()) }
}
// Remove unwanted tags.
unwanted.findAll(name).let {
it.forEach { occurrence -> name = name.replace(occurrence.value, "") }
}
// Check base case ch.xx
if (updateChapter(basic.find(name), chapter)) {
return
}
// Check one number occurrence.
val occurrences: MutableList<MatchResult> = arrayListOf()
occurrence.findAll(name).let {
it.forEach { occurrence -> occurrences.add(occurrence) }
}
if (occurrences.size == 1) {
if (updateChapter(occurrences[0], chapter)) {
return
}
}
// Remove manga title from chapter title.
val nameWithoutManga = name.replace(manga.title.lowercase(), "").trim()
// Check if first value is number after title remove.
if (updateChapter(withoutManga.find(nameWithoutManga), chapter)) {
return
}
// Take the first number encountered.
if (updateChapter(occurrence.find(nameWithoutManga), chapter)) {
return
}
}
/**
* Check if volume is found and update chapter
* @param match result of regex
* @param chapter chapter object
* @return true if volume is found
*/
private fun updateChapter(match: MatchResult?, chapter: SChapter): Boolean {
match?.let {
val initial = it.groups[1]?.value?.toFloat()!!
val subChapterDecimal = it.groups[2]?.value
val subChapterAlpha = it.groups[3]?.value
val addition = checkForDecimal(subChapterDecimal, subChapterAlpha)
chapter.chapter_number = initial.plus(addition)
return true
}
return false
}
/**
* Check for decimal in received strings
* @param decimal decimal value of regex
* @param alpha alpha value of regex
* @return decimal/alpha float value
*/
private fun checkForDecimal(decimal: String?, alpha: String?): Float {
if (!decimal.isNullOrEmpty()) {
return decimal.toFloat()
}
if (!alpha.isNullOrEmpty()) {
if (alpha.contains("extra")) {
return .99f
}
if (alpha.contains("omake")) {
return .98f
}
if (alpha.contains("special")) {
return .97f
}
return if (alpha[0] == '.') {
// Take value after (.)
parseAlphaPostFix(alpha[1])
} else {
parseAlphaPostFix(alpha[0])
}
}
return .0f
}
/**
* x.a -> x.1, x.b -> x.2, etc
*/
private fun parseAlphaPostFix(alpha: Char): Float {
return ("0." + (alpha.code - 96).toString()).toFloat()
}
}
|
apache-2.0
|
cfe0b3be5b94da5e956e744cd5e891db
| 29.539474 | 103 | 0.553856 | 4.286242 | false | false | false | false |
taskworld/KxAndroid
|
kxandroid-formatter/src/main/kotlin/com/taskworld/kxandroid/formatter/TextViews.kt
|
1
|
818
|
package com.taskworld.kxandroid
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.widget.TextView
import com.taskworld.kxandroid.formatter.BoldURLSpan
import com.taskworld.kxandroid.formatter.TextViewWebLink
fun TextView.bindWebLink(displayText: String, vararg words: TextViewWebLink) {
val sb: SpannableStringBuilder = SpannableStringBuilder(displayText)
words.forEach {
val start = displayText.indexOf(it.text)
val end = start + it.text.length
if (start >= 0) {
val span = BoldURLSpan(it.url, it.onClick, it.updateDrawState)
sb.setSpan(span, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
}
text = sb
movementMethod = LinkMovementMethod.getInstance()
}
|
mit
|
42b586df762ebadb0e71c157bf1a57de
| 33.083333 | 78 | 0.739609 | 4.328042 | false | false | false | false |
google/android-fhir
|
datacapture/src/main/java/com/google/android/fhir/datacapture/validation/QuestionnaireResponseValidator.kt
|
1
|
14169
|
/*
* Copyright 2022 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.android.fhir.datacapture.validation
import android.content.Context
import org.hl7.fhir.r4.model.Questionnaire
import org.hl7.fhir.r4.model.QuestionnaireResponse
import org.hl7.fhir.r4.model.Type
object QuestionnaireResponseValidator {
/**
* Validates [QuestionnaireResponse] using the constraints defined in the [Questionnaire].
* - Each item in the [QuestionnaireResponse] must have a corresponding item in the
* [Questionnaire] with the same `linkId` and `type`
* - The order of items in the [QuestionnaireResponse] must be the same as the order of the items
* in the [Questionnaire]
* -
* [Items nested under group](http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.item)
* and
* [items nested under answer](http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.answer.item)
* should follow the same rules recursively
*
* Note that although all the items in the [Questionnaire] SHOULD be included in the
* [QuestionnaireResponse], we do not throw an exception for missing items. This allows the
* [QuestionnaireResponse] to not include items that are not enabled due to `enableWhen`.
*
* @throws IllegalArgumentException if `questionnaireResponse` does not match `questionnaire`'s
* URL (if specified)
* @throws IllegalArgumentException if there is no questionnaire item with the same `linkId` as a
* questionnaire response item
* @throws IllegalArgumentException if the questionnaire response items are out of order
* @throws IllegalArgumentException if multiple answers are provided for a non-repeat
* questionnaire item
*
* See http://www.hl7.org/fhir/questionnaireresponse.html#link for more information.
*
* @return a map[linkIdToValidationResultMap] of linkIds to list of ValidationResult
*/
fun validateQuestionnaireResponse(
questionnaire: Questionnaire,
questionnaireResponse: QuestionnaireResponse,
context: Context
): Map<String, List<ValidationResult>> {
val linkIdToValidationResultMap = mutableMapOf<String, MutableList<ValidationResult>>()
require(
questionnaireResponse.questionnaire == null ||
questionnaire.url == questionnaireResponse.questionnaire
) {
"Mismatching Questionnaire ${questionnaire.url} and QuestionnaireResponse (for Questionnaire ${questionnaireResponse.questionnaire})"
}
validateQuestionnaireResponseItems(
questionnaire.item,
questionnaireResponse.item,
context,
linkIdToValidationResultMap
)
return linkIdToValidationResultMap
}
private fun validateQuestionnaireResponseItems(
questionnaireItemList: List<Questionnaire.QuestionnaireItemComponent>,
questionnaireResponseItemList: List<QuestionnaireResponse.QuestionnaireResponseItemComponent>,
context: Context,
linkIdToValidationResultMap: MutableMap<String, MutableList<ValidationResult>>
): Map<String, List<ValidationResult>> {
val questionnaireItemListIterator = questionnaireItemList.iterator()
val questionnaireResponseItemListIterator = questionnaireResponseItemList.iterator()
while (questionnaireResponseItemListIterator.hasNext()) {
val questionnaireResponseItem = questionnaireResponseItemListIterator.next()
var questionnaireItem: Questionnaire.QuestionnaireItemComponent?
do {
require(questionnaireItemListIterator.hasNext()) {
"Missing questionnaire item for questionnaire response item ${questionnaireResponseItem.linkId}"
}
questionnaireItem = questionnaireItemListIterator.next()
} while (questionnaireItem!!.linkId != questionnaireResponseItem.linkId)
validateQuestionnaireResponseItem(
questionnaireItem,
questionnaireResponseItem,
context,
linkIdToValidationResultMap
)
}
return linkIdToValidationResultMap
}
private fun validateQuestionnaireResponseItem(
questionnaireItem: Questionnaire.QuestionnaireItemComponent,
questionnaireResponseItem: QuestionnaireResponse.QuestionnaireResponseItemComponent,
context: Context,
linkIdToValidationResultMap: MutableMap<String, MutableList<ValidationResult>>
): Map<String, List<ValidationResult>> {
when (checkNotNull(questionnaireItem.type) { "Questionnaire item must have type" }) {
Questionnaire.QuestionnaireItemType.DISPLAY,
Questionnaire.QuestionnaireItemType.NULL -> Unit
Questionnaire.QuestionnaireItemType.GROUP ->
// Nested items under group
// http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.item
validateQuestionnaireResponseItems(
questionnaireItem.item,
questionnaireResponseItem.item,
context,
linkIdToValidationResultMap
)
else -> {
require(questionnaireItem.repeats || questionnaireResponseItem.answer.size <= 1) {
"Multiple answers for non-repeat questionnaire item ${questionnaireItem.linkId}"
}
questionnaireResponseItem.answer.forEach {
validateQuestionnaireResponseItems(
questionnaireItem.item,
it.item,
context,
linkIdToValidationResultMap
)
}
linkIdToValidationResultMap[questionnaireItem.linkId] = mutableListOf()
linkIdToValidationResultMap[questionnaireItem.linkId]?.add(
QuestionnaireResponseItemValidator.validate(
questionnaireItem,
questionnaireResponseItem.answer,
context
)
)
}
}
return linkIdToValidationResultMap
}
/**
* Checks that the [QuestionnaireResponse] is structurally consistent with the [Questionnaire].
* - Each item in the [QuestionnaireResponse] must have a corresponding item in the
* [Questionnaire] with the same `linkId` and `type`
* - The order of items in the [QuestionnaireResponse] must be the same as the order of the items
* in the [Questionnaire]
* -
* [Items nested under group](http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.item)
* and
* [items nested under answer](http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.answer.item)
* should follow the same rules recursively
*
* Note that although all the items in the [Questionnaire] SHOULD be included in the
* [QuestionnaireResponse], we do not throw an exception for missing items. This allows the
* [QuestionnaireResponse] to not include items that are not enabled due to `enableWhen`.
*
* @throws IllegalArgumentException if `questionnaireResponse` does not match `questionnaire`'s
* URL (if specified)
* @throws IllegalArgumentException if there is no questionnaire item with the same `linkId` as a
* questionnaire response item
* @throws IllegalArgumentException if the questionnaire response items are out of order
* @throws IllegalArgumentException if the type of a questionnaire response item does not match
* that of the questionnaire item
* @throws IllegalArgumentException if multiple answers are provided for a non-repeat
* questionnaire item
*
* See http://www.hl7.org/fhir/questionnaireresponse.html#link for more information.
*/
fun checkQuestionnaireResponse(
questionnaire: Questionnaire,
questionnaireResponse: QuestionnaireResponse
) {
require(
questionnaireResponse.questionnaire == null ||
questionnaire.url == questionnaireResponse.questionnaire
) {
"Mismatching Questionnaire ${questionnaire.url} and QuestionnaireResponse (for Questionnaire ${questionnaireResponse.questionnaire})"
}
checkQuestionnaireResponseItems(questionnaire.item, questionnaireResponse.item)
}
private fun checkQuestionnaireResponseItems(
questionnaireItemList: List<Questionnaire.QuestionnaireItemComponent>,
questionnaireResponseItemList: List<QuestionnaireResponse.QuestionnaireResponseItemComponent>
) {
val questionnaireItemIterator = questionnaireItemList.iterator()
val questionnaireResponseInputItemIterator = questionnaireResponseItemList.iterator()
while (questionnaireResponseInputItemIterator.hasNext()) {
val questionnaireResponseItem = questionnaireResponseInputItemIterator.next()
var questionnaireItem: Questionnaire.QuestionnaireItemComponent?
do {
require(questionnaireItemIterator.hasNext()) {
"Missing questionnaire item for questionnaire response item ${questionnaireResponseItem.linkId}"
}
questionnaireItem = questionnaireItemIterator.next()
} while (questionnaireItem!!.linkId != questionnaireResponseItem.linkId)
checkQuestionnaireResponseItem(questionnaireItem, questionnaireResponseItem)
}
}
private fun checkQuestionnaireResponseItem(
questionnaireItem: Questionnaire.QuestionnaireItemComponent,
questionnaireResponseItem: QuestionnaireResponse.QuestionnaireResponseItemComponent,
) {
when (checkNotNull(questionnaireItem.type) { "Questionnaire item must have type" }) {
Questionnaire.QuestionnaireItemType.DISPLAY,
Questionnaire.QuestionnaireItemType.NULL -> Unit
Questionnaire.QuestionnaireItemType.GROUP ->
// Nested items under group
// http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.item
checkQuestionnaireResponseItems(questionnaireItem.item, questionnaireResponseItem.item)
else -> {
require(questionnaireItem.repeats || questionnaireResponseItem.answer.size <= 1) {
"Multiple answers for non-repeat questionnaire item ${questionnaireItem.linkId}"
}
questionnaireResponseItem.answer.forEach {
checkQuestionnaireResponseAnswerItem(questionnaireItem, it)
}
}
}
}
private fun checkQuestionnaireResponseAnswerItem(
questionnaireItem: Questionnaire.QuestionnaireItemComponent,
answerItem: QuestionnaireResponse.QuestionnaireResponseItemAnswerComponent
) {
if (answerItem.hasValue()) {
checkQuestionnaireResponseAnswerItemType(
questionnaireItem.linkId,
questionnaireItem.type,
answerItem.value
)
}
// Nested items under answer
// http://www.hl7.org/fhir/questionnaireresponse-definitions.html#QuestionnaireResponse.item.answer.item
checkQuestionnaireResponseItems(questionnaireItem.item, answerItem.item)
}
private fun checkQuestionnaireResponseAnswerItemType(
linkId: String,
questionnaireItemType: Questionnaire.QuestionnaireItemType,
value: Type
) {
val answerType = value.fhirType()
when (questionnaireItemType) {
Questionnaire.QuestionnaireItemType.BOOLEAN ->
require(answerType == "boolean") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.DECIMAL ->
require(answerType == "decimal") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.INTEGER ->
require(answerType == "integer") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.DATE ->
require(answerType == "date") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.DATETIME ->
require(answerType == "dateTime") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.TIME ->
require(answerType == "time") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.STRING ->
require(answerType == "string") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.TEXT ->
require(answerType == "string") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.URL ->
require(answerType == "url") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.CHOICE,
Questionnaire.QuestionnaireItemType.OPENCHOICE ->
require(answerType == "Coding" || answerType == "string") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.ATTACHMENT ->
require(answerType == "Attachment") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.REFERENCE ->
require(answerType == "Reference") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
Questionnaire.QuestionnaireItemType.QUANTITY ->
require(answerType == "Quantity") {
"Mismatching question type $questionnaireItemType and answer type $answerType for $linkId"
}
else -> Unit
}
}
}
|
apache-2.0
|
6453294136630e6a6e38f9f75588d796
| 43.980952 | 139 | 0.735973 | 5.383359 | false | false | false | false |
StPatrck/edac
|
app/src/main/java/com/phapps/elitedangerous/companion/viewmodels/CalculateRouteViewModel.kt
|
1
|
2007
|
package com.phapps.elitedangerous.companion.viewmodels
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.phapps.elitedangerous.edsm.EdsmClient
import com.phapps.elitedangerous.edsm.callbacks.PlanRouteCallbacks
import com.phapps.elitedangerous.edsm.dto.SystemJumpDto
import com.phapps.elitedangerous.edsm.requests.PlanRouteRequest
/**
* A [ViewModel] that maintains a list of [SystemJumpDto]s along the calculated route.
*/
class CalculateRouteViewModel : ViewModel() {
private var mJumps: MutableLiveData<List<SystemJumpDto>>? = null
/**
* Retrieve the list of jumps from the last calculated route.
*
* @return a list of [SystemJumpDto]s along the calculated route.
*/
fun getJumps(): LiveData<List<SystemJumpDto>> {
if (mJumps == null) {
mJumps = MutableLiveData()
}
return mJumps as LiveData<List<SystemJumpDto>>
}
/**
* Calculates the most direct route between two systems.
*
* @param request [PlanRouteRequest] containing parameters to be considered when calculating a
* route.
*
* @return List of [SystemJumpDto]s between
*/
fun calculateRoute(request: PlanRouteRequest): MutableLiveData<List<SystemJumpDto>> {
if (mJumps == null) {
mJumps = MutableLiveData()
}
EdsmClient.getInstance().planRoute(request, object : PlanRouteCallbacks {
override fun onSuccess(jumps: Array<out SystemJumpDto>?) {
mJumps?.value = jumps?.toList() ?: emptyList()
}
override fun onFail(error: String?) {
mJumps?.value = emptyList()
}
override fun onError() {
mJumps?.value = emptyList()
}
})
return mJumps as MutableLiveData<List<SystemJumpDto>>
}
override fun onCleared() {
super.onCleared()
mJumps = null
}
}
|
gpl-3.0
|
c007407b6289780bc9fa735c667768c9
| 30.359375 | 98 | 0.652715 | 4.353579 | false | false | false | false |
drakelord/wire
|
wire-schema/src/test/java/com/squareup/wire/schema/SchemaProtoAdapterTest.kt
|
1
|
9508
|
/*
* Copyright (C) 2015 Square, Inc.
*
* 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.squareup.wire.schema
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import okio.Buffer
import okio.ByteString
import okio.ByteString.Companion.decodeHex
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assert.fail
import org.junit.Test
import java.io.EOFException
import java.io.IOException
import java.net.ProtocolException
class SchemaProtoAdapterTest {
private val coffeeSchema = RepoBuilder()
.add("coffee.proto",
"""
|message CafeDrink {
| optional string customer_name = 1;
| repeated EspressoShot shots = 2;
| optional Foam foam = 3;
| optional int32 size_ounces = 14;
| optional Dairy dairy = 15;
|
| enum Foam {
| NOT_FOAMY_AND_QUITE_BORING = 1;
| ZOMG_SO_FOAMY = 3;
| }
|}
|
|message Dairy {
| optional int32 count = 2;
| optional string type = 1;
|}
|
|message EspressoShot {
| optional string bean_type = 1;
| optional double caffeine_level = 2;
|}
""".trimMargin()
)
.schema()
// Golden data emitted by protoc using the schema above.
private val dansCoffee = ImmutableMap.of<String, Any>(
"customer_name", "Dan",
"shots", ImmutableList.of(ImmutableMap.of("caffeine_level", 0.5)),
"size_ounces", 16,
"dairy", ImmutableMap.of("count", 1))
private val dansCoffeeEncoded = "0a0344616e120911000000000000e03f70107a021001".decodeHex()
private val jessesCoffee = ImmutableMap.of<String, Any>(
"customer_name", "Jesse",
"shots",
ImmutableList.of(
ImmutableMap.of<String, Any>("bean_type", "colombian", "caffeine_level", 1.0),
ImmutableMap.of<String, Any>("bean_type", "colombian", "caffeine_level", 1.0)
),
"foam", "ZOMG_SO_FOAMY",
"size_ounces", 24)
private val jessesCoffeeEncoded = ("0a054a6573736512140a09636f6c" +
"6f6d6269616e11000000000000f03f12140a09636f6c6f6d6269616e11000000000000f03f18037018")
.decodeHex()
@Test
fun decode() {
val adapter = coffeeSchema.protoAdapter("CafeDrink", true)
assertThat(adapter.decode(Buffer().write(dansCoffeeEncoded))).isEqualTo(dansCoffee)
assertThat(adapter.decode(Buffer().write(jessesCoffeeEncoded))).isEqualTo(jessesCoffee)
}
@Test
@Throws(IOException::class)
fun encode() {
val adapter = coffeeSchema.protoAdapter("CafeDrink", true)
assertThat(ByteString.of(*adapter.encode(dansCoffee))).isEqualTo(dansCoffeeEncoded)
assertThat(ByteString.of(*adapter.encode(jessesCoffee))).isEqualTo(jessesCoffeeEncoded)
}
@Test
@Throws(IOException::class)
fun groupsIgnored() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| optional string a = 1;
| // repeated group Group1 = 2 {
| // optional SomeMessage a = 11;
| // }
| // repeated group Group2 = 3 {
| // optional SomeMessage b = 21;
| // }
| optional string b = 4;
|}
""".trimMargin()
)
.protoAdapter("Message")
val encoded = ("0a0161135a02080114135a02100214135a090803720568656c6c" +
"6f141baa010208011c1baa010210021c1baa01090803720568656c6c6f1c220162")
.decodeHex()
val expected = ImmutableMap.of<String, Any>("a", "a", "b", "b")
assertThat(adapter.decode(Buffer().write(encoded))).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun startGroupWithoutEndGroup() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| optional string a = 1;
|}
""".trimMargin()
)
.protoAdapter("Message")
val encoded = "130a0161".decodeHex()
try {
adapter.decode(Buffer().write(encoded))
fail()
} catch (expected: EOFException) {
}
}
@Test
@Throws(IOException::class)
fun unexpectedEndGroup() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| optional string a = 1;
|}
""".trimMargin()
)
.protoAdapter("Message")
val encoded = "0a01611c".decodeHex()
try {
adapter.decode(Buffer().write(encoded))
fail()
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Unexpected end group")
}
}
@Test
@Throws(IOException::class)
fun endGroupDoesntMatchStartGroup() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| optional string a = 1;
|}
""".trimMargin()
)
.protoAdapter("Message")
val encoded = "130a01611c".decodeHex()
try {
adapter.decode(Buffer().write(encoded))
fail()
} catch (expected: ProtocolException) {
assertThat(expected).hasMessage("Unexpected end group")
}
}
@Test
@Throws(IOException::class)
fun decodeToUnpacked() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| repeated int32 a = 90 [packed = false];
|}
""".trimMargin()
)
.protoAdapter("Message")
val expected = ImmutableMap.of<String, Any>(
"a", ImmutableList.of(601, 701))
val packedEncoded = "d20504d904bd05".decodeHex()
assertThat(adapter.decode(Buffer().write(packedEncoded))).isEqualTo(expected)
val unpackedEncoded = "d005d904d005bd05".decodeHex()
assertThat(adapter.decode(Buffer().write(unpackedEncoded))).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun decodeToPacked() {
val adapter = RepoBuilder()
.add("message.proto",
"""
|message Message {
| repeated int32 a = 90 [packed = true];
|}
""".trimMargin()
)
.protoAdapter("Message")
val expected = ImmutableMap.of<String, Any>(
"a", ImmutableList.of(601, 701))
val unpackedEncoded = "d005d904d005bd05".decodeHex()
assertThat(adapter.decode(Buffer().write(unpackedEncoded))).isEqualTo(expected)
val packedEncoded = "d20504d904bd05".decodeHex()
assertThat(adapter.decode(Buffer().write(packedEncoded))).isEqualTo(expected)
}
@Test
@Throws(IOException::class)
fun recursiveMessage() {
val adapter = RepoBuilder()
.add("tree.proto",
"""
|message BinaryTreeNode {
| optional BinaryTreeNode left = 1;
| optional BinaryTreeNode right = 2;
| optional string value = 3;
|}
""".trimMargin()
)
.protoAdapter("BinaryTreeNode")
val value = ImmutableMap.of<String, Any>(
"value", "D",
"left", ImmutableMap.of(
"value", "B",
"left", ImmutableMap.of("value", "A"),
"right", ImmutableMap.of("value", "C")),
"right", ImmutableMap.of(
"value", "F",
"left", ImmutableMap.of("value", "E"),
"right", ImmutableMap.of("value", "G")))
val encoded = "1a01440a0d1a01420a031a014112031a0143120d1a01460a031a014512031a0147".decodeHex()
assertThat(ByteString.of(*adapter.encode(value))).isEqualTo(encoded)
assertThat(adapter.decode(Buffer().write(encoded))).isEqualTo(value)
}
@Test
fun includeUnknowns() {
val schema = RepoBuilder()
.add("coffee.proto", """
|message CafeDrink {
| optional string customer_name = 1;
| optional int32 size_ounces = 14;
|}
""".trimMargin()
)
.schema()
val dansCoffeeWithUnknowns = ImmutableMap.of<String, Any>(
"customer_name", "Dan",
"2", ImmutableList.of("11000000000000e03f".decodeHex()),
"size_ounces", 16,
"15", ImmutableList.of("1001".decodeHex()))
val adapter = schema.protoAdapter("CafeDrink", true)
assertThat(adapter.decode(Buffer().write(dansCoffeeEncoded)))
.isEqualTo(dansCoffeeWithUnknowns)
}
@Test
fun omitUnknowns() {
val schema = RepoBuilder()
.add("coffee.proto",
"""
|message CafeDrink {
| optional string customer_name = 1;
| optional int32 size_ounces = 14;
|}
""".trimMargin()
)
.schema()
val dansCoffeeWithoutUnknowns = ImmutableMap.of(
"customer_name", "Dan",
"size_ounces", 16)
val adapter = schema.protoAdapter("CafeDrink", false)
assertThat(adapter.decode(Buffer().write(dansCoffeeEncoded)))
.isEqualTo(dansCoffeeWithoutUnknowns)
}
}
|
apache-2.0
|
93ee47bbe77e6805b24019c1a782ab1c
| 30.379538 | 98 | 0.598654 | 3.984912 | false | true | false | false |
ngthtung2805/dalatlaptop
|
app/src/main/java/com/tungnui/abccomputer/SettingsMy.kt
|
1
|
2095
|
package com.tungnui.abccomputer
import android.content.Context
import android.content.SharedPreferences
import com.tungnui.abccomputer.app.MyApplication
import com.tungnui.abccomputer.models.Customer
import com.tungnui.abccomputer.utils.Utils
object SettingsMy {
val PREF_ACTIVE_USER = "pref_active_user"
val PREF_USER_EMAIL = "pref_user_email"
val REGISTRATION_COMPLETE = "registrationComplete"
private val TAG = SettingsMy::class.java.simpleName
private var activeUser: Customer? = null
private var sharedPref: SharedPreferences? = null
var userEmailHint: String
get() {
val prefs = settings
val userEmail = prefs.getString(PREF_USER_EMAIL, "")
return userEmail
}
set(userEmail) {
putParam(PREF_USER_EMAIL, userEmail)
}
val settings: SharedPreferences
get() {
if (sharedPref == null) {
sharedPref = MyApplication.instance?.getSharedPreferences(MyApplication.PACKAGE_NAME, Context.MODE_PRIVATE)
}
return sharedPref!!
}
fun isUserLogin():Boolean=if(getActiveUser()== null)false else true
fun getActiveUser(): Customer? {
if (activeUser != null) {
return activeUser
} else {
val prefs = settings
val json = prefs.getString(PREF_ACTIVE_USER, "")
if (json.isEmpty() || "null" == json) {
return null
} else {
activeUser = Utils.getGsonParser().fromJson(json, Customer::class.java)
return activeUser
}
}
}
fun setActiveUser(customer: Customer?) {
SettingsMy.activeUser = customer
val json = Utils.getGsonParser().toJson(SettingsMy.activeUser)
val editor = settings.edit()
editor.putString(PREF_ACTIVE_USER, json)
editor.apply()
}
private fun putParam(key: String, value: String): Boolean {
val editor = settings.edit()
editor.putString(key, value)
return editor.commit()
}
}
|
mit
|
bb4afb0fcfb092c1dac4746dd8b53219
| 31.734375 | 123 | 0.618138 | 4.624724 | false | false | false | false |
cdietze/klay
|
tripleklay/src/main/kotlin/tripleklay/anim/AnimGroup.kt
|
1
|
4897
|
package tripleklay.anim
/**
* Allows one to specify a group of one or more animations that will be queued up to be started on
* an [Animator] at some later time. All animations added to the group will be started in
* parallel.
* ```
* val group = AnimGroup()
* group.tweenXY(...).then().tweenAlpha(...)
* group.play(sound).then().action(...)
* // the two animation chains (the tween chain and the play/action chain) will run in parallel
* // after this group is added to an Animator
* anim.add(group.toAnim())
* ```
*
* One can combine multiple animation groups to achieve any desired construction of sequential and
* parallel animations.
* ```
* val group2 = AnimGroup()
* group2.tweenXY(...).then().tweenAlpha(...)
* group2.play(sound).then().action(...)
* val group1 = AnimGroup()
* group1.delay(1000f).then().add(group2.toAnim())
* group1.delay(500f).then().play(sound)
* // group 1's two animation chains will be queued up to run in parallel, and the first of its
* // chains will delay 1s and then trigger group 2's chains, which themselves run in parallel
* anim.add(group1.toAnim())
* ```
*
* It is of course also possible to add a group with a single animation chain, which will contain
* no parallelism but can still be useful for situations where one wants to compose sequences of
* animations internally and then return that package of animations to be sequenced with other
* packages of animations by some outer mechanism:
* ```
* class Ship {
* fun createExplosionAnim(): Animation {
* val group = AnimGroup()
* group.play(sound).then().flipbook(...)
* return group.toAnim()
* }
* }
* ```
*/
class AnimGroup : AnimBuilder() {
/**
* Adds an animation to this group. This animation will be started in parallel with all other
* animations added to this group when the group is turned into an animation and started via
* [Animator.add] or added to another chain of animations that was added to an animator.
* @throws IllegalStateException if this method is called directly or implicitly (by any of the
* * [AnimBuilder] fluent methods) after [.toAnim] has been called.
*/
override fun <T : Animation> add(anim: T): T {
if (_anims == null) throw IllegalStateException("AnimGroup already animated.")
_anims!!.add(anim)
return anim
}
/**
* Returns a single animation that will execute all of the animations in this group to
* completion (in parallel) and will report itself as complete when the final animation in the
* group is complete. After calling this method, this group becomes unusable. It is not valid
* to call [.add] (or any other method) after [.toAnim].
*/
fun toAnim(): Animation {
val groupAnims = _anims!!.toTypedArray()
_anims = null
return object : Animation() {
override fun init(time: Float) {
super.init(time)
for (ii in groupAnims.indices) {
_curAnims[ii] = groupAnims[ii]
_curAnims[ii]!!.init(time)
}
}
override fun apply(animator: Animator?, time: Float): Float {
_animator = animator
return super.apply(animator, time)
}
override fun apply(time: Float): Float {
var remain = Float.NEGATIVE_INFINITY
var processed = 0
for (ii in _curAnims.indices) {
val anim = _curAnims[ii] ?: continue
val aremain = anim.apply(_animator, time)
// if this animation is now complete, remove it from the array
if (aremain <= 0) _curAnims[ii] = null
// note this animation's leftover time, we want our remaining time to be the
// highest remaining time of our internal animations
remain = maxOf(remain, aremain)
// note that we processed an animation
processed++
}
// if we somehow processed zero animations, return 0 (meaning we're done) rather
// than -infinity which would throw off any animation queued up after this one
return if (processed == 0) 0f else remain
}
override fun makeComplete() {
// if we haven't started, complete all anims, otherwise just the active anims
val anims = if (_start == 0f) groupAnims else _curAnims
for (anim in anims) {
anim?.completeChain()
}
}
private var _animator: Animator? = null
private var _curAnims = arrayOfNulls<Animation>(groupAnims.size)
}
}
private var _anims: MutableList<Animation>? = ArrayList()
}
|
apache-2.0
|
36f287ebdda22d43221978c4dfeecead
| 41.582609 | 99 | 0.606494 | 4.496786 | false | false | false | false |
FireZenk/Kartographer
|
library/src/main/java/org/firezenk/kartographer/library/types/Path.kt
|
1
|
375
|
package org.firezenk.kartographer.library.types
data class Path(private val namespace: String) {
override fun equals(other: Any?): Boolean = if (other != null) {
val otherNamespace = (other as Path).namespace
this.namespace == otherNamespace
} else false
override fun hashCode() = namespace.hashCode()
override fun toString() = namespace
}
|
mit
|
6872cd60c0b994e1286480bd92b28c65
| 27.923077 | 68 | 0.693333 | 4.573171 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/facet/MinecraftFacetEditorTab.kt
|
1
|
9116
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.facet
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.platform.PlatformType
import com.intellij.facet.ui.FacetEditorTab
import com.intellij.util.ui.UIUtil
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class MinecraftFacetEditorTab(private val configuration: MinecraftFacetConfiguration) : FacetEditorTab() {
private lateinit var panel: JPanel
private lateinit var bukkitEnabledCheckBox: JCheckBox
private lateinit var bukkitAutoCheckBox: JCheckBox
private lateinit var spigotEnabledCheckBox: JCheckBox
private lateinit var spigotAutoCheckBox: JCheckBox
private lateinit var paperEnabledCheckBox: JCheckBox
private lateinit var paperAutoCheckBox: JCheckBox
private lateinit var spongeEnabledCheckBox: JCheckBox
private lateinit var spongeAutoCheckBox: JCheckBox
private lateinit var forgeEnabledCheckBox: JCheckBox
private lateinit var forgeAutoCheckBox: JCheckBox
private lateinit var liteloaderEnabledCheckBox: JCheckBox
private lateinit var liteloaderAutoCheckBox: JCheckBox
private lateinit var mcpEnabledCheckBox: JCheckBox
private lateinit var mcpAutoCheckBox: JCheckBox
private lateinit var mixinEnabledCheckBox: JCheckBox
private lateinit var mixinAutoCheckBox: JCheckBox
private lateinit var bungeecordEnabledCheckBox: JCheckBox
private lateinit var bungeecordAutoCheckBox: JCheckBox
private lateinit var waterfallEnabledCheckBox: JCheckBox
private lateinit var waterfallAutoCheckBox: JCheckBox
private lateinit var spongeIcon: JLabel
private lateinit var mcpIcon: JLabel
private lateinit var mixinIcon: JLabel
private val enableCheckBoxArray: Array<JCheckBox> by lazy {
arrayOf(
bukkitEnabledCheckBox,
spigotEnabledCheckBox,
paperEnabledCheckBox,
spongeEnabledCheckBox,
forgeEnabledCheckBox,
liteloaderEnabledCheckBox,
mcpEnabledCheckBox,
mixinEnabledCheckBox,
bungeecordEnabledCheckBox,
waterfallEnabledCheckBox
)
}
private val autoCheckBoxArray: Array<JCheckBox> by lazy {
arrayOf(
bukkitAutoCheckBox,
spigotAutoCheckBox,
paperAutoCheckBox,
spongeAutoCheckBox,
forgeAutoCheckBox,
liteloaderAutoCheckBox,
mcpAutoCheckBox,
mixinAutoCheckBox,
bungeecordAutoCheckBox,
waterfallAutoCheckBox
)
}
override fun createComponent(): JComponent {
if (UIUtil.isUnderDarcula()) {
spongeIcon.icon = PlatformAssets.SPONGE_ICON_2X_DARK
mcpIcon.icon = PlatformAssets.MCP_ICON_2X_DARK
mixinIcon.icon = PlatformAssets.MIXIN_ICON_2X_DARK
}
runOnAll { enabled, auto, platformType, _, _ ->
auto.addActionListener { checkAuto(auto, enabled, platformType) }
}
bukkitEnabledCheckBox.addActionListener {
unique(
bukkitEnabledCheckBox,
spigotEnabledCheckBox,
paperEnabledCheckBox
)
}
spigotEnabledCheckBox.addActionListener {
unique(
spigotEnabledCheckBox,
bukkitEnabledCheckBox,
paperEnabledCheckBox
)
}
paperEnabledCheckBox.addActionListener {
unique(
paperEnabledCheckBox,
bukkitEnabledCheckBox,
spigotEnabledCheckBox
)
}
bukkitAutoCheckBox.addActionListener {
all(bukkitAutoCheckBox, spigotAutoCheckBox, paperAutoCheckBox)(
SPIGOT,
PAPER
)
}
spigotAutoCheckBox.addActionListener {
all(spigotAutoCheckBox, bukkitAutoCheckBox, paperAutoCheckBox)(
BUKKIT,
PAPER
)
}
paperAutoCheckBox.addActionListener {
all(paperAutoCheckBox, bukkitAutoCheckBox, spigotAutoCheckBox)(
BUKKIT,
SPIGOT
)
}
forgeEnabledCheckBox.addActionListener { also(forgeEnabledCheckBox, mcpEnabledCheckBox) }
liteloaderEnabledCheckBox.addActionListener { also(liteloaderEnabledCheckBox, mcpEnabledCheckBox) }
mixinEnabledCheckBox.addActionListener { also(mixinEnabledCheckBox, mcpEnabledCheckBox) }
bungeecordEnabledCheckBox.addActionListener { unique(bungeecordEnabledCheckBox, waterfallEnabledCheckBox) }
waterfallEnabledCheckBox.addActionListener { unique(waterfallEnabledCheckBox, bungeecordEnabledCheckBox) }
return panel
}
override fun getDisplayName() = "Minecraft Module Settings"
override fun isModified(): Boolean {
var modified = false
runOnAll { enabled, auto, platformType, userTypes, _ ->
modified += auto.isSelected == platformType in userTypes
modified += !auto.isSelected && enabled.isSelected != userTypes[platformType]
}
return modified
}
override fun reset() {
runOnAll { enabled, auto, platformType, userTypes, autoTypes ->
auto.isSelected = platformType !in userTypes
enabled.isSelected = userTypes[platformType] ?: (platformType in autoTypes)
if (auto.isSelected) {
enabled.isEnabled = false
}
}
}
override fun apply() {
configuration.state.userChosenTypes.clear()
runOnAll { enabled, auto, platformType, userTypes, _ ->
if (!auto.isSelected) {
userTypes[platformType] = enabled.isSelected
}
}
}
private inline fun runOnAll(
run: (JCheckBox, JCheckBox, PlatformType, MutableMap<PlatformType, Boolean>, Set<PlatformType>) -> Unit
) {
val state = configuration.state
for (i in indexes) {
run(
enableCheckBoxArray[i],
autoCheckBoxArray[i],
platformTypes[i],
state.userChosenTypes,
state.autoDetectTypes
)
}
}
private fun unique(vararg checkBoxes: JCheckBox) {
if (checkBoxes.size <= 1) {
return
}
if (checkBoxes[0].isSelected) {
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = false
}
}
}
private fun also(vararg checkBoxes: JCheckBox) {
if (checkBoxes.size <= 1) {
return
}
if (checkBoxes[0].isSelected) {
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = true
}
}
}
private fun all(vararg checkBoxes: JCheckBox): Invoker {
if (checkBoxes.size <= 1) {
return Invoker()
}
for (i in 1 until checkBoxes.size) {
checkBoxes[i].isSelected = checkBoxes[0].isSelected
}
return object : Invoker() {
override fun invoke(vararg indexes: Int) {
for (i in indexes) {
checkAuto(autoCheckBoxArray[i], enableCheckBoxArray[i], platformTypes[i])
}
}
}
}
private fun checkAuto(auto: JCheckBox, enabled: JCheckBox, type: PlatformType) {
if (auto.isSelected) {
enabled.isEnabled = false
enabled.isSelected = type in configuration.state.autoDetectTypes
} else {
enabled.isEnabled = true
}
}
private operator fun Boolean.plus(n: Boolean) = this || n
// This is here so we can use vararg. Can't use parameter modifiers in function type definitions for some reason
open class Invoker {
open operator fun invoke(vararg indexes: Int) {}
}
companion object {
private const val BUKKIT = 0
private const val SPIGOT = BUKKIT + 1
private const val PAPER = SPIGOT + 1
private const val SPONGE = PAPER + 1
private const val FORGE = SPONGE + 1
private const val LITELOADER = FORGE + 1
private const val MCP = LITELOADER + 1
private const val MIXIN = MCP + 1
private const val BUNGEECORD = MIXIN + 1
private const val WATERFALL = BUNGEECORD + 1
private val platformTypes = arrayOf(
PlatformType.BUKKIT,
PlatformType.SPIGOT,
PlatformType.PAPER,
PlatformType.SPONGE,
PlatformType.FORGE,
PlatformType.LITELOADER,
PlatformType.MCP,
PlatformType.MIXIN,
PlatformType.BUNGEECORD,
PlatformType.WATERFALL
)
private val indexes =
intArrayOf(BUKKIT, SPIGOT, PAPER, SPONGE, FORGE, LITELOADER, MCP, MIXIN, BUNGEECORD, WATERFALL)
}
}
|
mit
|
0e8da46ccef47069b50e14feafc12cba
| 32.028986 | 116 | 0.626481 | 5.129994 | false | false | false | false |
google/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/ReformatBeforeCheckinHandler.kt
|
1
|
1657
|
// 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.
package com.intellij.openapi.vcs.checkin
import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption
import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles
import com.intellij.openapi.vcs.ui.RefreshableOnComponent
import com.intellij.psi.formatter.FormatterUtil.getReformatBeforeCommitCommandName
class ReformatCheckinHandlerFactory : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler =
ReformatBeforeCheckinHandler(panel)
}
class ReformatBeforeCheckinHandler(commitPanel: CheckinProjectPanel) : CodeProcessorCheckinHandler(commitPanel) {
override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent =
BooleanCommitOption(commitPanel, message("checkbox.checkin.options.reformat.code"), true, settings::REFORMAT_BEFORE_PROJECT_COMMIT)
override fun isEnabled(): Boolean = settings.REFORMAT_BEFORE_PROJECT_COMMIT
override fun getProgressMessage(): String = message("progress.text.reformatting.code")
override fun createCodeProcessor(): AbstractLayoutCodeProcessor =
ReformatCodeProcessor(project, getPsiFiles(project, commitPanel.virtualFiles), getReformatBeforeCommitCommandName(), null, true)
}
|
apache-2.0
|
6ab510b64609a5dc2d2b8fd7ae0d40f0
| 56.172414 | 140 | 0.842486 | 4.902367 | false | false | false | false |
square/okhttp
|
okhttp-tls/src/main/kotlin/okhttp3/tls/internal/der/BasicDerAdapter.kt
|
4
|
4462
|
/*
* Copyright (C) 2020 Square, Inc.
*
* 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 okhttp3.tls.internal.der
import java.net.ProtocolException
/**
* Handles basic types that always use the same tag. This supports optional types and may set a type
* hint for further adapters to process.
*
* Types like ANY and CHOICE that don't have a consistent tag cannot use this.
*/
internal data class BasicDerAdapter<T>(
private val name: String,
/** The tag class this adapter expects, or -1 to match any tag class. */
val tagClass: Int,
/** The tag this adapter expects, or -1 to match any tag. */
val tag: Long,
/** Encode and decode the value once tags are handled. */
private val codec: Codec<T>,
/** True if the default value should be used if this value is absent during decoding. */
val isOptional: Boolean = false,
/** The value to return if this value is absent. Undefined unless this is optional. */
val defaultValue: T? = null,
/** True to set the encoded or decoded value as the type hint for the current SEQUENCE. */
private val typeHint: Boolean = false
) : DerAdapter<T> {
init {
require(tagClass >= 0)
require(tag >= 0)
}
override fun matches(header: DerHeader): Boolean = header.tagClass == tagClass && header.tag == tag
override fun fromDer(reader: DerReader): T {
val peekedHeader = reader.peekHeader()
if (peekedHeader == null || peekedHeader.tagClass != tagClass || peekedHeader.tag != tag) {
if (isOptional) return defaultValue as T
throw ProtocolException("expected $this but was $peekedHeader at $reader")
}
val result = reader.read(name) {
codec.decode(reader)
}
if (typeHint) {
reader.typeHint = result
}
return result
}
override fun toDer(writer: DerWriter, value: T) {
if (typeHint) {
writer.typeHint = value
}
if (isOptional && value == defaultValue) {
// Nothing to write!
return
}
writer.write(name, tagClass, tag) {
codec.encode(writer, value)
}
}
/**
* Returns a copy with a context tag. This should be used when the type is ambiguous on its own.
* For example, the tags in this schema are 0 and 1:
*
* ```
* Point ::= SEQUENCE {
* x [0] INTEGER OPTIONAL,
* y [1] INTEGER OPTIONAL
* }
* ```
*
* You may also specify a tag class like [DerHeader.TAG_CLASS_APPLICATION]. The default tag class
* is [DerHeader.TAG_CLASS_CONTEXT_SPECIFIC].
*
* ```
* Point ::= SEQUENCE {
* x [APPLICATION 0] INTEGER OPTIONAL,
* y [APPLICATION 1] INTEGER OPTIONAL
* }
* ```
*/
fun withTag(
tagClass: Int = DerHeader.TAG_CLASS_CONTEXT_SPECIFIC,
tag: Long
): BasicDerAdapter<T> = copy(tagClass = tagClass, tag = tag)
/** Returns a copy of this adapter that doesn't encode values equal to [defaultValue]. */
fun optional(defaultValue: T? = null): BasicDerAdapter<T> = copy(isOptional = true, defaultValue = defaultValue)
/**
* Returns a copy of this adapter that sets the encoded or decoded value as the type hint for the
* other adapters on this SEQUENCE to interrogate.
*/
fun asTypeHint(): BasicDerAdapter<T> = copy(typeHint = true)
// Avoid Long.hashCode(long) which isn't available on Android 5.
override fun hashCode(): Int {
var result = 0
result = 31 * result + name.hashCode()
result = 31 * result + tagClass
result = 31 * result + tag.toInt()
result = 31 * result + codec.hashCode()
result = 31 * result + (if (isOptional) 1 else 0)
result = 31 * result + defaultValue.hashCode()
result = 31 * result + (if (typeHint) 1 else 0)
return result
}
override fun toString(): String = "$name [$tagClass/$tag]"
/** Reads and writes values without knowledge of the enclosing tag, length, or defaults. */
interface Codec<T> {
fun decode(reader: DerReader): T
fun encode(writer: DerWriter, value: T)
}
}
|
apache-2.0
|
5b4e225316905aca74805573da1f70fe
| 30.202797 | 114 | 0.664948 | 3.980375 | false | false | false | false |
youdonghai/intellij-community
|
platform/configuration-store-impl/src/ComponentStoreImpl.kt
|
1
|
22641
|
/*
* Copyright 2000-2015 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 com.intellij.configurationStore
import com.intellij.configurationStore.StateStorageManager.ExternalizationSession
import com.intellij.notification.NotificationsManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.DecodeDefaultsUtil
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.*
import com.intellij.openapi.components.StateStorage.SaveSession
import com.intellij.openapi.components.StateStorageChooserEx.Resolution
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.DefaultStateSerializer
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.components.impl.stores.UnknownMacroNotification
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.project.isDirectoryBased
import com.intellij.ui.AppUIUtil
import com.intellij.util.ArrayUtilRt
import com.intellij.util.SmartList
import com.intellij.util.containers.SmartHashSet
import com.intellij.util.containers.isNullOrEmpty
import com.intellij.util.lang.CompoundRuntimeException
import com.intellij.util.messages.MessageBus
import com.intellij.util.xmlb.JDOMXIncluder
import gnu.trove.THashMap
import io.netty.util.internal.SystemPropertyUtil
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.io.IOException
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import com.intellij.openapi.util.Pair as JBPair
internal val LOG = Logger.getInstance(ComponentStoreImpl::class.java)
internal val deprecatedComparator = Comparator<Storage> { o1, o2 ->
val w1 = if (o1.deprecated) 1 else 0
val w2 = if (o2.deprecated) 1 else 0
w1 - w2
}
abstract class ComponentStoreImpl : IComponentStore {
private val components = Collections.synchronizedMap(THashMap<String, ComponentInfo>())
private val settingsSavingComponents = CopyOnWriteArrayList<SettingsSavingComponent>()
internal open val project: Project?
get() = null
open val loadPolicy: StateLoadPolicy
get() = StateLoadPolicy.LOAD
abstract val storageManager: StateStorageManager
override final fun getStateStorageManager() = storageManager
override final fun initComponent(component: Any, service: Boolean) {
if (component is SettingsSavingComponent) {
settingsSavingComponents.add(component)
}
var componentName = ""
try {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
val stateSpec = StoreUtil.getStateSpec(component)
componentName = stateSpec.name
val info = doAddComponent(componentName, component)
if (initComponent(stateSpec, component, info, null, false) && service) {
// if not service, so, component manager will check it later for all components
project?.let {
val app = ApplicationManager.getApplication()
if (!app.isHeadlessEnvironment && !app.isUnitTestMode && it.isInitialized) {
notifyUnknownMacros(this, it, componentName)
}
}
}
}
else if (component is JDOMExternalizable) {
componentName = ComponentManagerImpl.getComponentName(component)
@Suppress("DEPRECATION")
initJdomExternalizable(component, componentName)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
LOG.error("Cannot init ${componentName} component state", e)
return
}
}
override fun save(readonlyFiles: MutableList<JBPair<StateStorage.SaveSession, VirtualFile>>) {
var errors: MutableList<Throwable>? = null
// component state uses scheme manager in an ipr project, so, we must save it before
val isIprProject = project?.let { !it.isDirectoryBased } ?: false
if (isIprProject) {
settingsSavingComponents.firstOrNull { it is SchemeManagerFactoryBase }?.let {
try {
it.save()
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
}
val isUseModificationCount = Registry.`is`("store.save.use.modificationCount", true)
val externalizationSession = if (components.isEmpty()) null else storageManager.startExternalization()
if (externalizationSession != null) {
val names = ArrayUtilRt.toStringArray(components.keys)
Arrays.sort(names)
val timeLogPrefix = "Saving"
val timeLog = if (LOG.isDebugEnabled) StringBuilder(timeLogPrefix) else null
for (name in names) {
val start = if (timeLog == null) 0 else System.currentTimeMillis()
try {
val info = components.get(name)!!
var currentModificationCount = -1L
if (info.lastModificationCount >= 0) {
currentModificationCount = info.currentModificationCount
if (currentModificationCount == info.lastModificationCount) {
LOG.debug { "${if (isUseModificationCount) "Skip " else ""}$name: modificationCount ${currentModificationCount} equals to last saved" }
if (isUseModificationCount) {
continue
}
}
}
commitComponent(externalizationSession, info.component, name)
info.updateModificationCount(currentModificationCount)
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(Exception("Cannot get $name component state", e))
}
timeLog?.let {
val duration = System.currentTimeMillis() - start
if (duration > 10) {
it.append("\n").append(name).append(" took ").append(duration).append(" ms: ").append((duration / 60000)).append(" min ").append(((duration % 60000) / 1000)).append("sec")
}
}
}
if (timeLog != null && timeLog.length > timeLogPrefix.length) {
LOG.debug(timeLog.toString())
}
}
for (settingsSavingComponent in settingsSavingComponents) {
try {
if (!isIprProject || settingsSavingComponent !is SchemeManagerFactoryBase) {
settingsSavingComponent.save()
}
}
catch (e: Throwable) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors!!.add(e)
}
}
if (externalizationSession != null) {
errors = doSave(externalizationSession.createSaveSessions(), readonlyFiles, errors)
}
CompoundRuntimeException.throwIfNotEmpty(errors)
}
override @TestOnly fun saveApplicationComponent(component: PersistentStateComponent<*>) {
val externalizationSession = storageManager.startExternalization() ?: return
commitComponent(externalizationSession, component, null)
val sessions = externalizationSession.createSaveSessions()
if (sessions.isEmpty()) {
return
}
val state = StoreUtil.getStateSpec(component.javaClass) ?: throw AssertionError("${component.javaClass} doesn't have @State annotation and doesn't implement ExportableApplicationComponent")
val absolutePath = Paths.get(storageManager.expandMacros(findNonDeprecated(state.storages).path)).toAbsolutePath().toString()
runWriteAction {
try {
VfsRootAccess.allowRootAccess(absolutePath)
CompoundRuntimeException.throwIfNotEmpty(doSave(sessions))
}
finally {
VfsRootAccess.disallowRootAccess(absolutePath)
}
}
}
private fun commitComponent(session: ExternalizationSession, component: Any, componentName: String?) {
@Suppress("DEPRECATION")
if (component is PersistentStateComponent<*>) {
component.state?.let {
val stateSpec = StoreUtil.getStateSpec(component)
session.setState(getStorageSpecs(component, stateSpec, StateStorageOperation.WRITE), component, componentName ?: stateSpec.name, it)
}
}
else if (component is JDOMExternalizable) {
session.setStateInOldStorage(component, componentName ?: ComponentManagerImpl.getComponentName(component), component)
}
}
protected open fun doSave(saveSessions: List<SaveSession>, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>> = arrayListOf(), prevErrors: MutableList<Throwable>? = null): MutableList<Throwable>? {
var errors = prevErrors
for (session in saveSessions) {
errors = executeSave(session, readonlyFiles, prevErrors)
}
return errors
}
private fun initJdomExternalizable(@Suppress("DEPRECATION") component: JDOMExternalizable, componentName: String): String? {
doAddComponent(componentName, component)
if (loadPolicy != StateLoadPolicy.LOAD) {
return null
}
try {
getDefaultState(component, componentName, Element::class.java)?.let { component.readExternal(it) }
}
catch (e: Throwable) {
LOG.error(e)
}
val element = storageManager.getOldStorage(component, componentName, StateStorageOperation.READ)?.getState(component, componentName, Element::class.java, null, false) ?: return null
try {
component.readExternal(element)
}
catch (e: InvalidDataException) {
LOG.error(e)
return null
}
return componentName
}
private fun doAddComponent(name: String, component: Any): ComponentInfo {
val newInfo = when (component) {
is ModificationTracker -> ComponentWithModificationTrackerInfo(component)
is PersistentStateComponentWithModificationTracker<*> -> ComponentWithStateModificationTrackerInfo(component)
else -> ComponentInfoImpl(component)
}
val existing = components.put(name, newInfo)
if (existing != null && existing.component !== component) {
components.put(name, existing)
LOG.error("Conflicting component name '$name': ${existing.component.javaClass} and ${component.javaClass}")
return existing
}
return newInfo
}
private fun <T: Any> initComponent(stateSpec: State, component: PersistentStateComponent<T>, info: ComponentInfo, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
if (loadPolicy == StateLoadPolicy.NOT_LOAD) {
return false
}
if (doInitComponent(stateSpec, component, changedStorages, reloadData)) {
// if component was initialized, update lastModificationCount
info.updateModificationCount()
return true
}
return false
}
private fun <T: Any> doInitComponent(stateSpec: State, component: PersistentStateComponent<T>, changedStorages: Set<StateStorage>?, reloadData: Boolean): Boolean {
val name = stateSpec.name
val stateClass = ComponentSerializationUtil.getStateClass<T>(component.javaClass)
if (!stateSpec.defaultStateAsResource && LOG.isDebugEnabled && getDefaultState(component, name, stateClass) != null) {
LOG.error("$name has default state, but not marked to load it")
}
val defaultState = if (stateSpec.defaultStateAsResource) getDefaultState(component, name, stateClass) else null
if (loadPolicy == StateLoadPolicy.LOAD) {
val storageSpecs = getStorageSpecs(component, stateSpec, StateStorageOperation.READ)
val storageChooser = component as? StateStorageChooserEx
for (storageSpec in storageSpecs) {
if (storageChooser?.getResolution(storageSpec, StateStorageOperation.READ) == Resolution.SKIP) {
continue
}
val storage = storageManager.getStateStorage(storageSpec)
// todo "ProjectModuleManager" investigate why after loadState we get empty state on getState, test CMakeWorkspaceContentRootsTest
// todo fix FacetManager
// use.loaded.state.as.existing used in upsource
val stateGetter = if (isUseLoadedStateAsExisting(storage) &&
name != "AntConfiguration" &&
name != "ProjectModuleManager" &&
name != "FacetManager" &&
name != "NewModuleRootManager" /* will be changed only on actual user change, so, to speed up module loading, skip it */ &&
name != "DeprecatedModuleOptionManager" /* doesn't make sense to check it */ &&
SystemPropertyUtil.getBoolean("use.loaded.state.as.existing", true)) {
(storage as? StorageBaseEx<*>)?.createGetSession(component, name, stateClass)
}
else {
null
}
var state = if (stateGetter == null) storage.getState(component, name, stateClass, defaultState, reloadData) else stateGetter.getState(defaultState)
if (state == null) {
if (changedStorages != null && changedStorages.contains(storage)) {
// state will be null if file deleted
// we must create empty (initial) state to reinit component
state = DefaultStateSerializer.deserializeState(Element("state"), stateClass, null)!!
}
else {
continue
}
}
try {
component.loadState(state)
}
finally {
stateGetter?.close()
}
return true
}
}
// we load default state even if isLoadComponentState false - required for app components (for example, at least one color scheme must exists)
if (defaultState != null) {
component.loadState(defaultState)
}
return true
}
protected open fun isUseLoadedStateAsExisting(storage: StateStorage): Boolean = (storage as? XmlElementStorage)?.roamingType != RoamingType.DISABLED
protected open fun getPathMacroManagerForDefaults(): PathMacroManager? = null
private fun <T : Any> getDefaultState(component: Any, componentName: String, stateClass: Class<T>): T? {
val url = DecodeDefaultsUtil.getDefaults(component, componentName) ?: return null
try {
val documentElement = JDOMXIncluder.resolve(JDOMUtil.loadDocument(url), url.toExternalForm()).detachRootElement()
getPathMacroManagerForDefaults()?.expandPaths(documentElement)
return DefaultStateSerializer.deserializeState(documentElement, stateClass, null)
}
catch (e: Throwable) {
throw IOException("Error loading default state from $url", e)
}
}
protected open fun <T> getStorageSpecs(component: PersistentStateComponent<T>, stateSpec: State, operation: StateStorageOperation): Array<out Storage> {
val storages = stateSpec.storages
if (storages.size == 1 || component is StateStorageChooserEx) {
return storages
}
if (storages.isEmpty()) {
if (stateSpec.defaultStateAsResource) {
return storages
}
throw AssertionError("No storage specified")
}
return storages.sortByDeprecated()
}
override final fun isReloadPossible(componentNames: MutableSet<String>) = !componentNames.any { isNotReloadable(it) }
private fun isNotReloadable(name: String): Boolean {
val component = components.get(name)?.component ?: return false
return component !is PersistentStateComponent<*> || !StoreUtil.getStateSpec(component).reloadable
}
fun getNotReloadableComponents(componentNames: Collection<String>): Collection<String> {
var notReloadableComponents: MutableSet<String>? = null
for (componentName in componentNames) {
if (isNotReloadable(componentName)) {
if (notReloadableComponents == null) {
notReloadableComponents = LinkedHashSet<String>()
}
notReloadableComponents.add(componentName)
}
}
return notReloadableComponents ?: emptySet<String>()
}
override final fun reloadStates(componentNames: MutableSet<String>, messageBus: MessageBus) {
runBatchUpdate(messageBus) {
reinitComponents(componentNames)
}
}
override final fun reloadState(componentClass: Class<out PersistentStateComponent<*>>) {
val stateSpec = StoreUtil.getStateSpecOrError(componentClass)
val info = components.get(stateSpec.name) ?: return
(info.component as? PersistentStateComponent<*>)?.let {
initComponent(stateSpec, it, info, emptySet(), true)
}
}
private fun reloadState(componentName: String, changedStorages: Set<StateStorage>): Boolean {
val info = components.get(componentName) ?: return false
val component = info.component as? PersistentStateComponent<*> ?: return false
val changedStoragesEmpty = changedStorages.isEmpty()
initComponent(StoreUtil.getStateSpec(component), component, info, if (changedStoragesEmpty) null else changedStorages, changedStoragesEmpty)
return true
}
/**
* null if reloaded
* empty list if nothing to reload
* list of not reloadable components (reload is not performed)
*/
fun reload(changedStorages: Set<StateStorage>): Collection<String>? {
if (changedStorages.isEmpty()) {
return emptySet()
}
val componentNames = SmartHashSet<String>()
for (storage in changedStorages) {
try {
// we must update (reload in-memory storage data) even if non-reloadable component will be detected later
// not saved -> user does own modification -> new (on disk) state will be overwritten and not applied
storage.analyzeExternalChangesAndUpdateIfNeed(componentNames)
}
catch (e: Throwable) {
LOG.error(e)
}
}
if (componentNames.isEmpty) {
return emptySet()
}
val notReloadableComponents = getNotReloadableComponents(componentNames)
reinitComponents(componentNames, changedStorages, notReloadableComponents)
return if (notReloadableComponents.isEmpty()) null else notReloadableComponents
}
// used in settings repository plugin
/**
* You must call it in batch mode (use runBatchUpdate)
*/
fun reinitComponents(componentNames: Set<String>, changedStorages: Set<StateStorage> = emptySet(), notReloadableComponents: Collection<String> = emptySet()) {
for (componentName in componentNames) {
if (!notReloadableComponents.contains(componentName)) {
reloadState(componentName, changedStorages)
}
}
}
@TestOnly fun removeComponent(name: String) {
components.remove(name)
}
}
internal fun executeSave(session: SaveSession, readonlyFiles: MutableList<JBPair<SaveSession, VirtualFile>>, previousErrors: MutableList<Throwable>?): MutableList<Throwable>? {
var errors = previousErrors
try {
session.save()
}
catch (e: ReadOnlyModificationException) {
LOG.warn(e)
readonlyFiles.add(JBPair.create<SaveSession, VirtualFile>(e.session ?: session, e.file))
}
catch (e: Exception) {
if (errors == null) {
errors = SmartList<Throwable>()
}
errors.add(e)
}
return errors
}
private fun findNonDeprecated(storages: Array<Storage>): Storage {
for (storage in storages) {
if (!storage.deprecated) {
return storage
}
}
throw AssertionError("All storages are deprecated")
}
enum class StateLoadPolicy {
LOAD, LOAD_ONLY_DEFAULT, NOT_LOAD
}
internal fun Array<Storage>.sortByDeprecated(): Array<out Storage> {
if (isEmpty()) {
return this
}
if (!this[0].deprecated) {
var othersAreDeprecated = true
for (i in 1..size - 1) {
if (!this[i].deprecated) {
othersAreDeprecated = false
break
}
}
if (othersAreDeprecated) {
return this
}
}
return sortedArrayWith(deprecatedComparator)
}
private fun notifyUnknownMacros(store: IComponentStore, project: Project, componentName: String) {
val substitutor = store.stateStorageManager.macroSubstitutor ?: return
val immutableMacros = substitutor.getUnknownMacros(componentName)
if (immutableMacros.isEmpty()) {
return
}
val macros = LinkedHashSet(immutableMacros)
AppUIUtil.invokeOnEdt(Runnable {
var notified: MutableList<String>? = null
val manager = NotificationsManager.getNotificationsManager()
for (notification in manager.getNotificationsOfType(UnknownMacroNotification::class.java, project)) {
if (notified == null) {
notified = SmartList<String>()
}
notified.addAll(notification.macros)
}
if (!notified.isNullOrEmpty()) {
macros.removeAll(notified!!)
}
if (macros.isEmpty()) {
return@Runnable
}
LOG.debug("Reporting unknown path macros $macros in component $componentName")
doNotify(macros, project, Collections.singletonMap(substitutor, store))
}, project.disposed)
}
private interface ComponentInfo {
val component: Any
val lastModificationCount: Long
val currentModificationCount: Long
fun updateModificationCount(newCount: Long = currentModificationCount) {
}
}
private open class ComponentInfoImpl(override val component: Any) : ComponentInfo {
override val lastModificationCount: Long
get() = -1
override val currentModificationCount: Long
get() = -1
}
private abstract class ModificationTrackerAwareComponentInfo : ComponentInfo {
override abstract var lastModificationCount: Long
override final fun updateModificationCount(newCount: Long) {
lastModificationCount = newCount
}
}
private class ComponentWithStateModificationTrackerInfo(override val component: PersistentStateComponentWithModificationTracker<*>) : ModificationTrackerAwareComponentInfo() {
override var lastModificationCount = currentModificationCount
override val currentModificationCount: Long
get() = component.stateModificationCount
}
private class ComponentWithModificationTrackerInfo(override val component: ModificationTracker) : ModificationTrackerAwareComponentInfo() {
override var lastModificationCount = currentModificationCount
override val currentModificationCount: Long
get() = component.modificationCount
}
|
apache-2.0
|
dad56b0b7f4dd9bfd3306cd568c930a3
| 36.424793 | 209 | 0.711099 | 5.051539 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepik/android/view/course/ui/delegates/CourseHeaderDelegate.kt
|
1
|
27537
|
package org.stepik.android.view.course.ui.delegates
import android.app.Activity
import android.graphics.drawable.AnimationDrawable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.text.buildSpannedString
import androidx.core.text.strikeThrough
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.AppBarLayout
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.android.synthetic.main.activity_course.*
import kotlinx.android.synthetic.main.header_course.*
import kotlinx.android.synthetic.main.view_discounted_purchase_button.*
import org.stepic.droid.R
import org.stepic.droid.analytic.AmplitudeAnalytic
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.analytic.experiments.DiscountButtonAppearanceSplitTest
import org.stepic.droid.ui.util.PopupHelper
import org.stepic.droid.util.DateTimeHelper
import org.stepic.droid.util.DateTimeHelper.getPrintableOfIsoDate
import org.stepic.droid.util.resolveColorAttribute
import org.stepik.android.domain.course.analytic.BuyCoursePressedEvent
import org.stepik.android.domain.course.analytic.CourseJoinedEvent
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course.analytic.batch.BuyCoursePressedAnalyticBatchEvent
import org.stepik.android.domain.course.model.CourseHeaderData
import org.stepik.android.domain.course.model.EnrollmentState
import org.stepik.android.domain.course_continue.analytic.CourseContinuePressedEvent
import org.stepik.android.domain.course_payments.model.DeeplinkPromoCode
import org.stepik.android.domain.course_payments.model.PromoCodeSku
import org.stepik.android.presentation.course.CoursePresenter
import org.stepik.android.presentation.course.resolver.CoursePurchaseDataResolver
import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource
import org.stepik.android.presentation.course_purchase.model.CoursePurchaseData
import org.stepik.android.presentation.user_courses.model.UserCourseAction
import org.stepik.android.presentation.wishlist.model.WishlistAction
import org.stepik.android.view.base.ui.extension.ColorExtensions
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course.resolver.CoursePromoCodeResolver
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.app.core.model.safeCast
import ru.nobird.android.view.base.ui.extension.getAllQueryParameters
import ru.nobird.android.view.base.ui.extension.getDrawableCompat
import java.util.TimeZone
import kotlin.math.abs
class CourseHeaderDelegate
@AssistedInject
constructor(
@Assisted private val courseActivity: Activity,
private val analytic: Analytic,
@Assisted private val coursePresenter: CoursePresenter,
private val discountButtonAppearanceSplitTest: DiscountButtonAppearanceSplitTest,
private val displayPriceMapper: DisplayPriceMapper,
private val coursePromoCodeResolver: CoursePromoCodeResolver,
private val coursePurchaseDataResolver: CoursePurchaseDataResolver,
@Assisted private val courseViewSource: CourseViewSource,
@Assisted("isAuthorized")
private val isAuthorized: Boolean,
@Assisted("mustShowCourseRevenue")
private val mustShowCourseRevenue: Boolean,
@Assisted("showCourseRevenueAction")
private val showCourseRevenueAction: () -> Unit,
@Assisted("onSubmissionCountClicked")
onSubmissionCountClicked: () -> Unit,
@Assisted("isLocalSubmissionsEnabled")
isLocalSubmissionsEnabled: Boolean,
@Assisted("showCourseSearchAction")
private val showSearchCourseAction: () -> Unit,
@Assisted private val coursePurchaseFlowAction: (CoursePurchaseData, Boolean) -> Unit
) {
companion object {
private val CourseHeaderData.enrolledState: EnrollmentState.Enrolled?
get() = stats.enrollmentState.safeCast<EnrollmentState.Enrolled>()
private const val EVALUATION_FRAME_DURATION_MS = 250
}
var courseHeaderData: CourseHeaderData? = null
set(value) {
field = value
value?.let(::setCourseData)
}
private var courseBenefitsMenuItem: MenuItem? = null
private var courseSearchMenuItem: MenuItem? = null
private var dropCourseMenuItem: MenuItem? = null
private var shareCourseMenuItem: MenuItem? = null
private var restorePurchaseCourseMenuItem: MenuItem? = null
private val courseStatsDelegate = CourseStatsDelegate(courseActivity.courseStats)
private val courseProgressDelegate = CourseProgressDelegate(courseActivity.courseProgress, onSubmissionCountClicked, isLocalSubmissionsEnabled)
private val courseCollapsingToolbar = courseActivity.courseCollapsingToolbar
private val viewStateDelegate = ViewStateDelegate<EnrollmentState>()
init {
initCollapsingAnimation()
initActions()
initViewStateDelegate()
}
private fun initCollapsingAnimation() {
with(courseActivity) {
courseToolbarScrim.setBackgroundColor(ColorExtensions.colorSurfaceWithElevationOverlay(courseCollapsingToolbar.context, 4))
courseAppBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
val ratio = abs(verticalOffset).toFloat() / (courseCollapsingToolbar.height - courseToolbar.height)
courseToolbarScrim.alpha = ratio * 1.5f
})
}
}
private fun initActions() {
with(courseActivity) {
courseEnrollAction.setOnClickListener {
coursePresenter.enrollCourse()
courseHeaderData?.let { headerData ->
analytic.report(
CourseJoinedEvent(
CourseJoinedEvent.SOURCE_PREVIEW,
headerData.course,
headerData.course.isInWishlist
)
)
}
}
courseContinueAction.setOnClickListener {
coursePresenter.continueLearning()
courseHeaderData?.let { headerData ->
analytic.report(
CourseContinuePressedEvent(
headerData.course,
CourseContinueInteractionSource.COURSE_SCREEN,
courseViewSource
)
)
}
}
courseWishlistAction.setOnClickListener {
courseHeaderData?.let {
val action =
if (it.course.isInWishlist) {
WishlistAction.REMOVE
} else {
WishlistAction.ADD
}
coursePresenter.toggleWishlist(action)
}
}
courseBuyInWebAction.setOnClickListener {
courseHeaderData?.let(::setupBuyAction)
}
courseBuyInWebActionDiscounted.setOnClickListener {
courseHeaderData?.let(::setupBuyAction)
}
courseTryFree.setOnClickListener {
val course = courseHeaderData
?.course
?: return@setOnClickListener
coursePresenter.tryLessonFree(course.previewLesson, course.previewUnit)
}
}
}
private fun buyInWebAction() {
val queryParams = courseActivity
.intent
?.data
?.getAllQueryParameters()
coursePresenter.openCoursePurchaseInWeb(queryParams)
}
private fun initViewStateDelegate() {
with(courseActivity) {
viewStateDelegate.addState<EnrollmentState.Enrolled>(courseContinueAction)
viewStateDelegate.addState<EnrollmentState.NotEnrolledFree>(courseEnrollAction)
viewStateDelegate.addState<EnrollmentState.Pending>(courseEnrollmentProgress)
viewStateDelegate.addState<EnrollmentState.NotEnrolledUnavailableIAP>(courseWishlistAction, courseFeedbackContainer)
viewStateDelegate.addState<EnrollmentState.NotEnrolledEnded>(courseWishlistAction, courseFeedbackContainer)
viewStateDelegate.addState<EnrollmentState.NotEnrolledCantBeBought>(courseWishlistAction, courseFeedbackContainer)
viewStateDelegate.addState<EnrollmentState.NotEnrolledWeb>(purchaseContainer)
viewStateDelegate.addState<EnrollmentState.NotEnrolledMobileTier>(purchaseContainer)
// viewStateDelegate.addState<EnrollmentState.NotEnrolledInApp>(courseBuyInAppAction)
}
}
private fun setCourseData(courseHeaderData: CourseHeaderData) =
with(courseActivity) {
val multi = MultiTransformation(BlurTransformation(), CenterCrop())
Glide
.with(this)
.load(courseHeaderData.cover)
.placeholder(R.drawable.general_placeholder)
.apply(RequestOptions.bitmapTransform(multi))
.into(courseCover)
courseToolbarTitle.text = courseHeaderData.title
val isNeedShowProgress = courseHeaderData.stats.progress != null
courseProgress.isVisible = isNeedShowProgress
courseProgressSeparator.isVisible = isNeedShowProgress
courseStats.isVisible = !isNeedShowProgress
if (courseHeaderData.stats.progress != null) {
courseProgressDelegate.setProgress(courseHeaderData.stats.progress)
courseProgressDelegate.setSolutionsCount(courseHeaderData.localSubmissionsCount)
} else {
courseStatsDelegate.setStats(courseHeaderData.stats)
}
setupWishlistAction(courseHeaderData)
/**
* Purchase setup section
*/
if (courseHeaderData.stats.enrollmentState is EnrollmentState.NotEnrolledMobileTier) {
setupIAP(courseHeaderData)
} else {
setupWeb(courseHeaderData)
}
courseDefaultPromoInfo.text = courseHeaderData.defaultPromoCode.defaultPromoCodeExpireDate?.let {
val formattedDate = DateTimeHelper.getPrintableDate(it, DateTimeHelper.DISPLAY_DAY_MONTH_PATTERN, TimeZone.getDefault())
getString(R.string.course_promo_code_date, formattedDate)
}
courseDefaultPromoInfo.isVisible = (courseHeaderData.defaultPromoCode.defaultPromoCodeExpireDate?.time ?: -1L) > DateTimeHelper.nowUtc() &&
courseHeaderData.course.enrollment == 0L &&
(courseHeaderData.deeplinkPromoCode == DeeplinkPromoCode.EMPTY || courseHeaderData.deeplinkPromoCode.name == courseHeaderData.defaultPromoCode.defaultPromoCodeName)
with(courseHeaderData.stats.enrollmentState) {
viewStateDelegate.switchState(this)
dropCourseMenuItem?.isVisible = this is EnrollmentState.Enrolled
restorePurchaseCourseMenuItem?.isVisible = this is EnrollmentState.NotEnrolledMobileTier
}
courseTryFree.isVisible = courseHeaderData.course.previewLesson != 0L &&
courseHeaderData.course.enrollment == 0L &&
courseHeaderData.course.isPaid &&
(courseHeaderData.stats.enrollmentState is EnrollmentState.NotEnrolledMobileTier ||
courseHeaderData.stats.enrollmentState is EnrollmentState.NotEnrolledWeb ||
courseHeaderData.stats.enrollmentState is EnrollmentState.NotEnrolledUnavailableIAP)
shareCourseMenuItem?.isVisible = true
setupPurchaseFeedback(courseHeaderData)
}
private fun setupPurchaseFeedback(courseHeaderData: CourseHeaderData) {
with(courseActivity) {
ViewCompat.setBackgroundTintList(coursePurchaseFeedbackUnder, AppCompatResources.getColorStateList(courseActivity, R.color.black_alpha_30))
coursePurchaseFeedback.text =
when (courseHeaderData.stats.enrollmentState) {
is EnrollmentState.NotEnrolledUnavailableIAP ->
getString(R.string.course_purchase_unavailable)
is EnrollmentState.NotEnrolledEnded ->
if (courseHeaderData.course.endDate != null) {
getString(
R.string.course_payments_not_available_ended,
getPrintableOfIsoDate(courseHeaderData.course.endDate, DateTimeHelper.DISPLAY_DAY_MONTH_YEAR_GENITIVE_PATTERN, TimeZone.getDefault())
)
} else {
getString(R.string.course_payments_not_available)
}
is EnrollmentState.NotEnrolledCantBeBought ->
getString(R.string.course_payments_cant_be_bought)
else -> ""
}
}
}
private fun setupIAP(courseHeaderData: CourseHeaderData) {
with(courseActivity) {
val notEnrolledMobileTierState = courseHeaderData.stats.enrollmentState as EnrollmentState.NotEnrolledMobileTier
val promoCodeSku = when {
courseHeaderData.deeplinkPromoCodeSku != PromoCodeSku.EMPTY ->
courseHeaderData.deeplinkPromoCodeSku
notEnrolledMobileTierState.promoLightSku != null -> {
PromoCodeSku(courseHeaderData.course.defaultPromoCodeName.orEmpty(), notEnrolledMobileTierState.promoLightSku)
}
else ->
PromoCodeSku.EMPTY
}
courseBuyInWebAction.text =
if (courseHeaderData.course.displayPrice != null) {
if (promoCodeSku.lightSku != null) {
displayPriceMapper.mapToDiscountedDisplayPriceSpannedString(notEnrolledMobileTierState.standardLightSku.price, promoCodeSku.lightSku.price)
} else {
getString(R.string.course_payments_purchase_in_web_with_price, notEnrolledMobileTierState.standardLightSku.price)
}
} else {
getString(R.string.course_payments_purchase_in_web)
}
courseBuyInWebActionDiscountedNewPrice.text =
getString(R.string.course_payments_purchase_in_web_with_price, promoCodeSku.lightSku?.price)
courseBuyInWebActionDiscountedOldPrice.text =
buildSpannedString {
strikeThrough {
append(notEnrolledMobileTierState.standardLightSku.price)
}
}
setupDiscountButtons(hasDiscount = promoCodeSku.lightSku != null)
}
}
private fun setupWeb(courseHeaderData: CourseHeaderData) {
with(courseActivity) {
val (_, currencyCode, promoPrice, hasPromo) = coursePromoCodeResolver.resolvePromoCodeInfo(
courseHeaderData.deeplinkPromoCode,
courseHeaderData.defaultPromoCode,
courseHeaderData.course
)
val courseDisplayPrice = courseHeaderData.course.displayPrice
courseBuyInWebAction.text =
if (courseDisplayPrice != null) {
if (hasPromo) {
displayPriceMapper.mapToDiscountedDisplayPriceSpannedString(
courseDisplayPrice,
promoPrice,
currencyCode
)
} else {
getString(
R.string.course_payments_purchase_in_web_with_price,
courseDisplayPrice
)
}
} else {
getString(R.string.course_payments_purchase_in_web)
}
courseBuyInWebActionDiscountedNewPrice.text =
getString(R.string.course_payments_purchase_in_web_with_price, displayPriceMapper.mapToDisplayPriceWithCurrency(currencyCode, promoPrice))
courseBuyInWebActionDiscountedOldPrice.text =
buildSpannedString {
strikeThrough {
append(courseHeaderData.course.displayPrice)
}
}
setupDiscountButtons(hasDiscount = courseHeaderData.course.displayPrice != null && hasPromo)
}
}
private fun setupBuyAction(courseHeaderData: CourseHeaderData) {
coursePresenter.schedulePurchaseReminder()
analytic.report(BuyCoursePressedEvent(courseHeaderData.course, BuyCoursePressedEvent.COURSE_SCREEN, courseHeaderData.course.isInWishlist))
analytic.report(BuyCoursePressedAnalyticBatchEvent(courseHeaderData.courseId))
val coursePurchaseData = coursePurchaseDataResolver.resolveCoursePurchaseData(courseHeaderData)
if (coursePurchaseData != null) {
coursePurchaseFlowAction(coursePurchaseData, false)
} else {
buyInWebAction()
}
}
private fun setupDiscountButtons(hasDiscount: Boolean) {
with(courseActivity) {
if (hasDiscount) {
when (discountButtonAppearanceSplitTest.currentGroup) {
DiscountButtonAppearanceSplitTest.Group.DiscountTransparent -> {
courseBuyInWebAction.isVisible = false
courseBuyInWebActionDiscounted.isVisible = true
}
DiscountButtonAppearanceSplitTest.Group.DiscountGreen -> {
courseBuyInWebAction.isVisible = true
courseBuyInWebActionDiscounted.isVisible = false
ViewCompat.setBackgroundTintList(courseBuyInWebAction, AppCompatResources.getColorStateList(courseActivity, R.color.color_overlay_green))
}
DiscountButtonAppearanceSplitTest.Group.DiscountPurple -> {
courseBuyInWebAction.isVisible = true
courseBuyInWebActionDiscounted.isVisible = false
ViewCompat.setBackgroundTintList(courseBuyInWebAction, AppCompatResources.getColorStateList(courseActivity, R.color.color_overlay_violet))
}
}
} else {
courseBuyInWebAction.isVisible = true
courseBuyInWebActionDiscounted.isVisible = false
}
}
}
private fun setupWishlistAction(courseHeaderData: CourseHeaderData) {
with(courseActivity) {
courseWishlistAction.isEnabled = !courseHeaderData.course.isInWishlist && !courseHeaderData.isWishlistUpdating
val wishlistText = if (courseHeaderData.isWishlistUpdating) {
if (courseHeaderData.course.isInWishlist) {
getString(R.string.course_purchase_wishlist_removing)
} else {
getString(R.string.course_purchase_wishlist_adding)
}
} else {
if (courseHeaderData.course.isInWishlist) {
getString(R.string.course_purchase_wishlist_added)
} else {
getString(R.string.course_purchase_wishlist_add)
}
}
courseWishlistAction.text = wishlistText
if (courseHeaderData.isWishlistUpdating) {
val evaluationDrawable = AnimationDrawable()
evaluationDrawable.addFrame(getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_1), EVALUATION_FRAME_DURATION_MS)
evaluationDrawable.addFrame(getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_2), EVALUATION_FRAME_DURATION_MS)
evaluationDrawable.addFrame(getDrawableCompat(R.drawable.ic_step_quiz_evaluation_frame_3), EVALUATION_FRAME_DURATION_MS)
evaluationDrawable.isOneShot = false
courseWishlistAction.icon = evaluationDrawable
evaluationDrawable.start()
} else {
courseWishlistAction.icon = null
}
}
}
fun showCourseShareTooltip() {
val menuItemView = courseActivity
.courseToolbar
.findViewById<View>(R.id.share_course)
?: return
PopupHelper
.showPopupAnchoredToView(
courseActivity,
menuItemView,
courseActivity.getString(R.string.course_share_description),
theme = PopupHelper.PopupTheme.LIGHT,
cancelableOnTouchOutside = true,
withArrow = true
)
}
fun onOptionsMenuCreated(menu: Menu) {
val userCourseState = courseHeaderData?.enrolledState
courseBenefitsMenuItem = menu.findItem(R.id.course_benefits)
courseBenefitsMenuItem?.isVisible = mustShowCourseRevenue
courseSearchMenuItem = menu.findItem(R.id.course_search)
courseSearchMenuItem?.isVisible = courseHeaderData?.stats?.enrollmentState is EnrollmentState.Enrolled
menu.findItem(R.id.favorite_course)
?.let { favoriteCourseMenuItem ->
favoriteCourseMenuItem.isVisible = userCourseState != null
favoriteCourseMenuItem.isEnabled = userCourseState?.isUserCourseUpdating == false
favoriteCourseMenuItem.title =
if (userCourseState?.userCourse?.isFavorite == true) {
courseActivity.getString(R.string.course_action_favorites_remove)
} else {
courseActivity.getString(R.string.course_action_favorites_add)
}
}
menu.findItem(R.id.archive_course)
?.let { archiveCourseMenuItem ->
archiveCourseMenuItem.isVisible = userCourseState != null
archiveCourseMenuItem.isEnabled = userCourseState?.isUserCourseUpdating == false
archiveCourseMenuItem.title =
if (userCourseState?.userCourse?.isArchived == true) {
courseActivity.getString(R.string.course_action_archive_remove)
} else {
courseActivity.getString(R.string.course_action_archive_add)
}
}
dropCourseMenuItem = menu.findItem(R.id.drop_course)
dropCourseMenuItem?.isVisible = courseHeaderData?.stats?.enrollmentState is EnrollmentState.Enrolled
val dropCourseMenuItemSpan = SpannableString(dropCourseMenuItem?.title)
dropCourseMenuItemSpan.setSpan(ForegroundColorSpan(courseCollapsingToolbar.context.resolveColorAttribute(R.attr.colorError)), 0, dropCourseMenuItemSpan.length, 0)
dropCourseMenuItem?.title = dropCourseMenuItemSpan
menu.findItem(R.id.wishlist_course)
?.let { wishlistCourseMenuItem ->
wishlistCourseMenuItem.isVisible = courseHeaderData != null && courseHeaderData?.course?.enrollment == 0L && isAuthorized
wishlistCourseMenuItem.isEnabled = courseHeaderData?.isWishlistUpdating == false
val (icon, title) =
if (courseHeaderData?.course?.isInWishlist == true) {
ContextCompat.getDrawable(courseActivity, R.drawable.ic_wishlist_active) to courseActivity.getString(R.string.wishlist_add_action)
} else {
ContextCompat.getDrawable(courseActivity, R.drawable.ic_wishlist_inactive) to courseActivity.getString(R.string.wishlist_remove_action)
}
wishlistCourseMenuItem.icon = icon
wishlistCourseMenuItem.title = title
}
shareCourseMenuItem = menu.findItem(R.id.share_course)
shareCourseMenuItem?.isVisible = courseHeaderData != null
restorePurchaseCourseMenuItem = menu.findItem(R.id.restore_purchase)
restorePurchaseCourseMenuItem?.isVisible = courseHeaderData?.stats?.enrollmentState is EnrollmentState.NotEnrolledMobileTier
}
fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
R.id.course_benefits -> {
showCourseRevenueAction()
true
}
R.id.course_search -> {
showSearchCourseAction()
true
}
R.id.drop_course -> {
coursePresenter.dropCourse()
courseHeaderData?.let { headerData ->
analytic.reportAmplitudeEvent(
AmplitudeAnalytic.Course.UNSUBSCRIBED, mapOf(
AmplitudeAnalytic.Course.Params.COURSE to headerData.courseId
)
)
}
true
}
R.id.favorite_course -> {
courseHeaderData?.enrolledState?.let {
val action =
if (it.userCourse.isFavorite) {
UserCourseAction.REMOVE_FAVORITE
} else {
UserCourseAction.ADD_FAVORITE
}
coursePresenter.toggleUserCourse(action)
}
true
}
R.id.archive_course -> {
courseHeaderData?.enrolledState?.let {
val action =
if (it.userCourse.isArchived) {
UserCourseAction.REMOVE_ARCHIVE
} else {
UserCourseAction.ADD_ARCHIVE
}
coursePresenter.toggleUserCourse(action)
}
true
}
R.id.wishlist_course -> {
courseHeaderData?.course?.let {
val action =
if (it.isInWishlist) {
WishlistAction.REMOVE
} else {
WishlistAction.ADD
}
coursePresenter.toggleWishlist(action)
}
true
}
R.id.share_course -> {
coursePresenter.shareCourse()
true
}
R.id.restore_purchase -> {
val coursePurchaseData = courseHeaderData?.let(coursePurchaseDataResolver::resolveCoursePurchaseData)
if (coursePurchaseData != null) {
coursePurchaseFlowAction(coursePurchaseData, true)
}
true
}
else ->
false
}
}
|
apache-2.0
|
491710549c75fcde11552e9c4438df62
| 44.744186 | 180 | 0.633075 | 5.515121 | false | false | false | false |
ursjoss/sipamato
|
core/core-persistence-jooq/src/test/kotlin/ch/difty/scipamato/core/persistence/search/SearchOrderFilterConditionMapperTest.kt
|
1
|
2315
|
package ch.difty.scipamato.core.persistence.search
import ch.difty.scipamato.common.persistence.FilterConditionMapperTest
import ch.difty.scipamato.core.db.tables.SearchOrder
import ch.difty.scipamato.core.db.tables.SearchOrder.SEARCH_ORDER
import ch.difty.scipamato.core.db.tables.records.SearchOrderRecord
import ch.difty.scipamato.core.entity.search.SearchOrderFilter
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
internal class SearchOrderFilterConditionMapperTest :
FilterConditionMapperTest<SearchOrderRecord, SearchOrder, SearchOrderFilter>() {
override val mapper = SearchOrderFilterConditionMapper()
override val filter = SearchOrderFilter()
override val table: SearchOrder = SEARCH_ORDER
@Test
fun creatingWhereCondition_withNameMask_searchesForName() {
filter.nameMask = "fOo"
mapper.map(filter).toString() shouldBeEqualTo
""""public"."search_order"."name" ilike ('%' || replace(
| replace(
| replace(
| 'fOo',
| '!',
| '!!'
| ),
| '%',
| '!%'
| ),
| '_',
| '!_'
|) || '%') escape '!'""".trimMargin()
}
@Test
fun creatingWhereCondition_withOwnerIncludingGlobal_searchesForOwnerIdOrGlobal() {
filter.ownerIncludingGlobal = 10
mapper.map(filter).toString() shouldBeEqualTo
"""(
| "public"."search_order"."owner" = 10
| or "public"."search_order"."global" = true
|)""".trimMargin()
}
@Test
fun creatingWhereCondition_withOwner_searchesForOwnerId() {
filter.owner = 20
mapper.map(filter).toString() shouldBeEqualTo """"public"."search_order"."owner" = 20"""
}
@Test
fun creatingWhereCondition_forGlobal_searchesForGlobal() {
filter.global = true
mapper.map(filter).toString() shouldBeEqualTo """"public"."search_order"."global" = true"""
}
@Test
fun creatingWhereCondition_forGlobal_searchesForNotGlobal() {
filter.global = false
mapper.map(filter).toString() shouldBeEqualTo """"public"."search_order"."global" = false"""
}
}
|
gpl-3.0
|
4a4f289639f30718b372868597a5e28c
| 34.075758 | 100 | 0.613391 | 4.566075 | false | true | false | false |
zdary/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/repositories/RepositoryTree.kt
|
1
|
6052
|
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories
import com.intellij.ide.CopyProvider
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.ui.TreeUIHelper
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ui.tree.TreeUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RepositoryModel
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaledEmptyBorder
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rd.util.reactive.IPropertyView
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
internal class RepositoryTree(
private val project: Project,
installedKnownRepositories: IPropertyView<List<RepositoryModel>>,
lifetime: Lifetime
) : Tree(), DataProvider, CopyProvider {
private val rootNode: DefaultMutableTreeNode
get() = (model as DefaultTreeModel).root as DefaultMutableTreeNode
init {
setCellRenderer(RepositoryTreeItemRenderer())
selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
rootVisible = false
isRootVisible = false
showsRootHandles = true
@Suppress("MagicNumber") // Gotta love Swing APIs
border = scaledEmptyBorder(left = 8)
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.repositories.no.repositories.configured")
addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) {
if (e != null && e.clickCount >= 1) {
val treePath = getPathForLocation(e.x, e.y) ?: return
val item = getRepositoryItemFrom(treePath)
if (item != null && item is RepositoryTreeItem.Module) {
openFile(item)
}
}
}
})
addTreeSelectionListener {
val item = getRepositoryItemFrom(it.newLeadSelectionPath)
if (item != null && item is RepositoryTreeItem.Module) {
openFile(item)
}
}
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
if (e?.keyCode == KeyEvent.VK_ENTER) {
val item = getRepositoryItemFrom(selectionPath)
if (item != null && item is RepositoryTreeItem.Module) {
openFile(item)
}
}
}
})
TreeUIHelper.getInstance().installTreeSpeedSearch(this)
TreeUtil.installActions(this)
installedKnownRepositories.advise(lifetime) { repositories -> onRepositoriesChanged(repositories) }
}
private fun openFile(repositoryModuleItem: RepositoryTreeItem.Module, focusEditor: Boolean = false) {
if (!PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource) return
// TODO At some point it would be nice to jump to the location in the file
val file = repositoryModuleItem.usageInfo.projectModule.buildFile
FileEditorManager.getInstance(project).openFile(file, focusEditor, true)
}
private fun onRepositoriesChanged(repositories: List<RepositoryModel>) {
val previouslySelectedItem = getSelectedRepositoryItem()
clearSelection()
rootNode.removeAllChildren()
val sortedRepositories = repositories.sortedBy { it.displayName }
for (repository in sortedRepositories) {
if (repository.usageInfo.isEmpty()) continue
val repoItem = RepositoryTreeItem.Repository(repository)
val repoNode = DefaultMutableTreeNode(repoItem)
for (usageInfo in repository.usageInfo) {
val moduleItem = RepositoryTreeItem.Module(usageInfo)
val treeNode = DefaultMutableTreeNode(moduleItem)
repoNode.add(treeNode)
if (previouslySelectedItem == moduleItem) {
selectionModel.selectionPath = TreePath(treeNode)
}
}
rootNode.add(repoNode)
if (previouslySelectedItem == repoItem) {
selectionModel.selectionPath = TreePath(repoNode)
}
}
TreeUtil.expandAll(this)
updateUI()
}
override fun getData(dataId: String) =
when (val selectedItem = getSelectedRepositoryItem()) {
is DataProvider -> selectedItem.getData(dataId)
else -> null
}
override fun performCopy(dataContext: DataContext) {
val selectedItem = getSelectedRepositoryItem()
if (selectedItem is CopyProvider) selectedItem.performCopy(dataContext)
}
override fun isCopyEnabled(dataContext: DataContext): Boolean {
val selectedItem = getSelectedRepositoryItem()
return selectedItem is CopyProvider && selectedItem.isCopyEnabled(dataContext)
}
override fun isCopyVisible(dataContext: DataContext): Boolean {
val selectedItem = getSelectedRepositoryItem()
return selectedItem is CopyProvider && selectedItem.isCopyVisible(dataContext)
}
private fun getSelectedRepositoryItem() = getRepositoryItemFrom(this.selectionPath)
private fun getRepositoryItemFrom(treePath: TreePath?): RepositoryTreeItem? {
val item = treePath?.lastPathComponent as? DefaultMutableTreeNode?
return item?.userObject as? RepositoryTreeItem
}
}
|
apache-2.0
|
ea132faba5581565da0d526f33395fa0
| 38.555556 | 127 | 0.687046 | 5.374778 | false | false | false | false |
zdary/intellij-community
|
platform/platform-api/src/com/intellij/openapi/project/ProjectUtil.kt
|
1
|
12162
|
// 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:JvmName("ProjectUtil")
package com.intellij.openapi.project
import com.intellij.ide.DataManager
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.appSystemDir
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.fileEditor.UniqueVFilePathBuilder
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.module.ModifiableModuleModel
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFilePathWrapper
import com.intellij.openapi.wm.WindowManager
import com.intellij.util.PathUtilRt
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.exists
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.text.trimMiddle
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.nio.file.Files
import java.nio.file.InvalidPathException
import java.nio.file.Path
import java.util.*
import java.util.function.Consumer
import javax.swing.JComponent
val NOTIFICATIONS_SILENT_MODE = Key.create<Boolean>("NOTIFICATIONS_SILENT_MODE")
val Module.rootManager: ModuleRootManager
get() = ModuleRootManager.getInstance(this)
@JvmOverloads @NlsSafe
fun calcRelativeToProjectPath(file: VirtualFile,
project: Project?,
includeFilePath: Boolean = true,
includeUniqueFilePath: Boolean = false,
keepModuleAlwaysOnTheLeft: Boolean = false): String {
if (file is VirtualFilePathWrapper && file.enforcePresentableName()) {
return if (includeFilePath) file.presentablePath else file.name
}
val url = when {
includeFilePath -> file.presentableUrl
includeUniqueFilePath && project != null -> UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file)
else -> file.name
}
return if (project == null) url
else displayUrlRelativeToProject(file, url, project, includeFilePath, keepModuleAlwaysOnTheLeft)
}
fun guessProjectForFile(file: VirtualFile?): Project? = ProjectLocator.getInstance().guessProjectForFile(file)
/**
* guessProjectForFile works incorrectly - even if file is config (idea config file) first opened project will be returned
*/
@JvmOverloads
fun guessProjectForContentFile(file: VirtualFile,
fileType: FileType = FileTypeManager.getInstance().getFileTypeByFileName(file.nameSequence)): Project? {
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file, fileType)) {
return null
}
val list = ProjectManager.getInstance().openProjects.filter {
!it.isDefault && it.isInitialized && !it.isDisposed && ProjectRootManager.getInstance(it).fileIndex.isInContent(file)
}
return list.firstOrNull { WindowManager.getInstance().getFrame(it)?.isActive ?: false } ?: list.firstOrNull()
}
fun isProjectOrWorkspaceFile(file: VirtualFile): Boolean = ProjectCoreUtil.isProjectOrWorkspaceFile(file)
@Deprecated(message = "This method is an unreliable hack, find another way to locate a project instance.")
fun guessCurrentProject(component: JComponent?): Project {
var project: Project? = null
if (component != null) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(component))
}
@Suppress("DEPRECATION")
return project
?: ProjectManager.getInstance().openProjects.firstOrNull()
?: CommonDataKeys.PROJECT.getData(DataManager.getInstance().dataContext)
?: ProjectManager.getInstance().defaultProject
}
fun currentOrDefaultProject(project: Project?): Project = project ?: ProjectManager.getInstance().defaultProject
inline fun <T> Project.modifyModules(crossinline task: ModifiableModuleModel.() -> T): T {
val model = ModuleManager.getInstance(this).modifiableModel
val result = model.task()
runWriteAction {
model.commit()
}
return result
}
fun isProjectDirectoryExistsUsingIo(parent: VirtualFile): Boolean {
return try {
Files.exists(Path.of(parent.path, Project.DIRECTORY_STORE_FOLDER))
}
catch (e: InvalidPathException) {
false
}
}
/**
* Tries to guess the "main project directory" of the project.
*
* There is no strict definition of what is a project directory, since a project can contain multiple modules located in different places,
* and the `.idea` directory can be located elsewhere (making the popular [Project.getBaseDir] method not applicable to get the "project
* directory"). This method should be preferred, although it can't provide perfect accuracy either.
*/
fun Project.guessProjectDir() : VirtualFile? {
if (isDefault) {
return null
}
val modules = ModuleManager.getInstance(this).modules
val module = if (modules.size == 1) modules.first() else modules.firstOrNull { it.name == this.name }
module?.guessModuleDir()?.let { return it }
return LocalFileSystem.getInstance().findFileByPath(basePath!!)
}
/**
* Returns some directory which is located near module files.
*
* There is no such thing as "base directory" for a module in IntelliJ project model. A module may have multiple content roots, or not have
* content roots at all. The module configuration file (.iml) may be located far away from the module files or doesn't exist at all. So this
* method tries to suggest some directory which is related to the module but due to its heuristics nature its result shouldn't be used for
* real actions as is, user should be able to review and change it. For example it can be used as a default selection in a file chooser.
*/
fun Module.guessModuleDir(): VirtualFile? {
val contentRoots = rootManager.contentRoots.filter { it.isDirectory }
return contentRoots.find { it.name == name } ?: contentRoots.firstOrNull() ?: moduleFile?.parent
}
@JvmOverloads
fun Project.getProjectCacheFileName(isForceNameUse: Boolean = false, hashSeparator: String = ".", extensionWithDot: String = ""): String {
return getProjectCacheFileName(presentableUrl, name, isForceNameUse, hashSeparator, extensionWithDot)
}
/**
* This is a variant of [getProjectCacheFileName] which can be used in tests before [Project] instance is created
* @param projectPath value of [Project.getPresentableUrl]
*/
fun getProjectCacheFileName(projectPath: Path): String {
return getProjectCacheFileName(projectPath.systemIndependentPath, projectPath.fileName.toString(), false, ".", "")
}
private fun getProjectCacheFileName(presentableUrl: String?,
projectName: String,
isForceNameUse: Boolean,
hashSeparator: String,
extensionWithDot: String): String {
val name = when {
isForceNameUse || presentableUrl == null -> projectName
else -> {
// lower case here is used for cosmetic reasons (develar - discussed with jeka - leave it as it was, user projects will not have long names as in our tests
PathUtilRt.getFileName(presentableUrl).toLowerCase(Locale.US).removeSuffix(ProjectFileType.DOT_DEFAULT_EXTENSION)
}
}
return doGetProjectFileName(presentableUrl, sanitizeFileName(name, truncateIfNeeded = false), hashSeparator, extensionWithDot)
}
@ApiStatus.Internal
fun doGetProjectFileName(presentableUrl: String?,
name: String,
hashSeparator: String,
extensionWithDot: String): String {
// do not use project.locationHash to avoid prefix for IPR projects (not required in our case because name in any case is prepended)
val locationHash = Integer.toHexString((presentableUrl ?: name).hashCode())
// trim name to avoid "File name too long"
return "${name.trimMiddle(name.length.coerceAtMost(255 - hashSeparator.length - locationHash.length), useEllipsisSymbol = false)}$hashSeparator$locationHash$extensionWithDot"
}
@JvmOverloads
fun Project.getProjectCachePath(@NonNls cacheDirName: String, isForceNameUse: Boolean = false, extensionWithDot: String = ""): Path {
return appSystemDir.resolve(cacheDirName).resolve(getProjectCacheFileName(isForceNameUse, extensionWithDot = extensionWithDot))
}
/**
* Returns path to a directory which can be used to store project-specific caches. Caches for different projects are stored under different
* directories, [dataDirName] is used to provide different directories for different kinds of caches in the same project.
*
* The function is similar to [getProjectCachePath], but all paths returned by this function for the same project are located under the same directory,
* and if a new project is created with the same name and location as some previously deleted project, it won't reuse its caches.
*/
@ApiStatus.Experimental
fun Project.getProjectDataPath(@NonNls dataDirName: String): Path {
return getProjectDataPathRoot(this).resolve(dataDirName)
}
val projectsDataDir: Path
get() = appSystemDir.resolve("projects")
/**
* Asynchronously deletes caches directories obtained via [getProjectDataPath] for all projects.
*/
@ApiStatus.Experimental
fun clearCachesForAllProjects(@NonNls dataDirName: String) {
projectsDataDir.directoryStreamIfExists { dirs ->
val filesToDelete = dirs.asSequence().map { it.resolve(dataDirName) }.filter { it.exists() }.map { it.toFile() }.toList()
FileUtil.asyncDelete(filesToDelete)
}
}
@ApiStatus.Internal
fun getProjectDataPathRoot(project: Project): Path = projectsDataDir.resolve(project.getProjectCacheFileName())
@ApiStatus.Internal
fun getProjectDataPathRoot(projectPath: Path): Path = projectsDataDir.resolve(getProjectCacheFileName(projectPath))
fun Project.getExternalConfigurationDir(): Path {
return getProjectCachePath("external_build_system")
}
/**
* Use parameters only for migration purposes, once all usages will be migrated, parameters will be removed
*/
@JvmOverloads
fun Project.getProjectCachePath(baseDir: Path, forceNameUse: Boolean = false, hashSeparator: String = "."): Path {
return baseDir.resolve(getProjectCacheFileName(forceNameUse, hashSeparator))
}
/**
* Add one-time projectOpened listener.
*/
fun runWhenProjectOpened(project : Project, handler: Runnable) {
runWhenProjectOpened(project) {
handler.run()
}
}
/**
* Add one-time first projectOpened listener.
*/
@JvmOverloads
fun runWhenProjectOpened(project: Project? = null, handler: Consumer<Project>) {
runWhenProjectOpened(project) {
handler.accept(it)
}
}
/**
* Add one-time projectOpened listener.
*/
inline fun runWhenProjectOpened(project: Project? = null, crossinline handler: (project: Project) -> Unit) {
val connection = (project ?: ApplicationManager.getApplication()).messageBus.simpleConnect()
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectOpened(eventProject: Project) {
if (project == null || project === eventProject) {
connection.disconnect()
handler(eventProject)
}
}
})
}
inline fun processOpenedProjects(processor: (Project) -> Unit) {
for (project in (ProjectManager.getInstanceIfCreated()?.openProjects ?: return)) {
if (project.isDisposed || !project.isInitialized) {
continue
}
processor(project)
}
}
fun isNotificationSilentMode(project: Project?): Boolean {
return ApplicationManager.getApplication().isHeadlessEnvironment || NOTIFICATIONS_SILENT_MODE[project, false]
}
|
apache-2.0
|
5260fc097adbe4f0f164166bbcdf4d67
| 41.527972 | 176 | 0.753494 | 4.69032 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/boxInline/smap/smap.kt
|
2
|
1233
|
// FILE: 1.kt
package builders
inline fun init(init: () -> Unit) {
init()
}
inline fun initTag2(init: () -> Unit) {
val p = 1;
init()
}
//{val p = initTag2(init); return p} to remove difference in linenumber processing through MethodNode and MethodVisitor should be: = initTag2(init)
inline fun head(init: () -> Unit) { val p = initTag2(init); return p}
inline fun html(init: () -> Unit) {
return init(init)
}
// FILE: 2.kt
import builders.*
inline fun test(): String {
var res = "Fail"
html {
head {
res = "OK"
}
}
return res
}
fun box(): String {
var expected = test();
return expected
}
// FILE: 1.smap
SMAP
1.kt
Kotlin
*S Kotlin
*F
+ 1 1.kt
builders/_1Kt
*L
1#1,21:1
10#1,3:22
6#1,2:25
*E
*S KotlinDebug
*F
+ 1 1.kt
builders/_1Kt
*L
14#1,3:22
18#1,2:25
*E
// FILE: 2.smap
SMAP
2.kt
Kotlin
*S Kotlin
*F
+ 1 2.kt
_2Kt
+ 2 1.kt
builders/_1Kt
*L
1#1,25:1
7#1,3:40
10#1:45
11#1,2:49
13#1:52
15#1:54
18#2:26
6#2,9:27
10#2,3:36
7#2:39
18#2:43
6#2:44
14#2:46
10#2,2:47
12#2:51
7#2:53
*E
*S KotlinDebug
*F
+ 1 2.kt
_2Kt
*L
20#1,3:40
20#1:45
20#1,2:49
20#1:52
20#1:54
9#1:26
9#1,9:27
9#1,3:36
9#1:39
20#1:43
20#1:44
20#1:46
20#1,2:47
20#1:51
20#1:53
*E
|
apache-2.0
|
ed9f7960c557fb65b1c7adb29ac539d0
| 9.457627 | 147 | 0.588808 | 2.107692 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveModifierFix.kt
|
1
|
6874
|
// 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.daemon.impl.actions.IntentionActionWithFixAllOption
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.types.Variance
class RemoveModifierFix(
element: KtModifierListOwner,
@FileModifier.SafeFieldForPreview
private val modifier: KtModifierKeywordToken,
private val isRedundant: Boolean
) : KotlinCrossLanguageQuickFixAction<KtModifierListOwner>(element), IntentionActionWithFixAllOption {
@Nls
private val text = run {
val modifierText = modifier.value
when {
isRedundant ->
KotlinBundle.message("remove.redundant.0.modifier", modifierText)
modifier === KtTokens.ABSTRACT_KEYWORD || modifier === KtTokens.OPEN_KEYWORD ->
KotlinBundle.message("make.0.not.1", AddModifierFix.getElementName(element), modifierText)
else ->
KotlinBundle.message("remove.0.modifier", modifierText, modifier)
}
}
override fun getFamilyName() = KotlinBundle.message("remove.modifier")
override fun getText() = text
override fun isAvailableImpl(project: Project, editor: Editor?, file: PsiFile) = element?.hasModifier(modifier) == true
override fun invokeImpl(project: Project, editor: Editor?, file: PsiFile) {
invoke()
}
operator fun invoke() {
element?.removeModifier(modifier)
}
companion object {
fun createRemoveModifierFromListOwnerFactory(
modifier: KtModifierKeywordToken,
isRedundant: Boolean = false
): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val modifierListOwner = QuickFixUtil.getParentElementOfType(diagnostic, KtModifierListOwner::class.java) ?: return null
return RemoveModifierFix(modifierListOwner, modifier, isRedundant)
}
}
}
fun createRemoveModifierFactory(isRedundant: Boolean = false): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val psiElement = diagnostic.psiElement
val elementType = psiElement.node.elementType as? KtModifierKeywordToken ?: return null
val modifierListOwner = psiElement.getStrictParentOfType<KtModifierListOwner>() ?: return null
return RemoveModifierFix(modifierListOwner, elementType, isRedundant)
}
}
}
fun createRemoveProjectionFactory(isRedundant: Boolean): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val projection = diagnostic.psiElement as KtTypeProjection
val elementType = projection.projectionToken?.node?.elementType as? KtModifierKeywordToken ?: return null
return RemoveModifierFix(projection, elementType, isRedundant)
}
}
}
fun createRemoveVarianceFactory(): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val psiElement = diagnostic.psiElement as KtTypeParameter
val modifier = when (psiElement.variance) {
Variance.IN_VARIANCE -> KtTokens.IN_KEYWORD
Variance.OUT_VARIANCE -> KtTokens.OUT_KEYWORD
else -> return null
}
return RemoveModifierFix(psiElement, modifier, isRedundant = false)
}
}
}
fun createRemoveSuspendFactory(): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val suspendKeyword = diagnostic.psiElement
val modifierList = suspendKeyword.parent as KtDeclarationModifierList
val type = modifierList.parent as KtTypeReference
if (!type.hasModifier(KtTokens.SUSPEND_KEYWORD)) return null
return RemoveModifierFix(type, KtTokens.SUSPEND_KEYWORD, isRedundant = false)
}
}
}
fun createRemoveLateinitFactory(): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val keyword = diagnostic.psiElement
val modifierList = keyword.parent as? KtDeclarationModifierList ?: return null
val property = modifierList.parent as? KtProperty ?: return null
if (!property.hasModifier(KtTokens.LATEINIT_KEYWORD)) return null
return RemoveModifierFix(property, KtTokens.LATEINIT_KEYWORD, isRedundant = false)
}
}
}
fun createRemoveFunFromInterfaceFactory(): KotlinSingleIntentionActionFactory {
return object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): RemoveModifierFix? {
val keyword = diagnostic.psiElement
val modifierList = keyword.parent as? KtDeclarationModifierList ?: return null
val funInterface = (modifierList.parent as? KtClass)?.takeIf {
it.isInterface() && it.hasModifier(KtTokens.FUN_KEYWORD)
} ?: return null
return RemoveModifierFix(funInterface, KtTokens.FUN_KEYWORD, isRedundant = false)
}
}
}
}
}
|
apache-2.0
|
db3dbea4cfd93401b6e35a94d75d980b
| 48.453237 | 158 | 0.65915 | 6.159498 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/imports/unusedImports.kt
|
12
|
2356
|
// 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.
@file:JvmName("GroovyUnusedImportUtil")
package org.jetbrains.plugins.groovy.lang.resolve.imports
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiKeyword.SUPER
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition
fun unusedImports(file: GroovyFile): Set<GrImportStatement> {
val result = file.validImportStatements.toMutableSet()
result -= usedImports(file)
return result
}
fun usedImports(file: GroovyFile): Set<GrImportStatement> {
val imports = file.imports
val (referencedStatements, unresolvedReferenceNames) = run {
val searcher = ReferencedImportsSearcher()
file.accept(searcher)
searcher.results
}
val usedStatements = HashSet(referencedStatements)
usedStatements -= imports.findUnnecessaryStatements()
usedStatements += imports.findUnresolvedStatements(unresolvedReferenceNames)
return usedStatements
}
private class ReferencedImportsSearcher : PsiRecursiveElementWalkingVisitor() {
private val referencedStatements = HashSet<GrImportStatement>()
private val unresolvedReferenceNames = LinkedHashSet<String>()
val results: Pair<Set<GrImportStatement>, Set<String>> get() = referencedStatements to unresolvedReferenceNames
override fun visitElement(element: PsiElement) {
if (element !is GrImportStatement && element !is GrPackageDefinition) {
super.visitElement(element)
}
if (element is GrReferenceElement<*>) {
visitRefElement(element)
}
}
private fun visitRefElement(refElement: GrReferenceElement<*>) {
if (refElement.isQualified) return
val refName = refElement.referenceName
if (refName == null || SUPER == refName) return
val results = refElement.multiResolve(false)
if (results.isEmpty()) {
unresolvedReferenceNames.add(refName)
}
else {
results.mapNotNullTo(referencedStatements) {
it.currentFileResolveContext as? GrImportStatement
}
}
}
}
|
apache-2.0
|
f29f512ba8dc6d9b1812fd4788c4e799
| 34.164179 | 140 | 0.77292 | 4.592593 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt
|
1
|
6600
|
// 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.parameterInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetails
import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.containsError
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
import org.jetbrains.kotlin.types.typeUtil.isEnum
import org.jetbrains.kotlin.types.typeUtil.isUnit
fun providePropertyTypeHint(elem: PsiElement): List<InlayInfoDetails> {
(elem as? KtCallableDeclaration)?.let { property ->
property.nameIdentifier?.let { ident ->
provideTypeHint(property, ident.endOffset)?.let { return listOf(it) }
}
}
return emptyList()
}
fun provideTypeHint(element: KtCallableDeclaration, offset: Int): InlayInfoDetails? {
var type: KotlinType = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(element).unwrap()
if (type.containsError()) return null
val declarationDescriptor = type.constructor.declarationDescriptor
val name = declarationDescriptor?.name
if (name == SpecialNames.NO_NAME_PROVIDED) {
if (element is KtProperty && element.isLocal) {
// for local variables, an anonymous object type is not collapsed to its supertype,
// so showing the supertype will be misleading
return null
}
type = type.immediateSupertypes().singleOrNull() ?: return null
} else if (name?.isSpecial == true) {
return null
}
if (element is KtProperty && element.isLocal && type.isUnit() && element.isMultiLine()) {
val propertyLine = element.getLineNumber()
val equalsTokenLine = element.equalsToken?.getLineNumber() ?: -1
val initializerLine = element.initializer?.getLineNumber() ?: -1
if (propertyLine == equalsTokenLine && propertyLine != initializerLine) {
val indentBeforeProperty = (element.prevSibling as? PsiWhiteSpace)?.text?.substringAfterLast('\n')
val indentBeforeInitializer = (element.initializer?.prevSibling as? PsiWhiteSpace)?.text?.substringAfterLast('\n')
if (indentBeforeProperty == indentBeforeInitializer) {
return null
}
}
}
return if (isUnclearType(type, element)) {
val settings = element.containingKtFile.kotlinCustomSettings
val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(element.safeAnalyzeNonSourceRootCode(), element).renderTypeIntoInlayInfo(type)
val prefix = buildString {
if (settings.SPACE_BEFORE_TYPE_COLON) {
append(" ")
}
append(":")
if (settings.SPACE_AFTER_TYPE_COLON) {
append(" ")
}
}
val inlayInfo = InlayInfo(
text = "", offset = offset,
isShowOnlyIfExistedBefore = false, isFilterByBlacklist = true, relatesToPrecedingText = true
)
return InlayInfoDetails(inlayInfo, listOf(TextInlayInfoDetail(prefix)) + renderedType)
} else {
null
}
}
private fun isUnclearType(type: KotlinType, element: KtCallableDeclaration): Boolean {
if (element !is KtProperty) return true
val initializer = element.initializer ?: return true
if (initializer is KtConstantExpression || initializer is KtStringTemplateExpression) return false
if (initializer is KtUnaryExpression && initializer.baseExpression is KtConstantExpression) return false
if (isConstructorCall(initializer)) {
return false
}
if (initializer is KtDotQualifiedExpression) {
val selectorExpression = initializer.selectorExpression
if (type.isEnum()) {
// Do not show type for enums if initializer has enum entry with explicit enum name: val p = Enum.ENTRY
val enumEntryDescriptor: DeclarationDescriptor? = selectorExpression?.resolveMainReferenceToDescriptors()?.singleOrNull()
if (enumEntryDescriptor != null && DescriptorUtils.isEnumEntry(enumEntryDescriptor)) {
return false
}
}
if (initializer.receiverExpression.isClassOrPackageReference() && isConstructorCall(selectorExpression)) {
return false
}
}
return true
}
private fun isConstructorCall(initializer: KtExpression?): Boolean {
if (initializer is KtCallExpression) {
val resolvedCall = initializer.resolveToCall(BodyResolveMode.FULL)
val resolvedDescriptor = resolvedCall?.candidateDescriptor
if (resolvedDescriptor is SamConstructorDescriptor) {
return true
}
if (resolvedDescriptor is ConstructorDescriptor &&
(resolvedDescriptor.constructedClass.declaredTypeParameters.isEmpty() || initializer.typeArgumentList != null)
) {
return true
}
return false
}
return false
}
private fun KtExpression.isClassOrPackageReference(): Boolean =
when (this) {
is KtNameReferenceExpression -> this.resolveMainReferenceToDescriptors().singleOrNull()
.let { it is ClassDescriptor || it is PackageViewDescriptor }
is KtDotQualifiedExpression -> this.selectorExpression?.isClassOrPackageReference() ?: false
else -> false
}
|
apache-2.0
|
ceb8d56fd26ff87d911d9f71eaff48c7
| 43.295302 | 158 | 0.722727 | 5.254777 | false | false | false | false |
smmribeiro/intellij-community
|
platform/indexing-impl/src/com/intellij/psi/impl/search/WordRequestInfoImpl.kt
|
12
|
993
|
// 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.psi.impl.search
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.SearchSession
internal data class WordRequestInfoImpl internal constructor(
private val word: String,
private val searchScope: SearchScope,
private val caseSensitive: Boolean,
private val searchContext: Short,
private val containerName: String?
) : WordRequestInfo {
override fun getWord(): String = word
override fun getSearchScope(): SearchScope = searchScope
override fun isCaseSensitive(): Boolean = caseSensitive
override fun getSearchContext(): Short = searchContext
override fun getContainerName(): String? = containerName
override fun getSearchSession(): SearchSession {
return SearchSession() // layered searches optimization is not applicable to model search, continue to search the old way
}
}
|
apache-2.0
|
3eb4501f3c11c5fd0f4452ae2b93c65c
| 34.464286 | 140 | 0.780463 | 4.867647 | false | false | false | false |
google/intellij-community
|
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/utils.kt
|
1
|
5933
|
// 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.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.RawCommandLineEditor
import com.intellij.ui.SearchTextField
import com.intellij.ui.TitledSeparator
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.DslComponentProperty
import com.intellij.ui.dsl.builder.HyperlinkEventAction
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.builder.components.DslLabel
import com.intellij.ui.dsl.builder.components.DslLabelType
import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import com.intellij.ui.dsl.gridLayout.Gaps
import com.intellij.ui.dsl.gridLayout.GridLayoutComponentProperty
import com.intellij.ui.dsl.gridLayout.toGaps
import org.jetbrains.annotations.ApiStatus
import javax.swing.*
import javax.swing.text.JTextComponent
/**
* Internal component properties for UI DSL
*/
@ApiStatus.Internal
internal enum class DslComponentPropertyInternal {
/**
* A mark that component is a cell label, see [Cell.label]
*
* Value: true
*/
CELL_LABEL
}
/**
* [JPanel] descendants that should use default vertical gaps around similar to other standard components like labels, text fields etc
*/
private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf(
RawCommandLineEditor::class,
SearchTextField::class,
SegmentedButtonComponent::class,
SegmentedButtonToolbar::class,
TextFieldWithBrowseButton::class,
TitledSeparator::class
)
/**
* Throws exception instead of logging warning. Useful while forms building to avoid layout mistakes
*/
private const val FAIL_ON_WARN = false
private val LOG = Logger.getInstance("Jetbrains UI DSL")
/**
* Components that can have assigned labels
*/
private val ALLOWED_LABEL_COMPONENTS = listOf(
JComboBox::class,
JSlider::class,
JSpinner::class,
JTable::class,
JTextComponent::class,
JTree::class,
SegmentedButtonComponent::class,
SegmentedButtonToolbar::class
)
internal val JComponent.origin: JComponent
get() {
return when (this) {
is TextFieldWithBrowseButton -> textField
is ComponentWithBrowseButton<*> -> childComponent
else -> this
}
}
internal fun prepareVisualPaddings(component: JComponent): Gaps {
var customVisualPaddings = component.getClientProperty(DslComponentProperty.VISUAL_PADDINGS) as? Gaps
if (customVisualPaddings == null) {
// todo Move into components implementation
// Patch visual paddings for known components
customVisualPaddings = when (component) {
is RawCommandLineEditor -> component.editorField.insets.toGaps()
is SearchTextField -> component.textEditor.insets.toGaps()
is JScrollPane -> Gaps.EMPTY
is ComponentWithBrowseButton<*> -> component.childComponent.insets.toGaps()
else -> {
if (component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) != null) {
Gaps.EMPTY
}
else {
null
}
}
}
}
if (customVisualPaddings == null) {
return component.insets.toGaps()
}
component.putClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS, false)
return customVisualPaddings
}
internal fun getComponentGaps(left: Int, right: Int, component: JComponent, spacing: SpacingConfiguration): Gaps {
val top = getDefaultVerticalGap(component, spacing)
var bottom = top
if (component.getClientProperty(DslComponentProperty.NO_BOTTOM_GAP) == true) {
bottom = 0
}
return Gaps(top = top, left = left, bottom = bottom, right = right)
}
/**
* Returns default top and bottom gap for [component]. All non [JPanel] components or
* [DEFAULT_VERTICAL_GAP_COMPONENTS] have default vertical gap, zero otherwise
*/
internal fun getDefaultVerticalGap(component: JComponent, spacing: SpacingConfiguration): Int {
val noDefaultVerticalGap = component is JPanel
&& component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) == null
&& !DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz -> clazz.isInstance(component) }
return if (noDefaultVerticalGap) 0 else spacing.verticalComponentGap
}
internal fun createComment(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): DslLabel {
val result = DslLabel(DslLabelType.COMMENT)
result.action = action
result.maxLineLength = maxLineLength
result.text = text
return result
}
internal fun isAllowedLabel(cell: CellBaseImpl<*>?): Boolean {
return getLabelComponentFor(cell) != null
}
internal fun labelCell(label: JLabel, cell: CellBaseImpl<*>?) {
val component = getLabelComponentFor(cell) ?: return
label.labelFor = component
}
private fun getLabelComponentFor(cell: CellBaseImpl<*>?): JComponent? {
if (cell is CellImpl<*>) {
return getLabelComponentFor(cell.component.origin)
}
return null
}
private fun getLabelComponentFor(component: JComponent): JComponent? {
val labelFor = component.getClientProperty(DslComponentProperty.LABEL_FOR)
if (labelFor != null) {
if (labelFor is JComponent) {
return labelFor
}
else {
throw UiDslException("LABEL_FOR must be a JComponent: ${labelFor::class.java.name}")
}
}
if (ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(component) }) {
return component
}
return null
}
internal fun warn(message: String) {
if (FAIL_ON_WARN) {
throw UiDslException(message)
}
else {
LOG.warn(message)
}
}
|
apache-2.0
|
11ee2c2169495b55367ea6512a366be3
| 31.779006 | 158 | 0.748188 | 4.491294 | false | false | false | false |
michaelkourlas/voipms-sms-client
|
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/preferences/fragments/DatabasePreferencesFragment.kt
|
1
|
10623
|
/*
* VoIP.ms SMS
* Copyright (C) 2018-2021 Michael Kourlas
*
* 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.kourlas.voipms_sms.preferences.fragments
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.Intent.CATEGORY_OPENABLE
import android.net.Uri
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference
import com.takisoft.preferencex.PreferenceFragmentCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.preferences.getDids
import net.kourlas.voipms_sms.utils.preferences
import net.kourlas.voipms_sms.utils.showAlertDialog
import net.kourlas.voipms_sms.utils.showSnackbar
/**
* Fragment used to display the database preferences.
*/
class DatabasePreferencesFragment : PreferenceFragmentCompat() {
// Preference listeners
private val importActivityResultLauncher =
registerForActivityResult(object :
ActivityResultContracts.OpenDocument() {
override fun createIntent(
context: Context,
input: Array<out String>
): Intent {
val intent = super.createIntent(context, input)
intent.addCategory(CATEGORY_OPENABLE)
return intent
}
}) {
if (it != null) {
import(it)
}
}
private val importListener = Preference.OnPreferenceClickListener {
try {
importActivityResultLauncher.launch(arrayOf("*/*"))
} catch (_: ActivityNotFoundException) {
activity?.let {
showSnackbar(
it, R.id.coordinator_layout,
getString(
R.string.preferences_database_fail_open_document
)
)
}
}
true
}
private val exportActivityResultLauncher =
registerForActivityResult(object :
ActivityResultContracts.CreateDocument() {
override fun createIntent(
context: Context,
input: String
): Intent {
val intent = super.createIntent(context, input)
intent.type = "application/octet-stream"
return intent
}
}) {
if (it != null) {
export(it)
}
}
private val exportListener = Preference.OnPreferenceClickListener {
try {
exportActivityResultLauncher.launch("sms.db")
} catch (_: ActivityNotFoundException) {
activity?.let {
showSnackbar(
it, R.id.coordinator_layout,
getString(
R.string.preferences_database_fail_create_document
)
)
}
}
true
}
private val cleanUpListener = Preference.OnPreferenceClickListener {
cleanUp()
true
}
private val deleteListener = Preference.OnPreferenceClickListener {
delete()
true
}
override fun onCreatePreferencesFix(
savedInstanceState: Bundle?,
rootKey: String?
) {
// Add preferences
addPreferencesFromResource(R.xml.preferences_database)
// Assign handlers to preferences
for (preference in preferenceScreen.preferences) {
when (preference.key) {
getString(
R.string.preferences_database_import_key
) ->
preference.onPreferenceClickListener = importListener
getString(
R.string.preferences_database_export_key
) ->
preference.onPreferenceClickListener = exportListener
getString(
R.string.preferences_database_clean_up_key
) ->
preference.onPreferenceClickListener = cleanUpListener
getString(
R.string.preferences_database_delete_key
) ->
preference.onPreferenceClickListener = deleteListener
}
}
}
/**
* Imports the database located at the specified URI.
*/
private fun import(uri: Uri) {
activity?.let {
lifecycleScope.launch(Dispatchers.IO) {
try {
val importFd = it.contentResolver.openFileDescriptor(
uri, "r"
)
?: throw Exception("Could not open file")
Database.getInstance(it).import(importFd)
} catch (e: Exception) {
ensureActive()
lifecycleScope.launch(Dispatchers.Main) {
showSnackbar(
it,
R.id.coordinator_layout,
getString(
R.string.preferences_database_import_fail,
"${e.message} (${e.javaClass.simpleName})"
)
)
}
return@launch
}
ensureActive()
lifecycleScope.launch(Dispatchers.Main) {
showSnackbar(
it, R.id.coordinator_layout, it.getString(
R.string.preferences_database_import_success
)
)
}
}
}
}
/**
* Exports the database to the specified URI.
*/
private fun export(uri: Uri) {
activity?.let {
lifecycleScope.launch(Dispatchers.IO) {
try {
val exportFd = it.contentResolver.openFileDescriptor(
uri, "w"
)
?: throw Exception("Could not open file")
Database.getInstance(it).export(exportFd)
} catch (e: Exception) {
ensureActive()
withContext(Dispatchers.Default) {
showSnackbar(
it,
R.id.coordinator_layout,
getString(
R.string.preferences_database_export_fail,
"${e.message} (${e.javaClass.simpleName})"
)
)
}
return@launch
}
ensureActive()
withContext(Dispatchers.Default) {
showSnackbar(
it, R.id.coordinator_layout, it.getString(
R.string.preferences_database_export_success
)
)
}
}
}
}
private fun cleanUp() {
val activity = activity ?: return
val options = arrayOf(
activity.getString(
R.string.preferences_database_clean_up_deleted_messages
),
activity.getString(
R.string.preferences_database_clean_up_removed_dids
)
)
val selectedOptions = mutableListOf<Int>()
// Ask user which kind of clean up is desired, and then perform that
// clean up
AlertDialog.Builder(activity).apply {
setTitle(
context.getString(
R.string.preferences_database_clean_up_title
)
)
setMultiChoiceItems(
options, null
) { _, which, isChecked ->
if (isChecked) {
selectedOptions.add(which)
} else {
selectedOptions.remove(which)
}
}
setPositiveButton(
context.getString(R.string.ok)
) { _, _ ->
val deletedMessages = selectedOptions.contains(0)
val removedDids = selectedOptions.contains(1)
lifecycleScope.launch(Dispatchers.Default) {
if (deletedMessages) {
Database.getInstance(context)
.deleteTableDeletedContents()
}
if (removedDids) {
Database.getInstance(context).deleteMessagesWithoutDids(
getDids(context)
)
}
}
}
setNegativeButton(context.getString(R.string.cancel), null)
setCancelable(false)
show()
}
}
private fun delete() {
val activity = activity ?: return
// Prompt the user before actually deleting the entire database
showAlertDialog(
activity,
activity.getString(
R.string.preferences_database_delete_confirm_title
),
activity.getString(
R.string.preferences_database_delete_confirm_message
),
activity.applicationContext
.getString(R.string.delete),
{ _, _ ->
lifecycleScope.launch(Dispatchers.Default) {
Database.getInstance(
activity.applicationContext
)
.deleteTablesContents()
}
},
activity.getString(R.string.cancel), null
)
}
}
|
apache-2.0
|
c3a3616dfbb1f45bd111f2097380e3ea
| 33.160772 | 80 | 0.513226 | 5.918106 | false | false | false | false |
siosio/intellij-community
|
platform/vcs-impl/src/com/intellij/vcs/commit/ShowNotificationCommitResultHandler.kt
|
1
|
3950
|
// 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.notification.NotificationType
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.util.text.StringUtil.isEmpty
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_CANCELED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FAILED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED
import com.intellij.openapi.vcs.VcsNotificationIdsHolder.Companion.COMMIT_FINISHED_WITH_WARNINGS
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.vcs.commit.AbstractCommitter.Companion.collectErrors
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
private fun hasOnlyWarnings(exceptions: List<VcsException>) = exceptions.all { it.isWarning }
class ShowNotificationCommitResultHandler(private val committer: AbstractCommitter) : CommitResultHandler {
private val notifier = VcsNotifier.getInstance(committer.project)
override fun onSuccess(commitMessage: String) = reportResult()
override fun onCancel() {
notifier.notifyMinorWarning(COMMIT_CANCELED, "", message("vcs.commit.canceled"))
}
override fun onFailure(errors: List<VcsException>) = reportResult()
private fun reportResult() {
val message = getCommitSummary()
val allExceptions = committer.exceptions
if (allExceptions.isEmpty()) {
notifier.notifySuccess(COMMIT_FINISHED, "", message)
return
}
val errors = collectErrors(allExceptions)
val errorsSize = errors.size
val warningsSize = allExceptions.size - errorsSize
val notificationActions = allExceptions.filterIsInstance<CommitExceptionWithActions>().flatMap { it.actions }
val title: @NlsContexts.NotificationTitle String
val displayId: @NonNls String
val notificationType: NotificationType
if (errorsSize > 0) {
displayId = COMMIT_FAILED
title = message("message.text.commit.failed.with.error", errorsSize)
notificationType = NotificationType.ERROR
}
else {
displayId = COMMIT_FINISHED_WITH_WARNINGS
title = message("message.text.commit.finished.with.warning", warningsSize)
notificationType = NotificationType.WARNING
}
val notification = VcsNotifier.IMPORTANT_ERROR_NOTIFICATION.createNotification(title, message, notificationType)
notification.setDisplayId(displayId)
notificationActions.forEach { notification.addAction(it) }
notification.addAction(notifier.createShowDetailsAction())
notification.notify(committer.project)
}
@NlsContexts.NotificationContent
private fun getCommitSummary() = HtmlBuilder().apply {
append(getFileSummaryReport())
val commitMessage = committer.commitMessage
if (!isEmpty(commitMessage)) {
append(": ").append(commitMessage) // NON-NLS
}
val feedback = committer.feedback
if (feedback.isNotEmpty()) {
br()
appendWithSeparators(HtmlChunk.br(), feedback.map(HtmlChunk::text))
}
val exceptions = committer.exceptions
if (!hasOnlyWarnings(exceptions)) {
br()
appendWithSeparators(HtmlChunk.br(), exceptions.map { HtmlChunk.text(it.message) })
}
}.toString()
private fun getFileSummaryReport(): @Nls String {
val failed = committer.failedToCommitChanges.size
val committed = committer.changes.size - failed
if (failed > 0) {
return message("vcs.commit.files.committed.and.files.failed.to.commit", committed, failed)
}
return message("vcs.commit.files.committed", committed)
}
}
|
apache-2.0
|
4b8279e2924c195c77c7810bfcb90110
| 40.589474 | 140 | 0.766835 | 4.561201 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/KotlinLightCodeInsightFixtureTestCase.kt
|
1
|
22874
|
// 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.test
import com.intellij.application.options.CodeStyle
import com.intellij.codeInsight.daemon.impl.EditorTracker
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionManagerEx
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.externalSystem.service.project.ProjectDataManager
import com.intellij.openapi.fileEditor.impl.text.TextEditorPsiDataProvider
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiClassOwner
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.ProjectScope
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.LoggedErrorProcessor
import com.intellij.testFramework.RunAll
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.util.ThrowableRunnable
import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.config.CompilerSettings
import org.jetbrains.kotlin.config.CompilerSettings.Companion.DEFAULT_ADDITIONAL_ARGUMENTS
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.config.LanguageVersion
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCommonCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinCompilerSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.facet.*
import org.jetbrains.kotlin.idea.formatter.KotlinLanguageCodeStyleSettingsProvider
import org.jetbrains.kotlin.idea.formatter.KotlinStyleGuideCodeStyle
import org.jetbrains.kotlin.idea.inspections.UnusedSymbolInspection
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.API_VERSION_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.COMPILER_ARGUMENTS_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.JVM_TARGET_DIRECTIVE
import org.jetbrains.kotlin.idea.test.CompilerTestDirectives.LANGUAGE_VERSION_DIRECTIVE
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.KotlinRoot
import org.jetbrains.kotlin.idea.test.util.slashedPath
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.rethrow
import java.io.File
import java.io.IOException
import java.nio.file.Path
abstract class KotlinLightCodeInsightFixtureTestCase : KotlinLightCodeInsightFixtureTestCaseBase() {
private val exceptions = ArrayList<Throwable>()
protected open val captureExceptions = false
protected fun testDataFile(fileName: String): File = File(testDataDirectory, fileName)
protected fun testDataFile(): File = testDataFile(fileName())
protected fun testDataFilePath(): Path = testDataFile().toPath()
protected fun testPath(fileName: String = fileName()): String = testDataFile(fileName).toString()
protected fun testPath(): String = testPath(fileName())
protected open fun fileName(): String = KotlinTestUtils.getTestDataFileName(this::class.java, this.name) ?: (getTestName(false) + ".kt")
@Deprecated("Migrate to 'testDataDirectory'.", ReplaceWith("testDataDirectory"))
final override fun getTestDataPath(): String = testDataDirectory.slashedPath
open val testDataDirectory: File by lazy {
File(TestMetadataUtil.getTestDataPath(javaClass))
}
override fun setUp() {
super.setUp()
enableKotlinOfficialCodeStyle(project)
if (!isFirPlugin) {
// We do it here to avoid possible initialization problems
// UnusedSymbolInspection() calls IDEA UnusedDeclarationInspection() in static initializer,
// which in turn registers some extensions provoking "modifications aren't allowed during highlighting"
// when done lazily
UnusedSymbolInspection()
}
VfsRootAccess.allowRootAccess(myFixture.testRootDisposable, KotlinRoot.DIR.path)
EditorTracker.getInstance(project)
if (!isFirPlugin) {
invalidateLibraryCache(project)
}
}
override fun runBare(testRunnable: ThrowableRunnable<Throwable>) {
if (captureExceptions) {
LoggedErrorProcessor.executeWith<RuntimeException>(object : LoggedErrorProcessor() {
override fun processError(category: String, message: String?, t: Throwable?, details: Array<out String>): Boolean {
exceptions.addIfNotNull(t)
return super.processError(category, message, t, details)
}
}) {
super.runBare(testRunnable)
}
}
else {
super.runBare(testRunnable)
}
}
override fun tearDown() {
runAll(
ThrowableRunnable { disableKotlinOfficialCodeStyle(project) },
ThrowableRunnable { super.tearDown() },
)
if (exceptions.isNotEmpty()) {
exceptions.forEach { it.printStackTrace() }
throw AssertionError("Exceptions in other threads happened")
}
}
override fun getProjectDescriptor(): LightProjectDescriptor = getProjectDescriptorFromFileDirective()
protected fun getProjectDescriptorFromAnnotation(): LightProjectDescriptor {
val testMethod = this::class.java.getDeclaredMethod(name)
return when (testMethod.getAnnotation(ProjectDescriptorKind::class.java)?.value) {
JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES -> KotlinJdkAndMultiplatformStdlibDescriptor.JDK_AND_MULTIPLATFORM_STDLIB_WITH_SOURCES
KOTLIN_JVM_WITH_STDLIB_SOURCES -> ProjectDescriptorWithStdlibSources.INSTANCE
KOTLIN_JAVASCRIPT -> KotlinStdJSProjectDescriptor
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JVM_WITH_STDLIB_SOURCES_WITH_ADDITIONAL_JS,
mainModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE,
additionalModuleDescriptor = KotlinStdJSProjectDescriptor
)
}
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB -> {
KotlinMultiModuleProjectDescriptor(
KOTLIN_JAVASCRIPT_WITH_ADDITIONAL_JVM_WITH_STDLIB,
mainModuleDescriptor = KotlinStdJSProjectDescriptor,
additionalModuleDescriptor = ProjectDescriptorWithStdlibSources.INSTANCE
)
}
else -> throw IllegalStateException("Unknown value for project descriptor kind")
}
}
protected fun getProjectDescriptorFromTestName(): LightProjectDescriptor {
val testName = StringUtil.toLowerCase(getTestName(false))
return when {
testName.endsWith("runtime") -> KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
testName.endsWith("stdlib") -> ProjectDescriptorWithStdlibSources.INSTANCE
else -> KotlinLightProjectDescriptor.INSTANCE
}
}
protected fun getProjectDescriptorFromFileDirective(): LightProjectDescriptor {
val file = mainFile()
if (!file.exists()) {
return KotlinLightProjectDescriptor.INSTANCE
}
try {
val fileText = FileUtil.loadFile(file, true)
val withLibraryDirective = InTextDirectivesUtils.findLinesWithPrefixesRemoved(fileText, "WITH_LIBRARY:")
val minJavaVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "MIN_JAVA_VERSION:")?.toInt()
if (minJavaVersion != null && !(InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB"))
) {
error("MIN_JAVA_VERSION so far is supported for RUNTIME/WITH_STDLIB only")
}
return when {
withLibraryDirective.isNotEmpty() ->
SdkAndMockLibraryProjectDescriptor(IDEA_TEST_DATA_DIR.resolve(withLibraryDirective[0]).path, true)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITHOUT_SOURCES") ->
ProjectDescriptorWithStdlibSources.INSTANCE_NO_SOURCES
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_KOTLIN_TEST") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_KOTLIN_TEST
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_FULL_JDK") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_JDK_10") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance(LanguageLevel.JDK_10)
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_REFLECT") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_REFLECT
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_SCRIPT_RUNTIME") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_SCRIPT_RUNTIME
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME_WITH_STDLIB_JDK8") ->
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_WITH_STDLIB_JDK8
InTextDirectivesUtils.isDirectiveDefined(fileText, "RUNTIME") ||
InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_STDLIB") ->
if (minJavaVersion != null) {
object : KotlinWithJdkAndRuntimeLightProjectDescriptor(INSTANCE.libraryFiles, INSTANCE.librarySourceFiles) {
val sdkValue by lazy { sdk(minJavaVersion) }
override fun getSdk(): Sdk = sdkValue
}
} else {
KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
InTextDirectivesUtils.isDirectiveDefined(fileText, "JS") ->
KotlinStdJSProjectDescriptor
InTextDirectivesUtils.isDirectiveDefined(fileText, "ENABLE_MULTIPLATFORM") ->
KotlinProjectDescriptorWithFacet.KOTLIN_STABLE_WITH_MULTIPLATFORM
else -> getDefaultProjectDescriptor()
}
} catch (e: IOException) {
throw rethrow(e)
}
}
protected open fun mainFile() = File(testDataDirectory, fileName())
private fun sdk(javaVersion: Int): Sdk = when (javaVersion) {
6 -> IdeaTestUtil.getMockJdk16()
8 -> IdeaTestUtil.getMockJdk18()
9 -> IdeaTestUtil.getMockJdk9()
11 -> {
if (SystemInfo.isJavaVersionAtLeast(javaVersion, 0, 0)) {
PluginTestCaseBase.fullJdk()
} else {
error("JAVA_HOME have to point at least to JDK 11")
}
}
else -> error("Unsupported JDK version $javaVersion")
}
protected open fun getDefaultProjectDescriptor(): KotlinLightProjectDescriptor = KotlinLightProjectDescriptor.INSTANCE
protected fun performNotWriteEditorAction(actionId: String): Boolean {
val dataContext = (myFixture.editor as EditorEx).dataContext
val managerEx = ActionManagerEx.getInstanceEx()
val action = managerEx.getAction(actionId)
val event = AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, Presentation(), managerEx, 0)
if (ActionUtil.lastUpdateAndCheckDumb(action, event, false)) {
ActionUtil.performActionDumbAwareWithCallbacks(action, event)
return true
}
return false
}
fun JavaCodeInsightTestFixture.configureByFile(file: File): PsiFile {
val relativePath = file.toRelativeString(testDataDirectory)
return configureByFile(relativePath)
}
fun JavaCodeInsightTestFixture.configureByFiles(vararg file: File): List<PsiFile> {
val relativePaths = file.map { it.toRelativeString(testDataDirectory) }.toTypedArray()
return configureByFiles(*relativePaths).toList()
}
fun JavaCodeInsightTestFixture.checkResultByFile(file: File) {
val relativePath = file.toRelativeString(testDataDirectory)
checkResultByFile(relativePath)
}
}
object CompilerTestDirectives {
const val LANGUAGE_VERSION_DIRECTIVE = "LANGUAGE_VERSION:"
const val API_VERSION_DIRECTIVE = "API_VERSION:"
const val JVM_TARGET_DIRECTIVE = "JVM_TARGET:"
const val COMPILER_ARGUMENTS_DIRECTIVE = "COMPILER_ARGUMENTS:"
val ALL_COMPILER_TEST_DIRECTIVES = listOf(LANGUAGE_VERSION_DIRECTIVE, JVM_TARGET_DIRECTIVE, COMPILER_ARGUMENTS_DIRECTIVE)
}
fun <T> withCustomCompilerOptions(fileText: String, project: Project, module: Module, body: () -> T): T {
val removeFacet = !module.hasKotlinFacet()
val configured = configureCompilerOptions(fileText, project, module)
try {
return body()
} finally {
if (configured) {
rollbackCompilerOptions(project, module, removeFacet)
}
}
}
private fun configureCompilerOptions(fileText: String, project: Project, module: Module): Boolean {
val rawLanguageVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $LANGUAGE_VERSION_DIRECTIVE ")
val rawApiVersion = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $API_VERSION_DIRECTIVE ")
val jvmTarget = InTextDirectivesUtils.findStringWithPrefixes(fileText, "// $JVM_TARGET_DIRECTIVE ")
// We can have several such directives in quickFixMultiFile tests
// TODO: refactor such tests or add sophisticated check for the directive
val options = InTextDirectivesUtils.findListWithPrefixes(fileText, "// $COMPILER_ARGUMENTS_DIRECTIVE ").firstOrNull()
val languageVersion = rawLanguageVersion?.let { LanguageVersion.fromVersionString(rawLanguageVersion) }
val apiVersion = rawApiVersion?.let { ApiVersion.parse(rawApiVersion) }
if (languageVersion != null || apiVersion != null || jvmTarget != null || options != null) {
configureLanguageAndApiVersion(
project, module,
languageVersion ?: KotlinPluginLayout.instance.standaloneCompilerVersion.languageVersion,
apiVersion
)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
if (jvmTarget != null) {
val compilerArguments = facetSettings.compilerArguments
require(compilerArguments is K2JVMCompilerArguments) { "Attempt to specify `$JVM_TARGET_DIRECTIVE` for non-JVM test" }
compilerArguments.jvmTarget = jvmTarget
}
if (options != null) {
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = options
facetSettings.updateMergedArguments()
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = options }
}
return true
}
return false
}
fun configureRegistryAndRun(fileText: String, body: () -> Unit) {
val registers = InTextDirectivesUtils.findListWithPrefixes(fileText, "// REGISTRY:")
.map { it.split(' ') }
.map { Registry.get(it.first()) to it.last() }
try {
for ((register, value) in registers) {
register.setValue(value)
}
body()
} finally {
for ((register, _) in registers) {
register.resetToDefault()
}
}
}
fun configureCodeStyleAndRun(
project: Project,
configurator: (CodeStyleSettings) -> Unit = { },
body: () -> Unit
) {
val testSettings = CodeStyle.createTestSettings(CodeStyle.getSettings(project))
CodeStyle.doWithTemporarySettings(project, testSettings, Runnable {
configurator(testSettings)
body()
})
}
fun enableKotlinOfficialCodeStyle(project: Project) {
val settings = CodeStyleSettingsManager.getInstance(project).createTemporarySettings()
KotlinStyleGuideCodeStyle.apply(settings)
CodeStyle.setTemporarySettings(project, settings)
}
fun disableKotlinOfficialCodeStyle(project: Project) {
CodeStyle.dropTemporarySettings(project)
}
fun resetCodeStyle(project: Project) {
val provider = KotlinLanguageCodeStyleSettingsProvider()
CodeStyle.getSettings(project).apply {
removeCommonSettings(provider)
removeCustomSettings(provider)
clearCodeStyleSettings()
}
}
fun runAll(
vararg actions: ThrowableRunnable<Throwable>,
suppressedExceptions: List<Throwable> = emptyList()
) = RunAll(actions.toList()).run(suppressedExceptions)
private fun rollbackCompilerOptions(project: Project, module: Module, removeFacet: Boolean) {
KotlinCompilerSettings.getInstance(project).update { this.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS }
val bundledKotlinVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
KotlinCommonCompilerArgumentsHolder.getInstance(project).update {
this.languageVersion = bundledKotlinVersion.languageVersion.versionString
}
if (removeFacet) {
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
return
}
configureLanguageAndApiVersion(
project,
module,
bundledKotlinVersion.languageVersion,
bundledKotlinVersion.apiVersion
)
val facetSettings = KotlinFacet.get(module)!!.configuration.settings
(facetSettings.compilerArguments as? K2JVMCompilerArguments)?.jvmTarget = JvmTarget.DEFAULT.description
val compilerSettings = facetSettings.compilerSettings ?: CompilerSettings().also {
facetSettings.compilerSettings = it
}
compilerSettings.additionalArguments = DEFAULT_ADDITIONAL_ARGUMENTS
facetSettings.updateMergedArguments()
}
fun withCustomLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: LanguageVersion,
apiVersion: ApiVersion?,
body: () -> Unit
) {
val removeFacet = !module.hasKotlinFacet()
configureLanguageAndApiVersion(project, module, languageVersion, apiVersion)
try {
body()
} finally {
val bundledCompilerVersion = KotlinPluginLayout.instance.standaloneCompilerVersion
if (removeFacet) {
KotlinCommonCompilerArgumentsHolder.getInstance(project)
.update { this.languageVersion = bundledCompilerVersion.languageVersion.versionString }
module.removeKotlinFacet(ProjectDataManager.getInstance().createModifiableModelsProvider(project), commitModel = true)
} else {
configureLanguageAndApiVersion(
project,
module,
bundledCompilerVersion.languageVersion,
bundledCompilerVersion.apiVersion
)
}
}
}
private fun configureLanguageAndApiVersion(
project: Project,
module: Module,
languageVersion: LanguageVersion,
apiVersion: ApiVersion?
) {
WriteAction.run<Throwable> {
val modelsProvider = ProjectDataManager.getInstance().createModifiableModelsProvider(project)
val facet = module.getOrCreateFacet(modelsProvider, useProjectSettings = false)
val compilerArguments = facet.configuration.settings.compilerArguments
if (compilerArguments != null) {
compilerArguments.apiVersion = null
}
facet.configureFacet(IdeKotlinVersion.fromLanguageVersion(languageVersion), null, modelsProvider, emptySet())
if (apiVersion != null) {
facet.configuration.settings.apiLevel = LanguageVersion.fromVersionString(apiVersion.versionString)
}
KotlinCommonCompilerArgumentsHolder.getInstance(project).update { this.languageVersion = languageVersion.versionString }
modelsProvider.commit()
}
}
fun Project.allKotlinFiles(): List<KtFile> {
val virtualFiles = FileTypeIndex.getFiles(KotlinFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<KtFile>()
}
fun Project.allJavaFiles(): List<PsiJavaFile> {
val virtualFiles = FileTypeIndex.getFiles(JavaFileType.INSTANCE, ProjectScope.getProjectScope(this))
return virtualFiles
.map { PsiManager.getInstance(this).findFile(it) }
.filterIsInstance<PsiJavaFile>()
}
fun Project.findFileWithCaret(): PsiClassOwner {
return (allKotlinFiles() + allJavaFiles()).single {
"<caret>" in VfsUtilCore.loadText(it.virtualFile) && !it.virtualFile.name.endsWith(".after")
}
}
fun createTextEditorBasedDataContext(
project: Project,
editor: Editor,
caret: Caret,
additionalSteps: SimpleDataContext.Builder.() -> SimpleDataContext.Builder = { this },
): DataContext {
val textEditorPsiDataProvider = TextEditorPsiDataProvider()
val parentContext = DataContext { dataId -> textEditorPsiDataProvider.getData(dataId, editor, caret) }
return SimpleDataContext.builder()
.add(CommonDataKeys.PROJECT, project)
.add(CommonDataKeys.EDITOR, editor)
.additionalSteps()
.setParent(parentContext)
.build()
}
|
apache-2.0
|
c03a333e32e27a455519a7a236a1f526
| 41.835206 | 158 | 0.714086 | 5.600881 | false | true | false | false |
hughandrewarch/kotlin-koans
|
src/i_introduction/_4_Lambdas/n04Lambdas.kt
|
1
|
724
|
package i_introduction._4_Lambdas
import util.TODO
import util.doc4
fun example() {
val sum = { x: Int, y: Int -> x + y }
val square: (Int) -> Int = { x -> x * x }
sum(1, square(2)) == 5
}
fun todoTask4(collection: Collection<Int>): Nothing = TODO(
"""
Task 4.
Rewrite 'JavaCode4.task4()' in Kotlin using lambdas:
return true if the collection contains an even number.
You can find the appropriate function to call on 'Collection' by using code completion.
Don't use the class 'Iterables'.
""",
documentation = doc4(),
references = { JavaCode4().task4(collection) })
fun task4(collection: Collection<Int>): Boolean = collection.any { x -> x % 2 == 0}
|
mit
|
35604c236f5103e00e028ed09841c8fd
| 28 | 95 | 0.621547 | 3.731959 | false | false | false | false |
jwren/intellij-community
|
plugins/devkit/intellij.devkit.themes/src/actions/NewThemeAction.kt
|
1
|
6310
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.devkit.themes.actions
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.FileTemplateUtil
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.JBTextField
import com.intellij.ui.layout.*
import org.jetbrains.idea.devkit.actions.DevkitActionsUtil
import org.jetbrains.idea.devkit.inspections.quickfix.PluginDescriptorChooser
import org.jetbrains.idea.devkit.module.PluginModuleType
import org.jetbrains.idea.devkit.themes.DevKitThemesBundle
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.idea.devkit.util.PsiUtil
import java.util.*
import javax.swing.JComponent
//TODO better undo support
class NewThemeAction : AnAction(), UpdateInBackground {
private val THEME_JSON_TEMPLATE = "ThemeJson.json"
private val THEME_PROVIDER_EP_NAME = UIThemeProvider.EP_NAME.name
@Suppress("UsePropertyAccessSyntax") // IdeView#getOrChooseDirectory is not a getter
override fun actionPerformed(e: AnActionEvent) {
val view = e.getData(LangDataKeys.IDE_VIEW) ?: return
val dir = view.getOrChooseDirectory() ?: return
val module = e.getRequiredData(PlatformCoreDataKeys.MODULE)
val project = module.project
val dialog = NewThemeDialog(project)
dialog.show()
if (dialog.exitCode == DialogWrapper.OK_EXIT_CODE) {
val file = createThemeJson(dialog.name.text, dialog.isDark.isSelected, project, dir, module)
view.selectElement(file)
FileEditorManager.getInstance(project).openFile(file.virtualFile, true)
registerTheme(dir, file, module)
}
}
override fun update(e: AnActionEvent) {
val module = e.getData(PlatformCoreDataKeys.MODULE)
e.presentation.isEnabled = module != null && (PluginModuleType.get(module) is PluginModuleType || PsiUtil.isPluginModule(module))
}
@Suppress("HardCodedStringLiteral")
private fun createThemeJson(themeName: String,
isDark: Boolean,
project: Project,
dir: PsiDirectory,
module: Module): PsiFile {
val fileName = getThemeJsonFileName(themeName)
val colorSchemeFilename = getThemeColorSchemeFileName(themeName)
val template = FileTemplateManager.getInstance(project).getJ2eeTemplate(THEME_JSON_TEMPLATE)
val editorSchemeProps = Properties()
editorSchemeProps.setProperty("NAME", themeName)
editorSchemeProps.setProperty("PARENT_SCHEME", if (isDark) "Darcula" else "Default")
val editorSchemeTemplate = FileTemplateManager.getInstance(project).getJ2eeTemplate("ThemeEditorColorScheme.xml")
val colorScheme = FileTemplateUtil.createFromTemplate(editorSchemeTemplate, colorSchemeFilename, editorSchemeProps, dir)
val props = Properties()
props.setProperty("NAME", themeName)
props.setProperty("IS_DARK", isDark.toString())
props.setProperty("COLOR_SCHEME_NAME", getSourceRootRelativeLocation(module, colorScheme as PsiFile))
val created = FileTemplateUtil.createFromTemplate(template, fileName, props, dir)
assert(created is PsiFile)
return created as PsiFile
}
private fun getThemeJsonFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".theme.json"
}
private fun getThemeColorSchemeFileName(themeName: String): String {
return FileUtil.sanitizeFileName(themeName) + ".xml"
}
private fun registerTheme(dir: PsiDirectory, file: PsiFile, module: Module) {
val relativeLocation = getSourceRootRelativeLocation(module, file) ?: return
val pluginXml = DevkitActionsUtil.choosePluginModuleDescriptor(dir) ?: return
DescriptorUtil.checkPluginXmlsWritable(module.project, pluginXml)
val domFileElement = DescriptorUtil.getIdeaPluginFileElement(pluginXml)
WriteCommandAction.writeCommandAction(module.project, pluginXml).run<Throwable> {
val extensions = PluginDescriptorChooser.findOrCreateExtensionsForEP(domFileElement, THEME_PROVIDER_EP_NAME)
val extensionTag = extensions.addExtension(THEME_PROVIDER_EP_NAME).xmlTag
extensionTag.setAttribute("id", getRandomId())
extensionTag.setAttribute("path", relativeLocation)
}
}
private fun getSourceRootRelativeLocation(module: Module, file: PsiFile): String? {
val rootManager = ModuleRootManager.getInstance(module)
val sourceRoots = rootManager.getSourceRoots(false)
val virtualFile = file.virtualFile
var relativeLocation : String? = null
for (sourceRoot in sourceRoots) {
if (!VfsUtil.isAncestor(sourceRoot,virtualFile,true)) continue
relativeLocation = VfsUtil.getRelativeLocation(virtualFile, sourceRoot) ?: continue
break
}
return "/${relativeLocation}"
}
private fun getRandomId() = UUID.randomUUID().toString()
class NewThemeDialog(project: Project) : DialogWrapper(project) {
val name = JBTextField()
val isDark = CheckBox(DevKitThemesBundle.message("new.theme.dialog.is.dark.checkbox.text"), true)
init {
title = DevKitThemesBundle.message("new.theme.dialog.title")
init()
}
override fun createCenterPanel(): JComponent? {
return panel {
row(DevKitThemesBundle.message("new.theme.dialog.name.text.field.text")) {
cell {
name(growPolicy = GrowPolicy.MEDIUM_TEXT)
.focused()
//TODO max name length, maybe some other restrictions?
.withErrorOnApplyIf(DevKitThemesBundle.message("new.theme.dialog.name.empty")) { it.text.isBlank() }
}
}
row("") {
cell { isDark() }
}
}
}
}
}
|
apache-2.0
|
7e84a1071ba549210274060abaed35df
| 41.355705 | 133 | 0.744057 | 4.6261 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/base/plugin/src/org/jetbrains/kotlin/idea/compiler/configuration/LazyKotlinJpsPluginClasspathDownloader.kt
|
7
|
2687
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.compiler.configuration
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.plugin.KotlinBasePluginBundle
import org.jetbrains.kotlin.idea.base.plugin.artifacts.KotlinArtifactConstants
import org.jetbrains.kotlin.idea.base.plugin.artifacts.LazyFileOutputProducer
import org.jetbrains.kotlin.idea.compiler.configuration.LazyKotlinMavenArtifactDownloader.DownloadContext
import java.io.File
private val VERSION_UNTIL_OLD_FAT_JAR_IS_AVAILABLE = IdeKotlinVersion.get("1.7.20")
class LazyKotlinJpsPluginClasspathDownloader(private val version: String) :
LazyFileOutputProducer<Unit, LazyKotlinJpsPluginClasspathDownloader.Context> {
private val newDownloader = LazyKotlinMavenArtifactDownloader(KotlinArtifactConstants.KOTLIN_JPS_PLUGIN_PLUGIN_ARTIFACT_ID, version)
private val oldDownloader =
if (IdeKotlinVersion.get(version) < VERSION_UNTIL_OLD_FAT_JAR_IS_AVAILABLE) {
@Suppress("DEPRECATION")
LazyKotlinMavenArtifactDownloader(KotlinArtifactConstants.OLD_FAT_JAR_KOTLIN_JPS_PLUGIN_CLASSPATH_ARTIFACT_ID, version)
} else {
null
}
override fun isUpToDate(input: Unit) =
if (IdeKotlinVersion.get(version).isStandaloneCompilerVersion) true
else newDownloader.isUpToDate() || oldDownloader?.isUpToDate() == true
override fun lazyProduceOutput(input: Unit, computationContext: Context): List<File> {
getDownloadedIfUpToDateOrEmpty().takeIf { it.isNotEmpty() }?.let { return it }
val downloadContext = DownloadContext(
computationContext.project,
computationContext.indicator,
KotlinBasePluginBundle.message("progress.text.downloading.kotlin.jps.plugin")
)
return newDownloader.lazyDownload(downloadContext).takeIf { it.isNotEmpty() }
?: oldDownloader?.lazyDownload(downloadContext)
?: emptyList()
}
fun getDownloadedIfUpToDateOrEmpty() =
if (IdeKotlinVersion.get(version).isStandaloneCompilerVersion) {
KotlinPluginLayout.jpsPluginClasspath
} else {
newDownloader.getDownloadedIfUpToDateOrEmpty().takeIf { it.isNotEmpty() }
?: oldDownloader?.getDownloadedIfUpToDateOrEmpty()
?: emptyList()
}
fun lazyDownload(computationContext: Context) = lazyProduceOutput(Unit, computationContext)
data class Context(val project: Project, val indicator: ProgressIndicator)
}
|
apache-2.0
|
6908ee1220f8261d24812ea7ec7f614a
| 47.854545 | 136 | 0.742836 | 4.858951 | false | false | false | false |
androidx/androidx
|
credentials/credentials-play-services-auth/src/main/java/androidx/credentials/playservices/controllers/CreatePassword/CredentialProviderCreatePasswordController.kt
|
3
|
8391
|
/*
* 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.credentials.playservices.controllers.CreatePassword
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.os.Build
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.credentials.CreateCredentialResponse
import androidx.credentials.CreatePasswordRequest
import androidx.credentials.CreatePasswordResponse
import androidx.credentials.CredentialManagerCallback
import androidx.credentials.exceptions.CreateCredentialCancellationException
import androidx.credentials.exceptions.CreateCredentialException
import androidx.credentials.exceptions.CreateCredentialInterruptedException
import androidx.credentials.exceptions.CreateCredentialUnknownException
import androidx.credentials.playservices.controllers.CredentialProviderController
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SavePasswordRequest
import com.google.android.gms.auth.api.identity.SavePasswordResult
import com.google.android.gms.auth.api.identity.SignInPassword
import com.google.android.gms.common.api.ApiException
import java.util.concurrent.Executor
/**
* A controller to handle the CreatePassword flow with play services.
*
* @hide
*/
@Suppress("deprecation")
class CredentialProviderCreatePasswordController : CredentialProviderController<
CreatePasswordRequest,
SavePasswordRequest,
Unit,
CreateCredentialResponse,
CreateCredentialException>() {
/**
* The callback object state, used in the protected handleResponse method.
*/
private lateinit var callback: CredentialManagerCallback<CreateCredentialResponse,
CreateCredentialException>
/**
* The callback requires an executor to invoke it.
*/
private lateinit var executor: Executor
@SuppressLint("ClassVerificationFailure")
override fun invokePlayServices(
request: CreatePasswordRequest,
callback: CredentialManagerCallback<CreateCredentialResponse, CreateCredentialException>,
executor: Executor
) {
this.callback = callback
this.executor = executor
val convertedRequest: SavePasswordRequest = this.convertRequestToPlayServices(request)
Identity.getCredentialSavingClient(activity)
.savePassword(convertedRequest)
.addOnSuccessListener { result: SavePasswordResult ->
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
startIntentSenderForResult(
result.pendingIntent.intentSender,
REQUEST_CODE_GIS_SAVE_PASSWORD,
null, /* fillInIntent= */
0, /* flagsMask= */
0, /* flagsValue= */
0, /* extraFlags= */
null /* options= */
)
}
} catch (e: IntentSender.SendIntentException) {
Log.i(
TAG, "Failed to send pending intent for savePassword" +
" : " + e.message
)
val exception: CreateCredentialException = CreateCredentialUnknownException()
executor.execute { ->
callback.onError(
exception
)
}
}
}
.addOnFailureListener { e: Exception ->
Log.i(TAG, "CreatePassword failed with : " + e.message)
var exception: CreateCredentialException = CreateCredentialUnknownException()
if (e is ApiException && e.statusCode in this.retryables) {
exception = CreateCredentialInterruptedException()
}
executor.execute { ->
callback.onError(
exception
)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
handleResponse(requestCode, resultCode, data)
}
private fun handleResponse(uniqueRequestCode: Int, resultCode: Int, data: Intent?) {
Log.i(TAG, "$data - the intent back - is un-used.")
if (uniqueRequestCode != REQUEST_CODE_GIS_SAVE_PASSWORD) {
return
}
if (resultCode != Activity.RESULT_OK) {
var exception: CreateCredentialException = CreateCredentialUnknownException()
if (resultCode == Activity.RESULT_CANCELED) {
exception = CreateCredentialCancellationException()
}
this.executor.execute { -> this.callback.onError(exception) }
return
}
Log.i(TAG, "Saving password succeeded")
val response: CreateCredentialResponse = convertResponseToCredentialManager(Unit)
this.executor.execute { -> this.callback.onResult(response) }
}
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
public override fun convertRequestToPlayServices(request: CreatePasswordRequest):
SavePasswordRequest {
return SavePasswordRequest.builder().setSignInPassword(
SignInPassword(request.id, request.password)
).build()
}
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
public override fun convertResponseToCredentialManager(response: Unit):
CreateCredentialResponse {
return CreatePasswordResponse()
}
companion object {
private val TAG = CredentialProviderCreatePasswordController::class.java.name
private const val REQUEST_CODE_GIS_SAVE_PASSWORD: Int = 1
// TODO("Ensure this works with the lifecycle")
/**
* This finds a past version of the
* [CredentialProviderCreatePasswordController] if it exists, otherwise
* it generates a new instance.
*
* @param fragmentManager a fragment manager pulled from an android activity
* @return a credential provider controller for CreatePublicKeyCredential
*/
@JvmStatic
fun getInstance(fragmentManager: android.app.FragmentManager):
CredentialProviderCreatePasswordController {
var controller = findPastController(REQUEST_CODE_GIS_SAVE_PASSWORD, fragmentManager)
if (controller == null) {
controller = CredentialProviderCreatePasswordController()
fragmentManager.beginTransaction().add(controller,
REQUEST_CODE_GIS_SAVE_PASSWORD.toString())
.commitAllowingStateLoss()
fragmentManager.executePendingTransactions()
}
return controller
}
internal fun findPastController(
requestCode: Int,
fragmentManager: android.app.FragmentManager
): CredentialProviderCreatePasswordController? {
val oldFragment = fragmentManager.findFragmentByTag(requestCode.toString())
try {
return oldFragment as CredentialProviderCreatePasswordController
} catch (e: Exception) {
Log.i(TAG, "Error with old fragment or null - replacement required")
if (oldFragment != null) {
fragmentManager.beginTransaction().remove(oldFragment).commitAllowingStateLoss()
}
// TODO("Ensure this is well tested for fragment issues")
return null
}
}
}
}
|
apache-2.0
|
d6217dee65bffaf43c47afb5bd2e676d
| 41.811224 | 100 | 0.649267 | 5.597732 | false | false | false | false |
nimakro/tornadofx
|
src/test/kotlin/tornadofx/testapps/ImportStyles.kt
|
3
|
929
|
package tornadofx.testapps
import javafx.scene.paint.Color
import javafx.scene.text.FontWeight
import tornadofx.*
/**
* @author I58695 (2016-08-18)
*/
class ImportStyles : App(MainView::class, Styles::class) {
init {
dumpStylesheets()
}
class MainView : View() {
override val root = vbox {
addClass(box)
label("Test").addClass(test)
}
}
companion object {
val box by cssclass()
val test by cssclass()
}
class Styles : Stylesheet(ParentStyles::class) {
init {
test {
fontSize = 36.px
fontWeight = FontWeight.BOLD
textFill = Color.WHITE
}
}
}
class ParentStyles : Stylesheet() {
init {
box {
backgroundColor += Color.GRAY
padding = box(10.px, 100.px)
}
}
}
}
|
apache-2.0
|
019c15fded0af21cfe2e695d79b4e3dd
| 19.644444 | 58 | 0.50915 | 4.509709 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/top-mpp/src/linuxMain/kotlin/transitiveStory/bottomActual/mppBeginning/BottomActualDeclarations.kt
|
8
|
830
|
package transitiveStory.bottomActual.mppBeginning
actual open class <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>BottomActualDeclarations<!> {
actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>simpleVal<!>: Int = commonInt
actual companion object <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>Compainon<!> {
actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>inTheCompanionOfBottomActualDeclarations<!>: String =
"I'm a string from the companion object of `$this` in `$sourceSetName` module `$moduleName`"
}
}
actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>sourceSetName<!>: String = "linuxMain"
|
apache-2.0
|
88c5a1cf48fad0526988dbda62c95f1d
| 68.166667 | 153 | 0.73494 | 4.129353 | false | false | false | false |
idea4bsd/idea4bsd
|
platform/script-debugger/protocol/protocol-reader/src/Util.kt
|
19
|
1282
|
package org.jetbrains.protocolReader
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
val TYPE_FACTORY_NAME_PREFIX = 'F'
val READER_NAME = "reader"
val PENDING_INPUT_READER_NAME = "inputReader"
val JSON_READER_CLASS_NAME = "JsonReaderEx"
val JSON_READER_PARAMETER_DEF = "$READER_NAME: $JSON_READER_CLASS_NAME"
/**
* Generate Java type name of the passed type. Type may be parameterized.
*/
internal fun writeJavaTypeName(arg: Type, out: TextOutput) {
if (arg is Class<*>) {
val name = arg.canonicalName
out.append(
if (name == "java.util.List") "List"
else if (name == "java.lang.String") "String?"
else name
)
}
else if (arg is ParameterizedType) {
writeJavaTypeName(arg.rawType, out)
out.append('<')
val params = arg.actualTypeArguments
for (i in params.indices) {
if (i != 0) {
out.comma()
}
writeJavaTypeName(params[i], out)
}
out.append('>')
}
else if (arg is WildcardType) {
val upperBounds = arg.upperBounds!!
if (upperBounds.size != 1) {
throw RuntimeException()
}
out.append("? extends ")
writeJavaTypeName(upperBounds.first(), out)
}
else {
out.append(arg.toString())
}
}
|
apache-2.0
|
338bd5b0dcba0f86ed5c484e34f1ae4a
| 24.66 | 73 | 0.652886 | 3.748538 | false | false | false | false |
Iktwo/QuteLauncher
|
src/android/src/com/iktwo/qutelauncher/PackageChangedReceiver.kt
|
1
|
1237
|
package com.iktwo.qutelauncher
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class PackageChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val packageName = intent.data!!.schemeSpecificPart
if (packageName == null || packageName.isEmpty()) {
return
}
val action = intent.action
if (action == "android.intent.action.PACKAGE_ADDED") {
if (QuteLauncher.isApplaunchable(packageName))
jpackageAdded(QuteLauncher.getApplicationLabel(packageName), packageName, internalQtObject)
} else if (action == "android.intent.action.PACKAGE_REMOVED") {
jpackageRemoved(packageName, internalQtObject)
}
}
companion object {
@JvmStatic
var internalQtObject: Long = 0
@JvmStatic
fun setQtObject(qtObject2: Long) {
internalQtObject = qtObject2
}
@JvmStatic
private external fun jpackageAdded(label: String, packageName: String, qtObject: Long)
@JvmStatic
private external fun jpackageRemoved(packageName: String, qtObject: Long)
}
}
|
gpl-3.0
|
ee99d26d9ac81f0a521625961ce36126
| 28.452381 | 107 | 0.662086 | 4.667925 | false | false | false | false |
vovagrechka/fucking-everything
|
alraune/alraune/src/main/java/alraune/local-debug-rps.kt
|
1
|
2806
|
package alraune
import alraune.operations.*
import bolone.rp.GenericCoolRPResult
import bolone.rp.handleEarlyRPExit
import pieces100.*
import vgrechka.*
import java.awt.event.KeyEvent
import java.io.File
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor
val localDebugRPs = object : RPBunch(procNamePrefix = "localDebug.", rpClassPrefix = "LocalDebugRP_") {
init {
localDebug(LocalDebugRP_OpenDiffTool::class, GenericCoolRPResult::class)
localDebug(LocalDebugRP_RobotTypeText::class, GenericCoolRPResult::class)
localDebug(LocalDebugRP_RobotKey::class, GenericCoolRPResult::class)
localDebug(LocalDebugRP_RobotClick::class, GenericCoolRPResult::class)
localDebug(LocalDebugRP_RobotMoveMouse::class, GenericCoolRPResult::class)
}
override fun checkSite() {}
}
class LocalDebugRP_OpenDiffTool(val p: Params): Dancer<GenericCoolRPResult> {
class Params {
var name1 by once<String>()
var content1 by once<String>()
var name2 by once<String>()
var content2 by once<String>()
}
override fun dance(): GenericCoolRPResult {
val file1 = File.createTempFile("${p.name1}--", null)
val file2 = File.createTempFile("${p.name2}--", null)
file1.writeText(p.content1)
file2.writeText(p.content2)
runLocalMergeTool_noBlock(file1.path, file2.path)
return GenericCoolRPResult()
}
}
class LocalDebugRP_RobotTypeText(val p: Params): Dancer<GenericCoolRPResult> {
class Params {
var text by place<String>()
}
override fun dance(): GenericCoolRPResult {
RobotPile.typeText(p.text)
return GenericCoolRPResult()
}
}
class LocalDebugRP_RobotKey(val p: Params): Dancer<GenericCoolRPResult> {
class Params {
var key by place<String>()
}
override fun dance(): GenericCoolRPResult {
val key = KeyEvent::class.java.getField(p.key).getInt(null)
RobotPile.robot.keyPress(key)
RobotPile.robot.keyRelease(key)
return GenericCoolRPResult()
}
}
class LocalDebugRP_RobotClick(val p: Params): Dancer<GenericCoolRPResult> {
class Params {
var x by place<Int>()
var y by place<Int>()
var delayAfterMoveBeforeClick: Int? = null
}
override fun dance(): GenericCoolRPResult {
RobotPile.click(p.x, p.y, delayAfterMoveBeforeClick = (p.delayAfterMoveBeforeClick ?: 0).toLong())
return GenericCoolRPResult()
}
}
class LocalDebugRP_RobotMoveMouse(val p: Params): Dancer<GenericCoolRPResult> {
class Params {
var x by place<Int>()
var y by place<Int>()
}
override fun dance(): GenericCoolRPResult {
RobotPile.robot.mouseMove(p.x, p.y)
return GenericCoolRPResult()
}
}
|
apache-2.0
|
6548ad95e28d409dfd32e0baeb31ef75
| 29.5 | 106 | 0.684961 | 3.756359 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
|
1
|
62087
|
// 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.createFromUsage.callableBuilder
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.codeInsight.template.*
import com.intellij.codeInsight.template.impl.TemplateImpl
import com.intellij.codeInsight.template.impl.TemplateManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ScrollType
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.UnfairTextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor
import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode
import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.DialogWithEditor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl
import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeProjectionImpl
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
import kotlin.math.max
/**
* Represents a single choice for a type (e.g. parameter type or return type).
*/
class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) {
val typeParameters: Array<TypeParameterDescriptor>
var renderedTypes: List<String> = emptyList()
private set
var renderedTypeParameters: List<RenderedTypeParameter>? = null
private set
fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) {
renderedTypes = theType.renderShort(typeParameterNameMap)
renderedTypeParameters = typeParameters.map {
RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap.getValue(it))
}
}
init {
val typeParametersInType = theType.getTypeParameters()
if (scope == null) {
typeParameters = typeParametersInType.toTypedArray()
renderedTypes = theType.renderShort(Collections.emptyMap())
} else {
typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray()
}
}
override fun toString() = theType.toString()
}
data class RenderedTypeParameter(
val typeParameter: TypeParameterDescriptor,
val fake: Boolean,
val text: String
)
fun List<TypeCandidate>.getTypeByRenderedType(renderedTypes: List<String>): KotlinType? =
firstOrNull { it.renderedTypes == renderedTypes }?.theType
class CallableBuilderConfiguration(
val callableInfos: List<CallableInfo>,
val originalElement: KtElement,
val currentFile: KtFile = originalElement.containingKtFile,
val currentEditor: Editor? = null,
val isExtension: Boolean = false,
val enableSubstitutions: Boolean = true
)
sealed class CallablePlacement {
class WithReceiver(val receiverTypeCandidate: TypeCandidate) : CallablePlacement()
class NoReceiver(val containingElement: PsiElement) : CallablePlacement()
}
class CallableBuilder(val config: CallableBuilderConfiguration) {
private var finished: Boolean = false
val currentFileContext = config.currentFile.analyzeWithContent()
private lateinit var _currentFileModule: ModuleDescriptor
val currentFileModule: ModuleDescriptor
get() {
if (!_currentFileModule.isValid) {
updateCurrentModule()
}
return _currentFileModule
}
init {
updateCurrentModule()
}
val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) }
private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>()
var placement: CallablePlacement? = null
private val elementsToShorten = ArrayList<KtElement>()
private fun updateCurrentModule() {
_currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor
}
fun computeTypeCandidates(typeInfo: TypeInfo): List<TypeCandidate> =
typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } }
private fun computeTypeCandidates(
typeInfo: TypeInfo,
substitutions: List<KotlinTypeSubstitution>,
scope: HierarchicalScope
): List<TypeCandidate> {
if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo)
return typeCandidates.getOrPut(typeInfo) {
val types = typeInfo.getPossibleTypes(this).asReversed()
// We have to use semantic equality here
data class EqWrapper(val _type: KotlinType) {
override fun equals(other: Any?) = this === other
|| other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type)
override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals()
}
val newTypes = LinkedHashSet(types.map(::EqWrapper))
for (substitution in substitutions) {
// each substitution can be applied or not, so we offer all options
val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) }
// substitution.byType are type arguments, but they cannot already occur in the type before substitution
val toRemove = newTypes.filter { substitution.byType in it._type }
newTypes.addAll(toAdd.map(::EqWrapper))
newTypes.removeAll(toRemove)
}
if (newTypes.isEmpty()) {
newTypes.add(EqWrapper(currentFileModule.builtIns.anyType))
}
newTypes.map { TypeCandidate(it._type, scope) }.asReversed()
}
}
private fun buildNext(iterator: Iterator<CallableInfo>) {
if (iterator.hasNext()) {
val context = Context(iterator.next())
runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } }
ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() }
} else {
runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) }
}
}
fun build(onFinish: () -> Unit = {}) {
try {
assert(config.currentEditor != null) { "Can't run build() without editor" }
check(!finished) { "Current builder has already finished" }
buildNext(config.callableInfos.iterator())
} finally {
finished = true
onFinish()
}
}
private inner class Context(val callableInfo: CallableInfo) {
val skipReturnType: Boolean
val ktFileToEdit: KtFile
val containingFileEditor: Editor
val containingElement: PsiElement
val dialogWithEditor: DialogWithEditor?
val receiverClassDescriptor: ClassifierDescriptor?
val typeParameterNameMap: Map<TypeParameterDescriptor, String>
val receiverTypeCandidate: TypeCandidate?
val mandatoryTypeParametersAsCandidates: List<TypeCandidate>
val substitutions: List<KotlinTypeSubstitution>
var finished: Boolean = false
init {
// gather relevant information
val placement = placement
var nullableReceiver = false
when (placement) {
is CallablePlacement.NoReceiver -> {
containingElement = placement.containingElement
receiverClassDescriptor = with(placement.containingElement) {
when (this) {
is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this]
is PsiClass -> getJavaClassDescriptor()
else -> null
}
}
}
is CallablePlacement.WithReceiver -> {
val theType = placement.receiverTypeCandidate.theType
nullableReceiver = theType.isMarkedNullable
receiverClassDescriptor = theType.constructor.declarationDescriptor
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
}
else -> throw IllegalArgumentException("Placement wan't initialized")
}
val receiverType = receiverClassDescriptor?.defaultType?.let {
if (nullableReceiver) it.makeNullable() else it
}
val project = config.currentFile.project
if (containingElement.containingFile != config.currentFile) {
NavigationUtil.activateFileWithPsiElement(containingElement)
}
dialogWithEditor = if (containingElement is KtElement) {
ktFileToEdit = containingElement.containingKtFile
containingFileEditor = if (ktFileToEdit != config.currentFile) {
FileEditorManager.getInstance(project).selectedTextEditor!!
} else {
config.currentEditor!!
}
null
} else {
val dialog = object : DialogWithEditor(project, KotlinBundle.message("fix.create.from.usage.dialog.title"), "") {
override fun doOKAction() {
project.executeWriteCommand(KotlinBundle.message("premature.end.of.template")) {
TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false)
}
super.doOKAction()
}
}
containingFileEditor = dialog.editor
with(containingFileEditor.settings) {
additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project)
additionalLinesCount = 5
}
ktFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile
ktFileToEdit.analysisContext = config.currentFile
dialog
}
val scope = getDeclarationScope()
receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) }
val fakeFunction: FunctionDescriptor?
// figure out type substitutions for type parameters
val substitutionMap = LinkedHashMap<KotlinType, KotlinType>()
if (config.enableSubstitutions) {
collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap)
val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos
.map {
val typeCandidates = computeTypeCandidates(it)
assert(typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" }
typeCandidates.first().theType
}
.subtract(substitutionMap.keys)
fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size)
collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap)
mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map {
TypeCandidate(substitutionMap[it]!!, scope)
}
} else {
fakeFunction = null
mandatoryTypeParametersAsCandidates = Collections.emptyList()
}
substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) }
callableInfo.parameterInfos.forEach {
computeTypeCandidates(it.typeInfo, substitutions, scope)
}
val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull()
skipReturnType = when (callableInfo.kind) {
CallableKind.FUNCTION ->
returnTypeCandidate?.theType?.isUnit() ?: false
CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR ->
callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false
CallableKind.CONSTRUCTOR -> true
CallableKind.PROPERTY -> containingElement is KtBlockExpression
}
// figure out type parameter renames to avoid conflicts
typeParameterNameMap = getTypeParameterRenames(scope)
callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) }
if (!skipReturnType) {
renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction)
}
receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction)
mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) }
}
private fun getDeclarationScope(): HierarchicalScope {
if (config.isExtension || receiverClassDescriptor == null) {
return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope()
}
if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) {
return receiverClassDescriptor.scopeForMemberDeclarationResolution
}
assert(receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" }
val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters)
.map { TypeProjectionImpl(it.defaultType) }
val memberScope = receiverClassDescriptor.getMemberScope(projections)
return LexicalScopeImpl(
memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, emptyList(),
LexicalScopeKind.SYNTHETIC
) {
receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) }
}
}
private fun collectSubstitutionsForReceiverTypeParameters(
receiverType: KotlinType?,
result: MutableMap<KotlinType, KotlinType>
) {
if (placement is CallablePlacement.NoReceiver) return
val classTypeParameters = receiverType?.arguments ?: Collections.emptyList()
val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments
?: Collections.emptyList()
assert(ownerTypeArguments.size == classTypeParameters.size)
ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type }
}
private fun collectSubstitutionsForCallableTypeParameters(
fakeFunction: FunctionDescriptor,
typeArguments: Set<KotlinType>,
result: MutableMap<KotlinType, KotlinType>
) {
for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) {
result[typeArgument] = typeParameter.defaultType
}
}
@OptIn(FrontendInternals::class)
private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor {
val fakeFunction = SimpleFunctionDescriptorImpl.create(
MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")),
Annotations.EMPTY,
Name.identifier("fake"),
CallableMemberDescriptor.Kind.SYNTHESIZED,
SourceElement.NO_SOURCE
)
val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null }
val parameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator)
val typeParameters = (0 until typeParameterCount).map {
TypeParameterDescriptorImpl.createWithDefaultBound(
fakeFunction,
Annotations.EMPTY,
false,
Variance.INVARIANT,
Name.identifier(parameterNames[it]),
it,
ktFileToEdit.getResolutionFacade().frontendService()
)
}
return fakeFunction.initialize(
null, null, emptyList(), typeParameters, Collections.emptyList(), null,
null, DescriptorVisibilities.INTERNAL
)
}
private fun renderTypeCandidates(
typeInfo: TypeInfo,
typeParameterNameMap: Map<TypeParameterDescriptor, String>,
fakeFunction: FunctionDescriptor?
) {
typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) }
}
private fun isInsideInnerOrLocalClass(): Boolean {
val classOrObject = containingElement.getNonStrictParentOfType<KtClassOrObject>()
return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal)
}
private fun createDeclarationSkeleton(): KtNamedDeclaration {
with(config) {
val assignmentToReplace =
if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable == true) {
originalElement as KtBinaryExpression
} else null
val pointerOfAssignmentToReplace = assignmentToReplace?.createSmartPointer()
val ownerTypeString = if (isExtension) {
val renderedType = receiverTypeCandidate!!.renderedTypes.first()
val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor
if (isFunctionType) "($renderedType)." else "$renderedType."
} else ""
val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind
fun renderParamList(): String {
val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else ""
val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" }
return if (callableInfo.parameterInfos.isNotEmpty()
|| callableInfo.kind == CallableKind.FUNCTION
|| callableInfo.kind == CallableKind.CONSTRUCTOR
) "($list)" else list
}
val paramList = when (callableInfo.kind) {
CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR ->
renderParamList()
CallableKind.PROPERTY -> ""
}
val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any"
val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString"
val psiFactory = KtPsiFactory(currentFile)
val modifiers = buildString {
val modifierList = callableInfo.modifierList?.copied() ?: psiFactory.createEmptyModifierList()
val visibilityKeyword = modifierList.visibilityModifierType()
if (visibilityKeyword == null) {
val defaultVisibility =
if (callableInfo.isAbstract) ""
else if (containingElement is KtClassOrObject
&& !(containingElement is KtClass && containingElement.isInterface())
&& containingElement.isAncestor(config.originalElement)
&& callableInfo.kind != CallableKind.CONSTRUCTOR
) "private "
else if (isExtension) "private "
else ""
append(defaultVisibility)
}
// TODO: Get rid of isAbstract
if (callableInfo.isAbstract
&& containingElement is KtClass
&& !containingElement.isInterface()
&& !modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD)
) {
modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD)
}
val text = modifierList.normalize().text
if (text.isNotEmpty()) {
append("$text ")
}
}
val isExpectClassMember by lazy {
containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false
}
val declaration: KtNamedDeclaration = when (callableInfo.kind) {
CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> {
val body = when {
callableInfo is ConstructorInfo -> if (callableInfo.withBody) "{\n\n}" else ""
callableInfo.isAbstract -> ""
containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> ""
containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> ""
containingElement is KtObjectDeclaration && containingElement.isCompanion()
&& containingElement.parent.parent is KtClass
&& (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> ""
isExpectClassMember -> ""
else -> "{\n\n}"
}
@Suppress("USELESS_CAST") // KT-10755
when {
callableInfo is FunctionInfo -> psiFactory.createFunction("${modifiers}fun<> $header $body") as KtNamedDeclaration
(callableInfo as ConstructorInfo).isPrimary -> {
val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList
psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration
}
else -> psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration
}
}
CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> {
val classWithPrimaryConstructorInfo = callableInfo as ClassWithPrimaryConstructorInfo
with(classWithPrimaryConstructorInfo.classInfo) {
val classBody = when (kind) {
ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> ""
else -> "{\n\n}"
}
val safeName = name.quoteIfNeeded()
when (kind) {
ClassKind.ENUM_ENTRY -> {
val targetParent = applicableParents.singleOrNull()
if (!(targetParent is KtClass && targetParent.isEnum())) {
throw KotlinExceptionWithAttachments("Enum class expected: ${targetParent?.let { it::class.java }}")
.withPsiAttachment("targetParent", targetParent)
}
val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty()
psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}")
}
else -> {
val openMod = if (open && kind != ClassKind.INTERFACE) "open " else ""
val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else ""
val typeParamList = when (kind) {
ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>"
else -> ""
}
val ctor =
classWithPrimaryConstructorInfo.primaryConstructorVisibility?.name?.let { " $it constructor" } ?: ""
psiFactory.createDeclaration<KtClassOrObject>(
"$openMod$innerMod${kind.keyword} $safeName$typeParamList$ctor$paramList$returnTypeString $classBody"
)
}
}
}
}
CallableKind.PROPERTY -> {
val isVar = (callableInfo as PropertyInfo).writable
val const = if (callableInfo.isConst) "const " else ""
val valVar = if (isVar) "var" else "val"
val accessors = if (isExtension && !isExpectClassMember) {
buildString {
append("\nget() {}")
if (isVar) {
append("\nset() {}")
}
}
} else ""
psiFactory.createProperty("$modifiers$const$valVar<> $header$accessors")
}
}
if (callableInfo is PropertyInfo) {
callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) }
}
val newInitializer = pointerOfAssignmentToReplace?.element
if (newInitializer != null) {
(declaration as KtProperty).initializer = newInitializer.right
return newInitializer.replace(declaration) as KtCallableDeclaration
}
val container = if (containingElement is KtClass && callableInfo.isForCompanion) {
containingElement.getOrCreateCompanionObject()
} else containingElement
val declarationInPlace = placeDeclarationInContainer(declaration, container, config.originalElement, ktFileToEdit)
if (declarationInPlace is KtSecondaryConstructor) {
val containingClass = declarationInPlace.containingClassOrObject!!
val primaryConstructorParameters = containingClass.primaryConstructorParameters
if (primaryConstructorParameters.isNotEmpty()) {
declarationInPlace.replaceImplicitDelegationCallWithExplicit(true)
} else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors
.all { it.valueParameters.isNotEmpty() }
) {
declarationInPlace.replaceImplicitDelegationCallWithExplicit(false)
}
if (declarationInPlace.valueParameters.size > primaryConstructorParameters.size) {
val hasCompatibleTypes = primaryConstructorParameters.zip(callableInfo.parameterInfos).all { (primary, secondary) ->
val primaryType = currentFileContext[BindingContext.TYPE, primary.typeReference] ?: return@all false
val secondaryType = computeTypeCandidates(secondary.typeInfo).firstOrNull()?.theType ?: return@all false
secondaryType.isSubtypeOf(primaryType)
}
if (hasCompatibleTypes) {
val delegationCallArgumentList = declarationInPlace.getDelegationCall().valueArgumentList
primaryConstructorParameters.forEach {
val name = it.name
if (name != null) delegationCallArgumentList?.addArgument(psiFactory.createArgument(name))
}
}
}
}
return declarationInPlace
}
}
private fun getTypeParameterRenames(scope: HierarchicalScope): Map<TypeParameterDescriptor, String> {
val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>()
mandatoryTypeParametersAsCandidates.asSequence()
.plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() })
.flatMap { it.typeParameters.asSequence() }
.toCollection(allTypeParametersNotInScope)
if (!skipReturnType) {
computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) {
it.typeParameters.asSequence()
}
}
val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null }
val typeParameterNames = allTypeParametersNotInScope.map {
KotlinNameSuggester.suggestNameByName(it.name.asString(), validator)
}
return allTypeParametersNotInScope.zip(typeParameterNames).toMap()
}
private fun setupTypeReferencesForShortening(
declaration: KtNamedDeclaration,
parameterTypeExpressions: List<TypeExpression>
) {
if (config.isExtension) {
val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first()
val replacingTypeRef = KtPsiFactory(declaration).createType(receiverTypeText)
(declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!!
}
val returnTypeRefs = declaration.getReturnTypeReferences()
if (returnTypeRefs.isNotEmpty()) {
val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType(
returnTypeRefs.map { it.text }
)
if (returnType != null) {
// user selected a given type
replaceWithLongerName(returnTypeRefs, returnType)
}
}
val valueParameters = declaration.getValueParameters()
val parameterIndicesToShorten = ArrayList<Int>()
assert(valueParameters.size == parameterTypeExpressions.size)
for ((i, parameter) in valueParameters.asSequence().withIndex()) {
val parameterTypeRef = parameter.typeReference
if (parameterTypeRef != null) {
val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType(
listOf(parameterTypeRef.text)
)
if (parameterType != null) {
replaceWithLongerName(listOf(parameterTypeRef), parameterType)
parameterIndicesToShorten.add(i)
}
}
}
}
private fun postprocessDeclaration(declaration: KtNamedDeclaration) {
if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) {
if (declaration.containingClassOrObject == null) return
val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return
val returnType = propertyDescriptor.returnType ?: return
if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return
declaration.addModifier(KtTokens.LATEINIT_KEYWORD)
}
if (callableInfo.isAbstract) {
val containingClass = declaration.containingClassOrObject
if (containingClass is KtClass && containingClass.isInterface()) {
declaration.removeModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
}
private fun setupDeclarationBody(func: KtDeclarationWithBody) {
if (func !is KtNamedFunction && func !is KtPropertyAccessor) return
if (skipReturnType && callableInfo is FunctionInfo && callableInfo.preferEmptyBody) return
val oldBody = func.bodyExpression ?: return
val bodyText = getFunctionBodyTextFromTemplate(
func.project,
TemplateKind.FUNCTION,
if (callableInfo.name.isNotEmpty()) callableInfo.name else null,
if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "",
receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) }
)
oldBody.replace(KtPsiFactory(func).createBlock(bodyText))
}
private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) {
val oldTypeArgumentList = callElement.typeArgumentList ?: return
val renderedTypeArgs = typeParameters.map { typeParameter ->
val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType
IdeDescriptorRenderers.SOURCE_CODE.renderType(type)
}
if (renderedTypeArgs.isEmpty()) {
oldTypeArgumentList.delete()
} else {
oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">")))
elementsToShorten.add(callElement.typeArgumentList!!)
}
}
private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? {
val candidates = typeCandidates[callableInfo.returnTypeInfo]!!
if (candidates.isEmpty()) return null
val elementToReplace: KtElement?
val expression: TypeExpression = when (declaration) {
is KtCallableDeclaration -> {
elementToReplace = declaration.typeReference
TypeExpression.ForTypeReference(candidates)
}
is KtClassOrObject -> {
elementToReplace = declaration.superTypeListEntries.firstOrNull()
TypeExpression.ForDelegationSpecifier(candidates)
}
else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}")
.withPsiAttachment("declaration", declaration)
}
if (elementToReplace == null) return null
if (candidates.size == 1) {
builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text)
return null
}
builder.replaceElement(elementToReplace, expression)
return expression
}
private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) {
if (!(callableInfo as PropertyInfo).writable) {
builder.replaceElement(property.valOrVarKeyword, ValVarExpression)
}
}
private fun setupTypeParameterListTemplate(
builder: TemplateBuilderImpl,
declaration: KtNamedDeclaration
): TypeParameterListExpression? {
when (declaration) {
is KtObjectDeclaration -> return null
!is KtTypeParameterListOwner -> {
throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}")
.withPsiAttachment("declaration", declaration)
}
}
val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null
val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>()
val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>()
//receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) }
mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() }
callableInfo.parameterInfos.asSequence()
.flatMap { typeCandidates[it.typeInfo]!!.asSequence() }
.forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! }
if (declaration.getReturnTypeReference() != null) {
typeCandidates[callableInfo.returnTypeInfo]!!.forEach {
typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!!
}
}
val expression = TypeParameterListExpression(
mandatoryTypeParameters,
typeParameterMap,
callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR
)
val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace
val rangeStart = leftSpace?.startOffset ?: typeParameterList.startOffset
val offset = typeParameterList.startOffset
val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset)
builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false)
return expression
}
private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> {
assert(parameterList.size == callableInfo.parameterInfos.size)
val typeParameters = ArrayList<TypeExpression>()
for ((parameter, ktParameter) in callableInfo.parameterInfos.zip(parameterList)) {
val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!)
val parameterTypeRef = ktParameter.typeReference!!
builder.replaceElement(parameterTypeRef, parameterTypeExpression)
// add parameter name to the template
val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext)
val possibleNames = arrayOf(*parameter.nameSuggestions.toTypedArray(), *possibleNamesFromExpression)
// figure out suggested names for each type option
val parameterTypeToNamesMap = HashMap<String, Array<String>>()
typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate ->
val suggestedNames = KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true })
parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray()
}
// add expression to builder
val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap)
val parameterNameIdentifier = ktParameter.nameIdentifier!!
builder.replaceElement(parameterNameIdentifier, parameterNameExpression)
typeParameters.add(parameterTypeExpression)
}
return typeParameters
}
private fun replaceWithLongerName(typeRefs: List<KtTypeReference>, theType: KotlinType) {
val psiFactory = KtPsiFactory(ktFileToEdit.project)
val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) }
(typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) }
}
private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean {
fun convertToJava(targetClass: PsiClass): PsiMember? {
val psiFactory = KtPsiFactory(declaration)
psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let {
declaration.containingFile.addBefore(it, null)
}
val adjustedDeclaration = when (declaration) {
is KtNamedFunction, is KtProperty -> {
val klass = psiFactory.createClass("class Foo {}")
klass.body!!.add(declaration)
(declaration.replace(klass) as KtClass).body!!.declarations.first()
}
else -> declaration
}
return when (adjustedDeclaration) {
is KtNamedFunction, is KtSecondaryConstructor -> {
createJavaMethod(adjustedDeclaration as KtFunction, targetClass)
}
is KtProperty -> {
createJavaField(adjustedDeclaration, targetClass)
}
is KtClass -> {
createJavaClass(adjustedDeclaration, targetClass)
}
else -> null
}
}
if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false
val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass
if (targetClass == null || !targetClass.canRefactor()) return false
val project = declaration.project
val newJavaMember = convertToJava(targetClass) ?: return false
val modifierList = newJavaMember.modifierList!!
if (newJavaMember is PsiMethod || newJavaMember is PsiClass) {
modifierList.setModifierProperty(PsiModifier.FINAL, false)
}
val needStatic = when (callableInfo) {
is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) {
!inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS
}
else -> callableInfo.receiverTypeInfo.staticContextRequired
}
modifierList.setModifierProperty(PsiModifier.STATIC, needStatic)
JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember)
val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile)
val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!!
targetEditor.selectionModel.removeSelection()
when (newJavaMember) {
is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor)
is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1)
is PsiClass -> {
val constructor = newJavaMember.constructors.firstOrNull()
val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement
val superCall = superStatement?.expression as? PsiMethodCallExpression
if (superCall != null) {
val lParen = superCall.argumentList.firstChild
targetEditor.caretModel.moveToOffset(lParen.endOffset)
} else {
targetEditor.caretModel.moveToOffset(newJavaMember.nameIdentifier?.startOffset ?: newJavaMember.startOffset)
}
}
}
targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE)
return true
}
private fun setupEditor(declaration: KtNamedDeclaration) {
if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) {
val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType
val defaultValue = defaultValueType?.let { CodeInsightUtils.defaultInitializer(it) } ?: "null"
val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!!
val range = initializer.textRange
containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset)
containingFileEditor.caretModel.moveToOffset(range.endOffset)
return
}
if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) {
containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1)
return
}
setupEditorSelection(containingFileEditor, declaration)
}
// build templates
fun buildAndRunTemplate(onFinish: () -> Unit) {
val declarationSkeleton = createDeclarationSkeleton()
val project = declarationSkeleton.project
val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton)
// build templates
val documentManager = PsiDocumentManager.getInstance(project)
val document = containingFileEditor.document
documentManager.commitDocument(document)
documentManager.doPostponedOperationsAndUnblockDocument(document)
val caretModel = containingFileEditor.caretModel
caretModel.moveToOffset(ktFileToEdit.node.startOffset)
val declaration = declarationPointer.element ?: return
val declarationMarker = document.createRangeMarker(declaration.textRange)
val builder = TemplateBuilderImpl(ktFileToEdit)
if (declaration is KtProperty) {
setupValVarTemplate(builder, declaration)
}
if (!skipReturnType) {
setupReturnTypeTemplate(builder, declaration)
}
val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters())
// add a segment for the parameter list
// Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we
// need to create the segment first and then hack the Expression into the template later. We use this template to update the type
// parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to
// it.
val expression = setupTypeParameterListTemplate(builder, declaration)
documentManager.doPostponedOperationsAndUnblockDocument(document)
// the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it
val templateImpl = builder.buildInlineTemplate() as TemplateImpl
val variables = templateImpl.variables!!
if (variables.isNotEmpty()) {
val typeParametersVar = if (expression != null) variables.removeAt(0) else null
for (i in callableInfo.parameterInfos.indices) {
Collections.swap(variables, i * 2, i * 2 + 1)
}
typeParametersVar?.let { variables.add(it) }
}
// TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening
templateImpl.isToShortenLongNames = false
// run the template
TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() {
private fun finishTemplate(brokenOff: Boolean) {
try {
documentManager.commitDocument(document)
dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE)
if (brokenOff && !isUnitTestMode()) return
// file templates
val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset(
ktFileToEdit,
declarationMarker.startOffset,
declaration::class.java,
false
) ?: return
runWriteAction {
postprocessDeclaration(newDeclaration)
// file templates
if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) {
setupDeclarationBody(newDeclaration as KtFunction)
}
if (newDeclaration is KtProperty) {
newDeclaration.getter?.let { setupDeclarationBody(it) }
if (callableInfo is PropertyInfo && callableInfo.initializer != null) {
newDeclaration.initializer = callableInfo.initializer
}
}
val callElement = config.originalElement as? KtCallElement
if (callElement != null) {
setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList())
}
CodeStyleManager.getInstance(project).reformat(newDeclaration)
// change short type names to fully qualified ones (to be shortened below)
if (newDeclaration.getValueParameters().size == parameterTypeExpressions.size) {
setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions)
}
if (!transformToJavaMemberIfApplicable(newDeclaration)) {
elementsToShorten.add(newDeclaration)
setupEditor(newDeclaration)
}
}
} finally {
declarationMarker.dispose()
finished = true
onFinish()
}
}
override fun templateCancelled(template: Template?) {
finishTemplate(true)
}
override fun templateFinished(template: Template, brokenOff: Boolean) {
finishTemplate(brokenOff)
}
})
}
fun showDialogIfNeeded() {
if (!isUnitTestMode() && dialogWithEditor != null && !finished) {
dialogWithEditor.show()
}
}
}
}
// TODO: Simplify and use formatter as much as possible
@Suppress("UNCHECKED_CAST")
internal fun <D : KtNamedDeclaration> placeDeclarationInContainer(
declaration: D,
container: PsiElement,
anchor: PsiElement,
fileToEdit: KtFile = container.containingFile as KtFile
): D {
val psiFactory = KtPsiFactory(container)
val newLine = psiFactory.createNewLine()
fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int {
var lineBreaksPresent = 0
var neighbor: PsiElement? = null
siblingsLoop@
for (sibling in decl.siblings(forward = after, withItself = false)) {
when (sibling) {
is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' }
else -> {
neighbor = sibling
break@siblingsLoop
}
}
}
val neighborType = neighbor?.node?.elementType
val lineBreaksNeeded = when {
neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1
neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2
else -> 1
}
return max(lineBreaksNeeded - lineBreaksPresent, 0)
}
val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container
fun addDeclarationToClassOrObject(
classOrObject: KtClassOrObject,
declaration: KtNamedDeclaration
): KtNamedDeclaration {
val classBody = classOrObject.getOrCreateBody()
return if (declaration is KtNamedFunction) {
val neighbor = PsiTreeUtil.skipSiblingsBackward(
classBody.rBrace ?: classBody.lastChild!!,
PsiWhiteSpace::class.java
)
classBody.addAfter(declaration, neighbor) as KtNamedDeclaration
} else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration
}
fun addNextToOriginalElementContainer(addBefore: Boolean): D {
val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer }
return if (addBefore || PsiTreeUtil.hasErrorElements(sibling)) {
actualContainer.addBefore(declaration, sibling)
} else {
actualContainer.addAfter(declaration, sibling)
} as D
}
val declarationInPlace = when {
declaration is KtPrimaryConstructor -> {
(container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration)
}
declaration is KtProperty && container !is KtBlockExpression -> {
val sibling = actualContainer.getChildOfType<KtProperty>() ?: when (actualContainer) {
is KtClassBody -> actualContainer.declarations.firstOrNull() ?: actualContainer.rBrace
is KtFile -> actualContainer.declarations.first()
else -> null
}
sibling?.let { actualContainer.addBefore(declaration, it) as D } ?: fileToEdit.add(declaration) as D
}
actualContainer.isAncestor(anchor, true) -> {
val insertToBlock = container is KtBlockExpression
if (insertToBlock) {
val parent = container.parent
if (parent is KtFunctionLiteral) {
if (!parent.isMultiLine()) {
parent.addBefore(newLine, container)
parent.addAfter(newLine, container)
}
}
}
addNextToOriginalElementContainer(insertToBlock || declaration is KtTypeAlias)
}
container is KtFile -> container.add(declaration) as D
container is PsiClass -> {
if (declaration is KtSecondaryConstructor) {
val wrappingClass = psiFactory.createClass("class ${container.name} {\n}")
addDeclarationToClassOrObject(wrappingClass, declaration)
(fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D
} else {
fileToEdit.add(declaration) as D
}
}
container is KtClassOrObject -> {
var sibling: PsiElement? = container.declarations.lastOrNull { it::class == declaration::class }
if (sibling == null && declaration is KtProperty) {
sibling = container.body?.lBrace
}
insertMembersAfterAndReformat(null, container, declaration, sibling)
}
else -> throw KotlinExceptionWithAttachments("Invalid containing element: ${container::class.java}")
.withPsiAttachment("container", container)
}
when (declaration) {
is KtEnumEntry -> {
val prevEnumEntry = declarationInPlace.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtEnumEntry>()
if (prevEnumEntry != null) {
if ((prevEnumEntry.prevSibling as? PsiWhiteSpace)?.text?.contains('\n') == true) {
declarationInPlace.parent.addBefore(psiFactory.createNewLine(), declarationInPlace)
}
val comma = psiFactory.createComma()
if (prevEnumEntry.allChildren.any { it.node.elementType == KtTokens.COMMA }) {
declarationInPlace.add(comma)
} else {
prevEnumEntry.add(comma)
}
val semicolon = prevEnumEntry.allChildren.firstOrNull { it.node?.elementType == KtTokens.SEMICOLON }
if (semicolon != null) {
(semicolon.prevSibling as? PsiWhiteSpace)?.text?.let {
declarationInPlace.add(psiFactory.createWhiteSpace(it))
}
declarationInPlace.add(psiFactory.createSemicolon())
semicolon.delete()
}
}
}
!is KtPrimaryConstructor -> {
val parent = declarationInPlace.parent
calcNecessaryEmptyLines(declarationInPlace, false).let {
if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace)
}
calcNecessaryEmptyLines(declarationInPlace, true).let {
if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace)
}
}
}
return declarationInPlace
}
fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull()
internal fun KtNamedDeclaration.getReturnTypeReferences(): List<KtTypeReference> {
return when (this) {
is KtCallableDeclaration -> listOfNotNull(typeReference)
is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference }
else -> throw AssertionError("Unexpected declaration kind: $text")
}
}
fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this)
|
apache-2.0
|
611ff334c80be3707a41411b3d261d66
| 49.641925 | 158 | 0.61773 | 6.525171 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/introduceProperty/stringTemplates/rawTemplateWithSubstring.kt
|
13
|
277
|
// EXTRACTION_TARGET: property with initializer
val a = 1
fun foo(): String {
val x = """_c$a
:${a + 1}d_"""
val y = "_$a:${a + 1}d_"
val z = """_c$a:${a + 1}d_"""
val u = "_c$a\n:${a + 1}d_"
return """ab<selection>c$a
:${a + 1}d</selection>ef"""
}
|
apache-2.0
|
dd8ab78910dfe382d6caf0bb3652e394
| 22.166667 | 47 | 0.451264 | 2.541284 | false | false | false | false |
ThiagoGarciaAlves/intellij-community
|
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/ModuleHighlightingTest.kt
|
1
|
23976
|
// Copyright 2000-2017 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.java.codeInsight.daemon
import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes
import com.intellij.codeInsight.intention.IntentionActionDelegate
import com.intellij.codeInspection.deprecation.DeprecationInspection
import com.intellij.codeInspection.deprecation.MarkedForRemovalInspection
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.*
import com.intellij.openapi.util.TextRange
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl
import org.assertj.core.api.Assertions.assertThat
class ModuleHighlightingTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
(myFixture as CodeInsightTestFixtureImpl).setVirtualFileFilter({ it.name != "module-info.java"})
addFile("module-info.java", "module M2 { }", M2)
addFile("module-info.java", "module M3 { }", M3)
}
fun testPackageStatement() {
highlight("package pkg;")
highlight("""
<error descr="A module file should not have 'package' statement">package pkg;</error>
module M { }""".trimIndent())
fixes("<caret>package pkg;\nmodule M { }", arrayOf("DeleteElementFix"))
}
fun testSoftKeywords() {
addFile("pkg/module/C.java", "package pkg.module;\npublic class C { }")
myFixture.configureByText("module-info.java", "module M { exports pkg.module; }")
val keywords = myFixture.doHighlighting().filter { it.type == JavaHighlightInfoTypes.JAVA_KEYWORD }
assertEquals(2, keywords.size)
assertEquals(TextRange(0, 6), TextRange(keywords[0].startOffset, keywords[0].endOffset))
assertEquals(TextRange(11, 18), TextRange(keywords[1].startOffset, keywords[1].endOffset))
}
fun testWrongFileName() {
highlight("M.java", """/* ... */ <error descr="Module declaration should be in a file named 'module-info.java'">module M</error> { }""")
}
fun testFileDuplicate() {
addFile("pkg/module-info.java", """module M.bis { }""")
highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""")
}
fun testFileDuplicateInTestRoot() {
addTestFile("module-info.java", """module M.test { }""")
highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""")
}
fun testWrongFileLocation() {
highlight("pkg/module-info.java", """<error descr="Module declaration should be located in a module's source root">module M</error> { }""")
}
fun testIncompatibleModifiers() {
highlight("""
module M {
requires static transitive M2;
requires <error descr="Modifier 'private' not allowed here">private</error> <error descr="Modifier 'volatile' not allowed here">volatile</error> M3;
}""".trimIndent())
}
fun testAnnotations() {
highlight("""@Deprecated <error descr="'@Override' not applicable to module">@Override</error> module M { }""")
}
fun testDuplicateStatements() {
addFile("pkg/main/C.java", "package pkg.main;\npublic class C { }")
addFile("pkg/main/Impl.java", "package pkg.main;\npublic class Impl extends C { }")
highlight("""
import pkg.main.C;
module M {
requires M2;
<error descr="Duplicate 'requires': M2">requires M2;</error>
exports pkg.main;
<error descr="Duplicate 'exports': pkg.main">exports pkg. main;</error>
opens pkg.main;
<error descr="Duplicate 'opens': pkg.main">opens pkg. main;</error>
uses C;
<error descr="Duplicate 'uses': pkg.main.C">uses pkg. main . /*...*/ C;</error>
provides pkg .main .C with pkg.main.Impl;
<error descr="Duplicate 'provides': pkg.main.C">provides C with pkg. main. Impl;</error>
}""".trimIndent())
}
fun testUnusedServices() {
addFile("pkg/main/C1.java", "package pkg.main;\npublic class C1 { }")
addFile("pkg/main/C2.java", "package pkg.main;\npublic class C2 { }")
addFile("pkg/main/C3.java", "package pkg.main;\npublic class C3 { }")
addFile("pkg/main/Impl1.java", "package pkg.main;\npublic class Impl1 extends C1 { }")
addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 extends C2 { }")
addFile("pkg/main/Impl3.java", "package pkg.main;\npublic class Impl3 extends C3 { }")
highlight("""
import pkg.main.C2;
import pkg.main.C3;
module M {
uses C2;
uses pkg.main.C3;
provides pkg.main.<warning descr="Service interface provided but not exported or used">C1</warning> with pkg.main.Impl1;
provides pkg.main.C2 with pkg.main.Impl2;
provides C3 with pkg.main.Impl3;
}""".trimIndent())
}
fun testRequires() {
addFile("module-info.java", "module M2 { requires M1 }", M2)
highlight("""
module M1 {
requires <error descr="Module not found: M.missing">M.missing</error>;
requires <error descr="Cyclic dependence: M1">M1</error>;
requires <error descr="Cyclic dependence: M1, M2">M2</error>;
requires <error descr="Module is not in dependencies: M3">M3</error>;
requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>;
requires lib.multi.release;
requires lib.named;
requires lib.claimed;
}""".trimIndent())
}
fun testExports() {
addFile("pkg/empty/package-info.java", "package pkg.empty;")
addFile("pkg/main/C.java", "package pkg.main;\nclass C { }")
addFile("pkg/other/C.groovy", "package pkg.other\nclass C { }")
highlight("""
module M {
exports <error descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</error>;
exports <error descr="Package is empty: pkg.empty">pkg.empty</error>;
exports pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'exports' target: M2">M2</error>;
}""".trimIndent())
}
fun testOpens() {
addFile("pkg/empty/package-info.java", "package pkg.empty;")
addFile("pkg/main/C.java", "package pkg.main;\nclass C { }")
addFile("pkg/other/C.groovy", "package pkg.other\nclass C { }")
highlight("""
module M {
opens <warning descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</warning>;
opens <warning descr="Package is empty: pkg.empty">pkg.empty</warning>;
opens pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'opens' target: M2">M2</error>;
}""".trimIndent())
}
fun testWeakModule() {
highlight("""open module M { <error descr="'opens' is not allowed in an open module">opens pkg.missing;</error> }""")
}
fun testUses() {
addFile("pkg/main/C.java", "package pkg.main;\nclass C { void m(); }")
addFile("pkg/main/O.java", "package pkg.main;\npublic class O {\n public class I { void m(); }\n}")
addFile("pkg/main/E.java", "package pkg.main;\npublic enum E { }")
highlight("""
module M {
uses pkg.<error descr="Cannot resolve symbol 'main'">main</error>;
uses pkg.main.<error descr="Cannot resolve symbol 'X'">X</error>;
uses pkg.main.<error descr="'pkg.main.C' is not public in 'pkg.main'. Cannot be accessed from outside package">C</error>;
uses pkg.main.<error descr="The service definition is an enum: E">E</error>;
uses pkg.main.O.I;
uses pkg.main.O.I.<error descr="Cannot resolve symbol 'm'">m</error>;
}""".trimIndent())
}
fun testProvides() {
addFile("pkg/main/C.java", "package pkg.main;\npublic interface C { }")
addFile("pkg/main/CT.java", "package pkg.main;\npublic interface CT<T> { }")
addFile("pkg/main/Impl1.java", "package pkg.main;\nclass Impl1 { }")
addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 { }")
addFile("pkg/main/Impl3.java", "package pkg.main;\npublic abstract class Impl3 implements C { }")
addFile("pkg/main/Impl4.java", "package pkg.main;\npublic class Impl4 implements C {\n public Impl4(String s) { }\n}")
addFile("pkg/main/Impl5.java", "package pkg.main;\npublic class Impl5 implements C {\n protected Impl5() { }\n}")
addFile("pkg/main/Impl6.java", "package pkg.main;\npublic class Impl6 implements C { }")
addFile("pkg/main/Impl7.java", "package pkg.main;\npublic class Impl7 {\n public static void provider();\n}")
addFile("pkg/main/Impl8.java", "package pkg.main;\npublic class Impl8 {\n public static C provider();\n}")
addFile("pkg/main/Impl9.java", "package pkg.main;\npublic class Impl9 {\n public class Inner implements C { }\n}")
addFile("pkg/main/Impl10.java", "package pkg.main;\npublic class Impl10<T> implements CT<T> {\n private Impl10() { }\n public static CT provider();\n}")
addFile("module-info.java", "module M2 {\n exports pkg.m2;\n}", M2)
addFile("pkg/m2/C.java", "package pkg.m2;\npublic class C { }", M2)
addFile("pkg/m2/Impl.java", "package pkg.m2;\npublic class Impl extends C { }", M2)
highlight("""
import pkg.main.Impl6;
module M {
requires M2;
provides pkg.main.C with pkg.main.<error descr="Cannot resolve symbol 'NoImpl'">NoImpl</error>;
provides pkg.main.C with pkg.main.<error descr="'pkg.main.Impl1' is not public in 'pkg.main'. Cannot be accessed from outside package">Impl1</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation type must be a subtype of the service interface type, or have a public static no-args 'provider' method">Impl2</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation is an abstract class: Impl3">Impl3</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl4">Impl4</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl5">Impl5</error>;
provides pkg.main.C with pkg.main.Impl6, <error descr="Duplicate implementation: pkg.main.Impl6">Impl6</error>;
provides pkg.main.C with pkg.main.<error descr="The 'provider' method return type must be a subtype of the service interface type: Impl7">Impl7</error>;
provides pkg.main.C with pkg.main.Impl8;
provides pkg.main.C with pkg.main.Impl9.<error descr="The service implementation is an inner class: Inner">Inner</error>;
provides pkg.main.CT with pkg.main.Impl10;
provides pkg.m2.C with pkg.m2.<error descr="The service implementation must be defined in the same module as the provides directive">Impl</error>;
}""".trimIndent())
}
fun testQuickFixes() {
addFile("pkg/main/impl/X.java", "package pkg.main.impl;\npublic class X { }")
addFile("module-info.java", "module M2 { exports pkg.m2; }", M2)
addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2)
addFile("pkg/m3/C3.java", "package pkg.m3;\npublic class C3 { }", M3)
addFile("module-info.java", "module M6 { exports pkg.m6; }", M6)
addFile("pkg/m6/C6.java", "package pkg.m6;\nimport pkg.m8.*;\nimport java.util.function.*;\npublic class C6 { public void m(Consumer<C8> c) { } }", M6)
addFile("module-info.java", "module M8 { exports pkg.m8; }", M8)
addFile("pkg/m8/C8.java", "package pkg.m8;\npublic class C8 { }", M8)
fixes("module M { requires <caret>M.missing; }", arrayOf())
fixes("module M { requires <caret>M3; }", arrayOf("AddModuleDependencyFix"))
fixes("module M { exports pkg.main.impl to <caret>M3; }", arrayOf())
fixes("module M { exports <caret>pkg.missing; }", arrayOf())
fixes("module M { exports <caret>pkg.m3; }", arrayOf())
fixes("module M { uses pkg.m3.<caret>C3; }", arrayOf("AddModuleDependencyFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddRequiresDirectiveFix"))
addFile("module-info.java", "module M { requires M6; }")
addFile("pkg/main/Util.java", "package pkg.main;\nclass Util {\n static <T> void sink(T t) { }\n}")
fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>Util::sink); }}", arrayOf("AddRequiresDirectiveFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>t -> Util.sink(t)); }}", arrayOf("AddRequiresDirectiveFix"))
addFile("module-info.java", "module M2 { }", M2)
fixes("module M { requires M2; uses <caret>pkg.m2.C2; }", arrayOf("AddExportsDirectiveFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddExportsDirectiveFix"))
addFile("pkg/main/S.java", "package pkg.main;\npublic class S { }")
fixes("module M { provides pkg.main.<caret>S with pkg.main.S; }", arrayOf("AddExportsDirectiveFix", "AddUsesDirectiveFix"))
}
fun testPackageAccessibility() = doTestPackageAccessibility(moduleFileInTests = false, checkFileInTests = false)
fun testPackageAccessibilityInNonModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = false)
fun testPackageAccessibilityInModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = true)
private fun doTestPackageAccessibility(moduleFileInTests: Boolean = false, checkFileInTests: Boolean = false) {
val moduleFileText = "module M { requires M2; requires M6; requires lib.named; requires lib.auto; }"
if (moduleFileInTests) addTestFile("module-info.java", moduleFileText) else addFile("module-info.java", moduleFileText)
addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2)
addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2)
addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2)
addFile("pkg/sub/C2X.java", "package pkg.sub;\npublic class C2X { }", M2)
addFile("pkg/unreachable/C3.java", "package pkg.unreachable;\npublic class C3 { }", M3)
addFile("pkg/m4/C4.java", "package pkg.m4;\npublic class C4 { }", M4)
addFile("module-info.java", "module M5 { exports pkg.m5; }", M5)
addFile("pkg/m5/C5.java", "package pkg.m5;\npublic class C5 { }", M5)
addFile("module-info.java", "module M6 { requires transitive M7; }", M6)
addFile("pkg/sub/C6X.java", "package pkg.sub;\npublic class C6X { }", M6)
addFile("module-info.java", "module M7 { exports pkg.m7; }", M7)
addFile("pkg/m7/C7.java", "package pkg.m7;\npublic class C7 { }", M7)
var checkFileText = """
import pkg.m2.C2;
import pkg.m2.*;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.*;
import <error descr="Package 'pkg.m4' is declared in the unnamed module, but module 'M' does not read it">pkg.m4</error>.C4;
import <error descr="Package 'pkg.m5' is declared in module 'M5', but module 'M' does not read it">pkg.m5</error>.C5;
import pkg.m7.C7;
import <error descr="Package 'pkg.sub' is declared in module 'M2', which does not export it to module 'M'">pkg.sub</error>.*;
import <error descr="Package not found: pkg.unreachable">pkg.unreachable</error>.*;
import pkg.lib1.LC1;
import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.LC1Impl;
import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.*;
import pkg.lib2.LC2;
import pkg.lib2.impl.LC2Impl;
import static <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make;
import java.util.List;
import java.util.function.Supplier;
/** See also {@link C2Impl#I} and {@link C2Impl#make} */
class C {{
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.I = 0;
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.make();
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.I = 1;
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make();
List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>> l1 = null;
List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl> l2 = null;
Supplier<C2> s1 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>::make;
Supplier<C2> s2 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl::make;
}}
""".trimIndent()
if (moduleFileInTests != checkFileInTests) {
checkFileText = Regex("(<error [^>]+>)([^<]+)(</error>)").replace(checkFileText, {
if (it.value.contains("unreachable")) it.value else it.groups[2]!!.value
})
}
highlight("test.java", checkFileText, checkFileInTests)
}
fun testLinearModuleGraphBug() {
addFile("module-info.java", "module M6 { requires M7; }", M6)
addFile("module-info.java", "module M7 { }", M7)
highlight("module M { requires M6; }")
}
fun testDeprecations() {
myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection())
addFile("module-info.java", "@Deprecated module M2 { }", M2)
highlight("""module M { requires <warning descr="'M2' is deprecated">M2</warning>; }""")
}
fun testMarkedForRemoval() {
myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection())
addFile("module-info.java", "@Deprecated(forRemoval=true) module M2 { }", M2)
highlight("""module M { requires <error descr="'M2' is deprecated and marked for removal">M2</error>; }""")
}
fun testPackageConflicts() {
addFile("pkg/collision2/C2.java", "package pkg.collision2;\npublic class C2 { }", M2)
addFile("pkg/collision4/C4.java", "package pkg.collision4;\npublic class C4 { }", M4)
addFile("pkg/collision7/C7.java", "package pkg.collision7;\npublic class C7 { }", M7)
addFile("module-info.java", "module M2 { exports pkg.collision2; }", M2)
addFile("module-info.java", "module M4 { exports pkg.collision4 to M88; }", M4)
addFile("module-info.java", "module M6 { requires transitive M7; }", M6)
addFile("module-info.java", "module M7 { exports pkg.collision7 to M6; }", M7)
addFile("module-info.java", "module M { requires M2; requires M4; requires M6; requires lib.auto; }")
highlight("test1.java", """<error descr="Package 'pkg.collision2' exists in another module: M2">package pkg.collision2;</error>""")
highlight("test2.java", """package pkg.collision4;""")
highlight("test3.java", """package pkg.collision7;""")
highlight("test4.java", """<error descr="Package 'java.util' exists in another module: java.base">package java.util;</error>""")
highlight("test5.java", """<error descr="Package 'pkg.lib2' exists in another module: lib.auto">package pkg.lib2;</error>""")
}
fun testClashingReads1() {
addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2)
addFile("pkg/collision/C7.java", "package pkg.collision;\npublic class C7 { }", M7)
addFile("module-info.java", "module M2 { exports pkg.collision; }", M2)
addFile("module-info.java", "module M6 { requires transitive M7; }", M6)
addFile("module-info.java", "module M7 { exports pkg.collision; }", M7)
highlight("""
<error descr="Module 'M' reads package 'pkg.collision' from both 'M2' and 'M7'">module M</error> {
requires M2;
requires M6;
}""".trimIndent())
}
fun testClashingReads2() {
addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2)
addFile("pkg/collision/C4.java", "package pkg.collision;\npublic class C4 { }", M4)
addFile("module-info.java", "module M2 { exports pkg.collision; }", M2)
addFile("module-info.java", "module M4 { exports pkg.collision to somewhere; }", M4)
highlight("module M { requires M2; requires M4; }")
}
fun testClashingReads3() {
addFile("pkg/lib2/C2.java", "package pkg.lib2;\npublic class C2 { }", M2)
addFile("module-info.java", "module M2 { exports pkg.lib2; }", M2)
highlight("""
<error descr="Module 'M' reads package 'pkg.lib2' from both 'M2' and 'lib.auto'">module M</error> {
requires M2;
requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>;
}""".trimIndent())
}
fun testInaccessibleMemberType() {
addFile("module-info.java", "module C { exports pkg.c; }", M8)
addFile("module-info.java", "module B { requires C; exports pkg.b; }", M6)
addFile("module-info.java", "module A { requires B; }")
addFile("pkg/c/C.java", "package pkg.c;\npublic class C { }", M8)
addFile("pkg/b/B.java", """
package pkg.b;
import pkg.c.C;
public class B {
private static class I { }
public C f1;
public I f2;
public C m1(C p1, Class<? extends C> p2) { return new C(); }
public I m2(I p1, Class<? extends I> p2) { return new I(); }
}""".trimIndent(), M6)
highlight("pkg/a/A.java", """
package pkg.a;
import pkg.b.B;
public class A {
void test() {
B exposer = new B();
exposer.f1 = null;
exposer.f2 = null;
Object o1 = exposer.m1(null, null);
Object o2 = exposer.m2(null, null);
}
}""".trimIndent())
}
fun testAccessingDefaultPackage() {
addFile("X.java", "public class X {\n public static class XX extends X { }\n}")
highlight("""
module M {
uses <error descr="Class 'X' is in the default package">X</error>;
provides <error descr="Class 'X' is in the default package">X</error> with <error descr="Class 'X' is in the default package">X</error>.XX;
}""".trimIndent())
}
//<editor-fold desc="Helpers.">
private fun highlight(text: String) = highlight("module-info.java", text)
private fun highlight(path: String, text: String, isTest: Boolean = false) {
myFixture.configureFromExistingVirtualFile(if (isTest) addTestFile(path, text) else addFile(path, text))
myFixture.checkHighlighting()
}
private fun fixes(text: String, fixes: Array<String>) = fixes("module-info.java", text, fixes)
private fun fixes(path: String, text: String, fixes: Array<String>) {
myFixture.configureFromExistingVirtualFile(addFile(path, text))
val available = myFixture.availableIntentions
.map { (if (it is IntentionActionDelegate) it.delegate else it)::class.simpleName }
.filter { it != "GutterIntentionAction" }
assertThat(available).containsExactlyInAnyOrder(*fixes)
}
//</editor-fold>
}
|
apache-2.0
|
51e396b00ac2c40d5a96ef5e36d86ffe
| 56.224344 | 204 | 0.660202 | 3.631627 | false | true | false | false |
vicpinm/KPresenterAdapter
|
kpa-processor/src/main/java/com/vicpin/kpa/annotation/processor/ViewHolderWritter.kt
|
1
|
3824
|
package com.vicpin.kpa.annotation.processor
import com.vicpin.kpa.annotation.processor.model.Model
import java.io.IOException
import javax.annotation.processing.ProcessingEnvironment
/**
* Created by victor on 10/12/17.
*/
class ViewHolderWritter(private val entity: Model.EntityModel) {
private var text: String = ""
private val className: String
init {
this.className = entity.name + VIEWHOLDER_SUFIX
}
private fun generateClass(): String {
appendPackpage()
appendImports()
appendClassName()
appendClassProperties()
appendPrimaryConstructor()
appendGetPresenterMethod()
appendBindMethod()
appendGetContainerViewMethod()
appendClassEnding()
return text
}
private fun appendPackpage() {
newLine("package ${entity.pkg}", newLine = true)
}
private fun appendImports() {
newLine("import ${entity.modelClass}")
newLine("import android.view.View")
newLine("import com.vicpin.butcherknife.Binding")
newLine("import com.vicpin.kpresenteradapter.ViewHolder")
newLine("import com.vicpin.kpresenteradapter.ViewHolderPresenter")
newLine("import ${entity.pkg}.${entity.name}Binding", newLine = true)
}
private fun appendClassName() {
newLine("public class $className extends ViewHolder<${entity.name}> implements ${entity.name}PresenterParent.View {", newLine = true)
}
private fun appendClassProperties() {
newLine("private ${entity.name}${PresenterWritter.PRESENTER_SUFIX} presenter = new ${entity.name}${PresenterWritter.PRESENTER_SUFIX}()", level = 1)
newLine("private Binding binding", newLine = true, level = 1)
}
private fun appendPrimaryConstructor() {
newLine("public ${entity.name}ViewHolderParent(View itemView) {", level = 1)
newLine("super(itemView)", level = 2)
newLine("binding = ${entity.name}Binding.with(itemView)", level = 2)
newLine("}", newLine = true, level = 1)
}
private fun appendGetPresenterMethod() {
newLine("@Override public ViewHolderPresenter<${entity.name}, ${entity.name}${PresenterWritter.PRESENTER_SUFIX}.View> getPresenter() {", level = 1)
newLine("return presenter", level = 2)
newLine("}", newLine = true, level = 1)
}
private fun appendBindMethod() {
newLine("@Override public void bind(${entity.name} data) {", level = 1)
newLine("binding.bind(data)", level = 2);
newLine("}", newLine = true, level = 1)
}
private fun appendGetContainerViewMethod() {
newLine("@Override public View getContainerView() { return itemView; }", level = 1)
}
private fun appendClassEnding() {
newLine("}")
}
fun generateFile(env: ProcessingEnvironment) {
try { // write the file
val source = env.filer.createSourceFile("${entity.pkg}.$className")
val writer = source.openWriter()
writer.write(generateClass())
writer.flush()
writer.close()
} catch (e: IOException) {
// Note: calling e.printStackTrace() will print IO errors
// that occur from the file already existing after its first run, this is normal
}
}
fun newLine(line: String = "", level: Int = 0, newLine: Boolean = false) {
var indentation = ""
var semicolon = if (!line.isEmpty() && !line.endsWith("}") && !line.endsWith("{")) ";" else ""
(1..level).forEach { indentation += "\t" }
text += if (newLine) {
"$indentation$line$semicolon\n\n"
} else {
"$indentation$line$semicolon\n"
}
}
companion object {
private val VIEWHOLDER_SUFIX = "ViewHolderParent"
}
}
|
apache-2.0
|
cf4fcd5d2adb1431f5e6019c083e6e38
| 31.965517 | 155 | 0.627615 | 4.546968 | false | false | false | false |
Heapy/komodo
|
komodo-core/src/main/kotlin/io/heapy/komodo/DefaultKomodo.kt
|
1
|
771
|
package io.heapy.komodo
import io.heapy.komodo.di.Module
import kotlin.reflect.KClass
/**
* @author Ruslan Ibragimov
* @since 1.0
*/
class DefaultKomodo : Komodo {
private val modules = mutableListOf<Module>()
private val args = mutableListOf<String>()
private val env = mutableMapOf<String, String>()
override fun module(module: Module): Komodo {
modules += module
return this
}
override fun args(args: Array<String>): Komodo {
this.args += args
return this
}
override fun env(env: Map<String, String>): Komodo {
this.env += env
return this
}
override suspend fun <R> run(entryPoint: KClass<out EntryPoint<R>>): R {
return entryPoint.objectInstance!!.run()
}
}
|
lgpl-3.0
|
7924b9cc2f0b09a01ca08b6884655c77
| 22.363636 | 76 | 0.635538 | 4.101064 | false | false | false | false |
softappeal/yass
|
kotlin/yass/main/ch/softappeal/yass/remote/session/SessionWatcher.kt
|
1
|
1520
|
package ch.softappeal.yass.remote.session
import java.util.concurrent.*
/**
* Closes a session if it isn't healthy.
* [executor] is used twice; must interrupt it's threads to terminate checks,
* checks are also terminated if session is closed.
* [sessionChecker] must execute without an exception within timeout if session is ok.
*/
@JvmOverloads
fun watchSession(
executor: Executor, session: Session,
intervalSeconds: Long, timeoutSeconds: Long, delaySeconds: Long = 0L,
sessionChecker: () -> Unit
) {
require(intervalSeconds >= 1)
require(timeoutSeconds >= 1)
require(delaySeconds >= 0)
executor.execute {
try {
TimeUnit.SECONDS.sleep(delaySeconds)
} catch (e: InterruptedException) {
return@execute
}
while (!session.isClosed && !Thread.interrupted()) {
try {
TimeUnit.SECONDS.sleep(intervalSeconds)
} catch (e: InterruptedException) {
return@execute
}
val ok = CountDownLatch(1)
executor.execute {
try {
if (!ok.await(timeoutSeconds, TimeUnit.SECONDS)) session.close(Exception("sessionChecker"))
} catch (ignore: InterruptedException) {
}
}
try {
sessionChecker()
} catch (e: Exception) {
session.close(e)
return@execute
}
ok.countDown()
}
}
}
|
bsd-3-clause
|
6e887b2061dfdf1218fe502295f09e6e
| 30.666667 | 111 | 0.569737 | 4.810127 | false | false | false | false |
Duke1/UnrealMedia
|
UnrealMedia/app/src/main/java/com/qfleng/um/util/OkHttpReq.kt
|
1
|
1911
|
package com.qfleng.um.util
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import kotlin.jvm.Volatile
import okhttp3.Request
import java.io.IOException
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
/**
* Created by Duke
*/
class OkHttpReq private constructor() {
private val okHttpClient: OkHttpClient
private val TIME_OUT_SECONDS: Long = 30
val JSON = "application/json; charset=utf-8".toMediaType()
fun executeRequest(req: Request): String? {
try {
val response = okHttpClient.newCall(req).execute()
if (200 == response.code) {
val content = response.body!!.bytes()
return String(content, Charset.forName("UTF-8"))
}
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
companion object {
fun getChromeRequestBuilder(): Request.Builder {
return Request.Builder()
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.44")
}
@Volatile
private var _instance: OkHttpReq? = null
val instance: OkHttpReq
get() {
if (null == _instance) {
synchronized(OkHttpReq::class.java) {
if (null == _instance) {
_instance = OkHttpReq()
}
}
}
return _instance!!
}
}
init {
okHttpClient = OkHttpClient.Builder()
.connectTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(TIME_OUT_SECONDS, TimeUnit.SECONDS)
.build()
}
}
|
mit
|
ae05ab4d33e45ab61d969acc8c10342e
| 27.537313 | 176 | 0.559393 | 4.528436 | false | false | false | false |
intrigus/jtransc
|
jtransc-utils/src/com/jtransc/serialization/xml/XmlStream.kt
|
2
|
3723
|
package com.jtransc.serialization.xml
import com.jtransc.text.substr
import java.util.*
object XmlStream {
fun parse(str: String): Iterable<Element> = parse(StrReader(str))
fun parse(r: StrReader): Iterable<Element> = Xml2Iterable(r)
class Xml2Iterator(r2: StrReader) : Iterator<Element> {
val r = r2.clone()
var buffer: String = ""
var hasMore: Boolean = true
var current: Element? = null
fun flushBuffer() {
if (buffer.isNotEmpty()) {
current = Element.Text(XmlEntities.decode(buffer))
buffer = ""
}
}
fun prepare() {
if (current != null) return
if (r.eof) {
current = null
hasMore = false
return
}
mainLoop@ while (!r.eof) {
when (r.peekChar()) {
'<' -> {
flushBuffer()
if (current != null) return
r.readExpect("<")
if (r.matchLit("![CDATA[") != null) {
val start = r.pos
while (!r.eof) {
val end = r.pos
if (r.matchLit("]]>") != null) {
current = Element.Text(r.createRange(start until end).text)
return
}
r.readChar()
}
break@mainLoop
} else if (r.matchLit("!--") != null) {
val start = r.pos
while (!r.eof) {
val end = r.pos
if (r.matchLit("-->") != null) {
current = Element.CommentTag(r.createRange(start until end).text)
return
}
r.readChar()
}
break@mainLoop
} else {
r.skipSpaces()
val processingInstruction = r.matchLit("?") != null
val close = r.matchLit("/") != null
r.skipSpaces()
val name = r.matchIdentifier()!!
r.skipSpaces()
val attributes = LinkedHashMap<String, String>()
while (r.peekChar() != '?' && r.peekChar() != '/' && r.peekChar() != '>') {
val key = r.matchIdentifier() ?: throw IllegalArgumentException("Malformed document or unsupported xml construct around ~${r.peek(10)}~")
r.skipSpaces()
if (r.matchLit("=") != null) {
r.skipSpaces()
val argsQuote = r.matchSingleOrDoubleQuoteString()
attributes[key] = if (argsQuote != null) {
XmlEntities.decode(argsQuote.substr(1, -1))
} else {
val argsNq = r.matchIdentifier()
XmlEntities.decode(argsNq!!)
}
} else {
attributes[key] = key
}
r.skipSpaces()
}
val openclose = r.matchLit("/") != null
val processingInstructionEnd = r.matchLit("?") != null
r.readExpect(">")
current = if (processingInstruction) Element.ProcessingInstructionTag(name, attributes)
else if (openclose) Element.OpenCloseTag(name, attributes)
else if (close) Element.CloseTag(name)
else Element.OpenTag(name, attributes)
return
}
}
else -> {
buffer += r.readChar()
}
}
}
hasMore = (buffer.isNotEmpty())
flushBuffer()
}
override fun next(): Element {
prepare()
val out = this.current
this.current = null
return out!!
}
override fun hasNext(): Boolean {
prepare()
return hasMore
}
}
class Xml2Iterable(val reader2: StrReader) : Iterable<Element> {
val reader = reader2.clone()
override fun iterator(): Iterator<Element> = Xml2Iterator(reader)
}
sealed class Element {
class ProcessingInstructionTag(val name: String, val attributes: Map<String, String>) : Element()
class OpenCloseTag(val name: String, val attributes: Map<String, String>) : Element()
class OpenTag(val name: String, val attributes: Map<String, String>) : Element()
class CommentTag(val text: String) : Element()
class CloseTag(val name: String) : Element()
class Text(val text: String) : Element()
}
}
|
apache-2.0
|
e9d8b244bc5aade5aeec69a810382b09
| 27.204545 | 145 | 0.588235 | 3.450417 | false | false | false | false |
breadwallet/breadwallet-android
|
app/src/main/java/com/breadwallet/ui/home/WalletListItem.kt
|
1
|
8310
|
package com.breadwallet.ui.home
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.breadwallet.R
import com.breadwallet.breadbox.formatCryptoForUi
import com.breadwallet.databinding.WalletListItemBinding
import com.breadwallet.legacy.presenter.customviews.ShimmerLayout
import com.breadwallet.ui.formatFiatForUi
import com.breadwallet.tools.manager.BRSharedPrefs
import com.breadwallet.tools.util.TokenUtil
import com.breadwallet.util.isBrd
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.drag.IDraggable
import com.mikepenz.fastadapter.items.ModelAbstractItem
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.invoke
import kotlinx.coroutines.launch
import java.io.File
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.Locale
class WalletListItem(
wallet: Wallet
) : ModelAbstractItem<Wallet, WalletListItem.ViewHolder>(wallet), IDraggable {
override val type: Int = R.id.wallet_list_item
override val layoutRes: Int = R.layout.wallet_list_item
override var identifier: Long = wallet.currencyId.hashCode().toLong()
override val isDraggable: Boolean = true
override fun getViewHolder(v: View) = ViewHolder(v)
class ViewHolder(
v: View
) : FastAdapter.ViewHolder<WalletListItem>(v) {
private val boundScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
override fun bindView(item: WalletListItem, payloads: List<Any>) {
val wallet = item.model
val context = itemView.context
val currencyCode = wallet.currencyCode
if (currencyCode.isBrd() && !BRSharedPrefs.getRewardsAnimationShown()) {
(itemView as ShimmerLayout).startShimmerAnimation()
} else {
(itemView as ShimmerLayout).stopShimmerAnimation()
}
// Format numeric data
val preferredFiatIso = BRSharedPrefs.getPreferredFiatIso()
val exchangeRate = wallet.fiatPricePerUnit.formatFiatForUi(preferredFiatIso)
val fiatBalance = wallet.fiatBalance.formatFiatForUi(preferredFiatIso)
val cryptoBalance = wallet.balance.formatCryptoForUi(currencyCode, MAX_CRYPTO_DIGITS)
with(WalletListItemBinding.bind(itemView)) {
if (wallet.fiatPricePerUnit == BigDecimal.ZERO) {
walletBalanceFiat.visibility = View.INVISIBLE
walletTradePrice.visibility = View.INVISIBLE
} else {
walletBalanceFiat.visibility = View.VISIBLE
walletTradePrice.visibility = View.VISIBLE
}
val isSyncing = wallet.isSyncing
val isLoading = wallet.state == Wallet.State.LOADING
// Set wallet fields
walletName.text = wallet.currencyName
walletTradePrice.text = exchangeRate
walletBalanceFiat.text = fiatBalance
walletBalanceFiat.setTextColor(
context.getColor(
when {
isSyncing -> R.color.wallet_balance_fiat_syncing
else -> R.color.wallet_balance_fiat
}
)
)
walletBalanceCurrency.text = cryptoBalance
walletBalanceCurrency.isGone = isSyncing || isLoading
syncProgress.isVisible = isSyncing || isLoading
syncingLabel.isVisible = isSyncing || isLoading
if (isSyncing) {
val syncProgress = wallet.syncProgress
var labelText = context.getString(R.string.SyncingView_syncing)
if (syncProgress > 0) {
labelText += " ${NumberFormat.getPercentInstance()
.format(syncProgress.toDouble())}"
}
syncingLabel.text = labelText
} else if (isLoading) {
syncingLabel.setText(R.string.Account_loadingMessage)
}
val priceChange2 = wallet.priceChange
priceChange.visibility = if (priceChange2 != null) View.VISIBLE else View.INVISIBLE
divider.visibility = if (priceChange2 != null) View.VISIBLE else View.INVISIBLE
if (priceChange2 != null) {
priceChange.text = priceChange2.getPercentageChange()
}
if (itemView.tag == wallet.currencyCode) {
return
}
loadTokenIcon(this, currencyCode)
setBackground(this, wallet, context)
item.tag = wallet.currencyCode
}
}
override fun unbindView(item: WalletListItem) {
item.tag = null
boundScope.coroutineContext.cancelChildren()
}
private fun loadTokenIcon(binding: WalletListItemBinding, currencyCode: String) {
boundScope.launch {
// Get icon for currency
val tokenIconPath = Default {
TokenUtil.getTokenIconPath(currencyCode, false)
}
ensureActive()
with(binding) {
if (tokenIconPath.isNullOrBlank()) {
iconLetter.visibility = View.VISIBLE
currencyIconWhite.visibility = View.GONE
iconLetter.text = currencyCode.take(1).toUpperCase(Locale.ROOT)
} else {
val iconFile = File(tokenIconPath)
Picasso.get().load(iconFile).into(currencyIconWhite)
iconLetter.visibility = View.GONE
currencyIconWhite.visibility = View.VISIBLE
}
}
}
}
private fun setBackground(binding: WalletListItemBinding, wallet: Wallet, context: Context) {
val drawable = ContextCompat
.getDrawable(context, R.drawable.crypto_card_shape)!!
.mutate()
if (wallet.isSupported) {
// Create gradient if 2 colors exist.
val startColor = Color.parseColor(wallet.startColor ?: return)
val endColor = Color.parseColor(wallet.endColor ?: return)
(drawable as GradientDrawable).colors = intArrayOf(startColor, endColor)
drawable.orientation = GradientDrawable.Orientation.LEFT_RIGHT
binding.walletCard.background = drawable
setWalletItemColors(binding, R.dimen.token_background_no_alpha)
} else {
// To ensure that the unsupported wallet card has the same shape as
// the supported wallet card, we reuse the drawable.
(drawable as GradientDrawable).colors = intArrayOf(
context.getColor(R.color.wallet_delisted_token_background),
context.getColor(R.color.wallet_delisted_token_background)
)
binding.walletCard.background = drawable
setWalletItemColors(binding, R.dimen.token_background_with_alpha)
}
}
private fun setWalletItemColors(binding: WalletListItemBinding, dimenRes: Int) {
val typedValue = TypedValue()
itemView.context.resources.getValue(dimenRes, typedValue, true)
val alpha = typedValue.float
with(binding) {
currencyIconWhite.alpha = alpha
walletName.alpha = alpha
walletTradePrice.alpha = alpha
walletBalanceFiat.alpha = alpha
walletBalanceCurrency.alpha = alpha
}
}
}
}
|
mit
|
70407a6f371179cc8d2c5d4d2337e836
| 42.28125 | 101 | 0.612395 | 5.368217 | false | false | false | false |
Magneticraft-Team/ModelLoader
|
src/main/kotlin/com/cout970/modelloader/ModelManager.kt
|
1
|
8305
|
package com.cout970.modelloader
import com.cout970.modelloader.animation.AnimatedModel
import com.cout970.modelloader.api.*
import com.cout970.modelloader.mutable.MutableModel
import net.minecraft.client.renderer.model.IBakedModel
import net.minecraft.client.renderer.model.IUnbakedModel
import net.minecraft.client.renderer.model.ModelResourceLocation
import net.minecraft.client.renderer.texture.ISprite
import net.minecraft.client.renderer.vertex.DefaultVertexFormats
import net.minecraft.resources.IResourceManager
import net.minecraft.util.ResourceLocation
import net.minecraftforge.client.event.ModelBakeEvent
import net.minecraftforge.client.event.TextureStitchEvent
import net.minecraftforge.client.model.ModelLoader
import net.minecraftforge.fml.ModLoader
import java.util.stream.Collectors
/**
* Model loaded from disk
*/
data class PreBakeModel(
val modelId: ModelResourceLocation,
val pre: ModelConfig,
val unbaked: IUnbakedModel
)
/**
* Model after the bake event
*/
data class PostBakeModel(
val modelId: ModelResourceLocation,
val pre: ModelConfig,
val baked: IBakedModel?,
val animations: Map<String, AnimatedModel>,
val mutable: MutableModel?
)
/**
* IBakedModel with extra variables
*/
interface IItemTransformable {
fun setItemTransforms(it: ItemTransforms)
fun setHasItemRenderer(hasItemRenderer: Boolean)
}
/**
* Internal use only, please use ModelRegisterEvent and ModelRetrieveEvent instead
*/
object ModelManager {
private val registeredModels = mutableMapOf<ModelResourceLocation, ModelConfig>()
private val sharedModels = mutableMapOf<ModelResourceLocation, ModelResourceLocation>()
private var textureToRegister: Set<ResourceLocation>? = null
private var modelsToBake: List<PreBakeModel>? = null
private var loadedModels: Map<ModelResourceLocation, PostBakeModel> = emptyMap()
@JvmStatic
fun register(modelId: ModelResourceLocation, pre: ModelConfig) {
registeredModels[modelId] = pre
}
@JvmStatic
fun share(origin: ModelResourceLocation, destine: ModelResourceLocation) {
sharedModels[destine] = origin
}
@JvmStatic
fun getModel(modelId: ModelResourceLocation): IBakedModel? {
return loadedModels[modelId]?.baked
}
@JvmStatic
fun getAnimations(modelId: ModelResourceLocation): Map<String, AnimatedModel> {
return loadedModels[modelId]?.animations ?: emptyMap()
}
/**
* Called to load from disk all models
*/
fun loadModelFiles(resourceManager: IResourceManager) {
try {
ModLoader.get().postEvent(ModelRegisterEvent(registeredModels, sharedModels))
} catch (e: Exception) {
ModelLoaderMod.logger.error("Error in ModelRegisterEvent, some models may be missing, check the log for details")
}
// Load model from disk
val cache = if (Config.useMultithreading.get()) {
registeredModels.values
.parallelStream()
.map { it.location }
.distinct()
.map { it to ModelFormatRegistry.loadUnbakedModel(resourceManager, it) }
.collect(Collectors.toList())
.toMap()
} else {
registeredModels.values
.asSequence()
.map { it.location }
.distinct()
.map { it to ModelFormatRegistry.loadUnbakedModel(resourceManager, it) }
.toMap()
}
val textures = mutableSetOf<ResourceLocation>()
val models = mutableListOf<PreBakeModel>()
val errors = mutableSetOf<String>()
registeredModels.forEach { (modelId, pre) ->
// If the same model appears twice it gets loaded only once
// and here it gets shared to all registered models with the same location
val model = cache[pre.location] ?: return@forEach
// Collects all textures needed for the baking process
if (pre.bake) {
textures += model.getTextures({ null }, errors)
}
// Allow to alter the model before it gets baked
val processedModel = pre.preBake?.invoke(modelId, model) ?: model
// Apply filter if specified and supported
val finalModel = if (pre.partFilter != null) {
if (processedModel is FilterableModel) processedModel.filterParts(pre.partFilter) else processedModel
} else {
processedModel
}
models += PreBakeModel(modelId, pre, finalModel)
}
// Print texture errors
if (errors.isNotEmpty()) {
ModelLoaderMod.logger.warn("Found following texture errors:")
errors.forEach { ModelLoaderMod.logger.warn(" $it") }
}
// Save values for other events
textureToRegister = textures
modelsToBake = models
}
/**
* Called to get all textures needed for models
*/
fun onTextureStitchEvent(event: TextureStitchEvent.Pre) {
// Register all textures
textureToRegister?.forEach { event.addSprite(it) }
textureToRegister = null
}
/**
* Called to bake all models and animations
*/
fun onModelBakeEvent(event: ModelBakeEvent) {
val modelsToBake = modelsToBake ?: return
ModelManager.modelsToBake = null
// Bake models
val bakedModels = if (Config.useMultithreading.get()) {
modelsToBake
.toList()
.parallelStream()
.map { processModel(it, event.modelLoader) }
.collect(Collectors.toList())
} else {
modelsToBake.map { processModel(it, event.modelLoader) }
}
loadedModels = bakedModels.map { it.modelId to it }.toMap()
// Register baked models
bakedModels.forEach { (modelId, pre, bakedModel) ->
// Ignore null models
bakedModel ?: return@forEach
// Set item transformation for gui, ground, etc
if (bakedModel is IItemTransformable) {
bakedModel.setItemTransforms(pre.itemTransforms)
bakedModel.setHasItemRenderer(pre.itemRenderer)
}
// Allow to alter the model after it gets baked
val finalModel = pre.postBake?.invoke(modelId, bakedModel) ?: bakedModel
// Register the model into the game, so it can be used in any block/item that uses the same model id
event.modelRegistry[modelId] = finalModel
}
// Share models
sharedModels.forEach { (destine, origin) ->
val model = event.modelRegistry[origin]
if (model != null) {
event.modelRegistry[destine] = model
} else {
ModelLoaderMod.logger.error("Unable to share model $origin, it doesn't exist")
}
}
try {
ModLoader.get().postEvent(ModelRetrieveEvent(loadedModels))
} catch (e: Exception) {
ModelLoaderMod.logger.error("Error in ModelRetrieveEvent, some models may be missing, check the log for details")
}
}
/**
* Internal method: bake models and create animations
*/
private fun processModel(model: PreBakeModel, loader: ModelLoader): PostBakeModel {
val baked = if (model.pre.bake){
bakeModel(model.unbaked, loader, model.pre.rotation)
}
else {
null
}
val animations = if (model.pre.animate && model.unbaked is AnimatableModel) {
model.unbaked.getAnimations()
} else {
emptyMap()
}
val mutable = if (model.pre.mutable && model.unbaked is MutableModelConversion) {
model.unbaked.toMutable(ModelLoader.defaultTextureGetter(), DefaultVertexFormats.ITEM)
} else {
null
}
return PostBakeModel(model.modelId, model.pre, baked, animations, mutable)
}
/**
* Bake a single model
*/
fun bakeModel(model: IUnbakedModel, loader: ModelLoader, rotation: ISprite): IBakedModel? {
return model.bake(loader, ModelLoader.defaultTextureGetter(), rotation, DefaultVertexFormats.ITEM)
}
}
|
gpl-2.0
|
be104a7bc71751d376ae1fbfa9edb1cd
| 33.604167 | 125 | 0.640819 | 4.743004 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/collection/MapGeneImpact.kt
|
1
|
2788
|
package org.evomaster.core.search.impact.impactinfocollection.value.collection
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.collection.MapGene
import org.evomaster.core.search.impact.impactinfocollection.*
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.IntegerGeneImpact
/**
* created by manzh on 2019-09-09
*
* TODO need to further extend for elements
*
* MapGeneImpact now is shared by FixedMapGene and FlexibleMapGene
* now only consider impacts of different size
*/
class MapGeneImpact(sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo,
val sizeImpact : IntegerGeneImpact = IntegerGeneImpact("size")
) : CollectionImpact, GeneImpact(sharedImpactInfo, specificImpactInfo){
constructor(
id : String
) : this(SharedImpactInfo(id), SpecificImpactInfo())
override fun getSizeImpact(): Impact = sizeImpact
override fun copy(): MapGeneImpact {
return MapGeneImpact(
shared.copy(),
specific.copy(),
sizeImpact = sizeImpact.copy())
}
override fun clone(): MapGeneImpact {
return MapGeneImpact(
shared.clone(),
specific.clone(),
sizeImpact.clone()
)
}
override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext, noImpactTargets: Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) {
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.previous == null && impactTargets.isNotEmpty()) return
if(gc.current !is MapGene<*, *>)
throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be MapGene")
if (gc.previous != null && gc.previous !is MapGene<*, *>)
throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be MapGene")
if (gc.previous != null && (gc.previous as MapGene<*, *>).getAllElements().size != gc.current.getAllElements().size)
sizeImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
//TODO for elements
}
override fun validate(gene: Gene): Boolean = gene is MapGene<*, *>
override fun flatViewInnerImpact(): Map<String, Impact> {
return mutableMapOf("${getId()}-${sizeImpact.getId()}" to sizeImpact)
}
override fun innerImpacts(): List<Impact> {
return listOf(sizeImpact)
}
}
|
lgpl-3.0
|
40d20fe308f316b0382dba247faafdb3
| 41.907692 | 198 | 0.697991 | 4.908451 | false | false | false | false |
wuan/bo-android
|
app/src/main/java/org/blitzortung/android/data/beans/Station.kt
|
1
|
1563
|
/*
Copyright 2015 Andreas Würl
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.blitzortung.android.data.beans
class Station(
override val longitude: Double,
override val latitude: Double,
val name: String,
val offlineSince: Long
) : Location {
val state: State
get() {
return if (offlineSince == OFFLINE_SINCE_NOT_SET) {
State.ON
} else {
val now = System.currentTimeMillis()
val minutesAgo = (now - offlineSince) / 1000 / 60
when {
minutesAgo > 24 * 60 -> {
State.OFF
}
minutesAgo > 15 -> {
State.DELAYED
}
else -> {
State.ON
}
}
}
}
enum class State {
ON, DELAYED, OFF
}
companion object {
const val OFFLINE_SINCE_NOT_SET: Long = -1
}
}
|
apache-2.0
|
7517caac422228f53845a75a3bd9f963
| 25.931034 | 75 | 0.538412 | 4.974522 | false | false | false | false |
Litote/kmongo
|
kmongo-property/src/main/kotlin/org/litote/kmongo/Properties.kt
|
1
|
3780
|
/*
* Copyright (C) 2016/2022 Litote
*
* 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.litote.kmongo
import org.litote.kmongo.property.KCollectionSimplePropertyPath
import org.litote.kmongo.property.KMapSimplePropertyPath
import org.litote.kmongo.property.KPropertyPath
import org.litote.kmongo.service.ClassMappingType
import kotlin.reflect.KProperty
import kotlin.reflect.KProperty1
/**
* Returns a composed property. For example Friend.address / Address.postalCode = "address.postalCode".
*/
operator fun <T0, T1, T2> KProperty1<T0, T1?>.div(p2: KProperty1<T1, T2?>): KProperty1<T0, T2?> =
KPropertyPath(this, p2)
/**
* Returns a composed property without type checks. For example Friend.address % Address.postalCode = "address.postalCode".
*/
operator fun <T0, T1, T2> KProperty1<T0, T1?>.rem(p2: KProperty1<out T1, T2?>): KProperty1<T0, T2?> =
KPropertyPath(this, p2)
/**
* Returns a collection composed property. For example Friend.addresses / Address.postalCode = "addresses.postalCode".
*/
@JvmName("divCol")
operator fun <T0, T1, T2> KProperty1<T0, Iterable<T1>?>.div(p2: KProperty1<out T1, T2?>): KProperty1<T0, T2?> =
KPropertyPath(this, p2)
/**
* Returns a map composed property. For example Friend.addresses / Address.postalCode = "addresses.postalCode".
*/
@JvmName("divMap")
operator fun <T0, K, T1, T2> KProperty1<T0, Map<out K, T1>?>.div(p2: KProperty1<out T1, T2?>): KProperty1<T0, T2?> =
KPropertyPath(this, p2)
/**
* Returns a mongo path of a property.
*/
fun <T> KProperty<T>.path(): String =
(this as? KPropertyPath<*, T>)?.path ?: ClassMappingType.getPath(this)
/**
* Returns a collection property.
*/
val <T> KProperty1<out Any?, Iterable<T>?>.colProperty: KCollectionSimplePropertyPath<out Any?, T>
get() = KCollectionSimplePropertyPath(null, this)
/**
* In order to write array indexed expressions (like `accesses.0.timestamp`).
*/
fun <T> KProperty1<out Any?, Iterable<T>?>.pos(position: Int): KPropertyPath<out Any?, T?> =
colProperty.pos(position)
/**
* Returns a map property.
*/
val <K, T> KProperty1<out Any?, Map<out K, T>?>.mapProperty: KMapSimplePropertyPath<out Any?, K, T>
get() = KMapSimplePropertyPath(null, this)
/**
* [The positional array operator $ (projection or update)](https://docs.mongodb.com/manual/reference/operator/update/positional/)
*/
val <T> KProperty1<out Any?, Iterable<T>?>.posOp: KPropertyPath<out Any?, T?> get() = colProperty.posOp
/**
* [The all positional operator $[]](https://docs.mongodb.com/manual/reference/operator/update/positional-all/)
*/
val <T> KProperty1<out Any?, Iterable<T>?>.allPosOp: KPropertyPath<out Any?, T?> get() = colProperty.allPosOp
/**
* [The filtered positional operator $[<identifier>]](https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/)
*/
fun <T> KProperty1<out Any?, Iterable<T>?>.filteredPosOp(identifier: String): KPropertyPath<out Any?, T?> =
colProperty.filteredPosOp(identifier)
/**
* Key projection of map.
* Sample: `p.keyProjection(Locale.ENGLISH) / Gift::amount`
*/
@Suppress("UNCHECKED_CAST")
fun <K, T> KProperty1<out Any?, Map<out K, T>?>.keyProjection(key: K): KPropertyPath<Any?, T?> =
mapProperty.keyProjection(key) as KPropertyPath<Any?, T?>
|
apache-2.0
|
95a9c4e37a2c40b0f8c2c978450b106f
| 37.581633 | 133 | 0.718783 | 3.378016 | false | false | false | false |
proxer/ProxerLibAndroid
|
library/src/main/kotlin/me/proxer/library/internal/adapter/ConferenceAdapter.kt
|
2
|
2097
|
package me.proxer.library.internal.adapter
import com.squareup.moshi.FromJson
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.ToJson
import me.proxer.library.entity.messenger.Conference
import java.util.Date
/**
* @author Ruben Gees
*/
internal class ConferenceAdapter {
private companion object {
private const val IMAGE_DELIMITER = ":"
}
@FromJson
fun fromJson(json: IntermediateConference): Conference {
return Conference(
json.id, json.topic, json.customTopic, json.participantAmount, json.image, json.imageType,
json.isGroup, json.isRead, json.date, json.unreadMessageAmount, json.lastReadMessageId
)
}
@ToJson
fun toJson(value: Conference): IntermediateConference {
return IntermediateConference(
id = value.id,
topic = value.topic,
customTopic = value.customTopic,
participantAmount = value.participantAmount,
isGroup = value.isGroup,
isRead = value.isRead,
date = value.date,
unreadMessageAmount = value.unreadMessageAmount,
lastReadMessageId = value.lastReadMessageId,
rawImage = value.imageType + IMAGE_DELIMITER + value.image
)
}
@JsonClass(generateAdapter = true)
internal data class IntermediateConference(
@Json(name = "id") val id: String,
@Json(name = "topic") val topic: String,
@Json(name = "topic_custom") val customTopic: String,
@Json(name = "count") val participantAmount: Int,
@Json(name = "group") val isGroup: Boolean,
@Json(name = "read") val isRead: Boolean,
@Json(name = "timestamp_end") val date: Date,
@Json(name = "read_count") val unreadMessageAmount: Int,
@Json(name = "read_mid") val lastReadMessageId: String,
@Json(name = "image") val rawImage: String
) {
val imageType = rawImage.substringBefore(IMAGE_DELIMITER, "")
val image = rawImage.substringAfter(IMAGE_DELIMITER, "")
}
}
|
gpl-3.0
|
c68175532e94c6634f6e53d16ff83618
| 33.95 | 102 | 0.649022 | 4.305955 | false | false | false | false |
vjache/klips
|
src/test/java/org/klips/dsl/IffRulesTest.kt
|
1
|
824
|
package org.klips.dsl
import org.junit.Test
import org.klips.dsl.ActivationFilter.Both
import org.klips.engine.Adjacent
import org.klips.engine.CellId
import org.klips.engine.util.Log
class IffRulesTest {
@Test
fun adjacencySymmetry() {
val rs = rules(Log(workingMemory = true, agenda = true)) {
val cid = ref<CellId>("cid")
val cid1 = ref<CellId>("cid1")
rule("Adj-Symmetry") {
+Adjacent(cid, cid1)
effect(activation = Both) {
!Adjacent(cid1, cid)
}
}
}
rs.input.flush("Adj-Symmetry") {
+Adjacent(CellId(0).facet, CellId(1).facet)
}
rs.input.flush("Adj-Symmetry") {
-Adjacent(CellId(0).facet, CellId(1).facet)
}
}
}
|
apache-2.0
|
c5877ef83a950884cb20383c25a4e598
| 22.571429 | 66 | 0.543689 | 3.662222 | false | true | false | false |
k-thorat/Vanilla
|
examples/Android/app/src/main/java/com/example/flavours/ItemDetailFragment.kt
|
1
|
1837
|
package com.example.flavours
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.flavours.dummy.DummyContent
import kotlinx.android.synthetic.main.activity_item_detail.*
import kotlinx.android.synthetic.main.item_detail.view.*
/**
* A fragment representing a single Item detail screen.
* This fragment is either contained in a [ItemListActivity]
* in two-pane mode (on tablets) or a [ItemDetailActivity]
* on handsets.
*/
class ItemDetailFragment : Fragment() {
/**
* The dummy content this fragment is presenting.
*/
private var item: DummyContent.DummyItem? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
if (it.containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
item = DummyContent.ITEM_MAP[it.getString(ARG_ITEM_ID)]
activity?.toolbar_layout?.title = item?.content
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.item_detail, container, false)
// Show the dummy content as text in a TextView.
item?.let {
rootView.item_detail.text = it.details
}
return rootView
}
companion object {
/**
* The fragment argument representing the item ID that this fragment
* represents.
*/
const val ARG_ITEM_ID = "item_id"
}
}
|
mit
|
4f950237450403d3f23eddd711d9f298
| 29.633333 | 79 | 0.649428 | 4.524631 | false | false | false | false |
VerifAPS/verifaps-lib
|
util/src/main/kotlin/edu/kit/iti/formal/util/fuzzystring.kt
|
1
|
5576
|
package edu.kit.iti.formal.util
import java.util.*
/* Copyright (c) 2012 Kevin L. Stern
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* The Damerau-Levenshtein Algorithm is an extension to the Levenshtein
* Algorithm which solves the edit distance problem between a source string and
* a target string with the following operations:
*
*
* * Character Insertion
* * Character Deletion
* * Character Replacement
* * Adjacent Character Swap
*
*
* Note that the adjacent character swap operation is an edit that may be
* applied when two adjacent characters in the source string match two adjacent
* characters in the target string, but in reverse order, rather than a general
* allowance for adjacent character swaps.
*
*
*
* This implementation allows the client to specify the costs of the various
* edit operations with the restriction that the cost of two swap operations
* must not be less than the cost of a delete operation followed by an insert
* operation. This restriction is required to preclude two swaps involving the
* same character being required for optimality which, in turn, enables a fast
* dynamic programming solution.
*
*
*
* The running time of the Damerau-Levenshtein algorithm is O(n*m) where n is
* the length of the source string and m is the length of the target string.
* This implementation consumes O(n*m) space.
*
* @author Kevin L. Stern
*/
fun dlevenshtein(source: String, target: String,
deleteCost: Int = 1, insertCost: Int = 1,
replaceCost: Int = 1, swapCost: Int = 1): Int {
/*
* Required to facilitate the premise to the algorithm that two swaps of the
* same character are never required for optimality.
*/
if (2 * swapCost < insertCost + deleteCost) {
throw IllegalArgumentException("Unsupported cost assignment")
}
if (source.length == 0) {
return target.length * insertCost
}
if (target.length == 0) {
return source.length * deleteCost
}
val table = Array(source.length) { IntArray(target.length) }
val sourceIndexByCharacter = HashMap<Char, Int>()
if (source[0] != target[0]) {
table[0][0] = Math.min(replaceCost, deleteCost + insertCost)
}
sourceIndexByCharacter[source[0]] = 0
for (i in 1 until source.length) {
val deleteDistance = table[i - 1][0] + deleteCost
val insertDistance = (i + 1) * deleteCost + insertCost
val matchDistance = i * deleteCost + if (source[i] == target[0]) 0 else replaceCost
table[i][0] = Math.min(Math.min(deleteDistance, insertDistance),
matchDistance)
}
for (j in 1 until target.length) {
val deleteDistance = (j + 1) * insertCost + deleteCost
val insertDistance = table[0][j - 1] + insertCost
val matchDistance = j * insertCost + if (source[0] == target[j]) 0 else replaceCost
table[0][j] = Math.min(Math.min(deleteDistance, insertDistance),
matchDistance)
}
for (i in 1 until source.length) {
var maxSourceLetterMatchIndex = if (source[i] == target[0])
0
else
-1
for (j in 1 until target.length) {
val candidateSwapIndex = sourceIndexByCharacter[target[j]]
val jSwap = maxSourceLetterMatchIndex
val deleteDistance = table[i - 1][j] + deleteCost
val insertDistance = table[i][j - 1] + insertCost
var matchDistance = table[i - 1][j - 1]
if (source[i] != target[j]) {
matchDistance += replaceCost
} else {
maxSourceLetterMatchIndex = j
}
val swapDistance: Int
if (candidateSwapIndex != null && jSwap != -1) {
val preSwapCost: Int
if (candidateSwapIndex == 0 && jSwap == 0) {
preSwapCost = 0
} else {
preSwapCost = table[Math.max(0, candidateSwapIndex - 1)][Math.max(0, jSwap - 1)]
}
swapDistance = (preSwapCost + (i - candidateSwapIndex - 1) * deleteCost
+ (j - jSwap - 1) * insertCost + swapCost)
} else {
swapDistance = Integer.MAX_VALUE
}
table[i][j] = Math.min(Math.min(Math
.min(deleteDistance, insertDistance), matchDistance), swapDistance)
}
sourceIndexByCharacter[source[i]] = i
}
return table[source.length - 1][target.length - 1]
}
|
gpl-3.0
|
2462b8588c83662e186d5246565e9c53
| 41.564885 | 100 | 0.646521 | 4.173653 | false | false | false | false |
elect86/modern-jogl-examples
|
src/main/kotlin/glNext/tut05/baseVertexOverlap.kt
|
2
|
7114
|
package glNext.tut05
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.*
import main.framework.Framework
import uno.buffer.*
import uno.glsl.programOf
import glm.vec._3.Vec3
/**
* Created by elect on 22/02/17.
*/
fun main(args: Array<String>) {
BaseVertexOverlap_Next().setup("Tutorial 05 - Base Vertex With Overlap")
}
class BaseVertexOverlap_Next : Framework() {
object Buffer {
val VERTEX = 0
val INDEX = 1
val MAX = 2
}
var theProgram = 0
var offsetUniform = 0
var perspectiveMatrixUnif = 0
val numberOfVertices = 36
val perspectiveMatrix = FloatArray(16)
val frustumScale = 1.0f
val bufferObject = intBufferBig(Buffer.MAX)
val vao = intBufferBig(1)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeBuffers(gl)
initVertexArray(vao){
val colorData = Vec3.SIZE * numberOfVertices
array(bufferObject[Buffer.VERTEX], glf.pos3_col4, 0, colorData)
element(bufferObject[Buffer.INDEX])
}
cullFace {
enable()
cullFace = back
frontFace = cw
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut05", "standard.vert", "standard.frag")
withProgram(theProgram) {
offsetUniform = "offset".location
perspectiveMatrixUnif = "perspectiveMatrix".location
val zNear = 1.0f
val zFar = 3.0f
perspectiveMatrix[0] = frustumScale
perspectiveMatrix[5] = frustumScale
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar)
perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar)
perspectiveMatrix[11] = -1.0f
use { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) }
}
}
fun initializeBuffers(gl: GL3) = with(gl) {
glGenBuffers(bufferObject)
withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) }
withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) }
}
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
withVertexArray(vao) {
glUniform3f(offsetUniform)
glDrawElements(indexData.capacity(), GL_UNSIGNED_SHORT)
glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f)
glDrawElementsBaseVertex(indexData.capacity(), GL_UNSIGNED_SHORT, 0, numberOfVertices / 2)
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
perspectiveMatrix[0] = frustumScale * (h / w.f)
perspectiveMatrix[5] = frustumScale
usingProgram(theProgram) { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) }
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffers(bufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vao, bufferObject, vertexData, indexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
val RIGHT_EXTENT = 0.8f
val LEFT_EXTENT = -RIGHT_EXTENT
val TOP_EXTENT = 0.20f
val MIDDLE_EXTENT = 0.0f
val BOTTOM_EXTENT = -TOP_EXTENT
val FRONT_EXTENT = -1.25f
val REAR_EXTENT = -1.75f
val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f)
val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f)
val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f)
val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f)
val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f)
val vertexData = floatBufferOf(
//Object 1 positions
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
//Object 2 positions
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
//Object 1 colors
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
//Object 2 colors
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR)
val indexData = shortBufferOf(
0, 2, 1,
3, 2, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
11, 13, 12,
14, 16, 15,
17, 16, 14)
}
|
mit
|
34a839b86173f82b34f3b97043f0ae5e
| 26.260536 | 106 | 0.564099 | 3.992144 | false | false | false | false |
googlemaps/android-maps-rx
|
places-rx/src/main/java/com/google/maps/android/rx/places/PlacesClientFindCurrentPlaceSingle.kt
|
1
|
1723
|
package com.google.maps.android.rx.places
import androidx.annotation.RequiresPermission
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.maps.android.rx.places.internal.MainThreadTaskSingle
import com.google.maps.android.rx.places.internal.TaskCompletionListener
import io.reactivex.rxjava3.core.Single
/**
* Finds the current place and emits it in a [Single].
*
* @param placeFields the fields to return for the retrieved Place
* @return the Single emitting the current place
*/
@RequiresPermission(allOf = ["android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_WIFI_STATE"])
public fun PlacesClient.findCurrentPlace(
placeFields: List<Place.Field>
): Single<FindCurrentPlaceResponse> =
PlacesClientFindCurrentPlaceSingle(
placesClient = this,
placeFields = placeFields,
)
private class PlacesClientFindCurrentPlaceSingle(
private val placesClient: PlacesClient,
private val placeFields: List<Place.Field>
) : MainThreadTaskSingle<FindCurrentPlaceResponse>() {
@RequiresPermission(allOf = ["android.permission.ACCESS_FINE_LOCATION", "android.permission.ACCESS_WIFI_STATE"])
override fun invokeRequest(listener: TaskCompletionListener<FindCurrentPlaceResponse>) {
val request = FindCurrentPlaceRequest.builder(placeFields)
.setCancellationToken(listener.cancellationTokenSource.token)
.build()
placesClient.findCurrentPlace(request).addOnCompleteListener(listener)
}
}
|
apache-2.0
|
42d1ac5504968430afe66f8cfd38fb6a
| 44.368421 | 116 | 0.790482 | 4.318296 | false | false | false | false |
monzee/fist
|
fist-kt-android/src/main/java/ph/codeia/fist/ActionDsl.kt
|
1
|
2052
|
package ph.codeia.fist
/*
* This file is a part of the fist project.
*/
@DslMarker
annotation class ActionDsl
@ActionDsl
class MealyScope<S, E : Effects<S>> {
val noop: Mi<S, E> by lazy(LazyThreadSafetyMode.NONE) { Mi.noop<S, E>() }
val reenter: Mi<S, E> by lazy(LazyThreadSafetyMode.NONE) { Mi.reenter<S, E>() }
val enter: (S) -> Mi<S, E> = { Mi.enter(it) }
val forward: (Mi.Action<S, E>) -> Mi<S, E> = { Mi.forward(it) }
val raise: (Throwable) -> Mi<S, E> = { Mi.raise(it) }
inline fun await(
crossinline block: () -> Mi<S, E>
): Mi<S, E> = Mi.async {
val result = block()
Mi.Action<S, E> { _, _ -> result }
}
inline fun awaitAction(
crossinline block: () -> Mi.Action<S, E>
): Mi<S, E> = Mi.async {
block()
}
inline fun defer(
crossinline block: Mi.Continuation<S, E>.() -> Unit
): Mi<S, E> = Mi.defer {
block(it)
}
operator fun Mi<S, E>.plus(next: Mi<S, E>): Mi<S, E> = then(next)
operator fun Mi<S, E>.plus(next: Mi.Action<S, E>): Mi<S, E> = then(next)
}
@ActionDsl
class MooreScope<S> {
val noop: Mu<S> by lazy(LazyThreadSafetyMode.NONE) { Mu.noop<S>() }
val reenter: Mu<S> by lazy(LazyThreadSafetyMode.NONE) { Mu.reenter<S>() }
val enter: (S) -> Mu<S> = { Mu.enter(it) }
val forward: (Mu.Action<S>) -> Mu<S> = { Mu.forward(it) }
val raise: (Throwable) -> Mu<S> = { Mu.raise(it) }
fun enterMany(vararg states: S?): Mu<S> = Mu.enterMany(*states)
inline fun await(
crossinline block: () -> Mu<S>
): Mu<S> = Mu.async {
val result = block()
Mu.Action<S> { result }
}
inline fun awaitAction(
crossinline block: () -> Mu.Action<S>
): Mu<S> = Mu.async {
block()
}
inline fun defer(
crossinline block: Mu.Continuation<S>.() -> Unit
): Mu<S> = Mu.defer {
block(it)
}
operator fun Mu<S>.plus(next: Mu<S>): Mu<S> = then(next)
operator fun Mu<S>.plus(next: Mu.Action<S>): Mu<S> = then(next)
}
|
mit
|
4df320fa07d1e9435543584a1dec0352
| 25.307692 | 83 | 0.548733 | 2.948276 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/ChooseExecutor.kt
|
1
|
1609
|
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils
import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.cleanUpForOutput
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions
import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.ChooseCommand
class ChooseExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) {
inner class Options : LocalizedApplicationCommandOptions(loritta) {
val choices = stringList(
"choice",
ChooseCommand.I18N_PREFIX.Options.Choice,
minimum = 2, maximum = 25
)
}
override val options = Options()
override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) {
val options = args[options.choices]
context.sendReply(
content = context.i18nContext.get(
ChooseCommand.I18N_PREFIX.Result(
result = cleanUpForOutput(context, options.random()),
emote = Emotes.LoriYay
)
),
prefix = Emotes.LoriHm
)
}
}
|
agpl-3.0
|
c789c07017fc8f7a3e4c26e910523e02
| 43.722222 | 114 | 0.742076 | 5.190323 | false | false | false | false |
etesync/android
|
app/src/main/java/com/etesync/syncadapter/ui/setup/LoginCredentialsFragment.kt
|
1
|
5029
|
/*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.ui.setup
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckedTextView
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.fragment.app.replace
import com.etesync.syncadapter.Constants
import com.etesync.syncadapter.R
import com.etesync.syncadapter.ui.WebViewActivity
import com.etesync.syncadapter.ui.etebase.SignupFragment
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import net.cachapa.expandablelayout.ExpandableLayout
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import java.net.URI
class LoginCredentialsFragment : Fragment() {
internal lateinit var editUserName: EditText
internal lateinit var editUrlPassword: TextInputLayout
internal lateinit var showAdvanced: CheckedTextView
internal lateinit var customServer: EditText
internal var initialUsername: String? = null
internal var initialPassword: String? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.login_credentials_fragment, container, false)
editUserName = v.findViewById<TextInputEditText>(R.id.user_name)
editUrlPassword = v.findViewById<TextInputLayout>(R.id.url_password)
showAdvanced = v.findViewById<CheckedTextView>(R.id.show_advanced)
customServer = v.findViewById<TextInputEditText>(R.id.custom_server)
if (savedInstanceState == null) {
editUserName.setText(initialUsername ?: "")
editUrlPassword.editText?.setText(initialPassword ?: "")
}
val createAccount = v.findViewById<View>(R.id.create_account) as Button
createAccount.setOnClickListener {
parentFragmentManager.commit {
replace(android.R.id.content, SignupFragment.newInstance(editUserName.text.toString(), editUrlPassword.editText?.text.toString()))
}
}
val login = v.findViewById<View>(R.id.login) as Button
login.setOnClickListener {
val credentials = validateLoginData()
if (credentials != null)
DetectConfigurationFragment.newInstance(credentials).show(fragmentManager!!, null)
}
val forgotPassword = v.findViewById<View>(R.id.forgot_password) as TextView
forgotPassword.setOnClickListener { WebViewActivity.openUrl(context!!, Constants.forgotPassword) }
val advancedLayout = v.findViewById<View>(R.id.advanced_layout) as ExpandableLayout
showAdvanced.setOnClickListener {
if (showAdvanced.isChecked) {
showAdvanced.isChecked = false
advancedLayout.collapse()
} else {
showAdvanced.isChecked = true
advancedLayout.expand()
}
}
return v
}
protected fun validateLoginData(): LoginCredentials? {
var valid = true
val userName = editUserName.text.toString()
if (userName.isEmpty()) {
editUserName.error = getString(R.string.login_email_address_error)
valid = false
} else {
editUserName.error = null
}
val password = editUrlPassword.editText?.text.toString()
if (password.isEmpty()) {
editUrlPassword.error = getString(R.string.login_password_required)
valid = false
} else {
editUrlPassword.error = null
}
var uri: URI? = null
if (showAdvanced.isChecked) {
val server = customServer.text.toString()
// If this field is null, just use the default
if (!server.isEmpty()) {
val url = server.toHttpUrlOrNull()
if (url != null) {
uri = url.toUri()
customServer.error = null
} else {
customServer.error = getString(R.string.login_custom_server_error)
valid = false
}
}
}
return if (valid) LoginCredentials(uri, userName, password) else null
}
companion object {
fun newInstance(initialUsername: String?, initialPassword: String?): LoginCredentialsFragment {
val ret = LoginCredentialsFragment()
ret.initialUsername = initialUsername
ret.initialPassword = initialPassword
return ret
}
}
}
|
gpl-3.0
|
73cc0f09daa79ae34e507291b219dd5a
| 36.507463 | 146 | 0.668524 | 4.870155 | false | false | false | false |
MaibornWolff/codecharta
|
analysis/filter/StructureModifier/src/main/kotlin/de/maibornwolff/codecharta/filter/structuremodifier/FolderMover.kt
|
1
|
4996
|
package de.maibornwolff.codecharta.filter.structuremodifier
import de.maibornwolff.codecharta.model.AttributeDescriptor
import de.maibornwolff.codecharta.model.AttributeType
import de.maibornwolff.codecharta.model.BlacklistItem
import de.maibornwolff.codecharta.model.Edge
import de.maibornwolff.codecharta.model.MutableNode
import de.maibornwolff.codecharta.model.NodeType
import de.maibornwolff.codecharta.model.Project
import de.maibornwolff.codecharta.model.ProjectBuilder
import mu.KotlinLogging
class FolderMover(private val project: Project) {
private val logger = KotlinLogging.logger { }
private var toMove: List<MutableNode>? = null
fun move(moveFrom: String?, moveTo: String?): Project? {
if ((moveFrom == null) || (moveTo == null)) {
logger.error("In order to move nodes, both source and destination need to be set.")
return null
}
return ProjectBuilder(
moveNodes(moveFrom, moveTo),
extractEdges(moveFrom, moveTo),
copyAttributeTypes(),
copyAttributeDescriptors(),
copyBlacklist(moveFrom, moveTo)
).build()
}
private fun getPathSegments(path: String): List<String> {
return path.removePrefix("/").split("/").filter { it.isNotEmpty() }
}
private fun moveNodes(moveFrom: String, moveTo: String): List<MutableNode> {
val originPath = getPathSegments(moveFrom)
val destinationPath = getPathSegments(moveTo)
val rootNode = project.rootNode.toMutableNode()
val newStructure = removeMovedNodeFromStructure(originPath, rootNode)
?: MutableNode("root", type = NodeType.Folder)
val newStructureList = listOfNotNull(newStructure)
if (toMove == null) {
logger.warn("Path to move was not found in project. No nodes are therefore moved")
} else {
insertInNewStructure(destinationPath.drop(1), newStructure)
}
return newStructureList
}
private fun removeMovedNodeFromStructure(originPath: List<String>, node: MutableNode): MutableNode? {
return if (originPath.isEmpty() || originPath.first() != node.name) {
node
} else if (originPath.size == 1) {
toMove = node.children.toMutableList()
null
} else {
node.children = node.children.mapNotNull { child -> removeMovedNodeFromStructure(originPath.drop(1), child) }.toMutableSet()
node
}
}
private fun insertInNewStructure(destinationPath: List<String>, node: MutableNode) {
if (destinationPath.isEmpty()) {
val destinationNodeNamesAndType: HashMap<String, NodeType?> = hashMapOf()
node.children.forEach { destinationNodeNamesAndType[it.name] = it.type }
val filteredNodesToMove = toMove!!.filter {
!(destinationNodeNamesAndType.containsKey(it.name) && destinationNodeNamesAndType[it.name] == it.type)
}
if (filteredNodesToMove.size < toMove!!.size) {
logger.warn("Some nodes are already available in the target location, they were not moved and discarded instead.")
}
node.children.addAll(filteredNodesToMove)
} else {
var chosenChild: MutableNode? = node.children.filter { destinationPath.first() == it.name }.firstOrNull()
if (chosenChild == null) {
node.children.add(MutableNode(destinationPath.first(), type = NodeType.Folder))
chosenChild = node.children.firstOrNull { destinationPath.first() == it.name }
}
insertInNewStructure(destinationPath.drop(1), chosenChild!!)
}
}
private fun extractEdges(from: String, to: String): MutableList<Edge> {
val sanitizedFrom = "/" + from.removeSuffix("/").removePrefix("/")
val sanitizedTo = "/" + to.removeSuffix("/").removePrefix("/")
return project.edges.map { edge ->
edge.fromNodeName = edge.fromNodeName.replace(sanitizedFrom, sanitizedTo)
edge.toNodeName = edge.toNodeName.replace(sanitizedFrom, sanitizedTo)
edge
}.toMutableList()
}
private fun copyAttributeTypes(): MutableMap<String, MutableMap<String, AttributeType>> {
val mergedAttributeTypes: MutableMap<String, MutableMap<String, AttributeType>> = mutableMapOf()
project.attributeTypes.forEach {
mergedAttributeTypes[it.key] = it.value
}
return mergedAttributeTypes.toMutableMap()
}
private fun copyAttributeDescriptors(): MutableMap<String, AttributeDescriptor> {
return project.attributeDescriptors.toMutableMap()
}
private fun copyBlacklist(from: String, to: String): MutableList<BlacklistItem> {
return project.blacklist.map { blacklistItem ->
blacklistItem.path = blacklistItem.path.replace(from, to)
blacklistItem
}.toMutableList()
}
}
|
bsd-3-clause
|
0b3797bf3712f5a88baf531ae8982b9f
| 41.338983 | 136 | 0.661129 | 4.817743 | false | false | false | false |
DataDozer/DataDozer
|
core/src/main/kotlin/org/datadozer/Pools.kt
|
1
|
6147
|
package org.datadozer
import java.lang.IllegalStateException
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/*
* Licensed to DataDozer under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. DataDozer licenses this file to you 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.
*/
/**
* Provides a application specific thread pool where all the threads
* are numbered. This pool is used along with the object pool to
* provide no lock based object pool.
*/
fun threadPoolExecutorProvider(): ThreadPoolExecutor {
// Custom thread factory to ensure that
val threadFactory = object : ThreadFactory {
val counter = AtomicInteger(-1)
override fun newThread(r: Runnable?): Thread {
val t = Thread(r)
t.name = counter.incrementAndGet().toString()
return t
}
}
return ThreadPoolExecutor(AvailableProcessors, AvailableProcessors,
0L, TimeUnit.MILLISECONDS,
LinkedBlockingQueue<Runnable>(1000), threadFactory)
}
/**
* A fast int parser which only works in limited cases. It expects the numbers
* to be small and positive. Do not use it for parsing any user data. It is used
* by various pools to parse the thread name.
* NOTE:
* - This class does not do any overflow, null or empty string checks
* - We always assume the number is correctly formatted
*/
@Suppress("NOTHING_TO_INLINE")
inline fun fastIntParser(value: String): Int {
// Unroll the first run of the loop
var ch = value[0]
var v = '0' - ch
for (i in 1 until value.length) {
ch = value[i]
if (i > 0) {
v *= 10
}
v += '0' - ch
}
return -v
}
/**
* Returns the custom thread id associated with the current thread. This is only useful
* for the threads from our custom thread pool.
*/
@Suppress("NOTHING_TO_INLINE")
inline fun getThreadId(): Int {
try {
return fastIntParser(Thread.currentThread().name)
} catch (e: Exception) {
throw IllegalStateException("Object pool can only be accessed with specialized threads.")
}
}
/**
* This is a lock free object pool which only maintains one object per thread.
* In this regard this is not a generalized object pool. In concept it is similar
* to thread local variables but without the risk of leaking memory.
*
* @param provider
* Provider to create new pool items
*/
class SingleInstancePerThreadObjectPool<T : Any?>(private val provider: () -> T) {
private val logger = logProvider<SingleInstancePerThreadObjectPool<T>>()
private val pool = ArrayList<T>(AvailableProcessors)
// Tracks if an item is borrowed by a thread or not. Strictly speaking this is
// not necessary. We don't even need the return functionality as the pool will always
// hold an reference to the object. This is to avoid nasty problems in future if we have
// the same thread modifying the same object at more than one place without recycling it.
// We need strict discipline that the objects are always returned in the finally block.
private val borrowStatus = Array(AvailableProcessors, { _ -> false })
init {
for (i in 0 until AvailableProcessors) {
pool.add(provider())
}
}
/**
* Borrow an object from the pool. Make sure you only borrow the item once per thread.
* Borrowing more than once per thread will result in an error. Items should only
* be borrowed for a very short span of time.
*/
fun borrowObject(slotNumber: Int? = null): T {
val threadId = slotNumber ?: getThreadId()
val item = pool[threadId]
return if (!borrowStatus[threadId]) {
borrowStatus[threadId] = true
item
} else {
// This essentially means that we are borrowing an object from the same thread more than once without
// returning it back to the pool. Ideally this should never happen and the objects should be returned.
// The best way to recover is to give a new object back to the caller and log a warning.
logger.warn("Expecting object pool thread slot to have a value. Make sure you are not borrowing twice.")
provider()
}
}
/**
* Borrow an object from the pool and pass it to an action and automatically
* return the object back to the pool
*/
inline fun borrow(block: (T) -> Unit) {
val borrowed = borrowObject()
try {
block(borrowed)
} finally {
returnObject(borrowed)
}
}
/**
* Return an borrowed object to the pool. Never return an object twice as it will result
* in an error.
*/
fun returnObject(item: T, slotNumber: Int? = null) {
if (item == null) {
return
}
val threadId = slotNumber ?: getThreadId()
if (!borrowStatus[threadId]) {
logger.warn(
"Expecting object pool thread slot to be empty. Make sure you are not returning twice or returning a non pooled object.")
}
// Irrespective of whether the item was returned twice the best way to recover from the situation is to
// take the object and set the borrow status to false.
pool[threadId] = item
borrowStatus[threadId] = false
}
}
|
apache-2.0
|
c60ecdea8a8dd723bd6ed9275a66995a
| 36.260606 | 141 | 0.666992 | 4.57026 | false | false | false | false |
christophpickl/kpotpourri
|
github4k/src/main/kotlin/com/github/christophpickl/kpotpourri/github/internal/model.kt
|
1
|
1401
|
package com.github.christophpickl.kpotpourri.github.internal
import com.github.christophpickl.kpotpourri.common.KotlinNoArg
import com.github.christophpickl.kpotpourri.github.Issue
import com.github.christophpickl.kpotpourri.github.Milestone
import com.github.christophpickl.kpotpourri.github.State
@KotlinNoArg
internal annotation class JsonData
internal @JsonData data class MilestoneJson(
val title: String,
val number: Int,
val state: String,
val url: String
) {
fun toMilestone() = Milestone(
version = title,
number = number,
state = State.byJsonValue(state),
url = url
)
}
internal @JsonData data class IssueJson(
val title: String,
val number: Int,
val state: String, // "open", "closed"
val milestone: MilestoneJson? = null
) {
fun toIssue() = Issue(
title = title,
number = number,
state = State.byJsonValue(state),
milestone = milestone?.toMilestone()
)
}
internal @JsonData data class UpdateMilestoneRequestJson(
val state: String
)
internal @JsonData data class UpdateMilestoneResponseJson(
val state: String
)
internal @JsonData data class AssetUploadResponse(
val name: String,
val state: String,
val size: Int
) {
companion object // for test extensions
}
|
apache-2.0
|
7bcbb993a2caa927b6dc79daba8fb0f7
| 24.472727 | 62 | 0.659529 | 4.490385 | false | false | false | false |
TouK/bubble
|
bubble/src/test/java/pl/touk/android/bubble/testvalue/Degree.kt
|
1
|
844
|
package pl.touk.android.bubble.testvalue
class Degree {
/*
* http://www.jdroid.ch/grundelemente/bilder/sensorwerte.png
* pitch -90 -> full vertical (up of the phone points the sky)
* 0 -> full horizontal
* 90 -> full reverse vertical (up of the phone points the ground)
*
* roll 0 -> front oh the phone points the sky
* 90 -> front oh the phone points the right
* -90 -> front oh the phone points the left
* -180/180 -> front oh the phone points the ground
*/
companion object Degree {
val MINUS_90 = (-Math.PI/2f).toFloat()
val MINUS_45 = (-Math.PI/4f).toFloat()
val ZERO = 0f
val ONE = (Math.PI/180f).toFloat()
val PLUS_45 = (Math.PI/4f).toFloat()
}
}
|
apache-2.0
|
18d7446ccb7b302fb7e3e77c55b6ec1a
| 32.8 | 80 | 0.540284 | 3.669565 | false | false | false | false |
Shynixn/PetBlocks
|
petblocks-bukkit-plugin/petblocks-bukkit-nms-116R3/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/service/EntityRegistration116R3ServiceImpl.kt
|
1
|
2869
|
package com.github.shynixn.petblocks.bukkit.logic.business.service
import com.github.shynixn.petblocks.api.business.enumeration.EntityType
import com.github.shynixn.petblocks.api.business.service.EntityRegistrationService
import net.minecraft.server.v1_16_R3.*
/**
* The EntityRegistration116R3ServiceImpl handles registering the custom Entities into Minecraft.
* <p>
* Version 1.3
* <p>
* MIT License
* <p>
* Copyright (c) 2020 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class EntityRegistration116R3ServiceImpl : EntityRegistrationService {
private val classes = HashMap<Class<*>, EntityType>()
/**
* Registers a new customEntity Clazz as the given [entityType].
* Does nothing if the class is already registered.
*/
override fun <C> register(customEntityClazz: C, entityType: EntityType) {
if (customEntityClazz !is Class<*>) {
throw IllegalArgumentException("CustomEntityClass has to be a Class!")
}
if (classes.containsKey(customEntityClazz)) {
return
}
val entityRegistry = IRegistry.ENTITY_TYPE as RegistryBlocks<EntityTypes<*>>
val key = entityType.saveGame_11
val internalRegistry = (entityRegistry.get(MinecraftKey(key)));
val size = EntityTypes::class.java.getDeclaredMethod("l").invoke(internalRegistry) as EntitySize
IRegistry.a(
entityRegistry,
"petblocks_" + key.toLowerCase(),
EntityTypes.Builder.a<Entity>(EnumCreatureType.CREATURE).b().a().a(size.width, size.height).a(key)
)
classes[customEntityClazz] = entityType
}
/**
* Clears all resources this service has allocated and reverts internal
* nms changes.
*/
override fun clearResources() {
classes.clear()
}
}
|
apache-2.0
|
1e65662963471214babec90604d10728
| 39.408451 | 110 | 0.712443 | 4.434312 | false | false | false | false |
Magneticraft-Team/Magneticraft
|
ignore/test/multiblock/MultiblockSolarPanel.kt
|
2
|
5198
|
package multiblock.impl
import com.cout970.magneticraft.block.PROPERTY_ACTIVE
import com.cout970.magneticraft.block.PROPERTY_CENTER
import com.cout970.magneticraft.block.PROPERTY_DIRECTION
import com.cout970.magneticraft.block.decoration.BlockElectricalMachineBlock
import com.cout970.magneticraft.block.multiblock.BlockSolarPanel
import com.cout970.magneticraft.multiblock.BlockData
import com.cout970.magneticraft.multiblock.IMultiblockComponent
import com.cout970.magneticraft.multiblock.Multiblock
import com.cout970.magneticraft.multiblock.MultiblockContext
import com.cout970.magneticraft.multiblock.components.MainBlockComponent
import com.cout970.magneticraft.multiblock.components.SingleBlockComponent
import com.cout970.magneticraft.tilerenderer.PIXEL
import com.cout970.magneticraft.util.vector.times
import net.minecraft.util.math.AxisAlignedBB
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.util.text.ITextComponent
/**
* Created by cout970 on 2016/09/06.
*/
object MultiblockSolarPanel : Multiblock() {
override val name: String = "solar_panel"
override val size: BlockPos = BlockPos(3, 1, 3)
override val scheme: List<MultiblockLayer>
override val center: BlockPos = BlockPos(1, 0, 0)
init {
val replacement = BlockSolarPanel.defaultState
.withProperty(PROPERTY_CENTER, false)
.withProperty(PROPERTY_ACTIVE, true)
val P: IMultiblockComponent = SingleBlockComponent(BlockElectricalMachineBlock.defaultState, replacement)
val M: IMultiblockComponent = MainBlockComponent(BlockSolarPanel) { context, state, activate ->
if (activate) {
BlockSolarPanel.defaultState
.withProperty(PROPERTY_ACTIVE, true)
.withProperty(PROPERTY_CENTER, true)
.withProperty(PROPERTY_DIRECTION, context.facing)
} else {
BlockSolarPanel.defaultState
.withProperty(PROPERTY_ACTIVE, false)
.withProperty(PROPERTY_CENTER, true)
.withProperty(PROPERTY_DIRECTION, context.facing)
}
}
scheme = yLayers(
zLayers(listOf(P, M, P),
listOf(P, P, P),
listOf(P, P, P))
)
}
override fun getGlobalCollisionBox(): List<AxisAlignedBB> = listOf(
Vec3d(-13.0, 12.0, 1.0) * PIXEL to Vec3d(5.0, 14.0, 15.0) * PIXEL,
Vec3d(-12.0, 11.0, 2.0) * PIXEL to Vec3d(4.0, 12.0, 14.0) * PIXEL,
Vec3d(-6.0, 10.0, 6.0) * PIXEL to Vec3d(-2.0, 11.0, 10.0) * PIXEL,
Vec3d(-13.0, 12.0, 17.0) * PIXEL to Vec3d(5.0, 14.0, 31.0) * PIXEL,
Vec3d(-12.0, 11.0, 18.0) * PIXEL to Vec3d(4.0, 12.0, 30.0) * PIXEL,
Vec3d(-6.0, 10.0, 22.0) * PIXEL to Vec3d(-2.0, 11.0, 26.0) * PIXEL,
Vec3d(-13.0, 12.0, 33.0) * PIXEL to Vec3d(5.0, 14.0, 47.0) * PIXEL,
Vec3d(-12.0, 11.0, 34.0) * PIXEL to Vec3d(4.0, 12.0, 46.0) * PIXEL,
Vec3d(-6.0, 10.0, 38.0) * PIXEL to Vec3d(-2.0, 11.0, 42.0) * PIXEL,
Vec3d(-6.0, 0.0, 4.0) * PIXEL to Vec3d(-2.0, 2.0, 44.0) * PIXEL,
Vec3d(-5.0, 4.0, 39.0) * PIXEL to Vec3d(-3.0, 12.0, 41.0) * PIXEL,
Vec3d(-5.0, 4.0, 23.0) * PIXEL to Vec3d(-3.0, 12.0, 25.0) * PIXEL,
Vec3d(-7.0, 0.0, 38.0) * PIXEL to Vec3d(23.0, 4.0, 42.0) * PIXEL,
Vec3d(-7.0, 0.0, 22.0) * PIXEL to Vec3d(-1.0, 4.0, 26.0) * PIXEL,
Vec3d(-5.0, 4.0, 7.0) * PIXEL to Vec3d(-3.0, 12.0, 9.0) * PIXEL,
Vec3d(-7.0, 0.0, 6.0) * PIXEL to Vec3d(23.0, 4.0, 10.0) * PIXEL,
Vec3d(11.0, 12.0, 1.0) * PIXEL to Vec3d(29.0, 14.0, 15.0) * PIXEL,
Vec3d(12.0, 11.0, 2.0) * PIXEL to Vec3d(28.0, 12.0, 14.0) * PIXEL,
Vec3d(11.0, 12.0, 17.0) * PIXEL to Vec3d(29.0, 14.0, 31.0) * PIXEL,
Vec3d(12.0, 11.0, 18.0) * PIXEL to Vec3d(28.0, 12.0, 30.0) * PIXEL,
Vec3d(11.0, 12.0, 33.0) * PIXEL to Vec3d(29.0, 14.0, 47.0) * PIXEL,
Vec3d(12.0, 11.0, 34.0) * PIXEL to Vec3d(28.0, 12.0, 46.0) * PIXEL,
Vec3d(18.0, 10.0, 6.0) * PIXEL to Vec3d(22.0, 11.0, 10.0) * PIXEL,
Vec3d(18.0, 10.0, 22.0) * PIXEL to Vec3d(22.0, 11.0, 26.0) * PIXEL,
Vec3d(18.0, 10.0, 38.0) * PIXEL to Vec3d(22.0, 11.0, 42.0) * PIXEL,
Vec3d(19.0, 4.0, 7.0) * PIXEL to Vec3d(21.0, 12.0, 9.0) * PIXEL,
Vec3d(19.0, 4.0, 23.0) * PIXEL to Vec3d(21.0, 12.0, 25.0) * PIXEL,
Vec3d(19.0, 4.0, 39.0) * PIXEL to Vec3d(21.0, 12.0, 41.0) * PIXEL,
Vec3d(17.0, 0.0, 22.0) * PIXEL to Vec3d(23.0, 4.0, 26.0) * PIXEL,
Vec3d(18.0, 0.0, 4.0) * PIXEL to Vec3d(22.0, 2.0, 44.0) * PIXEL,
Vec3d(5.0, 0.0, 1.0) * PIXEL to Vec3d(11.0, 11.0, 6.0) * PIXEL,
Vec3d(6.0, 4.0, 6.0) * PIXEL to Vec3d(10.0, 10.0, 7.0) * PIXEL,
Vec3d(6.0, 6.0, 0.0) * PIXEL to Vec3d(10.0, 10.0, 1.0) * PIXEL
)
override fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> = listOf()
}
|
gpl-2.0
|
8692f862d1e596d0360742a494cec4af
| 52.05102 | 130 | 0.591766 | 2.781166 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
app/src/main/kotlin/de/ph1b/audiobook/features/bookmarks/list/BookMarkHolder.kt
|
1
|
2432
|
package de.ph1b.audiobook.features.bookmarks.list
import android.text.format.DateUtils
import android.view.ViewGroup
import de.ph1b.audiobook.R
import de.ph1b.audiobook.data.Bookmark2
import de.ph1b.audiobook.data.Chapter2
import de.ph1b.audiobook.data.markForPosition
import de.ph1b.audiobook.databinding.BookmarkRowLayoutBinding
import de.ph1b.audiobook.uitools.ViewBindingHolder
import voice.common.formatTime
import java.time.Instant
import java.time.temporal.ChronoUnit
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
class BookMarkHolder(
parent: ViewGroup,
private val listener: BookmarkClickListener
) : ViewBindingHolder<BookmarkRowLayoutBinding>(parent, BookmarkRowLayoutBinding::inflate) {
var boundBookmark: Bookmark2? = null
private set
init {
binding.edit.setOnClickListener { view ->
boundBookmark?.let {
listener.onOptionsMenuClicked(it, view)
}
}
itemView.setOnClickListener {
boundBookmark?.let { bookmark ->
listener.onBookmarkClicked(bookmark)
}
}
}
fun bind(bookmark: Bookmark2, chapters: List<Chapter2>) {
boundBookmark = bookmark
val currentChapter = chapters.single { it.id == bookmark.chapterId }
val bookmarkTitle = bookmark.title
binding.title.text = when {
bookmark.setBySleepTimer -> {
val justNowThreshold = 1.minutes
if (ChronoUnit.MILLIS.between(bookmark.addedAt, Instant.now()).milliseconds < justNowThreshold) {
itemView.context.getString(R.string.bookmark_just_now)
} else {
DateUtils.getRelativeDateTimeString(
itemView.context,
bookmark.addedAt.toEpochMilli(),
justNowThreshold.inWholeMilliseconds,
2.days.inWholeMilliseconds,
0
)
}
}
bookmarkTitle != null && bookmarkTitle.isNotEmpty() -> bookmarkTitle
else -> currentChapter.markForPosition(bookmark.time).name
}
binding.title.setCompoundDrawablesRelativeWithIntrinsicBounds(if (bookmark.setBySleepTimer) R.drawable.ic_sleep else 0, 0, 0, 0)
val size = chapters.size
val index = chapters.indexOf(currentChapter)
binding.summary.text = itemView.context.getString(
R.string.format_bookmarks_n_of,
index + 1,
size
)
binding.time.text = formatTime(bookmark.time)
}
}
|
lgpl-3.0
|
f95d4b68a8b765e4cbc8670b3f0456a8
| 32.777778 | 132 | 0.720806 | 4.274165 | false | false | false | false |
facebook/litho
|
litho-live-data/src/main/kotlin/com/facebook/litho/livedata/UseLiveData.kt
|
1
|
2612
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.livedata
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.facebook.litho.AOSPLithoLifecycleProvider
import com.facebook.litho.ComponentScope
import com.facebook.litho.ComponentTree
import com.facebook.litho.LithoView
import com.facebook.litho.State
import com.facebook.litho.annotations.Hook
import com.facebook.litho.getTreeProp
import com.facebook.litho.onCleanup
import com.facebook.litho.useEffect
import com.facebook.litho.useState
/**
* Uses the current value of a given [LiveData] in a Litho Kotlin component.
*
* The live data will be observed following the [AOSPLithoLifecycleProvider] lifecycle definition,
* and it's usage requires the [LithoView] or [ComponentTree] to be using the
* [AOSPLithoLifecycleProvider]
*/
@Hook
fun <T> ComponentScope.useLiveData(liveData: LiveData<T>): T? {
return useLiveData(liveData = liveData, initialValue = { liveData.value })
}
/**
* Uses the current value of a given [LiveData] in a Litho Kotlin component.
*
* The live data will be observed following the [AOSPLithoLifecycleProvider] lifecycle definition,
* and it's usage requires the [LithoView] or [ComponentTree] to be using the
* [AOSPLithoLifecycleProvider].
*
* This observation will also be canceled whenever [deps] change.
*/
@Hook
fun <T> ComponentScope.useLiveData(
liveData: LiveData<T>,
vararg deps: Any?,
initialValue: () -> T?
): T? {
val lifecycleOwner: LifecycleOwner =
getTreeProp<LifecycleOwner>()
?: error(
"There is no lifecycle owner. Make you created your LithoView with an AOSPLithoLifecycleProvider.")
val state: State<T?> = useState { initialValue() }
useEffect(lifecycleOwner, deps) {
val observer = Observer<T> { liveDataResult -> state.update { liveDataResult } }
liveData.observe(lifecycleOwner, observer)
onCleanup { liveData.removeObserver(observer) }
}
return state.value
}
|
apache-2.0
|
92297bc47ab08d7c1d43cb6efd9edb9c
| 34.297297 | 113 | 0.751914 | 4.132911 | false | false | false | false |
epabst/kotlin-showcase
|
src/jsMain/kotlin/firebase/firebase_wrappers.kt
|
1
|
2474
|
/**
* These are only here to force requiring "firebase/<something>" since there are no top-level functions or objects.
*/
package firebase
import firebase.firestore.CollectionReference
import firebase.firestore.DocumentReference
import firebase.firestore.Firestore
import kotlin.js.Date
import kotlin.js.Promise
@JsModule("firebase/app") @JsNonModule
external val requireApp: Nothing? = definedExternally
@JsModule("firebase/auth") @JsNonModule
external val requireAuth: Nothing? = definedExternally
@JsModule("firebase/database") @JsNonModule
external val requireDatabase: Nothing? = definedExternally
@JsModule("firebase/firestore") @JsNonModule
external val requireFirestore: Nothing? = definedExternally
@JsModule("firebase/storage") @JsNonModule
external val requireStorage: Nothing? = definedExternally
/** This is an alternative to [firebase.firestore.FieldPath] to work around the error "FieldPath is not a constructor" */
class FieldPath(val fieldName: String)
fun Firestore.generateConsecutiveId(): String = collection("ids").generateConsecutiveId()
fun <T> DocumentReference<T>.update(vararg fieldValues: Pair<FieldPath, Any>): Promise<Unit> {
return when (fieldValues.size) {
0 -> error("must provide at least one field to update")
1 -> update(
fieldValues[0].first.fieldName, fieldValues[0].second
)
2 -> update(
fieldValues[0].first.fieldName, fieldValues[0].second,
fieldValues[1].first.fieldName, fieldValues[1].second
)
3 -> update(
fieldValues[0].first.fieldName, fieldValues[0].second,
fieldValues[1].first.fieldName, fieldValues[1].second,
fieldValues[2].first.fieldName, fieldValues[2].second
)
else -> TODO("Support ${fieldValues.size}")
}
// This code should work for all cases but it doesn't compile:
// TranslationRuntimeException: Unexpected error occurred compiling the following fragment:
// 'update(fieldValues[0].first, fieldValues[0].second, *remainingFieldPathsAndValues)'
//
// val remainingFieldPathsAndValues: Array<Any> = fieldValues
// .drop(1)
// .flatMap { listOf(it.first.unsafeCast<Any>(), it.second) }
// .toTypedArray()
// return update(fieldValues[0].first, fieldValues[0].second, *remainingFieldPathsAndValues)
}
fun CollectionReference<*>.generateConsecutiveId(): String =
Date.now().toLong().toString(36) + doc().id.takeLast(3)
|
apache-2.0
|
6221aea36f54bc276b7633520bf8d6ec
| 39.557377 | 121 | 0.719078 | 4.355634 | false | false | false | false |
google/horologist
|
sample/src/main/java/com/google/android/horologist/datalayer/DataLayerNodesScreen.kt
|
1
|
2157
|
/*
* 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.
*/
package com.google.android.horologist.datalayer
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.items
@Composable
fun DataLayerNodesScreen(
viewModel: DataLayerNodesViewModel,
modifier: Modifier = Modifier
) {
val state by viewModel.state.collectAsStateWithLifecycle()
ScalingLazyColumn(modifier = modifier) {
item {
Text("Nodes")
}
items(state.nodes) {
Chip(
onClick = { },
label = {
Text("${it.displayName}(${it.id}) ${if (it.isNearby) "NEAR" else ""}")
}
)
}
item {
Text("Data")
}
item {
val thisData = state.thisData
if (thisData != null) {
Button(onClick = {
viewModel.increment()
}) {
Text("This Value: ${thisData.value} (${thisData.name})")
}
} else {
Text("This Value: None")
}
}
items(state.protoMap.entries.toList()) { (id, data) ->
Text("$id Value: ${data.value} (${data.name})")
}
}
}
|
apache-2.0
|
54432705a9288125494a66e546782da0
| 31.19403 | 90 | 0.616134 | 4.512552 | false | false | false | false |
google/horologist
|
sample/src/main/java/com/google/android/horologist/sample/ScrollAwayScreen.kt
|
1
|
5001
|
/*
* 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.
*/
package com.google.android.horologist.sample
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Card
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.PositionIndicator
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.TimeText
import androidx.wear.compose.material.rememberScalingLazyListState
import androidx.wear.compose.material.scrollAway
import com.google.android.horologist.compose.rotaryinput.rotaryWithFling
import com.google.android.horologist.compose.tools.WearLargeRoundDevicePreview
@Composable
fun ScrollScreenLazyColumn() {
val scrollState = rememberLazyListState()
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = Modifier.fillMaxSize(),
timeText = {
TimeText(modifier = Modifier.scrollAway(scrollState))
},
positionIndicator = {
PositionIndicator(lazyListState = scrollState)
}
) {
LazyColumn(
modifier = Modifier.rotaryWithFling(focusRequester, scrollState),
state = scrollState
) {
items(3) { i ->
val modifier = Modifier.fillParentMaxHeight(0.5f)
ExampleCard(modifier = modifier, i = i)
}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Composable
fun ScrollAwayScreenScalingLazyColumn() {
val scrollState = rememberScalingLazyListState()
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = Modifier.fillMaxSize(),
timeText = {
TimeText(modifier = Modifier.scrollAway(scrollState, 1, 0.dp))
},
positionIndicator = {
PositionIndicator(scalingLazyListState = scrollState)
}
) {
ScalingLazyColumn(
modifier = Modifier.rotaryWithFling(focusRequester, scrollState),
state = scrollState
) {
items(3) { i ->
ExampleCard(Modifier.fillParentMaxHeight(0.5f), i)
}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Composable
fun ScrollAwayScreenColumn() {
val scrollState = rememberScrollState()
val focusRequester = remember { FocusRequester() }
Scaffold(
modifier = Modifier.fillMaxSize(),
timeText = {
TimeText(modifier = Modifier.scrollAway(scrollState))
},
positionIndicator = {
PositionIndicator(scrollState = scrollState)
}
) {
Column(
modifier = Modifier
.rotaryWithFling(focusRequester, scrollState)
.verticalScroll(scrollState)
) {
val modifier = Modifier.height(LocalConfiguration.current.screenHeightDp.dp / 2)
repeat(3) { i ->
ExampleCard(modifier, i)
}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Composable
private fun ExampleCard(modifier: Modifier, i: Int) {
Card(
modifier = modifier,
onClick = { }
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.surface),
contentAlignment = Alignment.Center
) {
Text(text = "Card $i")
}
}
}
@WearLargeRoundDevicePreview
@Composable
fun ScrollAwayScreenPreview() {
ScrollScreenLazyColumn()
}
|
apache-2.0
|
7a53b0c43a3fe219d8cb5f137c5826c9
| 30.45283 | 92 | 0.684263 | 4.879024 | false | false | false | false |
fython/PackageTracker
|
mobile/src/main/kotlin/info/papdt/express/helper/ui/fragment/settings/SettingsAssistant.kt
|
1
|
3064
|
package info.papdt.express.helper.ui.fragment.settings
import android.content.ComponentName
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import info.papdt.express.helper.R
import info.papdt.express.helper.receiver.ProcessTextReceiver
import info.papdt.express.helper.services.ClipboardDetectService
import info.papdt.express.helper.support.Settings
import moe.shizuku.preference.Preference
import moe.shizuku.preference.SwitchPreference
class SettingsAssistant : AbsPrefFragment(), Preference.OnPreferenceChangeListener {
// Auto detect
private val mPrefFromClipboard: SwitchPreference by PreferenceProperty("from_clipboard")
private val mPrefSelectionAction: SwitchPreference by PreferenceProperty("selection_action")
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.settings_assistant)
mPrefFromClipboard.isChecked = settings.isClipboardDetectServiceEnabled()
mPrefSelectionAction.isChecked = context?.packageManager
?.getComponentEnabledSetting(
ComponentName(context!!, ProcessTextReceiver::class.java.name)
) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED
// Auto detect
mPrefFromClipboard.onPreferenceChangeListener = this
mPrefSelectionAction.onPreferenceChangeListener = this
}
override fun onPreferenceChange(pref: Preference, newValue: Any?): Boolean {
return when (pref) {
// Auto detect
mPrefFromClipboard -> {
val isOpen = newValue as Boolean
if (isOpen && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!android.provider.Settings.canDrawOverlays(activity)) {
val intent = Intent(
android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity!!.packageName)
)
startActivity(intent)
return false
}
}
settings.putBoolean(Settings.KEY_DETECT_FROM_CLIPBOARD, isOpen)
val intent = Intent(activity?.applicationContext, ClipboardDetectService::class.java)
intent.run(if (!isOpen) activity!!::stopService else activity!!::startService)
return true
}
mPrefSelectionAction -> {
return context?.packageManager?.setComponentEnabledSetting(
ComponentName(context!!, ProcessTextReceiver::class.java.name),
if (newValue as Boolean) PackageManager.COMPONENT_ENABLED_STATE_ENABLED
else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP
) != null
}
else -> false
}
}
}
|
gpl-3.0
|
646bb8b1f8f1c49952a66c93672bf287
| 44.073529 | 101 | 0.64752 | 5.491039 | false | false | false | false |
mbarta/scr-redesign
|
app/src/main/java/me/barta/stayintouch/ui/contactdetail/ContactDetailActivity.kt
|
1
|
7004
|
package me.barta.stayintouch.ui.contactdetail
import android.graphics.PorterDuff
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.SharedElementCallback
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import coil.imageLoader
import coil.load
import coil.request.ImageRequest
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import me.barta.stayintouch.R
import me.barta.stayintouch.common.utils.karmaColorList
import me.barta.stayintouch.common.utils.setColoredRating
import me.barta.stayintouch.common.utils.setNotImplementedClickListener
import me.barta.stayintouch.common.utils.toLegacyDate
import me.barta.stayintouch.common.viewbinding.viewBinding
import me.barta.stayintouch.common.viewstate.Failure
import me.barta.stayintouch.common.viewstate.Loading
import me.barta.stayintouch.common.viewstate.Success
import me.barta.stayintouch.data.models.ContactPerson
import me.barta.stayintouch.databinding.ActivityContactDetailBinding
import org.ocpsoft.prettytime.PrettyTime
import java.util.*
@AndroidEntryPoint
class ContactDetailActivity : AppCompatActivity(R.layout.activity_contact_detail) {
private val viewModel: ContactDetailViewModel by viewModels()
private val binding: ActivityContactDetailBinding by viewBinding(ActivityContactDetailBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
val contactId = intent?.extras?.getInt(CONTACT_ID) ?: -1
setUpSharedElementTransition(contactId)
setUpViews()
viewModel.viewState.observe(this) { state ->
when (state) {
is Loading -> Unit // No loading due to shared element transition
is Success -> handleSuccess(state.data)
is Failure -> handleError(state.throwable, contactId)
}
}
viewModel.loadContactById(contactId)
}
private fun setUpSharedElementTransition(contactId: Int) {
setEnterSharedElementCallback(object : SharedElementCallback() {
override fun onSharedElementStart(sharedElementNames: MutableList<String>, sharedElements: MutableList<View>, sharedElementSnapshots: MutableList<View>) {
super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots)
sharedElements.find { it.id == R.id.infoCard }?.findViewById<View>(R.id.infoCardContents)?.alpha = 0f
}
})
supportPostponeEnterTransition()
with(binding.content) {
photoCard.transitionName = SHARED_PICTURE_ID + contactId
infoCard.transitionName = SHARED_INFO_CARD_ID + contactId
}
}
override fun onEnterAnimationComplete() {
super.onEnterAnimationComplete()
val slideAnim = AnimationUtils.loadAnimation(this, R.anim.slide_from_bottom)
binding.contactButton.startAnimation(slideAnim)
val alphaAnim = binding.content.infoCardContents.animate()
.alpha(1.0f)
.setDuration(500)
.setInterpolator(LinearInterpolator())
alphaAnim.start()
}
private fun setUpViews() {
setUpToolbar()
binding.contactButton.setNotImplementedClickListener()
binding.content.contactFreq.setNotImplementedClickListener()
}
private fun setUpToolbar() {
val toolbarIcon = ResourcesCompat.getDrawable(resources, R.drawable.ic_arrow_back_24dp, theme)?.apply {
setTint(ContextCompat.getColor(this@ContactDetailActivity, R.color.white_transparent))
setTintMode(PorterDuff.Mode.SRC_IN)
}
binding.toolbar.navigationIcon = toolbarIcon
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = ""
binding.appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
var scrollRange = -1
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
//Initialize the size of the scroll
if (scrollRange == -1) {
scrollRange = appBarLayout.totalScrollRange
}
binding.toolbarArcBackground.scale = 1 + verticalOffset / scrollRange.toFloat()
}
})
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
supportFinishAfterTransition()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun handleSuccess(contact: ContactPerson) {
val request = ImageRequest.Builder(this)
.data(contact.photo)
.allowHardware(false)
.target(
onSuccess = { result ->
binding.toolbarArcBackground.bitmap = (result as BitmapDrawable).bitmap
supportStartPostponedEnterTransition()
},
onError = { supportStartPostponedEnterTransition() }
)
.build()
imageLoader.enqueue(request)
val pt = PrettyTime(Locale.getDefault())
with(binding.content) {
photo.load(contact.photo)
name.text = getString(R.string.contact_name, contact.firstName, contact.lastName)
lastContact.text = getString(R.string.last_contact, pt.format(contact.lastContact.toLegacyDate()))
nextContact.text = getString(R.string.next_contact, pt.format(contact.nextContact.toLegacyDate()))
ratingBar.setColoredRating(contact.karma)
rating.text = getString(R.string.rating, contact.karma)
rating.setTextColor(ContextCompat.getColor(this@ContactDetailActivity, karmaColorList[contact.karma - 1]))
frequency.text = contact.contactFreq
}
}
private fun handleError(error: Throwable, contactId: Int) {
supportStartPostponedEnterTransition()
Snackbar.make(binding.coordinatorLayout, R.string.error_loading_contact, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.retry) { viewModel.loadContactById(contactId) }
.setAnchorView(binding.anchor)
.show()
}
companion object {
const val CONTACT_ID = "ContactIdExtra"
const val SHARED_PICTURE_ID = "ContactPicture"
const val SHARED_INFO_CARD_ID = "ContactInfoCard"
}
}
|
mit
|
c2e7fca7f86bee2af7ad019631325da7
| 37.911111 | 166 | 0.686893 | 4.887648 | false | false | false | false |
qianmoCoder/beautifullife
|
icore/src/main/java/com/ddu/icore/ui/activity/BaseActivity.kt
|
2
|
3817
|
package com.ddu.icore.ui.activity
import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import com.ddu.icore.R
import com.ddu.icore.aidl.GodIntent
import com.ddu.icore.common.IObserver
import com.ddu.icore.common.ObserverManager
import com.ddu.icore.common.ext.find
import com.ddu.icore.navigation.Navigator
import com.ddu.icore.ui.widget.TitleBar
open class BaseActivity : AppCompatActivity(),
IObserver {
lateinit var mContext: Context
lateinit var mViewGroup: ViewGroup
var titleBar: TitleBar? = null
protected set
var fragmentCallback: OnFragmentCallback? = null
protected var mCustomerTitleBar: View? = null
private val appCompatDelegate: AppCompatDelegate? = null
open fun isShowTitleBar() = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.setBackgroundDrawable(null)
mContext = this
registerObserver()
// mImmersionBar = ImmersionBar.with(this)
// mImmersionBar.statusBarDarkFont(true,0.2f).statusBarColor(R.color.c_ffffff).fitsSystemWindows(true).init()
}
override fun setContentView(@LayoutRes layoutResID: Int) {
if (isShowTitleBar()) {
super.setContentView(R.layout.i_activity_base)
mViewGroup = find(R.id.ll_activity_base)
titleBar = find(R.id.ll_title_bar)
layoutInflater.inflate(layoutResID, mViewGroup)
} else {
super.setContentView(layoutResID)
}
}
fun startFragment(fragment: Class<out androidx.fragment.app.Fragment>) {
startFragment(fragment, null)
}
fun startFragment(fragmentName: String) {
Navigator.startShowDetailActivity(this, fragmentName, null)
}
fun startFragment(fragmentName: String, bundle: Bundle?) {
Navigator.startShowDetailActivity(this, fragmentName, bundle)
}
fun startFragment(fragment: Class<out androidx.fragment.app.Fragment>, bundle: Bundle?) {
Navigator.startShowDetailActivity(this, fragment, bundle)
}
open fun registerObserver() {
}
override fun onReceiverNotify(godIntent: GodIntent) {
}
override fun onDestroy() {
super.onDestroy()
ObserverManager.unRegisterObserver(this)
}
fun setDefaultTitle(resId: Int) {
titleBar?.let {
it.setMiddleText(resId)
setDefaultLeftImg()
}
}
fun setDefaultTitle(title: String) {
if (null != titleBar) {
titleBar!!.setMiddleText(title)
setDefaultLeftImg()
}
}
fun setRightText(text: String, onClickListener: View.OnClickListener) {
if (null != titleBar) {
val textView = titleBar!!.rightText
textView.text = text
textView.setOnClickListener(onClickListener)
}
}
fun setRightImg(resId: Int, onClickListener: View.OnClickListener) {
if (null != titleBar) {
val imageView = titleBar!!.rightImg
imageView.setImageResource(resId)
imageView.setOnClickListener(onClickListener)
}
}
private fun setDefaultLeftImg() {
if (null != titleBar) {
titleBar!!.setDefaultLeftImg { onBackPressed() }
}
}
interface OnFragmentCallback {
fun onFragmentKeyDownPress(keyCode: Int, keyEvent: KeyEvent): Boolean
fun onFragmentBackPress(): Boolean
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
return super.dispatchTouchEvent(ev)
}
}
|
apache-2.0
|
1c571f125133ad0a7e6d21c823bce891
| 27.485075 | 116 | 0.676447 | 4.593261 | false | false | false | false |
square/duktape-android
|
zipline/src/nativeMain/kotlin/app/cash/zipline/InboundCallChannel.kt
|
1
|
3392
|
/*
* Copyright (C) 2021 Square, Inc.
*
* 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.cash.zipline
import app.cash.zipline.internal.bridge.CallChannel
import app.cash.zipline.internal.bridge.inboundChannelName
import app.cash.zipline.quickjs.JS_FreeAtom
import app.cash.zipline.quickjs.JS_FreeValue
import app.cash.zipline.quickjs.JS_GetGlobalObject
import app.cash.zipline.quickjs.JS_GetPropertyStr
import app.cash.zipline.quickjs.JS_Invoke
import app.cash.zipline.quickjs.JS_NewAtom
import app.cash.zipline.quickjs.JS_NewString
import kotlinx.cinterop.memScoped
internal class InboundCallChannel(
private val quickJs: QuickJs,
) : CallChannel {
private val context = quickJs.context
override fun serviceNamesArray(): Array<String> {
quickJs.checkNotClosed()
val globalThis = JS_GetGlobalObject(context)
val inboundChannel = JS_GetPropertyStr(context, globalThis, inboundChannelName)
val property = JS_NewAtom(context, "serviceNamesArray")
val jsResult = JS_Invoke(context, inboundChannel, property, 0, null)
@Suppress("UNCHECKED_CAST") // Our JS implementation returns an Array<String>.
val kotlinResult = with(quickJs) { jsResult.toKotlinInstanceOrNull() } as Array<String>
JS_FreeValue(context, jsResult)
JS_FreeAtom(context, property)
JS_FreeValue(context, inboundChannel)
JS_FreeValue(context, globalThis)
return kotlinResult
}
override fun call(callJson: String): String {
quickJs.checkNotClosed()
val globalThis = JS_GetGlobalObject(context)
val inboundChannel = JS_GetPropertyStr(context, globalThis, inboundChannelName)
val property = JS_NewAtom(context, "call")
val arg0 = JS_NewString(context, callJson)
val jsResult = memScoped {
val args = allocArrayOf(arg0)
JS_Invoke(context, inboundChannel, property, 1, args)
}
val kotlinResult = with(quickJs) { jsResult.toKotlinInstanceOrNull() } as String
JS_FreeValue(context, jsResult)
JS_FreeValue(context, arg0)
JS_FreeAtom(context, property)
JS_FreeValue(context, inboundChannel)
JS_FreeValue(context, globalThis)
return kotlinResult
}
override fun disconnect(instanceName: String): Boolean {
quickJs.checkNotClosed()
val globalThis = JS_GetGlobalObject(context)
val inboundChannel = JS_GetPropertyStr(context, globalThis, inboundChannelName)
val property = JS_NewAtom(context, "disconnect")
val arg0 = JS_NewString(context, instanceName)
val jsResult = memScoped {
val args = allocArrayOf(arg0)
JS_Invoke(context, inboundChannel, property, 1, args)
}
val kotlinResult = with(quickJs) { jsResult.toKotlinInstanceOrNull() } as Boolean
JS_FreeValue(context, jsResult)
JS_FreeAtom(context, property)
JS_FreeValue(context, inboundChannel)
JS_FreeValue(context, globalThis)
return kotlinResult
}
}
|
apache-2.0
|
50f91ca08492f17fe8564a6ba1576b4c
| 33.969072 | 91 | 0.744399 | 3.84145 | false | false | false | false |
EvidentSolutions/apina
|
apina-core/src/main/kotlin/fi/evident/apina/java/model/JavaParameter.kt
|
1
|
557
|
package fi.evident.apina.java.model
import fi.evident.apina.java.model.type.JavaType
import java.util.*
/**
* Parameter definition for a [JavaMethod].
*/
class JavaParameter(val type: JavaType) : JavaAnnotatedElement {
var name: String? = null
private val _annotations = ArrayList<JavaAnnotation>()
override val annotations: List<JavaAnnotation>
get() = _annotations
override fun toString() = "$type ${name ?: "<unknown>"}"
fun addAnnotation(annotation: JavaAnnotation) {
this._annotations += annotation
}
}
|
mit
|
4ea7a3d4c359e674963db5898535d6ab
| 23.217391 | 64 | 0.691203 | 4.251908 | false | false | false | false |
mixitconf/mixit
|
src/main/kotlin/mixit/security/MixitWebFilter.kt
|
1
|
7435
|
package mixit.security
import com.google.common.annotations.VisibleForTesting
import mixit.MixitProperties
import mixit.routes.Routes
import mixit.security.model.Credential
import mixit.talk.model.Language
import mixit.user.model.Role
import mixit.user.model.User
import mixit.user.model.hasValidToken
import mixit.user.repository.UserRepository
import mixit.util.decodeFromBase64
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpHeaders.CONTENT_LANGUAGE
import org.springframework.http.HttpStatus
import org.springframework.http.server.reactive.ServerHttpRequest
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import org.springframework.web.server.WebSession
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.switchIfEmpty
import java.net.URI
import java.util.Locale
@Component
class MixitWebFilter(val properties: MixitProperties, val userRepository: UserRepository) : WebFilter {
companion object {
const val AUTHENT_COOKIE = "XSRF-TOKEN"
val BOTS = arrayOf("Google", "Bingbot", "Qwant", "Bingbot", "Slurp", "DuckDuckBot", "Baiduspider")
val WEB_RESSOURCE_EXTENSIONS =
arrayOf(".css", ".js", ".svg", ".jpg", ".png", ".webp", ".webapp", ".pdf", ".icns", ".ico", ".html")
const val SESSION_ROLE_KEY = "role"
const val SESSION_EMAIL_KEY = "email"
const val SESSION_TOKEN_KEY = "token"
const val SESSION_LOGIN_KEY = "login"
}
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> =
// People who used the old URL are directly redirected
if (isACallOnOldUrl(exchange)) {
redirect(exchange, exchange.request.uri.path, HttpStatus.PERMANENT_REDIRECT)
}
// For those who arrive on our home page with another language than french, we need to load the site in english
else if (isAHomePageCallFromForeignLanguage(exchange)) {
redirect(exchange, "/${Language.ENGLISH.toLanguageTag()}/")
}
// For web resource we don't need to know if the user is connected or not
else if (isWebResource(exchange.request.uri.path)) {
chain.filter(exchange)
}
// For other calls we have to check credentials
else {
exchange.session.flatMap {
filterAndCheckCredentials(
exchange,
chain,
it,
readCredentialsFromCookie(exchange.request)
)
}
}
/**
* In this method we try to read user credentials in request cookies
*/
fun filterAndCheckCredentials(
exchange: ServerWebExchange,
chain: WebFilterChain,
session: WebSession,
credential: Credential?
): Mono<Void> =
credential?.let { cred ->
// If session contains credentials we check data
userRepository
.findByNonEncryptedEmail(cred.email)
.switchIfEmpty { Mono.just(User()) }
.flatMap { user ->
// We have to see if the token is the good one anf if it is yet valid
if (user.hasValidToken(cred.token)) {
// If user is found we need to restore infos in session
session.attributes.let {
it[SESSION_ROLE_KEY] = user.role
it[SESSION_EMAIL_KEY] = cred.email
it[SESSION_TOKEN_KEY] = cred.token
it[SESSION_LOGIN_KEY] = user.login
filterWithCredential(exchange, chain, user)
}
} else {
filterWithCredential(exchange, chain)
}
}
} ?: run {
// If credentials are not read
filterWithCredential(exchange, chain)
}
private fun filterWithCredential(
exchange: ServerWebExchange,
chain: WebFilterChain,
user: User? = null
): Mono<Void> {
// When a user wants to see a page in english uri path starts with 'en'
val initUriPath = exchange.request.uri.rawPath
val languageEn = initUriPath.startsWith("/en/")
val uriPath = if (languageEn || initUriPath.startsWith("/fr/")) initUriPath.substring(3) else initUriPath
val req =
exchange.request.mutate().path(uriPath).header(CONTENT_LANGUAGE, if (languageEn) "en" else "fr").build()
// If url is securized we have to check the credentials information
return if (isASecuredUrl(uriPath)) {
if (user == null) {
redirect(exchange, "/login")
} else {
// If admin page we see if user is a staff member
if (isAnAdminUrl(uriPath) && user.role != Role.STAFF) {
redirect(exchange, "/")
} else if (isAVolunteerUrl(uriPath) && !listOf(Role.VOLUNTEER, Role.STAFF).contains(user.role)) {
redirect(exchange, "/")
} else {
chain.filter(exchange.mutate().request(req).build())
}
}
} else {
chain.filter(exchange.mutate().request(req).build())
}
}
@VisibleForTesting
fun readCredentialsFromCookie(request: ServerHttpRequest): Credential? =
runCatching {
(request.cookies)[AUTHENT_COOKIE]?.first()?.value?.decodeFromBase64()?.split(":")
?.let { if (it.size != 2) null else Credential(it[0], it[1]) }
}
.getOrNull()
@VisibleForTesting
fun isACallOnOldUrl(exchange: ServerWebExchange): Boolean =
exchange.request.headers.host?.hostString?.endsWith("mix-it.fr") == true
@VisibleForTesting
fun isAHomePageCallFromForeignLanguage(exchange: ServerWebExchange): Boolean = exchange.request.uri.path == "/" &&
(
exchange.request.headers.acceptLanguageAsLocales.firstOrNull()
?: Locale.FRENCH
).language != Language.FRENCH.toLanguageTag() &&
!isSearchEngineCrawler(exchange.request)
@VisibleForTesting
fun isWebResource(initUriPath: String) = WEB_RESSOURCE_EXTENSIONS.any { initUriPath.endsWith(it) }
@VisibleForTesting
fun isSearchEngineCrawler(request: ServerHttpRequest) = BOTS.any {
(request.headers.getFirst(HttpHeaders.USER_AGENT) ?: "").contains(it)
}
@VisibleForTesting
fun isASecuredUrl(path: String) =
(Routes.securedUrl + Routes.securedAdminUrl + Routes.securedVolunteerUrl).any { path.startsWith(it) }
@VisibleForTesting
fun isAnAdminUrl(path: String) =
Routes.securedAdminUrl.stream().anyMatch { path.startsWith(it) }
fun isAVolunteerUrl(path: String) =
Routes.securedVolunteerUrl.stream().anyMatch { path.startsWith(it) }
private fun redirect(
exchange: ServerWebExchange,
uri: String,
statusCode: HttpStatus = HttpStatus.TEMPORARY_REDIRECT
): Mono<Void> =
exchange.response.let {
it.statusCode = statusCode
it.headers.location = URI("${properties.baseUri}$uri")
Mono.empty()
}
}
|
apache-2.0
|
d23fe88c98e10493eb5a81d9837a2ce3
| 39.851648 | 119 | 0.620713 | 4.575385 | false | false | false | false |
tokenbrowser/token-android-client
|
app/src/main/java/com/toshi/manager/network/EthereumService.kt
|
1
|
3942
|
/*
* Copyright (c) 2017. Toshi Inc
*
* 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 com.toshi.manager.network
import com.squareup.moshi.Moshi
import com.toshi.manager.network.interceptor.AppInfoUserAgentInterceptor
import com.toshi.manager.network.interceptor.LoggingInterceptor
import com.toshi.manager.network.interceptor.SigningInterceptor
import com.toshi.model.adapter.BigIntegerAdapter
import com.toshi.model.local.network.Networks
import com.toshi.model.sofa.SofaAdapters
import com.toshi.model.sofa.SofaMessage
import com.toshi.model.sofa.payment.Payment
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.moshi.MoshiConverterFactory
import rx.Single
import rx.schedulers.Schedulers
object EthereumService : EthereumServiceInterface {
private var ethereumInterface: EthereumInterface
private var baseUrl: String
override fun get() = ethereumInterface
init {
baseUrl = getBaseUrl()
ethereumInterface = buildEthereumInterface(baseUrl)
}
private fun getBaseUrl(): String {
val network = Networks.getInstance().currentNetwork
return network.url
}
private fun buildEthereumInterface(baseUrl: String): EthereumInterface {
val moshi = Moshi.Builder()
.add(BigIntegerAdapter())
.build()
val rxAdapter = RxJavaCallAdapterFactory
.createWithScheduler(Schedulers.io())
val client: OkHttpClient.Builder = OkHttpClient.Builder()
.addInterceptor(AppInfoUserAgentInterceptor())
.addInterceptor(SigningInterceptor())
.addInterceptor(buildLoggingInterceptor())
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(rxAdapter)
.client(client.build())
.build()
return retrofit.create(EthereumInterface::class.java)
}
private fun buildLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor(LoggingInterceptor())
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
override fun changeBaseUrl(baseUrl: String) {
this.baseUrl = baseUrl
ethereumInterface = buildEthereumInterface(this.baseUrl)
}
override fun getStatusOfTransaction(transactionHash: String): Single<Payment> {
return Single.fromCallable {
val networkUrl = Networks.getInstance().defaultNetwork.url
val url = "$networkUrl/v1/tx/$transactionHash?format=sofa"
val request = Request.Builder()
.url(url)
.build()
val response = OkHttpClient()
.newCall(request)
.execute()
if (response.code() == 404) return@fromCallable null
val sofaMessage = SofaMessage().makeNew(response.body()?.string().orEmpty())
response.close()
return@fromCallable SofaAdapters.get().paymentFrom(sofaMessage.payload)
}
}
}
|
gpl-3.0
|
c6f77e23a91a2ddb8af338cb4a51dca6
| 35.174312 | 88 | 0.688483 | 5.002538 | false | false | false | false |
tokenbrowser/token-android-client
|
app/src/main/java/com/toshi/util/keyboard/KeyboardListener.kt
|
1
|
2270
|
/*
* Copyright (c) 2017. Toshi Inc
*
* 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 com.toshi.util.keyboard
import android.graphics.Rect
import android.support.v7.app.AppCompatActivity
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.toshi.R
import com.toshi.extensions.getPxSize
class KeyboardListener(
private val activity: AppCompatActivity,
private val onKeyboardVisible: () -> Unit
) {
private val layoutListener: ViewTreeObserver.OnGlobalLayoutListener
init {
layoutListener = initKeyboardListener()
}
private fun initKeyboardListener(): ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect()
val threshold = activity.getPxSize(R.dimen.keyboard_threshold)
val activityRoot = activity.findViewById<ViewGroup>(android.R.id.content).getChildAt(0)
var wasOpened = false
val layoutListener = ViewTreeObserver.OnGlobalLayoutListener {
activityRoot.getWindowVisibleDisplayFrame(rect)
val heightDiff = activityRoot.rootView.height - rect.height()
val isOpen = heightDiff > threshold
if (isOpen == wasOpened) return@OnGlobalLayoutListener
wasOpened = isOpen
if (isOpen) onKeyboardVisible()
}
activityRoot?.viewTreeObserver?.addOnGlobalLayoutListener(layoutListener)
return layoutListener
}
fun clear() {
val activityRoot = activity.findViewById<ViewGroup>(android.R.id.content).getChildAt(0)
activityRoot?.viewTreeObserver?.removeOnGlobalLayoutListener { layoutListener }
}
}
|
gpl-3.0
|
06baf6b095a39e75bf4f9af78c41c1a2
| 36.229508 | 95 | 0.711013 | 4.73904 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/advancement/LanternAdvancementBuilder.kt
|
1
|
2052
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.advancement
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.text.toPlain
import org.lanternpowered.server.catalog.AbstractNamedCatalogBuilder
import org.spongepowered.api.advancement.Advancement
import org.spongepowered.api.advancement.DisplayInfo
import org.spongepowered.api.advancement.criteria.AdvancementCriterion
class LanternAdvancementBuilder : AbstractNamedCatalogBuilder<Advancement, Advancement.Builder>(), Advancement.Builder {
private var parent: Advancement? = null
private var criterion: AdvancementCriterion = AdvancementCriterion.empty()
private var displayInfo: DisplayInfo? = null
override fun getFinalName(key: NamespacedKey): String {
val name = this.name
if (name != null)
return name
val displayInfo = this.displayInfo
if (displayInfo != null)
return displayInfo.title.toPlain()
return key.value
}
override fun parent(parent: Advancement?): Advancement.Builder =
this.apply { this.parent = parent }
override fun criterion(criterion: AdvancementCriterion): Advancement.Builder =
this.apply { this.criterion = criterion }
override fun displayInfo(displayInfo: DisplayInfo?): Advancement.Builder =
this.apply { this.displayInfo = displayInfo }
override fun reset(): Advancement.Builder {
this.criterion = AdvancementCriterion.empty()
this.displayInfo = null
this.parent = null
return super.reset()
}
override fun build(key: NamespacedKey, name: String): Advancement =
LanternAdvancement(key, name, this.parent, this.displayInfo, this.criterion)
}
|
mit
|
4d964c81f6c33a3193b0407076830b0b
| 37 | 120 | 0.721248 | 4.761021 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA
|
src/nl/hannahsten/texifyidea/settings/conventions/TexifyConventionsSchemesPanel.kt
|
1
|
6314
|
package nl.hannahsten.texifyidea.settings
import com.intellij.application.options.schemes.AbstractSchemeActions
import com.intellij.application.options.schemes.SchemesModel
import com.intellij.application.options.schemes.SimpleSchemesPanel
import nl.hannahsten.texifyidea.settings.conventions.TexifyConventionsScheme
import nl.hannahsten.texifyidea.settings.conventions.TexifyConventionsSettings
import javax.naming.OperationNotSupportedException
/**
* Controller for managing the convention settings. The panel allows selecting and editing the current scheme and copying settings
* between the schemes. The supplied [TexifyConventionsSettings] instance represents the corresponding model,
* containing the available schemes.
*
* @see TexifyConventionsScheme
* @see TexifyConventionsSettings
*/
internal class TexifyConventionsSchemesPanel(val settings: TexifyConventionsSettings) :
SimpleSchemesPanel<TexifyConventionsScheme>(),
SchemesModel<TexifyConventionsScheme> {
val type: Class<TexifyConventionsScheme>
get() = TexifyConventionsScheme::class.java
/**
* Listeners for changes in the scheme selection.
*/
private val listeners = mutableListOf<Listener>()
/**
* Actions that can be performed with this panel.
*/
val actions = createSchemeActions()
/**
* Registers a listener that will be informed whenever the scheme selection changed.
*
* @param listener the listener that listens to scheme-change events
*/
fun addListener(listener: Listener) = listeners.add(listener)
/**
* Forcefully updates the combo box so that its entries and the current selection reflect the `settings` instance.
*
* This panel instance will update the combo box by itself. Call this method if the `settings` instance has been
* changed externally and these changes need to be reflected.
*/
fun updateComboBoxList() {
settings.currentScheme.also { currentScheme ->
resetSchemes(settings.schemes)
selectScheme(currentScheme)
}
}
/**
* Returns true if a scheme with the given name is present in this panel.
*
* @param name the name to check for
* @param projectScheme ignored
* @return true if a scheme with the given name is present in this panel
*/
override fun containsScheme(name: String, projectScheme: Boolean) = settings.schemes.any { it.name == name }
/**
* Returns an object with a number of actions that can be performed on this panel.
*
* @return an object with a number of actions that can be performed on this panel
*/
override fun createSchemeActions() = SchemeActions()
override fun getModel() = this
override fun supportsProjectSchemes() = true
override fun highlightNonDefaultSchemes() = true
override fun useBoldForNonRemovableSchemes() = true
override fun isProjectScheme(scheme: TexifyConventionsScheme) = scheme.isProjectScheme
override fun canDeleteScheme(scheme: TexifyConventionsScheme) = false
override fun canDuplicateScheme(scheme: TexifyConventionsScheme) = false
override fun canRenameScheme(scheme: TexifyConventionsScheme) = false
override fun canResetScheme(scheme: TexifyConventionsScheme) = true
override fun differsFromDefault(scheme: TexifyConventionsScheme): Boolean {
// schemes differ if any setting except the name is different
return scheme.deepCopy() != TexifyConventionsScheme(myName = scheme.myName)
}
override fun removeScheme(scheme: TexifyConventionsScheme) {
throw OperationNotSupportedException()
}
/**
* The actions that can be performed with this panel.
*/
inner class SchemeActions : AbstractSchemeActions<TexifyConventionsScheme>(this) {
/**
* Called when the user changes the scheme using the combo box.
*
* @param scheme the scheme that has become the selected scheme
*/
public override fun onSchemeChanged(scheme: TexifyConventionsScheme?) {
if (scheme == null)
return
listeners.forEach { it.onCurrentSchemeWillChange(settings.currentScheme) }
settings.currentScheme = scheme
listeners.forEach { it.onCurrentSchemeHasChanged(scheme) }
}
override fun copyToIDE(scheme: TexifyConventionsScheme) {
settings.copyToDefaultScheme(scheme)
}
override fun copyToProject(scheme: TexifyConventionsScheme) {
settings.copyToProjectScheme(scheme)
}
override fun getSchemeType() = type
override fun resetScheme(scheme: TexifyConventionsScheme) {
scheme.copyFrom(TexifyConventionsScheme())
listeners.forEach { it.onCurrentSchemeHasChanged(scheme) }
}
/**
* Duplicates the currently active scheme.
*
* This method is useful only if there can be other schemes besides the projet and the global default scheme,
* which is currently not supported.
*/
override fun duplicateScheme(scheme: TexifyConventionsScheme, newName: String) {
throw OperationNotSupportedException()
}
/**
* Renames the currently active scheme.
*
* This method is useful only if there can be other schemes besides the projet and the global default scheme,
* which is currently not supported.
*/
override fun renameScheme(scheme: TexifyConventionsScheme, newName: String) {
throw OperationNotSupportedException()
}
}
/**
* A listener that listens to events that occur to this panel.
*/
interface Listener {
/**
* Invoked when the currently-selected scheme is about to change.
*
* @param scheme the scheme that is about to be replaced in favor of another scheme
*/
fun onCurrentSchemeWillChange(scheme: TexifyConventionsScheme)
/**
* Invoked when the currently-selected scheme has just been changed.
*
* @param scheme the scheme that has become the currently-selected scheme
*/
fun onCurrentSchemeHasChanged(scheme: TexifyConventionsScheme)
}
}
|
mit
|
08664e435cf6666d1e830aab98a81105
| 35.50289 | 131 | 0.693855 | 5.183908 | false | false | false | false |
ansman/okhttp
|
okhttp/src/main/kotlin/okhttp3/internal/http2/Settings.kt
|
7
|
3907
|
/*
* Copyright (C) 2012 Square, Inc.
*
* 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 okhttp3.internal.http2
/**
* Settings describe characteristics of the sending peer, which are used by the receiving peer.
* Settings are [connection][Http2Connection] scoped.
*/
class Settings {
/** Bitfield of which flags that values. */
private var set: Int = 0
/** Flag values. */
private val values = IntArray(COUNT)
/** Returns -1 if unset. */
val headerTableSize: Int
get() {
val bit = 1 shl HEADER_TABLE_SIZE
return if (bit and set != 0) values[HEADER_TABLE_SIZE] else -1
}
val initialWindowSize: Int
get() {
val bit = 1 shl INITIAL_WINDOW_SIZE
return if (bit and set != 0) values[INITIAL_WINDOW_SIZE] else DEFAULT_INITIAL_WINDOW_SIZE
}
fun clear() {
set = 0
values.fill(0)
}
operator fun set(id: Int, value: Int): Settings {
if (id < 0 || id >= values.size) {
return this // Discard unknown settings.
}
val bit = 1 shl id
set = set or bit
values[id] = value
return this
}
/** Returns true if a value has been assigned for the setting `id`. */
fun isSet(id: Int): Boolean {
val bit = 1 shl id
return set and bit != 0
}
/** Returns the value for the setting `id`, or 0 if unset. */
operator fun get(id: Int): Int = values[id]
/** Returns the number of settings that have values assigned. */
fun size(): Int = Integer.bitCount(set)
// TODO: honor this setting.
fun getEnablePush(defaultValue: Boolean): Boolean {
val bit = 1 shl ENABLE_PUSH
return if (bit and set != 0) values[ENABLE_PUSH] == 1 else defaultValue
}
fun getMaxConcurrentStreams(): Int {
val bit = 1 shl MAX_CONCURRENT_STREAMS
return if (bit and set != 0) values[MAX_CONCURRENT_STREAMS] else Int.MAX_VALUE
}
fun getMaxFrameSize(defaultValue: Int): Int {
val bit = 1 shl MAX_FRAME_SIZE
return if (bit and set != 0) values[MAX_FRAME_SIZE] else defaultValue
}
fun getMaxHeaderListSize(defaultValue: Int): Int {
val bit = 1 shl MAX_HEADER_LIST_SIZE
return if (bit and set != 0) values[MAX_HEADER_LIST_SIZE] else defaultValue
}
/**
* Writes `other` into this. If any setting is populated by this and `other`, the
* value and flags from `other` will be kept.
*/
fun merge(other: Settings) {
for (i in 0 until COUNT) {
if (!other.isSet(i)) continue
set(i, other[i])
}
}
companion object {
/**
* From the HTTP/2 specs, the default initial window size for all streams is 64 KiB. (Chrome 25
* uses 10 MiB).
*/
const val DEFAULT_INITIAL_WINDOW_SIZE = 65535
/** HTTP/2: Size in bytes of the table used to decode the sender's header blocks. */
const val HEADER_TABLE_SIZE = 1
/** HTTP/2: The peer must not send a PUSH_PROMISE frame when this is 0. */
const val ENABLE_PUSH = 2
/** Sender's maximum number of concurrent streams. */
const val MAX_CONCURRENT_STREAMS = 4
/** HTTP/2: Size in bytes of the largest frame payload the sender will accept. */
const val MAX_FRAME_SIZE = 5
/** HTTP/2: Advisory only. Size in bytes of the largest header list the sender will accept. */
const val MAX_HEADER_LIST_SIZE = 6
/** Window size in bytes. */
const val INITIAL_WINDOW_SIZE = 7
/** Total number of settings. */
const val COUNT = 10
}
}
|
apache-2.0
|
1211f2441cef067cec513e1f339ae68d
| 30.007937 | 99 | 0.656514 | 3.834151 | false | false | false | false |
SpineEventEngine/core-java
|
buildSrc/src/main/kotlin/io/spine/internal/gradle/publish/CloudArtifactRegistry.kt
|
2
|
3645
|
/*
* Copyright 2022, TeamDev. 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
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* 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
* OWNER 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 io.spine.internal.gradle.publish
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.artifactregistry.auth.DefaultCredentialProvider
import io.spine.internal.gradle.Credentials
import io.spine.internal.gradle.Repository
import java.io.IOException
import org.gradle.api.Project
/**
* The experimental Google Cloud Artifact Registry repository.
*
* In order to successfully publish into this repository, a service account key is needed.
* The published must create a service account, grant it the permission to write into
* Artifact Registry, and generate a JSON key.
* Then, the key must be placed somewhere on the file system and the environment variable
* `GOOGLE_APPLICATION_CREDENTIALS` must be set to point at the key file.
* Once these preconditions are met, publishing becomes possible.
*
* Google provides a Gradle plugin for configuring the publishing repository credentials
* automatically. We achieve the same goal by assembling the credentials manually. We do so
* in order to fit the Google Cloud Artifact Registry repository into the standard frame of
* the Maven [Repository]-s. Applying the plugin would take a substantial effort due to the fact
* that both our publishing scripts and the Google's plugin use `afterEvaluate { }` hooks.
* Ordering said hooks is a non-trivial operation and the result is usually quite fragile.
* Thus, we choose to do this small piece of configuration manually.
*/
internal object CloudArtifactRegistry {
private const val spineRepoLocation = "https://europe-maven.pkg.dev/spine-event-engine"
val repository = Repository(
releases = "${spineRepoLocation}/releases",
snapshots = "${spineRepoLocation}/snapshots",
credentialValues = this::fetchGoogleCredentials
)
private fun fetchGoogleCredentials(p: Project): Credentials? {
return try {
val googleCreds = DefaultCredentialProvider()
val creds = googleCreds.credential as GoogleCredentials
creds.refreshIfExpired()
Credentials("oauth2accesstoken", creds.accessToken.tokenValue)
} catch (e: IOException) {
p.logger.info("Unable to fetch credentials for Google Cloud Artifact Registry." +
" Reason: '${e.message}'." +
" The debug output may contain more details.")
null
}
}
}
|
apache-2.0
|
4dcb646571472965021723d29d29464d
| 45.730769 | 96 | 0.740192 | 4.655172 | false | false | false | false |
briantwatson/developer-support
|
runtime-android/kotlin-extensions/graphic-extensions/GraphicExt.kt
|
3
|
2460
|
/**
* A function that animates the movement of a marker graphic to provide a
* nice transition of a marker to a new location.
*/
fun Graphic.animatePointGraphic(handler: Handler, destination: Point) {
handler.removeCallbacksAndMessages(null)
val start = SystemClock.uptimeMillis()
val duration: Long = 1000
val graphic = this
val interpolator = LinearInterpolator()
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t = interpolator.getInterpolation(elapsed.toFloat() / duration)
val lng = t * destination.x + (1 - t) * (graphic.geometry as Point).x
val lat = t * destination.y + (1 - t) * (graphic.geometry as Point).y
graphic.geometry = Point(lng, lat, graphic.geometry.spatialReference)
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16)
}
}
})
}
/**
* The puleGraphicSize method allows developers to pulse a graphic size to show the graphic
* changing and getting larger and smaller between a range.
*/
fun Graphic.pulseGraphicSize(period: Long, min: Float = 2.0f, max: Float = 20.0f) {
val timer = Timer("pulse", false)
timer.scheduleAtFixedRate(SizePulseTimer(this.symbol, min, max), 0, period)
}
/**
*
* This class is used exclusively with the pulseGraphicSize extension function. This allows
* developers to easily pulse a graphic size.
*
*/
private class SizePulseTimer(val symbol: Symbol, val min: Float = 2.0f, val max: Float = 20.0f) : TimerTask() {
var size = 5.0f
var goingDown = true
override fun run() {
when(symbol) {
is SimpleMarkerSymbol -> symbol.size += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.size }
is PictureMarkerSymbol -> {
symbol.height += (if (goingDown) (-.01f) else (.01f))
symbol.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.height }
}
is SimpleLineSymbol -> symbol.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.width }
is SimpleFillSymbol -> symbol.outline.width += (if (goingDown) (-.01f) else (.01f)).apply { size = symbol.outline.width }
}
if (size < min) {
goingDown = false
} else if (size > max) {
goingDown = true
}
}
}
|
apache-2.0
|
44f16879e36f5bd3d9a5321f14ccfa42
| 34.652174 | 133 | 0.60813 | 3.967742 | false | false | false | false |
nemerosa/ontrack
|
ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/graphql/GQLLinksContributorImpl.kt
|
1
|
4654
|
package net.nemerosa.ontrack.boot.graphql
import graphql.Scalars.GraphQLString
import graphql.schema.DataFetcher
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLFieldDefinition.newFieldDefinition
import graphql.schema.GraphQLObjectType.newObject
import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.ui.controller.EntityURIBuilder
import net.nemerosa.ontrack.ui.resource.DefaultResourceContext
import net.nemerosa.ontrack.ui.resource.ResourceContext
import net.nemerosa.ontrack.ui.resource.ResourceDecorator
import net.nemerosa.ontrack.ui.resource.ResourceDecoratorDelegate
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
@Component
class GQLLinksContributorImpl(
private val uriBuilder: EntityURIBuilder,
private val securityService: SecurityService,
private val decorators: List<ResourceDecorator<*>>
) : GQLFieldContributor {
override fun getFields(type: Class<*>): List<GraphQLFieldDefinition> {
val resourceContext = DefaultResourceContext(uriBuilder, securityService)
val definitions = mutableListOf<GraphQLFieldDefinition>()
// Links
val typeDecorators = decorators
.filter { decorator -> decorator.appliesFor(type) }
val linkNames = typeDecorators
.flatMap { decorator -> decorator.linkNames }
.distinct()
if (linkNames.isNotEmpty()) {
definitions.add(
newFieldDefinition()
.name("links")
.description("Links")
.deprecate("Use the `actions` field instead.")
.type(
newObject()
.name(type.simpleName + "Links")
.description(type.simpleName + " links")
.fields(
linkNames
.map { linkName ->
newFieldDefinition()
.name(linkName)
.type(GraphQLString)
.dataFetcher(linkDataFetcher(linkName))
.build()
}
)
.build()
)
.dataFetcher { env -> LinksCache(resourceContext, env.getSource(), typeDecorators) }
.build()
)
}
// OK
return definitions
}
private fun linkDataFetcher(linkName: String) =
DataFetcher<String> { environment ->
val linksCache = environment.getSource<LinksCache>()
linksCache.getLink(linkName)
}
private class LinksCache(
private val resourceContext: ResourceContext,
private val source: Any,
private val typeDecorators: List<ResourceDecorator<*>>
) {
private val cache = ConcurrentHashMap<String, CachedLink>()
fun getLink(linkName: String): String? =
cache.getOrPut(linkName) {
computeLink(linkName)
}.link
private fun computeLink(linkName: String): CachedLink {
val link = typeDecorators.mapNotNull { decorator ->
computeLink(decorator, linkName)
}.firstOrNull()
return CachedLink(link)
}
private fun <T: Any> computeLink(decorator: ResourceDecorator<T>, linkName: String): String? =
if (linkName in decorator.linkNames) {
@Suppress("UNCHECKED_CAST")
val t: T = if (source is ResourceDecoratorDelegate) {
source.getLinkDelegate()
} else {
source
} as T
val link = decorator.linkByName(t, resourceContext, linkName)
link?.href?.toString()
} else {
null
}
}
private class CachedLink(val link: String?)
}
|
mit
|
0a767dcc4d2431338db3a28183b586a3
| 42.092593 | 112 | 0.515685 | 6.289189 | false | false | false | false |
yh-kim/gachi-android
|
Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/search/SearchPresenter.kt
|
1
|
3180
|
/*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.main.fragments.search
import com.pickth.commons.mvp.BaseView
import com.pickth.gachi.net.service.FestivalService
import com.pickth.gachi.util.OnItemClickListener
import com.pickth.gachi.view.main.fragments.festival.adapter.Festival
import com.pickth.gachi.view.main.fragments.search.adapter.SearchAdapterContract
import okhttp3.ResponseBody
import org.json.JSONArray
import retrofit2.Call
import retrofit2.Response
class SearchPresenter: SearchContract.Presenter, OnItemClickListener {
private lateinit var mView: SearchContract.View
private lateinit var mAdapterView: SearchAdapterContract.View
private lateinit var mAdapterModel: SearchAdapterContract.Model
override fun attachView(view: BaseView<*>) {
mView = view as SearchContract.View
}
override fun setAdapterView(view: SearchAdapterContract.View) {
mAdapterView = view
mAdapterView.setItemClickListener(this)
}
override fun setAdapterModel(model: SearchAdapterContract.Model) {
mAdapterModel = model
}
override fun searchFestivalList(text: String, page: Int) {
FestivalService().searchFestival(text, page)
.enqueue(object: retrofit2.Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
if(response?.code() != 200) return
val retArr = JSONArray(response.body()!!.string())
for(position in 0..retArr.length() - 1) {
retArr.getJSONObject(position).let {
val fid = it.getString("fid")
val title = it.getString("title")
val image = it.getString("image")
val from = it.getString("from").split("T")[0].replace("-",".")
val until = it.getString("until").split("T")[0].replace("-",".")
var date = "$from - $until"
mAdapterModel.addItem(Festival(fid, date, image, title))
}
}
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
}
})
}
override fun clearList() {
mAdapterModel.clearItems()
}
override fun onItemClick(position: Int) {
mView.intentToFestivalDetailActivity(mAdapterModel.getItem(position).fid)
}
}
|
apache-2.0
|
733daed00d4a86fabb9d1e865d13971b
| 37.792683 | 107 | 0.625157 | 4.760479 | false | false | false | false |
vjames19/kotlin-microservice-example
|
domain-implementation/src/main/kotlin/io/github/vjames19/kotlinmicroserviceexample/blog/service/RequeryPostService.kt
|
1
|
1979
|
package io.github.vjames19.kotlinmicroserviceexample.blog.service
import io.github.vjames19.kotlinmicroserviceexample.blog.domain.Post
import io.github.vjames19.kotlinmicroserviceexample.blog.model.PostModel
import io.github.vjames19.kotlinmicroserviceexample.blog.model.toDomain
import io.github.vjames19.kotlinmicroserviceexample.blog.model.toModel
import io.github.vjames19.kotlinmicroserviceexample.blog.util.KotlinCompletableEntityStore
import io.github.vjames19.kotlinmicroserviceexample.blog.util.doUpdate
import io.github.vjames19.kotlinmicroserviceexample.blog.util.firstOption
import io.github.vjames19.kotlinmicroserviceexample.blog.util.toOptional
import io.requery.Persistable
import io.requery.kotlin.eq
import java.util.*
import java.util.concurrent.CompletableFuture
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by victor.reventos on 6/9/17.
*/
@Singleton
class RequeryPostService @Inject constructor(val db: KotlinCompletableEntityStore<Persistable>) : PostService {
override fun getAllPostsForUser(userId: Long): CompletableFuture<List<Post>> = db.execute {
(select(PostModel::class) where (PostModel::userId eq (userId))).get()
.map(PostModel::toDomain)
}
override fun get(id: Long): CompletableFuture<Optional<Post>> = db.execute {
(select(PostModel::class) where (PostModel::id eq (id)) limit 1).get()
.firstOption()
.map(PostModel::toDomain)
}
override fun create(post: Post): CompletableFuture<Post> = db.execute {
insert(post.toModel()).toDomain()
}
override fun update(post: Post): CompletableFuture<Optional<Post>> = db.execute {
doUpdate {
update(post.toModel()).toDomain()
}
}
override fun delete(id: Long): CompletableFuture<Optional<*>> = db.execute {
(db.delete(PostModel::class) where (PostModel::id eq id))
.get()
.toOptional()
}
}
|
mit
|
fee6aad464ad8fac4e43bc14013a01b1
| 38.6 | 111 | 0.730167 | 4.080412 | false | false | false | false |
ohmae/mmupnp
|
mmupnp/src/test/java/net/mm2d/upnp/empty/EmptySsdpMessageTest.kt
|
1
|
1936
|
/*
* Copyright (c) 2018 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.empty
import com.google.common.truth.Truth.assertThat
import io.mockk.mockk
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.IOException
@RunWith(JUnit4::class)
class EmptySsdpMessageTest {
@Test
fun isPinned() {
val message = EmptySsdpMessage
assertThat(message.isPinned).isFalse()
}
@Test
fun getScopeId() {
val message = EmptySsdpMessage
assertThat(message.scopeId).isEqualTo(0)
}
@Test
fun getLocalAddress() {
val message = EmptySsdpMessage
assertThat(message.localAddress).isNull()
}
@Test
fun getHeader() {
val message = EmptySsdpMessage
assertThat(message.getHeader("")).isNull()
}
@Test
fun setHeader() {
val message = EmptySsdpMessage
message.setHeader("", "")
}
@Test
fun getUuid() {
val message = EmptySsdpMessage
assertThat(message.uuid).isNotNull()
}
@Test
fun getType() {
val message = EmptySsdpMessage
assertThat(message.type).isNotNull()
}
@Test
fun getNts() {
val message = EmptySsdpMessage
assertThat(message.nts).isNull()
}
@Test
fun getMaxAge() {
val message = EmptySsdpMessage
assertThat(message.maxAge >= 0).isTrue()
}
@Test
fun getExpireTime() {
val message = EmptySsdpMessage
assertThat(message.expireTime >= 0).isTrue()
}
@Test
fun getLocation() {
val message = EmptySsdpMessage
assertThat(message.location).isNull()
}
@Test(expected = IOException::class)
fun writeData() {
val message = EmptySsdpMessage
message.writeData(mockk())
}
}
|
mit
|
ec7264ac7276ad95051cfa76d018bfd6
| 20.422222 | 52 | 0.623444 | 4.155172 | false | true | false | false |
stoman/competitive-programming
|
problems/2021adventofcode08a/submissions/accepted/Stefan.kt
|
2
|
306
|
import java.util.*
import kotlin.math.absoluteValue
fun main() {
val s = Scanner(System.`in`).useDelimiter("\n")
var ret = 0
while(s.hasNext()) {
val line = s.next().split(" | ")
val output = line[1].split(" ")
ret += output.count { it.length in setOf(2, 3, 4, 7) }
}
println(ret)
}
|
mit
|
a675054e2c4a9e15651ffa806cd84361
| 22.538462 | 58 | 0.591503 | 3.06 | false | false | false | false |
apixandru/intellij-community
|
python/educational-core/src/com/jetbrains/edu/learning/actions/StudySwitchTaskPanelAction.kt
|
6
|
2181
|
package com.jetbrains.edu.learning.actions
import com.intellij.openapi.actionSystem.ActionPlaces.ACTION_SEARCH
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.DialogWrapper
import com.jetbrains.edu.learning.StudySettings
import com.jetbrains.edu.learning.StudyUtils
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
import javax.swing.JLabel
class StudySwitchTaskPanelAction: AnAction() {
override fun actionPerformed(e: AnActionEvent?) {
val project = e?.project
val result = createDialog().showAndGet()
if (result && project != null) {
StudyUtils.initToolWindows(project)
}
}
fun createDialog(): DialogWrapper {
return MyDialog(false)
}
class MyDialog(canBeParent: Boolean) : DialogWrapper(null, canBeParent) {
val JAVAFX_ITEM = "JavaFX"
val SWING_ITEM = "Swing"
private val myComboBox: ComboBox<String> = ComboBox()
override fun createCenterPanel(): JComponent? {
return myComboBox
}
override fun createNorthPanel(): JComponent? {
return JLabel("Choose panel: ")
}
override fun getPreferredFocusedComponent(): JComponent? {
return myComboBox
}
override fun doOKAction() {
super.doOKAction()
StudySettings.getInstance().setShouldUseJavaFx(myComboBox.selectedItem == JAVAFX_ITEM)
}
init {
val comboBoxModel = DefaultComboBoxModel<String>()
if (StudyUtils.hasJavaFx()) {
comboBoxModel.addElement(JAVAFX_ITEM)
}
comboBoxModel.addElement(SWING_ITEM)
comboBoxModel.selectedItem =
if (StudyUtils.hasJavaFx() && StudySettings.getInstance().shouldUseJavaFx()) JAVAFX_ITEM else SWING_ITEM
myComboBox.model = comboBoxModel
title = "Switch Task Description Panel"
myComboBox.setMinimumAndPreferredWidth(250)
init()
}
}
override fun update(e: AnActionEvent?) {
val place = e?.place
val project = e?.project
e?.presentation?.isEnabled = project != null && StudyUtils.isStudyProject(project) || ACTION_SEARCH == place
}
}
|
apache-2.0
|
15a03efd95508ae73d3a46c669267a05
| 29.732394 | 114 | 0.718478 | 4.487654 | false | false | false | false |
ffc-nectec/FFC
|
ffc/src/main/kotlin/ffc/app/auth/LoginActivity.kt
|
1
|
5867
|
/*
* Copyright (c) 2019 NECTEC
* National Electronics and Computer Technology Center, Thailand
*
* 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 ffc.app.auth
import android.os.Bundle
import android.transition.Explode
import android.transition.Fade
import android.transition.Slide
import android.view.Gravity
import ffc.android.allowTransitionOverlap
import ffc.android.enter
import ffc.android.exit
import ffc.android.find
import ffc.android.findFirst
import ffc.android.onLongClick
import ffc.android.setTransition
import ffc.app.BuildConfig
import ffc.app.FamilyFolderActivity
import ffc.app.R
import ffc.app.auth.legal.LegalAgreementActivity
import ffc.app.setting.SettingsActivity
import ffc.entity.Organization
import ffc.entity.gson.parseTo
import ffc.entity.gson.toJson
import kotlinx.android.synthetic.main.login_activity.versionView
import org.jetbrains.anko.alert
import org.jetbrains.anko.appcompat.v7.Appcompat
import org.jetbrains.anko.startActivity
import timber.log.Timber
class LoginActivity : FamilyFolderActivity(), LoginPresenter {
private lateinit var interactor: LoginInteractor
val isRelogin
get() = intent.getBooleanExtra("relogin", false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
setTransition {
enterTransition = Fade().enter().addTarget(R.id.overlay)
}
val auth = auth(this)
Timber.d("User id = ${auth.user?.id}")
interactor = LoginInteractor(this, auth, isRelogin)
savedInstanceState?.let { saved ->
val org = saved.getString("org")?.parseTo<Organization>()
org?.let { interactor.org = org }
}
versionView.text = "v${BuildConfig.VERSION_NAME}"
versionView.onLongClick {
startActivity<SettingsActivity>()
true
}
}
override fun showOrgSelector() {
if (savedInstanceState == null) {
val fragment = LoginOrgFragment()
fragment.orgSelected = { interactor.org = it }
fragment.setTransition {
exitTransition = Explode().exit()
allowTransitionOverlap = false
}
supportFragmentManager.beginTransaction()
.replace(R.id.contentContainer, fragment, "Org")
.commit()
}
}
override fun onLoginSuccess() {
if (!isRelogin) {
startActivity<LegalAgreementActivity>()
overridePendingTransition(0, 0)
}
finish()
}
override fun onSaveInstanceState(outState: Bundle) {
interactor.org?.let { outState.putString("org", it.toJson()) }
super.onSaveInstanceState(outState)
}
override fun onError(throwable: Throwable) {
supportFragmentManager
.findFirst<LoginExceptionPresenter>("otp", "Login", "Org")?.onException(throwable)
}
override fun onOrgSelected(org: Organization) {
val userPassFragment = supportFragmentManager.find("Login")
?: LoginUserFragment()
userPassFragment.onLogin = { user, pass -> interactor.doLogin(user, pass) }
userPassFragment.org = org
userPassFragment.setTransition {
enterTransition = Slide(Gravity.END).enter(delay = 50)
exitTransition = Explode().exit()
}
val orgFragment = supportFragmentManager.find<LoginOrgFragment?>("Org")
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().apply {
add(R.id.contentContainer, userPassFragment, "Login")
if (orgFragment != null) {
//there no orgFragment for Relogin action
hide(orgFragment)
addToBackStack(null)
}
}.commit()
}
}
override fun onActivateRequire() {
val otpFragment = supportFragmentManager.find("otp") ?: OtpFragment()
otpFragment.onOtpSend = { interactor.doActivate(it) }
otpFragment.setTransition {
enterTransition = Slide(Gravity.END).enter(delay = 50)
}
val userPassFragment = supportFragmentManager.find<LoginUserFragment?>("Login")
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().apply {
add(R.id.contentContainer, otpFragment, "otp")
if (userPassFragment != null) {
//there no orgFragment for Relogin action
hide(userPassFragment)
addToBackStack(null)
}
}.commit()
}
}
override fun onBackPressed() {
if (supportFragmentManager.backStackEntryCount > 0)
super.onBackPressed()
else {
alert(Appcompat, R.string.r_u_sure_to_close_app, R.string.close_app) {
iconResource = R.drawable.ic_logout_color_24dp
positiveButton(R.string.close_app) {
finishAffinity()
if (isRelogin) auth(this@LoginActivity).clear()
}
negativeButton(R.string.no) {}
}.show()
}
}
}
fun FamilyFolderActivity.relogin() {
startActivity<LoginActivity>("relogin" to true)
}
|
apache-2.0
|
673c7202e2d9ac478720ae8bf14ab68a
| 33.511765 | 94 | 0.640532 | 4.781581 | false | false | false | false |
panpf/sketch
|
sample/src/main/java/com/github/panpf/sketch/sample/util/ParamLazy.kt
|
1
|
1317
|
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* 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.github.panpf.sketch.sample.util
class ParamLazy<P, R>(private val callback: Callback<P, R>) {
@Volatile
private var instance: R? = null
fun get(p: P): R {
synchronized(this) {
val tempInstance = instance
if (tempInstance != null) return tempInstance
synchronized(this) {
val tempInstance2 = instance
if (tempInstance2 != null) return tempInstance2
val newInstance = callback.createInstantiate(p)
instance = newInstance
return newInstance
}
}
}
fun interface Callback<P, R> {
fun createInstantiate(p: P): R
}
}
|
apache-2.0
|
8bb1005d609d5249f67c790bf99b9cc1
| 31.95 | 75 | 0.645406 | 4.360927 | false | false | false | false |
android/security-samples
|
BiometricLoginKotlin/app/src/main/java/com/example/biometricloginsample/EnableBiometricLoginActivity.kt
|
1
|
4836
|
/*
* Copyright (C) 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 com.example.biometricloginsample
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.Observer
import com.example.biometricloginsample.databinding.ActivityEnableBiometricLoginBinding
class EnableBiometricLoginActivity : AppCompatActivity() {
private val TAG = "EnableBiometricLogin"
private lateinit var cryptographyManager: CryptographyManager
private val loginViewModel by viewModels<LoginWithPasswordViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityEnableBiometricLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.cancel.setOnClickListener { finish() }
loginViewModel.loginWithPasswordFormState.observe(this, Observer { formState ->
val loginState = formState ?: return@Observer
when (loginState) {
is SuccessfulLoginFormState -> binding.authorize.isEnabled = loginState.isDataValid
is FailedLoginFormState -> {
loginState.usernameError?.let { binding.username.error = getString(it) }
loginState.passwordError?.let { binding.password.error = getString(it) }
}
}
})
loginViewModel.loginResult.observe(this, Observer {
val loginResult = it ?: return@Observer
if (loginResult.success) {
showBiometricPromptForEncryption()
}
})
binding.username.doAfterTextChanged {
loginViewModel.onLoginDataChanged(
binding.username.text.toString(),
binding.password.text.toString()
)
}
binding.password.doAfterTextChanged {
loginViewModel.onLoginDataChanged(
binding.username.text.toString(),
binding.password.text.toString()
)
}
binding.password.setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE ->
loginViewModel.login(
binding.username.text.toString(),
binding.password.text.toString()
)
}
false
}
binding.authorize.setOnClickListener {
loginViewModel.login(binding.username.text.toString(), binding.password.text.toString())
}
}
private fun showBiometricPromptForEncryption() {
val canAuthenticate = BiometricManager.from(applicationContext).canAuthenticate()
if (canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS) {
val secretKeyName = getString(R.string.secret_key_name)
cryptographyManager = CryptographyManager()
val cipher = cryptographyManager.getInitializedCipherForEncryption(secretKeyName)
val biometricPrompt =
BiometricPromptUtils.createBiometricPrompt(this, ::encryptAndStoreServerToken)
val promptInfo = BiometricPromptUtils.createPromptInfo(this)
biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
}
}
private fun encryptAndStoreServerToken(authResult: BiometricPrompt.AuthenticationResult) {
authResult.cryptoObject?.cipher?.apply {
SampleAppUser.fakeToken?.let { token ->
Log.d(TAG, "The token from server is $token")
val encryptedServerTokenWrapper = cryptographyManager.encryptData(token, this)
cryptographyManager.persistCiphertextWrapperToSharedPrefs(
encryptedServerTokenWrapper,
applicationContext,
SHARED_PREFS_FILENAME,
Context.MODE_PRIVATE,
CIPHERTEXT_WRAPPER
)
}
}
finish()
}
}
|
apache-2.0
|
1256f21a7a223b503ba68cc63af9fab0
| 41.80531 | 100 | 0.662738 | 5.36737 | false | false | false | false |
wikimedia/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/dataclient/ServiceFactory.kt
|
1
|
4003
|
package org.wikipedia.dataclient
import androidx.collection.lruCache
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Response
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.eventplatform.DestinationEventService
import org.wikipedia.analytics.eventplatform.EventService
import org.wikipedia.analytics.eventplatform.StreamConfig
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory
import org.wikipedia.json.JsonUtil
import org.wikipedia.settings.Prefs
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.create
import java.io.IOException
object ServiceFactory {
private const val SERVICE_CACHE_SIZE = 8
private val SERVICE_CACHE = lruCache<WikiSite, Service>(SERVICE_CACHE_SIZE, create = {
// This method is called in the get() method if a value does not already exist.
createRetrofit(it, getBasePath(it)).create<Service>()
})
private val REST_SERVICE_CACHE = lruCache<WikiSite, RestService>(SERVICE_CACHE_SIZE, create = {
createRetrofit(it, getRestBasePath(it)).create<RestService>()
})
private val CORE_REST_SERVICE_CACHE = lruCache<WikiSite, CoreRestService>(SERVICE_CACHE_SIZE, create = {
createRetrofit(it, it.url() + "/" + CoreRestService.CORE_REST_API_PREFIX).create<CoreRestService>()
})
private val ANALYTICS_REST_SERVICE_CACHE = lruCache<DestinationEventService, EventService>(SERVICE_CACHE_SIZE, create = {
val intakeBaseUriOverride = Prefs.eventPlatformIntakeUriOverride.ifEmpty { it.baseUri }
createRetrofit(null, intakeBaseUriOverride).create<EventService>()
})
fun get(wiki: WikiSite): Service {
return SERVICE_CACHE[wiki]!!
}
fun getRest(wiki: WikiSite): RestService {
return REST_SERVICE_CACHE[wiki]!!
}
fun getCoreRest(wiki: WikiSite): CoreRestService {
return CORE_REST_SERVICE_CACHE[wiki]!!
}
fun getAnalyticsRest(streamConfig: StreamConfig): EventService {
return ANALYTICS_REST_SERVICE_CACHE[streamConfig.destinationEventService]!!
}
operator fun <T> get(wiki: WikiSite, baseUrl: String?, service: Class<T>): T {
val r = createRetrofit(wiki, baseUrl.orEmpty().ifEmpty { wiki.url() + "/" })
return r.create(service)
}
private fun getBasePath(wiki: WikiSite): String {
return Prefs.mediaWikiBaseUrl.ifEmpty { wiki.url() + "/" }
}
fun getRestBasePath(wiki: WikiSite): String {
var path = if (Prefs.restbaseUriFormat.isEmpty()) wiki.url() + "/" + RestService.REST_API_PREFIX
else String.format(Prefs.restbaseUriFormat, "https", wiki.authority())
if (!path.endsWith("/")) {
path += "/"
}
return path
}
private fun createRetrofit(wiki: WikiSite?, baseUrl: String): Retrofit {
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(OkHttpConnectionFactory.client.newBuilder().addInterceptor(LanguageVariantHeaderInterceptor(wiki)).build())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(JsonUtil.json.asConverterFactory("application/json".toMediaType()))
.build()
}
private class LanguageVariantHeaderInterceptor(private val wiki: WikiSite?) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
// TODO: remove when the https://phabricator.wikimedia.org/T271145 is resolved.
if (!request.url.encodedPath.contains("/page/related")) {
request = request.newBuilder()
.header("Accept-Language", WikipediaApp.instance.getAcceptLanguage(wiki))
.build()
}
return chain.proceed(request)
}
}
}
|
apache-2.0
|
c89afd03f85ddb86303a76a46b238783
| 39.434343 | 127 | 0.698976 | 4.585338 | false | false | false | false |
mvarnagiris/expensius
|
data/src/main/kotlin/com/mvcoding/expensius/data/ParameterRealtimeDataSource.kt
|
1
|
2220
|
/*
* Copyright (C) 2017 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.data
import rx.Observable
import java.io.Closeable
import java.util.concurrent.atomic.AtomicReference
class ParameterRealtimeDataSource<in PARAMETER, ITEM>(
private val parameterSource: DataSource<PARAMETER>,
private val createRealtimeList: (PARAMETER) -> RealtimeList<ITEM>,
private val getItemId: (ITEM) -> String) : DataSource<RealtimeData<ITEM>>, Closeable {
private val userIdAndRealtimeListDataSource = AtomicReference<Pair<PARAMETER, RealtimeListDataSource<ITEM>>?>()
override fun data(): Observable<RealtimeData<ITEM>> = parameterSource.data()
.distinctUntilChanged()
.switchMap {
val currentUserIdAndRealtimeListDataSource = userIdAndRealtimeListDataSource.get()
val currentUserId = currentUserIdAndRealtimeListDataSource?.first
val currentRealtimeListDataSource = currentUserIdAndRealtimeListDataSource?.second
val shouldUseSameRealtimeListDataSource = currentUserId != null && currentRealtimeListDataSource != null && currentUserId == it
if (shouldUseSameRealtimeListDataSource) currentRealtimeListDataSource!!.data()
else {
currentRealtimeListDataSource?.close()
val realtimeListDataSource = RealtimeListDataSource(createRealtimeList(it)) { getItemId(it) }
userIdAndRealtimeListDataSource.set(Pair(it, realtimeListDataSource))
realtimeListDataSource.data()
}
}
override fun close() {
userIdAndRealtimeListDataSource.get()?.second?.close()
}
}
|
gpl-3.0
|
593320bb2eb3e0521aed145b7587ee6b
| 45.270833 | 143 | 0.706306 | 5.056948 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.