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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
androidx/androidx | emoji2/emoji2-emojipicker/src/main/java/androidx/emoji2/emojipicker/StickyVariantProvider.kt | 3 | 2220 | /*
* 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.emoji2.emojipicker
import android.content.Context
import android.content.Context.MODE_PRIVATE
/**
* A class that handles user's emoji variant selection using SharedPreferences.
*/
internal class StickyVariantProvider(context: Context) {
companion object {
const val PREFERENCES_FILE_NAME = "androidx.emoji2.emojipicker.preferences"
const val STICKY_VARIANT_PROVIDER_KEY = "pref_key_sticky_variant"
const val KEY_VALUE_DELIMITER = "="
const val ENTRY_DELIMITER = "|"
}
private val sharedPreferences =
context.getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE)
private val stickyVariantMap: Map<String, String> by lazy {
sharedPreferences.getString(STICKY_VARIANT_PROVIDER_KEY, null)?.split(ENTRY_DELIMITER)
?.associate { entry ->
entry.split(KEY_VALUE_DELIMITER, limit = 2).takeIf { it.size == 2 }
?.let { it[0] to it[1] } ?: ("" to "")
} ?: mapOf()
}
internal operator fun get(emoji: String): String = stickyVariantMap[emoji] ?: emoji
internal fun update(baseEmoji: String, variantClicked: String) {
stickyVariantMap.toMutableMap().apply {
if (baseEmoji == variantClicked) {
this.remove(baseEmoji)
} else {
this[baseEmoji] = variantClicked
}
sharedPreferences.edit()
.putString(
STICKY_VARIANT_PROVIDER_KEY,
entries.joinToString(ENTRY_DELIMITER)
).commit()
}
}
}
| apache-2.0 | 95fc6da88a76f5d66a2a54a7073df357 | 36 | 94 | 0.65 | 4.475806 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/TextFieldDefaults.kt | 3 | 49563 | /*
* 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.compose.material3
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.interaction.Interaction
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.selection.LocalTextSelectionColors
import androidx.compose.foundation.text.selection.TextSelectionColors
import androidx.compose.material3.TextFieldDefaults.OutlinedTextFieldDecorationBox
import androidx.compose.material3.tokens.FilledTextFieldTokens
import androidx.compose.material3.tokens.OutlinedTextFieldTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* Contains the default values used by [TextField] and [OutlinedTextField].
*/
@ExperimentalMaterial3Api
@Immutable
object TextFieldDefaults {
/** Default shape for an outlined text field. */
val outlinedShape: Shape @Composable get() = OutlinedTextFieldTokens.ContainerShape.toShape()
/** Default shape for a filled text field. */
val filledShape: Shape @Composable get() = FilledTextFieldTokens.ContainerShape.toShape()
/**
* The default min width applied for a [TextField] and [OutlinedTextField].
* Note that you can override it by applying Modifier.heightIn directly on a text field.
*/
val MinHeight = 56.dp
/**
* The default min width applied for a [TextField] and [OutlinedTextField].
* Note that you can override it by applying Modifier.widthIn directly on a text field.
*/
val MinWidth = 280.dp
/**
* The default thickness of the border in [OutlinedTextField] or indicator line in [TextField]
* in unfocused state.
*/
val UnfocusedBorderThickness = 1.dp
/**
* The default thickness of the border in [OutlinedTextField] or indicator line in [TextField]
* in focused state.
*/
val FocusedBorderThickness = 2.dp
/**
* Composable that draws a default container for the content of [TextField], with an indicator
* line at the bottom. You can use it to draw a container for your custom text field based on
* [TextFieldDecorationBox]. [TextField] applies it automatically.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
* @param colors [TextFieldColors] used to resolve colors of the text field
* @param shape shape of the container
*/
@ExperimentalMaterial3Api
@Composable
fun FilledContainerBox(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource,
colors: TextFieldColors,
shape: Shape = filledShape,
) {
Box(
Modifier
.background(colors.containerColor().value, shape)
.indicatorLine(enabled, isError, interactionSource, colors))
}
/**
* A modifier to draw a default bottom indicator line in [TextField]. You can use this modifier
* if you build your custom text field using [TextFieldDecorationBox] whilst the [TextField]
* applies it automatically.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
* @param colors [TextFieldColors] used to resolve colors of the text field
* @param focusedIndicatorLineThickness thickness of the indicator line when text field is
* focused
* @param unfocusedIndicatorLineThickness thickness of the indicator line when text field is
* not focused
*/
@ExperimentalMaterial3Api
fun Modifier.indicatorLine(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource,
colors: TextFieldColors,
focusedIndicatorLineThickness: Dp = FocusedBorderThickness,
unfocusedIndicatorLineThickness: Dp = UnfocusedBorderThickness
) = composed(inspectorInfo = debugInspectorInfo {
name = "indicatorLine"
properties["enabled"] = enabled
properties["isError"] = isError
properties["interactionSource"] = interactionSource
properties["colors"] = colors
properties["focusedIndicatorLineThickness"] = focusedIndicatorLineThickness
properties["unfocusedIndicatorLineThickness"] = unfocusedIndicatorLineThickness
}) {
val stroke = animateBorderStrokeAsState(
enabled,
isError,
interactionSource,
colors,
focusedIndicatorLineThickness,
unfocusedIndicatorLineThickness
)
Modifier.drawIndicatorLine(stroke.value)
}
/**
* Composable that draws a default container for [OutlinedTextField] with a border stroke. You
* can use it to draw a border stroke in your custom text field based on
* [OutlinedTextFieldDecorationBox]. The [OutlinedTextField] applies it automatically.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
* @param colors [TextFieldColors] used to resolve colors of the text field
* @param focusedBorderThickness thickness of the [OutlinedTextField]'s border when it is in
* focused state
* @param unfocusedBorderThickness thickness of the [OutlinedTextField]'s border when it is not
* in focused state
*/
@ExperimentalMaterial3Api
@Composable
fun OutlinedBorderContainerBox(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource,
colors: TextFieldColors,
shape: Shape = OutlinedTextFieldTokens.ContainerShape.toShape(),
focusedBorderThickness: Dp = FocusedBorderThickness,
unfocusedBorderThickness: Dp = UnfocusedBorderThickness
) {
val borderStroke = animateBorderStrokeAsState(
enabled,
isError,
interactionSource,
colors,
focusedBorderThickness,
unfocusedBorderThickness
)
Box(
Modifier
.border(borderStroke.value, shape)
.background(colors.containerColor().value, shape))
}
/**
* Default content padding applied to [TextField] when there is a label.
*
* Note that when the label is present, the "top" padding is a distance between the top edge of
* the [TextField] and the top of the label, not to the top of the input field. The input field
* is placed directly beneath the label.
*
* See [PaddingValues] for more details.
*/
@ExperimentalMaterial3Api
fun textFieldWithLabelPadding(
start: Dp = TextFieldPadding,
end: Dp = TextFieldPadding,
top: Dp = TextFieldWithLabelVerticalPadding,
bottom: Dp = TextFieldWithLabelVerticalPadding
): PaddingValues = PaddingValues(start, top, end, bottom)
/**
* Default content padding applied to [TextField] when the label is null.
* See [PaddingValues] for more details.
*/
@ExperimentalMaterial3Api
fun textFieldWithoutLabelPadding(
start: Dp = TextFieldPadding,
top: Dp = TextFieldPadding,
end: Dp = TextFieldPadding,
bottom: Dp = TextFieldPadding
): PaddingValues = PaddingValues(start, top, end, bottom)
/**
* Default content padding applied to [OutlinedTextField].
* See [PaddingValues] for more details.
*/
@ExperimentalMaterial3Api
fun outlinedTextFieldPadding(
start: Dp = TextFieldPadding,
top: Dp = TextFieldPadding,
end: Dp = TextFieldPadding,
bottom: Dp = TextFieldPadding
): PaddingValues = PaddingValues(start, top, end, bottom)
/**
* Default padding applied to supporting text for both [TextField] and [OutlinedTextField].
* See [PaddingValues] for more details.
*/
// TODO(246775477): consider making this public
@ExperimentalMaterial3Api
internal fun supportingTextPadding(
start: Dp = TextFieldPadding,
top: Dp = SupportingTopPadding,
end: Dp = TextFieldPadding,
bottom: Dp = 0.dp,
): PaddingValues = PaddingValues(start, top, end, bottom)
/**
* Creates a [TextFieldColors] that represents the default input text, container, and content
* (including label, placeholder, leading and trailing icons) colors used in a [TextField].
*
* @param textColor the color used for the input text of this text field
* @param disabledTextColor the color used for the input text of this text field when disabled
* @param containerColor the container color for this text field
* @param cursorColor the cursor color for this text field
* @param errorCursorColor the cursor color for this text field when in error state
* @param selectionColors the colors used when the input text of this text field is selected
* @param focusedIndicatorColor the indicator color for this text field when focused
* @param unfocusedIndicatorColor the indicator color for this text field when not focused
* @param disabledIndicatorColor the indicator color for this text field when disabled
* @param errorIndicatorColor the indicator color for this text field when in error state
* @param focusedLeadingIconColor the leading icon color for this text field when focused
* @param unfocusedLeadingIconColor the leading icon color for this text field when not focused
* @param disabledLeadingIconColor the leading icon color for this text field when disabled
* @param errorLeadingIconColor the leading icon color for this text field when in error state
* @param focusedTrailingIconColor the trailing icon color for this text field when focused
* @param unfocusedTrailingIconColor the trailing icon color for this text field when not
* focused
* @param disabledTrailingIconColor the trailing icon color for this text field when disabled
* @param errorTrailingIconColor the trailing icon color for this text field when in error state
* @param focusedLabelColor the label color for this text field when focused
* @param unfocusedLabelColor the label color for this text field when not focused
* @param disabledLabelColor the label color for this text field when disabled
* @param errorLabelColor the label color for this text field when in error state
* @param placeholderColor the placeholder color for this text field
* @param disabledPlaceholderColor the placeholder color for this text field when disabled
* @param focusedSupportingTextColor the supporting text color for this text field when focused
* @param unfocusedSupportingTextColor the supporting text color for this text field when not
* focused
* @param disabledSupportingTextColor the supporting text color for this text field when
* disabled
* @param errorSupportingTextColor the supporting text color for this text field when in error
* state
*/
@ExperimentalMaterial3Api
@Composable
fun textFieldColors(
textColor: Color = FilledTextFieldTokens.InputColor.toColor(),
disabledTextColor: Color = FilledTextFieldTokens.DisabledInputColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledInputOpacity),
containerColor: Color = FilledTextFieldTokens.ContainerColor.toColor(),
cursorColor: Color = FilledTextFieldTokens.CaretColor.toColor(),
errorCursorColor: Color = FilledTextFieldTokens.ErrorFocusCaretColor.toColor(),
selectionColors: TextSelectionColors = LocalTextSelectionColors.current,
focusedIndicatorColor: Color = FilledTextFieldTokens.FocusActiveIndicatorColor.toColor(),
unfocusedIndicatorColor: Color = FilledTextFieldTokens.ActiveIndicatorColor.toColor(),
disabledIndicatorColor: Color = FilledTextFieldTokens.DisabledActiveIndicatorColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledActiveIndicatorOpacity),
errorIndicatorColor: Color = FilledTextFieldTokens.ErrorActiveIndicatorColor.toColor(),
focusedLeadingIconColor: Color = FilledTextFieldTokens.FocusLeadingIconColor.toColor(),
unfocusedLeadingIconColor: Color = FilledTextFieldTokens.LeadingIconColor.toColor(),
disabledLeadingIconColor: Color = FilledTextFieldTokens.DisabledLeadingIconColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledLeadingIconOpacity),
errorLeadingIconColor: Color = FilledTextFieldTokens.ErrorLeadingIconColor.toColor(),
focusedTrailingIconColor: Color = FilledTextFieldTokens.FocusTrailingIconColor.toColor(),
unfocusedTrailingIconColor: Color = FilledTextFieldTokens.TrailingIconColor.toColor(),
disabledTrailingIconColor: Color = FilledTextFieldTokens.DisabledTrailingIconColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledTrailingIconOpacity),
errorTrailingIconColor: Color = FilledTextFieldTokens.ErrorTrailingIconColor.toColor(),
focusedLabelColor: Color = FilledTextFieldTokens.FocusLabelColor.toColor(),
unfocusedLabelColor: Color = FilledTextFieldTokens.LabelColor.toColor(),
disabledLabelColor: Color = FilledTextFieldTokens.DisabledLabelColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledLabelOpacity),
errorLabelColor: Color = FilledTextFieldTokens.ErrorLabelColor.toColor(),
placeholderColor: Color = FilledTextFieldTokens.InputPlaceholderColor.toColor(),
disabledPlaceholderColor: Color = FilledTextFieldTokens.DisabledInputColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledInputOpacity),
focusedSupportingTextColor: Color = FilledTextFieldTokens.FocusSupportingColor.toColor(),
unfocusedSupportingTextColor: Color = FilledTextFieldTokens.SupportingColor.toColor(),
disabledSupportingTextColor: Color = FilledTextFieldTokens.DisabledSupportingColor.toColor()
.copy(alpha = FilledTextFieldTokens.DisabledSupportingOpacity),
errorSupportingTextColor: Color = FilledTextFieldTokens.ErrorSupportingColor.toColor(),
): TextFieldColors =
TextFieldColors(
textColor = textColor,
disabledTextColor = disabledTextColor,
containerColor = containerColor,
cursorColor = cursorColor,
errorCursorColor = errorCursorColor,
textSelectionColors = selectionColors,
focusedIndicatorColor = focusedIndicatorColor,
unfocusedIndicatorColor = unfocusedIndicatorColor,
errorIndicatorColor = errorIndicatorColor,
disabledIndicatorColor = disabledIndicatorColor,
focusedLeadingIconColor = focusedLeadingIconColor,
unfocusedLeadingIconColor = unfocusedLeadingIconColor,
disabledLeadingIconColor = disabledLeadingIconColor,
errorLeadingIconColor = errorLeadingIconColor,
focusedTrailingIconColor = focusedTrailingIconColor,
unfocusedTrailingIconColor = unfocusedTrailingIconColor,
disabledTrailingIconColor = disabledTrailingIconColor,
errorTrailingIconColor = errorTrailingIconColor,
focusedLabelColor = focusedLabelColor,
unfocusedLabelColor = unfocusedLabelColor,
disabledLabelColor = disabledLabelColor,
errorLabelColor = errorLabelColor,
placeholderColor = placeholderColor,
disabledPlaceholderColor = disabledPlaceholderColor,
focusedSupportingTextColor = focusedSupportingTextColor,
unfocusedSupportingTextColor = unfocusedSupportingTextColor,
disabledSupportingTextColor = disabledSupportingTextColor,
errorSupportingTextColor = errorSupportingTextColor,
)
/**
* Creates a [TextFieldColors] that represents the default input text, container, and content
* (including label, placeholder, leading and trailing icons) colors used in an
* [OutlinedTextField].
*
* @param textColor the color used for the input text of this text field
* @param disabledTextColor the color used for the input text of this text field when disabled
* @param containerColor the container color for this text field
* @param cursorColor the cursor color for this text field
* @param errorCursorColor the cursor color for this text field when in error state
* @param selectionColors the colors used when the input text of this text field is selected
* @param focusedBorderColor the border color for this text field when focused
* @param unfocusedBorderColor the border color for this text field when not focused
* @param disabledBorderColor the border color for this text field when disabled
* @param errorBorderColor the border color for this text field when in error state
* @param focusedLeadingIconColor the leading icon color for this text field when focused
* @param unfocusedLeadingIconColor the leading icon color for this text field when not focused
* @param disabledLeadingIconColor the leading icon color for this text field when disabled
* @param errorLeadingIconColor the leading icon color for this text field when in error state
* @param focusedTrailingIconColor the trailing icon color for this text field when focused
* @param unfocusedTrailingIconColor the trailing icon color for this text field when not focused
* @param disabledTrailingIconColor the trailing icon color for this text field when disabled
* @param errorTrailingIconColor the trailing icon color for this text field when in error state
* @param focusedLabelColor the label color for this text field when focused
* @param unfocusedLabelColor the label color for this text field when not focused
* @param disabledLabelColor the label color for this text field when disabled
* @param errorLabelColor the label color for this text field when in error state
* @param placeholderColor the placeholder color for this text field
* @param disabledPlaceholderColor the placeholder color for this text field when disabled
* @param focusedSupportingTextColor the supporting text color for this text field when focused
* @param unfocusedSupportingTextColor the supporting text color for this text field when not
* focused
* @param disabledSupportingTextColor the supporting text color for this text field when
* disabled
* @param errorSupportingTextColor the supporting text color for this text field when in error
* state
*/
@ExperimentalMaterial3Api
@Composable
fun outlinedTextFieldColors(
textColor: Color = OutlinedTextFieldTokens.InputColor.toColor(),
disabledTextColor: Color = OutlinedTextFieldTokens.DisabledInputColor.toColor()
.copy(alpha = OutlinedTextFieldTokens.DisabledInputOpacity),
containerColor: Color = Color.Transparent,
cursorColor: Color = OutlinedTextFieldTokens.CaretColor.toColor(),
errorCursorColor: Color = OutlinedTextFieldTokens.ErrorFocusCaretColor.toColor(),
selectionColors: TextSelectionColors = LocalTextSelectionColors.current,
focusedBorderColor: Color = OutlinedTextFieldTokens.FocusOutlineColor.toColor(),
unfocusedBorderColor: Color = OutlinedTextFieldTokens.OutlineColor.toColor(),
disabledBorderColor: Color = OutlinedTextFieldTokens.DisabledOutlineColor.toColor()
.copy(alpha = OutlinedTextFieldTokens.DisabledOutlineOpacity),
errorBorderColor: Color = OutlinedTextFieldTokens.ErrorOutlineColor.toColor(),
focusedLeadingIconColor: Color = OutlinedTextFieldTokens.FocusLeadingIconColor.toColor(),
unfocusedLeadingIconColor: Color = OutlinedTextFieldTokens.LeadingIconColor.toColor(),
disabledLeadingIconColor: Color = OutlinedTextFieldTokens.DisabledLeadingIconColor.toColor()
.copy(alpha = OutlinedTextFieldTokens.DisabledLeadingIconOpacity),
errorLeadingIconColor: Color = OutlinedTextFieldTokens.ErrorLeadingIconColor.toColor(),
focusedTrailingIconColor: Color = OutlinedTextFieldTokens.FocusTrailingIconColor.toColor(),
unfocusedTrailingIconColor: Color = OutlinedTextFieldTokens.TrailingIconColor.toColor(),
disabledTrailingIconColor: Color = OutlinedTextFieldTokens.DisabledTrailingIconColor
.toColor().copy(alpha = OutlinedTextFieldTokens.DisabledTrailingIconOpacity),
errorTrailingIconColor: Color = OutlinedTextFieldTokens.ErrorTrailingIconColor.toColor(),
focusedLabelColor: Color = OutlinedTextFieldTokens.FocusLabelColor.toColor(),
unfocusedLabelColor: Color = OutlinedTextFieldTokens.LabelColor.toColor(),
disabledLabelColor: Color = OutlinedTextFieldTokens.DisabledLabelColor.toColor()
.copy(alpha = OutlinedTextFieldTokens.DisabledLabelOpacity),
errorLabelColor: Color = OutlinedTextFieldTokens.ErrorLabelColor.toColor(),
placeholderColor: Color = OutlinedTextFieldTokens.InputPlaceholderColor.toColor(),
disabledPlaceholderColor: Color = OutlinedTextFieldTokens.DisabledInputColor.toColor()
.copy(alpha = OutlinedTextFieldTokens.DisabledInputOpacity),
focusedSupportingTextColor: Color = OutlinedTextFieldTokens.FocusSupportingColor.toColor(),
unfocusedSupportingTextColor: Color = OutlinedTextFieldTokens.SupportingColor.toColor(),
disabledSupportingTextColor: Color = OutlinedTextFieldTokens.DisabledSupportingColor
.toColor().copy(alpha = OutlinedTextFieldTokens.DisabledSupportingOpacity),
errorSupportingTextColor: Color = OutlinedTextFieldTokens.ErrorSupportingColor.toColor(),
): TextFieldColors =
TextFieldColors(
textColor = textColor,
disabledTextColor = disabledTextColor,
cursorColor = cursorColor,
errorCursorColor = errorCursorColor,
textSelectionColors = selectionColors,
focusedIndicatorColor = focusedBorderColor,
unfocusedIndicatorColor = unfocusedBorderColor,
errorIndicatorColor = errorBorderColor,
disabledIndicatorColor = disabledBorderColor,
focusedLeadingIconColor = focusedLeadingIconColor,
unfocusedLeadingIconColor = unfocusedLeadingIconColor,
disabledLeadingIconColor = disabledLeadingIconColor,
errorLeadingIconColor = errorLeadingIconColor,
focusedTrailingIconColor = focusedTrailingIconColor,
unfocusedTrailingIconColor = unfocusedTrailingIconColor,
disabledTrailingIconColor = disabledTrailingIconColor,
errorTrailingIconColor = errorTrailingIconColor,
containerColor = containerColor,
focusedLabelColor = focusedLabelColor,
unfocusedLabelColor = unfocusedLabelColor,
disabledLabelColor = disabledLabelColor,
errorLabelColor = errorLabelColor,
placeholderColor = placeholderColor,
disabledPlaceholderColor = disabledPlaceholderColor,
focusedSupportingTextColor = focusedSupportingTextColor,
unfocusedSupportingTextColor = unfocusedSupportingTextColor,
disabledSupportingTextColor = disabledSupportingTextColor,
errorSupportingTextColor = errorSupportingTextColor,
)
/**
* A decoration box which helps creating custom text fields based on
* <a href="https://material.io/components/text-fields#filled-text-field" class="external" target="_blank">Material Design filled text field</a>.
*
* If your text field requires customising elements that aren't exposed by [TextField],
* consider using this decoration box to achieve the desired design.
*
* For example, if you need to create a dense text field, use [contentPadding] parameter to
* decrease the paddings around the input field. If you need to customise the bottom indicator,
* apply [indicatorLine] modifier to achieve that.
*
* See example of using [TextFieldDecorationBox] to build your own custom text field
* @sample androidx.compose.material3.samples.CustomTextFieldBasedOnDecorationBox
*
* @param value the input [String] shown by the text field
* @param innerTextField input text field that this decoration box wraps. You will pass here a
* framework-controlled composable parameter "innerTextField" from the decorationBox lambda of
* the [BasicTextField]
* @param enabled controls the enabled state of the text field. When `false`, this component
* will not respond to user input, and it will appear visually disabled and disabled to
* accessibility services. You must also pass the same value to the [BasicTextField] for it to
* adjust the behavior accordingly.
* @param singleLine indicates if this is a single line or multi line text field. You must pass
* the same value as to [BasicTextField].
* @param visualTransformation transforms the visual representation of the input [value]. You
* must pass the same value as to [BasicTextField].
* @param interactionSource the read-only [InteractionSource] representing the stream of
* [Interaction]s for this text field. You must first create and pass in your own `remember`ed
* [MutableInteractionSource] instance to the [BasicTextField] for it to dispatch events. And
* then pass the same instance to this decoration box to observe [Interaction]s and customize
* the appearance / behavior of this text field in different states.
* @param isError indicates if the text field's current value is in error state. If set to
* true, the label, bottom indicator and trailing icon by default will be displayed in error
* color.
* @param label the optional label to be displayed inside the text field container. The default
* text style for internal [Text] is [Typography.bodySmall] when the text field is in focus and
* [Typography.bodyLarge] when the text field is not in focus.
* @param placeholder the optional placeholder to be displayed when the text field is in focus
* and the input text is empty. The default text style for internal [Text] is
* [Typography.bodyLarge].
* @param leadingIcon the optional leading icon to be displayed at the beginning of the text
* field container
* @param trailingIcon the optional trailing icon to be displayed at the end of the text field
* container
* @param supportingText the optional supporting text to be displayed below the text field
* @param colors [TextFieldColors] that will be used to resolve the colors used for this text
* field in different states. See [TextFieldDefaults.textFieldColors].
* @param contentPadding the spacing values to apply internally between the internals of text
* field and the decoration box container. You can use it to implement dense text fields or
* simply to control horizontal padding. See [TextFieldDefaults.textFieldWithLabelPadding] and
* [TextFieldDefaults.textFieldWithoutLabelPadding].
* Note that if there's a label in the text field, the [top][PaddingValues.calculateTopPadding]
* padding represents the distance from the top edge of the container to the top of the label.
* Otherwise if label is null, it represents the distance from the top edge of the container to
* the top of the input field. All other paddings represent the distance from the corresponding
* edge of the container to the corresponding edge of the closest element.
* @param container the container to be drawn behind the text field. By default, this includes
* the bottom indicator line. Default colors for the container come from the [colors].
*/
@Composable
@ExperimentalMaterial3Api
fun TextFieldDecorationBox(
value: String,
innerTextField: @Composable () -> Unit,
enabled: Boolean,
singleLine: Boolean,
visualTransformation: VisualTransformation,
interactionSource: InteractionSource,
isError: Boolean = false,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
supportingText: @Composable (() -> Unit)? = null,
shape: Shape = filledShape,
colors: TextFieldColors = textFieldColors(),
contentPadding: PaddingValues =
if (label == null) {
textFieldWithoutLabelPadding()
} else {
textFieldWithLabelPadding()
},
container: @Composable () -> Unit = {
FilledContainerBox(enabled, isError, interactionSource, colors, shape)
}
) {
CommonDecorationBox(
type = TextFieldType.Filled,
value = value,
innerTextField = innerTextField,
visualTransformation = visualTransformation,
placeholder = placeholder,
label = label,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
supportingText = supportingText,
singleLine = singleLine,
enabled = enabled,
isError = isError,
interactionSource = interactionSource,
colors = colors,
contentPadding = contentPadding,
container = container
)
}
/**
* A decoration box which helps creating custom text fields based on
* <a href="https://material.io/components/text-fields#outlined-text-field" class="external" target="_blank">Material Design outlined text field</a>.
*
* If your text field requires customising elements that aren't exposed by [OutlinedTextField],
* consider using this decoration box to achieve the desired design.
*
* For example, if you need to create a dense outlined text field, use [contentPadding]
* parameter to decrease the paddings around the input field. If you need to change the
* thickness of the border, use [container] parameter to achieve that.
*
* Example of custom text field based on [OutlinedTextFieldDecorationBox]:
* @sample androidx.compose.material3.samples.CustomOutlinedTextFieldBasedOnDecorationBox
*
* @param value the input [String] shown by the text field
* @param innerTextField input text field that this decoration box wraps. You will pass here a
* framework-controlled composable parameter "innerTextField" from the decorationBox lambda of
* the [BasicTextField]
* @param enabled controls the enabled state of the text field. When `false`, this component
* will not respond to user input, and it will appear visually disabled and disabled to
* accessibility services. You must also pass the same value to the [BasicTextField] for it to
* adjust the behavior accordingly.
* @param singleLine indicates if this is a single line or multi line text field. You must pass
* the same value as to [BasicTextField].
* @param visualTransformation transforms the visual representation of the input [value]. You
* must pass the same value as to [BasicTextField].
* @param interactionSource the read-only [InteractionSource] representing the stream of
* [Interaction]s for this text field. You must first create and pass in your own `remember`ed
* [MutableInteractionSource] instance to the [BasicTextField] for it to dispatch events. And
* then pass the same instance to this decoration box to observe [Interaction]s and customize
* the appearance / behavior of this text field in different states.
* @param isError indicates if the text field's current value is in error state. If set to
* true, the label, bottom indicator and trailing icon by default will be displayed in error
* color.
* @param label the optional label to be displayed inside the text field container. The default
* text style for internal [Text] is [Typography.bodySmall] when the text field is in focus and
* [Typography.bodyLarge] when the text field is not in focus.
* @param placeholder the optional placeholder to be displayed when the text field is in focus
* and the input text is empty. The default text style for internal [Text] is
* [Typography.bodyLarge].
* @param leadingIcon the optional leading icon to be displayed at the beginning of the text
* field container
* @param trailingIcon the optional trailing icon to be displayed at the end of the text field
* container
* @param supportingText the optional supporting text to be displayed below the text field
* @param colors [TextFieldColors] that will be used to resolve the colors used for this text
* field in different states. See [TextFieldDefaults.outlinedTextFieldColors].
* @param contentPadding the spacing values to apply internally between the internals of text
* field and the decoration box container. You can use it to implement dense text fields or
* simply to control horizontal padding. See [TextFieldDefaults.outlinedTextFieldPadding].
* @param container the container to be drawn behind the text field. By default, this is
* transparent and only includes a border. The cutout in the border to fit the [label] will be
* automatically added by the framework. Note that by default the color of the border comes from
* the [colors].
*/
@Composable
@ExperimentalMaterial3Api
fun OutlinedTextFieldDecorationBox(
value: String,
innerTextField: @Composable () -> Unit,
enabled: Boolean,
singleLine: Boolean,
visualTransformation: VisualTransformation,
interactionSource: InteractionSource,
isError: Boolean = false,
label: @Composable (() -> Unit)? = null,
placeholder: @Composable (() -> Unit)? = null,
leadingIcon: @Composable (() -> Unit)? = null,
trailingIcon: @Composable (() -> Unit)? = null,
supportingText: @Composable (() -> Unit)? = null,
colors: TextFieldColors = outlinedTextFieldColors(),
contentPadding: PaddingValues = outlinedTextFieldPadding(),
container: @Composable () -> Unit = {
OutlinedBorderContainerBox(enabled, isError, interactionSource, colors)
}
) {
CommonDecorationBox(
type = TextFieldType.Outlined,
value = value,
visualTransformation = visualTransformation,
innerTextField = innerTextField,
placeholder = placeholder,
label = label,
leadingIcon = leadingIcon,
trailingIcon = trailingIcon,
supportingText = supportingText,
singleLine = singleLine,
enabled = enabled,
isError = isError,
interactionSource = interactionSource,
colors = colors,
contentPadding = contentPadding,
container = container
)
}
}
/**
* Represents the colors of the input text, container, and content (including label, placeholder,
* leading and trailing icons) used in a text field in different states.
*
* See [TextFieldDefaults.textFieldColors] for the default colors used in [TextField].
* See [TextFieldDefaults.outlinedTextFieldColors] for the default colors used in
* [OutlinedTextField].
*/
@OptIn(ExperimentalMaterial3Api::class)
@Immutable
class TextFieldColors internal constructor(
private val textColor: Color,
private val disabledTextColor: Color,
private val containerColor: Color,
private val cursorColor: Color,
private val errorCursorColor: Color,
private val textSelectionColors: TextSelectionColors,
private val focusedIndicatorColor: Color,
private val unfocusedIndicatorColor: Color,
private val errorIndicatorColor: Color,
private val disabledIndicatorColor: Color,
private val focusedLeadingIconColor: Color,
private val unfocusedLeadingIconColor: Color,
private val disabledLeadingIconColor: Color,
private val errorLeadingIconColor: Color,
private val focusedTrailingIconColor: Color,
private val unfocusedTrailingIconColor: Color,
private val disabledTrailingIconColor: Color,
private val errorTrailingIconColor: Color,
private val focusedLabelColor: Color,
private val unfocusedLabelColor: Color,
private val disabledLabelColor: Color,
private val errorLabelColor: Color,
private val placeholderColor: Color,
private val disabledPlaceholderColor: Color,
private val focusedSupportingTextColor: Color,
private val unfocusedSupportingTextColor: Color,
private val disabledSupportingTextColor: Color,
private val errorSupportingTextColor: Color,
) {
/**
* Represents the color used for the leading icon of this text field.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
*/
@Composable
internal fun leadingIconColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
return rememberUpdatedState(
when {
!enabled -> disabledLeadingIconColor
isError -> errorLeadingIconColor
focused -> focusedLeadingIconColor
else -> unfocusedLeadingIconColor
}
)
}
/**
* Represents the color used for the trailing icon of this text field.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
*/
@Composable
internal fun trailingIconColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
return rememberUpdatedState(
when {
!enabled -> disabledTrailingIconColor
isError -> errorTrailingIconColor
focused -> focusedTrailingIconColor
else -> unfocusedTrailingIconColor
}
)
}
/**
* Represents the color used for the border indicator of this text field.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
*/
@Composable
internal fun indicatorColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
val targetValue = when {
!enabled -> disabledIndicatorColor
isError -> errorIndicatorColor
focused -> focusedIndicatorColor
else -> unfocusedIndicatorColor
}
return if (enabled) {
animateColorAsState(targetValue, tween(durationMillis = AnimationDuration))
} else {
rememberUpdatedState(targetValue)
}
}
/**
* Represents the container color for this text field.
*/
@Composable
internal fun containerColor(): State<Color> {
return rememberUpdatedState(containerColor)
}
/**
* Represents the color used for the placeholder of this text field.
*
* @param enabled whether the text field is enabled
*/
@Composable
internal fun placeholderColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) placeholderColor else disabledPlaceholderColor)
}
/**
* Represents the color used for the label of this text field.
*
* @param enabled whether the text field is enabled
* @param isError whether the text field's current value is in error
* @param interactionSource the [InteractionSource] of this text field. Helps to determine if
* the text field is in focus or not
*/
@Composable
internal fun labelColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
val targetValue = when {
!enabled -> disabledLabelColor
isError -> errorLabelColor
focused -> focusedLabelColor
else -> unfocusedLabelColor
}
return rememberUpdatedState(targetValue)
}
@Composable
internal fun textColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) textColor else disabledTextColor)
}
@Composable
internal fun supportingTextColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
return rememberUpdatedState(
when {
!enabled -> disabledSupportingTextColor
isError -> errorSupportingTextColor
focused -> focusedSupportingTextColor
else -> unfocusedSupportingTextColor
}
)
}
/**
* Represents the color used for the cursor of this text field.
*
* @param isError whether the text field's current value is in error
*/
@Composable
internal fun cursorColor(isError: Boolean): State<Color> {
return rememberUpdatedState(if (isError) errorCursorColor else cursorColor)
}
/**
* Represents the colors used for text selection in this text field.
*/
internal val selectionColors: TextSelectionColors
@Composable get() = textSelectionColors
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is TextFieldColors) return false
if (textColor != other.textColor) return false
if (disabledTextColor != other.disabledTextColor) return false
if (cursorColor != other.cursorColor) return false
if (errorCursorColor != other.errorCursorColor) return false
if (textSelectionColors != other.textSelectionColors) return false
if (focusedIndicatorColor != other.focusedIndicatorColor) return false
if (unfocusedIndicatorColor != other.unfocusedIndicatorColor) return false
if (errorIndicatorColor != other.errorIndicatorColor) return false
if (disabledIndicatorColor != other.disabledIndicatorColor) return false
if (focusedLeadingIconColor != other.focusedLeadingIconColor) return false
if (unfocusedLeadingIconColor != other.unfocusedLeadingIconColor) return false
if (disabledLeadingIconColor != other.disabledLeadingIconColor) return false
if (errorLeadingIconColor != other.errorLeadingIconColor) return false
if (focusedTrailingIconColor != other.focusedTrailingIconColor) return false
if (unfocusedTrailingIconColor != other.unfocusedTrailingIconColor) return false
if (disabledTrailingIconColor != other.disabledTrailingIconColor) return false
if (errorTrailingIconColor != other.errorTrailingIconColor) return false
if (containerColor != other.containerColor) return false
if (focusedLabelColor != other.focusedLabelColor) return false
if (unfocusedLabelColor != other.unfocusedLabelColor) return false
if (disabledLabelColor != other.disabledLabelColor) return false
if (errorLabelColor != other.errorLabelColor) return false
if (placeholderColor != other.placeholderColor) return false
if (disabledPlaceholderColor != other.disabledPlaceholderColor) return false
if (focusedSupportingTextColor != other.focusedSupportingTextColor) return false
if (unfocusedSupportingTextColor != other.unfocusedSupportingTextColor) return false
if (disabledSupportingTextColor != other.disabledSupportingTextColor) return false
if (errorSupportingTextColor != other.errorSupportingTextColor) return false
return true
}
override fun hashCode(): Int {
var result = textColor.hashCode()
result = 31 * result + disabledTextColor.hashCode()
result = 31 * result + cursorColor.hashCode()
result = 31 * result + errorCursorColor.hashCode()
result = 31 * result + textSelectionColors.hashCode()
result = 31 * result + focusedIndicatorColor.hashCode()
result = 31 * result + unfocusedIndicatorColor.hashCode()
result = 31 * result + errorIndicatorColor.hashCode()
result = 31 * result + disabledIndicatorColor.hashCode()
result = 31 * result + focusedLeadingIconColor.hashCode()
result = 31 * result + unfocusedLeadingIconColor.hashCode()
result = 31 * result + disabledLeadingIconColor.hashCode()
result = 31 * result + errorLeadingIconColor.hashCode()
result = 31 * result + focusedTrailingIconColor.hashCode()
result = 31 * result + unfocusedTrailingIconColor.hashCode()
result = 31 * result + disabledTrailingIconColor.hashCode()
result = 31 * result + errorTrailingIconColor.hashCode()
result = 31 * result + containerColor.hashCode()
result = 31 * result + focusedLabelColor.hashCode()
result = 31 * result + unfocusedLabelColor.hashCode()
result = 31 * result + disabledLabelColor.hashCode()
result = 31 * result + errorLabelColor.hashCode()
result = 31 * result + placeholderColor.hashCode()
result = 31 * result + disabledPlaceholderColor.hashCode()
result = 31 * result + focusedSupportingTextColor.hashCode()
result = 31 * result + unfocusedSupportingTextColor.hashCode()
result = 31 * result + disabledSupportingTextColor.hashCode()
result = 31 * result + errorSupportingTextColor.hashCode()
return result
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun animateBorderStrokeAsState(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource,
colors: TextFieldColors,
focusedBorderThickness: Dp,
unfocusedBorderThickness: Dp
): State<BorderStroke> {
val focused by interactionSource.collectIsFocusedAsState()
val indicatorColor = colors.indicatorColor(enabled, isError, interactionSource)
val targetThickness = if (focused) focusedBorderThickness else unfocusedBorderThickness
val animatedThickness = if (enabled) {
animateDpAsState(targetThickness, tween(durationMillis = AnimationDuration))
} else {
rememberUpdatedState(unfocusedBorderThickness)
}
return rememberUpdatedState(
BorderStroke(animatedThickness.value, SolidColor(indicatorColor.value))
)
} | apache-2.0 | cb54d48291b61104dd7e5e47043575fc | 50.52183 | 153 | 0.716886 | 5.34372 | false | false | false | false |
androidx/androidx | compose/material/material/samples/src/main/java/androidx/compose/material/samples/BottomSheetScaffoldSamples.kt | 3 | 5163 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.samples
import androidx.annotation.Sampled
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.BottomSheetScaffold
import androidx.compose.material.Button
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.FabPosition
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.rememberBottomSheetScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
private val colors = listOf(
Color(0xFFffd7d7.toInt()),
Color(0xFFffe9d6.toInt()),
Color(0xFFfffbd0.toInt()),
Color(0xFFe3ffd9.toInt()),
Color(0xFFd0fff8.toInt())
)
@Sampled
@Composable
@OptIn(ExperimentalMaterialApi::class)
fun BottomSheetScaffoldSample() {
val scope = rememberCoroutineScope()
val scaffoldState = rememberBottomSheetScaffoldState()
BottomSheetScaffold(
sheetContent = {
Box(
Modifier.fillMaxWidth().height(128.dp),
contentAlignment = Alignment.Center
) {
Text("Swipe up to expand sheet")
}
Column(
Modifier.fillMaxWidth().padding(64.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Sheet content")
Spacer(Modifier.height(20.dp))
Button(
onClick = {
scope.launch { scaffoldState.bottomSheetState.collapse() }
}
) {
Text("Click to collapse sheet")
}
}
},
scaffoldState = scaffoldState,
topBar = {
TopAppBar(
title = { Text("Bottom sheet scaffold") },
navigationIcon = {
IconButton(onClick = { scope.launch { scaffoldState.drawerState.open() } }) {
Icon(Icons.Default.Menu, contentDescription = "Localized description")
}
}
)
},
floatingActionButton = {
var clickCount by remember { mutableStateOf(0) }
FloatingActionButton(
onClick = {
// show snackbar as a suspend function
scope.launch {
scaffoldState.snackbarHostState.showSnackbar("Snackbar #${++clickCount}")
}
}
) {
Icon(Icons.Default.Favorite, contentDescription = "Localized description")
}
},
floatingActionButtonPosition = FabPosition.End,
sheetPeekHeight = 128.dp,
drawerContent = {
Column(
Modifier.fillMaxWidth().padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text("Drawer content")
Spacer(Modifier.height(20.dp))
Button(onClick = { scope.launch { scaffoldState.drawerState.close() } }) {
Text("Click to close drawer")
}
}
}
) { innerPadding ->
LazyColumn(contentPadding = innerPadding) {
items(100) {
Box(
Modifier
.fillMaxWidth()
.height(50.dp)
.background(colors[it % colors.size])
)
}
}
}
} | apache-2.0 | 07d88f3e5db0be0666fb00deae5b18d9 | 35.885714 | 97 | 0.632965 | 5.163 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/propertyBased/KotlinIntentionPolicy.kt | 4 | 2394 | // 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.propertyBased
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.IntentionActionDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import com.intellij.testFramework.propertyBased.IntentionPolicy
import org.jetbrains.kotlin.idea.intentions.ConvertToScopeIntention
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable.CreateCallableFromUsageFixBase
import org.jetbrains.kotlin.idea.refactoring.move.changePackage.ChangePackageIntention
internal class KotlinIntentionPolicy : IntentionPolicy() {
override fun shouldSkipIntention(actionText: String): Boolean =
// These intentions don't modify code (probably should not start in write-action?)
actionText == "Enable a trailing comma by default in the formatter" ||
actionText == "Disable a trailing comma by default in the formatter" ||
// May produce error hint instead of actual action which results in RefactoringErrorHintException
// TODO: ignore only exceptional case but proceed with normal one
actionText == "Convert to enum class"
override fun mayBreakCode(action: IntentionAction, editor: Editor, file: PsiFile): Boolean = false
override fun shouldTolerateIntroducedError(info: HighlightInfo): Boolean = false
override fun shouldCheckPreview(action: IntentionAction): Boolean {
val unwrapped = IntentionActionDelegate.unwrap(action)
val skipPreview =
action.familyName == "Create from usage" || // Starts template but may also perform modifications before that; thus not so easy to support
unwrapped is ConvertToScopeIntention || // Performs reference search which must be run under progress. Probably we can generate diff excluding references?..
unwrapped is CreateCallableFromUsageFixBase<*> || // Performs too much of complex stuff. Not sure whether it should start in write action...
unwrapped is ChangePackageIntention // Just starts the template; no reasonable preview could be displayed
return !skipPreview
}
}
| apache-2.0 | 5783f22484e47d9e06381588fa4470d4 | 65.5 | 176 | 0.766917 | 5.29646 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/intentions-k1/src/org/jetbrains/kotlin/idea/intentions/InsertExplicitTypeArgumentsIntention.kt | 1 | 4255 | // 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.intentions
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeArgumentList
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.inference.CapturedType
import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.checker.NewCapturedType
import org.jetbrains.kotlin.types.error.ErrorUtils
class InsertExplicitTypeArgumentsIntention : SelfTargetingRangeIntention<KtCallExpression>(
KtCallExpression::class.java,
KotlinBundle.lazyMessage("add.explicit.type.arguments")
), LowPriorityAction {
override fun applicabilityRange(element: KtCallExpression): TextRange? =
if (isApplicableTo(element)) element.calleeExpression?.textRange else null
override fun applyTo(element: KtCallExpression, editor: Editor?) = applyTo(element)
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction = InsertExplicitTypeArgumentsIntention()
fun isApplicableTo(element: KtCallElement, bindingContext: BindingContext = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)): Boolean {
if (element.typeArguments.isNotEmpty()) return false
if (element.calleeExpression == null) return false
val resolvedCall = element.getResolvedCall(bindingContext) ?: return false
val typeArgs = resolvedCall.typeArguments
if (resolvedCall is NewResolvedCallImpl<*>) {
val valueParameterTypes = resolvedCall.resultingDescriptor.valueParameters.map { it.type }
if (valueParameterTypes.any { ErrorUtils.containsErrorType(it) }) {
return false
}
}
return typeArgs.isNotEmpty() && typeArgs.values.none { ErrorUtils.containsErrorType(it) || it is CapturedType || it is NewCapturedType }
}
fun applyTo(element: KtCallElement, argumentList: KtTypeArgumentList, shortenReferences: Boolean = true) {
val callee = element.calleeExpression ?: return
val newArgumentList = element.addAfter(argumentList, callee) as KtTypeArgumentList
if (shortenReferences) {
ShortenReferences.DEFAULT.process(newArgumentList)
}
}
fun applyTo(element: KtCallElement, shortenReferences: Boolean = true) {
val argumentList = createTypeArguments(element, element.analyze()) ?: return
applyTo(element, argumentList, shortenReferences)
}
fun createTypeArguments(element: KtCallElement, bindingContext: BindingContext): KtTypeArgumentList? {
val resolvedCall = element.getResolvedCall(bindingContext) ?: return null
val args = resolvedCall.typeArguments
val types = resolvedCall.candidateDescriptor.typeParameters
val text = types.joinToString(", ", "<", ">") {
IdeDescriptorRenderers.SOURCE_CODE.renderType(args.getValue(it))
}
return KtPsiFactory(element).createTypeArguments(text)
}
}
}
| apache-2.0 | 98aaf156e4220dbab7ecc98a3adcd76b | 50.890244 | 157 | 0.751821 | 5.413486 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/BooleanEntityImpl.kt | 2 | 5996 | // 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.storage.entities.test.api
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class BooleanEntityImpl(val dataSource: BooleanEntityData) : BooleanEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val data: Boolean get() = dataSource.data
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: BooleanEntityData?) : ModifiableWorkspaceEntityBase<BooleanEntity, BooleanEntityData>(
result), BooleanEntity.Builder {
constructor() : this(BooleanEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity BooleanEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as BooleanEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.data != dataSource.data) this.data = dataSource.data
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var data: Boolean
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData(true).data = value
changedProperty.add("data")
}
override fun getEntityClass(): Class<BooleanEntity> = BooleanEntity::class.java
}
}
class BooleanEntityData : WorkspaceEntityData<BooleanEntity>() {
var data: Boolean = false
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<BooleanEntity> {
val modifiable = BooleanEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): BooleanEntity {
return getCached(snapshot) {
val entity = BooleanEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return BooleanEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return BooleanEntity(data, entitySource) {
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as BooleanEntityData
if (this.entitySource != other.entitySource) return false
if (this.data != other.data) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as BooleanEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + data.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | 9d478fe4e1caa4ad58a2a08d6c02aee4 | 30.893617 | 120 | 0.728652 | 5.164513 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/ClassObjects.fir.kt | 10 | 726 | package Jet86
class A {
companion object {
val x = 1
}
<error descr="[MANY_COMPANION_OBJECTS] Only one companion object is allowed per class">companion</error> object Another { // error
val x = 1
}
}
class B() {
val x = 12
}
object b {
companion object {
val x = 1
}
// error
}
val a = A.x
val c = B.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: x">x</error>
val d = b.<error descr="[UNRESOLVED_REFERENCE] Unresolved reference: x">x</error>
val s = <error descr="[NO_COMPANION_OBJECT] Classifier 'java/lang/System' does not have a companion object, and thus must be initialized here">System</error> // error
fun test() {
System.out.println()
java.lang.System.out.println()
}
| apache-2.0 | c7a7ee17752b9769f4d31b8625ccb708 | 22.419355 | 167 | 0.670799 | 3.408451 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/KotlinObsoleteCodeStyle.kt | 1 | 2925 | // 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.formatter
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
class KotlinObsoleteCodeStyle : KotlinPredefinedCodeStyle(CODE_STYLE_TITLE, KotlinLanguage.INSTANCE) {
override val codeStyleId: String = CODE_STYLE_ID
override fun apply(settings: CodeStyleSettings) {
Companion.apply(settings)
}
companion object {
val INSTANCE = KotlinObsoleteCodeStyle()
const val CODE_STYLE_ID = "KOTLIN_OLD_DEFAULTS"
const val CODE_STYLE_SETTING = "obsolete"
const val CODE_STYLE_TITLE = "Kotlin obsolete IntelliJ IDEA codestyle"
fun apply(settings: CodeStyleSettings) {
applyToKotlinCustomSettings(settings.kotlinCustomSettings)
applyToCommonSettings(settings.kotlinCommonSettings)
}
fun applyToKotlinCustomSettings(kotlinCustomSettings: KotlinCodeStyleSettings, modifyCodeStyle: Boolean = true) {
kotlinCustomSettings.apply {
if (modifyCodeStyle) {
CODE_STYLE_DEFAULTS = CODE_STYLE_ID
}
CONTINUATION_INDENT_IN_PARAMETER_LISTS = true
CONTINUATION_INDENT_IN_ARGUMENT_LISTS = true
CONTINUATION_INDENT_FOR_EXPRESSION_BODIES = true
CONTINUATION_INDENT_FOR_CHAINED_CALLS = true
CONTINUATION_INDENT_IN_SUPERTYPE_LISTS = true
CONTINUATION_INDENT_IN_IF_CONDITIONS = true
CONTINUATION_INDENT_IN_ELVIS = true
WRAP_EXPRESSION_BODY_FUNCTIONS = CodeStyleSettings.DO_NOT_WRAP
IF_RPAREN_ON_NEW_LINE = false
}
}
fun applyToCommonSettings(commonSettings: CommonCodeStyleSettings, modifyCodeStyle: Boolean = true) {
commonSettings.apply {
CALL_PARAMETERS_WRAP = CodeStyleSettings.DO_NOT_WRAP
CALL_PARAMETERS_LPAREN_ON_NEXT_LINE = false
CALL_PARAMETERS_RPAREN_ON_NEXT_LINE = false
METHOD_PARAMETERS_WRAP = CodeStyleSettings.DO_NOT_WRAP
METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE = false
METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE = false
EXTENDS_LIST_WRAP = CodeStyleSettings.DO_NOT_WRAP
METHOD_CALL_CHAIN_WRAP = CodeStyleSettings.DO_NOT_WRAP
ASSIGNMENT_WRAP = CodeStyleSettings.DO_NOT_WRAP
}
if (modifyCodeStyle && commonSettings is KotlinCommonCodeStyleSettings) {
commonSettings.CODE_STYLE_DEFAULTS = CODE_STYLE_ID
}
}
}
}
| apache-2.0 | 02acfaf8c9bc6704edaed11281c21a80 | 42.656716 | 158 | 0.662222 | 4.949239 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/settings/MarkdownSettingsConfigurable.kt | 1 | 11539 | // 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.intellij.plugins.markdown.settings
import com.intellij.ide.highlighter.HighlighterFactory
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorSettings
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.TextEditorWithPreview
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.fileTypes.UnknownFileType
import com.intellij.openapi.options.BoundSearchableConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.EnumComboBoxModel
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.dsl.builder.*
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.Row
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.ui.layout.*
import com.intellij.util.application
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownConfigurableExtension
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithDownloadableFiles
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithExternalFiles
import org.intellij.plugins.markdown.extensions.MarkdownExtensionsUtil
import org.intellij.plugins.markdown.settings.pandoc.PandocSettingsPanel
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider
import org.jetbrains.annotations.Nls
import javax.swing.DefaultComboBoxModel
class MarkdownSettingsConfigurable(private val project: Project): BoundSearchableConfigurable(
MarkdownBundle.message("markdown.settings.name"),
MarkdownBundle.message("markdown.settings.name"),
_id = ID
) {
private val settings
get() = MarkdownSettings.getInstance(project)
private var customStylesheetEditor: Editor? = null
override fun createPanel(): DialogPanel {
if (!MarkdownHtmlPanelProvider.hasAvailableProviders()) {
return panel {
row {
label(MarkdownBundle.message("markdown.settings.no.providers"))
}
}
}
return panel {
if (MarkdownHtmlPanelProvider.getAvailableProviders().size > 1) {
htmlPanelProvidersRow()
}
row(MarkdownBundle.message("markdown.settings.default.layout")) {
comboBox(
model = EnumComboBoxModel(TextEditorWithPreview.Layout::class.java),
renderer = SimpleListCellRenderer.create("") { it?.getName() ?: "" }
).bindItem(settings::splitLayout)
}
row(MarkdownBundle.message("markdown.settings.preview.layout.label")) {
comboBox(
model = DefaultComboBoxModel(arrayOf(false, true)),
renderer = SimpleListCellRenderer.create("", ::presentSplitLayout)
).bindItem(settings::isVerticalSplit)
}.bottomGap(BottomGap.SMALL)
row {
checkBox(MarkdownBundle.message("markdown.settings.preview.auto.scroll.checkbox"))
.bindSelected(settings::isAutoScrollEnabled)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.enable.injections"))
.bindSelected(settings::areInjectionsEnabled)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.enable.enhance.editing.experience"))
.bindSelected(settings::isEnhancedEditingEnabled)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.hide.errors"))
.bindSelected(settings::hideErrorsInCodeBlocks)
}
row {
checkBox(MarkdownBundle.message("markdown.settings.commandrunner.text"))
.bindSelected(settings::isRunnerEnabled)
}.bottomGap(BottomGap.SMALL)
extensionsListRow().apply {
onApply {
val publisher = application.messageBus.syncPublisher(MarkdownExtensionsSettings.ChangeListener.TOPIC)
publisher.extensionsSettingsChanged(fromSettingsDialog = true)
}
}
customCssRow()
pandocSettingsRow()
}
}
private fun Panel.htmlPanelProvidersRow(): Row {
return row(MarkdownBundle.message("markdown.settings.preview.providers.label")) {
val providers = MarkdownHtmlPanelProvider.getProviders().map { it.providerInfo }
comboBox(model = DefaultComboBoxModel(providers.toTypedArray()))
.bindItem(settings::previewPanelProviderInfo)
}
}
private fun validateCustomStylesheetPath(builder: ValidationInfoBuilder, textField: TextFieldWithBrowseButton): ValidationInfo? {
return builder.run {
val fieldText = textField.text
when {
!FileUtil.exists(fieldText) -> error(MarkdownBundle.message("dialog.message.path.error", fieldText))
else -> null
}
}
}
private fun Panel.customCssRow() {
collapsibleGroup(MarkdownBundle.message("markdown.settings.css.title.name")) {
row {
val externalCssCheckBox = checkBox(MarkdownBundle.message("markdown.settings.external.css.path.label"))
.bindSelected(settings::useCustomStylesheetPath)
.gap(RightGap.SMALL)
textFieldWithBrowseButton()
.applyToComponent {
text = settings.customStylesheetPath ?: ""
}
.horizontalAlign(HorizontalAlign.FILL)
.enabledIf(externalCssCheckBox.selected)
.applyIfEnabled()
.validationOnInput(::validateCustomStylesheetPath)
.validationOnApply(::validateCustomStylesheetPath)
.apply {
onApply { settings.customStylesheetPath = component.text.takeIf { externalCssCheckBox.component.isSelected } }
onIsModified { externalCssCheckBox.component.isSelected && settings.customStylesheetPath != component.text }
}
}
lateinit var editorCheckbox: Cell<JBCheckBox>
row {
editorCheckbox = checkBox(MarkdownBundle.message("markdown.settings.custom.css.text.label"))
.bindSelected(settings::useCustomStylesheetText)
.applyToComponent {
addActionListener { setEditorReadonlyState(isReadonly = !isSelected) }
}
}
row {
val editor = createCustomStylesheetEditor()
cell(editor.component)
.horizontalAlign(HorizontalAlign.FILL)
.onApply { settings.customStylesheetText = runReadAction { editor.document.text } }
.onIsModified { settings.customStylesheetText != runReadAction { editor.document.text.takeIf { it.isNotEmpty() } } }
.onReset { resetEditorText(settings.customStylesheetText ?: "") }
customStylesheetEditor = editor
setEditorReadonlyState(isReadonly = !editorCheckbox.component.isSelected)
}
}
}
private fun setEditorReadonlyState(isReadonly: Boolean) {
customStylesheetEditor?.let {
it.document.setReadOnly(isReadonly)
it.contentComponent.isEnabled = !isReadonly
}
}
private fun Panel.pandocSettingsRow() {
collapsibleGroup(MarkdownBundle.message("markdown.settings.pandoc.name")) {
row {
cell(PandocSettingsPanel(project))
.horizontalAlign(HorizontalAlign.FILL)
.apply {
onApply { component.apply() }
onIsModified { component.isModified() }
onReset { component.reset() }
}
}
}
}
override fun apply() {
settings.update {
super.apply()
}
}
override fun disposeUIResources() {
customStylesheetEditor?.let(EditorFactory.getInstance()::releaseEditor)
customStylesheetEditor = null
super.disposeUIResources()
}
private fun Panel.extensionsListRow(): ButtonsGroup {
return buttonsGroup(MarkdownBundle.message("markdown.settings.preview.extensions.name")) {
val extensions = MarkdownExtensionsUtil.collectConfigurableExtensions()
for (extension in extensions) {
createExtensionEntry(extension)
}
}
}
private fun Panel.createExtensionEntry(extension: MarkdownConfigurableExtension) {
row {
val extensionsSettings = MarkdownExtensionsSettings.getInstance()
val extensionCheckBox = checkBox(text = extension.displayName).bindSelected(
{ extensionsSettings.extensionsEnabledState[extension.id] ?: false },
{ extensionsSettings.extensionsEnabledState[extension.id] = it}
).gap(RightGap.SMALL)
extensionCheckBox.enabled((extension as? MarkdownExtensionWithExternalFiles)?.isAvailable ?: true)
contextHelp(extension.description).gap(RightGap.SMALL)
if ((extension as? MarkdownExtensionWithDownloadableFiles)?.isAvailable == false) {
lateinit var installLink: Cell<ActionLink>
installLink = link(MarkdownBundle.message("markdown.settings.extension.install.label")) {
MarkdownSettingsUtil.downloadExtension(
extension,
enableAfterDownload = false
)
extensionCheckBox.enabled(extension.isAvailable)
installLink.component.isVisible = !extension.isAvailable
installLink.component.isEnabled = !extension.isAvailable
}
}
}
}
private fun createCustomStylesheetEditor(): EditorEx {
val editorFactory = EditorFactory.getInstance()
val editorDocument = editorFactory.createDocument(settings.customStylesheetText ?: "")
val editor = editorFactory.createEditor(editorDocument) as EditorEx
fillEditorSettings(editor.settings)
setEditorHighlighting(editor)
return editor
}
private fun setEditorHighlighting(editor: EditorEx) {
val cssFileType = FileTypeManager.getInstance().getFileTypeByExtension("css")
if (cssFileType === UnknownFileType.INSTANCE) {
return
}
val editorHighlighter = HighlighterFactory.createHighlighter(
cssFileType,
EditorColorsManager.getInstance().globalScheme,
null
)
editor.highlighter = editorHighlighter
}
private fun resetEditorText(cssText: String) {
customStylesheetEditor?.let { editor ->
if (!editor.isDisposed) {
runWriteAction {
val writable = editor.document.isWritable
editor.document.setReadOnly(false)
editor.document.setText(cssText)
editor.document.setReadOnly(!writable)
}
}
}
}
private fun fillEditorSettings(editorSettings: EditorSettings) {
with(editorSettings) {
isWhitespacesShown = false
isLineMarkerAreaShown = false
isIndentGuidesShown = false
isLineNumbersShown = true
isFoldingOutlineShown = false
additionalColumnsCount = 1
additionalLinesCount = 3
isUseSoftWraps = false
}
}
companion object {
const val ID = "Settings.Markdown"
private fun presentSplitLayout(splitLayout: Boolean?): @Nls String {
return when (splitLayout) {
false -> MarkdownBundle.message("markdown.settings.preview.layout.horizontal")
true -> MarkdownBundle.message("markdown.settings.preview.layout.vertical")
else -> ""
}
}
}
}
| apache-2.0 | a8ebf39d5204aab3d391619ef15fc8b5 | 38.652921 | 158 | 0.72034 | 4.956615 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/RuntimeChooserJre.kt | 2 | 7882 | // 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.openapi.projectRoots.impl.jdkDownloader
import com.intellij.ReviseWhenPortedToJDK
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.wsl.WslDistributionManager
import com.intellij.lang.LangBundle
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ui.configuration.SdkPopupBuilder
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.io.isDirectory
import com.intellij.util.io.isFile
import com.intellij.util.lang.JavaVersion
import org.jetbrains.jps.model.java.JdkVersionDetector
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import kotlin.io.path.div
import kotlin.io.path.isExecutable
private val LOG = logger<RuntimeChooserJreValidator>()
interface RuntimeChooserJreValidatorCallback<R> {
fun onSdkResolved(displayName: String?, versionString: String, sdkHome: Path): R
fun onError(@NlsContexts.DialogMessage message: String): R
}
object RuntimeChooserJreValidator {
@ReviseWhenPortedToJDK("12")
private val minJdkFeatureVersion
get() = 11
fun isSupportedSdkItem(item: JdkItem): Boolean {
//we do only support mac bundle layout
if (SystemInfo.isMac && !item.packageToBinJavaPrefix.endsWith("Contents/Home")) {
return false
}
return item.jdkMajorVersion >= minJdkFeatureVersion && item.os == JdkPredicate.currentOS && item.arch == JdkPredicate.currentArch
}
fun isSupportedSdkItem(sdk: Sdk) = isSupportedSdkItem({ sdk.versionString }, { sdk.homePath })
fun isSupportedSdkItem(sdk: SdkPopupBuilder.SuggestedSdk) = isSupportedSdkItem({ sdk.versionString }, { sdk.homePath })
private inline fun isSupportedSdkItem(versionString: () -> String?, homePath: () -> String?): Boolean = runCatching {
val version = versionString() ?: return false
val home = homePath() ?: return false
//we do only support mac bundle layout
if (SystemInfo.isMac && !home.endsWith("/Contents/Home")) {
return false
}
val javaVersion = JavaVersion.tryParse(version) ?: return false
javaVersion.feature >= minJdkFeatureVersion && !WslDistributionManager.isWslPath(home)
}.getOrDefault(false)
fun <R> testNewJdkUnderProgress(
allowRunProcesses: Boolean,
computeHomePath: () -> String?,
callback: RuntimeChooserJreValidatorCallback<R>,
): R {
val homeDir = runCatching { Path.of(computeHomePath()).toAbsolutePath() }.getOrNull()
?: return callback.onError(
LangBundle.message("dialog.message.choose.ide.runtime.set.unknown.error", LangBundle.message("dialog.message.choose.ide.runtime.no.file.part")))
if (SystemInfo.isMac && homeDir.toString().endsWith("/Contents/Home")) {
return testNewJdkUnderProgress(allowRunProcesses, { homeDir.parent?.parent?.toString() }, callback)
}
if (SystemInfo.isMac && homeDir.fileName.toString() == "Contents" && (homeDir / "Home").isDirectory()) {
return testNewJdkUnderProgress(allowRunProcesses, { homeDir.parent?.toString() }, callback)
}
if (SystemInfo.isMac && !(homeDir / "Contents" / "Home").isDirectory()) {
LOG.warn("Failed to scan JDK for boot runtime: ${homeDir}. macOS Bundle layout is expected")
return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.error.mac.bundle", homeDir))
}
if (SystemInfo.isWindows && WslDistributionManager.isWslPath(homeDir.toString())) {
LOG.warn("Failed to scan JDK for boot runtime: ${homeDir}. macOS Bundle layout is expected")
callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.version.error.wsl", homeDir))
}
val binJava = when {
SystemInfo.isWindows -> homeDir / "bin" / "java.exe"
SystemInfo.isMac -> homeDir / "Contents" / "Home" / "bin" / "java"
else -> homeDir / "bin" / "java"
}
if (!binJava.isFile() || (SystemInfo.isUnix && !binJava.isExecutable())) {
LOG.warn("Failed to scan JDK for boot runtime: ${homeDir}. Failed to find bin/java executable at $binJava")
return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.cannot.start.error", homeDir))
}
val info = runCatching {
//we compute the path to handle macOS bundle layout once again here
val inferredHome = binJava.parent?.parent?.toString() ?: return@runCatching null
JdkVersionDetector.getInstance().detectJdkVersionInfo(inferredHome)
}.getOrNull() ?: return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.unknown.error", homeDir))
if (info.version == null || info.version.feature < minJdkFeatureVersion) {
LOG.warn("Failed to scan JDK for boot runtime: ${homeDir}. The version $info is less than $minJdkFeatureVersion")
return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.version.error", homeDir, "11",
info.version.toString()))
}
val jdkVersion = tryComputeAdvancedFullVersion(binJava)
?: info.version?.toString()
?: return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.unknown.error", homeDir))
if (allowRunProcesses) {
try {
val cmd = GeneralCommandLine(binJava.toString(), "-version")
val exitCode = CapturingProcessHandler(cmd).runProcess(30_000).exitCode
if (exitCode != 0) {
LOG.warn("Failed to run JDK for boot runtime: ${homeDir}. Exit code is ${exitCode} for $binJava.")
return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.cannot.start.error", homeDir))
}
}
catch (t: Throwable) {
if (t is ControlFlowException) throw t
LOG.warn("Failed to run JDK for boot runtime: $homeDir. ${t.message}", t)
return callback.onError(LangBundle.message("dialog.message.choose.ide.runtime.set.cannot.start.error", homeDir))
}
}
return callback.onSdkResolved(info.variant.displayName, jdkVersion, homeDir)
}
}
private class ReleaseProperties(releaseFile: Path) {
private val p = Properties()
init {
runCatching {
if (Files.isRegularFile(releaseFile)) {
Files.newInputStream(releaseFile).use { p.load(it) }
}
}
}
fun getJdkProperty(name: String) = p
.getProperty(name)
?.trim()
?.removeSurrounding("\"")
?.trim()
}
private fun tryComputeAdvancedFullVersion(binJava: Path): String? = runCatching {
//we compute the path to handle macOS bundle layout once again here
val theReleaseFile = binJava.parent?.parent?.resolve("release") ?: return@runCatching null
val p = ReleaseProperties(theReleaseFile)
val implementor = p.getJdkProperty("IMPLEMENTOR")
when {
implementor.isNullOrBlank() -> null
implementor.startsWith("JetBrains") -> {
p.getJdkProperty("IMPLEMENTOR_VERSION")
?.removePrefix("JBR-")
?.replace("JBRSDK-", "JBRSDK ")
?.trim()
}
implementor.startsWith("Azul") -> {
listOfNotNull(
p.getJdkProperty("JAVA_VERSION"),
p.getJdkProperty("IMPLEMENTOR_VERSION")
).joinToString(" ").takeIf { it.isNotBlank() }
}
implementor.startsWith("Amazon.com") -> {
val implVersion = p.getJdkProperty("IMPLEMENTOR_VERSION")
if (implVersion != null && implVersion.startsWith("Corretto-")) {
implVersion.removePrefix("Corretto-")
} else null
}
else -> null
}
}.getOrNull()
| apache-2.0 | 9c93db739d608467b212604c09db2b3a | 41.605405 | 164 | 0.70477 | 4.226273 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/checker/infos/PropertiesWithBackingFields.kt | 3 | 1913 | <info>abstract</info> class Test() {
<info>abstract</info> val x : Int
<info>abstract</info> val x1 : Int <info>get</info>
<info>abstract</info> val x2 : Int <error><info>get</info>() = 1</error>
<error>val a : Int</error>
<error>val b : Int</error> <info>get</info>
val c = 1
val c1 = 1
<info>get</info>
val c2 : Int
<info>get</info>() = 1
val c3 : Int
<info>get</info>() { return 1 }
val c4 : Int
<info>get</info>() = 1
<error>val c5 : Int</error>
<info>get</info>() = field + 1
<info>abstract</info> var y : Int
<info>abstract</info> var y1 : Int <info>get</info>
<info>abstract</info> var y2 : Int <info>set</info>
<info>abstract</info> var y3 : Int <info>set</info> <info>get</info>
<info>abstract</info> var y4 : Int <info>set</info> <error><info>get</info>() = 1</error>
<info>abstract</info> var y5 : Int <error><info>set</info>(x) {}</error> <error><info>get</info>() = 1</error>
<info>abstract</info> var y6 : Int <error><info>set</info>(x) {}</error>
<error>var v : Int</error>
<error>var v1 : Int</error> <info>get</info>
<error>var v2 : Int</error> <info>get</info> <info>set</info>
<error>var v3 : Int</error> <info>get</info>() = 1; <info>set</info>
var v4 : Int <info>get</info>() = 1; <info>set</info>(<warning>x</warning>){}
<error>var v5 : Int</error> <info>get</info>() = 1; <info>set</info>(x){field = x}
<error>var v6 : Int</error> <info>get</info>() = field + 1; <info>set</info>(<warning>x</warning>){}
<error>var v9 : Int</error> <info>set</info>
<error>var v10 : Int</error> <info>get</info>
}
<info>open</info> class Super(<warning>i</warning> : Int)
class TestPCParameters(w : Int, <warning>x</warning> : Int, val y : Int, var z : Int) : Super(w) {
val xx = w
<info>init</info> {
w + 1
}
fun foo() = <error>x</error>
} | apache-2.0 | 331061789e8cbdaa91a96d8603f9bd50 | 33.8 | 114 | 0.56874 | 2.752518 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/provider/local/LocalFile.kt | 1 | 1179 | package com.timepath.vfs.provider.local
import com.timepath.vfs.provider.ExtendedVFile
import java.io.BufferedInputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.util.logging.Level
import java.util.logging.Logger
/**
* @author TimePath
*/
open class LocalFile(protected val file: File) : ExtendedVFile() {
override val attributes: Any?
get() = null
override val root: ExtendedVFile
get() = this
override val isComplete: Boolean
get() = true
override val name: String
get() = file.name
override fun openStream() = try {
BufferedInputStream(FileInputStream(file))
} catch (ex: FileNotFoundException) {
LOG.log(Level.SEVERE, null, ex)
null
}
override val isDirectory: Boolean
get() = file.isDirectory()
override var lastModified: Long
get() = file.lastModified()
set(time) {
file.setLastModified(time)
}
override val length: Long
get() = file.length()
companion object {
private val LOG = Logger.getLogger(javaClass<LocalFile>().getName())
}
}
| artistic-2.0 | df0409142abdd569eef9ef993b857f5b | 22.117647 | 76 | 0.657337 | 4.3829 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/daemon/IgnoredEditingNotificationProvider.kt | 1 | 2514 | // 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 mobi.hsz.idea.gitignore.daemon
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.IgnoreManager
import mobi.hsz.idea.gitignore.settings.IgnoreSettings
import mobi.hsz.idea.gitignore.util.Icons
import mobi.hsz.idea.gitignore.util.Properties
/**
* Editor notification provider that informs about the attempt of the ignored file modification.
*/
class IgnoredEditingNotificationProvider(project: Project) : EditorNotifications.Provider<EditorNotificationPanel?>() {
private val notifications = EditorNotifications.getInstance(project)
private val settings = service<IgnoreSettings>()
private val manager = project.service<IgnoreManager>()
private val changeListManager = ChangeListManager.getInstance(project)
companion object {
private val KEY = Key.create<EditorNotificationPanel?>("IgnoredEditingNotificationProvider")
}
override fun getKey() = KEY
/**
* Creates notification panel for given file and checks if is allowed to show the notification.
*
* @param file current file
* @param fileEditor current file editor
* @return created notification panel
*/
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project) = when {
!settings.notifyIgnoredEditing || Properties.isDismissedIgnoredEditingNotification(project, file)
|| !changeListManager.isIgnoredFile(file) && !manager.isFileIgnored(file) -> null
else -> EditorNotificationPanel().apply {
text = IgnoreBundle.message("daemon.ignoredEditing")
createActionLabel(IgnoreBundle.message("daemon.ok")) {
Properties.setDismissedIgnoredEditingNotification(project, file)
notifications.updateAllNotifications()
}
try { // ignore if older SDK does not support panel icon
icon(Icons.IGNORE)
} catch (ignored: NoSuchMethodError) {
}
}
}
}
| mit | f40c431e92ea2878869fd2b08a906527 | 43.892857 | 140 | 0.739459 | 5.007968 | false | false | false | false |
mcilloni/kt-uplink | src/main/kotlin/Uplink.kt | 1 | 7527 | /*
* uplink, a simple daemon to implement a simple chat protocol
* Copyright (C) Marco Cilloni <[email protected]> 2016
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
* Exhibit B is not attached; this software is compatible with the
* licenses expressed under Section 1.12 of the MPL v2.
*
*/
@file:JvmName("Uplink")
@file:JvmMultifileClass
package com.github.mcilloni.uplink
import com.github.mcilloni.uplink.nano.UplinkGrpc
import com.github.mcilloni.uplink.nano.UplinkProto
import com.github.mcilloni.uplink.nano.UplinkProto.Notification
import io.grpc.ManagedChannelBuilder
import io.grpc.Metadata
import io.grpc.stub.MetadataUtils
import io.grpc.stub.StreamObserver
import java.util.concurrent.ExecutionException
internal class Stubs(astub: UplinkGrpc.UplinkStub, bstub: UplinkGrpc.UplinkBlockingStub) {
var asyncStub = astub
private set
var blockingStub = bstub
private set
fun setSessionInfo(uid: Long, sessid: String) {
val metadata = Metadata()
metadata.put(Metadata.Key.of("uid", Metadata.ASCII_STRING_MARSHALLER), uid.toString())
metadata.put(Metadata.Key.of("sessid", Metadata.ASCII_STRING_MARSHALLER), sessid)
this.asyncStub = MetadataUtils.attachHeaders(this.asyncStub, metadata)
this.blockingStub = MetadataUtils.attachHeaders(this.blockingStub, metadata)
}
}
private fun connect(url: String, port: Int) : Stubs {
val chan = ManagedChannelBuilder.forAddress(url, port).usePlaintext(true).build()
val blocking = UplinkGrpc.newBlockingStub(chan)
val async = UplinkGrpc.newStub(chan)
return Stubs(async, blocking)
}
data class Session(val uid: Long, val sessid: String)
fun login(url: String, port: Int, userName: String, authPass: String) = rpc {
val stubs = connect(url, port)
val info = stubs.blockingStub.login(with(UplinkProto.AuthInfo()) {
name = userName
pass = authPass
this
})
val session = Session(info.uid, info.sessionId)
UplinkConnection(stubs, session, userName)
}
fun newUser(url: String, port: Int, userName: String, authPass: String) = rpc {
val stubs = connect(url, port)
val existsResp = stubs.blockingStub.exists(with(UplinkProto.Name()) {
name = userName
this
})
if (existsResp.success) {
throw NameAlreadyTakenException()
}
val resp = stubs.blockingStub.newUser(with(UplinkProto.AuthInfo()) {
name = userName
pass = authPass
this
})
UplinkConnection(stubs, Session(resp.uid, resp.sessionId), userName)
}
fun resumeSession(url: String, port: Int, name: String, sessInfo: Session) = try {
val stubs = connect(url, port)
UplinkConnection(stubs, sessInfo, name)
} catch (e: ExecutionException) {
throw normExc(e.cause ?: throw e)
}
interface NotificationHandler {
fun onNewMessage(message: Message)
fun onFriendRequest(userName: String)
fun onNewFriendship(userName: String)
fun onConversationInvite(conversationInvite: ConversationInvite)
fun onNewUserInConversation(userName: String, conv: Conversation)
fun onServerReady()
fun onError(t: Throwable)
}
class UplinkConnection internal constructor(internal val stubs: Stubs, val sessInfo: Session, val username: String) {
init {
stubs.setSessionInfo(sessInfo.uid, sessInfo.sessid)
}
fun acceptFriendshipWith(name: String) = rpc {
stubs.blockingStub.acceptFriendship(with(UplinkProto.Name()) {
this.name = name
this
}).success
}
fun acceptInvite(convID: Long) = rpc {
stubs.blockingStub.acceptInvite(with(UplinkProto.ID()) {
this.id = convID
this
}).success
}
fun beginConversation(name: String) = rpc {
Conversation(name, stubs.blockingStub.newConversation(with(UplinkProto.Name()) {
this.name = name
this
}).id, this)
}
fun getConversations() = rpc {
stubs.blockingStub.conversations(UplinkProto.Empty()).convs.map {
Conversation(it, this)
}
}
fun getFriends() : Array<String> = rpc {
stubs.blockingStub.friends(UplinkProto.Empty()).friends
}
fun getFriendshipRequests() : Array<String> = rpc {
stubs.blockingStub.receivedRequests(UplinkProto.Empty()).friends
}
fun getInvites() = rpc {
stubs.blockingStub.invites(UplinkProto.Empty()).invites.map {
Invite(fromUser = it.who, toConv = it.convName, convID = it.convId)
}
}
fun getConversationFor(convID: Long) = rpc {
stubs.blockingStub.conversationInfo(with(UplinkProto.ID()){
id = convID
this
}).let {
Conversation(it, this)
}
}
fun ping() = rpc {
stubs.blockingStub.ping(UplinkProto.Empty()).success
}
// Not verified - may explode horribly
fun recreateConversation(name: String, id: Long) = Conversation(name, id, this)
fun sendFriendshipRequest(user: String) = rpc {
stubs.blockingStub.requestFriendship(with(UplinkProto.Name()){
name = user
this
}).success
}
fun sendInvite(user: String, convID: Long) = rpc {
stubs.blockingStub.sendInvite(with(UplinkProto.Invite()){
who = user
convId = convID
this
}).success
}
infix fun subscribe (handler: NotificationHandler) : UplinkConnection {
stubs.asyncStub.notifications(UplinkProto.Empty(), object : StreamObserver<UplinkProto.Notification> {
override fun onError(t: Throwable?) {
handler.onError(t ?: NullPointerException())
}
override fun onCompleted() {}
override fun onNext(value: UplinkProto.Notification?) {
if (value != null) {
with (value) {
when (type) {
Notification.HANDLER_READY -> {
handler.onServerReady()
}
Notification.MESSAGE -> {
handler.onNewMessage(Message(msgTag, userName, convId, body))
}
Notification.JOIN_REQ -> {
handler.onConversationInvite(ConversationInvite(userName, Conversation(convName, convId, this@UplinkConnection)))
}
Notification.JOIN_ACC -> {
handler.onNewUserInConversation(userName, Conversation(convName, convId, this@UplinkConnection))
}
Notification.FRIENDSHIP_REQ -> {
handler.onFriendRequest(userName)
}
Notification.FRIENDSHIP_ACC -> {
handler.onNewFriendship(userName)
}
}
}
}
}
})
return this
}
fun submitPushRegistrationId(regID: String) = rpc {
stubs.blockingStub.submitRegID(with(UplinkProto.RegID()) {
this.regId = regID
this
}).success
}
} | mpl-2.0 | 11897a46ea0cb1d16aef1ac4482a7d78 | 29.601626 | 145 | 0.609938 | 4.279136 | false | false | false | false |
datawire/discovery | discovery-server/src/main/kotlin/io/datawire/discovery/registry/DiscoveryVerticle.kt | 1 | 2763 | package io.datawire.discovery.registry
import com.fasterxml.jackson.databind.InjectableValues
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.datawire.discovery.auth.DiscoveryAuthHandler
import io.datawire.discovery.registry.model.BaseMessage
import io.datawire.discovery.registry.model.MessageContext
import io.datawire.discovery.registry.model.RoutesResponse
import io.vertx.core.AbstractVerticle
import io.vertx.core.buffer.Buffer
import io.vertx.core.http.ServerWebSocket
import io.vertx.ext.auth.jwt.JWTAuth
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.CorsHandler
import io.vertx.ext.web.handler.JWTAuthHandler
import java.nio.charset.Charset
abstract class DiscoveryVerticle(
protected val registry: RoutingTable
): AbstractVerticle() {
protected lateinit var jwt: JWTAuthHandler
protected val objectMapper: ObjectMapper = ObjectMapper().registerKotlinModule()
protected val router: Router = Router.router(vertx)
override fun start() {
setup()
start(deploymentID())
}
fun setup() {
val jwtAuth = JWTAuth.create(vertx, config().getJsonObject("jsonWebToken"))
jwt = DiscoveryAuthHandler(jwtAuth, "/health")
router.route("/*").handler(CorsHandler.create("*"))
router.get("/health").handler { rc -> rc.response().setStatusCode(200).end() }
router.route("/v1/messages/*").handler(jwt)
}
abstract fun start(verticleId: String)
fun publishRoutingTable(tenant: String) {
val routingTable = registry.mapNamesToEndpoints(tenant)
vertx.eventBus().publish(
"routing-table:$tenant:notifications", serializeMessage(RoutesResponse("${deploymentID()}", routingTable)))
}
fun sendRoutingTable(tenant: String, socket: ServerWebSocket) {
val routingTable = registry.mapNamesToEndpoints(tenant)
socket.writeFinalTextFrame(serializeMessage(RoutesResponse(deploymentID(), routingTable)))
}
protected fun processMessage(tenant: String, client: String, buffer: Buffer): Pair<MessageContext, BaseMessage> {
val message = deserializeMessage(client, buffer)
return Pair(MessageContext(tenant, client), message)
}
protected fun deserializeMessage(client: String, buffer: Buffer): BaseMessage {
val injections = InjectableValues.Std().addValue("origin", client)
val reader = objectMapper.readerFor(BaseMessage::class.java).with(injections)
return reader.readValue<BaseMessage>(buffer.toString(Charsets.UTF_8.name()))
}
protected fun serializeMessage(message: BaseMessage, charset: Charset = Charsets.UTF_8): String {
val writer = objectMapper.writer()
val json = writer.writeValueAsString(message)
return Buffer.buffer(json).toString(charset.name())
}
} | apache-2.0 | 10ad3c99df98048bddf7b6f896f4e7f1 | 37.929577 | 115 | 0.769815 | 4.24424 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/presentation/group_editor/GroupEditorViewModel.kt | 1 | 4842 | package com.ivanovsky.passnotes.presentation.group_editor
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.terrakok.cicerone.Router
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.entity.Group
import com.ivanovsky.passnotes.domain.ResourceProvider
import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor
import com.ivanovsky.passnotes.domain.interactor.group_editor.GroupEditorInteractor
import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler
import com.ivanovsky.passnotes.presentation.core.ScreenState
import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
import kotlinx.coroutines.launch
import java.util.UUID
class GroupEditorViewModel(
private val interactor: GroupEditorInteractor,
private val errorInteractor: ErrorInteractor,
private val resourceProvider: ResourceProvider,
private val router: Router
) : ViewModel() {
val screenStateHandler = DefaultScreenStateHandler()
val screenState = MutableLiveData(ScreenState.notInitialized())
val groupTitle = MutableLiveData(EMPTY)
val errorText = MutableLiveData<String?>()
val doneButtonVisibility = MutableLiveData(true)
val hideKeyboardEvent = SingleLiveEvent<Unit>()
private lateinit var mode: Mode
private var groupUid: UUID? = null
private var parentGroupUid: UUID? = null
private var group: Group? = null
fun start(args: GroupEditorArgs) {
when (args) {
is GroupEditorArgs.NewGroup -> {
parentGroupUid = args.parentGroupUid
mode = Mode.NEW
}
is GroupEditorArgs.EditGroup ->{
groupUid = args.groupUid
mode = Mode.EDIT
}
}
if (mode == Mode.EDIT) {
loadData()
} else {
screenState.value = ScreenState.data()
}
}
fun loadData() {
val groupUid = groupUid ?: return
screenState.value = ScreenState.loading()
viewModelScope.launch {
val getGroupResult = interactor.getGroup(groupUid)
if (getGroupResult.isSucceededOrDeferred) {
group = getGroupResult.obj
groupTitle.value = getGroupResult.obj.title
screenState.value = ScreenState.data()
} else {
val message = errorInteractor.processAndGetMessage(getGroupResult.error)
screenState.value = ScreenState.error(message)
}
}
}
fun onDoneButtonClicked() {
when (mode) {
Mode.NEW -> createNewGroup()
Mode.EDIT -> updateGroup()
}
}
fun navigateBack() = router.exit()
private fun createNewGroup() {
val parentGroupUid = parentGroupUid ?: return
val title = groupTitle.value?.trim() ?: return
if (title.isEmpty()) {
errorText.value = resourceProvider.getString(R.string.empty_field)
return
}
hideKeyboardEvent.call()
doneButtonVisibility.value = false
errorText.value = null
screenState.value = ScreenState.loading()
viewModelScope.launch {
val createResult = interactor.createNewGroup(title, parentGroupUid)
if (createResult.isSucceededOrDeferred) {
router.exit()
} else {
doneButtonVisibility.value = true
val message = errorInteractor.processAndGetMessage(createResult.error)
screenState.value = ScreenState.dataWithError(message)
}
}
}
private fun updateGroup() {
val group = group ?: return
val newTitle = groupTitle.value?.trim() ?: return
if (newTitle.isEmpty()) {
errorText.value = resourceProvider.getString(R.string.empty_field)
return
}
if (newTitle == group.title) {
router.exit()
return
}
hideKeyboardEvent.call()
doneButtonVisibility.value = false
screenState.value = ScreenState.loading()
val newGroup = Group().apply {
title = newTitle
uid = group.uid
}
viewModelScope.launch {
val updateResult = interactor.updateGroup(newGroup)
if (updateResult.isSucceededOrDeferred) {
router.exit()
} else {
doneButtonVisibility.value = true
val message = errorInteractor.processAndGetMessage(updateResult.error)
screenState.value = ScreenState.dataWithError(message)
}
}
}
enum class Mode {
NEW,
EDIT
}
} | gpl-2.0 | cf714192d0e07f453595fe1184b9c077 | 30.448052 | 88 | 0.634036 | 5.086134 | false | false | false | false |
aosp-mirror/platform_frameworks_support | buildSrc/src/main/kotlin/androidx/build/SourceJarTaskHelper.kt | 1 | 2062 | /*
* Copyright 2017 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.build
import com.android.build.gradle.LibraryExtension
import com.android.builder.core.BuilderConstants
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.bundling.Jar
/**
* Sets up a source jar task for an Android library project.
*/
fun setUpSoureJarTaskForAndroidProject(project: Project, extension: LibraryExtension) {
// Create sources jar for release builds
extension.libraryVariants.all { libraryVariant ->
if (libraryVariant.buildType.name != BuilderConstants.RELEASE) {
return@all // Skip non-release builds.
}
val sourceJar = project.tasks.create("sourceJarRelease", Jar::class.java)
sourceJar.isPreserveFileTimestamps = false
sourceJar.classifier = "sources"
sourceJar.from(extension.sourceSets.findByName("main")!!.java.srcDirs)
project.artifacts.add("archives", sourceJar)
}
}
/**
* Sets up a source jar task for a Java library project.
*/
fun setUpSourceJarTaskForJavaProject(project: Project) {
val sourceJar = project.tasks.create("sourceJar", Jar::class.java)
sourceJar.isPreserveFileTimestamps = false
sourceJar.classifier = "sources"
val convention = project.convention.getPlugin(JavaPluginConvention::class.java)
sourceJar.from(convention.sourceSets.findByName("main")!!.allSource.srcDirs)
project.artifacts.add("archives", sourceJar)
}
| apache-2.0 | 4370da09145e6bb351756acb1d114978 | 37.185185 | 87 | 0.741998 | 4.22541 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/notes/book/BookAdapter.kt | 1 | 5578 | package com.orgzly.android.ui.notes.book
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.orgzly.R
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.Note
import com.orgzly.android.db.entity.NoteView
import com.orgzly.android.prefs.AppPreferences
import com.orgzly.android.ui.SelectableItemAdapter
import com.orgzly.android.ui.Selection
import com.orgzly.android.ui.notes.NoteItemViewBinder
import com.orgzly.android.ui.notes.NoteItemViewHolder
import com.orgzly.databinding.ItemHeadBinding
import com.orgzly.databinding.ItemPrefaceBinding
class BookAdapter(
private val bookId: Long,
private val context: Context,
private val clickListener: OnClickListener,
private val inBook: Boolean
) :
ListAdapterWithHeaders<NoteView, RecyclerView.ViewHolder>(DIFF_CALLBACK, 1),
SelectableItemAdapter {
private var currentPreface: String? = null
private val adapterSelection = Selection()
private val noteItemViewBinder = NoteItemViewBinder(context, inBook)
private val prefaceItemViewBinder = PrefaceItemViewBinder(context)
private val noteViewHolderListener = object: NoteItemViewHolder.ClickListener {
override fun onClick(view: View, position: Int) {
clickListener.onNoteClick(view, position, getItem(position))
}
override fun onLongClick(view: View, position: Int) {
clickListener.onNoteLongClick(view, position, getItem(position))
}
}
inner class FoldedViewHolder(view: View) : RecyclerView.ViewHolder(view)
inner class PrefaceViewHolder(val binding: ItemPrefaceBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.root.setOnClickListener {
clickListener.onPrefaceClick()
}
}
}
override fun getItemViewType(position: Int): Int {
return when {
position == 0 -> R.layout.item_preface
isVisible(getItem(position).note) -> VISIBLE_ITEM_TYPE
else -> HIDDEN_ITEM_TYPE
}
}
private fun isVisible(note: Note): Boolean {
return !inBook || note.position.foldedUnderId == 0L
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
R.layout.item_preface -> {
val binding = ItemPrefaceBinding.inflate(
LayoutInflater.from(context), parent, false)
PrefaceViewHolder(binding)
}
HIDDEN_ITEM_TYPE -> {
FoldedViewHolder(View(context))
}
else -> {
val binding = ItemHeadBinding.inflate(
LayoutInflater.from(context), parent, false)
NoteItemViewBinder.setupSpacingForDensitySetting(context, binding)
NoteItemViewHolder(binding, noteViewHolderListener)
}
}
}
override fun onBindViewHolder(h: RecyclerView.ViewHolder, position: Int) {
when {
position == 0 -> {
val holder = h as PrefaceViewHolder
prefaceItemViewBinder.bind(holder, bookId, currentPreface, isPrefaceDisplayed())
}
h.itemViewType == HIDDEN_ITEM_TYPE -> {
h.itemView.visibility = View.GONE
return
}
else -> {
val holder = h as NoteItemViewHolder
val noteView = getItem(position)
val note = noteView.note
noteItemViewBinder.bind(holder, noteView)
getSelection().setBackgroundIfSelected(holder.itemView, note.id)
}
}
}
override fun getItemId(position: Int): Long {
return if (position > 0) {
getItem(position).note.id
} else {
-1
}
}
override fun getSelection(): Selection {
return adapterSelection
}
fun clearSelection() {
if (getSelection().count > 0) {
getSelection().clear()
notifyDataSetChanged() // FIXME
}
}
fun setPreface(book: Book?) {
currentPreface = book?.preface
notifyItemChanged(0)
}
fun isPrefaceDisplayed(): Boolean {
val hidden =
context.getString(R.string.pref_value_preface_in_book_hide) ==
AppPreferences.prefaceDisplay(context)
return !TextUtils.isEmpty(currentPreface) && !hidden
}
interface OnClickListener {
fun onPrefaceClick()
fun onNoteClick(view: View, position: Int, noteView: NoteView)
fun onNoteLongClick(view: View, position: Int, noteView: NoteView)
}
companion object {
private val TAG = BookAdapter::class.java.name
const val HIDDEN_ITEM_TYPE = 0 // Not used
const val VISIBLE_ITEM_TYPE = 1
private val DIFF_CALLBACK: DiffUtil.ItemCallback<NoteView> =
object : DiffUtil.ItemCallback<NoteView>() {
override fun areItemsTheSame(oldItem: NoteView, newItem: NoteView): Boolean {
return oldItem.note.id == newItem.note.id
}
override fun areContentsTheSame(oldItem: NoteView, newItem: NoteView): Boolean {
return oldItem == newItem
}
}
}
}
| gpl-3.0 | 769ad3ed151e424506467ef5944a295a | 30.514124 | 96 | 0.630692 | 4.854656 | false | false | false | false |
markusfisch/BinaryEye | app/src/main/kotlin/de/markusfisch/android/binaryeye/actions/vtype/VType.kt | 1 | 1265 | package de.markusfisch.android.binaryeye.actions.vtype
import java.util.*
object VTypeParser {
private const val BACKSLASH_R_LEGACY =
"(?:\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029])"
private val vTypeRegex =
"""^BEGIN:(V.+)(?:$BACKSLASH_R_LEGACY.+?:[\s\S]+?)+?${BACKSLASH_R_LEGACY}END:\1$BACKSLASH_R_LEGACY?$""".toRegex(
RegexOption.IGNORE_CASE
)
private val propertyRegex = """^(.+?):([\s\S]*?)$""".toRegex(
RegexOption.MULTILINE
)
fun parseVType(data: String): String? = vTypeRegex.matchEntire(
data
)?.groupValues?.get(1)?.uppercase(Locale.US)
fun parseMap(
data: String
): Map<String, List<VTypeProperty>> = propertyRegex.findAll(data).map {
it.groupValues[1].split(';').let { typeAndInfo ->
typeAndInfo[0] to VTypeProperty(
typeAndInfo.drop(1),
it.groupValues[2]
)
}
}.groupBy({ it.first.uppercase(Locale.US) }) { it.second }
}
data class VTypeProperty(
val info: List<String>,
val value: String
) {
val firstTypeOrFirstInfo: String?
get() = this.info.find { it.startsWith("TYPE=", true) }?.let {
typeRegex.matchEntire(it)?.groupValues?.get(1)
} ?: this.info.firstOrNull()
companion object {
private val typeRegex = """^(?:TYPE=)(.+?)[:;]?.*$""".toRegex(RegexOption.IGNORE_CASE)
}
}
| mit | 557782b456386a7fb9dbc058344babb5 | 27.75 | 114 | 0.668775 | 2.894737 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/sym/SymmetricCryptoHandler.kt | 1 | 2985 | package io.oversec.one.crypto.sym
import android.content.Context
import android.content.Intent
import io.oversec.one.crypto.AbstractEncryptionParams
import io.oversec.one.crypto.BaseDecryptResult
import io.oversec.one.crypto.EncryptionMethod
import io.oversec.one.crypto.UserInteractionRequiredException
import io.oversec.one.crypto.encoding.Base64XCoder
import io.oversec.one.crypto.proto.Outer
import io.oversec.one.crypto.sym.ui.SymmetricBinaryEncryptionInfoFragment
import io.oversec.one.crypto.sym.ui.SymmetricTextEncryptionInfoFragment
import io.oversec.one.crypto.symbase.BaseSymmetricCryptoHandler
import io.oversec.one.crypto.symbase.SymmetricDecryptResult
import io.oversec.one.crypto.ui.AbstractBinaryEncryptionInfoFragment
import io.oversec.one.crypto.ui.AbstractTextEncryptionInfoFragment
class SymmetricCryptoHandler(ctx: Context) : BaseSymmetricCryptoHandler(ctx) {
private val mKeyStore: OversecKeystore2
override val method: EncryptionMethod
get() = EncryptionMethod.SYM
init {
mKeyStore = OversecKeystore2.getInstance(ctx)
}
override fun buildDefaultEncryptionParams(tdr: BaseDecryptResult): AbstractEncryptionParams {
val r = tdr as SymmetricDecryptResult
return SymmetricEncryptionParams(r.symmetricKeyId, Base64XCoder.ID, null)
}
@Throws(UserInteractionRequiredException::class)
override fun decrypt(
msg: Outer.Msg,
actionIntent: Intent?,
encryptedText: String?
): BaseDecryptResult {
return tryDecrypt(msg.msgTextSymV0, encryptedText)
}
override fun getTextEncryptionInfoFragment(packagename: String?): AbstractTextEncryptionInfoFragment {
return SymmetricTextEncryptionInfoFragment.newInstance(packagename)
}
override fun getBinaryEncryptionInfoFragment(packagename: String?): AbstractBinaryEncryptionInfoFragment {
return SymmetricBinaryEncryptionInfoFragment.newInstance(packagename)
}
@Throws(KeyNotCachedException::class)
override fun getKeyByHashedKeyId(
keyhash: Long,
salt: ByteArray,
cost: Int,
encryptedText: String?
): SymmetricKeyPlain? {
val keyId = mKeyStore.getKeyIdByHashedKeyId(keyhash, salt, cost)
return if (keyId == null) null else mKeyCache.get(keyId)
}
@Throws(UserInteractionRequiredException::class)
override fun handleNoKeyFoundForDecryption(
keyHashes: LongArray,
salts: Array<ByteArray>,
costKeyhash: Int,
encryptedText: String?
) {
//noop
}
override fun setMessage(
builderMsg: Outer.Msg.Builder,
symMsgBuilder: Outer.MsgTextSymV0.Builder
) {
builderMsg.setMsgTextSymV0(symMsgBuilder)
}
fun hasAnyKey(): Boolean {
return !mKeyStore.isEmpty
}
companion object {
const val BCRYPT_FINGERPRINT_COST = 10
init {
OversecKeystore2.noop()//init security provider
}
}
}
| gpl-3.0 | 2c38d5a51d8ae9366016da8fda5b56d3 | 30.09375 | 110 | 0.737018 | 4.522727 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/account/JamiAccountUsernameFragment.kt | 1 | 7898 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Authors: AmirHossein Naghshzan <[email protected]>
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.account
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView.OnEditorActionListener
import com.google.android.material.textfield.TextInputLayout
import cx.ring.R
import cx.ring.databinding.FragAccJamiUsernameBinding
import cx.ring.mvp.BaseSupportFragment
import cx.ring.utils.RegisteredNameFilter
import dagger.hilt.android.AndroidEntryPoint
import net.jami.account.JamiAccountCreationPresenter
import net.jami.account.JamiAccountCreationView
import net.jami.account.JamiAccountCreationView.UsernameAvailabilityStatus
import net.jami.model.AccountCreationModel
@AndroidEntryPoint
class JamiAccountUsernameFragment : BaseSupportFragment<JamiAccountCreationPresenter, JamiAccountCreationView>(),
JamiAccountCreationView {
private var model: AccountCreationModel? = null
private var binding: FragAccJamiUsernameBinding? = null
override fun onSaveInstanceState(outState: Bundle) {
if (model != null) outState.putSerializable(KEY_MODEL, model)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
retainInstance = true
if (savedInstanceState != null && model == null) {
model = savedInstanceState.getSerializable(KEY_MODEL) as AccountCreationModelImpl?
}
return FragAccJamiUsernameBinding.inflate(inflater, container, false).apply {
ringUsername.filters = arrayOf<InputFilter>(RegisteredNameFilter())
createAccount.setOnClickListener { presenter.createAccount() }
skip.setOnClickListener {
presenter.registerUsernameChanged(false)
presenter.createAccount()
}
ringUsername.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
presenter.userNameChanged(s.toString())
}
})
ringUsername.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE && binding!!.createAccount.isEnabled) {
val inputMethodManager =
requireContext().getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(requireActivity().currentFocus!!.windowToken, 0)
presenter.createAccount()
return@OnEditorActionListener true
}
false
})
binding = this
}.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding!!.ringUsername.requestFocus()
val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(binding!!.ringUsername, InputMethodManager.SHOW_IMPLICIT)
presenter.init(model)
presenter.setPush(true)
}
override fun updateUsernameAvailability(status: UsernameAvailabilityStatus) {
val binding = binding ?: return
binding.ringUsernameAvailabilitySpinner.visibility = View.GONE
when (status) {
UsernameAvailabilityStatus.ERROR -> {
binding.ringUsernameTxtBox.isErrorEnabled = true
binding.ringUsernameTxtBox.error = getString(R.string.unknown_error)
binding.ringUsernameTxtBox.endIconMode = TextInputLayout.END_ICON_NONE
enableNextButton(false)
}
UsernameAvailabilityStatus.ERROR_USERNAME_INVALID -> {
binding.ringUsernameTxtBox.isErrorEnabled = true
binding.ringUsernameTxtBox.error = getString(R.string.invalid_username)
binding.ringUsernameTxtBox.endIconMode = TextInputLayout.END_ICON_NONE
enableNextButton(false)
}
UsernameAvailabilityStatus.ERROR_USERNAME_TAKEN -> {
binding.ringUsernameTxtBox.isErrorEnabled = true
binding.ringUsernameTxtBox.error = getString(R.string.username_already_taken)
binding.ringUsernameTxtBox.endIconMode = TextInputLayout.END_ICON_NONE
enableNextButton(false)
}
UsernameAvailabilityStatus.LOADING -> {
binding.ringUsernameTxtBox.isErrorEnabled = false
binding.ringUsernameTxtBox.endIconMode = TextInputLayout.END_ICON_NONE
binding.ringUsernameAvailabilitySpinner.visibility = View.VISIBLE
enableNextButton(false)
}
UsernameAvailabilityStatus.AVAILABLE -> {
binding.ringUsernameTxtBox.isErrorEnabled = false
binding.ringUsernameTxtBox.endIconMode = TextInputLayout.END_ICON_CUSTOM
binding.ringUsernameTxtBox.setEndIconDrawable(R.drawable.ic_good_green)
enableNextButton(true)
}
UsernameAvailabilityStatus.RESET -> {
binding.ringUsernameTxtBox.isErrorEnabled = false
binding.ringUsername.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
enableNextButton(false)
}
}
}
override fun showInvalidPasswordError(display: Boolean) {}
override fun showNonMatchingPasswordError(display: Boolean) {}
override fun enableNextButton(enabled: Boolean) {
binding!!.createAccount.isEnabled = enabled
}
override fun goToAccountCreation(accountCreationModel: AccountCreationModel) {
val parent = parentFragment as JamiAccountCreationFragment?
if (parent != null) {
parent.scrollPagerFragment(accountCreationModel)
val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(binding!!.ringUsername.windowToken, 0)
}
}
override fun cancel() {
val wizardActivity: Activity? = activity
wizardActivity?.onBackPressed()
}
companion object {
private const val KEY_MODEL = "model"
fun newInstance(ringAccountViewModel: AccountCreationModelImpl): JamiAccountUsernameFragment {
val fragment = JamiAccountUsernameFragment()
fragment.model = ringAccountViewModel
return fragment
}
}
} | gpl-3.0 | 2c9e34f5b225ec53fe9f6273c22ee07d | 45.192982 | 115 | 0.69258 | 5.322102 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/arcgis-vector-tiled-layer-custom-style/src/main/java/com/esri/arcgisruntime/sample/arcgisvectortiledlayercustomstyle/MainActivity.kt | 1 | 12786 | /*
* Copyright 2021 Esri
*
* 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.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.concurrent.Job
import com.esri.arcgisruntime.data.VectorTileCache
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.ItemResourceCache
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.portal.Portal
import com.esri.arcgisruntime.portal.PortalItem
import com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle.databinding.ActivityMainBinding
import com.esri.arcgisruntime.sample.arcgisvectortiledlayercustomstyle.databinding.SpinnerItemBinding
import com.esri.arcgisruntime.tasks.vectortilecache.ExportVectorTilesTask
class MainActivity : AppCompatActivity() {
// A list of portal item IDs for the online layers.
private var onlineItemIds: Array<String> = arrayOf(
"1349bfa0ed08485d8a92c442a3850b06",
"bd8ac41667014d98b933e97713ba8377",
"02f85ec376084c508b9c8e5a311724fa",
"1bf0cc4a4380468fbbff107e100f65a5"
)
// A list of portal item IDs for the layers which custom style is applied from local resources.
private var offlineItemIds: Array<String> = arrayOf(
// A vector tiled layer created by the local VTPK and light custom style.
"e01262ef2a4f4d91897d9bbd3a9b1075",
// A vector tiled layer created by the local VTPK and dark custom style.
"ce8a34e5d4ca4fa193a097511daa8855"
)
// The item ID of the currently showing layer.
private var currentItemID: String = onlineItemIds[0]
// A dictionary to cache loaded vector tiled layers.
private var vectorTiledLayersMap: MutableMap<String, ArcGISVectorTiledLayer> = mutableMapOf()
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val spinner: Spinner by lazy {
activityMainBinding.spinner
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// Set the map to be displayed in the layout's MapView
mapView.map = ArcGISMap()
// Authentication with an API key or named user is required to access basemaps and other location services.
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
// Set the currentItemID to default layer.
currentItemID = onlineItemIds[0]
// Sets up the spinner to change the selected Vector Styled Layer.
setUpSpinner()
}
/**
* Displays the layer of the given [itemID].
*/
private fun showSelectedItem(itemID: String) {
currentItemID = itemID
val vectorTiledLayer: ArcGISVectorTiledLayer
// Checks if the layer has been cached.
when {
vectorTiledLayersMap.contains(itemID) -> {
vectorTiledLayer = vectorTiledLayersMap.getValue(itemID)
}
onlineItemIds.contains(itemID) -> {
// Retrieve the layer from online.
val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
vectorTiledLayer = ArcGISVectorTiledLayer(portalItem)
// Adds the retrieved layer to the mutable map for cache.
vectorTiledLayersMap[itemID] = vectorTiledLayer
}
else -> {
// Load the layer using offline Vector Tiles.
checkOfflineItemCache(itemID)
return
}
}
// OnlineItemIDs uses WebMercator as a spatial ref.
val viewpoint = Viewpoint(
Point(1990591.559979, 794036.007991, SpatialReferences.getWebMercator()),
100000000.0
)
setMap(vectorTiledLayer, viewpoint)
}
/**
* Checks local cache for local cache files using the [itemID].
* If not, it calls loadLayerWithOfflineCustomStyle([itemID]) to retrieve the cache files.
*/
private fun checkOfflineItemCache(itemID: String) {
val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
val itemResourceCache =
ItemResourceCache(getExternalFilesDir(null)?.path + "/" + portalItem.itemId)
itemResourceCache.addDoneLoadingListener {
if (itemResourceCache.loadStatus == LoadStatus.LOADED) {
setResourceAndVectorTileCache(itemResourceCache)
} else {
loadLayerWithOfflineCustomStyle(itemID)
}
}
itemResourceCache.loadAsync()
}
/**
* Retrieves the style resource files using [itemID] and caches it to the local device.
*/
private fun loadLayerWithOfflineCustomStyle(itemID: String) {
// Retrieve the layer from online.
val portalItem = PortalItem(Portal("https://www.arcgis.com"), itemID)
val task = ExportVectorTilesTask(portalItem)
// Create job using portalItem ID and .vtpk path to retrieve the itemResourceCache
val exportVectorTilesJob =
task.exportStyleResourceCache(getExternalFilesDir(null)?.path + "/" + portalItem.itemId)
exportVectorTilesJob.addJobDoneListener {
if (exportVectorTilesJob.status == Job.Status.SUCCEEDED) {
setResourceAndVectorTileCache(exportVectorTilesJob.result.itemResourceCache)
} else {
Toast.makeText(
this,
"Error reading cache: " + exportVectorTilesJob.error.message,
Toast.LENGTH_LONG
).show()
}
}
exportVectorTilesJob.start()
}
/**
* Sets up an ArcGISVectorTiledLayer using the [itemResourceCache]
* for the setMap() function.
*/
private fun setResourceAndVectorTileCache(itemResourceCache: ItemResourceCache) {
//Loads the vector tile layer cache.
val vectorTileCache = VectorTileCache(getExternalFilesDir(null)?.path + "/dodge_city.vtpk")
vectorTileCache.loadAsync()
vectorTileCache.addDoneLoadingListener {
if (vectorTileCache.loadStatus == LoadStatus.LOADED) {
// Loads the layer based on the vector tile cache and the style resource.
val layer = ArcGISVectorTiledLayer(vectorTileCache, itemResourceCache)
layer.addDoneLoadingListener {
if (layer.loadStatus != LoadStatus.LOADED) {
Toast.makeText(
applicationContext,
layer.loadError.message + ": " + layer.loadError.additionalMessage,
Toast.LENGTH_SHORT
).show()
}
}
// OfflineItemIDs uses WGS-84 as a spatial ref.
val viewpoint =
Viewpoint(Point(-100.01766, 37.76528, SpatialReferences.getWgs84()), 100000.0)
setMap(layer, viewpoint)
} else
Toast.makeText(
applicationContext,
vectorTileCache.loadError.message + ": " + vectorTileCache.loadError.additionalMessage,
Toast.LENGTH_SHORT
).show()
}
}
/**
* Set the map using the [layer] and the [viewpoint].
*/
private fun setMap(layer: ArcGISVectorTiledLayer, viewpoint: Viewpoint) {
// Clears the existing basemap layer
mapView.map.basemap.baseLayers.clear()
// Adds the new vector tiled layer to the basemap.
mapView.map.basemap.baseLayers.add(layer)
//Set viewpoint without animation.
mapView.setViewpoint(viewpoint)
}
/**
* Sets the adapter and listens for a item selection to update the
* MapView with the selected layer.
*/
private fun setUpSpinner() {
val customDropDownAdapter = CustomSpinnerAdapter(this)
spinner.adapter = customDropDownAdapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// Sets the selected itemID to either the Online/Custom ID.
// Position 4 or 5 in the spinner are the custom (offline) style layers.
currentItemID = when (position) {
4 -> {
// Custom style 1 - Dodge City OSM - Light
offlineItemIds[0]
}
5 -> {
// Custom style 2 - Dodge City OSM - Dark
offlineItemIds[1]
}
else -> {
// Else use the online vector styles
onlineItemIds[position]
}
}
showSelectedItem(currentItemID)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
//Keeps the current selected vector style.
}
}
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
/**
* Custom adapter to set and control the spinner.
* [context] is used to help render the view
*/
class CustomSpinnerAdapter(private val context: Context) : BaseAdapter() {
// Inflates each row of the adapter.
private val inflater: LayoutInflater =
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val spinnerItemBinding = SpinnerItemBinding.inflate(inflater)
val view: View
val itemHolder: ItemHolder
if (convertView == null) {
view = spinnerItemBinding.root
itemHolder = ItemHolder(view)
view.tag = itemHolder
} else {
view = convertView
itemHolder = view.tag as ItemHolder
}
// Sets the TextView to the style name.
itemHolder.layerText.text =
context.resources.getStringArray(R.array.style_names)[position]
// Gets the drawable style associated with the position.
val id = context.resources.getIdentifier(
context.resources.getStringArray(R.array.style_drawable_names)[position],
"drawable",
context.packageName
)
// Sets the retrieved drawable as the background of the colorView.
itemHolder.colorView.setBackgroundResource(id)
return view
}
override fun getItem(position: Int): Any {
return context.resources.getStringArray(R.array.style_names)[position]
}
override fun getCount(): Int {
return context.resources.getStringArray(R.array.style_names).size
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
private class ItemHolder(row: View?) {
val layerText: TextView = row?.findViewById(R.id.text) as TextView
val colorView: View = row?.findViewById(R.id.colorView) as View
}
}
}
| apache-2.0 | cee8bad75b2481bf1570024ddd183490 | 36.940653 | 115 | 0.628656 | 4.78518 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/TraktRatingsFetcher.kt | 1 | 2985 | package com.battlelancer.seriesguide.traktapi
import android.content.Context
import android.text.format.DateUtils
import androidx.collection.LruCache
import com.battlelancer.seriesguide.SgApp
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.uwetrottmann.androidutils.AndroidUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
/**
* Downloads Trakt ratings for an episode, stores them in the database.
* The recent 50 downloads are cached for at most a day.
*/
object TraktRatingsFetcher {
private const val HARD_CACHE_CAPACITY = 50
private const val MAXIMUM_AGE = DateUtils.DAY_IN_MILLIS
// Hard cache, with a fixed maximum capacity
private val lruCache = LruCache<Long, Long>(HARD_CACHE_CAPACITY)
@JvmStatic
fun fetchEpisodeRatingsAsync(
context: Context,
episodeId: Long
): Job {
return SgApp.coroutineScope.launch {
fetchRating(context.applicationContext, episodeId)
}
}
private suspend fun fetchRating(
context: Context,
episodeId: Long,
) = withContext(Dispatchers.IO) {
val helper = SgRoomDatabase.getInstance(context).sgEpisode2Helper()
val episode = helper.getEpisodeNumbers(episodeId)
?: return@withContext
// avoid saving ratings too frequently
// (network requests are cached, but also avoiding database writes)
val currentTimeMillis = System.currentTimeMillis()
synchronized(lruCache) {
val lastUpdateMillis = lruCache[episodeId]
// if the ratings were just updated, do nothing
if (lastUpdateMillis != null && lastUpdateMillis > currentTimeMillis - MAXIMUM_AGE) {
Timber.d("Just loaded rating for %s, skip.", episodeId)
return@withContext
}
}
if (!isActive || !AndroidUtils.isNetworkConnected(context)) {
return@withContext
}
// look up show trakt id
val showTraktId = SgApp.getServicesComponent(context)
.showTools().getShowTraktId(episode.showId)
if (showTraktId == null) {
Timber.d("Show %s has no trakt id, skip.", episode.showId)
return@withContext
}
val showTraktIdString = showTraktId.toString()
Timber.d("Updating rating for episode $episodeId")
val ratings = TraktTools2.getEpisodeRatings(
context,
showTraktIdString,
episode.season,
episode.episodenumber
)
if (ratings != null) {
helper.updateRating(episodeId, ratings.first, ratings.second)
}
// cache download time to avoid saving ratings too frequently
synchronized(lruCache) {
lruCache.put(episodeId, currentTimeMillis)
}
}
} | apache-2.0 | 51fb83742ca85d8e4688d43b42fda3a4 | 32.177778 | 97 | 0.667337 | 5.093857 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/series/HighSeriesOf8Statistic.kt | 1 | 951 | package ca.josephroque.bowlingcompanion.statistics.impl.series
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Highest series of 8 games.
*/
class HighSeriesOf8Statistic(value: Int = 0) : HighSeriesStatistic(value) {
// MARK: Overrides
override val seriesSize = 8
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::HighSeriesOf8Statistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_high_series_of_8
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(value = p.readInt())
}
| mit | c01b350dcf3bb0f9162eb5595d7255cf | 25.416667 | 75 | 0.685594 | 4.245536 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-banks-bukkit/src/main/kotlin/com/rpkit/banks/bukkit/database/table/RPKBankTable.kt | 1 | 8708 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.banks.bukkit.database.table
import com.rpkit.banks.bukkit.RPKBanksBukkit
import com.rpkit.banks.bukkit.bank.RPKBank
import com.rpkit.banks.bukkit.database.create
import com.rpkit.banks.bukkit.database.jooq.Tables.RPKIT_BANK
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.characters.bukkit.character.RPKCharacterId
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.core.service.Services
import com.rpkit.economy.bukkit.currency.RPKCurrency
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.runAsync
import java.util.logging.Level.SEVERE
/**
* Represents the bank table.
*/
class RPKBankTable(private val database: Database, private val plugin: RPKBanksBukkit) : Table {
private data class CharacterCurrencyCacheKey(
val characterId: Int,
val currencyName: String
)
private val cache = if (plugin.config.getBoolean("caching.rpkit_bank.character_id.enabled")) {
database.cacheManager.createCache(
"rpk-banks-bukkit.rpkit_bank.character_id",
CharacterCurrencyCacheKey::class.java,
RPKBank::class.java,
plugin.config.getLong("caching.rpkit_bank.character_id.size")
)
} else {
null
}
fun insert(entity: RPKBank): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.insertInto(
RPKIT_BANK,
RPKIT_BANK.CHARACTER_ID,
RPKIT_BANK.CURRENCY_NAME,
RPKIT_BANK.BALANCE
)
.values(
characterId.value,
currencyName.value,
entity.balance
)
.execute()
cache?.set(CharacterCurrencyCacheKey(characterId.value, currencyName.value), entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to insert bank", exception)
throw exception
}
}
fun update(entity: RPKBank): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.update(RPKIT_BANK)
.set(RPKIT_BANK.CURRENCY_NAME, currencyName.value)
.set(RPKIT_BANK.BALANCE, entity.balance)
.where(RPKIT_BANK.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_BANK.CURRENCY_NAME.eq(currencyName.value))
.execute()
cache?.set(CharacterCurrencyCacheKey(characterId.value, currencyName.value), entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to update bank", exception)
throw exception
}
}
/**
* Gets the bank account for the given character in the given currency.
* If no account exists, one will be created.
*
* @param character The character to get the account for
* @param currency The currency which the account should be in
* @return The account of the character in the currency
*/
operator fun get(character: RPKCharacter, currency: RPKCurrency): CompletableFuture<RPKBank?> {
val characterId = character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = currency.name
val cacheKey = CharacterCurrencyCacheKey(characterId.value, currencyName.value)
if (cache?.containsKey(cacheKey) == true) {
return CompletableFuture.completedFuture(cache[cacheKey])
}
return CompletableFuture.supplyAsync {
val result = database.create
.select(RPKIT_BANK.BALANCE)
.from(RPKIT_BANK)
.where(RPKIT_BANK.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_BANK.CURRENCY_NAME.eq(currencyName.value))
.fetchOne() ?: return@supplyAsync null
val bank = RPKBank(
character,
currency,
result.get(RPKIT_BANK.BALANCE)
)
cache?.set(cacheKey, bank)
return@supplyAsync bank
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get bank", exception)
throw exception
}
}
/**
* Gets the characters with the highest balance in the given currency.
*
* @param amount The amount of characters to retrieve
* @param currency The currency to
* @return A list of characters with the highest balance in the given currency
*/
fun getTop(amount: Int = 5, currency: RPKCurrency): CompletableFuture<List<RPKBank>> {
return CompletableFuture.supplyAsync {
val currencyName = currency.name
val results = database.create
.select(
RPKIT_BANK.CHARACTER_ID,
RPKIT_BANK.BALANCE
)
.from(RPKIT_BANK)
.where(RPKIT_BANK.CURRENCY_NAME.eq(currencyName.value))
.orderBy(RPKIT_BANK.BALANCE.desc())
.limit(amount)
.fetch()
val characterService = Services[RPKCharacterService::class.java] ?: return@supplyAsync emptyList()
val banks = results
.mapNotNull { result ->
val characterId = result[RPKIT_BANK.CHARACTER_ID]
val character = characterService.getCharacter(RPKCharacterId(characterId)).join()
if (character == null) {
database.create.deleteFrom(RPKIT_BANK)
.where(RPKIT_BANK.CHARACTER_ID.eq(characterId))
.execute()
cache?.remove(CharacterCurrencyCacheKey(characterId, currencyName.value))
null
} else {
RPKBank(
character,
currency,
result[RPKIT_BANK.BALANCE]
)
}
}
banks.forEach { bank ->
val characterId = bank.character.id
if (characterId != null) {
cache?.set(CharacterCurrencyCacheKey(characterId.value, currencyName.value), bank)
}
}
return@supplyAsync banks
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get top bank balances", exception)
throw exception
}
}
fun delete(entity: RPKBank): CompletableFuture<Void> {
val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null)
val currencyName = entity.currency.name
return runAsync {
database.create
.deleteFrom(RPKIT_BANK)
.where(RPKIT_BANK.CHARACTER_ID.eq(characterId.value))
.and(RPKIT_BANK.CURRENCY_NAME.eq(currencyName.value))
.execute()
cache?.remove(CharacterCurrencyCacheKey(characterId.value, currencyName.value))
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete bank", exception)
throw exception
}
}
fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_BANK)
.where(RPKIT_BANK.CHARACTER_ID.eq(characterId.value))
.execute()
cache?.removeMatching { it.character.id?.value == characterId.value }
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete banks for character", exception)
throw exception
}
} | apache-2.0 | 4d43448ac287c562aea76a5bd75a9a5b | 40.274882 | 110 | 0.609325 | 4.919774 | false | false | false | false |
michaeimm/kmn_bot-tool | app/src/main/java/tw/shounenwind/kmnbottool/activities/BoxActivity.kt | 1 | 14908 | package tw.shounenwind.kmnbottool.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Pair
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.activity_mons_data.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.intentFor
import tw.shounenwind.kmnbottool.R
import tw.shounenwind.kmnbottool.gson.BoxData
import tw.shounenwind.kmnbottool.gson.Pet
import tw.shounenwind.kmnbottool.skeleton.BaseActivity
import tw.shounenwind.kmnbottool.util.glide.CircularViewTarget
import tw.shounenwind.kmnbottool.util.glide.GlideApp
import java.lang.ref.WeakReference
import java.text.Collator
import java.util.*
import kotlin.Comparator
import kotlin.collections.ArrayList
class BoxActivity : BaseActivity() {
private lateinit var boxData: BoxData
private var selectFor: String? = null
private lateinit var adapter: BoxAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mons_data)
bindToolbarHomeButton()
selectFor = intent.getStringExtra("selectFor")
boxData = intent.getParcelableExtra("boxData")!!
adapter = BoxAdapter(this)
listView.layoutManager = LinearLayoutManager(this)
listView.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.mons_data_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_profile -> {
val s: String = if (boxData.player.completedRate != "0%") {
boxData.player.name +
"\n" +
getString(R.string.completion) +
": " +
boxData.player.completedRate
} else {
getString(R.string.no_data)
}
val alertDialog = AlertDialog.Builder(this)
.setMessage(s)
.setPositiveButton(R.string.confirm, null)
.create()
alertDialog.show()
return true
}
R.id.sort_series -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
item.isChecked = true
}
return true
}
R.id.sort_name -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val collator = Collator.getInstance(Locale.CHINESE)
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
sort(data, Comparator { o1, o2 ->
collator.compare(o1.name, o2.name)
})
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
item.isChecked = true
}
return true
}
R.id.sort_rare -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
sort(data, Comparator { o1, o2 ->
o1.rare.compareTo(o2.rare) * -1
})
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
item.isChecked = true
}
return true
}
R.id.sort_level -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
data.sortWith(Comparator { o1, o2 ->
val r1 = if (o1!!.level == o1.maxLevel) {
Int.MAX_VALUE
} else {
o1.level
}
val r2 = if (o2!!.level == o2.maxLevel) {
Int.MAX_VALUE
} else {
o2.level
}
r1.compareTo(r2) * -1
})
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
item.isChecked = true
}
return true
}
R.id.sort_class -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
sort(data, Comparator { o1, o2 ->
o1.petClass.compareTo(o2.petClass) * -1
})
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
}
item.isChecked = true
return true
}
R.id.sort_type -> {
mainScope?.launch {
showProgressDialog(getString(R.string.loading))
val collator = Collator.getInstance(Locale.CHINESE)
val data = ArrayList<Pet>(boxData.pets.size)
data.addAll(boxData.pets)
sort(data, Comparator { o1, o2 ->
collator.compare(o1.type + o1.name, o2.type + o2.name)
})
val diffResult = calculateDiff(adapter.monsters, data)
dismissProgressDialog()
adapter.monsters = data
diffResult.dispatchUpdatesTo(adapter)
}
item.isChecked = true
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun getPets() : List<Pet>{
boxData.pets.also { pets ->
val monsters = ArrayList<Pet>(pets.size + 1)
if (selectFor != null && selectFor != "exp") {
val pet = Pet().apply {
name = getString(R.string.no_select)
image = "https://i.imgur.com/6sPlPEzb.jpg"
battleType = ""
maxLevel = Integer.MAX_VALUE
level = 0
maxClass = Integer.MAX_VALUE
petClass = 0
rare = 0
series = ""
skill = ""
type = ""
}
monsters.add(pet)
}
monsters.addAll(pets)
return monsters
}
}
private suspend fun calculateDiff(
oldData: List<Pet>,
newData: List<Pet>
) = withContext(Dispatchers.IO) {
DiffUtil.calculateDiff(BoxDiffCallback(oldData, newData))
}
private suspend fun <T> sort(
data: ArrayList<T>,
comparator: Comparator<T>
) = withContext(Dispatchers.IO) {
data.sortWith(comparator)
}
private class BoxDiffCallback(private val oldData: List<Pet>, private val newData: List<Pet>) : DiffUtil.Callback() {
override fun areItemsTheSame(p0: Int, p1: Int): Boolean {
return oldData[p0].name == newData[p1].name
}
override fun getOldListSize(): Int {
return oldData.size
}
override fun getNewListSize(): Int {
return newData.size
}
override fun areContentsTheSame(p0: Int, p1: Int): Boolean {
return oldData[p0].name == newData[p1].name
}
}
private inner class BoxAdapter(mContext: BoxActivity) : RecyclerView.Adapter<BoxAdapter.MonsterDataHolder>() {
private val wrContext: WeakReference<BoxActivity> = WeakReference(mContext)
var monsters: List<Pet> = getPets()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MonsterDataHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.unit_monster, parent, false)
view.layoutParams = RecyclerView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
)
return MonsterDataHolder(view)
}
override fun getItemCount(): Int {
return monsters.size
}
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: MonsterDataHolder, position: Int) {
val mContext: BoxActivity = wrContext.get()?:return
if (mContext.isFinishing)
return
val monster = monsters[position]
when {
monster.name == getString(R.string.no_select) ->
holder.name.text = monster.name
monster.level == monster.maxLevel ->
holder.name.text = "${monster.name} (Lv.Max)"
else ->
holder.name.text = "${monster.name} (Lv.${monster.level})"
}
val imageView = holder.image
GlideApp.with(mContext)
.asBitmap()
.load(monster.image)
.apply(RequestOptions().centerCrop()
.diskCacheStrategy(DiskCacheStrategy.DATA)
)
.centerCrop()
.into(CircularViewTarget(mContext, imageView))
holder.type.setTextColor(getMonsterColor(monster.type))
if (monster.name != getString(R.string.no_select)) {
if (monster.petClass == monster.maxClass) {
holder.monsterClass.text = "階級:${monster.petClass}(最大)"
} else {
holder.monsterClass.text = "階級:${monster.petClass}"
}
val star = StringBuilder()
val len = monster.rare
repeat(len) {
star.append("☆")
}
holder.type.text = star.toString()
}
if (mContext.selectFor != null) {
holder.item.setOnClickListener {
val intent = Intent()
intent.putExtra("name", monster.name)
mContext.setResult(Activity.RESULT_OK, intent)
mContext.finish()
}
if (monster.name != getString(R.string.no_select)) {
holder.item.setOnLongClickListener {
val intent = intentFor<DetailActivity>()
intent.putExtra("pet", monster)
startActivityWithTransition(intent)
true
}
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imageView.transitionName = "list_p$position"
}
holder.item.setOnClickListener {
val intent = intentFor<DetailActivity>().apply {
putExtra("pet", monster)
putExtra("position", position)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
startActivityWithTransition(
intent,
Pair.create(imageView, imageView.transitionName)
)
} else {
startActivityWithTransition(intent)
}
}
}
}
override fun onViewRecycled(holder: MonsterDataHolder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.image.transitionName = null
}
}
private fun getMonsterColor(type: String): Int {
return when (type) {
"[紅]" -> RED_TYPE
"[綠]" -> GREEN_TYPE
"[藍]" -> BLUE_TYPE
"[黃]" -> YELLOW_TYPE
"[黑]" -> BLACK_TYPE
else -> Color.WHITE
}
}
inner class MonsterDataHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val item = itemView.findViewById<ConstraintLayout>(R.id.monster_unit)!!
val image = itemView.findViewById<ImageView>(R.id.monster_img)!!
val name = itemView.findViewById<TextView>(R.id.monster_name)!!
val type = itemView.findViewById<TextView>(R.id.monster_type)!!
val monsterClass = itemView.findViewById<TextView>(R.id.tvMonsterClass)!!
}
}
companion object {
@JvmStatic
private val RED_TYPE = Color.parseColor("#fc699a")
@JvmStatic
private val GREEN_TYPE = Color.parseColor("#aae467")
@JvmStatic
private val BLUE_TYPE = Color.parseColor("#5ac2f2")
@JvmStatic
private val YELLOW_TYPE = Color.parseColor("#f4e225")
@JvmStatic
private val BLACK_TYPE = Color.parseColor("#a379ec")
}
} | apache-2.0 | a419f6c3b2b64be3e6295b4b25d06747 | 37.853786 | 121 | 0.52043 | 5.233908 | false | false | false | false |
cketti/k-9 | mail/protocols/smtp/src/main/java/com/fsck/k9/mail/transport/smtp/SmtpTransport.kt | 1 | 26918 | package com.fsck.k9.mail.transport.smtp
import com.fsck.k9.logging.Timber
import com.fsck.k9.mail.Address
import com.fsck.k9.mail.AuthType
import com.fsck.k9.mail.Authentication
import com.fsck.k9.mail.AuthenticationFailedException
import com.fsck.k9.mail.CertificateValidationException
import com.fsck.k9.mail.ConnectionSecurity
import com.fsck.k9.mail.K9MailLib
import com.fsck.k9.mail.Message
import com.fsck.k9.mail.Message.RecipientType
import com.fsck.k9.mail.MessagingException
import com.fsck.k9.mail.NetworkTimeouts.SOCKET_CONNECT_TIMEOUT
import com.fsck.k9.mail.NetworkTimeouts.SOCKET_READ_TIMEOUT
import com.fsck.k9.mail.ServerSettings
import com.fsck.k9.mail.filter.Base64
import com.fsck.k9.mail.filter.EOLConvertingOutputStream
import com.fsck.k9.mail.filter.LineWrapOutputStream
import com.fsck.k9.mail.filter.PeekableInputStream
import com.fsck.k9.mail.filter.SmtpDataStuffing
import com.fsck.k9.mail.oauth.OAuth2TokenProvider
import com.fsck.k9.mail.oauth.XOAuth2ChallengeParser
import com.fsck.k9.mail.ssl.TrustedSocketFactory
import com.fsck.k9.mail.transport.smtp.SmtpHelloResponse.Hello
import com.fsck.k9.sasl.buildOAuthBearerInitialClientResponse
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.IOException
import java.io.OutputStream
import java.net.Inet6Address
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.security.GeneralSecurityException
import java.util.Locale
import javax.net.ssl.SSLException
import org.apache.commons.io.IOUtils
import org.jetbrains.annotations.VisibleForTesting
private const val SOCKET_SEND_MESSAGE_READ_TIMEOUT = 5 * 60 * 1000 // 5 minutes
private const val SMTP_CONTINUE_REQUEST = 334
private const val SMTP_AUTHENTICATION_FAILURE_ERROR_CODE = 535
class SmtpTransport(
serverSettings: ServerSettings,
private val trustedSocketFactory: TrustedSocketFactory,
private val oauthTokenProvider: OAuth2TokenProvider?
) {
private val host = serverSettings.host
private val port = serverSettings.port
private val username = serverSettings.username
private val password = serverSettings.password
private val clientCertificateAlias = serverSettings.clientCertificateAlias
private val authType = serverSettings.authenticationType
private val connectionSecurity = serverSettings.connectionSecurity
private var socket: Socket? = null
private var inputStream: PeekableInputStream? = null
private var outputStream: OutputStream? = null
private var responseParser: SmtpResponseParser? = null
private var is8bitEncodingAllowed = false
private var isEnhancedStatusCodesProvided = false
private var largestAcceptableMessage = 0
private var retryOAuthWithNewToken = false
private var isPipeliningSupported = false
private val logger: SmtpLogger = object : SmtpLogger {
override val isRawProtocolLoggingEnabled: Boolean
get() = K9MailLib.isDebug()
override fun log(throwable: Throwable?, message: String, vararg args: Any?) {
Timber.v(throwable, message, *args)
}
}
init {
require(serverSettings.type == "smtp") { "Expected SMTP ServerSettings!" }
}
// TODO: Fix tests to not use open() directly
@VisibleForTesting
@Throws(MessagingException::class)
internal fun open() {
try {
var secureConnection = connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED
val socket = connect()
this.socket = socket
socket.soTimeout = SOCKET_READ_TIMEOUT
inputStream = PeekableInputStream(BufferedInputStream(socket.getInputStream(), 1024))
responseParser = SmtpResponseParser(logger, inputStream!!)
outputStream = BufferedOutputStream(socket.getOutputStream(), 1024)
readGreeting()
val helloName = buildHostnameToReport()
var extensions = sendHello(helloName)
is8bitEncodingAllowed = extensions.containsKey("8BITMIME")
isEnhancedStatusCodesProvided = extensions.containsKey("ENHANCEDSTATUSCODES")
isPipeliningSupported = extensions.containsKey("PIPELINING")
if (connectionSecurity == ConnectionSecurity.STARTTLS_REQUIRED) {
if (extensions.containsKey("STARTTLS")) {
executeCommand("STARTTLS")
val tlsSocket = trustedSocketFactory.createSocket(
socket,
host,
port,
clientCertificateAlias
)
this.socket = tlsSocket
inputStream = PeekableInputStream(BufferedInputStream(tlsSocket.getInputStream(), 1024))
responseParser = SmtpResponseParser(logger, inputStream!!)
outputStream = BufferedOutputStream(tlsSocket.getOutputStream(), 1024)
// Now resend the EHLO. Required by RFC2487 Sec. 5.2, and more specifically, Exim.
extensions = sendHello(helloName)
secureConnection = true
} else {
// This exception triggers a "Certificate error" notification that takes the user to the incoming
// server settings for review. This might be needed if the account was configured with an obsolete
// "STARTTLS (if available)" setting.
throw CertificateValidationException("STARTTLS connection security not available")
}
}
var authLoginSupported = false
var authPlainSupported = false
var authCramMD5Supported = false
var authExternalSupported = false
var authXoauth2Supported = false
var authOAuthBearerSupported = false
val saslMechanisms = extensions["AUTH"]
if (saslMechanisms != null) {
authLoginSupported = saslMechanisms.contains("LOGIN")
authPlainSupported = saslMechanisms.contains("PLAIN")
authCramMD5Supported = saslMechanisms.contains("CRAM-MD5")
authExternalSupported = saslMechanisms.contains("EXTERNAL")
authXoauth2Supported = saslMechanisms.contains("XOAUTH2")
authOAuthBearerSupported = saslMechanisms.contains("OAUTHBEARER")
}
parseOptionalSizeValue(extensions["SIZE"])
if (
username.isNotEmpty() &&
(!password.isNullOrEmpty() || AuthType.EXTERNAL == authType || AuthType.XOAUTH2 == authType)
) {
when (authType) {
AuthType.LOGIN, AuthType.PLAIN -> {
// try saslAuthPlain first, because it supports UTF-8 explicitly
if (authPlainSupported) {
saslAuthPlain()
} else if (authLoginSupported) {
saslAuthLogin()
} else {
throw MessagingException("Authentication methods SASL PLAIN and LOGIN are unavailable.")
}
}
AuthType.CRAM_MD5 -> {
if (authCramMD5Supported) {
saslAuthCramMD5()
} else {
throw MessagingException("Authentication method CRAM-MD5 is unavailable.")
}
}
AuthType.XOAUTH2 -> {
if (oauthTokenProvider == null) {
throw MessagingException("No OAuth2TokenProvider available.")
} else if (authOAuthBearerSupported) {
saslOAuth(OAuthMethod.OAUTHBEARER)
} else if (authXoauth2Supported) {
saslOAuth(OAuthMethod.XOAUTH2)
} else {
throw MessagingException("Server doesn't support SASL OAUTHBEARER or XOAUTH2.")
}
}
AuthType.EXTERNAL -> {
if (authExternalSupported) {
saslAuthExternal()
} else {
// Some SMTP servers are known to provide no error indication when a client certificate
// fails to validate, other than to not offer the AUTH EXTERNAL capability.
// So, we treat it is an error to not offer AUTH EXTERNAL when using client certificates.
// That way, the user can be notified of a problem during account setup.
throw CertificateValidationException(
CertificateValidationException.Reason.MissingCapability
)
}
}
AuthType.AUTOMATIC -> {
if (secureConnection) {
// try saslAuthPlain first, because it supports UTF-8 explicitly
if (authPlainSupported) {
saslAuthPlain()
} else if (authLoginSupported) {
saslAuthLogin()
} else if (authCramMD5Supported) {
saslAuthCramMD5()
} else {
throw MessagingException("No supported authentication methods available.")
}
} else {
if (authCramMD5Supported) {
saslAuthCramMD5()
} else {
// We refuse to insecurely transmit the password using the obsolete AUTOMATIC setting
// because of the potential for a MITM attack. Affected users must choose a different
// setting.
throw MessagingException(
"Update your outgoing server authentication setting. " +
"AUTOMATIC authentication is unavailable."
)
}
}
}
else -> {
throw MessagingException("Unhandled authentication method found in server settings (bug).")
}
}
}
} catch (e: MessagingException) {
close()
throw e
} catch (e: SSLException) {
close()
throw CertificateValidationException(e.message, e)
} catch (e: GeneralSecurityException) {
close()
throw MessagingException("Unable to open connection to SMTP server due to security error.", e)
} catch (e: IOException) {
close()
throw MessagingException("Unable to open connection to SMTP server.", e)
}
}
private fun connect(): Socket {
val inetAddresses = InetAddress.getAllByName(host)
var connectException: Exception? = null
for (address in inetAddresses) {
connectException = try {
return connectToAddress(address)
} catch (e: IOException) {
Timber.w(e, "Could not connect to %s", address)
e
}
}
throw MessagingException("Cannot connect to host", connectException)
}
private fun connectToAddress(address: InetAddress): Socket {
if (K9MailLib.isDebug() && K9MailLib.DEBUG_PROTOCOL_SMTP) {
Timber.d("Connecting to %s as %s", host, address)
}
val socketAddress = InetSocketAddress(address, port)
val socket = if (connectionSecurity == ConnectionSecurity.SSL_TLS_REQUIRED) {
trustedSocketFactory.createSocket(null, host, port, clientCertificateAlias)
} else {
Socket()
}
socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT)
return socket
}
private fun readGreeting() {
val smtpResponse = responseParser!!.readGreeting()
logResponse(smtpResponse)
}
private fun logResponse(smtpResponse: SmtpResponse, omitText: Boolean = false) {
if (K9MailLib.isDebug()) {
Timber.v("%s", smtpResponse.toLogString(omitText, linePrefix = "SMTP <<< "))
}
}
private fun buildHostnameToReport(): String {
val localAddress = socket!!.localAddress
// We use local IP statically for privacy reasons, see https://github.com/thundernest/k-9/pull/3798
return if (localAddress is Inet6Address) {
"[IPv6:::1]"
} else {
"[127.0.0.1]"
}
}
private fun parseOptionalSizeValue(sizeParameters: List<String>?) {
if (sizeParameters != null && sizeParameters.isNotEmpty()) {
val sizeParameter = sizeParameters.first()
val size = sizeParameter.toIntOrNull()
if (size != null) {
largestAcceptableMessage = size
} else {
if (K9MailLib.isDebug() && K9MailLib.DEBUG_PROTOCOL_SMTP) {
Timber.d("SIZE parameter is not a valid integer: %s", sizeParameter)
}
}
}
}
/**
* Send the client "identity" using the `EHLO` or `HELO` command.
*
* We first try the EHLO command. If the server sends a negative response, it probably doesn't support the
* `EHLO` command. So we try the older `HELO` command that all servers have to support. And if that fails, too,
* we pretend everything is fine and continue unimpressed.
*
* @param host The EHLO/HELO parameter as defined by the RFC.
*
* @return A (possibly empty) `Map<String, List<String>>` of extensions (upper case) and their parameters
* (possibly empty) as returned by the EHLO command.
*/
private fun sendHello(host: String): Map<String, List<String>> {
writeLine("EHLO $host")
val helloResponse = responseParser!!.readHelloResponse()
logResponse(helloResponse.response)
return if (helloResponse is Hello) {
helloResponse.keywords
} else {
if (K9MailLib.isDebug()) {
Timber.v("Server doesn't support the EHLO command. Trying HELO...")
}
try {
executeCommand("HELO %s", host)
} catch (e: NegativeSmtpReplyException) {
Timber.w("Server doesn't support the HELO command. Continuing anyway.")
}
emptyMap()
}
}
@Throws(MessagingException::class)
fun sendMessage(message: Message) {
val addresses = buildSet<String> {
for (address in message.getRecipients(RecipientType.TO)) {
add(address.address)
}
for (address in message.getRecipients(RecipientType.CC)) {
add(address.address)
}
for (address in message.getRecipients(RecipientType.BCC)) {
add(address.address)
}
}
if (addresses.isEmpty()) {
return
}
message.removeHeader("Bcc")
ensureClosed()
open()
// If the message has attachments and our server has told us about a limit on the size of messages, count
// the message's size before sending it.
if (largestAcceptableMessage > 0 && message.hasAttachments()) {
if (message.calculateSize() > largestAcceptableMessage) {
throw MessagingException("Message too large for server", true)
}
}
var entireMessageSent = false
try {
val mailFrom = constructSmtpMailFromCommand(message.from, is8bitEncodingAllowed)
if (isPipeliningSupported) {
val pipelinedCommands = buildList {
add(mailFrom)
for (address in addresses) {
add(String.format("RCPT TO:<%s>", address))
}
}
executePipelinedCommands(pipelinedCommands)
readPipelinedResponse(pipelinedCommands)
} else {
executeCommand(mailFrom)
for (address in addresses) {
executeCommand("RCPT TO:<%s>", address)
}
}
executeCommand("DATA")
// Sending large messages might take a long time. We're using an extended timeout while waiting for the
// final response to the DATA command.
val socket = this.socket ?: error("socket == null")
socket.soTimeout = SOCKET_SEND_MESSAGE_READ_TIMEOUT
val msgOut = EOLConvertingOutputStream(
LineWrapOutputStream(
SmtpDataStuffing(outputStream), 1000
)
)
message.writeTo(msgOut)
msgOut.endWithCrLfAndFlush()
// After the "\r\n." is attempted, we may have sent the message
entireMessageSent = true
executeCommand(".")
} catch (e: NegativeSmtpReplyException) {
throw e
} catch (e: Exception) {
throw MessagingException("Unable to send message", entireMessageSent, e)
} finally {
close()
}
}
private fun constructSmtpMailFromCommand(from: Array<Address>, is8bitEncodingAllowed: Boolean): String {
val fromAddress = from.first().address
return if (is8bitEncodingAllowed) {
String.format("MAIL FROM:<%s> BODY=8BITMIME", fromAddress)
} else {
Timber.d("Server does not support 8-bit transfer encoding")
String.format("MAIL FROM:<%s>", fromAddress)
}
}
private fun ensureClosed() {
if (inputStream != null || outputStream != null || socket != null || responseParser != null) {
Timber.w(RuntimeException(), "SmtpTransport was open when it was expected to be closed")
close()
}
}
private fun close() {
writeQuitCommand()
IOUtils.closeQuietly(inputStream)
IOUtils.closeQuietly(outputStream)
IOUtils.closeQuietly(socket)
inputStream = null
responseParser = null
outputStream = null
socket = null
}
private fun writeQuitCommand() {
try {
// We don't care about the server's response to the QUIT command
writeLine("QUIT")
} catch (ignored: Exception) {
}
}
private fun writeLine(command: String, sensitive: Boolean = false) {
if (K9MailLib.isDebug() && K9MailLib.DEBUG_PROTOCOL_SMTP) {
val commandToLog = if (sensitive && !K9MailLib.isDebugSensitive()) {
"SMTP >>> *sensitive*"
} else {
"SMTP >>> $command"
}
Timber.d(commandToLog)
}
// Important: Send command + CRLF using just one write() call. Using multiple calls might result in multiple
// TCP packets being sent and some SMTP servers misbehave if CR and LF arrive in separate packets.
// See https://code.google.com/archive/p/k9mail/issues/799
val data = (command + "\r\n").toByteArray()
outputStream!!.apply {
write(data)
flush()
}
}
private fun executeSensitiveCommand(format: String, vararg args: Any): SmtpResponse {
return executeCommand(sensitive = true, format, *args)
}
private fun executeCommand(format: String, vararg args: Any): SmtpResponse {
return executeCommand(sensitive = false, format, *args)
}
private fun executeCommand(sensitive: Boolean, format: String, vararg args: Any): SmtpResponse {
val command = String.format(Locale.ROOT, format, *args)
writeLine(command, sensitive)
val response = responseParser!!.readResponse(isEnhancedStatusCodesProvided)
logResponse(response, sensitive)
if (response.isNegativeResponse) {
throw buildNegativeSmtpReplyException(response)
}
return response
}
private fun buildNegativeSmtpReplyException(response: SmtpResponse): NegativeSmtpReplyException {
return NegativeSmtpReplyException(
replyCode = response.replyCode,
replyText = response.joinedText,
enhancedStatusCode = response.enhancedStatusCode
)
}
private fun executePipelinedCommands(pipelinedCommands: List<String>) {
for (command in pipelinedCommands) {
writeLine(command, false)
}
}
private fun readPipelinedResponse(pipelinedCommands: List<String>) {
val responseParser = responseParser!!
var firstException: MessagingException? = null
repeat(pipelinedCommands.size) {
val response = responseParser.readResponse(isEnhancedStatusCodesProvided)
logResponse(response, omitText = false)
if (response.isNegativeResponse && firstException == null) {
firstException = buildNegativeSmtpReplyException(response)
}
}
firstException?.let {
throw it
}
}
private fun saslAuthLogin() {
try {
executeCommand("AUTH LOGIN")
executeSensitiveCommand(Base64.encode(username))
executeSensitiveCommand(Base64.encode(password))
} catch (exception: NegativeSmtpReplyException) {
if (exception.replyCode == SMTP_AUTHENTICATION_FAILURE_ERROR_CODE) {
throw AuthenticationFailedException("AUTH LOGIN failed (${exception.message})")
} else {
throw exception
}
}
}
private fun saslAuthPlain() {
val data = Base64.encode("\u0000" + username + "\u0000" + password)
try {
executeSensitiveCommand("AUTH PLAIN %s", data)
} catch (exception: NegativeSmtpReplyException) {
if (exception.replyCode == SMTP_AUTHENTICATION_FAILURE_ERROR_CODE) {
throw AuthenticationFailedException("AUTH PLAIN failed (${exception.message})")
} else {
throw exception
}
}
}
private fun saslAuthCramMD5() {
val respList = executeCommand("AUTH CRAM-MD5").texts
if (respList.size != 1) {
throw MessagingException("Unable to negotiate CRAM-MD5")
}
val b64Nonce = respList[0]
val b64CRAMString = Authentication.computeCramMd5(username, password, b64Nonce)
try {
executeSensitiveCommand(b64CRAMString)
} catch (exception: NegativeSmtpReplyException) {
if (exception.replyCode == SMTP_AUTHENTICATION_FAILURE_ERROR_CODE) {
throw AuthenticationFailedException(exception.message!!, exception)
} else {
throw exception
}
}
}
private fun saslOAuth(method: OAuthMethod) {
retryOAuthWithNewToken = true
try {
attempOAuth(method, username)
} catch (negativeResponse: NegativeSmtpReplyException) {
if (negativeResponse.replyCode != SMTP_AUTHENTICATION_FAILURE_ERROR_CODE) {
throw negativeResponse
}
oauthTokenProvider!!.invalidateToken()
if (!retryOAuthWithNewToken) {
handlePermanentFailure(negativeResponse)
} else {
handleTemporaryFailure(method, username, negativeResponse)
}
}
}
private fun handlePermanentFailure(negativeResponse: NegativeSmtpReplyException): Nothing {
throw AuthenticationFailedException(negativeResponse.message!!, negativeResponse)
}
private fun handleTemporaryFailure(
method: OAuthMethod,
username: String,
negativeResponseFromOldToken: NegativeSmtpReplyException
) {
// Token was invalid. We could avoid this double check if we had a reasonable chance of knowing if a token was
// invalid before use (e.g. due to expiry). But we don't. This is the intended behaviour per AccountManager.
Timber.v(negativeResponseFromOldToken, "Authentication exception, re-trying with new token")
try {
attempOAuth(method, username)
} catch (negativeResponseFromNewToken: NegativeSmtpReplyException) {
if (negativeResponseFromNewToken.replyCode != SMTP_AUTHENTICATION_FAILURE_ERROR_CODE) {
throw negativeResponseFromNewToken
}
// Okay, we failed on a new token. Invalidate the token anyway but assume it's permanent.
Timber.v(negativeResponseFromNewToken, "Authentication exception for new token, permanent error assumed")
oauthTokenProvider!!.invalidateToken()
handlePermanentFailure(negativeResponseFromNewToken)
}
}
private fun attempOAuth(method: OAuthMethod, username: String) {
val token = oauthTokenProvider!!.getToken(OAuth2TokenProvider.OAUTH2_TIMEOUT.toLong())
val authString = method.buildInitialClientResponse(username, token)
val response = executeSensitiveCommand("%s %s", method.command, authString)
if (response.replyCode == SMTP_CONTINUE_REQUEST) {
val replyText = response.joinedText
retryOAuthWithNewToken = XOAuth2ChallengeParser.shouldRetry(replyText, host)
// Per Google spec, respond to challenge with empty response
executeCommand("")
}
}
private fun saslAuthExternal() {
executeCommand("AUTH EXTERNAL %s", Base64.encode(username))
}
@Throws(MessagingException::class)
fun checkSettings() {
ensureClosed()
try {
open()
} finally {
close()
}
}
}
private enum class OAuthMethod {
XOAUTH2 {
override val command = "AUTH XOAUTH2"
override fun buildInitialClientResponse(username: String, token: String): String {
return Authentication.computeXoauth(username, token)
}
},
OAUTHBEARER {
override val command = "AUTH OAUTHBEARER"
override fun buildInitialClientResponse(username: String, token: String): String {
return buildOAuthBearerInitialClientResponse(username, token)
}
};
abstract val command: String
abstract fun buildInitialClientResponse(username: String, token: String): String
}
| apache-2.0 | 7102b62b30127c05d5ca1f48dc7540eb | 38.469208 | 118 | 0.597221 | 5.055973 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/schedule/ScheduleAdapter.kt | 1 | 3648 | package me.proxer.app.anime.schedule
import android.os.Parcelable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL
import androidx.recyclerview.widget.RecyclerView
import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.anime.schedule.ScheduleAdapter.ViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.util.DeviceUtils
import me.proxer.app.util.extension.safeLayoutManager
import me.proxer.app.util.extension.toAppString
import me.proxer.library.entity.media.CalendarEntry
import me.proxer.library.enums.CalendarDay
import kotlin.math.max
/**
* @author Ruben Gees
*/
class ScheduleAdapter : BaseAdapter<Pair<CalendarDay, List<CalendarEntry>>, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, CalendarEntry>> = PublishSubject.create()
private val layoutManagerStates = mutableMapOf<CalendarDay, Parcelable?>()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int) = data[position].let { (day, _) -> day.ordinal.toLong() }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_schedule_day, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun onViewRecycled(holder: ViewHolder) {
withSafeBindingAdapterPosition(holder) {
layoutManagerStates[data[it].first] = holder.childRecyclerView.safeLayoutManager.onSaveInstanceState()
}
holder.childRecyclerView.layoutManager = null
holder.childRecyclerView.adapter = null
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal val weekDay by bindView<TextView>(R.id.weekDay)
internal val childRecyclerView by bindView<RecyclerView>(R.id.childRecyclerView)
init {
childRecyclerView.setHasFixedSize(true)
childRecyclerView.isNestedScrollingEnabled = false
GravitySnapHelper(Gravity.START).attachToRecyclerView(childRecyclerView)
}
fun bind(item: Pair<CalendarDay, List<CalendarEntry>>) {
val (day, calendarEntries) = item
val adapter = ScheduleEntryAdapter()
adapter.glide = glide
adapter.clickSubject.subscribe(clickSubject)
adapter.swapDataAndNotifyWithDiffing(calendarEntries)
weekDay.text = day.toAppString(weekDay.context)
childRecyclerView.layoutManager = LinearLayoutManager(childRecyclerView.context, HORIZONTAL, false).apply {
initialPrefetchItemCount = when (DeviceUtils.isLandscape(itemView.resources)) {
true -> max(5, calendarEntries.size)
false -> max(3, calendarEntries.size)
}
}
childRecyclerView.swapAdapter(adapter, false)
layoutManagerStates[item.first]?.let {
childRecyclerView.safeLayoutManager.onRestoreInstanceState(it)
}
}
}
}
| gpl-3.0 | d2a94fa382cea16b8e8931504d2a9822 | 35.48 | 119 | 0.724232 | 5.017882 | false | false | false | false |
danyf90/DFReminder | app/src/main/java/com/formichelli/dfreminder/DFReminderNotificationListener.kt | 1 | 2637 | package com.formichelli.dfreminder
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import java.util.*
/**
* Listen for notifications
*
*
* Created by daniele on 29/10/15.
*/
class DFReminderNotificationListener : NotificationListenerService() {
private var notifications = HashSet<String>()
private var remindTimer: RemindTimer? = null
private var sharedPreferences: SharedPreferences? = null
private var isEnabledPreferenceString: String? = null
private var packageWhiteList = setOf("android", "com.android.providers.downloads", "com.android.vending", "com.android.systemui")
override fun onCreate() {
remindTimer = RemindTimer(applicationContext, notifications)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
isEnabledPreferenceString = applicationContext.getString(R.string.pref_key_enable_dfreminder)
}
override fun onNotificationPosted(sbn: StatusBarNotification) {
synchronized(remindTimer!!) {
if (shouldBeIgnored(sbn, true))
return
notifications.add(sbn.packageName)
remindTimer!!.restartReminderTimer()
}
}
override fun onNotificationRemoved(sbn: StatusBarNotification) {
synchronized(remindTimer!!) {
if (shouldBeIgnored(sbn, false))
return
notifications.remove(sbn.packageName)
if (notifications.isEmpty())
remindTimer!!.stopReminderTimerIfRunning()
}
}
private fun shouldBeIgnored(sbn: StatusBarNotification, posted: Boolean): Boolean {
val prefix = if (posted) "New" else "Removed"
val packageName = sbn.packageName
if (!sharedPreferences!!.getBoolean(isEnabledPreferenceString, false)) {
Log.d(DFReminderMainActivity.TAG, "$prefix notification from $packageName: DF reminder disabled")
return true
}
if (packageWhiteList.contains(packageName)) {
Log.d(DFReminderMainActivity.TAG, "$prefix notification from $packageName ignored")
return true
}
if (!sbn.isClearable) {
Log.d(DFReminderMainActivity.TAG, "$prefix not clearable notification from $packageName ignored")
return true
}
Log.d(DFReminderMainActivity.TAG, "$prefix notification from $packageName, total: " + notifications.size)
return false
}
}
| gpl-3.0 | 0014deb7dfa6d77cd7cdefe8c3b7952f | 35.123288 | 133 | 0.692833 | 5.110465 | false | false | false | false |
elmozgo/PortalMirror | portalmirror-twitterfeed-core/src/main/kotlin/org/portalmirror/twitterfeed/core/logic/TwitterRepository.kt | 1 | 3886 | package org.portalmirror.twitterfeed.core.logic
import com.google.common.cache.CacheLoader
import twitter4j.*
import twitter4j.conf.Configuration
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
import com.google.common.cache.CacheBuilder
import mu.KotlinLogging
class TwitterRepository(configuration: Configuration, cacheTimeout : Long) {
private val logger = KotlinLogging.logger {}
private val repliesToUserCacheLoader = object : CacheLoader<String, List<Status>>() {
override fun load(key: String?): List<Status> {
logger.debug { "repliesToUserCacheLoader called" }
return getRepliesToUser(key!!)
}
}
private val repliesToUsersCache = CacheBuilder
.newBuilder()
.expireAfterWrite(cacheTimeout, TimeUnit.SECONDS)
.build(repliesToUserCacheLoader)
private fun getRepliesToUser(screenName : String, since : Date? = null , until : Date? = null) : List<Status> {
logger.debug { "getRepliesToUser : screenName=[$screenName], since=[${since?.formatToLog()}], until=[${until?.formatToLog()}]" }
val globalRepliesToUser : MutableList<Status> = mutableListOf()
val query = Query("to:$screenName")
since?.let {
query.since = since.formatToTwitterDate()
}
until?.let {
query.until = until.formatToTwitterDate()
}
query.count = 100
var maxId = Long.MAX_VALUE
for(i in 1..10) {
query.maxId = maxId
logger.debug { "calling twitter.search(query) : q=[${query.query}] maxId=[$maxId] " }
val tweets = twitter.search(query).tweets
logger.debug { "received ${tweets.size} tweets" }
if(tweets.isEmpty()) {
break
}
globalRepliesToUser.addAll(tweets)
maxId = tweets.minBy({ it.id })!!.id
}
logger.debug { "found ${globalRepliesToUser.size} replies" }
return globalRepliesToUser
}
private val twitter: Twitter = TwitterFactory(configuration).instance
fun getTop20StatusesFromTimeline (screenName: String): List<Status> {
logger.debug { "getTop20StatusesFromTimeline() : screenName=$screenName" }
return twitter.getUserTimeline(screenName)
}
fun getAllRepliesToStatus(status : Status) : List<Status>{
logger.debug { "getAllRepliesToStatus() : statusId=[${status.id}]" }
val cachedReplies : List<Status> = repliesToUsersCache.get(status.user.screenName)
if(cachedReplies.isEmpty()) {
logger.debug { "no replies" }
return cachedReplies
}
val totalReplies : List<Status>
if(cachedReplies.none { it.createdAt.before(status.createdAt) }) {
val dateOfOldestReply = cachedReplies.minWith(Comparator { o1, o2 ->
o1.createdAt.compareTo(o2.createdAt)
})!!.createdAt
val olderReplies = getRepliesToUser(status.user.screenName, status.createdAt, dateOfOldestReply)
totalReplies = cachedReplies + olderReplies
repliesToUsersCache.put(status.user.screenName, totalReplies)
logger.debug { "cache updated for screenName=[${status.user.screenName}], repliesCount=[${totalReplies.size}]" }
} else {
totalReplies = cachedReplies
}
val repliesToStatus = totalReplies.filter { tweet -> tweet.inReplyToStatusId == status.id }
logger.debug { "number of replies to statusId=[${status.id}] : ${repliesToStatus.size}" }
return repliesToStatus
}
}
fun java.util.Date.formatToLog() : String {
return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(this)
}
fun java.util.Date.formatToTwitterDate() : String {
return SimpleDateFormat("yyyy-MM-dd").format(this)
} | gpl-3.0 | c7391887a639b4c17eb0ba43d55d763c | 31.123967 | 136 | 0.645908 | 4.482122 | false | false | false | false |
StefanOltmann/Kaesekaestchen | app/src/main/java/de/stefan_oltmann/kaesekaestchen/model/Spielfeld.kt | 1 | 8072 | /*
* Kaesekaestchen
* A simple Dots'n'Boxes Game for Android
*
* Copyright (C) Stefan Oltmann
*
* Contact : [email protected]
* Homepage: https://github.com/StefanOltmann/Kaesekaestchen
*
* This file is part of Kaesekaestchen.
*
* Kaesekaestchen 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.
*
* Kaesekaestchen 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 Kaesekaestchen. If not, see <http://www.gnu.org/licenses/>.
*/
package de.stefan_oltmann.kaesekaestchen.model
/**
* Das Spielfeld. Es besteht aus {@link Kaestchen}.
*/
class Spielfeld private constructor() {
private lateinit var spielfeldGroesse: SpielfeldGroesse
val breiteInKaestchen
get() = spielfeldGroesse.breiteInKaestchen
val hoeheInKaestchen
get() = spielfeldGroesse.hoeheInKaestchen
private lateinit var kaestchenArray: Array<Array<Kaestchen?>>
/*
* Die Liste aller Kästchen
*/
private val _kaestchenListe: MutableList<Kaestchen> = mutableListOf()
val kaestchenListe: List<Kaestchen>
get() = _kaestchenListe
/**
* Aus Performance-Gründen wird eine zweite Liste geführt, damit die
* 'kaestchenListe' nicht so häufig durch-iteriert werden muss. Dies führt
* bei großen Feldern zu schlechter Performance.
*/
private val offeneKaestchen: MutableList<Kaestchen> = mutableListOf()
private val stricheOhneBesitzer: MutableSet<Strich> = mutableSetOf()
/*
* Der zuletzt gesetze Strich soll eine andere Farbe haben, damit der
* Spieler besser erkennen kann, wo zuletzt einer dazugekommen ist.
*/
var zuletztGesetzterStrich: Strich? = null
constructor(spielfeldGroesse: SpielfeldGroesse) : this() {
this.spielfeldGroesse = spielfeldGroesse
val breiteInKaestchen = spielfeldGroesse.breiteInKaestchen
val hoeheInKaestchen = spielfeldGroesse.hoeheInKaestchen
kaestchenArray = Array(breiteInKaestchen) { arrayOfNulls<Kaestchen?>(hoeheInKaestchen) }
/*
* Erstmal alle Kästchen erzeugen und in das Array sowie
* die Listen einfügen.
*/
for (rasterX in 0 until breiteInKaestchen) {
for (rasterY in 0 until hoeheInKaestchen) {
val kaestchen = Kaestchen(rasterX, rasterY)
kaestchenArray[kaestchen.rasterX][kaestchen.rasterY] = kaestchen
_kaestchenListe.add(kaestchen)
offeneKaestchen.add(kaestchen)
}
}
/**
* Jetzt die Beziehungen zueinander herstellen um
* gemeinsame Striche der Kästchen zu ermitteln.
*/
for (kaestchen in _kaestchenListe) {
val rasterX = kaestchen.rasterX
val rasterY = kaestchen.rasterY
/*
* Nach rechts
*/
var kaestchenRechts: Kaestchen? = null
if (rasterX < breiteInKaestchen - 1)
kaestchenRechts = kaestchenArray[rasterX + 1][rasterY]
if (kaestchenRechts != null) {
val strichRechts = Strich(null, null, kaestchen, kaestchenRechts)
kaestchen.strichRechts = strichRechts
kaestchenRechts.strichLinks = strichRechts
stricheOhneBesitzer.add(strichRechts)
}
/*
* Nach unten
*/
var kaestchenUnten: Kaestchen? = null
if (rasterY < hoeheInKaestchen - 1)
kaestchenUnten = kaestchenArray[rasterX][rasterY + 1]
if (kaestchenUnten != null) {
val strichUnten = Strich(kaestchen, kaestchenUnten, null, null)
kaestchen.strichUnten = strichUnten
kaestchenUnten.strichOben = strichUnten
stricheOhneBesitzer.add(strichUnten)
}
}
}
fun getKaestchen(rasterX: Int, rasterY: Int): Kaestchen {
/* Außerhalb des Rasters gibts kein Kästchen. */
require(isImRaster(rasterX, rasterY)) {
"Das Kästchen liegt außerhalb des Rasters: " +
"$rasterX >= $spielfeldGroesse.groesseX || $rasterY >= $spielfeldGroesse.groesseY"
}
return kaestchenArray[rasterX][rasterY]!!
}
fun isImRaster(rasterX: Int, rasterY: Int) =
rasterX < spielfeldGroesse.breiteInKaestchen && rasterY < spielfeldGroesse.hoeheInKaestchen
/**
* Schließt alle Kästchen, die geschlossen werden können.
*
* @param zuzuweisenderBesitzer
* Der zuzuweisende Besitzer dieser Kästchen
*
* @return Konnte mindestens ein Kästchen geschlossen werden? (Wichtig für Spielablauf)
*/
private fun schliesseAlleMoeglichenKaestchen(zuzuweisenderBesitzer: Spieler): Boolean {
var mindestensEinKaestchenKonnteGeschlossenWerden = false
val offeneKaestchenIt = offeneKaestchen.iterator()
while (offeneKaestchenIt.hasNext()) {
val kaestchen = offeneKaestchenIt.next()
if (kaestchen.isAlleStricheHabenBesitzer && kaestchen.besitzer == null) {
kaestchen.besitzer = zuzuweisenderBesitzer
offeneKaestchenIt.remove()
mindestensEinKaestchenKonnteGeschlossenWerden = true
}
}
return mindestensEinKaestchenKonnteGeschlossenWerden
}
fun isAlleKaestchenHabenBesitzer() = offeneKaestchen.isEmpty()
fun isEsGibtFreieStriche() = stricheOhneBesitzer.isNotEmpty()
fun waehleStrich(strich: Strich, spieler: Spieler): Boolean {
strich.besitzer = spieler
stricheOhneBesitzer.remove(strich)
zuletztGesetzterStrich = strich
return schliesseAlleMoeglichenKaestchen(spieler)
}
fun ermittleGutenStrichFuerComputerZug(): Strich {
/*
* Wenn irgendwo ein Kästchen geschlossen werden kann, dann
* soll das natürlich auf jeden Fall passieren. Alles andere
* wäre ja wirklich sehr dumm.
*/
findeLetztenOffenenStrichFuerKaestchen()?.let {
return it
}
/*
* Falls kein Kästchen irgendwo geschlossen werden kann probieren
* wir jetzt zufällig Striche durch und achten darauf, dass wir
* dabei keine Punkte verschenken. Wenn wir aber nach 30 Versuchen
* nichts gefunden haben, muss es wohl so sein.
*/
var zufallsStrich = findeZufaelligenStrich()
var loopCounter = 0
while (zufallsStrich.isKoennteUmliegendendesKaestchenSchliessen()) {
zufallsStrich = findeZufaelligenStrich()
if (++loopCounter >= ANZAHL_KI_VERSUCHE)
break
}
return zufallsStrich
}
private fun findeLetztenOffenenStrichFuerKaestchen(): Strich? {
for (kaestchen in offeneKaestchen)
if (kaestchen.stricheOhneBesitzer.size == 1)
return kaestchen.stricheOhneBesitzer[0]
return null
}
private fun findeZufaelligenStrich(): Strich {
check(isEsGibtFreieStriche()) { "Es gibt keine freien Striche mehr." }
val stricheOhneBesitzer = stricheOhneBesitzer.toList()
val zufallsZahl = (0..stricheOhneBesitzer.size.minus(1)).random()
return stricheOhneBesitzer[zufallsZahl]
}
fun ermittlePunktzahl(spieler: Spieler): Int {
var punkte = 0
for (kaestchen in _kaestchenListe)
if (kaestchen.besitzer == spieler)
punkte++
return punkte
}
companion object {
private const val ANZAHL_KI_VERSUCHE = 30
}
}
| gpl-3.0 | e04f142bb54bdd4a4ac27f6fc54bf22a | 29.484848 | 99 | 0.648733 | 3.45556 | false | false | false | false |
edsilfer/presence-control | app/src/main/java/br/com/edsilfer/android/presence_control/activity/presentation/view/ActivityListAdapter.kt | 1 | 2528 | package br.com.edsilfer.android.presence_control.activity.presentation.view
import android.support.v7.widget.RecyclerView
import br.com.edsilfer.android.presence_control.R
import br.com.edsilfer.android.presence_control.activity.domain.entity.Activity
import br.com.edsilfer.android.presence_control.activity.domain.entity.ActivityAction
import br.com.edsilfer.android.presence_control.activity.domain.observables.ObservableActivityItemClicked
import br.com.edsilfer.android.presence_control.activity.presentation.model.ActivityHolder
import br.com.edsilfer.android.presence_control.commons.utils.extension.format
import br.com.edsilfer.android.presence_control.commons.utils.extension.parseHtml
import br.com.edsilfer.android.presence_control.core.presentation.BaseAdapter
import java.util.*
/**
* Created by ferna on 5/21/2017.
*/
class ActivityListAdapter(
mActivity: android.support.v7.app.AppCompatActivity,
mDataSet: MutableList<Activity>,
mLayout: Int
) : BaseAdapter<Activity>(mActivity, mDataSet, mLayout) {
override fun getViewHolder(view: android.view.View): android.support.v7.widget.RecyclerView.ViewHolder {
return ActivityHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val myHolder = holder as ActivityHolder
val activity = mDataSet[position]
val date = Date(activity.timestamp)
when (ActivityAction.fromString(activity.action)) {
ActivityAction.ARRIVED -> {
myHolder.action.text = String.format(
mContext.getString(R.string.str_activity_arrived_header),
activity.action,
activity.location.name,
date.format("hh:mm")
).parseHtml()
}
ActivityAction.LEFT -> {
myHolder.action.text = String.format(
mContext.getString(R.string.str_activity_left_header),
activity.action,
activity.location.name,
date.format("hh:mm")
).parseHtml()
}
}
myHolder.location.text = String.format(mContext.getString(R.string.str_activity_address), activity.location.address).parseHtml()
myHolder.timestamp.text = date.format("dd/MM")
myHolder.container.setOnLongClickListener {
ObservableActivityItemClicked.publish(activity)
true
}
}
} | apache-2.0 | 77c9f4696be334652151578ed389b5b7 | 42.603448 | 136 | 0.672864 | 4.490231 | false | false | false | false |
nlefler/Glucloser | Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/FoodListRecyclerAdapter.kt | 1 | 1725 | package com.nlefler.glucloser.a.dataSource
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.nlefler.glucloser.a.R
import com.nlefler.glucloser.a.models.Food
import java.util.*
public class FoodListRecyclerAdapter(private var foods: List<Food>) : RecyclerView.Adapter<FoodListRecyclerAdapter.ViewHolder>() {
init {
this.foods = ArrayList<Food>()
}
public class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
internal var food: Food? = null
internal var foodName: TextView
internal var carbsValue: TextView
init {
this.foodName = itemView.findViewById(R.id.food_list_item_name) as TextView
this.carbsValue = itemView.findViewById(R.id.food_list_item_carbs) as TextView
}
}
public fun setFoods(foods: List<Food>) {
this.foods = foods
notifyDataSetChanged()
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): FoodListRecyclerAdapter.ViewHolder {
val view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.food_list_item, viewGroup, false)
return FoodListRecyclerAdapter.ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: FoodListRecyclerAdapter.ViewHolder, i: Int) {
if (i >= this.foods.size) {
return
}
val food = this.foods.get(i)
viewHolder.food = food
viewHolder.foodName.setText("${food.foodName}")
viewHolder.carbsValue.setText("${food.carbs}")
}
override fun getItemCount(): Int {
return this.foods.size
}
}
| gpl-2.0 | 0005ee8a4441a0c55dd7af17af456e11 | 31.54717 | 130 | 0.691014 | 4.345088 | false | false | false | false |
yuzumone/PokePortal | app/src/main/kotlin/net/yuzumone/pokeportal/util/ResourceUtil.kt | 1 | 1943 | package net.yuzumone.pokeportal.util
import android.annotation.TargetApi
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.VectorDrawable
import android.os.Build
import android.support.annotation.DrawableRes
import android.support.graphics.drawable.VectorDrawableCompat
import android.support.v4.content.ContextCompat
class ResourceUtil {
companion object {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private fun getBitmap(vectorDrawable: VectorDrawable): Bitmap {
val bitmap = Bitmap.createBitmap(vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
vectorDrawable.draw(canvas)
return bitmap
}
private fun getBitmap(vectorDrawable: VectorDrawableCompat): Bitmap {
val bitmap = Bitmap.createBitmap(vectorDrawable.intrinsicWidth,
vectorDrawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
vectorDrawable.setBounds(0, 0, canvas.width, canvas.height)
vectorDrawable.draw(canvas)
return bitmap
}
fun getBitmap(context: Context, @DrawableRes drawableResId: Int): Bitmap {
val drawable = ContextCompat.getDrawable(context, drawableResId)
if (drawable is BitmapDrawable) {
return drawable.bitmap
} else if (drawable is VectorDrawableCompat) {
return getBitmap(drawable)
} else if (drawable is VectorDrawable) {
return getBitmap(drawable)
} else {
throw IllegalArgumentException("Unsupported drawable type")
}
}
}
} | apache-2.0 | a8cb16816f460daa3400e199fc951a99 | 38.673469 | 82 | 0.676274 | 5.382271 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/tilemodules/ModuleMultiblockCenter.kt | 2 | 2030 | package com.cout970.magneticraft.systems.tilemodules
import com.cout970.magneticraft.AABB
import com.cout970.magneticraft.systems.multiblocks.IMultiblockCenter
import com.cout970.magneticraft.systems.multiblocks.Multiblock
import com.cout970.magneticraft.systems.tileentities.IModule
import com.cout970.magneticraft.systems.tileentities.IModuleContainer
import net.minecraft.util.EnumFacing
import net.minecraft.util.math.BlockPos
import net.minecraftforge.common.capabilities.Capability
class ModuleMultiblockCenter(
val multiblockStructure: Multiblock,
val facingGetter: () -> EnumFacing,
val capabilityGetter: (cap: Capability<*>, side: EnumFacing?, pos: BlockPos) -> Any?,
val dynamicCollisionBoxes: (BlockPos) -> List<AABB> = { emptyList() },
override val name: String = "module_multiblock"
) : IModule, IMultiblockCenter {
override lateinit var container: IModuleContainer
companion object {
val emptyCapabilityGetter: (cap: Capability<*>, side: EnumFacing?, pos: BlockPos) -> Any? = { _, _, _ -> null }
}
//current multiblock
override var multiblock: Multiblock? = multiblockStructure
set(_) {}
//relative position from the multiblock center to this block
override var centerPos: BlockPos? = BlockPos.ORIGIN
set(_) {}
//orientation of the multiblock
override var multiblockFacing: EnumFacing?
get() = facingGetter()
set(_) {}
override fun onDeactivate() {
container.tile.onBreak()
}
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?, relPos: BlockPos): Boolean {
return capabilityGetter.invoke(capability, facing, relPos) != null
}
@Suppress("UNCHECKED_CAST")
override fun <T> getCapability(capability: Capability<T>, facing: EnumFacing?, relPos: BlockPos): T? {
return capabilityGetter.invoke(capability, facing, relPos) as? T?
}
override fun getDynamicCollisionBoxes(otherPos: BlockPos): List<AABB> = dynamicCollisionBoxes(otherPos)
} | gpl-2.0 | 0b581483112b3c7e27252b6a653caaa0 | 37.320755 | 119 | 0.727586 | 4.481236 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ideaInterop/fileTypes/uxml/codeInsight/schema/UxmlSchemaProvider.kt | 1 | 3172 | package com.jetbrains.rider.plugins.unity.ideaInterop.fileTypes.uxml.codeInsight.schema
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ModificationTracker
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.util.CachedValue
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.xml.XmlFile
import com.intellij.xml.XmlSchemaProvider
import com.jetbrains.rd.platform.util.idea.getOrCreateUserData
import com.jetbrains.rider.plugins.unity.isUnityProject
import com.jetbrains.rider.projectDir
import com.jetbrains.rider.projectView.solutionDirectory
import java.nio.file.Paths
class UxmlSchemaProvider: XmlSchemaProvider(), DumbAware {
private val SCHEMAS_FILE_MAP_KEY: Key<MutableMap<String, CachedValue<XmlFile>>> = Key.create("UXML_SCHEMAS_FILE_MAP_KEY")
override fun isAvailable(file: XmlFile): Boolean {
// Add schemas for any XML file type in a Unity project. This means schemas will resolve inside the .xsd files too
return file.project.isUnityProject()
}
override fun getSchema(url: String, module: Module?, baseFile: PsiFile): XmlFile? {
// Load the schema for the given url. Basically, this will be /UIElementSchema/{url}.xsd
if (url.isEmpty()) return null
val project = baseFile.project
val schemas = getSchemas(project)
val cachedValue = schemas[url]
if (cachedValue != null) return cachedValue.value
val schema = CachedValuesManager.getManager(project).createCachedValue(object : CachedValueProvider<XmlFile> {
override fun compute(): CachedValueProvider.Result<XmlFile>? {
val file = project.projectDir.findFileByRelativePath("/UIElementsSchema/$url.xsd")
if (file == null || !file.exists()) {
return CachedValueProvider.Result(null, ModificationTracker.EVER_CHANGED)
}
val psiFile = PsiManager.getInstance(project).findFile(file)
return CachedValueProvider.Result.create(psiFile as XmlFile, psiFile, file)
}
}, true)
schemas[url] = schema
return schema.value
}
override fun getAvailableNamespaces(file: XmlFile, tagName: String?): Set<String> {
// For the given XmlFile, what namespaces do we know about?
// The schemas are named after the namespace
return getSchemas(file.project).keys
}
override fun getLocations(namespace: String, context: XmlFile): Set<String>? {
val schemas = getSchemas(context.project)
if (schemas.containsKey(namespace)) {
return mutableSetOf(context.project.solutionDirectory.resolve("UIElementsSchema/$namespace.xsd").toURI().toString())
}
return null
}
private fun getSchemas(project: Project): MutableMap<String, CachedValue<XmlFile>> {
return project.getOrCreateUserData(SCHEMAS_FILE_MAP_KEY) { mutableMapOf() }
}
} | apache-2.0 | 3f09cefa004a32d0d0a254748e462fa9 | 41.878378 | 128 | 0.718474 | 4.537911 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt | 1 | 67251 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.infer
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.containers.isNullOrEmpty
import org.jetbrains.annotations.TestOnly
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.SelectionResult
import org.rust.lang.core.resolve.StdKnownItems
import org.rust.lang.core.resolve.ref.MethodCallee
import org.rust.lang.core.resolve.ref.resolveFieldLookupReferenceWithReceiverType
import org.rust.lang.core.resolve.ref.resolveMethodCallReferenceWithReceiverType
import org.rust.lang.core.resolve.ref.resolvePath
import org.rust.lang.core.stubs.RsStubLiteralType
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.TraitRef
import org.rust.lang.core.types.selfType
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.ty.Mutability.IMMUTABLE
import org.rust.lang.core.types.ty.Mutability.MUTABLE
import org.rust.lang.core.types.type
import org.rust.lang.utils.RsDiagnostic
import org.rust.openapiext.Testmark
import org.rust.openapiext.forEachChild
import org.rust.openapiext.recursionGuard
import org.rust.stdext.singleOrFilter
import org.rust.stdext.singleOrLet
import org.rust.stdext.zipValues
fun inferTypesIn(element: RsInferenceContextOwner): RsInferenceResult {
val items = StdKnownItems.relativeTo(element)
val lookup = ImplLookup(element.project, items)
return recursionGuard(element, Computable { lookup.ctx.infer(element) })
?: error("Can not run nested type inference")
}
/**
* [RsInferenceResult] is an immutable per-function map
* from expressions to their types.
*/
class RsInferenceResult(
private val bindings: Map<RsPatBinding, Ty>,
private val exprTypes: Map<RsExpr, Ty>,
private val resolvedPaths: Map<RsPathExpr, List<RsElement>>,
private val resolvedMethods: Map<RsMethodCall, List<RsFunction>>,
private val resolvedFields: Map<RsFieldLookup, List<RsElement>>,
val diagnostics: List<RsDiagnostic>
) {
fun getExprType(expr: RsExpr): Ty =
exprTypes[expr] ?: TyUnknown
fun getBindingType(binding: RsPatBinding): Ty =
bindings[binding] ?: TyUnknown
fun getResolvedPath(expr: RsPathExpr): List<RsElement> =
resolvedPaths[expr] ?: emptyList()
fun getResolvedMethod(call: RsMethodCall): List<RsFunction> =
resolvedMethods[call] ?: emptyList()
fun getResolvedField(call: RsFieldLookup): List<RsElement> =
resolvedFields[call] ?: emptyList()
override fun toString(): String =
"RsInferenceResult(bindings=$bindings, exprTypes=$exprTypes)"
@TestOnly
fun isExprTypeInferred(expr: RsExpr): Boolean =
expr in exprTypes
}
/**
* A mutable object, which is filled while we walk function body top down.
*/
class RsInferenceContext(
val lookup: ImplLookup,
val items: StdKnownItems
) {
val fulfill: FulfillmentContext = FulfillmentContext(this, lookup)
private val bindings: MutableMap<RsPatBinding, Ty> = HashMap()
private val exprTypes: MutableMap<RsExpr, Ty> = HashMap()
private val resolvedPaths: MutableMap<RsPathExpr, List<RsElement>> = HashMap()
private val resolvedMethods: MutableMap<RsMethodCall, List<RsFunction>> = HashMap()
private val resolvedFields: MutableMap<RsFieldLookup, List<RsElement>> = HashMap()
private val pathRefinements: MutableList<Pair<RsPathExpr, TraitRef>> = mutableListOf()
private val methodRefinements: MutableList<Pair<RsMethodCall, TraitRef>> = mutableListOf()
val diagnostics: MutableList<RsDiagnostic> = mutableListOf()
private val intUnificationTable: UnificationTable<TyInfer.IntVar, TyInteger> = UnificationTable()
private val floatUnificationTable: UnificationTable<TyInfer.FloatVar, TyFloat> = UnificationTable()
private val varUnificationTable: UnificationTable<TyInfer.TyVar, Ty> = UnificationTable()
private val projectionCache: ProjectionCache = ProjectionCache()
private class CombinedSnapshot(vararg val snapshots: Snapshot) : Snapshot {
override fun rollback() = snapshots.forEach { it.rollback() }
override fun commit() = snapshots.forEach { it.commit() }
}
fun startSnapshot(): Snapshot = CombinedSnapshot(
intUnificationTable.startSnapshot(),
floatUnificationTable.startSnapshot(),
varUnificationTable.startSnapshot(),
projectionCache.startSnapshot()
)
inline fun <T> probe(action: () -> T): T {
val snapshot = startSnapshot()
try {
return action()
} finally {
snapshot.rollback()
}
}
fun infer(element: RsInferenceContextOwner): RsInferenceResult {
if (element is RsFunction) {
val fctx = RsFnInferenceContext(this, element.returnType)
fctx.extractParameterBindings(element)
element.block?.let { fctx.inferFnBody(it) }
} else {
val (retTy, expr) = when (element) {
is RsConstant -> element.typeReference?.type to element.expr
is RsArrayType -> TyInteger.USize to element.expr
is RsVariantDiscriminant -> TyInteger.ISize to element.expr
else -> error("Type inference is not implemented for PSI element of type " +
"`${element.javaClass}` that implement `RsInferenceContextOwner`")
}
if (expr != null) {
RsFnInferenceContext(this, retTy ?: TyUnknown).inferLambdaBody(expr)
}
}
fulfill.selectWherePossible()
exprTypes.replaceAll { _, ty -> fullyResolve(ty) }
bindings.replaceAll { _, ty -> fullyResolve(ty) }
performPathsRefinement(lookup)
return RsInferenceResult(bindings, exprTypes, resolvedPaths, resolvedMethods, resolvedFields, diagnostics)
}
private fun performPathsRefinement(lookup: ImplLookup) {
for ((path, traitRef) in pathRefinements) {
val fnName = resolvedPaths[path]?.firstOrNull()?.let { (it as? RsFunction)?.name }
lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()
?.impl?.members?.functionList?.find { it.name == fnName }
?.let { resolvedPaths[path] = listOf(it) }
}
for ((call, traitRef) in methodRefinements) {
val fnName = resolvedMethods[call]?.firstOrNull()?.name
lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()
?.impl?.members?.functionList?.find { it.name == fnName }
?.let { resolvedMethods[call] = listOf(it) }
}
}
fun getExprType(expr: RsExpr): Ty {
return exprTypes[expr] ?: TyUnknown
}
fun isTypeInferred(expr: RsExpr): Boolean {
return exprTypes.containsKey(expr)
}
fun getBindingType(binding: RsPatBinding): Ty {
return bindings[binding] ?: TyUnknown
}
fun getResolvedPaths(expr: RsPathExpr): List<RsElement> {
return resolvedPaths[expr] ?: emptyList()
}
fun writeExprTy(psi: RsExpr, ty: Ty) {
exprTypes[psi] = ty
}
fun writeBindingTy(psi: RsPatBinding, ty: Ty) {
bindings[psi] = ty
}
fun writePath(path: RsPathExpr, resolved: List<BoundElement<RsElement>>) {
resolvedPaths[path] = resolved.map { it.element }
}
fun writeResolvedMethod(call: RsMethodCall, resolvedTo: List<RsFunction>) {
resolvedMethods[call] = resolvedTo
}
fun writeResolvedField(lookup: RsFieldLookup, resolvedTo: List<RsElement>) {
resolvedFields[lookup] = resolvedTo
}
fun registerPathRefinement(path: RsPathExpr, traitRef: TraitRef) {
pathRefinements.add(Pair(path, traitRef))
}
fun registerMethodRefinement(path: RsMethodCall, traitRef: TraitRef) {
methodRefinements.add(Pair(path, traitRef))
}
fun reportTypeMismatch(expr: RsExpr, expected: Ty, actual: Ty) {
diagnostics.add(RsDiagnostic.TypeError(expr, expected, actual))
}
fun canCombineTypes(ty1: Ty, ty2: Ty): Boolean {
return probe { combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2)) }
}
fun combineTypesIfOk(ty1: Ty, ty2: Ty): Boolean {
return combineTypesIfOkResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesIfOkResolved(ty1: Ty, ty2: Ty): Boolean {
val snapshot = startSnapshot()
val res = combineTypesResolved(ty1, ty2)
if (res) {
snapshot.commit()
} else {
snapshot.rollback()
}
return res
}
fun combineTypes(ty1: Ty, ty2: Ty): Boolean {
return combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2))
}
private fun combineTypesResolved(ty1: Ty, ty2: Ty): Boolean {
return when {
ty1 is TyInfer.TyVar -> combineTyVar(ty1, ty2)
ty2 is TyInfer.TyVar -> combineTyVar(ty2, ty1)
else -> when {
ty1 is TyInfer -> combineIntOrFloatVar(ty1, ty2)
ty2 is TyInfer -> combineIntOrFloatVar(ty2, ty1)
else -> combineTypesNoVars(ty1, ty2)
}
}
}
private fun combineTyVar(ty1: TyInfer.TyVar, ty2: Ty): Boolean {
when (ty2) {
is TyInfer.TyVar -> varUnificationTable.unifyVarVar(ty1, ty2)
else -> {
val ty1r = varUnificationTable.findRoot(ty1)
val isTy2ContainsTy1 = ty2.visitWith(object : TypeVisitor {
override fun invoke(ty: Ty): Boolean = when {
ty is TyInfer.TyVar && varUnificationTable.findRoot(ty) == ty1r -> true
ty.hasTyInfer -> ty.superVisitWith(this)
else -> false
}
})
if (isTy2ContainsTy1) {
// "E0308 cyclic type of infinite size"
TypeInferenceMarks.cyclicType.hit()
varUnificationTable.unifyVarValue(ty1r, TyUnknown)
} else {
varUnificationTable.unifyVarValue(ty1r, ty2)
}
}
}
return true
}
private fun combineIntOrFloatVar(ty1: TyInfer, ty2: Ty): Boolean {
when (ty1) {
is TyInfer.IntVar -> when (ty2) {
is TyInfer.IntVar -> intUnificationTable.unifyVarVar(ty1, ty2)
is TyInteger -> intUnificationTable.unifyVarValue(ty1, ty2)
else -> return false
}
is TyInfer.FloatVar -> when (ty2) {
is TyInfer.FloatVar -> floatUnificationTable.unifyVarVar(ty1, ty2)
is TyFloat -> floatUnificationTable.unifyVarValue(ty1, ty2)
else -> return false
}
is TyInfer.TyVar -> error("unreachable")
}
return true
}
private fun combineTypesNoVars(ty1: Ty, ty2: Ty): Boolean {
return ty1 === ty2 || when {
ty1 is TyPrimitive && ty2 is TyPrimitive && ty1 == ty2 -> true
ty1 is TyTypeParameter && ty2 is TyTypeParameter && ty1 == ty2 -> true
ty1 is TyReference && ty2 is TyReference && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyPointer && ty2 is TyPointer && ty1.mutability == ty2.mutability -> {
combineTypes(ty1.referenced, ty2.referenced)
}
ty1 is TyArray && ty2 is TyArray &&
(ty1.size == null || ty2.size == null || ty1.size == ty2.size) -> combineTypes(ty1.base, ty2.base)
ty1 is TySlice && ty2 is TySlice -> combineTypes(ty1.elementType, ty2.elementType)
ty1 is TyTuple && ty2 is TyTuple -> combinePairs(ty1.types.zip(ty2.types))
ty1 is TyFunction && ty2 is TyFunction && ty1.paramTypes.size == ty2.paramTypes.size -> {
combinePairs(ty1.paramTypes.zip(ty2.paramTypes)) && combineTypes(ty1.retType, ty2.retType)
}
ty1 is TyAdt && ty2 is TyAdt && ty1.item == ty2.item -> {
combinePairs(ty1.typeArguments.zip(ty2.typeArguments))
}
ty1 is TyTraitObject && ty2 is TyTraitObject && ty1.trait == ty2.trait -> true
ty1 is TyAnon && ty2 is TyAnon && ty1.definition == ty2.definition -> true
ty1 is TyNever || ty2 is TyNever -> true
else -> false
}
}
fun combinePairs(pairs: List<Pair<Ty, Ty>>): Boolean {
var canUnify = true
for ((t1, t2) in pairs) {
canUnify = combineTypes(t1, t2) && canUnify
}
return canUnify
}
fun combineTraitRefs(ref1: TraitRef, ref2: TraitRef): Boolean =
ref1.trait.element == ref2.trait.element &&
combineTypes(ref1.selfTy, ref2.selfTy) &&
zipValues(ref1.trait.subst, ref2.trait.subst).all { (a, b) ->
combineTypes(a, b)
}
fun shallowResolve(ty: Ty): Ty {
if (ty !is TyInfer) return ty
return when (ty) {
is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: ty
is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: ty
is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(this::shallowResolve) ?: ty
}
}
fun <T : TypeFoldable<T>> resolveTypeVarsIfPossible(ty: T): T {
return ty.foldTyInferWith(this::shallowResolve)
}
private fun fullyResolve(ty: Ty): Ty {
fun go(ty: Ty): Ty {
if (ty !is TyInfer) return ty
return when (ty) {
is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: TyInteger.DEFAULT
is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: TyFloat.DEFAULT
is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(::go) ?: ty.origin ?: TyUnknown
}
}
return ty.foldTyInferWith(::go)
}
fun typeVarForParam(ty: TyTypeParameter): Ty {
return TyInfer.TyVar(ty)
}
/** Deeply normalize projection types. See [normalizeProjectionType] */
fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T, recursionDepth: Int = 0): TyWithObligations<T> {
val obligations = mutableListOf<Obligation>()
val normTy = ty.foldTyProjectionWith {
val normTy = normalizeProjectionType(it, recursionDepth)
obligations += normTy.obligations
normTy.value
}
return TyWithObligations(normTy, obligations)
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* If ambiguity arises, which implies that
* there are unresolved type variables in the projection, we will
* substitute a fresh type variable `$X` and generate a new
* obligation `<T as Trait>::Item == $X` for later.
*/
private fun normalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty> {
return optNormalizeProjectionType(projectionTy, recursionDepth) ?: run {
val tyVar = TyInfer.TyVar(projectionTy)
val obligation = Obligation(recursionDepth + 1, Predicate.Projection(projectionTy, tyVar))
TyWithObligations(tyVar, listOf(obligation))
}
}
/**
* Normalize a specific projection like `<T as Trait>::Item`.
* The result is always a type (and possibly additional obligations).
* Returns `null` in the case of ambiguity, which indicates that there
* are unbound type variables.
*/
fun optNormalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? =
optNormalizeProjectionTypeResolved(resolveTypeVarsIfPossible(projectionTy) as TyProjection, recursionDepth)
/** See [optNormalizeProjectionType] */
private fun optNormalizeProjectionTypeResolved(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? {
if (projectionTy.type is TyInfer) return null
val cacheResult = projectionCache.tryStart(projectionTy)
return when (cacheResult) {
ProjectionCacheEntry.Ambiguous -> {
// If we found ambiguity the last time, that generally
// means we will continue to do so until some type in the
// key changes (and we know it hasn't, because we just
// fully resolved it).
// TODO rustc has an exception for closure types here
null
}
ProjectionCacheEntry.InProgress -> {
// While normalized A::B we are asked to normalize A::B.
// TODO rustc halts the compilation immediately (panics) here
TyWithObligations(TyUnknown)
}
ProjectionCacheEntry.Error -> {
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is ProjectionCacheEntry.NormalizedTy -> {
var ty = cacheResult.ty
// If we find the value in the cache, then return it along
// with the obligations that went along with it. Note
// that, when using a fulfillment context, these
// obligations could in principle be ignored: they have
// already been registered when the cache entry was
// created (and hence the new ones will quickly be
// discarded as duplicated). But when doing trait
// evaluation this is not the case.
// (See rustc's https://github.com/rust-lang/rust/issues/43132 )
if (!hasUnresolvedTypeVars(ty.value)) {
// Once we have inferred everything we need to know, we
// can ignore the `obligations` from that point on.
ty = TyWithObligations(ty.value)
projectionCache.putTy(projectionTy, ty)
}
ty
}
null -> {
val selResult = lookup.selectProjection(projectionTy, recursionDepth)
when (selResult) {
is SelectionResult.Ok -> {
val result = selResult.result ?: TyWithObligations(projectionTy)
projectionCache.putTy(projectionTy, pruneCacheValueObligations(result))
result
}
is SelectionResult.Err -> {
projectionCache.error(projectionTy)
// TODO report an error. See rustc's `normalize_to_error`
TyWithObligations(TyUnknown)
}
is SelectionResult.Ambiguous -> {
projectionCache.ambiguous(projectionTy)
null
}
}
}
}
}
/**
* If there are unresolved type variables, then we need to include
* any subobligations that bind them, at least until those type
* variables are fully resolved.
*/
private fun pruneCacheValueObligations(ty: TyWithObligations<Ty>): TyWithObligations<Ty> {
if (!hasUnresolvedTypeVars(ty.value)) return TyWithObligations(ty.value)
// I don't completely understand why we leave the only projection
// predicates here, but here is the comment from rustc about it
//
// If we found a `T: Foo<X = U>` predicate, let's check
// if `U` references any unresolved type
// variables. In principle, we only care if this
// projection can help resolve any of the type
// variables found in `result.value` -- but we just
// check for any type variables here, for fear of
// indirect obligations (e.g., we project to `?0`,
// but we have `T: Foo<X = ?1>` and `?1: Bar<X =
// ?0>`).
//
// We are only interested in `T: Foo<X = U>` predicates, where
// `U` references one of `unresolved_type_vars`.
val obligations = ty.obligations
.filter { it.predicate is Predicate.Projection && hasUnresolvedTypeVars(it.predicate) }
return TyWithObligations(ty.value, obligations)
}
private fun <T : TypeFoldable<T>> hasUnresolvedTypeVars(_ty: T): Boolean = _ty.visitWith(object : TypeVisitor {
override fun invoke(_ty: Ty): Boolean {
val ty = shallowResolve(_ty)
return when {
ty is TyInfer -> true
!ty.hasTyInfer -> false
else -> ty.superVisitWith(this)
}
}
})
fun instantiateBounds(
bounds: List<TraitRef>,
subst: Map<TyTypeParameter, Ty> = emptySubstitution,
recursionDepth: Int = 0
): Sequence<Obligation> {
return bounds.asSequence()
.map { it.substitute(subst) }
.map { normalizeAssociatedTypesIn(it, recursionDepth) }
.flatMap { it.obligations.asSequence() + Obligation(recursionDepth, Predicate.Trait(it.value)) }
}
override fun toString(): String {
return "RsInferenceContext(bindings=$bindings, exprTypes=$exprTypes)"
}
}
private class RsFnInferenceContext(
private val ctx: RsInferenceContext,
private val returnTy: Ty
) {
private val lookup get() = ctx.lookup
private val items get() = ctx.items
private val fulfill get() = ctx.fulfill
private val RsStructLiteralField.type: Ty get() = resolveToDeclaration?.typeReference?.type ?: TyUnknown
private fun resolveTypeVarsWithObligations(ty: Ty): Ty {
if (!ty.hasTyInfer) return ty
val tyRes = ctx.resolveTypeVarsIfPossible(ty)
if (!tyRes.hasTyInfer) return tyRes
selectObligationsWherePossible()
return ctx.resolveTypeVarsIfPossible(tyRes)
}
fun selectObligationsWherePossible() {
fulfill.selectWherePossible()
}
fun inferFnBody(block: RsBlock): Ty =
block.inferTypeCoercableTo(returnTy)
fun inferLambdaBody(expr: RsExpr): Ty =
if (expr is RsBlockExpr) {
// skipping diverging procession for lambda body
ctx.writeExprTy(expr, returnTy)
inferFnBody(expr.block)
} else {
expr.inferTypeCoercableTo(returnTy)
}
private fun RsBlock.inferTypeCoercableTo(expected: Ty): Ty =
inferType(expected, true)
private fun RsBlock.inferType(expected: Ty? = null, coerce: Boolean = false): Ty {
var isDiverging = false
for (stmt in stmtList) {
isDiverging = processStatement(stmt) || isDiverging
}
val type = (if (coerce) expr?.inferTypeCoercableTo(expected!!) else expr?.inferType(expected)) ?: TyUnit
return if (isDiverging) TyNever else type
}
// returns true if expr is always diverging
private fun processStatement(psi: RsStmt): Boolean = when (psi) {
is RsLetDecl -> {
val explicitTy = psi.typeReference?.type
?.let { normalizeAssociatedTypesIn(it) }
val inferredTy = explicitTy
?.let { psi.expr?.inferTypeCoercableTo(it) }
?: psi.expr?.inferType()
?: TyInfer.TyVar()
psi.pat?.extractBindings(explicitTy ?: resolveTypeVarsWithObligations(inferredTy))
inferredTy == TyNever
}
is RsExprStmt -> psi.expr.inferType() == TyNever
else -> false
}
private fun RsExpr.inferType(expected: Ty? = null): Ty {
if (ctx.isTypeInferred(this)) error("Trying to infer expression type twice")
val ty = when (this) {
is RsPathExpr -> inferPathExprType(this)
is RsStructLiteral -> inferStructLiteralType(this, expected)
is RsTupleExpr -> inferRsTupleExprType(this, expected)
is RsParenExpr -> this.expr.inferType(expected)
is RsUnitExpr -> TyUnit
is RsCastExpr -> inferCastExprType(this)
is RsCallExpr -> inferCallExprType(this, expected)
is RsDotExpr -> inferDotExprType(this, expected)
is RsLitExpr -> inferLitExprType(this, expected)
is RsBlockExpr -> this.block.inferType(expected)
is RsIfExpr -> inferIfExprType(this, expected)
is RsLoopExpr -> inferLoopExprType(this)
is RsWhileExpr -> inferWhileExprType(this)
is RsForExpr -> inferForExprType(this)
is RsMatchExpr -> inferMatchExprType(this, expected)
is RsUnaryExpr -> inferUnaryExprType(this, expected)
is RsBinaryExpr -> inferBinaryExprType(this)
is RsTryExpr -> inferTryExprType(this, expected)
is RsArrayExpr -> inferArrayType(this, expected)
is RsRangeExpr -> inferRangeType(this)
is RsIndexExpr -> inferIndexExprType(this)
is RsMacroExpr -> inferMacroExprType(this)
is RsLambdaExpr -> inferLambdaExprType(this, expected)
is RsRetExpr -> inferRetExprType(this)
is RsBreakExpr -> inferBreakExprType(this)
is RsContExpr -> TyNever
else -> TyUnknown
}
ctx.writeExprTy(this, ty)
return ty
}
private fun RsExpr.inferTypeCoercableTo(expected: Ty): Ty {
val inferred = inferType(expected)
coerce(this, inferred, expected)
return inferred
}
private fun coerce(expr: RsExpr, inferred: Ty, expected: Ty) {
coerceResolved(expr, resolveTypeVarsWithObligations(inferred), resolveTypeVarsWithObligations(expected))
}
private fun coerceResolved(expr: RsExpr, inferred: Ty, expected: Ty) {
val ok = tryCoerce(inferred, expected)
if (!ok) {
// ignoring possible false-positives (it's only basic experimental type checking)
val ignoredTys = listOf(
TyUnknown::class.java,
TyInfer.TyVar::class.java,
TyTypeParameter::class.java,
TyTraitObject::class.java
)
if (!expected.containsTyOfClass(ignoredTys) && !inferred.containsTyOfClass(ignoredTys)) {
// another awful hack: check that inner expressions did not annotated as an error
// to disallow annotation intersections. This should be done in a different way
fun PsiElement.isChildOf(psi: PsiElement) = this.ancestors.contains(psi)
if (ctx.diagnostics.all { !it.element.isChildOf(expr) }) {
ctx.reportTypeMismatch(expr, expected, inferred)
}
}
}
}
private fun tryCoerce(inferred: Ty, expected: Ty): Boolean {
return when {
// Coerce array to slice
inferred is TyReference && inferred.referenced is TyArray &&
expected is TyReference && expected.referenced is TySlice -> {
ctx.combineTypes(inferred.referenced.base, expected.referenced.elementType)
}
// Coerce reference to pointer
inferred is TyReference && expected is TyPointer &&
coerceMutability(inferred.mutability, expected.mutability) -> {
ctx.combineTypes(inferred.referenced, expected.referenced)
}
// Coerce mutable pointer to const pointer
inferred is TyPointer && inferred.mutability.isMut
&& expected is TyPointer && !expected.mutability.isMut -> {
ctx.combineTypes(inferred.referenced, expected.referenced)
}
// Coerce references
inferred is TyReference && expected is TyReference &&
coerceMutability(inferred.mutability, expected.mutability) -> {
coerceReference(inferred, expected)
}
// TODO trait object unsizing
else -> ctx.combineTypes(inferred, expected)
}
}
private fun coerceMutability(from: Mutability, to: Mutability): Boolean =
from == to || from.isMut && !to.isMut
/**
* Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`.
* To match `A` with `B`, autoderef will be performed
*/
private fun coerceReference(inferred: TyReference, expected: TyReference): Boolean {
for (derefTy in lookup.coercionSequence(inferred).drop(1)) {
val derefTyRef = TyReference(derefTy, expected.mutability)
if (ctx.combineTypesIfOk(derefTyRef, expected)) return true
}
return false
}
fun inferLitExprType(expr: RsLitExpr, expected: Ty?): Ty {
val stubType = expr.stubType
return when (stubType) {
is RsStubLiteralType.Boolean -> TyBool
is RsStubLiteralType.Char -> if (stubType.isByte) TyInteger.U8 else TyChar
is RsStubLiteralType.String -> {
if (stubType.isByte) {
TyReference(TyArray(TyInteger.U8, stubType.length), IMMUTABLE)
} else {
TyReference(TyStr, IMMUTABLE)
}
}
is RsStubLiteralType.Integer -> {
val ty = stubType.kind
ty ?: when (expected) {
is TyInteger -> expected
TyChar -> TyInteger.U8
is TyPointer, is TyFunction -> TyInteger.USize
else -> TyInfer.IntVar()
}
}
is RsStubLiteralType.Float -> {
val ty = stubType.kind
ty ?: (expected?.takeIf { it is TyFloat } ?: TyInfer.FloatVar())
}
null -> TyUnknown
}
}
private fun inferPathExprType(expr: RsPathExpr): Ty {
val variants = resolvePath(expr.path, lookup).mapNotNull { it.downcast<RsNamedElement>() }
ctx.writePath(expr, variants)
val qualifier = expr.path.path
if (variants.size > 1 && qualifier != null) {
val resolved = collapseToTrait(variants.map { it.element })
if (resolved != null) {
// TODO remap subst
return instantiatePath(BoundElement(resolved, variants.first().subst), expr, tryRefinePath = true)
}
}
val first = variants.firstOrNull() ?: return TyUnknown
return instantiatePath(first, expr, tryRefinePath = variants.size == 1)
}
/** This works for `String::from` where multiple impls of `From` trait found for `String` */
private fun collapseToTrait(elements: List<RsNamedElement>): RsFunction? {
if (elements.size <= 1) return null
val traits = elements.mapNotNull {
val owner = (it as? RsFunction)?.owner
when (owner) {
is RsAbstractableOwner.Impl -> owner.impl.traitRef?.resolveToTrait
is RsAbstractableOwner.Trait -> owner.trait
else -> null
}
}
if (traits.size == elements.size && traits.toSet().size == 1) {
val fnName = elements.first().name
val trait = traits.first()
return trait.members?.functionList?.find { it.name == fnName } ?: return null
}
return null
}
private fun instantiatePath(
boundElement: BoundElement<RsNamedElement>,
pathExpr: RsPathExpr? = null,
tryRefinePath: Boolean = false
): Ty {
val (element, subst) = boundElement
val type = when (element) {
is RsPatBinding -> ctx.getBindingType(element)
is RsTypeDeclarationElement -> element.declaredType
is RsEnumVariant -> element.parentEnum.declaredType
is RsFunction -> element.typeOfValue
is RsConstant -> element.typeReference?.type ?: TyUnknown
is RsSelfParameter -> element.typeOfValue
else -> return TyUnknown
}
val typeParameters = when (element) {
is RsFunction -> {
val owner = element.owner
var (typeParameters, selfTy) = when (owner) {
is RsAbstractableOwner.Impl -> {
val typeParameters = instantiateBounds(owner.impl)
val selfTy = owner.impl.typeReference?.type?.substitute(typeParameters) ?: TyUnknown
subst[TyTypeParameter.self()]?.let { ctx.combineTypes(selfTy, it) }
typeParameters to selfTy
}
is RsAbstractableOwner.Trait -> {
val typeParameters = instantiateBounds(owner.trait)
// UFCS - add predicate `Self : Trait<Args>`
val selfTy = subst[TyTypeParameter.self()] ?: ctx.typeVarForParam(TyTypeParameter.self())
val boundTrait = BoundElement(owner.trait, owner.trait.generics.associateBy { it })
.substitute(typeParameters)
val traitRef = TraitRef(selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
if (pathExpr != null && tryRefinePath) ctx.registerPathRefinement(pathExpr, traitRef)
typeParameters to selfTy
}
else -> emptySubstitution to null
}
typeParameters = instantiateBounds(element, selfTy, typeParameters)
typeParameters
}
is RsEnumVariant -> instantiateBounds(element.parentEnum)
is RsGenericDeclaration -> instantiateBounds(element)
else -> emptySubstitution
}
unifySubst(subst, typeParameters)
val tupleFields = (element as? RsFieldsOwner)?.tupleFields
return if (tupleFields != null) {
// Treat tuple constructor as a function
TyFunction(tupleFields.tupleFieldDeclList.map { it.typeReference.type }, type)
} else {
type
}.substitute(typeParameters).foldWith(this::normalizeAssociatedTypesIn)
}
private fun instantiateBounds(
element: RsGenericDeclaration,
selfTy: Ty? = null,
typeParameters: Substitution = emptySubstitution
): Substitution {
val map = run {
val map = typeParameters + element.generics.associate { it to ctx.typeVarForParam(it) }
if (selfTy != null) {
map + (TyTypeParameter.self() to selfTy)
} else {
map
}
}
ctx.instantiateBounds(element.bounds, map).forEach(fulfill::registerPredicateObligation)
return map
}
private fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T): T {
val (normTy, obligations) = ctx.normalizeAssociatedTypesIn(ty)
obligations.forEach(fulfill::registerPredicateObligation)
return normTy
}
private fun unifySubst(subst1: Substitution, subst2: Substitution) {
subst1.forEach { (k, v1) ->
subst2[k]?.let { v2 ->
if (k != v1 && k != TyTypeParameter.self() && v1 !is TyTypeParameter && v1 !is TyUnknown) {
ctx.combineTypes(v2, v1)
}
}
}
}
private fun inferStructLiteralType(expr: RsStructLiteral, expected: Ty?): Ty {
val boundElement = expr.path.reference.advancedResolve()
if (boundElement == null) {
for (field in expr.structLiteralBody.structLiteralFieldList) {
field.expr?.inferType()
}
// Handle struct update syntax { ..expression }
expr.structLiteralBody.expr?.inferType()
return TyUnknown
}
var (element, subst) = boundElement
// Resolve potential type aliases
while (element is RsTypeAlias) {
val resolved = (element.typeReference?.typeElement as? RsBaseType)?.path?.reference?.advancedResolve()
element = resolved?.element ?: return TyUnknown
subst = resolved.subst.substituteInValues(subst)
}
val genericDecl: RsGenericDeclaration = when (element) {
is RsStructItem -> element
is RsEnumVariant -> element.parentEnum
else -> return TyUnknown
}
val typeParameters = instantiateBounds(genericDecl)
unifySubst(subst, typeParameters)
if (expected != null) unifySubst(typeParameters, expected.typeParameterValues)
val type = when (element) {
is RsStructItem -> element.declaredType
is RsEnumVariant -> element.parentEnum.declaredType
else -> TyUnknown
}.substitute(typeParameters)
inferStructTypeArguments(expr, typeParameters)
// Handle struct update syntax { ..expression }
expr.structLiteralBody.expr?.inferTypeCoercableTo(type)
return type
}
private fun inferStructTypeArguments(literal: RsStructLiteral, typeParameters: Substitution) {
literal.structLiteralBody.structLiteralFieldList.mapNotNull { field ->
field.expr?.let { expr ->
val fieldType = field.type
expr.inferTypeCoercableTo(fieldType.substitute(typeParameters))
}
}
}
private fun inferRsTupleExprType(expr: RsTupleExpr, expected: Ty?): Ty {
return TyTuple(inferExprList(expr.exprList, (expected as? TyTuple)?.types))
}
private fun inferExprList(exprs: List<RsExpr>, expected: List<Ty>?): List<Ty> {
val extended = expected.orEmpty().asSequence().infiniteWithTyUnknown()
return exprs.asSequence().zip(extended).map { (expr, ty) -> expr.inferTypeCoercableTo(ty) }.toList()
}
private fun inferCastExprType(expr: RsCastExpr): Ty {
expr.expr.inferType()
return expr.typeReference.type
}
private fun inferCallExprType(expr: RsCallExpr, expected: Ty?): Ty {
val ty = resolveTypeVarsWithObligations(expr.expr.inferType()) // or error
val argExprs = expr.valueArgumentList.exprList
// `struct S; S();`
if (ty is TyAdt && argExprs.isEmpty()) return ty
val calleeType = lookup.asTyFunction(ty)?.register() ?: unknownTyFunction(argExprs.size)
if (expected != null) ctx.combineTypes(expected, calleeType.retType)
inferArgumentTypes(calleeType.paramTypes, argExprs)
return calleeType.retType
}
private fun inferMethodCallExprType(receiver: Ty, methodCall: RsMethodCall, expected: Ty?): Ty {
val argExprs = methodCall.valueArgumentList.exprList
val callee = run {
val variants = resolveMethodCallReferenceWithReceiverType(lookup, receiver, methodCall)
val callee = pickSingleMethod(variants, methodCall)
// If we failed to resolve ambiguity just write the all possible methods
val variantsForDisplay = (callee?.let(::listOf) ?: variants).map { it.element }
ctx.writeResolvedMethod(methodCall, variantsForDisplay)
callee ?: variants.firstOrNull()
}
if (callee == null) {
val methodType = unknownTyFunction(argExprs.size)
inferArgumentTypes(methodType.paramTypes, argExprs)
return methodType.retType
}
val impl = callee.impl
var typeParameters = if (impl != null) {
val typeParameters = instantiateBounds(impl)
impl.typeReference?.type?.substitute(typeParameters)?.let { ctx.combineTypes(callee.selfTy, it) }
if (callee.element.owner is RsAbstractableOwner.Trait) {
impl.traitRef?.resolveToBoundTrait?.substitute(typeParameters)?.subst ?: emptySubstitution
} else {
typeParameters
}
} else {
// Method has been resolved to a trait, so we should add a predicate
// `Self : Trait<Args>` to select args and also refine method path if possible.
// Method path refinement needed if there are multiple impls of the same trait to the same type
val trait = (callee.element.owner as RsAbstractableOwner.Trait).trait
when (callee.selfTy) {
// All these branches except `else` are optimization, they can be removed without loss of functionality
is TyTypeParameter -> callee.selfTy.getTraitBoundsTransitively()
.find { it.element == trait }?.subst ?: emptySubstitution
is TyAnon -> callee.selfTy.getTraitBoundsTransitively()
.find { it.element == trait }?.subst ?: emptySubstitution
is TyTraitObject -> callee.selfTy.trait.flattenHierarchy
.find { it.element == trait }?.subst ?: emptySubstitution
else -> {
val typeParameters = instantiateBounds(trait)
val boundTrait = BoundElement(trait, trait.generics.associateBy { it })
.substitute(typeParameters)
val traitRef = TraitRef(callee.selfTy, boundTrait)
fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef)))
ctx.registerMethodRefinement(methodCall, traitRef)
typeParameters
}
}
}
typeParameters = instantiateBounds(callee.element, callee.selfTy, typeParameters)
val fnSubst = run {
val typeArguments = methodCall.typeArgumentList?.typeReferenceList.orEmpty().map { it.type }
if (typeArguments.isEmpty()) {
emptySubstitution
} else {
val parameters = callee.element.typeParameterList?.typeParameterList.orEmpty()
.map { TyTypeParameter.named(it) }
parameters.zip(typeArguments).toMap()
}
}
unifySubst(fnSubst, typeParameters)
val methodType = (callee.element.typeOfValue)
.substitute(typeParameters)
.foldWith(this::normalizeAssociatedTypesIn) as TyFunction
if (expected != null) ctx.combineTypes(expected, methodType.retType)
// drop first element of paramTypes because it's `self` param
// and it doesn't have value in `methodCall.valueArgumentList.exprList`
inferArgumentTypes(methodType.paramTypes.drop(1), argExprs)
return methodType.retType
}
private fun pickSingleMethod(variants: List<MethodCallee>, methodCall: RsMethodCall): MethodCallee? {
val filtered = variants.singleOrFilter {
// 1. filter traits that are not imported
TypeInferenceMarks.methodPickTraitScope.hit()
val trait = it.impl?.traitRef?.path?.reference?.resolve() as? RsTraitItem ?: return@singleOrFilter true
lookup.isTraitVisibleFrom(trait, methodCall)
}.singleOrFilter { callee ->
// 2. Filter methods by trait bounds (try to select all obligations for each impl)
TypeInferenceMarks.methodPickCheckBounds.hit()
val impl = callee.impl ?: return@singleOrFilter true
val ff = FulfillmentContext(ctx, lookup)
val typeParameters = impl.generics.associate { it to ctx.typeVarForParam(it) }
ctx.instantiateBounds(impl.bounds, typeParameters)
.forEach(ff::registerPredicateObligation)
impl.typeReference?.type?.substitute(typeParameters)?.let { ctx.combineTypes(callee.selfTy, it) }
ctx.probe { ff.selectUntilError() }
}.singleOrLet { list ->
// 3. Pick results on the first deref level
// TODO this is not how compiler actually work, see `test non inherent impl 2`
TypeInferenceMarks.methodPickDerefOrder.hit()
val first = list.first()
list.takeWhile { it.derefCount == first.derefCount }
}
return when (filtered.size) {
0 -> null
1 -> filtered.single()
else -> {
// 4. Try to collapse multiple resolved methods of the same trait, e.g.
// ```rust
// trait Foo<T> { fn foo(&self, _: T) {} }
// impl Foo<Bar> for S { fn foo(&self, _: Bar) {} }
// impl Foo<Baz> for S { fn foo(&self, _: Baz) {} }
// ```
// In this case we `filtered` list contains 2 function defined in 2 impls.
// We want to collapse them to the single function defined in the trait.
// Specific impl will be selected later according to the method parameter type.
val first = filtered.first()
collapseToTrait(filtered.map { it.element })?.let {
TypeInferenceMarks.methodPickCollapseTraits.hit()
MethodCallee(first.name, it, null, first.selfTy, first.derefCount)
}
}
}
}
private fun unknownTyFunction(arity: Int): TyFunction =
TyFunction(generateSequence { TyUnknown }.take(arity).toList(), TyUnknown)
private fun inferArgumentTypes(argDefs: List<Ty>, argExprs: List<RsExpr>) {
// We do this just like rustc, and comments copied from rustc too
// We do this in a pretty awful way: first we typecheck any arguments
// that are not closures, then we typecheck the closures. This is so
// that we have more information about the types of arguments when we
// typecheck the functions.
for (checkLambdas in booleanArrayOf(false, true)) {
// More awful hacks: before we check argument types, try to do
// an "opportunistic" vtable resolution of any trait bounds on
// the call. This helps coercions.
if (checkLambdas) {
selectObligationsWherePossible()
}
// extending argument definitions to be sure that type inference launched for each arg expr
val argDefsExt = argDefs.asSequence().infiniteWithTyUnknown()
for ((type, expr) in argDefsExt.zip(argExprs.asSequence().map(::unwrapParenExprs))) {
val isLambda = expr is RsLambdaExpr
if (isLambda != checkLambdas) continue
expr.inferTypeCoercableTo(type)
}
}
}
private fun inferFieldExprType(receiver: Ty, fieldLookup: RsFieldLookup): Ty {
val variants = resolveFieldLookupReferenceWithReceiverType(lookup, receiver, fieldLookup)
ctx.writeResolvedField(fieldLookup, variants)
val field = variants.firstOrNull()
if (field == null) {
for (type in lookup.coercionSequence(receiver)) {
if (type is TyTuple) {
val fieldIndex = fieldLookup.integerLiteral?.text?.toIntOrNull() ?: return TyUnknown
return type.types.getOrElse(fieldIndex) { TyUnknown }
}
}
return TyUnknown
}
val raw = when (field) {
is RsFieldDecl -> field.typeReference?.type
is RsTupleFieldDecl -> field.typeReference.type
else -> null
} ?: TyUnknown
return raw.substitute(receiver.typeParameterValues)
}
private fun inferDotExprType(expr: RsDotExpr, expected: Ty?): Ty {
val receiver = resolveTypeVarsWithObligations(expr.expr.inferType())
val methodCall = expr.methodCall
val fieldLookup = expr.fieldLookup
return when {
methodCall != null -> inferMethodCallExprType(receiver, methodCall, expected)
fieldLookup != null -> inferFieldExprType(receiver, fieldLookup)
else -> TyUnknown
}
}
private fun inferLoopExprType(expr: RsLoopExpr): Ty {
expr.block?.inferType()
val returningTypes = mutableListOf<Ty>()
val label = expr.labelDecl?.name
fun collectReturningTypes(element: PsiElement, matchOnlyByLabel: Boolean) {
element.forEachChild { child ->
when (child) {
is RsBreakExpr -> {
collectReturningTypes(child, matchOnlyByLabel)
if (!matchOnlyByLabel && child.label == null || child.label?.referenceName == label) {
returningTypes += child.expr?.let(ctx::getExprType) ?: TyUnit
}
}
is RsLabeledExpression -> {
if (label != null) {
collectReturningTypes(child, true)
}
}
else -> collectReturningTypes(child, matchOnlyByLabel)
}
}
}
collectReturningTypes(expr, false)
return if (returningTypes.isEmpty()) TyNever else getMoreCompleteType(returningTypes)
}
private fun inferForExprType(expr: RsForExpr): Ty {
val exprTy = expr.expr?.inferType() ?: TyUnknown
expr.pat?.extractBindings(lookup.findIteratorItemType(exprTy)?.register() ?: TyUnknown)
expr.block?.inferType()
return TyUnit
}
private fun inferWhileExprType(expr: RsWhileExpr): Ty {
expr.condition?.let { it.pat?.extractBindings(it.expr.inferType()) ?: it.expr.inferType(TyBool) }
expr.block?.inferType()
return TyUnit
}
private fun inferMatchExprType(expr: RsMatchExpr, expected: Ty?): Ty {
val matchingExprTy = resolveTypeVarsWithObligations(expr.expr?.inferType() ?: TyUnknown)
val arms = expr.matchBody?.matchArmList.orEmpty()
for (arm in arms) {
for (pat in arm.patList) {
pat.extractBindings(matchingExprTy)
}
arm.expr?.inferType(expected)
arm.matchArmGuard?.expr?.inferType(TyBool)
}
return getMoreCompleteType(arms.mapNotNull { it.expr?.let(ctx::getExprType) })
}
private fun inferUnaryExprType(expr: RsUnaryExpr, expected: Ty?): Ty {
val innerExpr = expr.expr ?: return TyUnknown
return when (expr.operatorType) {
UnaryOperator.REF -> inferRefType(innerExpr, expected, IMMUTABLE)
UnaryOperator.REF_MUT -> inferRefType(innerExpr, expected, MUTABLE)
UnaryOperator.DEREF -> {
// expectation must NOT be used for deref
val base = innerExpr.inferType()
val deref = lookup.deref(base)
// TODO if (deref == null) emit E0614
deref ?: TyUnknown
}
UnaryOperator.MINUS -> innerExpr.inferType(expected)
UnaryOperator.NOT -> innerExpr.inferType(expected)
UnaryOperator.BOX -> {
innerExpr.inferType()
TyUnknown
}
}
}
private fun inferRefType(expr: RsExpr, expected: Ty?, mutable: Mutability): Ty =
TyReference(expr.inferType((expected as? TyReference)?.referenced), mutable)
private fun inferIfExprType(expr: RsIfExpr, expected: Ty?): Ty {
expr.condition?.let { it.pat?.extractBindings(it.expr.inferType()) ?: it.expr.inferType(TyBool) }
val blockTys = mutableListOf<Ty?>()
blockTys.add(expr.block?.inferType(expected))
val elseBranch = expr.elseBranch
if (elseBranch != null) {
blockTys.add(elseBranch.ifExpr?.inferType(expected))
blockTys.add(elseBranch.block?.inferType(expected))
}
return if (expr.elseBranch == null) TyUnit else getMoreCompleteType(blockTys.filterNotNull())
}
private fun inferBinaryExprType(expr: RsBinaryExpr): Ty {
val op = expr.operatorType
return when (op) {
is BoolOp -> {
expr.left.inferType()
expr.right?.inferType()
TyBool
}
is ArithmeticOp -> {
val lhsType = expr.left.inferType()
val rhsType = expr.right?.inferType() ?: TyUnknown
lookup.findArithmeticBinaryExprOutputType(lhsType, rhsType, op)?.register() ?: TyUnknown
}
is AssignmentOp -> {
val lhsType = expr.left.inferType()
expr.right?.inferTypeCoercableTo(lhsType)
TyUnit
}
}
}
private fun inferTryExprType(expr: RsTryExpr, expected: Ty?): Ty =
inferTryExprOrMacroType(expr.expr, expected, allowOption = true)
private fun inferTryExprOrMacroType(arg: RsExpr, expected: Ty?, allowOption: Boolean): Ty {
val base = arg.inferType(expected) as? TyAdt ?: return TyUnknown
//TODO: make it work with generic `std::ops::Try` trait
if (base.item == items.findResultItem() || (allowOption && base.item == items.findOptionItem())) {
TypeInferenceMarks.questionOperator.hit()
return base.typeArguments.firstOrNull() ?: TyUnknown
}
return TyUnknown
}
private fun inferRangeType(expr: RsRangeExpr): Ty {
val el = expr.exprList
val dot2 = expr.dotdot
val dot3 = expr.dotdotdot
val (rangeName, indexType) = when {
dot2 != null && el.size == 0 -> "RangeFull" to null
dot2 != null && el.size == 1 -> {
val e = el[0]
if (e.startOffsetInParent < dot2.startOffsetInParent) {
"RangeFrom" to e.inferType()
} else {
"RangeTo" to e.inferType()
}
}
dot2 != null && el.size == 2 -> {
"Range" to getMoreCompleteType(el[0].inferType(), el[1].inferType())
}
dot3 != null && el.size == 1 -> {
val e = el[0]
if (e.startOffsetInParent < dot3.startOffsetInParent) {
return TyUnknown
} else {
"RangeToInclusive" to e.inferType()
}
}
dot3 != null && el.size == 2 -> {
"RangeInclusive" to getMoreCompleteType(el[0].inferType(), el[1].inferType())
}
else -> error("Unrecognized range expression")
}
return items.findRangeTy(rangeName, indexType)
}
private fun inferIndexExprType(expr: RsIndexExpr): Ty {
val containerType = expr.containerExpr?.inferType() ?: return TyUnknown
val indexType = expr.indexExpr?.inferType() ?: return TyUnknown
return lookup.coercionSequence(containerType)
.mapNotNull { type -> lookup.findIndexOutputType(type, indexType) }
.firstOrNull()
?.register()
?: TyUnknown
}
private fun inferMacroExprType(expr: RsMacroExpr): Ty {
val tryArg = expr.macroCall.tryMacroArgument
if (tryArg != null) {
// See RsTryExpr where we handle the ? expression in a similar way
return inferTryExprOrMacroType(tryArg.expr, null, allowOption = false)
}
inferChildExprsRecursively(expr.macroCall)
val vecArg = expr.macroCall.vecMacroArgument
if (vecArg != null) {
val elementTypes = vecArg.exprList.map { ctx.getExprType(it) }
val elementType = getMoreCompleteType(elementTypes)
return items.findVecForElementTy(elementType)
}
val name = expr.macroCall.macroName
return when {
"print" in name || "assert" in name -> TyUnit
name == "format" -> items.findStringTy()
name == "format_args" -> items.findArgumentsTy()
name == "unimplemented" || name == "unreachable" || name == "panic" -> TyNever
expr.macroCall.formatMacroArgument != null || expr.macroCall.logMacroArgument != null -> TyUnit
else -> TyUnknown
}
}
private fun inferChildExprsRecursively(psi: PsiElement) {
when (psi) {
is RsExpr -> psi.inferType()
else -> psi.forEachChild(this::inferChildExprsRecursively)
}
}
private fun inferLambdaExprType(expr: RsLambdaExpr, expected: Ty?): Ty {
val params = expr.valueParameterList.valueParameterList
val expectedFnTy = expected
?.let(this::deduceLambdaType)
?: unknownTyFunction(params.size)
val extendedArgs = expectedFnTy.paramTypes.asSequence().infiniteWithTyUnknown()
val paramTypes = extendedArgs.zip(params.asSequence()).map { (expectedArg, actualArg) ->
val paramTy = actualArg.typeReference?.type ?: expectedArg
actualArg.pat?.extractBindings(paramTy)
paramTy
}.toList()
val retTy = expr.retType?.typeReference?.type
?: expectedFnTy.retType.takeIf { it != TyUnknown }
?: TyInfer.TyVar()
expr.expr?.let { RsFnInferenceContext(ctx, retTy).inferLambdaBody(it) }
return TyFunction(paramTypes, retTy)
}
private fun deduceLambdaType(expected: Ty): TyFunction? {
return when (expected) {
is TyInfer.TyVar -> {
fulfill.pendingObligations
.mapNotNull { it.obligation.predicate as? Predicate.Trait }
.find { it.trait.selfTy == expected }
?.let { lookup.asTyFunction(it.trait.trait) }
}
is TyReference -> {
if (expected.referenced is TyTraitObject) {
null // TODO
} else {
null
}
}
is TyFunction -> expected
else -> null
}
}
private fun inferArrayType(expr: RsArrayExpr, expected: Ty?): Ty {
val expectedElemTy = when (expected) {
is TyArray -> expected.base
is TySlice -> expected.elementType
else -> null
}
val (elementType, size) = if (expr.semicolon != null) {
// It is "repeat expr", e.g. `[1; 5]`
val elementType = expectedElemTy
?.let { expr.initializer?.inferTypeCoercableTo(expectedElemTy) }
?: expr.initializer?.inferType()
?: return TySlice(TyUnknown)
expr.sizeExpr?.inferType(TyInteger.USize)
val size = calculateArraySize(expr.sizeExpr) { ctx.getResolvedPaths(it).singleOrNull() }
elementType to size
} else {
val elementTypes = expr.arrayElements?.map { it.inferType(expectedElemTy) }
if (elementTypes.isNullOrEmpty()) return TySlice(TyUnknown)
// '!!' is safe here because we've just checked that elementTypes isn't null
val elementType = getMoreCompleteType(elementTypes!!)
if (expectedElemTy != null) tryCoerce(elementType, expectedElemTy)
elementType to elementTypes.size.toLong()
}
return TyArray(elementType, size)
}
private fun inferRetExprType(expr: RsRetExpr): Ty {
expr.expr?.inferTypeCoercableTo(returnTy)
return TyNever
}
private fun inferBreakExprType(expr: RsBreakExpr): Ty {
expr.expr?.inferType()
return TyNever
}
// TODO should be replaced with coerceMany
private fun getMoreCompleteType(types: List<Ty>): Ty {
if (types.isEmpty()) return TyUnknown
return types.reduce { acc, ty -> getMoreCompleteType(acc, ty) }
}
// TODO should be replaced with coerceMany
fun getMoreCompleteType(ty1: Ty, ty2: Ty): Ty = when (ty1) {
is TyNever -> ty2
is TyUnknown -> if (ty2 !is TyNever) ty2 else TyUnknown
else -> {
ctx.combineTypes(ty1, ty2)
ty1
}
}
fun <T> TyWithObligations<T>.register(): T {
obligations.forEach(fulfill::registerPredicateObligation)
return value
}
fun extractParameterBindings(fn: RsFunction) {
for (param in fn.valueParameters) {
param.pat?.extractBindings(param.typeReference?.type ?: TyUnknown)
}
}
private fun RsPat.extractBindings(type: Ty) {
when (this) {
is RsPatWild -> {}
is RsPatConst -> expr.inferTypeCoercableTo(type)
is RsPatRef -> pat.extractBindings((type as? TyReference)?.referenced ?: TyUnknown)
is RsPatRange -> patConstList.forEach { it.expr.inferTypeCoercableTo(type) }
is RsPatIdent -> {
val patBinding = patBinding
val bindingType = if (patBinding.isRef) TyReference(type, patBinding.mutability) else type
ctx.writeBindingTy(patBinding, bindingType)
pat?.extractBindings(type)
}
is RsPatTup -> {
val types = (type as? TyTuple)?.types.orEmpty()
for ((idx, p) in patList.withIndex()) {
p.extractBindings(types.getOrElse(idx, { TyUnknown }))
}
}
is RsPatEnum -> {
// the type might actually be either a tuple variant of enum, or a tuple struct.
val ref = path.reference.resolve()
val tupleFields = (ref as? RsFieldsOwner)?.tupleFields
?: ((type as? TyAdt)?.item as? RsStructItem)?.tupleFields
?: return
for ((idx, p) in patList.withIndex()) {
val fieldType = tupleFields.tupleFieldDeclList
.getOrNull(idx)
?.typeReference
?.type
?.substitute(type.typeParameterValues)
?: TyUnknown
p.extractBindings(fieldType)
}
}
is RsPatStruct -> {
val struct = path.reference.resolve() as? RsFieldsOwner
?: ((type as? TyAdt)?.item as? RsStructItem)
?: return
val structFields = struct.blockFields?.fieldDeclList?.associateBy { it.name }.orEmpty()
for (patField in patFieldList) {
val fieldPun = patField.patBinding
val fieldName = if (fieldPun != null) {
// Foo { bar }
fieldPun.identifier.text
} else {
patField.identifier?.text
?: error("`pat_field` may be either `pat_binding` or should contain identifier! ${patField.text}")
}
val fieldType = structFields[fieldName]
?.typeReference
?.type
?.substitute(type.typeParameterValues)
?: TyUnknown
patField.pat?.extractBindings(fieldType)
if (fieldPun != null) {
ctx.writeBindingTy(fieldPun, fieldType)
}
}
}
is RsPatVec -> {
val elementType = when (type) {
is TyArray -> type.base
is TySlice -> type.elementType
else -> TyUnknown
}
patList.forEach { it.extractBindings(elementType) }
}
else -> {
// not yet handled
}
}
}
}
private val RsSelfParameter.typeOfValue: Ty
get() {
val owner = parentFunction.owner
var selfType = when (owner) {
is RsAbstractableOwner.Impl -> owner.impl.selfType
is RsAbstractableOwner.Trait -> owner.trait.selfType
else -> return TyUnknown
}
if (isExplicitType) {
// self: Self, self: &Self, self: &mut Self, self: Box<Self>
val ty = this.typeReference?.type ?: TyUnknown
return ty.substitute(mapOf(TyTypeParameter.self() to selfType))
}
// self, &self, &mut self
if (isRef) {
selfType = TyReference(selfType, mutability)
}
return selfType
}
private val RsFunction.typeOfValue: TyFunction
get() {
val paramTypes = mutableListOf<Ty>()
val self = selfParameter
if (self != null) {
paramTypes += self.typeOfValue
}
paramTypes += valueParameters.map { it.typeReference?.type ?: TyUnknown }
return TyFunction(paramTypes, returnType)
}
val RsGenericDeclaration.generics: List<TyTypeParameter>
get() = typeParameters.map { TyTypeParameter.named(it) }
val RsGenericDeclaration.bounds: List<TraitRef>
get() = CachedValuesManager.getCachedValue(this, {
CachedValueProvider.Result.create(
doGetBounds(),
PsiModificationTracker.MODIFICATION_COUNT
)
})
private fun RsGenericDeclaration.doGetBounds(): List<TraitRef> {
val whereBounds = this.whereClause?.wherePredList.orEmpty().asSequence()
.flatMap {
val (element, subst) = (it.typeReference?.typeElement as? RsBaseType)?.path?.reference?.advancedResolve()
?: return@flatMap emptySequence<TraitRef>()
val selfTy = ((element as? RsTypeDeclarationElement)?.declaredType)
?.substitute(subst)
?: return@flatMap emptySequence<TraitRef>()
it.typeParamBounds?.polyboundList.toTraitRefs(selfTy)
}
return (typeParameters.asSequence().flatMap {
val selfTy = TyTypeParameter.named(it)
it.typeParamBounds?.polyboundList.toTraitRefs(selfTy)
} + whereBounds).toList()
}
private fun List<RsPolybound>?.toTraitRefs(selfTy: Ty): Sequence<TraitRef> = orEmpty().asSequence()
.mapNotNull { it.bound.traitRef?.resolveToBoundTrait }
.filter { !it.element.isSizedTrait }
.map { TraitRef(selfTy, it) }
private fun Sequence<Ty>.infiniteWithTyUnknown(): Sequence<Ty> =
this + generateSequence { TyUnknown }
private fun unwrapParenExprs(expr: RsExpr): RsExpr {
var child = expr
while (child is RsParenExpr) {
child = child.expr
}
return child
}
data class TyWithObligations<out T>(
val value: T,
val obligations: List<Obligation> = emptyList()
)
fun <T> TyWithObligations<T>.withObligations(addObligations: List<Obligation>) =
TyWithObligations(value, obligations + addObligations)
object TypeInferenceMarks {
val cyclicType = Testmark("cyclicType")
val questionOperator = Testmark("questionOperator")
val methodPickTraitScope = Testmark("methodPickTraitScope")
val methodPickCheckBounds = Testmark("methodPickCheckBounds")
val methodPickDerefOrder = Testmark("methodPickDerefOrder")
val methodPickCollapseTraits = Testmark("methodPickCollapseTraits")
val traitSelectionSpecialization = Testmark("traitSelectionSpecialization")
}
| mit | 31d8e741be4230296ee17bc596d3808b | 41.058161 | 126 | 0.602296 | 4.815682 | false | false | false | false |
moezbhatti/qksms | presentation/src/main/java/com/moez/QKSMS/feature/compose/editing/PhoneNumberPickerAdapter.kt | 3 | 3149 | /*
* Copyright (C) 2019 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.compose.editing
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkAdapter
import com.moez.QKSMS.common.base.QkViewHolder
import com.moez.QKSMS.common.util.extensions.forwardTouches
import com.moez.QKSMS.extensions.Optional
import com.moez.QKSMS.model.PhoneNumber
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.phone_number_list_item.*
import kotlinx.android.synthetic.main.radio_preference_view.*
import kotlinx.android.synthetic.main.radio_preference_view.view.*
import javax.inject.Inject
class PhoneNumberPickerAdapter @Inject constructor(
private val context: Context
) : QkAdapter<PhoneNumber>() {
val selectedItemChanges: Subject<Optional<Long>> = BehaviorSubject.create()
private var selectedItem: Long? = null
set(value) {
data.indexOfFirst { number -> number.id == field }.takeIf { it != -1 }?.run(::notifyItemChanged)
field = value
data.indexOfFirst { number -> number.id == field }.takeIf { it != -1 }?.run(::notifyItemChanged)
selectedItemChanges.onNext(Optional(value))
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.phone_number_list_item, parent, false)
return QkViewHolder(view).apply {
radioButton.forwardTouches(itemView)
view.setOnClickListener {
val phoneNumber = getItem(adapterPosition)
selectedItem = phoneNumber.id
}
}
}
override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val phoneNumber = getItem(position)
holder.number.radioButton.isChecked = phoneNumber.id == selectedItem
holder.number.titleView.text = phoneNumber.address
holder.number.summaryView.text = when (phoneNumber.isDefault) {
true -> context.getString(R.string.compose_number_picker_default, phoneNumber.type)
false -> phoneNumber.type
}
}
override fun onDatasetChanged() {
super.onDatasetChanged()
selectedItem = data.find { number -> number.isDefault }?.id ?: data.firstOrNull()?.id
}
}
| gpl-3.0 | bb6731bcf0423a8c6d51cc0ed0974015 | 38.3625 | 108 | 0.710384 | 4.367545 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2021/Day2.kt | 1 | 1146 | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
/**
* --- Day 2: Dive! ---
* https://adventofcode.com/2021/day/2
*/
class Day2 : Solver {
override fun solve(lines: List<String>): Result {
val instructions = lines.map { it.split(" ") }.map { Instr(it[0], it[1].toLong()) }
return resultFrom(calcA(instructions), calcB(instructions))
}
private fun calcA(instructions: List<Instr>): Long {
var horPos = 0L
var depth = 0L
for (i in instructions) {
if (i.instr == "forward") horPos += i.value
if (i.instr == "down") depth += i.value
if (i.instr == "up") depth -= i.value
}
return horPos * depth
}
private fun calcB(instructions: List<Instr>): Long {
var horPos = 0L
var depth = 0L
var aim = 0L
for (i in instructions) {
if (i.instr == "forward") {
horPos += i.value
depth += i.value * aim
}
if (i.instr == "down") aim += i.value
if (i.instr == "up") aim -= i.value
}
return horPos * depth
}
private data class Instr(val instr: String, val value: Long)
} | apache-2.0 | 110af3a79e3f3e727f4df9f45ca0d01e | 25.068182 | 87 | 0.594241 | 3.192201 | false | false | false | false |
daigotsu/kotlin-dev-proxy | src/main/kotlin/server/Server.kt | 1 | 3631 | package server
import org.apache.http.HttpResponse
import org.apache.http.client.fluent.Request
import org.apache.http.util.EntityUtils
import spark.Spark.delete
import spark.Spark.get
import spark.Spark.post
import spark.Spark.put
import spark.Spark.options
import spark.SparkBase.externalStaticFileLocation
import spark.SparkBase.port
import java.util.Arrays
import java.util.Properties
fun main(args: Array<String>) {
val settings = ServerSettings()
settings.printSettings()
// Server setup
externalStaticFileLocation(settings.getString("static.files.location"))
port(settings.getInt("server.port"))
val proxyPrefix = settings.getString("server.proxy") + "*"
fun url(req: spark.Request): String {
val proxyUrl = req.pathInfo().replace(settings.getString("server.proxy"), "")
return if (req.queryString() === null) proxyUrl else proxyUrl + "?" + req.queryString()
}
// Extensions for library
fun Request.addHeaders(req: spark.Request): Request {
req.headers().filter { it !== "Content-Length" }.forEach {
this.setHeader(it, req.headers(it))
}
return this
}
fun Request.addBody(req: spark.Request): Request {
return this.bodyByteArray(req.bodyAsBytes())
}
fun Request.go(): HttpResponse {
return this.execute().returnResponse()
}
fun HttpResponse.mapHeaders(res: spark.Response): HttpResponse {
this.getAllHeaders().forEach {
res.header(it.getName(), it.getValue())
}
return this
}
fun HttpResponse.mapStatus(res: spark.Response): HttpResponse {
res.status(this.getStatusLine().getStatusCode())
return this
}
fun HttpResponse.result(): String {
val entity = this.getEntity()
return if (entity === null) "" else String(EntityUtils.toByteArray(entity))
}
// Actually proxy
get(proxyPrefix, { req, res ->
Request.Get(url(req)).addHeaders(req)
.go()
.mapHeaders(res).mapStatus(res)
.result()
})
post(proxyPrefix, { req, res ->
Request.Post(url(req)).addHeaders(req).addBody(req)
.go()
.mapHeaders(res).mapStatus(res)
.result()
})
put(proxyPrefix, { req, res ->
Request.Put(url(req)).addHeaders(req).addBody(req)
.go()
.mapHeaders(res).mapStatus(res)
.result()
})
options(proxyPrefix, { req, res ->
Request.Options(url(req)).addHeaders(req).addBody(req)
.go()
.mapHeaders(res).mapStatus(res)
.result()
})
delete(proxyPrefix, { req, res ->
Request.Delete(url(req)).addHeaders(req)
.go()
.mapHeaders(res).mapStatus(res)
.result()
})
}
class ServerSettings {
val resources = Properties()
init {
Arrays.asList("/default.properties", "/custom.properties").forEach {
val url = resources.javaClass.getResource(it)
if (url === null) return@forEach
resources.javaClass.getResourceAsStream(it).use {
resources.load(it)
}
}
}
fun printSettings() {
resources.stringPropertyNames().forEach {
println("Property: '${it}' has value: '${resources.get(it)}'")
}
}
fun getString(key: String): String {
return resources.get(key)!! as String
}
fun getInt(key: String): Int {
return (resources.get(key)!! as String).toInt()
}
} | gpl-3.0 | 6be8821d68e439d1e522996ba665d942 | 26.515152 | 95 | 0.594877 | 4.197688 | false | false | false | false |
tommykw/ESOutline | app/src/main/java/tommy_kw/esoutline/ContentLoader.kt | 2 | 1075 | package tommy_kw.esoutline
import android.content.Context
import android.support.v4.content.AsyncTaskLoader
/**
* Created by tomita on 15/07/06.
*/
class ContentLoader(context: Context,
val mUrl: String,
val mClassName: String) : AsyncTaskLoader<List<DesingInfo>>(context) {
private var mList: List<DesingInfo>? = null
override fun loadInBackground(): List<DesingInfo>? {
return null
}
override fun onStartLoading() {
}
override fun onStopLoading() {
super.onStopLoading()
cancelLoad()
}
override fun deliverResult(data: List<DesingInfo>) {
if (isReset) {
return
}
if (mList != null) mList = null
mList = data
if (isStarted) {
super.deliverResult(data)
}
}
override fun onReset() {
super.onReset()
onStopLoading()
if (mList != null) {
mList = null
}
}
companion object {
private val TAG = ContentLoader::class.simpleName
}
}
| apache-2.0 | 4f9386c3d3f51bb300e4c55cf4a9f79d | 21.395833 | 90 | 0.573023 | 4.535865 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/sdk/add/PyAddExistingVirtualEnvPanel.kt | 4 | 2338 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.ui.FormBuilder
import com.jetbrains.python.sdk.*
import icons.PythonIcons
import java.awt.BorderLayout
import javax.swing.Icon
/**
* @author vlan
*/
class PyAddExistingVirtualEnvPanel(private val project: Project?,
private val existingSdks: List<Sdk>,
override var newProjectPath: String?) : PyAddSdkPanel() {
override val panelName = "Existing environment"
override val icon: Icon = PythonIcons.Python.Virtualenv
private val sdkComboBox = PySdkPathChoosingComboBox(detectVirtualEnvs(project, existingSdks)
.filterNot { it.isAssociatedWithAnotherProject(project) },
null)
private val makeSharedField = JBCheckBox("Make available to all projects")
init {
layout = BorderLayout()
val formPanel = FormBuilder.createFormBuilder()
.addLabeledComponent("Interpreter:", sdkComboBox)
.addComponent(makeSharedField)
.panel
add(formPanel, BorderLayout.NORTH)
}
override fun validateAll() =
listOf(validateSdkComboBox(sdkComboBox))
.filterNotNull()
override fun getOrCreateSdk(): Sdk? {
val sdk = sdkComboBox.selectedSdk
return when (sdk) {
is PyDetectedSdk -> sdk.setupAssociated(existingSdks, newProjectPath ?: project?.basePath)?.apply {
if (!makeSharedField.isSelected) {
associateWithProject(project, newProjectPath != null)
}
}
else -> sdk
}
}
} | apache-2.0 | 0ed90609a6760eedba68f8d5c926ef63 | 35.546875 | 114 | 0.685201 | 4.850622 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/codeInsight/implement/PyImplementMethodsHandler.kt | 6 | 1595 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.codeInsight.implement
import com.intellij.lang.LanguageCodeInsightActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.jetbrains.python.codeInsight.override.PyOverrideImplementUtil
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.types.TypeEvalContext
class PyImplementMethodsHandler : LanguageCodeInsightActionHandler {
override fun isValidFor(editor: Editor?, file: PsiFile?): Boolean {
return editor != null && file is PyFile && PyOverrideImplementUtil.getContextClass(editor, file) != null
}
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
val cls = PyOverrideImplementUtil.getContextClass(editor, file)
if (cls != null) {
PyOverrideImplementUtil.chooseAndImplementMethods(project, editor, cls, TypeEvalContext.codeCompletion(project, file))
}
}
override fun startInWriteAction() = false
} | apache-2.0 | e37bcea3a014ff64c4c88feecf79ab8d | 38.9 | 124 | 0.776176 | 4.253333 | false | false | false | false |
kacperkr90/kotlin-tutorial | src/v_builders/_36_ExtensionFunctionLiterals.kt | 2 | 550 | package v_builders
import util.TODO
import util.doc36
fun todoTask36(): Nothing = TODO(
"""
Task 36.
Read about extension function literals.
You can declare `isEven` and `isOdd` as values, that can be called as extension functions.
Complete the declarations below.
""",
documentation = doc36()
)
fun task36(): List<Boolean> {
val isEven: Int.() -> Boolean = { this % 2 == 0 }
val isOdd: Int.() -> Boolean = { !this.isEven() }
return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}
| mit | 2b3c84471f4907e2c24052981118dd74 | 21.916667 | 98 | 0.618182 | 3.928571 | false | false | false | false |
rei-m/android_hyakuninisshu | infrastructure/src/main/java/me/rei_m/hyakuninisshu/infrastructure/database/KarutaQuizSchema.kt | 1 | 1810 | /*
* Copyright (c) 2020. Rei Matsushita
*
* 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.
*/
/* ktlint-disable package-name */
package me.rei_m.hyakuninisshu.infrastructure.database
import com.github.gfx.android.orma.annotation.Column
import com.github.gfx.android.orma.annotation.PrimaryKey
import com.github.gfx.android.orma.annotation.Setter
import com.github.gfx.android.orma.annotation.Table
import java.util.Date
@Table
data class KarutaQuizSchema(
@Setter("id") @PrimaryKey(autoincrement = true) var id: Long = 0,
@Setter("quizId") @Column(indexed = true) var quizId: String,
@Setter("no") @Column var no: Int? = 0,
@Setter("collectId") @Column var collectId: Long,
@Setter("startDate") @Column var startDate: Date? = null,
@Setter("choiceNo") @Column var choiceNo: Int? = null,
@Setter("isCollect") @Column var isCollect: Boolean = false,
@Setter("answerTime") @Column var answerTime: Long? = 0
) {
fun getChoices(orma: OrmaDatabase): KarutaQuizChoiceSchema_Relation {
return orma.relationOfKarutaQuizChoiceSchema()
.karutaQuizSchemaEq(this)
.orderByOrderNoAsc()
}
companion object {
fun relation(orma: OrmaDatabase): KarutaQuizSchema_Relation {
return orma.relationOfKarutaQuizSchema()
}
}
}
| apache-2.0 | 96e95a45dabee003f8f7cd743eac9eb7 | 39.222222 | 112 | 0.718785 | 3.917749 | false | false | false | false |
rei-m/android_hyakuninisshu | feature/material/src/main/java/me/rei_m/hyakuninisshu/feature/material/ui/MaterialDetailPageFragment.kt | 1 | 2222 | /*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.feature.material.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import me.rei_m.hyakuninisshu.feature.material.databinding.MaterialDetailPageFragmentBinding
import me.rei_m.hyakuninisshu.state.material.model.Material
class MaterialDetailPageFragment : Fragment() {
private val args: MaterialDetailPageFragmentArgs by navArgs()
private var _binding: MaterialDetailPageFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = MaterialDetailPageFragmentBinding.inflate(inflater, container, false)
binding.lifecycleOwner = viewLifecycleOwner
// ここなくてもいいかも
val materialFromBundle = requireArguments().getParcelable<Material>(ARG_MATERIAL)
if (materialFromBundle == null) {
binding.material = args.material
} else {
binding.material = materialFromBundle
}
return binding.root
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
companion object {
private const val ARG_MATERIAL = "material"
fun newInstance(material: Material) = MaterialDetailPageFragment().apply {
arguments = Bundle().apply {
putParcelable(ARG_MATERIAL, material)
}
}
}
}
| apache-2.0 | 3dd06c2cfe85a8d8ecf8ac8b0f417392 | 33.952381 | 112 | 0.709809 | 4.735484 | false | false | false | false |
rock3r/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/PathMatchers.kt | 1 | 1303 | package io.gitlab.arturbosch.detekt.api.internal
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.psi.KtFile
import java.nio.file.FileSystem
import java.nio.file.FileSystems
import java.nio.file.PathMatcher
/**
* Converts given [pattern] into a [PathMatcher] specified by [FileSystem.getPathMatcher].
* We only support the "glob:" syntax to stay os independently.
* Internally a globbing pattern is transformed to a regex respecting the Windows file system.
*/
fun pathMatcher(pattern: String): PathMatcher {
val result = when (pattern.substringBefore(":")) {
"glob" -> pattern
"regex" -> throw IllegalArgumentException(USE_GLOB_MSG)
else -> "glob:$pattern"
}
return FileSystems.getDefault().getPathMatcher(result)
}
private const val USE_GLOB_MSG =
"Only globbing patterns are supported as they are treated os-independently by the PathMatcher api."
fun KtFile.absolutePath(): String =
getUserData(ABSOLUTE_PATH) ?: error("KtFile '$name' expected to have an absolute path.")
fun KtFile.relativePath(): String =
getUserData(RELATIVE_PATH) ?: error("KtFile '$name' expected to have an relative path.")
val RELATIVE_PATH: Key<String> = Key("relativePath")
val ABSOLUTE_PATH: Key<String> = Key("absolutePath")
| apache-2.0 | ee98699c66203356f627570cf1192547 | 36.228571 | 103 | 0.739064 | 4.136508 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/reviewer/ReviewerCustomFonts.kt | 1 | 5820 | /****************************************************************************************
* Copyright (c) 2013 Flavio Lerda <[email protected]> *
* *
* 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.ichi2.anki.reviewer
import android.content.Context
import android.text.TextUtils
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.AnkiFont
import com.ichi2.libanki.Utils
import com.ichi2.utils.HashUtil.HashMapInit
class ReviewerCustomFonts(context: Context) {
private val mCustomStyle: String
private var mDefaultFontStyle: String? = null
private var mOverrideFontStyle: String? = null
private var mDominantFontStyle: String? = null
fun updateCssStyle(cssStyle: StringBuilder) {
cssStyle.append(mCustomStyle)
}
/**
* Returns the CSS used to set the default font.
*
* @return the default font style, or the empty string if no default font is set
*/
private fun getDefaultFontStyle(context: Context, customFontsMap: Map<String?, AnkiFont>): String? {
if (mDefaultFontStyle == null) {
val preferences = AnkiDroidApp.getSharedPrefs(context)
val defaultFont = customFontsMap[preferences.getString("defaultFont", null)]
mDefaultFontStyle = if (defaultFont != null) {
"""BODY { ${defaultFont.getCSS(false)} }
"""
} else {
""
}
}
return mDefaultFontStyle
}
/**
* Returns the CSS used to set the override font.
*
* @return the override font style, or the empty string if no override font is set
*/
private fun getOverrideFontStyle(context: Context, customFontsMap: Map<String?, AnkiFont>): String? {
if (mOverrideFontStyle == null) {
val preferences = AnkiDroidApp.getSharedPrefs(context)
val defaultFont = customFontsMap[preferences.getString("defaultFont", null)]
val overrideFont = "1" == preferences.getString("overrideFontBehavior", "0")
mOverrideFontStyle = if (defaultFont != null && overrideFont) {
"""BODY, .card, * { ${defaultFont.getCSS(true)} }
"""
} else {
""
}
}
return mOverrideFontStyle
}
/**
* Returns the CSS that determines font choice in a global fashion.
*
* @return the font style, or the empty string if none applies
*/
private fun getDominantFontStyle(context: Context, customFontsMap: Map<String?, AnkiFont>): String? {
if (mDominantFontStyle == null) {
mDominantFontStyle = getOverrideFontStyle(context, customFontsMap)
if (TextUtils.isEmpty(mDominantFontStyle)) {
mDominantFontStyle = getDefaultFontStyle(context, customFontsMap)
if (TextUtils.isEmpty(mDominantFontStyle)) {
mDominantFontStyle = themeFontStyle
}
}
}
return mDominantFontStyle
}
companion object {
/**
* @return the CSS used to set the theme font.
*
* The font used to be variable
*/
private const val themeFontStyle = "BODY {font-family: 'OpenSans';font-weight: normal;font-style: normal;font-stretch: normal;}"
/**
* Returns the CSS used to handle custom fonts.
* <p>
* Custom fonts live in fonts directory in the directory used to store decks.
* <p>
* Each font is mapped to the font family by the same name as the name of the font without the extension.
*/
private fun getCustomFontsStyle(customFontsMap: Map<String?, AnkiFont>): String {
val builder = StringBuilder()
for (font in customFontsMap.values) {
builder.append(font.declaration)
builder.append('\n')
}
return builder.toString()
}
/**
* Returns a map from custom fonts names to the corresponding {@link AnkiFont} object.
* <p>
* The list of constructed lazily the first time is needed.
*/
private fun getCustomFontsMap(context: Context): Map<String?, AnkiFont> {
val fonts = Utils.getCustomFonts(context)
val customFontsMap: MutableMap<String?, AnkiFont> = HashMapInit(fonts.size)
for (f in fonts) {
customFontsMap[f.name] = f
}
return customFontsMap
}
}
init {
val customFontsMap = getCustomFontsMap(context)
mCustomStyle = getCustomFontsStyle(customFontsMap) + getDominantFontStyle(context, customFontsMap)
}
}
| gpl-3.0 | fa8a918b3881f4c23246e3860e1798cb | 42.111111 | 136 | 0.562027 | 5.017241 | false | false | false | false |
davidwhitman/Tir | app/src/main/kotlin/com/thunderclouddev/tirforgoodreads/ui/viewbooks/ViewBooksController.kt | 1 | 4009 | package com.thunderclouddev.tirforgoodreads.ui.viewbooks
import android.databinding.DataBindingUtil
import android.net.Uri
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.bluelinelabs.conductor.Controller
import com.thunderclouddev.tirforgoodreads.ui.BaseApp
import com.thunderclouddev.tirforgoodreads.R
import com.thunderclouddev.tirforgoodreads.databinding.ViewBooksBinding
import com.thunderclouddev.tirforgoodreads.logging.timberkt.TimberKt
import com.uber.autodispose.CompletableScoper
import com.uber.autodispose.ObservableScoper
import com.uber.autodispose.android.ViewScopeProvider
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.fuckboilerplate.rx_social_connect.RxSocialConnect
import org.fuckboilerplate.rx_social_connect.query_string.QueryString
import org.fuckboilerplate.rx_social_connect.query_string.QueryStringStrategy
/**
* Created by David Whitman on 11 Mar, 2017.
*/
class ViewBooksController : Controller() {
private lateinit var binding: ViewBooksBinding
private lateinit var booksAdapter: ViewBooksAdapter
init {
addLifecycleListener(object : LifecycleListener() {
override fun postAttach(controller: Controller, view: View) {
super.postAttach(controller, view)
subscribeToDatabase(booksAdapter)
}
})
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View {
binding = DataBindingUtil.inflate<ViewBooksBinding>(inflater, R.layout.view_books, container, false)
binding.bookList.layoutManager = LinearLayoutManager(activity)
binding.booksRefreshLayout.setOnRefreshListener { refresh() }
booksAdapter = ViewBooksAdapter()
binding.bookList.adapter = booksAdapter
binding.getFeed.setOnClickListener {
trySignIn()
}
return binding.root
}
private fun trySignIn() {
QueryString.PARSER.replaceStrategyOAuth1(object : QueryStringStrategy {
override fun extractCode(uri: Uri): String {
return uri.getQueryParameter("oauth_token")
}
override fun extractError(uri: Uri): String? {
return uri.getQueryParameter("error")
}
})
RxSocialConnect.with(activity, BaseApp.goodreadsOAuthService)
.subscribe({ response ->
Toast.makeText(response.targetUI(), response.token().token, Toast.LENGTH_LONG).show()
TimberKt.d { response.token().token }
}, { error ->
TimberKt.e(error, { "Couldn't get token!" })
})
}
fun refresh() {
fetchBooksByAuthor("18541")
.doOnSubscribe { binding.booksRefreshLayout.isRefreshing = true }
.doOnTerminate { binding.booksRefreshLayout.isRefreshing = false }
.to(CompletableScoper(ViewScopeProvider.from(binding.root)))
.subscribe({}, { error ->
})
}
private fun subscribeToDatabase(booksAdapter: ViewBooksAdapter) {
BaseApp.data.createBooksByAuthorFromDatabaseObservable("18541")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.to(ObservableScoper(ViewScopeProvider.from(binding.root)))
.subscribe({ book ->
TimberKt.v { "Reading book from db: $book" }
booksAdapter.edit().add(ViewBooksAdapter.BookViewModel(book)).commit()
}, { error ->
throw error
})
}
private fun fetchBooksByAuthor(authorId: String) = BaseApp.data.queryBooksByAuthorFromApi(authorId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
} | gpl-3.0 | 3df368177c5ed71e8165cd4b0e1a312a | 38.70297 | 108 | 0.67573 | 5.01125 | false | false | false | false |
Nearsoft/nearbooks-android | app/src/main/java/com/nearsoft/nearbooks/view/activities/GoogleApiClientBaseActivity.kt | 2 | 1684 | package com.nearsoft.nearbooks.view.activities
import android.os.Bundle
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.nearsoft.nearbooks.NearbooksApplication
import com.nearsoft.nearbooks.di.components.DaggerGoogleApiClientComponent
import com.nearsoft.nearbooks.di.components.GoogleApiClientComponent
import com.nearsoft.nearbooks.di.modules.GoogleApiClientModule
import javax.inject.Inject
/**
* Google api client base activity.
* Created by epool on 11/17/15.
*/
abstract class GoogleApiClientBaseActivity : BaseActivity(), GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
@Inject
lateinit protected var mGoogleApiClient: GoogleApiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val googleApiClientComponent = DaggerGoogleApiClientComponent
.builder()
.nearbooksApplicationComponent(NearbooksApplication.applicationComponent)
.baseActivityModule(baseActivityModule)
.googleApiClientModule(GoogleApiClientModule(this, this))
.build()
injectComponent(googleApiClientComponent)
}
protected open fun injectComponent(googleApiClientComponent: GoogleApiClientComponent) {
googleApiClientComponent.inject(this)
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
println("onConnectionFailed ====>: " + connectionResult.errorMessage!!)
}
override fun onConnectionSuspended(i: Int) {
println("onConnectionSuspended ====>: " + i)
}
}
| mit | a007827d7a919358e3c7149853a69ac6 | 35.608696 | 142 | 0.757126 | 5.346032 | false | false | false | false |
RoverPlatform/rover-android | location/src/main/kotlin/io/rover/sdk/location/GoogleBeaconTrackerService.kt | 1 | 8982 | package io.rover.sdk.location
import android.Manifest
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_IMMUTABLE
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.google.android.gms.nearby.Nearby
import com.google.android.gms.nearby.messages.EddystoneUid
import com.google.android.gms.nearby.messages.IBeaconId
import com.google.android.gms.nearby.messages.Message
import com.google.android.gms.nearby.messages.MessageFilter
import com.google.android.gms.nearby.messages.MessageListener
import com.google.android.gms.nearby.messages.MessagesClient
import com.google.android.gms.nearby.messages.MessagesOptions
import com.google.android.gms.nearby.messages.NearbyPermissions
import com.google.android.gms.nearby.messages.Strategy
import com.google.android.gms.nearby.messages.SubscribeOptions
import io.rover.sdk.core.Rover
import io.rover.sdk.core.logging.log
import io.rover.sdk.core.permissions.PermissionsNotifierInterface
import io.rover.sdk.core.platform.whenNotNull
import io.rover.sdk.core.streams.Publishers
import io.rover.sdk.core.streams.Scheduler
import io.rover.sdk.core.streams.doOnNext
import io.rover.sdk.core.streams.filter
import io.rover.sdk.core.streams.map
import io.rover.sdk.core.streams.observeOn
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.location.domain.Beacon
import io.rover.sdk.location.sync.BeaconsRepository
import java.util.UUID
/**
* Subscribes to Beacon updates from Nearby Messages API and emits events and emits beacon
* reporting events.
*
* Google documentation: https://developers.google.com/nearby/messages/android/get-beacon-messages
*/
class GoogleBeaconTrackerService(
private val applicationContext: Context,
private val nearbyMessagesClient: MessagesClient,
private val beaconsRepository: BeaconsRepository,
mainScheduler: Scheduler,
ioScheduler: Scheduler,
private val locationReportingService: LocationReportingServiceInterface,
permissionsNotifier: PermissionsNotifierInterface
) : GoogleBeaconTrackerServiceInterface {
override fun newGoogleBeaconMessage(intent: Intent) {
nearbyMessagesClient.handleIntent(
intent,
object : MessageListener() {
override fun onFound(message: Message) {
log.v("A beacon found: $message")
emitEventForPossibleBeacon(message, true)
}
override fun onLost(message: Message) {
log.v("A beacon lost: $message")
emitEventForPossibleBeacon(message, false)
}
}
)
}
/**
* If the message matches a given [Beacon] in the database, and emits events as needed.
*/
private fun emitEventForPossibleBeacon(message: Message, enter: Boolean) {
return when (message.type) {
Message.MESSAGE_TYPE_I_BEACON_ID -> {
val ibeacon = IBeaconId.from(message)
beaconsRepository.beaconByUuidMajorAndMinor(
ibeacon.proximityUuid,
ibeacon.major,
ibeacon.minor
).subscribe { beacon ->
beacon.whenNotNull {
if (enter) {
locationReportingService.trackEnterBeacon(it)
} else {
locationReportingService.trackExitBeacon(it)
}
}
}
}
Message.MESSAGE_TYPE_EDDYSTONE_UID -> {
val eddystoneUid = EddystoneUid.from(message)
log.w("Eddystone beacons not currently supported by Rover SDK 2.0 (uid was $eddystoneUid), and it appears you have one registered with your project. Ignoring.")
}
else -> {
log.w("Unknown beacon type: '${message.type}'. Full payload was '${message.content}'. Ignoring.")
}
}
}
@SuppressLint("MissingPermission")
private fun startMonitoringBeacons(uuids: Set<UUID>) {
val messagesClient = Nearby.getMessagesClient(
applicationContext,
MessagesOptions.Builder()
.setPermissions(NearbyPermissions.BLE)
.build()
)
val messageFilters = uuids.map { uuid ->
// for now we only support iBeacon filters. No Eddystone for now.
MessageFilter.Builder()
.includeIBeaconIds(uuid, null, null)
.build()
}
val subscribeOptions = SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.apply { messageFilters.forEach { this.setFilter(it) } }
.build()
messagesClient.subscribe(
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, BeaconBroadcastReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { FLAG_IMMUTABLE } else { 0 }
),
subscribeOptions
).addOnFailureListener {
log.w("Unable to configure Rover beacon tracking because: $it")
}.addOnCompleteListener {
log.w("Successfully registered for beacon tracking updates.")
}
}
companion object {
private const val BACKGROUND_LOCATION_PERMISSION_CODE = "android.permission.ACCESS_BACKGROUND_LOCATION"
private const val Q_VERSION_CODE = 29
}
init {
val fineLocationSource = Publishers.concat(
Publishers.just(false),
permissionsNotifier.notifyForPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.map { it == Manifest.permission.ACCESS_FINE_LOCATION }
)
val backgroundLocationSource = Publishers.concat(
Publishers.just(false),
permissionsNotifier.notifyForPermission(BACKGROUND_LOCATION_PERMISSION_CODE)
.map { it == BACKGROUND_LOCATION_PERMISSION_CODE }
)
// This publisher emits whenever all necessary permissions for starting beacon monitoring are granted.
val permissionGranted = Publishers.combineLatest(fineLocationSource, backgroundLocationSource) {
fineLocationGranted, _ ->
val backgroundPermissionGranted = (ContextCompat.checkSelfPermission(applicationContext, BACKGROUND_LOCATION_PERMISSION_CODE) == PackageManager.PERMISSION_GRANTED)
// The BACKGROUND_LOCATION_PERMISSION_CODE permission is required for monitoring for
// beacons on Q and above.
fineLocationGranted && (Build.VERSION.SDK_INT < Q_VERSION_CODE || backgroundPermissionGranted)
}.filter { it }
Publishers.combineLatest(
// observeOn(mainScheduler) used on each because combineLatest() is not thread safe.
permissionGranted.doOnNext { log.v("Permission obtained. $it") },
beaconsRepository.allBeacons().observeOn(mainScheduler).doOnNext { log.v("Full beacons list obtained from sync.") }
) { permission, beacons ->
Pair(permission, beacons)
}.observeOn(ioScheduler).map { (_, beacons) ->
val fetchedBeacons = beacons.iterator().use { it.asSequence().toList() }
fetchedBeacons.aggregateToUniqueUuids().apply {
log.v("Starting up beacon tracking for ${fetchedBeacons.count()} beacon(s), aggregated to ${count()} filter(s).")
}
}.observeOn(mainScheduler).subscribe { beaconUuids ->
startMonitoringBeacons(beaconUuids)
}
}
}
class BeaconBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val rover = Rover.shared
if (rover == null) {
log.e("Received a beacon result from Google, but Rover is not initialized. Ignoring.")
return
}
val beaconTrackerService = rover.resolve(GoogleBeaconTrackerServiceInterface::class.java)
if (beaconTrackerService == null) {
log.e("Received a beacon result from Google, but GoogleBeaconTrackerServiceInterface is not registered in the Rover container. Ensure LocationAssembler() is in Rover.initialize(). Ignoring.")
return
} else beaconTrackerService.newGoogleBeaconMessage(
intent
)
}
}
/**
* We can tell Google Nearby to filter only on UUID, effectively wildcarding the major and minor.b
*
* This allows us to use far fewer filters, avoiding hitting undocumented but existent limits.
*/
fun Collection<Beacon>.aggregateToUniqueUuids(): Set<UUID> {
return this.map { it.uuid }.toSet()
}
| apache-2.0 | 5963dae19911e91c44db9c2e38f56fc1 | 42.182692 | 203 | 0.662102 | 4.83423 | false | false | false | false |
asamm/locus-api | locus-api-android/src/main/java/locus/api/android/features/mapProvider/MapTileService.kt | 1 | 2184 | package locus.api.android.features.mapProvider
import android.app.Service
import android.content.Intent
import android.os.IBinder
import locus.api.android.features.mapProvider.data.MapConfigLayer
import locus.api.android.features.mapProvider.data.MapTileRequest
import locus.api.android.features.mapProvider.data.MapTileResponse
import locus.api.utils.Logger
import java.util.*
/**
* IN PREPARATION - NOT YET FULLY WORKING!!
*/
abstract class MapTileService : Service() {
private val mBinder = object : IMapTileService.Stub() {
override fun getMapConfigs(): MapDataContainer {
val configs = [email protected]
return if (configs == null || configs.isEmpty()) {
Logger.logW(TAG, "getMapConfigs(), invalid configs")
MapDataContainer(ArrayList())
} else {
MapDataContainer(configs)
}
}
override fun getMapTile(request: MapDataContainer?): MapDataContainer {
// check request
if (request == null || !request.isValid(
MapDataContainer.DATA_TYPE_TILE_REQUEST)) {
Logger.logW(TAG, "getMapTile($request), invalid request")
val resp = MapTileResponse()
resp.resultCode = MapTileResponse.CODE_INVALID_REQUEST
return MapDataContainer(resp)
}
// handle request
val response = [email protected](request.tileRequest!!)
return if (response == null) {
Logger.logW(TAG, "getMapTile($request), invalid response")
val resp = MapTileResponse()
resp.resultCode = MapTileResponse.CODE_INTERNAL_ERROR
MapDataContainer(resp)
} else {
MapDataContainer(response)
}
}
}
// ABSTRACT PART
abstract val mapConfigs: List<MapConfigLayer>?
override fun onBind(intent: Intent): IBinder? {
return mBinder
}
abstract fun getMapTile(request: MapTileRequest): MapTileResponse?
companion object {
private val TAG = "MapTileService"
}
}
| mit | 901fff0cc23aa89de82904411620ec92 | 32.090909 | 80 | 0.622253 | 4.952381 | false | true | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/Calls.kt | 1 | 1269 | package com.duopoints.android
import com.duopoints.android.rest.clients.*
import com.duopoints.android.rest.services.*
object Calls {
private const val USER_BASE_URL = "https://duopoints.herokuapp.com"
private val geoClient: GeoClient = GeoClient()
private val userClient: UserClient = UserClient(USER_BASE_URL)
private val friendClient: FriendClient = FriendClient(USER_BASE_URL)
private val pointClient: PointClient = PointClient(USER_BASE_URL)
private val relationshipClient: RelationshipClient = RelationshipClient(USER_BASE_URL)
private val mediaClient: MediaClient = MediaClient(USER_BASE_URL)
private val reportClient: ReportClient = ReportClient(USER_BASE_URL)
val geoService: GeoService
get() = geoClient.geoService
val userService: UserService
get() = userClient.userService
val friendService: FriendService
get() = friendClient.friendService
val pointService: PointService
get() = pointClient.pointService
val relationshipService: RelationshipService
get() = relationshipClient.relationshipService
val mediaService: MediaService
get() = mediaClient.mediaService
val reportService: ReportService
get() = reportClient.reportService
}
| gpl-3.0 | e2bfed8469689cace8431d178162bb5d | 33.297297 | 90 | 0.742317 | 4.421603 | false | false | false | false |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/MayBeConst.kt | 1 | 4482 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isConstant
import io.gitlab.arturbosch.detekt.rules.isOverridden
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
/**
* This rule identifies and reports properties (`val`) that may be `const val` instead.
* Using `const val` can lead to better performance of the resulting bytecode as well as better interoperability with
* Java.
*
* <noncompliant>
* val myConstant = "abc"
* </noncompliant>
*
* <compliant>
* const val MY_CONSTANT = "abc"
* </compliant>
*
* @author Marvin Ramin
* @author schalkms
*/
class MayBeConst(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
"Reports vals that can be const val instead.",
Debt.FIVE_MINS)
private val binaryTokens = hashSetOf<KtSingleValueToken>(KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL,
KtTokens.DIV, KtTokens.PERC)
private val topLevelConstants = HashSet<String?>()
private val companionObjectConstants = HashSet<String?>()
override fun visitKtFile(file: KtFile) {
topLevelConstants.clear()
val topLevelProperties = file.declarations
.filterIsInstance<KtProperty>()
.filter { it.isTopLevel && it.isConstant() }
.mapNotNull { it.name }
topLevelConstants.addAll(topLevelProperties)
super.visitKtFile(file)
}
override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
val constProperties = declaration.declarations
.filterIsInstance<KtProperty>()
.filter { it.isConstant() }
.mapNotNull { it.name }
companionObjectConstants.addAll(constProperties)
super.visitObjectDeclaration(declaration)
companionObjectConstants.removeAll(constProperties)
}
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
if (property.canBeConst()) {
report(CodeSmell(issue, Entity.from(property), "${property.nameAsSafeName} can be a `const val`."))
}
}
private fun KtProperty.canBeConst(): Boolean {
if (cannotBeConstant() || isInObject() || isJvmField()) {
return false
}
return this.initializer?.isConstantExpression() == true
}
private fun KtProperty.isJvmField(): Boolean {
val isJvmField = annotationEntries.any { it.text == "@JvmField" }
return annotationEntries.isNotEmpty() && !isJvmField
}
private fun KtProperty.cannotBeConstant(): Boolean {
return isLocal ||
isVar ||
getter != null ||
isConstant() ||
isOverridden()
}
private fun KtProperty.isInObject() =
!isTopLevel && containingClassOrObject !is KtObjectDeclaration
private fun KtExpression.isConstantExpression(): Boolean {
return this is KtStringTemplateExpression && !hasInterpolation() ||
node.elementType == KtNodeTypes.BOOLEAN_CONSTANT ||
node.elementType == KtNodeTypes.INTEGER_CONSTANT ||
node.elementType == KtNodeTypes.CHARACTER_CONSTANT ||
node.elementType == KtNodeTypes.FLOAT_CONSTANT ||
topLevelConstants.contains(text) ||
companionObjectConstants.contains(text) ||
isBinaryExpression(this) ||
isParenthesizedExpression(this)
}
private fun isParenthesizedExpression(expression: KtExpression) =
(expression as? KtParenthesizedExpression)?.expression?.isConstantExpression() == true
private fun isBinaryExpression(expression: KtExpression): Boolean {
val binaryExpression = expression as? KtBinaryExpression ?: return false
return expression.node.elementType == KtNodeTypes.BINARY_EXPRESSION &&
binaryTokens.contains(binaryExpression.operationToken) &&
binaryExpression.left?.isConstantExpression() == true &&
binaryExpression.right?.isConstantExpression() == true
}
}
| apache-2.0 | 94dd1f643ddb0a138687498bd15ba6da | 34.571429 | 117 | 0.76863 | 4.228302 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Presenters/CustomLayout/DrawingView.kt | 1 | 4619 | package com.polito.sismic.Presenters.CustomLayout
import android.annotation.TargetApi
import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.graphics.Bitmap
import android.media.ThumbnailUtils
import android.widget.ImageView
import java.io.ByteArrayOutputStream
class DrawingView : View {
@JvmOverloads
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: super(context, attrs, defStyleAttr)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
constructor(
context: Context,
attrs: AttributeSet?,
defStyleAttr: Int,
defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes)
var mPaint: Paint? = null
var mWidth: Int = 0
var mHeight: Int = 0
private var mBitmap: Bitmap? = null
private var mCanvas: Canvas? = null
private val mPath: Path = Path()
private val mBitmapPaint: Paint = Paint(Paint.DITHER_FLAG)
private val circlePaint: Paint = Paint()
private val circlePath: Path = Path()
private val TOUCH_TOLERANCE : Float = 4f
init {
circlePaint.isAntiAlias = true
circlePaint.color = Color.BLACK
circlePaint.style = Paint.Style.STROKE
circlePaint.strokeJoin = Paint.Join.MITER
circlePaint.strokeWidth = TOUCH_TOLERANCE
isDrawingCacheEnabled = true
}
fun setPaint(paint : Paint)
{
mPaint = paint
}
fun clearDrawing() {
isDrawingCacheEnabled = false
// don't forget that one and the match below,
// or you just keep getting a duplicate when you save.
onSizeChanged(width, height, width, height)
invalidate()
isDrawingCacheEnabled = true
}
fun getDrawingToSave() : ByteArrayOutputStream
{
//var whatTheUserDrewBitmap = drawingCache;
//// don't forget to clear it (see above) or you just get duplicates
//
//// almost always you will want to reduce res from the very high screen res
//whatTheUserDrewBitmap =UserDrewBitmap, 256,
// ThumbnailUtils.extractThumbnail(whatThe256);
// NOTE that's an incredibly useful trick for cropping/resizing squares
// while handling all memory problems etc
// http://stackoverflow.com/a/17733530/294884
// these days you often need a "byte array". for example,
// to save to parse.com or other cloud services
val baos = ByteArrayOutputStream()
drawingCache.compress(Bitmap.CompressFormat.PNG, 75, baos)
return baos
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w
mHeight = h
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
mCanvas = Canvas(mBitmap)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(mBitmap, 0f, 0f, mBitmapPaint)
canvas.drawPath(mPath, mPaint)
canvas.drawPath(circlePath, circlePaint)
}
private var mX: Float = 0.toFloat()
private var mY: Float = 0.toFloat()
private fun touch_start(x: Float, y: Float) {
mPath.reset()
mPath.moveTo(x, y)
mX = x
mY = y
}
private fun touch_move(x: Float, y: Float) {
val dx = Math.abs(x - mX)
val dy = Math.abs(y - mY)
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2)
mX = x
mY = y
circlePath.reset()
circlePath.addCircle(mX, mY, 30f, Path.Direction.CW)
}
}
private fun touch_up() {
mPath.lineTo(mX, mY)
circlePath.reset()
// commit the path to our offscreen
mCanvas!!.drawPath(mPath, mPaint)
// kill this so we don't double draw
mPath.reset()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val x = event.x
val y = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> {
touch_start(x, y)
invalidate()
}
MotionEvent.ACTION_MOVE -> {
touch_move(x, y)
invalidate()
}
MotionEvent.ACTION_UP -> {
touch_up()
invalidate()
}
}
return true
}
} | mit | 670f4fb67023bd3595698a53b5894bde | 28.240506 | 84 | 0.599697 | 4.304753 | false | false | false | false |
FHannes/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUAssertExpression.kt | 8 | 2014 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.PsiAssertStatement
import com.intellij.psi.PsiType
import org.jetbrains.uast.*
class JavaUAssertExpression(
override val psi: PsiAssertStatement,
override val uastParent: UElement?
) : JavaAbstractUExpression(), UCallExpression {
val condition: UExpression by lz { JavaConverter.convertOrEmpty(psi.assertCondition, this) }
val message: UExpression? by lz { JavaConverter.convertOrNull(psi.assertDescription, this) }
override val methodIdentifier: UIdentifier?
get() = null
override val classReference: UReferenceExpression?
get() = null
override val methodName: String
get() = "assert"
override val receiver: UExpression?
get() = null
override val receiverType: PsiType?
get() = null
override val valueArgumentCount: Int
get() = if (message != null) 2 else 1
override val valueArguments by lz {
val message = this.message
if (message != null) listOf(condition, message) else listOf(condition)
}
override val typeArgumentCount: Int
get() = 0
override val typeArguments: List<PsiType>
get() = emptyList()
override val returnType: PsiType
get() = PsiType.VOID
override val kind: UastCallKind
get() = JavaUastCallKinds.ASSERT
override fun resolve() = null
} | apache-2.0 | ecab1f01c4345af1861276da5f41df7a | 29.074627 | 96 | 0.694638 | 4.662037 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/services/LocationManager.kt | 1 | 3726 | package za.org.grassroot2.services
import android.content.IntentSender
import android.location.Location
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.app.AppCompatActivity
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.*
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import javax.inject.Inject
class LocationManager @Inject
constructor(a: AppCompatActivity) : GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private val context: FragmentActivity
private val googleApiClient: GoogleApiClient
private var oneTimeLocationRequest: LocationRequest? = null
private val locationSubject = PublishSubject.create<Location>()
val currentLocation: Observable<Location>
get() {
if (googleApiClient.isConnected) {
checkSettingsAndReuqestLocation()
} else if (!googleApiClient.isConnected) {
googleApiClient.connect()
}
return locationSubject
}
init {
context = a
googleApiClient = GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()
createOneTimeLocationRequest()
}
fun disconnect() {
if (googleApiClient.isConnected) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this)
googleApiClient.disconnect()
}
}
override fun onConnected(bundle: Bundle?) {
checkSettingsAndReuqestLocation()
}
private fun checkSettingsAndReuqestLocation() {
val builder = LocationSettingsRequest.Builder()
.addLocationRequest(oneTimeLocationRequest)
val result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient,
builder.build())
result.setResultCallback { locationSettingsResult ->
val status = locationSettingsResult.status
when (status.statusCode) {
LocationSettingsStatusCodes.SUCCESS -> try {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, oneTimeLocationRequest, this@LocationManager)
} catch (e: SecurityException) {
e.printStackTrace()
}
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS)
} catch (e: IntentSender.SendIntentException) {
// Ignore the error.
}
LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
}
}
}
}
override fun onConnectionSuspended(i: Int) {
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
}
private fun createOneTimeLocationRequest() {
oneTimeLocationRequest = LocationRequest()
oneTimeLocationRequest!!.interval = 10000
oneTimeLocationRequest!!.fastestInterval = 5000
oneTimeLocationRequest!!.numUpdates = 1
oneTimeLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
override fun onLocationChanged(location: Location) {
locationSubject.onNext(location)
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this)
}
companion object {
private const val REQUEST_CHECK_SETTINGS = 1
}
}
| bsd-3-clause | 361be1bd70ffe11641ccc09d4f4e00d1 | 34.826923 | 139 | 0.678476 | 5.821875 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/home/view/MainMetadataView.kt | 1 | 14178 | package io.casey.musikcube.remote.ui.home.view
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.AttrRes
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.injection.DaggerViewComponent
import io.casey.musikcube.remote.injection.GlideApp
import io.casey.musikcube.remote.service.playback.IPlaybackService
import io.casey.musikcube.remote.service.playback.PlaybackServiceFactory
import io.casey.musikcube.remote.service.playback.PlaybackState
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.playback.impl.streaming.StreamingPlaybackService
import io.casey.musikcube.remote.service.websocket.Messages
import io.casey.musikcube.remote.service.websocket.SocketMessage
import io.casey.musikcube.remote.service.websocket.WebSocketService
import io.casey.musikcube.remote.ui.albums.activity.AlbumBrowseActivity
import io.casey.musikcube.remote.ui.settings.constants.Prefs
import io.casey.musikcube.remote.ui.shared.extension.fallback
import io.casey.musikcube.remote.ui.shared.extension.getColorCompat
import io.casey.musikcube.remote.ui.shared.util.Size
import io.casey.musikcube.remote.ui.tracks.activity.TrackListActivity
import org.json.JSONArray
import javax.inject.Inject
import kotlin.math.roundToLong
import io.casey.musikcube.remote.ui.shared.util.AlbumArtLookup.getUrl as getAlbumArtUrl
class MainMetadataView : FrameLayout {
@Inject lateinit var wss: WebSocketService
private lateinit var prefs: SharedPreferences
private var paused = true
private lateinit var title: TextView
private lateinit var artist: TextView
private lateinit var album: TextView
private lateinit var volume: TextView
private lateinit var titleWithArt: TextView
private lateinit var artistAndAlbumWithArt: TextView
private lateinit var volumeWithArt: TextView
private lateinit var mainTrackMetadataWithAlbumArt: View
private lateinit var mainTrackMetadataNoAlbumArt: View
private lateinit var buffering: View
private lateinit var albumArtImageView: ImageView
private enum class DisplayMode {
Artwork, NoArtwork, Stopped
}
private var lastDisplayMode = DisplayMode.Stopped
private var loadedAlbumArtUrl: String? = null
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
fun onResume() {
this.wss.addClient(wssClient)
paused = false
}
fun onPause() {
this.wss.removeClient(wssClient)
paused = true
}
fun clear() {
if (!paused) {
loadedAlbumArtUrl = null
updateAlbumArt()
}
}
fun hide() {
visibility = View.GONE
}
fun refresh() {
if (!paused) {
visibility = View.VISIBLE
val playback = playbackService
val playing = playbackService.playingTrack
val buffering = playback.state == PlaybackState.Buffering
val streaming = playback is StreamingPlaybackService
val artist = fallback(playing.artist, "")
val album = fallback(playing.album, "")
val title = fallback(playing.title, "")
/* we don't display the volume amount when we're streaming -- the system has
overlays for drawing volume. */
if (streaming) {
volume.visibility = View.GONE
volumeWithArt.visibility = View.GONE
}
else {
val volume = getString(R.string.status_volume, (playback.volume * 100).roundToLong())
this.volume.visibility = View.VISIBLE
this.volumeWithArt.visibility = View.VISIBLE
this.volume.text = volume
this.volumeWithArt.text = volume
}
this.title.text = title.ifEmpty { getString(if (buffering) R.string.buffering else R.string.unknown_title) }
this.artist.text = artist.ifEmpty { getString(if (buffering) R.string.buffering else R.string.unknown_artist) }
this.album.text = album.ifEmpty { getString(if (buffering) R.string.buffering else R.string.unknown_album) }
this.rebindAlbumArtistWithArtTextView(playback)
this.titleWithArt.text = title.ifEmpty { getString(if (buffering) R.string.buffering else R.string.unknown_title) }
this.buffering.visibility = if (buffering) View.VISIBLE else View.GONE
if (artist.isEmpty() || album.isEmpty()) {
setMetadataDisplayMode(DisplayMode.NoArtwork)
loadedAlbumArtUrl = null
}
else {
val newUrl = getAlbumArtUrl(playing, Size.Mega) ?: ""
if (newUrl != loadedAlbumArtUrl) {
updateAlbumArt(newUrl)
}
}
}
}
private val playbackService: IPlaybackService
get() = PlaybackServiceFactory.instance(context)
private fun getString(resId: Int): String {
return context.getString(resId)
}
private fun getString(resId: Int, vararg args: Any): String {
return context.getString(resId, *args)
}
private fun setMetadataDisplayMode(mode: DisplayMode) {
lastDisplayMode = mode
when (mode) {
DisplayMode.Stopped -> {
albumArtImageView.setImageDrawable(null)
mainTrackMetadataWithAlbumArt.visibility = View.GONE
mainTrackMetadataNoAlbumArt.visibility = View.GONE
}
DisplayMode.Artwork -> {
mainTrackMetadataWithAlbumArt.visibility = View.VISIBLE
mainTrackMetadataNoAlbumArt.visibility = View.GONE
}
else -> {
albumArtImageView.setImageDrawable(null)
mainTrackMetadataWithAlbumArt.visibility = View.GONE
mainTrackMetadataNoAlbumArt.visibility = View.VISIBLE
}
}
}
private fun rebindAlbumArtistWithArtTextView(playback: IPlaybackService) {
val playing = playback.playingTrack
val buffering = playback.state == PlaybackState.Buffering
val artist = fallback(
playing.artist,
getString(if (buffering) R.string.buffering else R.string.unknown_artist))
val album = fallback(
playing.album,
getString(if (buffering) R.string.buffering else R.string.unknown_album))
val albumColor = ForegroundColorSpan(getColorCompat(R.color.theme_orange))
val artistColor = ForegroundColorSpan(getColorCompat(R.color.theme_yellow))
val builder = SpannableStringBuilder().append(album).append(" - ").append(artist)
val albumClickable = object : ClickableSpan() {
override fun onClick(widget: View) {
navigateToCurrentAlbum()
}
override fun updateDrawState(ds: TextPaint) {}
}
val artistClickable = object : ClickableSpan() {
override fun onClick(widget: View) {
navigateToCurrentArtist()
}
override fun updateDrawState(ds: TextPaint) {}
}
val artistOffset = album.length + 3
builder.setSpan(albumColor, 0, album.length, 0)
builder.setSpan(albumClickable, 0, album.length, 0)
builder.setSpan(artistColor, artistOffset, artistOffset + artist.length, 0)
builder.setSpan(artistClickable, artistOffset, artistOffset + artist.length, 0)
artistAndAlbumWithArt.movementMethod = LinkMovementMethod.getInstance()
artistAndAlbumWithArt.highlightColor = Color.TRANSPARENT
artistAndAlbumWithArt.text = builder
}
private fun updateAlbumArt(albumArtUrl: String = "") {
if (playbackService.state == PlaybackState.Stopped) {
setMetadataDisplayMode(DisplayMode.NoArtwork)
}
if (albumArtUrl.isEmpty()) {
loadedAlbumArtUrl = null
setMetadataDisplayMode(DisplayMode.NoArtwork)
}
else if (albumArtUrl != loadedAlbumArtUrl || lastDisplayMode == DisplayMode.Stopped) {
loadedAlbumArtUrl = albumArtUrl
GlideApp.with(context)
.load(albumArtUrl)
.apply(BITMAP_OPTIONS)
.listener(object: RequestListener<Drawable> {
override fun onResourceReady(resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean): Boolean {
if (!paused) {
preloadNextImage()
}
setMetadataDisplayMode(DisplayMode.Artwork)
return false
}
override fun onLoadFailed(e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean): Boolean {
setMetadataDisplayMode(DisplayMode.NoArtwork)
loadedAlbumArtUrl = null
return false
}
})
.into(albumArtImageView)
}
else {
setMetadataDisplayMode(lastDisplayMode)
}
}
private fun preloadNextImage() {
val request = SocketMessage.Builder
.request(Messages.Request.QueryPlayQueueTracks)
.addOption(Messages.Key.OFFSET, playbackService.queuePosition + 1)
.addOption(Messages.Key.LIMIT, 1)
.build()
this.wss.send(request, wssClient) { response: SocketMessage ->
val data = response.getJsonArrayOption(Messages.Key.DATA, JSONArray())
if (data != null && data.length() > 0) {
val track = data.optJSONObject(0)
val artist = track.optString(Metadata.Track.ARTIST, "")
val album = track.optString(Metadata.Track.ALBUM, "")
val newUrl = getAlbumArtUrl(artist, album, Size.Mega)
if (loadedAlbumArtUrl != newUrl) {
GlideApp.with(context).load(newUrl).apply(BITMAP_OPTIONS).submit(width, height)
}
}
}
}
private fun init() {
DaggerViewComponent.builder()
.appComponent(Application.appComponent)
.build().inject(this)
this.prefs = context.getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE)
val child = LayoutInflater.from(context).inflate(R.layout.main_metadata, this, false)
addView(child, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
this.title = findViewById(R.id.track_title)
this.artist = findViewById(R.id.track_artist)
this.album = findViewById(R.id.track_album)
this.volume = findViewById(R.id.volume)
this.buffering = findViewById(R.id.buffering)
this.titleWithArt = findViewById(R.id.with_art_track_title)
this.artistAndAlbumWithArt = findViewById(R.id.with_art_artist_and_album)
this.volumeWithArt = findViewById(R.id.with_art_volume)
this.mainTrackMetadataWithAlbumArt = findViewById(R.id.main_track_metadata_with_art)
this.mainTrackMetadataNoAlbumArt = findViewById(R.id.main_track_metadata_without_art)
this.albumArtImageView = findViewById(R.id.album_art)
this.album.setOnClickListener { navigateToCurrentAlbum() }
this.artist.setOnClickListener { navigateToCurrentArtist() }
}
private fun navigateToCurrentArtist() {
val context = context
val playing = playbackService.playingTrack
val artistId = playing.artistId
if (artistId != -1L) {
val artistName = fallback(playing.artist, "")
context.startActivity(AlbumBrowseActivity.getStartIntent(
context, Metadata.Category.ARTIST, artistId, artistName))
}
}
private fun navigateToCurrentAlbum() {
val context = context
val playing = playbackService.playingTrack
val albumId = playing.albumId
if (albumId != -1L) {
val albumName = fallback(playing.album, "")
context.startActivity(TrackListActivity.getStartIntent(
context, Metadata.Category.ALBUM, albumId, albumName))
}
}
private val wssClient = object : WebSocketService.Client {
override fun onStateChanged(newState: WebSocketService.State, oldState: WebSocketService.State) {}
override fun onMessageReceived(message: SocketMessage) {}
override fun onInvalidPassword() {}
}
private companion object {
val BITMAP_OPTIONS = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
}
}
| bsd-3-clause | 5509ca66000484b0115bba8dcc8108be | 38.274238 | 127 | 0.646424 | 5.150018 | false | false | false | false |
bravelocation/yeltzland-android | app/src/main/java/com/bravelocation/yeltzlandnew/viewmodels/WebViewViewModel.kt | 1 | 3868 | package com.bravelocation.yeltzlandnew.viewmodels
import android.net.Uri
import android.os.Bundle
import android.webkit.CookieManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
enum class WebNavigationEvent {
NONE,
BACK,
FORWARD,
RELOAD,
LOAD
}
data class WebNavigationData(
val event: WebNavigationEvent = WebNavigationEvent.NONE,
val url: String = ""
)
class WebViewViewModel constructor(val homeUrl: String): ViewModel() {
private var _canGoBack: MutableLiveData<Boolean> = MutableLiveData(false)
private var _canGoForward: MutableLiveData<Boolean> = MutableLiveData(false)
private val _progress : MutableLiveData<Int> = MutableLiveData(0)
private val _navigationEvent = MutableLiveData(WebNavigationData(event = WebNavigationEvent.NONE))
private var _loadingError: MutableLiveData<Boolean> = MutableLiveData(false)
private var _currentUrl: String
private var _webViewBundle: Bundle? = null
val progress: LiveData<Int> = _progress
val navigationEvent: LiveData<WebNavigationData> = _navigationEvent
val canGoBack: LiveData<Boolean> = _canGoBack
val canGoForward: LiveData<Boolean> = _canGoForward
val loadingError: LiveData<Boolean> = _loadingError
init {
_currentUrl = homeUrl
}
val currentUrl: String
get() {
return _currentUrl
}
var savedState: Bundle
get() {
if (_webViewBundle == null) {
_webViewBundle = Bundle()
}
return _webViewBundle!!
}
set(value) {
_webViewBundle = value
}
// Update state on web change
fun updateProgress(progress: Int) {
_loadingError.postValue(false)
_progress.postValue(progress)
}
fun updateWebState(canGoBack: Boolean, canGoForward: Boolean, currentUrl: String) {
_canGoBack.postValue(canGoBack)
_canGoForward.postValue(canGoForward)
_currentUrl = currentUrl
}
fun receivedLoadingError() {
_loadingError.postValue(true)
}
fun onHomeDomain(url: String): Boolean {
// Check if URL is on a different domain as the home URL
try {
val home = Uri.parse(this.homeUrl)
val current = Uri.parse(url)
home.host?.let { homeHost ->
current.host?.let { currentHost ->
if (homeHost != currentHost) {
return false
}
}
}
} catch (e: NullPointerException) {
// Badly formed URL - ignore and return false
}
return true
}
fun validExternalUrl(url: String) : Boolean {
// Check if URL is on a different domain as the home URL
try {
val current = Uri.parse(url)
current.scheme?.let { currentScheme ->
if (currentScheme == "https" || currentScheme == "http" || currentScheme == "mailto" ) {
return true
}
}
} catch (e: NullPointerException) {
// Badly formed URL - ignore and return false
}
return false
}
// Cookie manager actions
fun flushCookies() {
CookieManager.getInstance().flush()
}
// Web view actions
fun goBack() {
_navigationEvent.postValue(WebNavigationData(event = WebNavigationEvent.BACK))
}
fun goForward() {
_navigationEvent.postValue(WebNavigationData(event = WebNavigationEvent.FORWARD))
}
fun goHome() {
_navigationEvent.postValue(WebNavigationData(event = WebNavigationEvent.LOAD, url = homeUrl))
}
fun reload() {
_navigationEvent.postValue(WebNavigationData(event = WebNavigationEvent.RELOAD))
}
} | mit | 028f69715f8658c0276a5afd3f62336c | 27.659259 | 104 | 0.622027 | 4.828964 | false | false | false | false |
andrei-heidelbacher/metanalysis | chronolens-core/src/main/kotlin/org/chronolens/core/repository/Repository.kt | 1 | 3626 | /*
* Copyright 2018-2021 Andrei Heidelbacher <[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 org.chronolens.core.repository
import org.chronolens.core.model.SourceFile
import org.chronolens.core.model.SourceTree
import java.util.stream.Stream
import kotlin.streams.asStream
/**
* A wrapper which connects to a repository and allows querying source code
* metadata and the source tree history.
*/
public interface Repository {
/**
* Returns the id of the `head` revision.
*
* @throws CorruptedRepositoryException if the repository is corrupted
*/
public fun getHeadId(): String
/**
* Returns the interpretable source files from the `head` revision.
*
* @throws CorruptedRepositoryException if the repository is corrupted
*/
public fun listSources(): Set<String>
/**
* Returns the list of all revisions in chronological order.
*
* @throws CorruptedRepositoryException if the repository is corrupted
*/
public fun listRevisions(): List<String>
/**
* Returns the source file found at the given [path] in the `head` revision,
* or `null` if the [path] doesn't exist in the `head` revision or couldn't
* be interpreted.
*
* If the source contains syntax errors, then the most recent version which
* can be parsed without errors will be returned. If all versions of the
* source contain errors, then the empty source file will be returned.
*
* @throws IllegalArgumentException if the given [path] is invalid
* @throws CorruptedRepositoryException if the repository is corrupted
*/
public fun getSource(path: String): SourceFile?
/**
* Returns the snapshot of the repository at the `head` revision.
*
* @throws CorruptedRepositoryException if the repository is corrupted
* @see getSource for details about how the latest sources are retrieved
*/
public fun getSnapshot(): SourceTree {
val sources = listSources().map(::getSource).checkNoNulls()
return SourceTree.of(sources)
}
/**
* Returns a lazy view of the transactions applied to the repository in
* chronological order.
*
* Iterating over the sequence may throw an [java.io.UncheckedIOException]
* if any I/O errors occur, or a [CorruptedRepositoryException] if the
* repository is corrupted.
*
* @throws CorruptedRepositoryException if the repository is corrupted
*/
public fun getHistory(): Sequence<Transaction>
/** Delegates to [getHistory]. */
public fun getHistoryStream(): Stream<Transaction> = getHistory().asStream()
public companion object {
/** Returns whether the given source file [path] is valid. */
public fun isValidPath(path: String): Boolean =
"/$path/".indexOfAny(listOf("//", "/./", "/../")) == -1
/** Returns whether the given revision [id] is valid. */
public fun isValidRevisionId(id: String): Boolean =
id.isNotEmpty() && id.all(Character::isLetterOrDigit)
}
}
| apache-2.0 | 2b956b9e48636c5c93597f93263fa4e0 | 35.626263 | 80 | 0.688086 | 4.613232 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/MonitorComponent.kt | 2 | 6665 | package com.cout970.magneticraft.systems.gui.components
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.api.core.ITileRef
import com.cout970.magneticraft.misc.guiTexture
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.misc.resource
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.computer.DeviceKeyboard
import com.cout970.magneticraft.systems.computer.DeviceMonitor
import com.cout970.magneticraft.systems.config.Config
import com.cout970.magneticraft.systems.gui.DATA_ID_MONITOR_CLIPBOARD
import com.cout970.magneticraft.systems.gui.render.*
import net.minecraft.client.gui.Gui
import net.minecraft.client.gui.GuiScreen
import net.minecraft.client.renderer.GlStateManager.color
import org.lwjgl.input.Keyboard
/**
* Created by cout970 on 20/05/2016.
*/
class MonitorComponent(
val tile: ITileRef,
val monitor: DeviceMonitor,
val keyboard: DeviceKeyboard
) : IComponent {
companion object {
@JvmStatic
val TEXTURE = resource("textures/gui/monitor_text.png")
}
override val pos: IVector2 = Vec2d.ZERO
override val size: IVector2 = Vec2d(350, 230)
override lateinit var gui: IGui
override fun init() {
Keyboard.enableRepeatEvents(true)
}
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
gui.bindTexture(guiTexture("misc"))
val start = gui.pos + vec2Of(11, 11)
val end = start + vec2Of(328, 208)
gui.drawColor(start - 1, end + 1, 0xFF1E1E1E.toInt())
gui.drawColor(start, end, 0xFF232323.toInt())
gui.bindTexture(guiTexture("monitor_text"))
// 0 => amber 1, 1 => amber 2, 2 => white, 3 => green 1, 4 => apple 2, 5 => green 2, 6 => apple 2c, 7 => green 3, 8 => green 4
when (Config.computerTextColor) {
0 -> color(255f / 255f, 176f / 255f, 0f / 255f, 1.0f)// Amber
1 -> color(255f / 255f, 204f / 255f, 0f / 255f, 1.0f) // Amb
2 -> color(220f / 255f, 220f / 255f, 220f / 255f, 1.0f) // white
3 -> color(51f / 255f, 255f / 255f, 0f / 255f, 1.0f) // Green 1
4 -> color(51f / 255f, 255f / 255f, 51f / 255f, 1.0f) // Apple 2
5 -> color(0f / 255f, 255f / 255f, 51f / 255f, 1.0f) // Green 2
6 -> color(102f / 255f, 255f / 255f, 102f / 255f, 1.0f) // Apple 2c
7 -> color(0f / 255f, 255f / 255f, 102f / 255f, 1.0f) // Green 3
else -> color(47f / 255f, 140f / 255f, 64f / 255f, 1.0f) // Intellij
}
val lines = monitor.lines
val columns = monitor.columns
val scale = 4
for (line in 0 until lines) {
for (column in 0 until columns) {
var character = monitor.getChar(line * columns + column) and 0xFF
if (line == monitor.cursorLine && column == monitor.cursorColumn &&
tile.world.totalWorldTime % 10 >= 4) {
character = character xor 128
}
if (character != 32 && character != 0) {
val posX = gui.pos.xi + 15 + column * scale
val posY = gui.pos.yi + 15 + line * (scale + 2)
val x = character and 15
val y = character shr 4
Gui.drawScaledCustomSizeModalRect(
posX, posY,
x * 16f, y * 16f,
16, 16,
scale, scale,
256f, 256f
)
}
}
}
color(1.0f, 1.0f, 1.0f, 1.0f)
}
override fun onKeyTyped(typedChar: Char, keyCode: Int): Boolean {
// Ignore ESC, otherwise you cannot exit the gui
if (keyCode == 1) return false
// Paste from clipboard
// SHIFT + CTRL + ALT + V
if (isShiftKeyDown() && isCtrlKeyDown() && isAltKeyDown() && keyCode == 47) {
val str = GuiScreen.getClipboardString()
if (str.isNotBlank()) {
gui.container.sendUpdate(IBD().apply { setString(DATA_ID_MONITOR_CLIPBOARD, str) })
}
}
sendKey(typedChar, keyCode, true)
return true
}
override fun onKeyReleased(typedChar: Char, keyCode: Int): Boolean {
sendKey(typedChar, keyCode, false)
return true
}
fun sendKey(typedChar: Char, keyCode: Int, press: Boolean) {
var intChar = typedChar.toInt()
if (isCtrlKeyDown() && keyCode != 29) {
if (intChar in 65..90) {
intChar += 96
}
}
val key = when (intChar) {
// Unknown keys
202, 204, 206 -> intChar
// printable ascii chars
in 32..126 -> intChar
else -> when (keyCode) {
0 -> return // Unknown
1 -> return // ESC
58 -> return // Caps lock
200 -> 1 // UP
208 -> 2 // DOWN
203 -> 3 // LEFT
205 -> 4 // RIGHT
199 -> 5 // HOME
201 -> 6 // PRIOR (re-pag)
207 -> 7 // END
209 -> 8 // NEXT (av-pag)
210 -> 10 // INSERT
211 -> 13 // DELETE
14 -> 11 // BACK
15 -> 9 // TAB
28 -> 10 // RETURN
29 -> 14 // LCONTROL
42 -> 15 // LSHIFT
54 -> 16 // RSHIFT
56 -> 17 // LMENU
59 -> 18 // F1
60 -> 19 // F2
61 -> 20 // F3
62 -> 21 // F4
63 -> 22 // F5
64 -> 23 // F6
65 -> 24 // F7
66 -> 25 // F8
67 -> 26 // F9
68 -> 27 // F10
157 -> 28 // RCONTROL
184 -> 29 // RMENU
219 -> 30 // LMETA
220 -> 31 // RMETA
else -> {
return
}
}
}
// debug("sendKey: $key (${key.toChar()})")
sendKey(key, keyCode, press)
}
fun sendKey(key: Int, code: Int, press: Boolean) {
if (press) {
keyboard.onKeyPress(key, code)
} else {
keyboard.onKeyRelease(key, code)
}
gui.container.detectAndSendChanges()
}
override fun onGuiClosed() {
keyboard.reset()
Keyboard.enableRepeatEvents(false)
}
} | gpl-2.0 | b76c88d4afe00b96d495ee386e328099 | 31.676471 | 134 | 0.505776 | 4.010229 | false | false | false | false |
soniccat/android-taskmanager | tools/src/main/java/com/example/alexeyglushkov/tools/SparceArrayTools.kt | 1 | 1161 | package com.example.alexeyglushkov.tools
import android.os.Bundle
import android.util.SparseArray
/**
* Created by alexeyglushkov on 26.08.16.
*/
object SparceArrayTools {
@JvmStatic
fun storeSparceArray(array: SparseArray<String?>?, bundle: Bundle, id: Int) {
val arrayBundle = Bundle(bundle.classLoader)
val size = array?.size() ?: 0
arrayBundle.putInt("sparceArrayLength", size)
for (i in 0 until array!!.size()) {
arrayBundle.putInt("sparceArrayKey$i", array.keyAt(i))
arrayBundle.putString("sparceArrayValue$i", array.valueAt(i))
}
bundle.putBundle("sparceArray$id", arrayBundle)
}
@JvmStatic
fun readSparceArray(bundle: Bundle, id: Int): SparseArray<String> {
val arrayBundle = bundle.getBundle("sparceArray$id")
val result = SparseArray<String>()
val len = arrayBundle.getInt("sparceArrayLength")
for (i in 0 until len) {
val key = arrayBundle.getInt("sparceArrayKey$i")
val value = arrayBundle.getString("sparceArrayValue$i")
result.put(key, value)
}
return result
}
} | mit | 58a545cb8396d3def07fa39aa17f5fe3 | 33.176471 | 81 | 0.64255 | 3.962457 | false | false | false | false |
programingjd/server | src/main/kotlin/info/jdavid/asynk/server/http/route/NoParams.kt | 1 | 927 | package info.jdavid.asynk.server.http.route
import info.jdavid.asynk.http.Method
import info.jdavid.asynk.server.http.handler.HttpHandler
/**
* Special [Route] implementation that accepts all requests and returns itself for the acceptance parameters.
* This should also be used as the acceptance type when no parameter is needed and a maximum request size
* of 4kb is enough.
*/
object NoParams: HttpHandler.Route<NoParams>, Map<String, String> {
override val maxRequestSize = 4096
override fun match(method: Method, uri: String): NoParams? {
return this
}
override val entries = emptySet<Map.Entry<String,String>>()
override val keys = emptySet<String>()
override val values = emptySet<String>()
override val size = 0
override fun isEmpty() = true
override fun containsKey(key: String) = false
override fun containsValue(value: String) = false
override fun get(key: String) = null
}
| apache-2.0 | ad71d407546ddb00b8dcd8461417bbe7 | 25.485714 | 109 | 0.742179 | 4.175676 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/Call.kt | 1 | 5842 | package com.xiaojinzi.component.impl
import android.app.Activity
import android.content.Intent
import androidx.annotation.AnyThread
import androidx.annotation.CheckResult
import com.xiaojinzi.component.anno.support.CheckClassNameAnno
import com.xiaojinzi.component.bean.ActivityResult
import com.xiaojinzi.component.support.NavigationDisposable
/**
* 这个对象表示一个可调用的路由跳转
*/
@CheckClassNameAnno
interface Call {
/**
* 普通跳转
*/
@AnyThread
fun forward()
/**
* 普通跳转
*
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigate(): NavigationDisposable
/**
* 普通跳转
*
* @param callback 当跳转完毕或者发生错误会回调
*/
@AnyThread
fun forward(callback: Callback?)
/**
* 执行跳转的具体逻辑
* 返回值不可以为空, 是为了使用的时候更加的顺溜,不用判断空
*
* @param callback 当跳转完毕或者发生错误会回调,
* 回调给用户的 [Callback], 回调中的各个方法, 每个方法至多有一个方法被调用, 并且只有一次
* @return 返回的对象有可能是一个空实现对象 [Router.emptyNavigationDisposable],可以取消路由或者获取原始request对象
*/
@AnyThread
@CheckResult
fun navigate(callback: Callback?): NavigationDisposable
/**
* 跳转拿到 [ActivityResult] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
*/
@AnyThread
fun forwardForResult(callback: BiCallback<ActivityResult>)
/**
* 跳转拿到 [ActivityResult] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForResult(callback: BiCallback<ActivityResult>): NavigationDisposable
/**
* 跳转拿到 [Intent] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
*/
@AnyThread
fun forwardForIntent(callback: BiCallback<Intent>)
/**
* 跳转拿到 [Intent] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForIntent(callback: BiCallback<Intent>): NavigationDisposable
/**
* 跳转拿到 [Intent] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @param expectedResultCode 会匹配的 resultCode
*/
@AnyThread
fun forwardForIntentAndResultCodeMatch(
callback: BiCallback<Intent>,
expectedResultCode: Int = Activity.RESULT_OK
)
/**
* 跳转拿到 [Intent] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @param expectedResultCode 会匹配的 resultCode
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForIntentAndResultCodeMatch(
callback: BiCallback<Intent>,
expectedResultCode: Int = Activity.RESULT_OK
): NavigationDisposable
/**
* 跳转为了匹配 [ActivityResult] 中的 [ActivityResult.resultCode]
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @param expectedResultCode 会匹配的 resultCode
*/
@AnyThread
fun forwardForResultCodeMatch(
callback: Callback,
expectedResultCode: Int = Activity.RESULT_OK
)
/**
* 跳转为了匹配 [ActivityResult] 中的 [ActivityResult.resultCode]
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @param expectedResultCode 会匹配的 resultCode
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForResultCodeMatch(
callback: Callback,
expectedResultCode: Int = Activity.RESULT_OK
): NavigationDisposable
/**
* 跳转拿到 [ActivityResult.resultCode] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
*/
@AnyThread
fun forwardForResultCode(callback: BiCallback<Int>)
/**
* 跳转拿到 [ActivityResult.resultCode] 数据
*
* @param callback 当 [ActivityResult] 拿到之后或者发生错误会回调
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForResultCode(callback: BiCallback<Int>): NavigationDisposable
/**
* 跳转, 获取目标的 Intent 的. 不会真正的发起跳转
* @return 可用于取消本次路由
*/
@AnyThread
fun forwardForTargetIntent(callback: BiCallback<Intent>)
/**
* 警告:切勿用作通知或者小部件的 Intent 使用
* 此方法虽然在回调中返回了目标界面的真实 Intent, 但是是经过了整个路由的过程获取到的.
* 甚至目标 Intent 都可能因为参数的不同而不同.
* 所以通知或者小部件, 请使用如下方式, 如下方式不会发起路由. 只会返回一个代理的 Intent 供你使用.
* 当你通过代理 Intent 发起跳转之后, 会发起真实的路由过程
* ```
* val targetProxyIntent = Router
* .newProxyIntentBuilder()
* .putString("name", "testName")
* // .....
* .buildProxyIntent();
* ```
* 跳转, 获取目标的 Intent 的. 不会真正的发起跳转
* @return 可用于取消本次路由
*/
@AnyThread
@CheckResult
fun navigateForTargetIntent(callback: BiCallback<Intent>): NavigationDisposable
} | apache-2.0 | 97101b8b9b950881f2a05f3fb6d08cd9 | 24.103261 | 88 | 0.645518 | 3.627651 | false | false | false | false |
enolive/exercism | kotlin/nth-prime/src/main/kotlin/Prime.kt | 1 | 460 | object Prime {
fun nth(i: Int): Int {
require(i > 0)
return primes().elementAt(i - 1)
}
private fun primes(): Sequence<Int> {
return generateSequence(2) { it + 1 }
.filter { it.isPrime() }
}
}
private fun Int.isPrime() = (2..upperLimit()).all { !divisibleBy(it) }
private fun Int.upperLimit() = Math.sqrt(this.toDouble()).toInt()
private infix fun Int.divisibleBy(divisor: Int) = this % divisor == 0
| mit | 42c488dc27a287bba9ed0ab13e1b6bd8 | 26.058824 | 70 | 0.586957 | 3.565891 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/alphaupdater/AlphaUpdateChecker.kt | 1 | 2946 | package org.wikipedia.alphaupdater
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import okhttp3.Request
import okhttp3.Response
import org.wikipedia.dataclient.okhttp.OkHttpConnectionFactory.client
import org.wikipedia.notifications.NotificationCategory
import org.wikipedia.recurring.RecurringTask
import org.wikipedia.settings.PrefsIoUtil
import org.wikipedia.util.DeviceUtil
import java.io.IOException
import java.util.*
import java.util.concurrent.TimeUnit
class AlphaUpdateChecker(private val context: Context) : RecurringTask() {
override val name = "alpha-update-checker"
override fun shouldRun(lastRun: Date): Boolean {
return System.currentTimeMillis() - lastRun.time >= RUN_INTERVAL_MILLI
}
override fun run(lastRun: Date) {
// Check for updates!
val hashString: String
var response: Response? = null
try {
val request: Request = Request.Builder().url(ALPHA_BUILD_DATA_URL).build()
response = client.newCall(request).execute()
hashString = response.body!!.string()
} catch (e: IOException) {
// It's ok, we can do nothing.
return
} finally {
response?.close()
}
if (PrefsIoUtil.getString(PREFERENCE_KEY_ALPHA_COMMIT, "") != hashString) {
showNotification()
}
PrefsIoUtil.setString(PREFERENCE_KEY_ALPHA_COMMIT, hashString)
}
private fun showNotification() {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(ALPHA_BUILD_APK_URL))
val pintent = PendingIntent.getActivity(context, 0, intent, DeviceUtil.pendingIntentFlags)
val notificationManagerCompat = NotificationManagerCompat.from(context)
val notificationCategory = NotificationCategory.ALPHA_BUILD_CHECKER
val notificationBuilder = NotificationCompat.Builder(context, notificationCategory.id)
.setContentTitle(context.getString(notificationCategory.title))
.setContentText(context.getString(notificationCategory.description))
.setContentIntent(pintent)
.setAutoCancel(true)
notificationBuilder.setSmallIcon(notificationCategory.iconResId)
notificationManagerCompat.notify(1, notificationBuilder.build())
}
companion object {
private val RUN_INTERVAL_MILLI = TimeUnit.DAYS.toMillis(1)
private const val PREFERENCE_KEY_ALPHA_COMMIT = "alpha_last_checked_commit"
private const val ALPHA_BUILD_APK_URL = "https://github.com/wikimedia/apps-android-wikipedia/releases/download/latest/app-alpha-universal-release.apk"
private const val ALPHA_BUILD_DATA_URL = "https://github.com/wikimedia/apps-android-wikipedia/releases/download/latest/rev-hash.txt"
}
}
| apache-2.0 | 2620f18dbd7cf18c1e17988e66192658 | 41.695652 | 158 | 0.716904 | 4.66878 | false | false | false | false |
UnknownJoe796/ponderize | app/src/main/java/com/ivieleague/ponderize/model/Book.kt | 1 | 755 | package com.ivieleague.ponderize.model
import android.database.sqlite.SQLiteDatabase
import java.util.*
/**
* Created by josep on 10/4/2015.
*/
class Book(
var volume: Volume,
var id: Int = 0,
var title: String = "",
var titleJst: String = "",
var titleLong: String = "",
var titleShort: String = "",
var subtitle: String = "",
var urlPart: String = "",
var numChapters: Int = 0,
var verses: Int = 0) {
public val database: SQLiteDatabase get() = volume.database
val chapters: List<Chapter> get() {
val list: ArrayList<Chapter> = ArrayList()
for (i in 1..numChapters) {
list.add(Chapter(this, i))
}
return list
}
} | mit | 4cd2c8307fa61faf828aca2e52942a6a | 25.068966 | 63 | 0.568212 | 3.973684 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/opdefs/TensorflowOpDescriptorLoader.kt | 1 | 5610 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.tensorflow.opdefs
import org.apache.commons.io.IOUtils
import org.nd4j.common.config.ND4JClassLoading
import org.nd4j.common.io.ClassPathResource
import org.nd4j.ir.MapperNamespace
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoader
import org.nd4j.samediff.frameworkimport.opdefs.nd4jFileNameTextDefault
import org.nd4j.samediff.frameworkimport.opdefs.nd4jFileSpecifierProperty
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.samediff.frameworkimport.tensorflow.process.TensorflowMappingProcessLoader
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import org.nd4j.shade.protobuf.TextFormat
import org.tensorflow.framework.*
import java.lang.Exception
import java.nio.charset.Charset
class TensorflowOpDescriptorLoader: OpDescriptorLoader<OpDef> {
val tensorflowFileNameTextDefault = "/tensorflow-op-def.pbtxt"
val tensorflowFileSpecifierProperty = "samediff.import.tensorflowdescriptors"
val tensorflowMappingRulSetDefaultFile = "/tensorflow-mapping-ruleset.pbtxt"
val tensorflowRulesetSpecifierProperty = "samediff.import.tensorflowmappingrules"
val nd4jOpDescriptors = nd4jOpList()
var mapperDefSet: MapperNamespace.MappingDefinitionSet? = mappingProcessDefinitionSet()
var cachedOpList: Map<String,OpDef>? = inputFrameworkOpDescriptorList()
override fun frameworkName(): String {
return "tensorflow"
}
override fun nd4jOpList(): OpNamespace.OpDescriptorList {
val fileName = System.getProperty(nd4jFileSpecifierProperty, nd4jFileNameTextDefault)
val nd4jOpDescriptorResourceStream = ClassPathResource(fileName,ND4JClassLoading.getNd4jClassloader()).inputStream
val resourceString = IOUtils.toString(nd4jOpDescriptorResourceStream, Charset.defaultCharset())
val descriptorListBuilder = OpNamespace.OpDescriptorList.newBuilder()
TextFormat.merge(resourceString,descriptorListBuilder)
val ret = descriptorListBuilder.build()
val mutableList = ArrayList(ret.opListList)
mutableList.sortBy { it.name }
val newResultBuilder = OpNamespace.OpDescriptorList.newBuilder()
newResultBuilder.addAllOpList(mutableList)
return newResultBuilder.build()
}
override fun inputFrameworkOpDescriptorList(): Map<String,OpDef> {
if(cachedOpList != null) {
return cachedOpList!!
}
val fileName = System.getProperty(tensorflowFileSpecifierProperty, tensorflowFileNameTextDefault)
val string = IOUtils.toString(ClassPathResource(fileName,ND4JClassLoading.getNd4jClassloader()).inputStream, Charset.defaultCharset())
val tfListBuilder = OpList.newBuilder()
TextFormat.merge(string, tfListBuilder)
val ret = HashMap<String,OpDef>()
tfListBuilder.build().opList.forEach { opDef ->
ret[opDef.name] = opDef
}
return ret
}
override fun mappingProcessDefinitionSet(): MapperNamespace.MappingDefinitionSet {
if(mapperDefSet != null)
return mapperDefSet!!
val fileName = System.getProperty(tensorflowRulesetSpecifierProperty, tensorflowMappingRulSetDefaultFile)
val string = IOUtils.toString(ClassPathResource(fileName,ND4JClassLoading.getNd4jClassloader()).inputStream, Charset.defaultCharset())
val declarationBuilder = MapperNamespace.MappingDefinitionSet.newBuilder()
try {
TextFormat.merge(string,declarationBuilder)
} catch(e: Exception) {
println("Unable to parse mapper definitions for file file $fileName")
}
return declarationBuilder.build()
}
override fun <GRAPH_TYPE : GeneratedMessageV3, NODE_TYPE : GeneratedMessageV3, OP_DEF_TYPE : GeneratedMessageV3, TENSOR_TYPE : GeneratedMessageV3, ATTR_DEF_TYPE : GeneratedMessageV3, ATTR_VALUE_TYPE : GeneratedMessageV3, DATA_TYPE : ProtocolMessageEnum> createOpMappingRegistry(): OpMappingRegistry<GRAPH_TYPE, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, DATA_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE> {
val tensorflowOpMappingRegistry = OpMappingRegistry<GraphDef,NodeDef,OpDef,TensorProto,DataType,OpDef.AttrDef,AttrValue>("tensorflow",nd4jOpDescriptors)
val loader = TensorflowMappingProcessLoader(tensorflowOpMappingRegistry)
val mappingProcessDefs = mappingProcessDefinitionSet()
tensorflowOpMappingRegistry.loadFromDefinitions(mappingProcessDefs,loader)
return tensorflowOpMappingRegistry as OpMappingRegistry<GRAPH_TYPE, NODE_TYPE, OP_DEF_TYPE, TENSOR_TYPE, DATA_TYPE, ATTR_DEF_TYPE, ATTR_VALUE_TYPE>
}
} | apache-2.0 | f9a26c66d9b95c01357921393e68b957 | 50.953704 | 396 | 0.742068 | 4.553571 | false | false | false | false |
Code-Tome/hexameter | mixite.core/src/commonTest/kotlin/org/hexworks/mixite/core/internal/impl/HexagonalGridImplTest.kt | 2 | 8745 | package org.hexworks.mixite.core.internal.impl
import org.hexworks.mixite.core.api.*
import org.hexworks.mixite.core.api.CubeCoordinate.Companion.fromCoordinates
import org.hexworks.mixite.core.api.HexagonalGridLayout.RECTANGULAR
import org.hexworks.mixite.core.api.defaults.DefaultSatelliteData
import kotlin.test.*
class HexagonalGridImplTest {
private lateinit var target: HexagonalGrid<DefaultSatelliteData>
private lateinit var builder: HexagonalGridBuilder<DefaultSatelliteData>
@BeforeTest
fun setUp() {
builder = HexagonalGridBuilder<DefaultSatelliteData>()
.setGridHeight(GRID_HEIGHT)
.setGridWidth(GRID_WIDTH)
.setRadius(RADIUS.toDouble())
.setOrientation(ORIENTATION)
target = builder.build()
}
@Test
fun shouldReturnHexagonsInProperIterationOrderWhenGetHexagonsIsCalled() {
val expectedCoordinates = ArrayList<CubeCoordinate>()
val actualCoordinates = ArrayList<CubeCoordinate>()
for (cubeCoordinate in builder.gridLayoutStrategy.fetchGridCoordinates(builder)) {
expectedCoordinates.add(cubeCoordinate)
}
for (hexagon in target.hexagons) {
actualCoordinates.add(hexagon.cubeCoordinate)
}
assertEquals(expectedCoordinates, actualCoordinates)
}
@Test
fun shouldReturnProperHexagonsWhenEachHexagonIsTestedInAGivenGrid() {
val hexagons = target.hexagons
val expectedCoordinates = HashSet<String>()
for (x in 0 until GRID_WIDTH) {
for (y in 0 until GRID_HEIGHT) {
val gridX = CoordinateConverter.convertOffsetCoordinatesToCubeX(x, y, ORIENTATION)
val gridZ = CoordinateConverter.convertOffsetCoordinatesToCubeZ(x, y, ORIENTATION)
expectedCoordinates.add("$gridX,$gridZ")
}
}
var count = 0
for (hexagon in hexagons) {
expectedCoordinates.remove("${hexagon.gridX},${hexagon.gridZ}")
count++
}
assertEquals(100, count)
assertTrue(expectedCoordinates.isEmpty())
}
@Test
fun shouldReturnProperHexagonsWhenGetHexagonsByAxialRangeIsCalled() {
val expected = HashSet<Hexagon<DefaultSatelliteData>>()
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 5)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 5)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 5)).get())
val actual = target.getHexagonsByCubeRange(fromCoordinates(GRID_X_FROM, GRID_Z_FROM), fromCoordinates(GRID_X_TO, GRID_Z_TO))
var count = 0
val actuals = ArrayList<Hexagon<DefaultSatelliteData>>()
for (hex in actual) {
actuals.add(hex)
count++
}
assertEquals(expected.size, count)
for (hex in actuals) {
expected.remove(hex)
}
assertTrue(expected.isEmpty())
}
@Test
fun shouldReturnProperHexagonsWhenGetHexagonsByOffsetRangeIsCalled() {
val expected = HashSet<Hexagon<DefaultSatelliteData>>()
expected.add(target.getByCubeCoordinate(fromCoordinates(1, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 3)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(0, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(1, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 4)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(0, 5)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(1, 5)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 5)).get())
val actual = target.getHexagonsByOffsetRange(GRID_X_FROM, GRID_X_TO, GRID_Z_FROM, GRID_Z_TO)
var count = 0
val actuals = ArrayList<Hexagon<DefaultSatelliteData>>()
for (hex in actual) {
actuals.add(hex)
count++
}
assertEquals(expected.size, count)
for (hex in actuals) {
expected.remove(hex)
}
assertTrue(expected.isEmpty())
}
@Test
fun shouldContainCoordinateWhenContainsCoorinateIsCalledWithProperParameters() {
val gridX = 2
val gridZ = 3
assertTrue(target.containsCubeCoordinate(fromCoordinates(gridX, gridZ)))
}
@Test
fun shouldReturnHexagonWhenGetByGridCoordinateIsCalledWithProperCoordinates() {
val gridX = 2
val gridZ = 3
val hex = target.getByCubeCoordinate(fromCoordinates(gridX, gridZ))
assertTrue(hex.isPresent)
}
@Test
fun shouldBeEmptyWhenGetByGridCoordinateIsCalledWithInvalidCoordinates() {
val gridX = 20
val gridZ = 30
val result = target.getByCubeCoordinate(fromCoordinates(gridX, gridZ))
assertFalse(result.isPresent)
}
@Test
fun shouldReturnHexagonWhenCalledWithProperCoordinates() {
val x = 310.0
val y = 255.0
val hex = target.getByPixelCoordinate(x, y).get()
assertEquals(hex.gridX, 3)
assertEquals(hex.gridZ, 5)
}
@Test
fun shouldReturnHexagonWhenCalledWithProperCoordinates2() {
val x = 300.0
val y = 275.0
val hex = target.getByPixelCoordinate(x, y).get()
assertEquals(hex.gridX, 3)
assertEquals(hex.gridZ, 5)
}
@Test
fun shouldReturnHexagonWhenCalledWithProperCoordinates3() {
val x = 325.0
val y = 275.0
val hex = target.getByPixelCoordinate(x, y).get()
assertEquals(hex.gridX, 3)
assertEquals(hex.gridZ, 5)
}
@Test
fun shouldReturnProperNeighborsOfHexagonWhenHexIsInMiddle() {
val hex = target.getByCubeCoordinate(fromCoordinates(3, 7)).get()
val expected = HashSet<Hexagon<DefaultSatelliteData>>()
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 6)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 6)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 7)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(3, 8)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 8)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(2, 7)).get())
val actual = target.getNeighborsOf(hex)
assertEquals(expected, actual)
}
@Test
fun shouldReturnProperNeighborsOfHexagonWhenHexIsOnTheEdge() {
val hex = target.getByCubeCoordinate(fromCoordinates(5, 9)).get()
val expected = HashSet<Hexagon<DefaultSatelliteData>>()
expected.add(target.getByCubeCoordinate(fromCoordinates(5, 8)).get())
expected.add(target.getByCubeCoordinate(fromCoordinates(4, 9)).get())
val actual = target.getNeighborsOf(hex)
assertEquals(expected, actual)
}
@Test
fun shouldProperlyReturnGridLayoutWhenGetGridLayoutIsCalled() {
assertEquals(RECTANGULAR, target.gridData.gridLayout)
}
@Test
fun shouldProperlyReturnSharedHexagonDataWhenGetSharedHexagonDataIsCalled() {
assertEquals(builder.gridData.hexagonHeight, target.gridData.hexagonHeight)
assertEquals(builder.gridData.hexagonWidth, target.gridData.hexagonWidth)
assertEquals(builder.gridData.radius, target.gridData.radius)
assertEquals(builder.gridData.orientation, target.gridData.orientation)
}
@Test
fun shouldProperlyReturnGridWidthWhenGetGridWidthIsCalled() {
assertEquals(GRID_WIDTH, target.gridData.gridWidth)
}
@Test
fun shouldProperlyReturnGridHeightWhenGetGridHeightIsCalled() {
assertEquals(GRID_HEIGHT, target.gridData.gridHeight)
}
companion object {
private const val RADIUS = 30
private const val GRID_WIDTH = 10
private const val GRID_HEIGHT = 10
private const val GRID_X_FROM = 2
private const val GRID_X_TO = 4
private const val GRID_Z_FROM = 3
private const val GRID_Z_TO = 5
private val ORIENTATION = HexagonOrientation.POINTY_TOP
}
}
| mit | e570901d423b30f255fee56547637b48 | 37.355263 | 132 | 0.679131 | 4.470859 | false | true | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/admin/handlers/AjaxAccountsHandler.kt | 1 | 781 | package au.com.codeka.warworlds.server.admin.handlers
import au.com.codeka.warworlds.server.store.DataStore
/**
* Handler for /admin/ajax/accounts, allowing various actions on accounts.
*/
class AjaxAccountsHandler : AjaxHandler() {
public override fun post() {
val empireId = request.getParameter("id").toLong()
val pair = DataStore.i.accounts().getByEmpireId(empireId)
if (pair == null) {
setResponseText("No account for empire #$empireId")
return
}
/*
val account = pair.two
when (request.getParameter("action")) {
"resend" -> {
AccountManager.i.sendVerificationEmail(account)
}
"force-verify" -> {
AccountManager.i.verifyAccount(account)
}
}
*/
setResponseText("success")
}
}
| mit | 05e915acc5fc17fdda1b4db66e9b6482 | 25.033333 | 74 | 0.654289 | 3.944444 | false | false | false | false |
AndroidX/androidx | activity/activity/src/androidTest/java/androidx/activity/ComponentActivityMenuTest.kt | 3 | 10630 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity
import android.os.Build
import android.os.Bundle
import android.view.ContextMenu
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.activity.test.R
import androidx.core.view.MenuProvider
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.longClick
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import leakcanary.DetectLeaksAfterTestSuccess
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) // Previous SDK levels have issues passing
// null menu that causes leak canary to crash to we don't want to run on those devices
@MediumTest
@RunWith(AndroidJUnit4::class)
class ComponentActivityMenuTest {
@get:Rule
val rule = DetectLeaksAfterTestSuccess()
@Test
fun inflatesMenu() {
withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
})
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu2, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
})
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).check(matches(isDisplayed()))
onView(withText("Item2")).check(matches(isDisplayed()))
onView(withText("Item3")).check(matches(isDisplayed()))
onView(withText("Item4")).check(matches(isDisplayed()))
}
}
@Test
fun onPrepareMenu() {
withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var menuPrepared: Boolean
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
override fun onPrepareMenu(menu: Menu) {
menuPrepared = true
}
})
menuPrepared = false
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).perform(click())
assertThat(menuPrepared).isTrue()
}
}
@Test
fun menuItemSelected() {
withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var itemSelectedId: Int? = null
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.item1, R.id.item2 -> {
itemSelectedId = menuItem.itemId
return true
}
else -> false
}
}
})
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).perform(click())
assertThat(itemSelectedId).isEqualTo(R.id.item1)
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu2, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.item3, R.id.item4 -> {
itemSelectedId = menuItem.itemId
return true
}
else -> false
}
}
})
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item3")).perform(click())
assertThat(itemSelectedId).isEqualTo(R.id.item3)
}
}
@Test
fun onMenuClosed() {
withUse(ActivityScenario.launch(ComponentActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var menuClosed = false
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
override fun onMenuClosed(menu: Menu) {
menuClosed = true
}
})
openActionBarOverflowOrOptionsMenu(menuHost)
withActivity { closeOptionsMenu() }
assertThat(menuClosed).isTrue()
}
}
@Test
fun onPanelClosed() {
withUse(ActivityScenario.launch(ContextMenuComponentActivity::class.java)) {
onView(withText("Context Menu")).perform(longClick())
onView(withText("Item1")).check(matches(isDisplayed()))
onView(withText("Item2")).check(matches(isDisplayed()))
pressBack()
val countDownLatch = withActivity { this.contextMenuClosedCountDownLatch }
assertWithMessage("onPanelClosed was not called")
.that(countDownLatch.await(1000, TimeUnit.MILLISECONDS))
.isTrue()
}
}
@Test
fun menuAPIsCalledWithoutCallingSuper() {
withUse(ActivityScenario.launch(OptionMenuNoSuperActivity::class.java)) {
val menuHost: ComponentActivity = withActivity { this }
var itemSelectedId: Int? = null
var menuPrepared = false
var menuCreated = false
var menuItemSelected = false
menuHost.addMenuProvider(object : MenuProvider {
override fun onPrepareMenu(menu: Menu) {
menuPrepared = true
super.onPrepareMenu(menu)
}
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.example_menu, menu)
menuCreated = true
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
menuItemSelected = true
return when (menuItem.itemId) {
R.id.item1, R.id.item2 -> {
itemSelectedId = menuItem.itemId
return true
}
else -> false
}
}
})
openActionBarOverflowOrOptionsMenu(menuHost)
onView(withText("Item1")).perform(click())
assertThat(itemSelectedId).isEqualTo(R.id.item1)
assertThat(menuPrepared).isTrue()
assertThat(menuCreated).isTrue()
assertThat(menuItemSelected).isTrue()
}
}
}
class ContextMenuComponentActivity : ComponentActivity() {
val contextMenuClosedCountDownLatch = CountDownLatch(1)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.context_menu)
val contextMenuTextView = findViewById<TextView>(R.id.context_menu_tv)
registerForContextMenu(contextMenuTextView)
}
override fun onCreateContextMenu(
menu: ContextMenu,
v: View,
menuInfo: ContextMenu.ContextMenuInfo?
) {
super.onCreateContextMenu(menu, v, menuInfo)
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.example_menu, menu)
}
override fun onContextMenuClosed(menu: Menu) {
contextMenuClosedCountDownLatch.countDown()
super.onContextMenuClosed(menu)
}
}
class OptionMenuNoSuperActivity : ComponentActivity() {
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
return true
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// overriding this to not call super
return false
}
}
| apache-2.0 | 3521cb65c5debba3288e1b85ca0c5730 | 35.40411 | 94 | 0.616181 | 5.409669 | false | true | false | false |
colesadam/hill-lists | app/src/main/java/uk/colessoft/android/hilllist/ui/activity/HillListMapActivity.kt | 1 | 1434 | package uk.colessoft.android.hilllist.ui.activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.ViewModelProviders
import uk.colessoft.android.hilllist.R
import uk.colessoft.android.hilllist.ui.activity.dialogs.BaseActivity
import uk.colessoft.android.hilllist.ui.fragment.HillListFragment
import uk.colessoft.android.hilllist.ui.fragment.HillDetailFragment
import uk.colessoft.android.hilllist.ui.viewmodel.HillListViewModel
import uk.colessoft.android.hilllist.ui.viewmodel.ViewModelFactory
import javax.inject.Inject
class HillListMapActivity : BaseActivity(), HillListFragment.OnHillSelectedListener {
@Inject
lateinit var vmFactory: ViewModelFactory<HillListViewModel>
lateinit var vm: HillListViewModel
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
vm = ViewModelProviders.of(this, vmFactory)[HillListViewModel::class.java]
setContentView(R.layout.hills_map_fragment)
}
override fun onHillSelected(hillId: Long) {
val fragment = supportFragmentManager
.findFragmentById(R.id.hill_detail_fragment) as HillDetailFragment?
if (fragment == null || !fragment.isInLayout) {
val intent = Intent(this, HillDetailActivity::class.java)
intent.putExtra("rowid", hillId)
startActivity(intent)
} else {
vm.select(hillId)
}
}
}
| mit | b399121239ea5ff323192d522c37a770 | 30.866667 | 85 | 0.739888 | 4.280597 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/ide/inspections/FortranProgramUnitNameMismatchInspection.kt | 1 | 1612 | package org.jetbrains.fortran.ide.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.fortran.ide.inspections.fixes.SubstituteTextFix
import org.jetbrains.fortran.lang.psi.FortranProgramUnit
import org.jetbrains.fortran.lang.psi.FortranVisitor
import org.jetbrains.fortran.lang.psi.ext.beginUnitStmt
import org.jetbrains.fortran.lang.psi.ext.endUnitStmt
import org.jetbrains.fortran.lang.psi.ext.smartPointer
class FortranProgramUnitNameMismatchInspection : LocalInspectionTool() {
override fun getDisplayName() = "Program unit name mismatch"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : FortranVisitor() {
override fun visitProgramUnit(unit: FortranProgramUnit) {
val stmtName = unit.beginUnitStmt?.entityDecl?.name
val endStmtDataPath = unit.endUnitStmt?.dataPath
if (endStmtDataPath != null && !endStmtDataPath.referenceName.equals(stmtName, true)) {
registerProblemForReference(
holder,
endStmtDataPath.reference,
ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
"Program unit name mismatch",
SubstituteTextFix(endStmtDataPath.smartPointer(), stmtName, "Fix unit name")
)
}
}
}
}
| apache-2.0 | 1d80c8e7d574677dc881f4800290c689 | 47.848485 | 108 | 0.654467 | 5.320132 | false | false | false | false |
stoyicker/dinger | data/src/main/kotlin/data/tinder/recommendation/RecommendationResponseObjectMapper.kt | 1 | 10314 | package data.tinder.recommendation
import data.ObjectMapper
import domain.DomainException
import domain.recommendation.DomainRecommendationCommonFriend
import domain.recommendation.DomainRecommendationCommonFriendPhoto
import domain.recommendation.DomainRecommendationCompany
import domain.recommendation.DomainRecommendationInstagram
import domain.recommendation.DomainRecommendationInstagramPhoto
import domain.recommendation.DomainRecommendationJob
import domain.recommendation.DomainRecommendationLike
import domain.recommendation.DomainRecommendationPhoto
import domain.recommendation.DomainRecommendationProcessedFile
import domain.recommendation.DomainRecommendationSchool
import domain.recommendation.DomainRecommendationSpotifyAlbum
import domain.recommendation.DomainRecommendationSpotifyArtist
import domain.recommendation.DomainRecommendationSpotifyThemeTrack
import domain.recommendation.DomainRecommendationTeaser
import domain.recommendation.DomainRecommendationTitle
import domain.recommendation.DomainRecommendationUser
internal class RecommendationResponseObjectMapper(
private val eventTracker: RecommendationEventTracker,
private val commonFriendDelegate
: ObjectMapper<RecommendationUserCommonFriend, DomainRecommendationCommonFriend>,
private val instagramDelegate
: ObjectMapper<RecommendationUserInstagram?, DomainRecommendationInstagram?>,
private val teaserDelegate
: ObjectMapper<RecommendationUserTeaser, DomainRecommendationTeaser>,
private val spotifyThemeTrackDelegate
: ObjectMapper<RecommendationUserSpotifyThemeTrack?, DomainRecommendationSpotifyThemeTrack?>,
private val commonLikeDelegate
: ObjectMapper<RecommendationLike, DomainRecommendationLike>,
private val photoDelegate
: ObjectMapper<RecommendationUserPhoto, DomainRecommendationPhoto>,
private val jobDelegate: ObjectMapper<RecommendationUserJob, DomainRecommendationJob>,
private val schoolDelegate: ObjectMapper<RecommendationUserSchool,
DomainRecommendationSchool>)
: ObjectMapper<RecommendationResponse, List<DomainRecommendationUser>> {
override fun from(source: RecommendationResponse): List<DomainRecommendationUser> =
source.let {
eventTracker.track(it)
return it.recommendations.let {
when (it) {
null -> throw when (source.message) {
is String -> DomainException(source.message)
else -> IllegalStateException(
"Unexpected 2xx (${source.status}) recommendation response without message." +
"Array size: ${source.recommendations?.size ?: 0}")
}
else -> it.map { transformRecommendation(it) }
}
}
}
private fun transformRecommendation(source: Recommendation) = DomainRecommendationUser(
bio = source.bio,
distanceMiles = source.distanceMiles,
commonFriendCount = source.commonFriendCount,
commonFriends = source.commonFriends.map {
commonFriendDelegate.from(it)
},
commonLikeCount = source.commonLikeCount,
commonLikes = source.commonLikes.map {
commonLikeDelegate.from(it)
},
id = source.id,
birthDate = source.birthDate,
name = source.name,
instagram = instagramDelegate.from(source.instagram),
teaser = teaserDelegate.from(source.teaser),
spotifyThemeTrack = spotifyThemeTrackDelegate.from(source.spotifyThemeTrack),
gender = source.gender,
birthDateInfo = source.birthDateInfo,
contentHash = source.contentHash,
groupMatched = source.groupMatched,
sNumber = source.sNumber,
photos = source.photos.map { photoDelegate.from(it) },
jobs = source.jobs.map { jobDelegate.from(it) },
schools = source.schools.map { schoolDelegate.from(it) },
teasers = source.teasers.map { teaserDelegate.from(it) })
}
internal class RecommendationUserCommonFriendObjectMapper(
private val commonFriendPhotoDelegate
: ObjectMapper<RecommendationUserCommonFriendPhoto, DomainRecommendationCommonFriendPhoto>)
: ObjectMapper<RecommendationUserCommonFriend, DomainRecommendationCommonFriend> {
override fun from(source: RecommendationUserCommonFriend) =
DomainRecommendationCommonFriend(
id = source.id,
name = source.name,
degree = source.degree,
photos = source.photos?.map { commonFriendPhotoDelegate.from(it) })
}
internal class RecommendationUserCommonFriendPhotoObjectMapper
: ObjectMapper<RecommendationUserCommonFriendPhoto, DomainRecommendationCommonFriendPhoto> {
override fun from(source: RecommendationUserCommonFriendPhoto) =
DomainRecommendationCommonFriendPhoto(
small = source.small,
medium = source.medium,
large = source.large)
}
internal class RecommendationInstagramObjectMapper(
private val instagramPhotoDelegate
: ObjectMapper<RecommendationUserInstagramPhoto, DomainRecommendationInstagramPhoto>)
: ObjectMapper<RecommendationUserInstagram?, DomainRecommendationInstagram?> {
override fun from(source: RecommendationUserInstagram?) = source?.let {
DomainRecommendationInstagram(
profilePictureUrl = it.profilePictureUrl,
lastFetchTime = it.lastFetchTime,
mediaCount = it.mediaCount,
completedInitialFetch = it.completedInitialFetch,
username = it.username,
photos = it.photos?.map { instagramPhotoDelegate.from(it) })
}
}
internal class RecommendationInstagramPhotoObjectMapper
: ObjectMapper<RecommendationUserInstagramPhoto, DomainRecommendationInstagramPhoto> {
override fun from(source: RecommendationUserInstagramPhoto) =
DomainRecommendationInstagramPhoto(
link = source.link,
imageUrl = source.imageUrl,
thumbnailUrl = source.thumbnailUrl,
ts = source.ts)
}
internal class RecommendationTeaserObjectMapper
: ObjectMapper<RecommendationUserTeaser, DomainRecommendationTeaser> {
override fun from(source: RecommendationUserTeaser) =
DomainRecommendationTeaser(
id = RecommendationUserTeaserEntity.createId(
description = source.description,
type = source.type),
description = source.description,
type = source.type)
}
internal class RecommendationSpotifyThemeTrackObjectMapper(
private val albumDelegate
: ObjectMapper<RecommendationUserSpotifyThemeTrackAlbum, DomainRecommendationSpotifyAlbum>,
private val artistDelegate
: ObjectMapper<RecommendationUserSpotifyThemeTrackArtist, DomainRecommendationSpotifyArtist>)
: ObjectMapper<RecommendationUserSpotifyThemeTrack?, DomainRecommendationSpotifyThemeTrack?> {
override fun from(source: RecommendationUserSpotifyThemeTrack?) = source?.let {
DomainRecommendationSpotifyThemeTrack(
album = albumDelegate.from(it.album),
artists = it.artists.map { artistDelegate.from(it) },
id = it.id,
name = it.name,
previewUrl = it.previewUrl,
uri = it.uri)
}
}
internal class RecommendationSpotifyThemeTrackAlbumObjectMapper(
private val processedFileDelegate
: ObjectMapper<RecommendationUserPhotoProcessedFile, DomainRecommendationProcessedFile>)
: ObjectMapper<RecommendationUserSpotifyThemeTrackAlbum, DomainRecommendationSpotifyAlbum> {
override fun from(source: RecommendationUserSpotifyThemeTrackAlbum) =
DomainRecommendationSpotifyAlbum(
id = source.id,
name = source.name,
images = source.images.map { processedFileDelegate.from(it) })
}
internal class RecommendationProcessedFileObjectMapper
: ObjectMapper<RecommendationUserPhotoProcessedFile, DomainRecommendationProcessedFile> {
override fun from(source: RecommendationUserPhotoProcessedFile) =
DomainRecommendationProcessedFile(
widthPx = source.widthPx,
url = source.url,
heightPx = source.heightPx)
}
internal class RecommendationSpotifyThemeTrackArtistObjectMapper
: ObjectMapper<RecommendationUserSpotifyThemeTrackArtist, DomainRecommendationSpotifyArtist> {
override fun from(source: RecommendationUserSpotifyThemeTrackArtist) =
DomainRecommendationSpotifyArtist(id = source.id, name = source.name)
}
internal class RecommendationLikeObjectMapper
: ObjectMapper<RecommendationLike, DomainRecommendationLike> {
override fun from(source: RecommendationLike) =
DomainRecommendationLike(id = source.id, name = source.name)
}
internal class RecommendationPhotoObjectMapper(
private val processedFileDelegate
: ObjectMapper<RecommendationUserPhotoProcessedFile, DomainRecommendationProcessedFile>)
: ObjectMapper<RecommendationUserPhoto, DomainRecommendationPhoto> {
override fun from(source: RecommendationUserPhoto) = DomainRecommendationPhoto(
id = source.id,
url = source.url,
processedFiles = source.processedFiles.map { processedFileDelegate.from(it) })
}
internal class RecommendationJobObjectMapper(
private val companyDelegate: ObjectMapper<RecommendationUserJobCompany, DomainRecommendationCompany>,
private val titleDelegate: ObjectMapper<RecommendationUserJobTitle, DomainRecommendationTitle>)
: ObjectMapper<RecommendationUserJob, DomainRecommendationJob> {
override fun from(source: RecommendationUserJob) = DomainRecommendationJob(
id = RecommendationUserJob.createId(source.company, source.title),
company = source.company?.let { companyDelegate.from(it) },
title = source.title?.let { titleDelegate.from(it) })
}
internal class RecommendationJobCompanyObjectMapper
: ObjectMapper<RecommendationUserJobCompany, DomainRecommendationCompany> {
override fun from(source: RecommendationUserJobCompany) = DomainRecommendationCompany(
name = source.name
)
}
internal class RecommendationJobTitleObjectMapper
: ObjectMapper<RecommendationUserJobTitle, DomainRecommendationTitle> {
override fun from(source: RecommendationUserJobTitle) = DomainRecommendationTitle(
name = source.name
)
}
internal class RecommendationSchoolObjectMapper
: ObjectMapper<RecommendationUserSchool, DomainRecommendationSchool> {
override fun from(source: RecommendationUserSchool) = DomainRecommendationSchool(
id = source.id,
name = source.name)
}
| mit | b1c653a2c7480d1b74f617cb6c4f7332 | 43.843478 | 105 | 0.774481 | 5.305556 | false | false | false | false |
pthomain/SharedPreferenceStore | lib/src/main/java/uk/co/glass_software/android/shared_preferences/persistence/serialisation/Base64Serialiser.kt | 1 | 4264 | /*
* Copyright (C) 2017 Glass Software Ltd
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF 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.
*/
package uk.co.glass_software.android.shared_preferences.persistence.serialisation
import android.util.Base64
import uk.co.glass_software.android.boilerplate.core.utils.log.Logger
import java.io.*
class Base64Serialiser(private val logger: Logger,
private val base64: CustomBase64) : Serialiser {
override fun canHandleType(targetClass: Class<*>) =
targetClass.isPrimitive || Serializable::class.java.isAssignableFrom(targetClass)
override fun canHandleSerialisedFormat(serialised: String) =
serialised.startsWith(PREFIX) && serialised.contains(DELIMITER)
@Throws(Serialiser.SerialisationException::class)
override fun <O : Any> serialise(deserialised: O): String {
val targetClass = deserialised::class.java
require(canHandleType(targetClass)) {
"Cannot serialise objects of type:$targetClass"
}
try {
ByteArrayOutputStream().use { bos ->
ObjectOutputStream(bos).use {
it.writeObject(deserialised)
val valueBytes = bos.toByteArray()
return base64.encode(valueBytes, Base64.DEFAULT).let {
format(it, targetClass)
}
}
}
} catch (e: IOException) {
logger.e(this, e)
throw Serialiser.SerialisationException(e)
}
}
@Suppress("UNCHECKED_CAST")
@Throws(Serialiser.SerialisationException::class)
override fun <O> deserialise(serialised: String,
targetClass: Class<O>): O {
try {
val read = read(serialised)
if (targetClass != read[0]) {
throw Serialiser.SerialisationException(
"Serialised class didn't match: expected: "
+ targetClass
+ "; serialised: "
+ read[0]
)
}
return base64.decode(read[1] as String, Base64.DEFAULT).let {
ByteArrayInputStream(it).use { bis ->
ObjectInputStream(bis).use {
it.readObject()
}
}
} as O
} catch (e: Exception) {
logger.e(this, e)
throw Serialiser.SerialisationException(e)
}
}
private fun format(base64: String,
objectClass: Class<*>) =
"$PREFIX${objectClass.canonicalName}$DELIMITER$base64"
@Throws(ClassNotFoundException::class)
private fun read(base64: String): Array<Any> {
if (canHandleSerialisedFormat(base64)) {
val payload = base64.substring(base64.indexOf(DELIMITER) + DELIMITER.length)
val className = base64.substring(base64.indexOf(PREFIX) + PREFIX.length, base64.indexOf(DELIMITER))
val targetClass = Class.forName(className)
return arrayOf(targetClass, payload)
}
throw IllegalArgumentException("Not a Base64 string: $base64")
}
interface CustomBase64 {
fun encode(input: ByteArray, flags: Int): String
fun decode(input: String, flags: Int): ByteArray
}
private companion object {
private const val PREFIX = "BASE_64_"
private const val DELIMITER = "_START_DATA_"
}
} | apache-2.0 | bf0ec1a6f38a1e0e81c43d10d41aff33 | 36.743363 | 111 | 0.606942 | 4.769575 | false | false | false | false |
jvsegarra/kotlin-koans | test/ii_collections/TestShop.kt | 9 | 2045 | package ii_collections.data
import ii_collections.*
import ii_collections.shopBuilders.*
//products
val idea = Product("IntelliJ IDEA Ultimate", 199.0)
val reSharper = Product("ReSharper", 149.0)
val dotTrace = Product("DotTrace", 159.0)
val dotMemory = Product("DotTrace", 129.0)
val dotCover = Product("DotCover", 99.0)
val appCode = Product("AppCode", 99.0)
val phpStorm = Product("PhpStorm", 99.0)
val pyCharm = Product("PyCharm", 99.0)
val rubyMine = Product("RubyMine", 99.0)
val webStorm = Product("WebStorm", 49.0)
val teamCity = Product("TeamCity", 299.0)
val youTrack = Product("YouTrack", 500.0)
//customers
val lucas = "Lucas"
val cooper = "Cooper"
val nathan = "Nathan"
val reka = "Reka"
val bajram = "Bajram"
val asuka = "Asuka"
//cities
val Canberra = City("Canberra")
val Vancouver = City("Vancouver")
val Budapest = City("Budapest")
val Ankara = City("Ankara")
val Tokyo = City("Tokyo")
val shop = shop("test shop") {
customer(lucas, Canberra) {
order(reSharper)
order(reSharper, dotMemory, dotTrace)
}
customer(cooper, Canberra) {}
customer(nathan, Vancouver) {
order(rubyMine, webStorm)
}
customer(reka, Budapest) {
order(isDelivered = false, products = idea)
order(isDelivered = false, products = idea)
order(idea)
}
customer(bajram, Ankara) {
order(reSharper)
}
customer(asuka, Tokyo) {
order(idea)
}
}
val customers: Map<String, Customer> = shop.customers.fold(hashMapOf<String, Customer>(), {
map, customer ->
map[customer.name] = customer
map
})
val orderedProducts = setOf(idea, reSharper, dotTrace, dotMemory, rubyMine, webStorm)
val sortedCustomers = listOf(cooper, nathan, bajram, asuka, lucas, reka).map { customers[it] }
val groupedByCities = mapOf(
Canberra to listOf(lucas, cooper),
Vancouver to listOf(nathan),
Budapest to listOf(reka),
Ankara to listOf(bajram),
Tokyo to listOf(asuka)
).mapValues { it.value.map { name -> customers[name] } }
| mit | bdf1b2463f4414eb915f91ba184a79b7 | 27.013699 | 94 | 0.667971 | 3.146154 | false | false | false | false |
darkpaw/boss_roobot | src/org/darkpaw/ld33/mobs/BossMob.kt | 1 | 1412 | package org.darkpaw.ld33.mobs
import org.darkpaw.ld33.GameWorld
import org.darkpaw.ld33.Vector
import org.darkpaw.ld33.sprites.RooSprite
class BossMob(gw : GameWorld, val sprite : RooSprite) {
val game_world = gw
var position = Vector()
var boss_delta = Vector()
var reload_timer = ActionTimer()
var reloading : Boolean = false
val cycle_time = 2400
var HP = 0
var cycle_angle = 0.0
init { reset() }
fun reset(){
HP = 500
position = Vector(game_world.width * 0.6, game_world.height - 175.0)
reloading = false
}
fun draw(){
val draw_position = Vector(position.x - sprite.size_on_screen / 2, position.y - sprite.size_on_screen)
sprite.draw(draw_position)
}
fun move(frame_count : Long){
val frames = frame_count.mod(cycle_time)
val frames_degrees : Double = frames / cycle_time.toDouble() * 180.0
cycle_angle = frames_degrees
reload_timer.tick()
reloading = ! reload_timer.expired
val y = (Math.sin(frames_degrees) + 1) / 2.0 // normalised to range 0.0 .. 1.0
val new_pos_x = game_world.width * 0.75 + y * 80.0
val new_pos_y = game_world.height + 20.0 - y * 0.5 * game_world.height
position = Vector(new_pos_x, new_pos_y)
}
fun fire(){
reload_timer.set(game_world.target_fps * 2.4)
reloading = true
}
} | agpl-3.0 | 92bcc31ff4f4e56724e96efa6c506992 | 24.690909 | 110 | 0.605524 | 3.306792 | false | false | false | false |
jean79/yested | src/main/kotlin/net/yested/bootstrap/buttongroup.kt | 2 | 1531 | package net.yested.bootstrap
import net.yested.*
/**
* Created by jean on 24.12.2014.
* <div class="btn-group" role="group" aria-label="...">
<button type="button" class="btn btn-default">Left</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
*/
class ButtonGroup(val size: ButtonSize = ButtonSize.DEFAULT, val onSelect:Function1<String, Unit>? = null) : Component {
override val element = createElement("div")
private val buttons = HashMap<String, BtsButton>()
init {
element.setAttribute("class", "btn-group")
element.setAttribute("role", "group")
}
var value:String? = null
fun select(selectValue:String) {
value = selectValue
onSelect?.invoke(selectValue)
for ((key, button) in buttons) {
if (key == selectValue) {
button.active = true
} else {
button.active = false
}
}
}
fun button(value:String, look: ButtonLook = ButtonLook.DEFAULT, label : HTMLComponent.() -> Unit) {
val button = BtsButton(label = label, look = look, size = size) {
select(value)
}
element.appendComponent(button)
buttons.put(value, button)
}
}
fun HTMLComponent.buttonGroup(size: ButtonSize = ButtonSize.DEFAULT, onSelect:Function1<String, Unit>? = null, init:ButtonGroup.() -> Unit) {
+(ButtonGroup(size = size, onSelect = onSelect) with init)
} | mit | 0aa7b651c8b5b3b10e4876d4668d0e29 | 29.64 | 142 | 0.621816 | 3.885787 | false | false | false | false |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/util/TimeUtils.kt | 1 | 1923 | /*
* Copyright (c) 2017 52inc.
*
* 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.ftinc.kit.util
object TimeUtils {
private const val SECOND = 1000
private const val MINUTE = 60 * SECOND
private const val HOUR = 60 * MINUTE
private const val DAY = 24 * HOUR
/**
* Get a timestamp in a an *ago format
* e.g.; "just now", "a minute ago", "5 minutes ago", "10 hours ago", "2 days ago", etc...
* @param time the time to format
* @return the formatted time
*/
fun getRelativeTimeSpan(time: Long): String? {
var _time = time
// If time is in seconds, convert to milliseconds
if (_time < 1000000000000L) {
_time *= 1000
}
val now = System.currentTimeMillis()
if (_time > now || _time <= 0) {
return null
}
val diff = now - _time
return if (diff < MINUTE) {
"just now"
} else if (diff < 2 * MINUTE) {
"a minute ago"
} else if (diff < 50 * MINUTE) {
(diff / MINUTE).toString() + " minutes ago"
} else if (diff < 90 * MINUTE) {
"an hour ago"
} else if (diff < 24 * HOUR) {
(diff / HOUR).toString() + " hours ago"
} else if (diff < 48 * HOUR) {
"yesterday"
} else {
(diff / DAY).toString() + " days ago"
}
}
}
| apache-2.0 | 09f5bc44356dc0c586b32349f7d40916 | 29.046875 | 94 | 0.570463 | 4.00625 | false | false | false | false |
anlun/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/HaskellDebugProcess.kt | 1 | 14113 | package org.jetbrains.haskell.debugger
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.execution.ui.ExecutionConsole
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.XSourcePosition
import com.intellij.execution.process.ProcessHandler
import com.intellij.xdebugger.breakpoints.XBreakpointProperties
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.intellij.xdebugger.breakpoints.XBreakpointHandler
import com.intellij.execution.ui.ConsoleView
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointType
import org.jetbrains.haskell.debugger.breakpoints.HaskellLineBreakpointHandler
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.Condition
import org.jetbrains.haskell.debugger.utils.HaskellUtils
import org.jetbrains.haskell.debugger.highlighting.HsDebugSessionListener
import org.jetbrains.haskell.debugger.parser.LocalBinding
import java.util.concurrent.locks.ReentrantLock
import org.jetbrains.haskell.debugger.protocol.ForceCommand
import org.jetbrains.haskell.debugger.config.HaskellDebugSettings
import com.intellij.xdebugger.ui.XDebugTabLayouter
import com.intellij.openapi.actionSystem.DefaultActionGroup
import org.jetbrains.haskell.debugger.protocol.SyncCommand
import org.jetbrains.haskell.debugger.utils.SyncObject
import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointHandler
import org.jetbrains.haskell.debugger.breakpoints.HaskellExceptionBreakpointProperties
import java.util.ArrayList
import org.jetbrains.haskell.debugger.protocol.BreakpointListCommand
import org.jetbrains.haskell.debugger.protocol.SetBreakpointByIndexCommand
import org.jetbrains.haskell.debugger.protocol.SetBreakpointCommand
import org.jetbrains.haskell.debugger.parser.BreakInfo
import com.intellij.notification.Notifications
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.xdebugger.impl.actions.StepOutAction
import com.intellij.xdebugger.impl.actions.ForceStepIntoAction
import org.jetbrains.haskell.debugger.procdebuggers.ProcessDebugger
import org.jetbrains.haskell.debugger.procdebuggers.GHCiDebugger
import org.jetbrains.haskell.debugger.procdebuggers.RemoteDebugger
import org.jetbrains.haskell.debugger.history.HistoryManager
import org.jetbrains.haskell.debugger.prochandlers.HaskellDebugProcessHandler
import com.intellij.execution.ui.RunnerLayoutUi
import java.util.Deque
import com.intellij.xdebugger.frame.XSuspendContext
import java.util.ArrayDeque
import org.jetbrains.haskell.debugger.procdebuggers.utils.DefaultRespondent
import org.jetbrains.haskell.debugger.procdebuggers.utils.DebugRespondent
import com.intellij.xdebugger.impl.XDebugSessionImpl
import org.jetbrains.haskell.repl.HaskellConsole
/**
* Main class for managing debug process and sending commands to real debug process through it's ProcessDebugger member.
*
* Attention! When sending commands to the underlying ProcessDebugger they are enqueued. But some commands may require
* a lot of time to finish and, for example, if you call asynchronous command that needs much time to finish and
* after that call synchronous command that freezes UI thread, you will get all the UI frozen until the first
* command is finished. To check no command is in progress use
* {@link org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand}
*
* @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand
*/
public class HaskellDebugProcess(session: XDebugSession,
val executionConsole: ExecutionConsole,
val _processHandler: HaskellDebugProcessHandler,
val stopAfterTrace: Boolean)
: XDebugProcess(session) {
//public val historyManager: HistoryManager = HistoryManager(session , this)
public var exceptionBreakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>? = null
private set
public val debugger: ProcessDebugger
private val debugRespondent: DebugRespondent = DefaultRespondent(this)
private val contexts: Deque<XSuspendContext> = ArrayDeque()
private val debugProcessStateUpdater: DebugProcessStateUpdater
private val _editorsProvider: XDebuggerEditorsProvider = HaskellDebuggerEditorsProvider()
private val _breakpointHandlers: Array<XBreakpointHandler<*>> = arrayOf(HaskellLineBreakpointHandler(getSession()!!.getProject(), javaClass<HaskellLineBreakpointType>(), this),
HaskellExceptionBreakpointHandler(this)
)
private val registeredBreakpoints: MutableMap<BreakpointPosition, BreakpointEntry> = hashMapOf()
private val BREAK_BY_INDEX_ERROR_MSG = "Only remote debugger supports breakpoint setting by index"
init {
val debuggerIsGHCi = HaskellDebugSettings.getInstance().getState().debuggerType ==
HaskellDebugSettings.Companion.DebuggerType.GHCI
if (debuggerIsGHCi) {
debugProcessStateUpdater = GHCiDebugProcessStateUpdater()
debugger = GHCiDebugger(debugRespondent, _processHandler,
executionConsole as ConsoleView,
debugProcessStateUpdater.INPUT_READINESS_PORT)
debugProcessStateUpdater.debugger = debugger
} else {
debugProcessStateUpdater = RemoteDebugProcessStateUpdater()
debugger = RemoteDebugger(debugRespondent, _processHandler)
debugProcessStateUpdater.debugger = debugger
}
_processHandler.setDebugProcessListener(debugProcessStateUpdater)
}
// XDebugProcess methods overriding
override fun getEditorsProvider(): XDebuggerEditorsProvider = _editorsProvider
override fun getBreakpointHandlers()
: Array<XBreakpointHandler<out XBreakpoint<out XBreakpointProperties<*>?>?>> = _breakpointHandlers
override fun doGetProcessHandler(): ProcessHandler? = _processHandler
override fun createConsole(): ExecutionConsole = executionConsole
override fun startStepOver() = debugger.stepOver()
override fun startStepInto() = debugger.stepInto()
override fun startStepOut() {
val msg = "'Step out' not implemented"
Notifications.Bus.notify(Notification("", "Debug execution error", msg, NotificationType.WARNING))
getSession()!!.positionReached(getSession()!!.getSuspendContext()!!)
}
override fun stop() {
//historyManager.clean()
debugger.close()
debugProcessStateUpdater.close()
}
override fun resume() = debugger.resume()
override fun runToPosition(position: XSourcePosition) =
debugger.runToPosition(
HaskellUtils.getModuleName(getSession()!!.getProject(), position.getFile()),
HaskellUtils.zeroBasedToHaskellLineNumber(position.getLine()))
override fun sessionInitialized() {
super<XDebugProcess>.sessionInitialized()
val currentSession = getSession()
currentSession?.addSessionListener(HsDebugSessionListener(currentSession))
debugger.prepareDebugger()
if (stopAfterTrace) {
debugger.trace(null)
}
}
override fun createTabLayouter(): XDebugTabLayouter = object : XDebugTabLayouter() {
override fun registerAdditionalContent(ui: RunnerLayoutUi) {
//historyManager.registerContent(ui)
}
}
override fun registerAdditionalActions(leftToolbar: DefaultActionGroup, topToolbar: DefaultActionGroup) {
//temporary code for removal of unused actions from debug panel
var stepOut: StepOutAction? = null
var forceStepInto: ForceStepIntoAction? = null
for (action in topToolbar.getChildActionsOrStubs()) {
if (action is StepOutAction) {
stepOut = action
}
if (action is ForceStepIntoAction) {
forceStepInto = action
}
}
topToolbar.remove(stepOut)
topToolbar.remove(forceStepInto)
//historyManager.registerActions(topToolbar)
}
// Class' own methods
public fun startTrace(line: String?) {
//historyManager.saveState()
val context = getSession()!!.getSuspendContext()
if (context != null) {
contexts.add(context)
}
// disable actions
debugger.trace(line)
}
public fun traceFinished() {
/*
if (historyManager.hasSavedStates()) {
historyManager.loadState()
if (!contexts.isEmpty()) {
getSession()!!.positionReached(contexts.pollLast()!!)
}
} else if (stopAfterTrace) {
getSession()!!.stop()
} else {
}
*/
}
public fun isReadyForNextCommand(): Boolean = debugger.isReadyForNextCommand()
public fun addExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) {
exceptionBreakpoint = breakpoint
debugger.setExceptionBreakpoint(breakpoint.getProperties()!!.getState().exceptionType ==
HaskellExceptionBreakpointProperties.ExceptionType.ERROR)
}
public fun removeExceptionBreakpoint(breakpoint: XBreakpoint<HaskellExceptionBreakpointProperties>) {
assert(breakpoint == exceptionBreakpoint)
exceptionBreakpoint = null
debugger.removeExceptionBreakpoint()
}
public fun setBreakpointNumberAtLine(breakpointNumber: Int, module: String, line: Int) {
val entry = registeredBreakpoints.get(BreakpointPosition(module, line))
if (entry != null) {
entry.breakpointNumber = breakpointNumber
}
}
public fun getBreakpointAtPosition(module: String, line: Int): XLineBreakpoint<XBreakpointProperties<*>>? =
registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpoint
public fun addBreakpoint(module: String, line: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) {
registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(null, breakpoint))
debugger.setBreakpoint(module, line)
}
public fun addBreakpointByIndex(module: String, index: Int, breakpoint: XLineBreakpoint<XBreakpointProperties<*>>) {
if (HaskellDebugSettings.getInstance().getState().debuggerType == HaskellDebugSettings.Companion.DebuggerType.REMOTE) {
val line = HaskellUtils.zeroBasedToHaskellLineNumber(breakpoint.getLine())
registeredBreakpoints.put(BreakpointPosition(module, line), BreakpointEntry(index, breakpoint))
val command = SetBreakpointByIndexCommand(module, index, SetBreakpointCommand.Companion.StandardSetBreakpointCallback(module, debugRespondent))
debugger.enqueueCommand(command)
} else {
throw RuntimeException(BREAK_BY_INDEX_ERROR_MSG)
}
}
public fun removeBreakpoint(module: String, line: Int) {
val breakpointNumber: Int? = registeredBreakpoints.get(BreakpointPosition(module, line))?.breakpointNumber
if (breakpointNumber != null) {
registeredBreakpoints.remove(BreakpointPosition(module, line))
debugger.removeBreakpoint(module, breakpointNumber)
}
}
public fun forceSetValue(localBinding: LocalBinding) {
if (localBinding.name != null) {
val syncObject: Lock = ReentrantLock()
val bindingValueIsSet: Condition = syncObject.newCondition()
val syncLocalBinding: LocalBinding = LocalBinding(localBinding.name, "", null)
syncObject.lock()
try {
/*
historyManager.withRealFrameUpdate {
debugger.force(localBinding.name!!,
ForceCommand.StandardForceCallback(syncLocalBinding, syncObject, bindingValueIsSet, this))
}
*/
while (syncLocalBinding.value == null) {
bindingValueIsSet.await()
}
if (syncLocalBinding.value?.isNotEmpty() ?: false) {
localBinding.value = syncLocalBinding.value
}
} finally {
syncObject.unlock()
}
}
}
public fun syncBreakListForLine(moduleName: String, lineNumber: Int): ArrayList<BreakInfo> {
if (HaskellDebugSettings.getInstance().getState().debuggerType == HaskellDebugSettings.Companion.DebuggerType.REMOTE) {
val syncObject = SyncObject()
val resultArray: ArrayList<BreakInfo> = ArrayList()
val callback = BreakpointListCommand.Companion.DefaultCallback(resultArray)
val command = BreakpointListCommand(moduleName, lineNumber, syncObject, callback)
syncCommand(command, syncObject)
return resultArray
}
return ArrayList()
}
private class BreakpointPosition(val module: String, val line: Int) {
override fun equals(other: Any?): Boolean {
if (other == null || other !is BreakpointPosition) {
return false
}
return module.equals(other.module) && line.equals(other.line)
}
override fun hashCode(): Int = module.hashCode() * 31 + line
}
private class BreakpointEntry(var breakpointNumber: Int?, val breakpoint: XLineBreakpoint<XBreakpointProperties<*>>)
/**
* Used to make synchronous requests to debugger.
*
* @see org.jetbrains.haskell.debugger.utils.SyncObject
* @see org.jetbrains.haskell.debugger.HaskellDebugProcess#isReadyForNextCommand
*/
private fun syncCommand(command: SyncCommand<*>, syncObject: SyncObject) {
syncObject.lock()
try {
debugger.enqueueCommand(command)
while (!syncObject.signaled()) {
syncObject.await()
}
} finally {
syncObject.unlock()
}
}
} | apache-2.0 | 294d6cc60c4c62b1f89022c2d29cfd65 | 43.949045 | 180 | 0.714802 | 5.428077 | false | false | false | false |
y2k/JoyReactor | core/src/main/kotlin/y2k/joyreactor/viewmodel/MainViewModel.kt | 1 | 2349 | package y2k.joyreactor.viewmodel
import y2k.joyreactor.common.ListWithDivider
import y2k.joyreactor.common.platform.NavigationService
import y2k.joyreactor.common.platform.open
import y2k.joyreactor.common.property
import y2k.joyreactor.common.registerProperty
import y2k.joyreactor.common.ui
import y2k.joyreactor.model.Group
import y2k.joyreactor.services.*
/**
* Created by y2k on 5/9/16.
*/
class MainViewModel(
private val navigation: NavigationService,
private val service: TagService,
private val userService: UserService,
private val lifeCycleService: LifeCycleService,
private val postService: PostService,
private val reportService: ReportService) {
val isBusy = property(false)
val posts = property<ListWithDivider<PostItemViewModel>>()
val hasNewPosts = property(false)
val isError = property(false)
val quality = property(Group.Quality.Good)
val group = property(Group.makeFeatured())
private lateinit var state: PostListViewModel
init {
lifeCycleService.registerProperty(BroadcastService.TagSelected::class, group)
group.subscribeLazy { changeCurrentGroup() }
quality.subscribeLazy { changeCurrentGroup() }
changeCurrentGroup(true)
}
fun changeCurrentGroup(isFirst: Boolean = false) {
userService
.makeGroup(group.value, quality.value)
.ui {
if (!isFirst) {
state.isBusy.unsubscribe(isBusy)
state.posts.unsubscribe(posts)
state.hasNewPosts.unsubscribe(hasNewPosts)
state.isError.unsubscribe(isError)
}
state = PostListViewModel(navigation, lifeCycleService, service, postService, it)
state.isBusy.subscribe(isBusy)
state.posts.subscribe(posts)
state.hasNewPosts.subscribe(hasNewPosts)
state.isError.subscribe(isError)
}
}
fun applyNew() = state.applyNew()
fun loadMore() = state.loadMore()
fun reloadFirstPage() = state.reloadFirstPage()
fun openProfile() = navigation.open<ProfileViewModel>()
fun openMessages() = navigation.open<ThreadsViewModel>()
fun openAddTag() = navigation.open<AddTagViewModel>()
fun openFeedback() = reportService.createFeedback()
} | gpl-2.0 | b4448906c58d070f1860d0206893342c | 33.558824 | 97 | 0.684121 | 4.552326 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/widget/AbstractCameraGLSurfaceView.kt | 1 | 12922 | package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [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.
*/
import android.content.Context
import android.graphics.SurfaceTexture
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.SurfaceHolder
import android.view.View
import com.serenegiant.gl.GLDrawer2D
import com.serenegiant.gl.GLUtils
import com.serenegiant.glutils.IRendererHolder
import com.serenegiant.glutils.IRendererHolder.RenderHolderCallback
import com.serenegiant.graphics.MatrixUtils
import com.serenegiant.math.Fraction
import com.serenegiant.utils.HandlerThreadHandler
import com.serenegiant.widget.CameraDelegator.ICameraRenderer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
/**
* カメラ映像をIRendererHolder経由で取得してプレビュー表示するためのGLSurfaceView実装
*/
abstract class AbstractCameraGLSurfaceView @JvmOverloads constructor(
context: Context?, attrs: AttributeSet? = null)
: GLSurfaceView(context, attrs), ICameraView {
protected val glVersion: Int
private val mCameraDelegator: CameraDelegator
/**
* 子クラスからIRendererHolderへアクセスできるように
* @return
*/
protected var rendererHolder: IRendererHolder? = null
private set
init {
if (DEBUG) Log.v(TAG, "コンストラクタ:")
glVersion = GLUtils.getSupportedGLVersion()
mCameraDelegator = CameraDelegator(this@AbstractCameraGLSurfaceView,
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT,
CameraRenderer())
@Suppress("LeakingThis")
setEGLContextClientVersion(glVersion)
@Suppress("LeakingThis")
setRenderer(mCameraDelegator.cameraRenderer as CameraRenderer)
val holder = holder
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
if (DEBUG) Log.v(TAG, "surfaceCreated:")
// do nothing
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { // do nothing
if (DEBUG) Log.v(TAG, "surfaceChanged:")
mCameraDelegator.cameraRenderer.updateViewport()
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (DEBUG) Log.v(TAG, "surfaceDestroyed:")
mCameraDelegator.cameraRenderer.onSurfaceDestroyed()
}
})
}
override fun getView() : View {
return this
}
@Synchronized
override fun onResume() {
if (DEBUG) Log.v(TAG, "onResume:")
super.onResume()
rendererHolder = createRendererHolder(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT,
mRenderHolderCallback)
mCameraDelegator.onResume()
}
@Synchronized
override fun onPause() {
if (DEBUG) Log.v(TAG, "onPause:")
mCameraDelegator.onPause()
if (rendererHolder != null) {
rendererHolder!!.release()
rendererHolder = null
}
super.onPause()
}
override fun addListener(listener: CameraDelegator.OnFrameAvailableListener) {
mCameraDelegator.addListener(listener)
}
override fun removeListener(listener: CameraDelegator.OnFrameAvailableListener) {
mCameraDelegator.removeListener(listener)
}
override fun setScaleMode(mode: Int) {
mCameraDelegator.scaleMode = mode
(mCameraDelegator.cameraRenderer as CameraRenderer).updateViewport()
}
override fun getScaleMode(): Int {
return mCameraDelegator.scaleMode
}
override fun setVideoSize(width: Int, height: Int) {
mCameraDelegator.setVideoSize(width, height)
}
override fun getVideoWidth(): Int {
return mCameraDelegator.previewWidth
}
override fun getVideoHeight(): Int {
return mCameraDelegator.previewHeight
}
/**
* プレビュー表示用Surfaceを追加
* @param id
* @param surface
* @param isRecordable
*/
@Synchronized
override fun addSurface(
id: Int, surface: Any,
isRecordable: Boolean,
maxFps: Fraction?) {
if (DEBUG) Log.v(TAG, "addSurface:$id")
rendererHolder?.addSurface(id, surface, isRecordable, maxFps)
}
/**
* プレビュー表示用Surfaceを除去
* @param id
*/
@Synchronized
override fun removeSurface(id: Int) {
if (DEBUG) Log.v(TAG, "removeSurface:$id")
rendererHolder?.removeSurface(id)
}
override fun isRecordingSupported(): Boolean {
return true
}
/**
* IRendererHolderを生成
* @param width
* @param height
* @param callback
* @return
*/
protected abstract fun createRendererHolder(
width: Int, height: Int,
callback: RenderHolderCallback?): IRendererHolder
/**
* IRendererからのコールバックリスナーを実装
*/
private val mRenderHolderCallback: RenderHolderCallback
= object : RenderHolderCallback {
override fun onCreate(surface: Surface) {
if (DEBUG) Log.v(TAG, "RenderHolderCallback#onCreate:")
}
override fun onFrameAvailable() {
// if (DEBUG) Log.v(TAG, "RenderHolderCallback#onFrameAvailable:");
mCameraDelegator.callOnFrameAvailable()
}
override fun onDestroy() {
if (DEBUG) Log.v(TAG, "RenderHolderCallback#onDestroy:")
}
}
/**
* GLSurfaceViewのRenderer
*/
private inner class CameraRenderer : ICameraRenderer, Renderer, SurfaceTexture.OnFrameAvailableListener {
// API >= 11
private var inputSurfaceTexture: SurfaceTexture? = null // API >= 11
private var hTex = 0
private var mDrawer: GLDrawer2D? = null
private val mStMatrix = FloatArray(16)
private val mMvpMatrix = FloatArray(16)
private var mHasSurface = false
@Volatile
private var requestUpdateTex = false
init {
if (DEBUG) Log.v(TAG, "CameraRenderer:")
Matrix.setIdentityM(mMvpMatrix, 0)
}
override fun onSurfaceCreated(unused: GL10, config: EGLConfig) {
if (DEBUG) Log.v(TAG, "CameraRenderer#onSurfaceCreated:")
// This renderer required OES_EGL_image_external extension
val extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS) // API >= 8
// if (DEBUG) Log.i(TAG, "onSurfaceCreated:Gl extensions: " + extensions);
if (!extensions.contains("OES_EGL_image_external")) {
throw RuntimeException("This system does not support OES_EGL_image_external.")
}
val isOES3 = extensions.contains("GL_OES_EGL_image_external_essl3")
val drawer = GLDrawer2D.create(isOES3, true)
mDrawer = drawer
// create texture ID
hTex = drawer.initTex(GLES20.GL_TEXTURE0)
// create SurfaceTexture with texture ID.
val st = SurfaceTexture(hTex)
inputSurfaceTexture = st
st.setDefaultBufferSize(
mCameraDelegator.requestWidth, mCameraDelegator.requestHeight)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
st.setOnFrameAvailableListener(
this, HandlerThreadHandler.createHandler(TAG))
} else {
st.setOnFrameAvailableListener(this)
}
// clear screen with yellow color so that you can see rendering rectangle
GLES20.glClearColor(1.0f, 1.0f, 0.0f, 1.0f)
mHasSurface = true
// create object for preview display
drawer.setMvpMatrix(mMvpMatrix, 0)
addSurface(1, Surface(st), false)
}
override fun onSurfaceChanged(unused: GL10, width: Int, height: Int) {
if (DEBUG) Log.v(TAG, String.format("CameraRenderer#onSurfaceChanged:(%d,%d)",
width, height))
// if at least with or height is zero, initialization of this view is still progress.
if ((width == 0) || (height == 0)) {
return
}
updateViewport()
mCameraDelegator.startPreview(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
}
/**
* when GLSurface context is soon destroyed
*/
fun onSurfaceDestroyed() {
if (DEBUG) Log.v(TAG, "CameraRenderer#onSurfaceDestroyed:")
mHasSurface = false
removeSurface(1)
release()
}
override fun hasSurface(): Boolean {
return mHasSurface
}
override fun onPreviewSizeChanged(width: Int, height: Int) {
inputSurfaceTexture?.setDefaultBufferSize(width, height)
}
override fun getInputSurface(): SurfaceTexture {
if (DEBUG) Log.v(TAG, "getInputSurfaceTexture:")
checkNotNull(rendererHolder)
return rendererHolder!!.surfaceTexture
}
fun release() {
if (DEBUG) Log.v(TAG, "CameraRenderer#release:")
val drawer = mDrawer
mDrawer = null
drawer?.deleteTex(hTex)
// drawer?.release() // GT-N7100で動作がおかしくなる
val st = inputSurfaceTexture
inputSurfaceTexture = null
st?.release()
}
private var cnt = 0
/**
* drawing to GLSurface
* we set renderMode to GLSurfaceView.RENDERMODE_WHEN_DIRTY,
* this method is only called when #requestRender is called(= when texture is required to update)
* if you don't set RENDERMODE_WHEN_DIRTY, this method is called at maximum 60fps
*/
override fun onDrawFrame(unused: GL10) {
if (DEBUG && ++cnt % 1000 == 0) Log.v(TAG, "onDrawFrame::$cnt")
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
val st = inputSurfaceTexture
if (requestUpdateTex && (st != null)) {
requestUpdateTex = false
// update texture(came from camera)
st.updateTexImage()
// get texture matrix
st.getTransformMatrix(mStMatrix)
}
// draw to preview screen
mDrawer?.draw(GLES20.GL_TEXTURE0, hTex, mStMatrix, 0)
}
fun updateViewport() {
queueEvent { updateViewportOnGLThread() }
}
fun updateViewportOnGLThread() {
val viewWidth = width
val viewHeight = height
if ((viewWidth == 0) || (viewHeight == 0)) {
if (DEBUG) Log.v(TAG, String.format("updateViewport:view is not ready(%dx%d)",
viewWidth, viewHeight))
return
}
GLES20.glViewport(0, 0, viewWidth, viewHeight)
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
val videoWidth = mCameraDelegator.previewWidth.toDouble()
val videoHeight = mCameraDelegator.previewHeight.toDouble()
if ((videoWidth == 0.0) || (videoHeight == 0.0)) {
if (DEBUG) Log.v(TAG, String.format("updateViewport:video is not ready(%dx%d)",
viewWidth, viewHeight))
return
}
val viewAspect = viewWidth / viewHeight.toDouble()
val scaleMode = mCameraDelegator.scaleMode
Log.i(TAG, String.format("updateViewport:view(%d,%d)%f,video(%1.0f,%1.0f),scaleMode=%d",
viewWidth, viewHeight, viewAspect, videoWidth, videoHeight, scaleMode))
Matrix.setIdentityM(mMvpMatrix, 0)
when (scaleMode) {
CameraDelegator.SCALE_STRETCH_FIT -> {
}
CameraDelegator.SCALE_KEEP_ASPECT_VIEWPORT -> {
val req = videoWidth / videoHeight
val x: Int
val y: Int
val width: Int
val height: Int
if (viewAspect > req) {
// if view is wider than camera image, calc width of drawing area based on view height
y = 0
height = viewHeight
width = (req * viewHeight).toInt()
x = (viewWidth - width) / 2
} else {
// if view is higher than camera image, calc height of drawing area based on view width
x = 0
width = viewWidth
height = (viewWidth / req).toInt()
y = (viewHeight - height) / 2
}
// set viewport to draw keeping aspect ration of camera image
Log.i(TAG, String.format("updateViewport:xy(%d,%d),size(%d,%d)",
x, y, width, height))
GLES20.glViewport(x, y, width, height)
}
CameraDelegator.SCALE_KEEP_ASPECT,
CameraDelegator.SCALE_CROP_CENTER -> {
val scaleX = viewWidth / videoWidth
val scaleY = viewHeight / videoHeight
val scale
= if (scaleMode == CameraDelegator.SCALE_CROP_CENTER)
Math.max(scaleX, scaleY) else Math.min(scaleX, scaleY)
val width = scale * videoWidth
val height = scale * videoHeight
Log.i(TAG, String.format("updateViewport:size(%1.0f,%1.0f),scale(%f,%f),mat(%f,%f)",
width, height, scaleX, scaleY, width / viewWidth, height / viewHeight))
Matrix.scaleM(mMvpMatrix, 0,
(width / viewWidth).toFloat(),
(height / viewHeight).toFloat(),
1.0f)
}
}
Log.v(TAG, "updateViewport:" + MatrixUtils.toGLMatrixString(mMvpMatrix))
mDrawer?.setMvpMatrix(mMvpMatrix, 0)
}
/**
* OnFrameAvailableListenerインターフェースの実装
* @param st
*/
override fun onFrameAvailable(st: SurfaceTexture) {
requestUpdateTex = true
}
} // CameraRenderer
companion object {
private const val DEBUG = true // TODO set false on release
private val TAG = AbstractCameraGLSurfaceView::class.java.simpleName
}
} | apache-2.0 | 3e469894ae900bc8296e1f6d0860bb49 | 29.813107 | 107 | 0.716874 | 3.595016 | false | false | false | false |
czyzby/ktx | scene2d/src/main/kotlin/ktx/scene2d/tooltip.kt | 2 | 3004 | package ktx.scene2d
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip
import com.badlogic.gdx.scenes.scene2d.ui.Tooltip
import com.badlogic.gdx.scenes.scene2d.ui.TooltipManager
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* Adds a new [TextTooltip] to this actor.
* @param text will be displayed on the tooltip.
* @param style name of the style of the tooltip. Defaults to [defaultStyle].
* @param skin [Skin] instance which contains the style. Defaults to [Scene2DSkin.defaultSkin].
* @param tooltipManager manages tooltips and their settings. Defaults to the global manager obtained with
* [TooltipManager.getInstance].
* @param init inlined building block, which allows to manage [Label] actor of the [TextTooltip]. Takes the
* [TextTooltip] as its parameter, so it can be modified with the *it* reference as well. See usage examples.
* @return a new [TextTooltip] instance added to the actor.
*/
@Scene2dDsl
@OptIn(ExperimentalContracts::class)
inline fun Actor.textTooltip(
text: String,
style: String = defaultStyle,
skin: Skin = Scene2DSkin.defaultSkin,
tooltipManager: TooltipManager = TooltipManager.getInstance(),
init: (@Scene2dDsl Label).(TextTooltip) -> Unit = {}
): TextTooltip {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
val tooltip = TextTooltip(text, tooltipManager, skin, style)
tooltip.actor.init(tooltip)
this.addListener(tooltip)
return tooltip
}
/**
* Adds a new [Tooltip] to this actor, storing a flexible [Table] widget.
* @param background optional name of a drawable which will be extracted from the [Skin] and set as the main table's
* background. Defaults to null.
* @param skin [Skin] instance which contains the background. Will be passed to the [Table].
* @param tooltipManager manages tooltips and their settings. Defaults to the global manager obtained with
* [TooltipManager.getInstance].
* @param init inlined building block, which allows to manage main [Table] content and fill it with children. Takes the
* [Tooltip] as its parameter, so it can be modified with the *it* reference. See usage examples.
* @return a new [Tooltip] instance added to this actor.
*/
@Scene2dDsl
@OptIn(ExperimentalContracts::class)
inline fun Actor.tooltip(
background: String? = null,
skin: Skin = Scene2DSkin.defaultSkin,
tooltipManager: TooltipManager = TooltipManager.getInstance(),
init: KTableWidget.(Tooltip<KTableWidget>) -> Unit = {}
): Tooltip<KTableWidget> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
val table = KTableWidget(skin)
if (background != null) {
table.setBackground(background)
}
val tooltip = Tooltip(table, tooltipManager)
table.init(tooltip)
this.addListener(tooltip)
return tooltip
}
| cc0-1.0 | 9fabb4801cc7f98dd519f5cb1edea67c | 42.536232 | 119 | 0.765646 | 3.881137 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/osm/upload/OsmInChangesetsUploader.kt | 1 | 4135 | package de.westnordost.streetcomplete.data.osm.upload
import androidx.annotation.CallSuper
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementUpdateController
import de.westnordost.streetcomplete.data.osm.upload.changesets.OpenQuestChangesetsManager
import de.westnordost.streetcomplete.data.upload.OnUploadedChangeListener
import de.westnordost.streetcomplete.data.upload.Uploader
import java.util.concurrent.atomic.AtomicBoolean
/** Base class for all uploaders which upload OSM data. They all have in common that they handle
* OSM data (of course), and that the data is uploaded in changesets. */
abstract class OsmInChangesetsUploader<T : UploadableInChangeset>(
private val changesetManager: OpenQuestChangesetsManager,
private val elementUpdateController: OsmElementUpdateController
): Uploader {
override var uploadedChangeListener: OnUploadedChangeListener? = null
@Synchronized @CallSuper override fun upload(cancelled: AtomicBoolean) {
if (cancelled.get()) return
val uploadedQuestTypes = mutableSetOf<OsmElementQuestType<*>>()
for (quest in getAll()) {
if (cancelled.get()) break
try {
val uploadedElements = uploadSingle(quest)
/* onUploadSuccessful must be called before updating the element because in there,
the entry from the database that this-thing-needs-to-be-uploaded is removed.
Such entry blocks the creation of new quests. See #2418
*/
onUploadSuccessful(quest)
for (element in uploadedElements) {
updateElement(element, quest)
}
uploadedQuestTypes.add(quest.osmElementQuestType)
uploadedChangeListener?.onUploaded(quest.osmElementQuestType.name, quest.position)
} catch (e: ElementIncompatibleException) {
elementUpdateController.delete(quest.elementType, quest.elementId)
onUploadFailed(quest, e)
uploadedChangeListener?.onDiscarded(quest.osmElementQuestType.name, quest.position)
} catch (e: ElementConflictException) {
onUploadFailed(quest, e)
uploadedChangeListener?.onDiscarded(quest.osmElementQuestType.name, quest.position)
}
}
cleanUp(uploadedQuestTypes)
}
protected open fun updateElement(element: Element, quest: T) {
elementUpdateController.update(element, null)
}
private fun uploadSingle(quest: T) : List<Element> {
val element = elementUpdateController.get(quest.elementType, quest.elementId)
?: throw ElementDeletedException("Element deleted")
return try {
val changesetId = changesetManager.getOrCreateChangeset(quest.osmElementQuestType, quest.source)
uploadSingle(changesetId, quest, element)
} catch (e: ChangesetConflictException) {
val changesetId = changesetManager.createChangeset(quest.osmElementQuestType, quest.source)
uploadSingle(changesetId, quest, element)
}
}
@CallSuper protected open fun cleanUp(questTypes: Set<OsmElementQuestType<*>>) {
// must be after unreferenced elements have been deleted
for (questType in questTypes) {
questType.cleanMetadata()
}
}
protected abstract fun getAll() : Collection<T>
/** Upload the changes for a single quest and element.
* Returns the updated element(s) for which it should be checked whether they are eligible
* for new quests (or not eligible anymore for existing quests) */
protected abstract fun uploadSingle(changesetId: Long, quest: T, element: Element): List<Element>
protected abstract fun onUploadSuccessful(quest: T)
protected abstract fun onUploadFailed(quest: T, e: Throwable)
}
private val QuestType<*>.name get() = javaClass.simpleName
| gpl-3.0 | 3dc6723615ebfdb0e3bb34496d6b414a | 45.460674 | 108 | 0.704232 | 4.975933 | false | false | false | false |
elect86/jAssimp | src/main/kotlin/assimp/material.kt | 1 | 18064 | package assimp
import glm_.BYTES
import glm_.vec3.Vec3
import kool.BYTES
import java.nio.ByteBuffer
/**
* Created by elect on 17/11/2016.
*/
// Name for default materials (2nd is used if meshes have UV coords)
const val AI_DEFAULT_MATERIAL_NAME = "DefaultMaterial"
class AiTexture {
/** Width of the texture, in pixels
*
* If height is zero the texture is compressed in a format like JPEG. In this case width specifies the size of the memory area pcData is pointing to, in bytes. */
var width = 0 // ColladaParser.findFilenameForEffectTexture lies on this to be 0 at start, if you have to change it, check it
/** Height of the texture, in pixels
*
* If this value is zero, pcData points to an compressed texture in any format (e.g. JPEG). */
var height = 0
/** A hint from the loader to make it easier for applications to determine the type of embedded textures.
*
* If height != 0 this member is show how data is packed. Hint will consist of two parts: channel order and channel bitness (count of the bits for every color
* channel). For simple parsing by the viewer it's better to not omit absent color channel and just use 0 for bitness. For example:
* 1. Image contain RGBA and 8 bit per channel, achFormatHint == "rgba8888";
* 2. Image contain ARGB and 8 bit per channel, achFormatHint == "argb8888";
* 3. Image contain RGB and 5 bit for R and B channels and 6 bit for G channel, achFormatHint == "rgba5650";
* 4. One color image with B channel and 1 bit for it, achFormatHint == "rgba0010";
* If height == 0 then achFormatHint is set set to '\\0\\0\\0\\0' if the loader has no additional information about the texture file format used OR the file
* extension of the format without a trailing dot. If there are multiple file extensions for a format, the shortest extension is chosen (JPEG maps to 'jpg',
* not to 'jpeg').
* E.g. 'dds\\0', 'pcx\\0', 'jpg\\0'. All characters are lower-case.
* The fourth character will always be '\\0'. */
var achFormatHint = ""// 8 for string + 1 for terminator.
/** Data of the texture.
*
* Points to an array of width * height aiTexel's.
* The format of the texture data is always ARGB8888 to
* make the implementation for user of the library as easy
* as possible. If height = 0 this is a pointer to a memory
* buffer of size width containing the compressed texture
* data. Good luck, have fun!
*/
var pcData = byteArrayOf()
// ---------------------------------------------------------------------------
/** @brief Defines how the Nth texture of a specific Type is combined with the result of all previous layers.
*
* Example (left: key, right: value): <br>
* @code
* DiffColor0 - gray
* DiffTextureOp0 - aiTextureOpMultiply
* DiffTexture0 - tex1.png
* DiffTextureOp0 - aiTextureOpAdd
* DiffTexture1 - tex2.png
* @endcode
* Written as equation, the final diffuse term for a specific pixel would be:
* @code
* diffFinal = DiffColor0 * sampleTex(DiffTexture0,UV0) + sampleTex(DiffTexture1,UV0) * diffContrib;
* @endcode
* where 'diffContrib' is the intensity of the incoming light for that pixel.
*/
enum class Op(val i: Int) {
/** T = T1 * T2 */
multiply(0x0),
/** T ( T1 + T2 */
add(0x1),
/** T ( T1 - T2 */
subtract(0x2),
/** T ( T1 / T2 */
divide(0x3),
/** T ( (T1 + T2) - (T1 * T2) */
smoothAdd(0x4),
/** T ( T1 + (T2-0.5) */
signedAdd(0x5);
companion object {
fun of(i: Int) = values().first { it.i == i }
}
}
// ---------------------------------------------------------------------------
/** @brief Defines how UV coordinates outside the [0...1] range are handled.
*
* Commonly referred to as 'wrapping mode'.
*/
enum class MapMode(val i: Int) {
/** A texture coordinate u|v is translated to u%1|v%1 */
wrap(0x0),
/** Texture coordinates outside [0...1]
* are clamped to the nearest valid value. */
clamp(0x1),
/** If the texture coordinates for a pixel are outside [0...1]
* the texture is not applied to that pixel */
decal(0x3),
/** A texture coordinate u|v becomes u%1|v%1 if (u-(u%1))%2 is zero and
* 1-(u%1)|1-(v%1) otherwise */
mirror(0x2);
companion object {
fun of(i: Int) = values().first { it.i == i }
}
}
// ---------------------------------------------------------------------------
/** @brief Defines how the mapping coords for a texture are generated.
*
* Real-time applications typically require full UV coordinates, so the use of the aiProcess_GenUVCoords step is highly
* recommended. It generates proper UV channels for non-UV mapped objects, as long as an accurate description how the
* mapping should look like (e.g spherical) is given.
* See the #AI_MATKEY_MAPPING property for more details.
*/
enum class Mapping(val i: Int) {
/** The mapping coordinates are taken from an UV channel.
*
* The #AI_MATKEY_UVWSRC key specifies from which UV channel the texture coordinates are to be taken from
* (remember, meshes can have more than one UV channel).
*/
uv(0x0),
/** Spherical mapping */
sphere(0x1),
/** Cylindrical mapping */
cylinder(0x2),
/** Cubic mapping */
box(0x3),
/** Planar mapping */
plane(0x4),
/** Undefined mapping. Have fun. */
other(0x5);
companion object {
fun of(i: Int) = values().first { it.i == i }
}
}
// ---------------------------------------------------------------------------
/** @brief Defines the purpose of a texture
*
* This is a very difficult topic. Different 3D packages support different kinds of textures. For very common texture
* types, such as bumpmaps, the rendering results depend on implementation details in the rendering pipelines of these
* applications. Assimp loads all texture references from the model file and tries to determine which of the predefined
* texture types below is the best choice to match the original use of the texture as closely as possible.<br>
*
* In content pipelines you'll usually define how textures have to be handled, and the artists working on models have
* to conform to this specification, regardless which 3D tool they're using. */
enum class Type(val i: Int) {
/** Dummy value.
*
* No texture, but the value to be used as 'texture semantic' (#aiMaterialProperty::mSemantic) for all material
* properties *not* related to textures. */
none(0x0),
/** The texture is combined with the result of the diffuse lighting equation. */
diffuse(0x1),
/** The texture is combined with the result of the specular lighting equation. */
specular(0x2),
/** The texture is combined with the result of the ambient lighting equation. */
ambient(0x3),
/** The texture is added to the result of the lighting calculation. It isn't influenced by incoming light. */
emissive(0x4),
/** The texture is a height map.
*
* By convention, higher gray-scale values stand for higher elevations from the base height. */
height(0x5),
/** The texture is a (tangent space) normal-map.
*
* Again, there are several conventions for tangent-space normal maps. Assimp does (intentionally) not distinguish
* here. */
normals(0x6),
/** The texture defines the glossiness of the material.
*
* The glossiness is in fact the exponent of the specular (phong) lighting equation. Usually there is a conversion
* function defined to map the linear color values in the texture to a suitable exponent. Have fun. */
shininess(0x7),
/** The texture defines per-pixel opacity.
*
* Usually 'white' means opaque and 'black' means 'transparency'. Or quite the opposite. Have fun. */
opacity(0x8),
/** Displacement texture
*
* The exact purpose and format is application-dependent.
* Higher color values stand for higher vertex displacements. */
displacement(0x9),
/** Lightmap texture (aka Ambient Occlusion)
*
* Both 'Lightmaps' and dedicated 'ambient occlusion maps' are covered by this material property. The texture
* contains a scaling value for the final color value of a pixel. Its intensity is not affected by incoming light. */
lightmap(0xA),
/** Reflection texture
*
* Contains the color of a perfect mirror reflection.
* Rarely used, almost never for real-time applications. */
reflection(0xB),
/** Unknown texture
*
* A texture reference that does not match any of the definitions above is considered to be 'unknown'. It is still
* imported, but is excluded from any further postprocessing. */
unknown(0xC)
}
// ---------------------------------------------------------------------------
/** @brief Defines some mixed flags for a particular texture.
*
* Usually you'll instruct your cg artists how textures have to look like ... and how they will be processed in your
* application. However, if you use Assimp for completely generic loading purposes you might also need to process these
* flags in order to display as many 'unknown' 3D models as possible correctly.
*
* This corresponds to the #AI_MATKEY_TEXFLAGS property. */
enum class Flags(val i: Int) {
/** The texture's color values have to be inverted (componentwise 1-n) */
invert(0x1),
/** Explicit request to the application to process the alpha channel of the texture.
*
* Mutually exclusive with #aiTextureFlags_IgnoreAlpha. These flags are set if the library can say for sure that
* the alpha channel is used/is not used. If the model format does not define this, it is left to the application
* to decide whether the texture alpha channel - if any - is evaluated or not. */
useAlpha(0x2),
/** Explicit request to the application to ignore the alpha channel of the texture.
*
* Mutually exclusive with #aiTextureFlags_UseAlpha. */
ignoreAlpha(0x4)
}
companion object {
val size = 2 * Int.BYTES
}
}
// ---------------------------------------------------------------------------
/** @brief Defines all shading models supported by the library
*
* The list of shading modes has been taken from Blender.
* See Blender documentation for more information. The API does not distinguish between "specular" and "diffuse"
* shaders (thus the specular term for diffuse shading models like Oren-Nayar remains undefined). <br>
* Again, this value is just a hint. Assimp tries to select the shader whose most common implementation matches the
* original rendering results of the 3D modeller which wrote a particular model as closely as possible. */
enum class AiShadingMode(val i: Int) {
/** Flat shading. Shading is done on per-face base, diffuse only. Also known as 'faceted shading'. */
flat(0x1),
/** Simple Gouraud shading. */
gouraud(0x2),
/** Phong-Shading - */
phong(0x3),
/** Phong-Blinn-Shading */
blinn(0x4),
/** Toon-Shading per pixel
*
* Also known as 'comic' shader. */
toon(0x5),
/** OrenNayar-Shading per pixel
*
* Extension to standard Lambertian shading, taking the roughness of the material into account */
orenNayar(0x6),
/** Minnaert-Shading per pixel
*
* Extension to standard Lambertian shading, taking the "darkness" of the material into account */
minnaert(0x7),
/** CookTorrance-Shading per pixel
*
* Special shader for metallic surfaces. */
cookTorrance(0x8),
/** No shading at all. Constant light influence of 1.0. */
noShading(0x9),
/** Fresnel shading */
fresnel(0xa);
companion object {
fun of(i: Int) = values().first { it.i == i }
}
}
// ---------------------------------------------------------------------------
/** @brief Defines alpha-blend flags.
*
* If you're familiar with OpenGL or D3D, these flags aren't new to you.
* They define *how* the final color value of a pixel is computed, basing on the previous color at that pixel and the
* new color value from the material.
* The blend formula is:
* @code
* SourceColor * SourceBlend + DestColor * DestBlend
* @endcode
* where DestColor is the previous color in the framebuffer at this position and SourceColor is the material color
* before the transparency calculation.<br>
* This corresponds to the #AI_MATKEY_BLEND_FUNC property. */
enum class AiBlendMode(val i: Int) {
/**
* Formula:
* @code
* SourceColor*SourceAlpha + DestColor*(1-SourceAlpha)
* @endcode */
default(0x0),
/** Additive blending
*
* Formula:
* @code
* SourceColor*1 + DestColor*1
* @endcode */
additive(0x1);
companion object {
fun of(i: Int) = values().first { it.i == i }
}
// we don't need more for the moment, but we might need them in future versions ...
}
// ---------------------------------------------------------------------------
/** @brief Defines how an UV channel is transformed.
*
* This is just a helper structure for the #AI_MATKEY_UVTRANSFORM key.
* See its documentation for more details.
*
* Typically you'll want to build a matrix of this information. However, we keep separate scaling/translation/rotation
* values to make it easier to process and optimize UV transformations internally.
*/
data class AiUVTransform(
/** Translation on the u and v axes.
*
* The default value is (0|0). */
var translation: AiVector2D = AiVector2D(),
/** Scaling on the u and v axes.
*
* The default value is (1|1). */
var scaling: AiVector2D = AiVector2D(),
/** Rotation - in counter-clockwise direction.
*
* The rotation angle is specified in radians. The rotation center is 0.5f|0.5f. The default value 0.f. */
var rotation: Float = 0f
)
data class AiMaterial(
var name: String? = null,
var twoSided: Boolean? = null,
var shadingModel: AiShadingMode? = null,
var wireframe: Boolean? = null,
var blendFunc: AiBlendMode? = null,
var opacity: Float? = null,
var bumpScaling: Float? = null, // TODO unsure
var shininess: Float? = null,
var reflectivity: Float? = null, // TODO unsure
var shininessStrength: Float? = null,
var refracti: Float? = null,
var color: Color? = null,
var displacementScaling: Float? = null,
var textures: MutableList<Texture> = mutableListOf()
// TODO const AI_MATKEY_GLOBAL_BACKGROUND_IMAGE = '?bg.global';
) {
constructor(other: AiMaterial) : this(other.name, other.twoSided, other.shadingModel, other.wireframe,
other.blendFunc, other.opacity, other.bumpScaling, other.shininess, other.reflectivity,
other.shininessStrength, other.refracti, if (other.color == null) null else Color(other.color!!),
other.displacementScaling, MutableList(other.textures.size) { Texture(other.textures[it]) })
data class Color(
var diffuse: AiColor3D? = null,
var ambient: AiColor3D? = null,
var specular: AiColor3D? = null,
var emissive: AiColor3D? = null,
var transparent: AiColor3D? = null,
var reflective: AiColor3D? = null // TODO unsure
) {
constructor(other: Color) : this(
if (other.diffuse == null) null else AiColor3D(other.diffuse!!),
if (other.ambient == null) null else AiColor3D(other.ambient!!),
if (other.specular == null) null else AiColor3D(other.specular!!),
if (other.emissive == null) null else AiColor3D(other.emissive!!),
if (other.transparent == null) null else AiColor3D(other.transparent!!),
if (other.reflective == null) null else AiColor3D(other.reflective!!))
companion object {
val size = 6 * Vec3.size
}
}
data class Texture(
var type: AiTexture.Type? = null,
var file: String? = null, // HINT this is used as the index to reference textures in AiScene.textures
var blend: Float? = null,
var op: AiTexture.Op? = null,
var mapping: AiTexture.Mapping? = null,
var uvwsrc: Int? = null,
var mapModeU: AiTexture.MapMode? = null,
var mapModeV: AiTexture.MapMode? = null,
var mapAxis: AiVector3D? = null,
var flags: Int? = null,
var uvTrafo: AiUVTransform? = null
) {
constructor(other: Texture) : this(other.type, other.file, other.blend, other.op, other.mapping, other.uvwsrc,
other.mapModeU, other.mapModeV, other.mapAxis, other.flags, other.uvTrafo)
companion object {
val size = 8 * Int.BYTES + Float.BYTES + Vec3.size
}
}
companion object {
val size = 4 * Int.BYTES + 6 * Float.BYTES + Color.size + Texture.size
}
} | mit | a0a7895073132564284e0a59332a6565 | 36.170782 | 170 | 0.597764 | 4.160295 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/bridges/test6.kt | 1 | 511 | // vtable call + interface call
interface Z {
fun foo(): Any
}
interface Y {
fun foo(): Int
}
open class A {
open fun foo(): Any = "A"
}
open class C : A() {
override fun foo(): Int = 42
}
open class D: C(), Y, Z
fun main(args: Array<String>) {
val d = D()
val y: Y = d
val z: Z = d
val c: C = d
val a: A = d
println(d.foo().toString())
println(y.foo().toString())
println(z.foo().toString())
println(c.foo().toString())
println(a.foo().toString())
} | apache-2.0 | 90ddaadf942e644e4b0a79a21b48177e | 15.516129 | 32 | 0.536204 | 3.005882 | false | false | false | false |
WangDaYeeeeee/GeometricWeather | app/src/main/java/wangdaye/com/geometricweather/remoteviews/presenters/MaterialYouCurrentWidgetIMP.kt | 1 | 2913 | package wangdaye.com.geometricweather.remoteviews.presenters
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import android.widget.RemoteViews
import androidx.annotation.LayoutRes
import wangdaye.com.geometricweather.GeometricWeather
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.background.receiver.widget.WidgetMaterialYouCurrentProvider
import wangdaye.com.geometricweather.common.basic.models.Location
import wangdaye.com.geometricweather.common.basic.models.options.NotificationTextColor
import wangdaye.com.geometricweather.settings.SettingsManager
import wangdaye.com.geometricweather.theme.resource.ResourceHelper
import wangdaye.com.geometricweather.theme.resource.ResourcesProviderFactory
class MaterialYouCurrentWidgetIMP: AbstractRemoteViewsPresenter() {
companion object {
@JvmStatic
fun isEnable(context: Context): Boolean {
return AppWidgetManager.getInstance(
context
).getAppWidgetIds(
ComponentName(
context,
WidgetMaterialYouCurrentProvider::class.java
)
).isNotEmpty()
}
@JvmStatic
fun updateWidgetView(context: Context, location: Location) {
AppWidgetManager.getInstance(context).updateAppWidget(
ComponentName(context, WidgetMaterialYouCurrentProvider::class.java),
buildRemoteViews(context, location, R.layout.widget_material_you_current)
)
}
}
}
private fun buildRemoteViews(
context: Context,
location: Location,
@LayoutRes layoutId: Int,
): RemoteViews {
val views = RemoteViews(
context.packageName,
layoutId
)
val weather = location.weather
val dayTime = location.isDaylight
val provider = ResourcesProviderFactory.getNewInstance()
val settings = SettingsManager.getInstance(context)
val temperatureUnit = settings.temperatureUnit
if (weather == null) {
return views
}
// current.
views.setImageViewUri(
R.id.widget_material_you_current_currentIcon,
ResourceHelper.getWidgetNotificationIconUri(
provider,
weather.current.weatherCode,
dayTime,
false,
NotificationTextColor.LIGHT
)
)
views.setTextViewText(
R.id.widget_material_you_current_currentTemperature,
weather.current.temperature.getShortTemperature(context, temperatureUnit)
)
// pending intent.
views.setOnClickPendingIntent(
android.R.id.background,
AbstractRemoteViewsPresenter.getWeatherPendingIntent(
context,
location,
GeometricWeather.WIDGET_MATERIAL_YOU_CURRENT_PENDING_INTENT_CODE_WEATHER
)
)
return views
} | lgpl-3.0 | a489a33c82ae71b3996ccf26761e7d31 | 29.673684 | 96 | 0.698936 | 5.277174 | false | false | false | false |
mtzaperas/burpbuddy | src/main/kotlin/burp/BHttpRequestResponse.kt | 1 | 1579 | package burp
import java.util.Base64
class BHttpRequestResponse(val httpMessage: HttpRequestResponse, val service: HttpService): IHttpRequestResponse {
override fun setComment(comment: String) {
httpMessage.comment = comment
}
override fun getComment(): String {
return httpMessage.comment
}
override fun setRequest(rawRequest: ByteArray) {
// TODO: I'm not sure if i should set all the other variables for a request.
httpMessage.request.raw = Base64.getEncoder().encodeToString(rawRequest)
}
override fun getHttpService(): IHttpService {
return BHttpService(service)
}
override fun getHighlight(): String {
return httpMessage.highlight
}
override fun getResponse(): ByteArray? {
if (httpMessage.response != null && httpMessage.response.raw.length > 0) {
return Base64.getDecoder().decode(httpMessage.response.raw)
}
return null
}
override fun setHighlight(color: String) {
httpMessage.highlight = color
}
override fun setHttpService(httpService: IHttpService) {
service.protocol = httpService.protocol
service.port = httpService.port
service.host = httpService.host
}
override fun setResponse(rawResponse: ByteArray) {
if (httpMessage.response != null) {
httpMessage.response.raw = Base64.getEncoder().encodeToString(rawResponse)
}
}
override fun getRequest(): ByteArray {
return Base64.getDecoder().decode(httpMessage.request.raw)
}
} | mit | fde6ceba6e18f8323b5712109b3a2c79 | 28.811321 | 114 | 0.671944 | 4.644118 | false | false | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/util/AppUtil.kt | 1 | 1145 | package info.hzvtc.hipixiv.util
import android.app.Activity
import android.content.Context
import java.util.*
import android.net.ConnectivityManager
class AppUtil{
companion object{
/**
* @return zh_CN,en_US,ja_JP
*/
fun getLocalLanguage() : String = Locale.getDefault().language + "_" + Locale.getDefault().country
fun isNetworkConnected(context : Context?) : Boolean {
if (context != null) {
val mConnectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable
}
}
return false
}
fun getNowTimestamp() = System.currentTimeMillis()/1000
fun getVersion(context: Context) : String{
val packageManager = context.packageManager
val info = packageManager.getPackageInfo(context.packageName, 0)
return info.versionName
}
}
}
| mit | f10ffd60d1c661440a168f8a93905a32 | 29.131579 | 106 | 0.60524 | 5.400943 | false | false | false | false |
Heiner1/AndroidAPS | automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputButton.kt | 1 | 670 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout
class InputButton() : Element() {
var text: String? = null
var runnable: Runnable? = null
constructor(text: String, runnable: Runnable) : this() {
this.text = text
this.runnable = runnable
}
override fun addToLayout(root: LinearLayout) {
root.addView(
Button(root.context).also {
it.text = text
it.setOnClickListener { runnable?.run() }
it.gravity = Gravity.CENTER_HORIZONTAL
})
}
} | agpl-3.0 | cae45b395c21e837264dd21fc668ae3b | 25.84 | 70 | 0.629851 | 4.527027 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt | 1 | 2389 | package info.nightscout.androidaps.diaconn.packet
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.interfaces.ResourceHelper
import javax.inject.Inject
/**
* InjectionSnackResultReportPacket
*/
class InjectionSnackResultReportPacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) {
@Inject lateinit var diaconnG8Pump: DiaconnG8Pump
@Inject lateinit var rxBus: RxBus
@Inject lateinit var rh: ResourceHelper
init {
msgType = 0xe4.toByte()
aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackResultReportPacket init ")
}
override fun handleMessage(data: ByteArray?) {
val defectCheck = defect(data)
if (defectCheck != 0) {
aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackResultReportPacket Got some Error")
failed = true
return
} else failed = false
val bufferData = prefixDecode(data)
val result = getByteToInt(bufferData)
val bolusAmountToBeDelivered = getShortToInt(bufferData)/100.0
val deliveredBolusAmount = getShortToInt(bufferData)/100.0
diaconnG8Pump.bolusAmountToBeDelivered = bolusAmountToBeDelivered
diaconnG8Pump.lastBolusAmount = deliveredBolusAmount
diaconnG8Pump.lastBolusTime = dateUtil.now()
diaconnG8Pump.bolusingTreatment?.insulin = deliveredBolusAmount
if(result == 1) {
diaconnG8Pump.bolusStopped = true // 주입 중 취소 처리!
}
diaconnG8Pump.bolusDone = true // 주입완료 처리!
aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result")
aapsLogger.debug(LTag.PUMPCOMM, "bolusAmountToBeDelivered --> ${diaconnG8Pump.bolusAmountToBeDelivered}")
aapsLogger.debug(LTag.PUMPCOMM, "lastBolusAmount --> ${diaconnG8Pump.lastBolusAmount}")
aapsLogger.debug(LTag.PUMPCOMM, "lastBolusTime --> ${diaconnG8Pump.lastBolusTime}")
aapsLogger.debug(LTag.PUMPCOMM, "diaconnG8Pump.bolusingTreatment?.insulin --> ${diaconnG8Pump.bolusingTreatment?.insulin}")
aapsLogger.debug(LTag.PUMPCOMM, "bolusDone --> ${diaconnG8Pump.bolusDone}")
}
override fun getFriendlyName(): String {
return "PUMP_INJECTION_SNACK_REPORT"
}
} | agpl-3.0 | 0165856ed4d5e7f106d5424b461e2b8d | 39.067797 | 131 | 0.719424 | 4.35175 | false | false | false | false |
Heiner1/AndroidAPS | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt | 1 | 1860 | package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.encryption.BleEncryption
import javax.inject.Inject
class DanaRSPacketBolusSetStepBolusStart(
injector: HasAndroidInjector,
private var amount: Double = 0.0,
private var speed: Int = 0
) : DanaRSPacket(injector) {
@Inject lateinit var danaPump: DanaPump
@Inject lateinit var constraintChecker: ConstraintChecker
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START
// Speed 0 => 12 sec/U, 1 => 30 sec/U, 2 => 60 sec/U
// HARDCODED LIMIT - if there is one that could be created
amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value()
aapsLogger.debug(LTag.PUMPCOMM, "Bolus start : $amount speed: $speed")
}
override fun getRequestParams(): ByteArray {
val stepBolusRate = (amount * 100).toInt()
val request = ByteArray(3)
request[0] = (stepBolusRate and 0xff).toByte()
request[1] = (stepBolusRate ushr 8 and 0xff).toByte()
request[2] = (speed and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
danaPump.bolusStartErrorCode = intFromBuff(data, 0, 1)
if (danaPump.bolusStartErrorCode == 0) {
failed = false
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
} else {
aapsLogger.error("Result Error: ${danaPump.bolusStartErrorCode}")
failed = true
}
}
override val friendlyName: String = "BOLUS__SET_STEP_BOLUS_START"
} | agpl-3.0 | 85ef7cf76ff94d0f29ebe2c2a394c482 | 36.979592 | 84 | 0.694086 | 4.397163 | false | false | false | false |
unbroken-dome/gradle-xjc-plugin | src/integrationTest/kotlin/org/unbrokendome/gradle/plugins/xjc/testutil/assertions/JarFile.kt | 1 | 1475 | package org.unbrokendome.gradle.plugins.xjc.testutil.assertions
import assertk.Assert
import assertk.all
import assertk.assertions.isFile
import assertk.assertions.support.expected
import assertk.assertions.support.show
import java.io.File
import java.util.jar.JarFile
import java.util.zip.ZipFile
fun Assert<File>.withJarFile(block: Assert<JarFile>.() -> Unit) {
isFile()
given { actual ->
JarFile(actual).use { jarFile ->
assertThat(jarFile, "jar:$name").all(block)
}
}
}
fun Assert<ZipFile>.containsEntry(name: String) = given { actual ->
if (actual.getEntry(name) == null) {
val actualEntryNames = actual.entries().toList().map { it.name }
expected(
"to have an entry ${show(name)}, but was: ${show(actualEntryNames)}",
actual = actualEntryNames
)
}
}
fun Assert<ZipFile>.containsEntries(vararg names: String) = all {
for (name in names) {
containsEntry(name)
}
}
fun Assert<ZipFile>.doesNotContainEntry(name: String) = given { actual ->
if (actual.getEntry(name) != null) {
val actualEntryNames = actual.entries().toList().map { it.name }
expected(
"to have no entry ${show(name)}, but was: ${show(actualEntryNames)}",
actual = actualEntryNames
)
}
}
fun Assert<ZipFile>.doesNotContainEntries(vararg names: String) = all {
for (name in names) {
doesNotContainEntry(name)
}
}
| mit | 4b398a86fa524fbdc11752cbb326d7d4 | 25.339286 | 81 | 0.645424 | 3.922872 | false | false | false | false |
Adventech/sabbath-school-android-2 | app/src/main/java/com/cryart/sabbathschool/navigation/AppNavigatorImpl.kt | 1 | 8525 | /*
* Copyright (c) 2021. Adventech <[email protected]>
*
* 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.
*/
package com.cryart.sabbathschool.navigation
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.app.TaskStackBuilder
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import app.ss.auth.AuthRepository
import com.cryart.sabbathschool.account.AccountDialogFragment
import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider
import com.cryart.sabbathschool.core.extensions.prefs.SSPrefs
import com.cryart.sabbathschool.core.navigation.AppNavigator
import com.cryart.sabbathschool.core.navigation.Destination
import com.cryart.sabbathschool.lessons.ui.lessons.SSLessonsActivity
import com.cryart.sabbathschool.lessons.ui.quarterlies.QuarterliesActivity
import com.cryart.sabbathschool.lessons.ui.readings.SSReadingActivity
import com.cryart.sabbathschool.settings.SSSettingsActivity
import com.cryart.sabbathschool.ui.about.AboutActivity
import com.cryart.sabbathschool.ui.login.LoginActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Singleton
/**
* Implementation for [AppNavigator]
*/
@Singleton
class AppNavigatorImpl @Inject constructor(
private val ssPrefs: SSPrefs,
private val authRepository: AuthRepository,
private val dispatcherProvider: DispatcherProvider
) : AppNavigator, CoroutineScope by MainScope() {
private suspend fun isSignedIn(): Boolean {
return authRepository.getUser().data != null
}
override fun navigate(activity: Activity, destination: Destination, extras: Bundle?) {
launch(dispatcherProvider.default) {
val clazz = getDestinationClass(destination) ?: return@launch
val loginClass = LoginActivity::class.java
val intent = if (clazz == loginClass || !isSignedIn()) {
Intent(activity, loginClass).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
} else if (destination == Destination.ACCOUNT) {
val fragment = AccountDialogFragment()
val fm = (activity as? FragmentActivity)?.supportFragmentManager ?: return@launch
fragment.show(fm, fragment.tag)
return@launch
} else {
Intent(activity, clazz)
}
extras?.let {
intent.putExtras(it)
}
when (destination) {
Destination.LESSONS -> {
with(TaskStackBuilder.create(activity)) {
addNextIntent(QuarterliesActivity.launchIntent(activity))
addNextIntentWithParentStack(intent)
startActivities()
}
}
Destination.READ -> {
with(TaskStackBuilder.create(activity)) {
addNextIntent(QuarterliesActivity.launchIntent(activity))
ssPrefs.getLastQuarterlyIndex()?.let { index ->
addNextIntent(SSLessonsActivity.launchIntent(activity, index))
}
addNextIntentWithParentStack(intent)
startActivities()
}
}
else -> {
activity.startActivity(intent)
}
}
}
}
override fun navigate(activity: Activity, deepLink: Uri) {
val host = deepLink.host ?: return
val destination = Destination.fromKey(host) ?: return
if (destination == Destination.READ_WEB) {
navigateFromWeb(activity, deepLink)
} else {
navigate(activity, destination, getExtras(deepLink))
}
}
private fun getDestinationClass(destination: Destination): Class<*>? {
return when (destination) {
Destination.ABOUT -> AboutActivity::class.java
Destination.ACCOUNT -> AccountDialogFragment::class.java
Destination.LESSONS -> SSLessonsActivity::class.java
Destination.LOGIN -> LoginActivity::class.java
Destination.SETTINGS -> SSSettingsActivity::class.java
Destination.READ -> SSReadingActivity::class.java
else -> null
}
}
private fun getExtras(uri: Uri): Bundle {
val pairs = uri.queryParameterNames.map { key ->
key to uri.getQueryParameter(key)
}.toTypedArray()
return bundleOf(*pairs)
}
/**
* Navigate to either [SSLessonsActivity] or [SSReadingActivity]
* depending on the uri from web (sabbath-school.adventech.io) received.
*
* If no quarterly index is found in the Uri we launch normal flow.
*
* Example links:
* [1] https://sabbath-school.adventech.io/en/2021-03
* [2] https://sabbath-school.adventech.io/en/2021-03/03/07-friday-further-thought/
*/
private fun navigateFromWeb(activity: Activity, uri: Uri) = launch(dispatcherProvider.default) {
if (!isSignedIn()) {
val intent = Intent(activity, LoginActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
activity.startActivity(intent)
return@launch
}
val segments = uri.pathSegments
val quarterlyIndex: String
val lessonIndex: String
val endIntent: Intent
val taskBuilder = TaskStackBuilder.create(activity)
taskBuilder.addNextIntent(QuarterliesActivity.launchIntent(activity))
if (uri.path?.matches(WEB_LINK_REGEX.toRegex()) == true && segments.size >= 2) {
quarterlyIndex = "${segments.first()}-${segments[1]}"
if (segments.size > 2) {
lessonIndex = "$quarterlyIndex-${segments[2]}"
val readPosition = if (segments.size > 3) {
val dayNumber = segments[3].filter { it.isDigit() }
val index = dayNumber.toIntOrNull()?.minus(1)
index?.toString()
} else {
null
}
taskBuilder.addNextIntent(SSLessonsActivity.launchIntent(activity, quarterlyIndex))
endIntent = SSReadingActivity.launchIntent(activity, lessonIndex, readPosition)
} else {
endIntent = SSLessonsActivity.launchIntent(activity, quarterlyIndex)
}
with(taskBuilder) {
addNextIntentWithParentStack(endIntent)
startActivities()
}
} else {
launchNormalFlow(activity)
}
}
private fun launchNormalFlow(activity: Activity) {
val intent = QuarterliesActivity.launchIntent(activity).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
activity.startActivity(intent)
}
companion object {
private const val WEB_LINK_REGEX =
"(^\\/[a-z]{2,}\\/?\$)|(^\\/[a-z]{2,}\\/\\d{4}-\\d{2}(-[a-z]{2})?\\/?\$)|(^\\/[a-z]{2,}\\/\\d{4}-\\d{2}(-[a-z]{2})?\\/\\d{2}\\/?\$)|" +
"(^\\/[a-z]{2,}\\/\\d{4}-\\d{2}(-[a-z]{2})?\\/\\d{2}\\/\\d{2}(-.+)?\\/?\$)"
}
}
| mit | 5b55692a6a25f3bf87cd57ebac5955a8 | 39.985577 | 147 | 0.630381 | 4.786637 | false | false | false | false |
rbi/HomebankCsvConverter | src/main/kotlin/de/voidnode/homebankCvsConverter/CommerzbankReader.kt | 1 | 2929 | /*
* This file is part of HomebankCvsConverter.
* Copyright (C) 2015 Raik Bieniek <[email protected]>
*
* HomebankCvsConverter 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.
*
* HomebankCvsConverter 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 HomebankCvsConverter. If not, see <http://www.gnu.org/licenses/>.
*/
package de.voidnode.homebankCvsConverter
import kotlin.text.Regex
import kotlin.text.MatchGroupCollection
import java.time.LocalDate
private val commerzbankCsvLine = Regex("([^;]*);([0-9]+)\\.([0-9]+)\\.([0-9]+);([^;]*);\"([^;]*)\";(-?)([0-9]+),([0-9]+);([A-Z]*);([0-9]*);([0-9]*);([A-Za-z0-9]*)(;([^;]*))?")
/**
* Converts CSV files exported from the website of the commerzbank to [Transaction]s.
*/
fun readCommerzbankCsv(lines: List<String>) : List<Transaction> {
// skip the first entry as it is the csv header
return lines.drop(1).map(::convertCommerzbankCsvLine)
}
private fun convertCommerzbankCsvLine(line: String) : Transaction {
val matcher = commerzbankCsvLine.matchEntire(line)
if(matcher != null) {
val date = readDate(matcher.groups)
val paymentType = matcher.groups[5]?.value?.let { readPaymentType(it) }
val postingText = matcher.groups[6]
val money = readMoney(matcher.groups)
if(date != null && postingText != null && money != null) {
return Transaction(date, postingText.value, money, paymentType)
}
}
throw IllegalArgumentException("The following line in the CSV file did not match the Commerzbank CSV pattern:\n$line")
}
private fun readMoney(groups: MatchGroupCollection) : Money? {
val invert = if(groups[7]?.value == "-") -1 else 1
val major = groups[8]
val minor = groups[9]
if(major != null && minor != null) {
return Money( invert * major.value.toLong(), minor.value.toLong())
}
return null
}
private fun readPaymentType(rawType: String) : PaymentType? {
return when (rawType ){
"Überweisung" -> PaymentType.TRANSFER
"Zinsen/Entgelte" -> PaymentType.INTEREST_OR_FEE
"Einzahlung/Auszahlung" -> PaymentType.DEPOSIT_OR_WITHDRAWAL
"Lastschrift" -> PaymentType.DIRECT_WITHDRAWL
"Gutschrift" -> PaymentType.CREDIT_NOTE
"Dauerauftrag" -> PaymentType.STANDING_ORDER
else -> null
}
}
private fun readDate(groups: MatchGroupCollection) : LocalDate? {
val day = groups[2]?.value?.toInt()
val month = groups[3]?.value?.toInt()
val year = groups[4]?.value?.toInt()
if(year != null && month != null && day != null) {
return LocalDate.of(year, month, day)
}
return null
} | gpl-3.0 | b912ae799c5dcf02ed30a6ace17eb0ec | 35.6125 | 175 | 0.705943 | 3.260579 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/contacts/ContactLetterBitmapCreator.kt | 1 | 3306 | package com.fsck.k9.contacts
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import com.fsck.k9.mail.Address
import com.fsck.k9.ui.helper.MaterialColors
/**
* Draw a `Bitmap` containing the "contact letter" obtained by [ContactLetterExtractor].
*/
class ContactLetterBitmapCreator(
private val letterExtractor: ContactLetterExtractor,
val config: ContactLetterBitmapConfig
) {
fun drawBitmap(bitmap: Bitmap, pictureSizeInPx: Int, address: Address): Bitmap {
val canvas = Canvas(bitmap)
val backgroundColor = calcUnknownContactColor(address)
bitmap.eraseColor(backgroundColor)
val letter = letterExtractor.extractContactLetter(address)
val paint = Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
setARGB(255, 255, 255, 255)
textSize = pictureSizeInPx.toFloat() * 0.65f
}
val rect = Rect()
paint.getTextBounds(letter, 0, 1, rect)
val width = paint.measureText(letter)
canvas.drawText(
letter,
pictureSizeInPx / 2f - width / 2f,
pictureSizeInPx / 2f + rect.height() / 2f, paint
)
return bitmap
}
private fun calcUnknownContactColor(address: Address): Int {
if (config.hasDefaultBackgroundColor) {
return config.defaultBackgroundColor
}
val hash = address.hashCode()
if (config.useDarkTheme) {
val colorIndex = (hash and Integer.MAX_VALUE) % BACKGROUND_COLORS_DARK.size
return BACKGROUND_COLORS_DARK[colorIndex]
} else {
val colorIndex = (hash and Integer.MAX_VALUE) % BACKGROUND_COLORS_LIGHT.size
return BACKGROUND_COLORS_LIGHT[colorIndex]
}
}
fun signatureOf(address: Address): String {
return calcUnknownContactColor(address).toString()
}
companion object {
private val BACKGROUND_COLORS_LIGHT = intArrayOf(
MaterialColors.RED_300,
MaterialColors.DEEP_PURPLE_300,
MaterialColors.LIGHT_BLUE_300,
MaterialColors.GREEN_300,
MaterialColors.DEEP_ORANGE_300,
MaterialColors.BLUE_GREY_300,
MaterialColors.PINK_300,
MaterialColors.INDIGO_300,
MaterialColors.CYAN_300,
MaterialColors.AMBER_400,
MaterialColors.BROWN_300,
MaterialColors.PURPLE_300,
MaterialColors.BLUE_300,
MaterialColors.TEAL_300,
MaterialColors.ORANGE_400
)
private val BACKGROUND_COLORS_DARK = intArrayOf(
MaterialColors.RED_600,
MaterialColors.DEEP_PURPLE_600,
MaterialColors.LIGHT_BLUE_600,
MaterialColors.GREEN_600,
MaterialColors.DEEP_ORANGE_600,
MaterialColors.BLUE_GREY_600,
MaterialColors.PINK_600,
MaterialColors.INDIGO_600,
MaterialColors.CYAN_600,
MaterialColors.AMBER_600,
MaterialColors.BROWN_600,
MaterialColors.PURPLE_600,
MaterialColors.BLUE_600,
MaterialColors.TEAL_600,
MaterialColors.ORANGE_600
)
}
}
| apache-2.0 | 9978ce60d32589a91ade78aa23304c6a | 31.732673 | 88 | 0.626134 | 4.770563 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/storage/messages/CheckFolderOperations.kt | 2 | 1292 | package com.fsck.k9.storage.messages
import com.fsck.k9.mailstore.LockableDatabase
internal class CheckFolderOperations(private val lockableDatabase: LockableDatabase) {
fun areAllIncludedInUnifiedInbox(folderIds: Collection<Long>): Boolean {
return lockableDatabase.execute(false) { database ->
var allIncludedInUnifiedInbox = true
performChunkedOperation(
arguments = folderIds,
argumentTransformation = Long::toString
) { selectionSet, selectionArguments ->
if (allIncludedInUnifiedInbox) {
database.rawQuery(
"SELECT COUNT(id) FROM folders WHERE integrate = 1 AND id $selectionSet", selectionArguments
).use { cursor ->
if (cursor.moveToFirst()) {
val count = cursor.getInt(0)
if (count != selectionArguments.size) {
allIncludedInUnifiedInbox = false
}
} else {
allIncludedInUnifiedInbox = false
}
}
}
}
allIncludedInUnifiedInbox
}
}
}
| apache-2.0 | 8cd9deb96301260a4944fb2d2e066ddf | 38.151515 | 116 | 0.51935 | 5.899543 | false | false | false | false |
k9mail/k-9 | mail/protocols/imap/src/main/java/com/fsck/k9/mail/store/imap/RealImapFolderIdler.kt | 2 | 6065 | package com.fsck.k9.mail.store.imap
import com.fsck.k9.logging.Timber
import com.fsck.k9.mail.MessagingException
import com.fsck.k9.mail.power.WakeLock
import java.io.IOException
private const val SOCKET_EXTRA_TIMEOUT_MS = 2 * 60 * 1000L
internal class RealImapFolderIdler(
private val idleRefreshManager: IdleRefreshManager,
private val wakeLock: WakeLock,
private val imapStore: ImapStore,
private val connectionProvider: ImapConnectionProvider,
private val folderServerId: String,
private val idleRefreshTimeoutProvider: IdleRefreshTimeoutProvider
) : ImapFolderIdler {
private val logTag = "ImapFolderIdler[$folderServerId]"
private var folder: ImapFolder? = null
@get:Synchronized
@set:Synchronized
private var idleRefreshTimer: IdleRefreshTimer? = null
@Volatile
private var stopIdle = false
private var idleSent = false
private var doneSent = false
override fun idle(): IdleResult {
Timber.v("%s.idle()", logTag)
val folder = imapStore.getFolder(folderServerId).also { this.folder = it }
folder.open(OpenMode.READ_ONLY)
try {
return folder.idle().also { idleResult ->
Timber.v("%s.idle(): result=%s", logTag, idleResult)
}
} finally {
folder.close()
}
}
@Synchronized
override fun refresh() {
Timber.v("%s.refresh()", logTag)
endIdle()
}
@Synchronized
override fun stop() {
Timber.v("%s.stop()", logTag)
stopIdle = true
endIdle()
}
private fun endIdle() {
if (idleSent && !doneSent) {
idleRefreshTimer?.cancel()
try {
sendDone()
} catch (e: IOException) {
Timber.v(e, "%s: IOException while sending DONE", logTag)
}
}
}
private fun ImapFolder.idle(): IdleResult {
var result = IdleResult.STOPPED
val connection = connectionProvider.getConnection(this)!!
if (!connection.isIdleCapable) {
Timber.w("%s: IDLE not supported by server", logTag)
return IdleResult.NOT_SUPPORTED
}
stopIdle = false
do {
synchronized(this) {
idleSent = false
doneSent = false
}
val tag = connection.sendCommand("IDLE", false)
synchronized(this) {
idleSent = true
}
var receivedRelevantResponse = false
do {
val response = connection.readResponse()
if (response.tag == tag) {
Timber.w("%s.idle(): IDLE command completed without a continuation request response", logTag)
return IdleResult.NOT_SUPPORTED
} else if (response.isRelevant) {
receivedRelevantResponse = true
}
} while (!response.isContinuationRequested)
if (receivedRelevantResponse) {
Timber.v("%s.idle(): Received a relevant untagged response right after sending IDLE command", logTag)
result = IdleResult.SYNC
stopIdle = true
sendDone()
} else {
connection.setSocketIdleReadTimeout()
}
var response: ImapResponse
do {
idleRefreshTimer = idleRefreshManager.startTimer(
timeout = idleRefreshTimeoutProvider.idleRefreshTimeoutMs,
callback = ::idleRefresh
)
wakeLock.release()
try {
response = connection.readResponse()
} finally {
wakeLock.acquire()
idleRefreshTimer?.cancel()
}
if (response.isRelevant && !stopIdle) {
Timber.v("%s.idle(): Received a relevant untagged response during IDLE", logTag)
result = IdleResult.SYNC
stopIdle = true
sendDone()
} else if (!response.isTagged) {
Timber.v("%s.idle(): Ignoring untagged response", logTag)
}
} while (response.tag != tag)
if (!response.isOk) {
throw MessagingException("Received non-OK response to IDLE command")
}
} while (!stopIdle)
return result
}
@Synchronized
private fun idleRefresh() {
Timber.v("%s.idleRefresh()", logTag)
if (!idleSent || doneSent) {
Timber.v("%s: Connection is not in a state where it can be refreshed.", logTag)
return
}
try {
sendDone()
} catch (e: IOException) {
Timber.v(e, "%s: IOException while sending DONE", logTag)
}
}
@Synchronized
private fun sendDone() {
val folder = folder ?: return
val connection = connectionProvider.getConnection(folder) ?: return
synchronized(connection) {
if (connection.isConnected) {
doneSent = true
connection.setSocketDefaultReadTimeout()
connection.sendContinuation("DONE")
}
}
}
private fun ImapConnection.setSocketIdleReadTimeout() {
setSocketReadTimeout((idleRefreshTimeoutProvider.idleRefreshTimeoutMs + SOCKET_EXTRA_TIMEOUT_MS).toInt())
}
private val ImapResponse.isRelevant: Boolean
get() {
return if (!isTagged && size >= 2) {
ImapResponseParser.equalsIgnoreCase(get(1), "EXISTS") ||
ImapResponseParser.equalsIgnoreCase(get(1), "EXPUNGE") ||
ImapResponseParser.equalsIgnoreCase(get(1), "FETCH")
} else {
false
}
}
private val ImapResponse.isOk: Boolean
get() = isTagged && size >= 1 && ImapResponseParser.equalsIgnoreCase(get(0), Responses.OK)
}
| apache-2.0 | 70c54e2cbe0a96eb961587fa68d51030 | 30.102564 | 117 | 0.555317 | 5.033195 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/reader/usecases/ReaderSiteNotificationsUseCase.kt | 1 | 4832 | package org.wordpress.android.ui.reader.usecases
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.analytics.AnalyticsTracker
import org.wordpress.android.datasets.ReaderBlogTableWrapper
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.AccountActionBuilder
import org.wordpress.android.fluxc.store.AccountStore.AddOrDeleteSubscriptionPayload
import org.wordpress.android.fluxc.store.AccountStore.AddOrDeleteSubscriptionPayload.SubscriptionAction
import org.wordpress.android.fluxc.store.AccountStore.AddOrDeleteSubscriptionPayload.SubscriptionAction.DELETE
import org.wordpress.android.fluxc.store.AccountStore.AddOrDeleteSubscriptionPayload.SubscriptionAction.NEW
import org.wordpress.android.fluxc.store.AccountStore.OnSubscriptionUpdated
import org.wordpress.android.ui.reader.tracker.ReaderTracker
import org.wordpress.android.ui.reader.usecases.ReaderSiteNotificationsUseCase.SiteNotificationState.Failed.AlreadyRunning
import org.wordpress.android.ui.reader.usecases.ReaderSiteNotificationsUseCase.SiteNotificationState.Failed.NoNetwork
import org.wordpress.android.ui.reader.usecases.ReaderSiteNotificationsUseCase.SiteNotificationState.Failed.RequestFailed
import org.wordpress.android.ui.reader.usecases.ReaderSiteNotificationsUseCase.SiteNotificationState.Success
import org.wordpress.android.util.AppLog
import org.wordpress.android.util.AppLog.T.API
import org.wordpress.android.util.NetworkUtilsWrapper
import javax.inject.Inject
import kotlin.coroutines.Continuation
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
/**
* This class handles reader notification events.
*/
class ReaderSiteNotificationsUseCase @Inject constructor(
private val dispatcher: Dispatcher,
private val readerTracker: ReaderTracker,
private val readerBlogTableWrapper: ReaderBlogTableWrapper,
private val networkUtilsWrapper: NetworkUtilsWrapper
) {
private var continuation: Continuation<Boolean>? = null
suspend fun toggleNotification(
blogId: Long,
feedId: Long
): SiteNotificationState {
if (continuation != null) {
return AlreadyRunning
}
if (!networkUtilsWrapper.isNetworkAvailable()) {
return NoNetwork
}
// We want to track the action no matter the result
trackEvent(blogId, feedId)
val succeeded = suspendCoroutine<Boolean> { cont ->
continuation = cont
val action = if (readerBlogTableWrapper.isNotificationsEnabled(blogId)) {
DELETE
} else {
NEW
}
updateSubscription(blogId, action)
}
return if (succeeded) {
updateNotificationEnabledForBlogInDb(blogId, !readerBlogTableWrapper.isNotificationsEnabled(blogId))
fetchSubscriptions()
Success
} else {
RequestFailed
}
}
private fun trackEvent(blogId: Long, feedId: Long) {
val trackingEvent = if (readerBlogTableWrapper.isNotificationsEnabled(blogId)) {
AnalyticsTracker.Stat.FOLLOWED_BLOG_NOTIFICATIONS_READER_MENU_OFF
} else {
AnalyticsTracker.Stat.FOLLOWED_BLOG_NOTIFICATIONS_READER_MENU_ON
}
readerTracker.trackBlog(trackingEvent, blogId, feedId)
}
fun updateNotificationEnabledForBlogInDb(blogId: Long, isNotificationEnabledForBlog: Boolean) {
readerBlogTableWrapper.setNotificationsEnabledByBlogId(blogId, isNotificationEnabledForBlog)
}
fun fetchSubscriptions() {
dispatcher.dispatch(AccountActionBuilder.newFetchSubscriptionsAction())
}
fun updateSubscription(blogId: Long, action: SubscriptionAction) {
val payload = AddOrDeleteSubscriptionPayload(blogId.toString(), action)
dispatcher.dispatch(AccountActionBuilder.newUpdateSubscriptionNotificationPostAction(payload))
}
@Suppress("unused")
@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onSubscriptionUpdated(event: OnSubscriptionUpdated) {
if (event.isError) {
continuation?.resume(false)
AppLog.e(
API,
ReaderSiteNotificationsUseCase::class.java.simpleName + ".onSubscriptionUpdated: " +
event.error.type + " - " + event.error.message
)
} else {
continuation?.resume(true)
}
continuation = null
}
sealed class SiteNotificationState {
object Success : SiteNotificationState()
sealed class Failed : SiteNotificationState() {
object NoNetwork : Failed()
object RequestFailed : Failed()
object AlreadyRunning : Failed()
}
}
}
| gpl-2.0 | 905fc787643280ba3389777f4077966f | 39.605042 | 122 | 0.729512 | 5.097046 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/internal/benchmark/HighlightingBenchmarkAction.kt | 1 | 8509 | // 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.actions.internal.benchmark
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl
import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar
import com.intellij.codeInsight.navigation.NavigationUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogBuilder
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.JBTextField
import com.intellij.uiDesigner.core.GridLayoutManager
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.onClosed
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.addBoxWithLabel
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.collectSuitableKotlinFiles
import org.jetbrains.kotlin.idea.actions.internal.benchmark.AbstractCompletionBenchmarkAction.Companion.shuffledSequence
import org.jetbrains.kotlin.idea.core.util.EDT
import org.jetbrains.kotlin.idea.base.psi.getLineCount
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.KtFile
import java.util.*
import javax.swing.JFileChooser
import kotlin.properties.Delegates
class HighlightingBenchmarkAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val settings = showSettingsDialog() ?: return
val random = Random(settings.seed)
fun collectFiles(): List<KtFile>? {
val ktFiles = collectSuitableKotlinFiles(project) { it.getLineCount() >= settings.lines }
if (ktFiles.size < settings.files) {
AbstractCompletionBenchmarkAction.showPopup(
project,
KotlinBundle.message("number.of.attempts.then.files.in.project.0", ktFiles.size)
)
return null
}
return ktFiles
}
val ktFiles = collectFiles() ?: return
val results = mutableListOf<Result>()
val connection = project.messageBus.connect()
ActionManager.getInstance().getAction("CloseAllEditors").actionPerformed(e)
val finishListener = DaemonFinishListener()
connection.subscribe(DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC, finishListener)
GlobalScope.launch(EDT) {
try {
delay(100)
ktFiles
.shuffledSequence(random)
.take(settings.files)
.forEach { file ->
results += openFileAndMeasureTimeToHighlight(file, project, finishListener)
}
saveResults(results, project)
} finally {
connection.disconnect()
finishListener.channel.close()
}
}
}
private data class Settings(val seed: Long, val files: Int, val lines: Int)
private inner class DaemonFinishListener : DaemonCodeAnalyzer.DaemonListener {
val channel = Channel<String>(capacity = Channel.CONFLATED)
override fun daemonFinished() {
channel.trySend(SUCCESS).onClosed { throw IllegalStateException(it) }
}
override fun daemonCancelEventOccurred(reason: String) {
channel.trySend(reason).onClosed { throw IllegalStateException(it) }
}
}
companion object {
private const val SUCCESS = "Success"
}
private fun showSettingsDialog(): Settings? {
var cSeed: JBTextField by Delegates.notNull()
var cFiles: JBTextField by Delegates.notNull()
var cLines: JBTextField by Delegates.notNull()
val dialogBuilder = DialogBuilder()
val jPanel = JBPanel<JBPanel<*>>(GridLayoutManager(3, 2)).apply {
var i = 0
cSeed = addBoxWithLabel(KotlinBundle.message("random.seed"), default = "0", i = i++)
cFiles = addBoxWithLabel(KotlinBundle.message("files.to.visit"), default = "20", i = i++)
cLines = addBoxWithLabel(KotlinBundle.message("minimal.line.count"), default = "100", i = i)
}
dialogBuilder.centerPanel(jPanel)
if (!dialogBuilder.showAndGet()) return null
return Settings(cSeed.text.toLong(), cFiles.text.toInt(), cLines.text.toInt())
}
private sealed class Result(val location: String, val lines: Int) {
abstract fun toCSV(builder: StringBuilder)
class Success(location: String, lines: Int, val time: Long, val status: String) : Result(location, lines) {
override fun toCSV(builder: StringBuilder): Unit = with(builder) {
append(location)
append(", ")
append(lines)
append(", ")
append(status)
append(", ")
append(time)
}
}
class Error(location: String, lines: Int = 0, val reason: String) : Result(location, lines) {
override fun toCSV(builder: StringBuilder): Unit = with(builder) {
append(location)
append(", ")
append(lines)
append(", fail: ")
append(reason)
append(", ")
}
}
}
private suspend fun openFileAndMeasureTimeToHighlight(file: KtFile, project: Project, finishListener: DaemonFinishListener): Result {
NavigationUtil.openFileWithPsiElement(file.navigationElement, true, true)
val location = file.virtualFile.path
val lines = file.getLineCount()
val document = PsiDocumentManager.getInstance(project).getDocument(file) ?: return Result.Error(location, lines, "No document")
val daemon = DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl
if (!daemon.isHighlightingAvailable(file)) return Result.Error(location, lines, "Highlighting not available")
if (!daemon.isRunningOrPending) return Result.Error(location, lines, "Analysis not running or pending")
val start = System.currentTimeMillis()
val outcome = finishListener.channel.receive()
if (outcome != SUCCESS) {
return Result.Error(location, lines, outcome)
}
val analysisTime = System.currentTimeMillis() - start
val model = DocumentMarkupModel.forDocument(document, project, true)
val severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project)
val maxSeverity = model.allHighlighters
.mapNotNull { highlighter ->
val info = highlighter.errorStripeTooltip as? HighlightInfo ?: return@mapNotNull null
info.severity
}.maxWithOrNull(severityRegistrar)
return Result.Success(location, lines, analysisTime, maxSeverity?.myName ?: "clean")
}
private fun saveResults(allResults: List<Result>, project: Project) {
val jfc = JFileChooser()
val result = jfc.showSaveDialog(null)
if (result == JFileChooser.APPROVE_OPTION) {
val file = jfc.selectedFile
file.writeText(buildString {
appendLine("n, file, lines, status, time")
var i = 0
allResults.forEach {
append(i++)
append(", ")
it.toCSV(this)
appendLine()
}
})
}
AbstractCompletionBenchmarkAction.showPopup(project, KotlinBundle.message("text.done"))
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = isApplicationInternalMode()
}
}
| apache-2.0 | 4f4c0809a3c1bb2804c8f2d060c34c2a | 38.761682 | 158 | 0.665061 | 5.101319 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.