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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_vertex_program.kt | 4 | 18402 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_vertex_program = "ARBVertexProgram".nativeClassGL("ARB_vertex_program", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
Unextended OpenGL mandates a certain set of configurable per-vertex computations defining vertex transformation, texture coordinate generation and
transformation, and lighting. Several extensions have added further per-vertex computations to OpenGL. For example, extensions have defined new texture
coordinate generation modes (${ARB_texture_cube_map.link}, ${NV_texgen_reflection.link}, ${registryLinkTo("NV", "texgen_emboss")}), new vertex
transformation modes (${ARB_vertex_blend.link}, ${registryLinkTo("EXT", "vertex_weighting")}), new lighting modes (OpenGL 1.2's separate specular and
rescale normal functionality), several modes for fog distance generation (${NV_fog_distance.link}), and eye-distance point size attenuation
(${ARB_point_parameters.link}).
Each such extension adds a small set of relatively inflexible per-vertex computations.
This inflexibility is in contrast to the typical flexibility provided by the underlying programmable floating point engines (whether micro-coded vertex
engines, DSPs, or CPUs) that are traditionally used to implement OpenGL's per-vertex computations. The purpose of this extension is to expose to the
OpenGL application writer a significant degree of per-vertex programmability for computing vertex parameters.
For the purposes of discussing this extension, a vertex program is a sequence of floating-point 4-component vector operations that determines how a set
of program parameters (defined outside of OpenGL's #Begin()/#End() pair) and an input set of per-vertex parameters are transformed to a set of
per-vertex result parameters.
The per-vertex computations for standard OpenGL given a particular set of lighting and texture coordinate generation modes (along with any state for
extensions defining per-vertex computations) is, in essence, a vertex program. However, the sequence of operations is defined implicitly by the current
OpenGL state settings rather than defined explicitly as a sequence of instructions.
This extension provides an explicit mechanism for defining vertex program instruction sequences for application-defined vertex programs. In order to
define such vertex programs, this extension defines a vertex programming model including a floating-point 4-component vector instruction set and a
relatively large set of floating-point 4-component registers.
The extension's vertex programming model is designed for efficient hardware implementation and to support a wide variety of vertex programs. By design,
the entire set of existing vertex programs defined by existing OpenGL per-vertex computation extensions can be implemented using the extension's vertex
programming model.
"""
IntConstant(
"""
Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of ProgramStringARB, BindProgramARB, ProgramEnvParameter4[df][v]ARB, ProgramLocalParameter4[df][v]ARB,
GetProgramEnvParameter[df]vARB, GetProgramLocalParameter[df]vARB, GetProgramivARB, and GetProgramStringARB.
""",
"VERTEX_PROGRAM_ARB"..0x8620
)
IntConstant(
"""
Accepted by the {@code cap} parameter of Disable, Enable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev.
""",
"VERTEX_PROGRAM_POINT_SIZE_ARB"..0x8642,
"VERTEX_PROGRAM_TWO_SIDE_ARB"..0x8643,
"COLOR_SUM_ARB"..0x8458
)
IntConstant(
"Accepted by the {@code format} parameter of ProgramStringARB.",
"PROGRAM_FORMAT_ASCII_ARB"..0x8875
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttrib[dfi]vARB.",
"VERTEX_ATTRIB_ARRAY_ENABLED_ARB"..0x8622,
"VERTEX_ATTRIB_ARRAY_SIZE_ARB"..0x8623,
"VERTEX_ATTRIB_ARRAY_STRIDE_ARB"..0x8624,
"VERTEX_ATTRIB_ARRAY_TYPE_ARB"..0x8625,
"VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB"..0x886A,
"CURRENT_VERTEX_ATTRIB_ARB"..0x8626
)
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttribPointervARB.",
"VERTEX_ATTRIB_ARRAY_POINTER_ARB"..0x8645
)
val PARAMS = IntConstant(
"Accepted by the {@code pname} parameter of GetProgramivARB.",
"PROGRAM_LENGTH_ARB"..0x8627,
"PROGRAM_FORMAT_ARB"..0x8876,
"PROGRAM_BINDING_ARB"..0x8677,
"PROGRAM_INSTRUCTIONS_ARB"..0x88A0,
"MAX_PROGRAM_INSTRUCTIONS_ARB"..0x88A1,
"PROGRAM_NATIVE_INSTRUCTIONS_ARB"..0x88A2,
"MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB"..0x88A3,
"PROGRAM_TEMPORARIES_ARB"..0x88A4,
"MAX_PROGRAM_TEMPORARIES_ARB"..0x88A5,
"PROGRAM_NATIVE_TEMPORARIES_ARB"..0x88A6,
"MAX_PROGRAM_NATIVE_TEMPORARIES_ARB"..0x88A7,
"PROGRAM_PARAMETERS_ARB"..0x88A8,
"MAX_PROGRAM_PARAMETERS_ARB"..0x88A9,
"PROGRAM_NATIVE_PARAMETERS_ARB"..0x88AA,
"MAX_PROGRAM_NATIVE_PARAMETERS_ARB"..0x88AB,
"PROGRAM_ATTRIBS_ARB"..0x88AC,
"MAX_PROGRAM_ATTRIBS_ARB"..0x88AD,
"PROGRAM_NATIVE_ATTRIBS_ARB"..0x88AE,
"MAX_PROGRAM_NATIVE_ATTRIBS_ARB"..0x88AF,
"PROGRAM_ADDRESS_REGISTERS_ARB"..0x88B0,
"MAX_PROGRAM_ADDRESS_REGISTERS_ARB"..0x88B1,
"PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"..0x88B2,
"MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB"..0x88B3,
"MAX_PROGRAM_LOCAL_PARAMETERS_ARB"..0x88B4,
"MAX_PROGRAM_ENV_PARAMETERS_ARB"..0x88B5,
"PROGRAM_UNDER_NATIVE_LIMITS_ARB"..0x88B6
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramStringARB.",
"PROGRAM_STRING_ARB"..0x8628
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"PROGRAM_ERROR_POSITION_ARB"..0x864B,
"CURRENT_MATRIX_ARB"..0x8641,
"TRANSPOSE_CURRENT_MATRIX_ARB"..0x88B7,
"CURRENT_MATRIX_STACK_DEPTH_ARB"..0x8640,
"MAX_VERTEX_ATTRIBS_ARB"..0x8869,
"MAX_PROGRAM_MATRICES_ARB"..0x862F,
"MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB"..0x862E
)
IntConstant(
"Accepted by the {@code name} parameter of GetString.",
"PROGRAM_ERROR_STRING_ARB"..0x8874
)
IntConstant(
"Accepted by the {@code mode} parameter of MatrixMode.",
"MATRIX0_ARB"..0x88C0,
"MATRIX1_ARB"..0x88C1,
"MATRIX2_ARB"..0x88C2,
"MATRIX3_ARB"..0x88C3,
"MATRIX4_ARB"..0x88C4,
"MATRIX5_ARB"..0x88C5,
"MATRIX6_ARB"..0x88C6,
"MATRIX7_ARB"..0x88C7,
"MATRIX8_ARB"..0x88C8,
"MATRIX9_ARB"..0x88C9,
"MATRIX10_ARB"..0x88CA,
"MATRIX11_ARB"..0x88CB,
"MATRIX12_ARB"..0x88CC,
"MATRIX13_ARB"..0x88CD,
"MATRIX14_ARB"..0x88CE,
"MATRIX15_ARB"..0x88CF,
"MATRIX16_ARB"..0x88D0,
"MATRIX17_ARB"..0x88D1,
"MATRIX18_ARB"..0x88D2,
"MATRIX19_ARB"..0x88D3,
"MATRIX20_ARB"..0x88D4,
"MATRIX21_ARB"..0x88D5,
"MATRIX22_ARB"..0x88D6,
"MATRIX23_ARB"..0x88D7,
"MATRIX24_ARB"..0x88D8,
"MATRIX25_ARB"..0x88D9,
"MATRIX26_ARB"..0x88DA,
"MATRIX27_ARB"..0x88DB,
"MATRIX28_ARB"..0x88DC,
"MATRIX29_ARB"..0x88DD,
"MATRIX30_ARB"..0x88DE,
"MATRIX31_ARB"..0x88DF
)
reuse(ARB_vertex_shader, "VertexAttrib1sARB")
reuse(ARB_vertex_shader, "VertexAttrib1fARB")
reuse(ARB_vertex_shader, "VertexAttrib1dARB")
reuse(ARB_vertex_shader, "VertexAttrib2sARB")
reuse(ARB_vertex_shader, "VertexAttrib2fARB")
reuse(ARB_vertex_shader, "VertexAttrib2dARB")
reuse(ARB_vertex_shader, "VertexAttrib3sARB")
reuse(ARB_vertex_shader, "VertexAttrib3fARB")
reuse(ARB_vertex_shader, "VertexAttrib3dARB")
reuse(ARB_vertex_shader, "VertexAttrib4sARB")
reuse(ARB_vertex_shader, "VertexAttrib4fARB")
reuse(ARB_vertex_shader, "VertexAttrib4dARB")
reuse(ARB_vertex_shader, "VertexAttrib4NubARB")
reuse(ARB_vertex_shader, "VertexAttrib1svARB")
reuse(ARB_vertex_shader, "VertexAttrib1fvARB")
reuse(ARB_vertex_shader, "VertexAttrib1dvARB")
reuse(ARB_vertex_shader, "VertexAttrib2svARB")
reuse(ARB_vertex_shader, "VertexAttrib2fvARB")
reuse(ARB_vertex_shader, "VertexAttrib2dvARB")
reuse(ARB_vertex_shader, "VertexAttrib3svARB")
reuse(ARB_vertex_shader, "VertexAttrib3fvARB")
reuse(ARB_vertex_shader, "VertexAttrib3dvARB")
reuse(ARB_vertex_shader, "VertexAttrib4fvARB")
reuse(ARB_vertex_shader, "VertexAttrib4bvARB")
reuse(ARB_vertex_shader, "VertexAttrib4svARB")
reuse(ARB_vertex_shader, "VertexAttrib4ivARB")
reuse(ARB_vertex_shader, "VertexAttrib4ubvARB")
reuse(ARB_vertex_shader, "VertexAttrib4usvARB")
reuse(ARB_vertex_shader, "VertexAttrib4uivARB")
reuse(ARB_vertex_shader, "VertexAttrib4dvARB")
reuse(ARB_vertex_shader, "VertexAttrib4NbvARB")
reuse(ARB_vertex_shader, "VertexAttrib4NsvARB")
reuse(ARB_vertex_shader, "VertexAttrib4NivARB")
reuse(ARB_vertex_shader, "VertexAttrib4NubvARB")
reuse(ARB_vertex_shader, "VertexAttrib4NusvARB")
reuse(ARB_vertex_shader, "VertexAttrib4NuivARB")
reuse(ARB_vertex_shader, "VertexAttribPointerARB")
reuse(ARB_vertex_shader, "EnableVertexAttribArrayARB")
reuse(ARB_vertex_shader, "DisableVertexAttribArrayARB")
val TARGET = GLenum("target", "the program target", "#VERTEX_PROGRAM_ARB #FRAGMENT_PROGRAM_ARB")
void(
"ProgramStringARB",
"""
Updates the program string for the current program object for {@code target}.
When a program string is loaded, it is interpreted according to syntactic and semantic rules corresponding to the program target specified by
{@code target}. If a program violates the syntactic or semantic restrictions of the program target, ProgramStringARB generates the error
#INVALID_OPERATION.
Additionally, ProgramString will update the program error position (#PROGRAM_ERROR_POSITION_ARB) and error string (#PROGRAM_ERROR_STRING_ARB). If a
program fails to load, the value of the program error position is set to the ubyte offset into the specified program string indicating where the first
program error was detected. If the program fails to load because of a semantic restriction that is not detected until the program is fully scanned, the
error position is set to the value of {@code len}. If a program loads successfully, the error position is set to the value negative one. The
implementation-dependent program error string contains one or more error or warning messages. If a program loads succesfully, the error string may
either contain warning messages or be empty.
""",
TARGET,
GLenum("format", "the format of the program string", "#PROGRAM_FORMAT_ASCII_ARB"),
AutoSize("string")..GLsizei("len", "the length of the program string, excluding the null-terminator"),
void.const.p("string", "an array of bytes representing the program string being loaded")
)
void(
"BindProgramARB",
"""
Creates a named program object by binding an unused program object name to a valid program target. Also can be used to bind an existing program object
to a program target.
""",
TARGET,
GLuint(
"program",
"""
the program object to bind. If {@code program} is zero, the default program object for {@code target} is bound. If {@code program} is the name of
an existing program object whose associated program target is {@code target}, the named program object is bound.
"""
)
)
void(
"DeleteProgramsARB",
"Deletes program objects.",
AutoSize("programs")..GLsizei("n", "the number of program object to delete"),
GLuint.const.p("programs", "an array of {@code n} program objects to be deleted")
)
void(
"GenProgramsARB",
"""
Returns {@code n} currently unused program names in {@code programs}. These names are marked as used, for the purposes of GenProgramsARB only, but
objects are created only when they are first bound using #BindProgramARB().
""",
AutoSize("programs")..GLsizei("n", "the number of program names to genereate"),
ReturnParam..GLuint.p("programs", "an array in which to return the generated program names")
)
val VP_INDEX = GLuint("index", "the environment parameter index")
val VP_X = "the {@code x} parameter component"
val VP_Y = "the {@code y} parameter component"
val VP_Z = "the {@code z} parameter component"
val VP_W = "the {@code w} parameter component"
val VP_V = "a buffer from which to read the parameter value"
void("ProgramEnvParameter4dARB", "Double version of #ProgramEnvParameter4fARB().", TARGET, VP_INDEX, GLdouble("x", VP_X), GLdouble("y", VP_Y), GLdouble("z", VP_Z), GLdouble("w", VP_W))
void("ProgramEnvParameter4dvARB", "Pointer version of #ProgramEnvParameter4dARB()", TARGET, VP_INDEX, Check(4)..GLdouble.const.p("params", VP_V))
void(
"ProgramEnvParameter4fARB",
"Updates the values of the program environment parameter numbered {@code index} for the specified program target {@code target}.",
TARGET,
VP_INDEX,
GLfloat("x", VP_X),
GLfloat("y", VP_Y),
GLfloat("z", VP_Z),
GLfloat("w", VP_W)
)
void("ProgramEnvParameter4fvARB", "Pointer version of #ProgramEnvParameter4fARB().", TARGET, VP_INDEX, Check(4)..GLfloat.const.p("params", VP_V))
void("ProgramLocalParameter4dARB", "Double version of #ProgramLocalParameter4fARB().", TARGET, VP_INDEX, GLdouble("x", VP_X), GLdouble("y", VP_Y), GLdouble("z", VP_Z), GLdouble("w", VP_W))
void("ProgramLocalParameter4dvARB", "Pointer version of #ProgramLocalParameter4dARB().", TARGET, VP_INDEX, Check(4)..GLdouble.const.p("params", VP_V))
void(
"ProgramLocalParameter4fARB",
"Updates the values of the program local parameter numbered {@code index} for the specified program target {@code target}.",
TARGET,
VP_INDEX,
GLfloat("x", VP_X),
GLfloat("y", VP_Y),
GLfloat("z", VP_Z),
GLfloat("w", VP_W)
)
void("ProgramLocalParameter4fvARB", "Pointer version of #ProgramLocalParameter4fARB().", TARGET, VP_INDEX, Check(4)..GLfloat.const.p("params", VP_V))
void(
"GetProgramEnvParameterfvARB",
"""
Obtain the current value for the program environment parameter numbered {@code index} for the specified program target {@code target}, and places the
information in the array {@code params}.
""",
TARGET,
VP_INDEX,
Check(4)..GLfloat.p("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramEnvParameterdvARB",
"Double version of #GetProgramEnvParameterfvARB().",
TARGET,
VP_INDEX,
Check(4)..GLdouble.p("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramLocalParameterfvARB",
"""
Obtain the current value for the program local parameter numbered {@code index} for the specified program target {@code target}, and places the
information in the array {@code params}.
""",
TARGET,
VP_INDEX,
Check(4)..GLfloat.p("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramLocalParameterdvARB",
"Double version of #GetProgramLocalParameterfvARB().",
TARGET,
VP_INDEX,
Check(4)..GLdouble.p("params", "a buffer in which to place the current parameter value")
)
void(
"GetProgramivARB",
"""
Obtains program state for the program target {@code target}, writing the state into the array given by {@code params}. GetProgramivARB can be used to
determine the properties of the currently bound program object or implementation limits for {@code target}.
""",
TARGET,
GLenum("pname", "the parameter to query", PARAMS),
ReturnParam..Check(1)..GLint.p("params", "an array in which to place the parameter value")
)
void(
"GetProgramStringARB",
"""
Obtains the program string for the program object bound to {@code target} and places the information in the array {@code string}.
{@code n} ubytes are returned into the array program where {@code n} is the length of the program in ubytes, as returned by #GetProgramivARB() when
{@code pname} is #PROGRAM_LENGTH_ARB. The program string is always returned using the format given when the program string was specified.
""",
TARGET,
GLenum("pname", "the parameter to query", "#PROGRAM_STRING_ARB"),
Check("glGetProgramiARB(target, GL_PROGRAM_LENGTH_ARB)", debug = true)..void.p("string", "an array in which to place the program string")
)
reuse(ARB_vertex_shader, "GetVertexAttribfvARB")
reuse(ARB_vertex_shader, "GetVertexAttribdvARB")
reuse(ARB_vertex_shader, "GetVertexAttribivARB")
reuse(ARB_vertex_shader, "GetVertexAttribPointervARB")
GLboolean(
"IsProgramARB",
"""
Returns #TRUE if {@code program} is the name of a program object. If {@code program} is zero or is a non-zero value that is not the name of a
program object, or if an error condition occurs, IsProgramARB returns #FALSE. A name returned by #GenProgramsARB(), but not yet bound, is not the
name of a program object.
""",
GLuint("program", "the program name")
)
} | bsd-3-clause | 9dedee7f4e21033890e1c5ae7a493a70 | 43.344578 | 192 | 0.674438 | 4.040843 | false | false | false | false |
octarine-noise/BetterFoliage | src/main/kotlin/mods/octarinecore/common/Geometry.kt | 1 | 11018 | package mods.octarinecore.common
import mods.octarinecore.cross
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumFacing.*
import net.minecraft.util.EnumFacing.Axis.*
import net.minecraft.util.EnumFacing.AxisDirection.NEGATIVE
import net.minecraft.util.EnumFacing.AxisDirection.POSITIVE
import net.minecraft.util.math.BlockPos
// ================================
// Axes and directions
// ================================
val axes = listOf(X, Y, Z)
val axisDirs = listOf(POSITIVE, NEGATIVE)
val EnumFacing.dir: AxisDirection get() = axisDirection
val AxisDirection.sign: String get() = when(this) { POSITIVE -> "+"; NEGATIVE -> "-" }
val forgeDirs = EnumFacing.values()
val forgeDirsHorizontal = listOf(NORTH, SOUTH, EAST, WEST)
val forgeDirOffsets = forgeDirs.map { Int3(it) }
val Pair<Axis, AxisDirection>.face: EnumFacing get() = when(this) {
X to POSITIVE -> EAST; X to NEGATIVE -> WEST;
Y to POSITIVE -> UP; Y to NEGATIVE -> DOWN;
Z to POSITIVE -> SOUTH; else -> NORTH;
}
val EnumFacing.perpendiculars: List<EnumFacing> get() =
axes.filter { it != this.axis }.cross(axisDirs).map { it.face }
val EnumFacing.offset: Int3 get() = forgeDirOffsets[ordinal]
/** Old ForgeDirection rotation matrix yanked from 1.7.10 */
val ROTATION_MATRIX: Array<IntArray> get() = arrayOf(
intArrayOf(0, 1, 4, 5, 3, 2, 6),
intArrayOf(0, 1, 5, 4, 2, 3, 6),
intArrayOf(5, 4, 2, 3, 0, 1, 6),
intArrayOf(4, 5, 2, 3, 1, 0, 6),
intArrayOf(2, 3, 1, 0, 4, 5, 6),
intArrayOf(3, 2, 0, 1, 4, 5, 6)
)
// ================================
// Vectors
// ================================
operator fun EnumFacing.times(scale: Double) =
Double3(directionVec.x.toDouble() * scale, directionVec.y.toDouble() * scale, directionVec.z.toDouble() * scale)
val EnumFacing.vec: Double3 get() = Double3(directionVec.x.toDouble(), directionVec.y.toDouble(), directionVec.z.toDouble())
operator fun BlockPos.plus(other: Int3) = BlockPos(x + other.x, y + other.y, z + other.z)
/** 3D vector of [Double]s. Offers both mutable operations, and immutable operations in operator notation. */
data class Double3(var x: Double, var y: Double, var z: Double) {
constructor(x: Float, y: Float, z: Float) : this(x.toDouble(), y.toDouble(), z.toDouble())
constructor(dir: EnumFacing) : this(dir.directionVec.x.toDouble(), dir.directionVec.y.toDouble(), dir.directionVec.z.toDouble())
companion object {
val zero: Double3 get() = Double3(0.0, 0.0, 0.0)
fun weight(v1: Double3, weight1: Double, v2: Double3, weight2: Double) =
Double3(v1.x * weight1 + v2.x * weight2, v1.y * weight1 + v2.y * weight2, v1.z * weight1 + v2.z * weight2)
}
// immutable operations
operator fun plus(other: Double3) = Double3(x + other.x, y + other.y, z + other.z)
operator fun unaryMinus() = Double3(-x, -y, -z)
operator fun minus(other: Double3) = Double3(x - other.x, y - other.y, z - other.z)
operator fun times(scale: Double) = Double3(x * scale, y * scale, z * scale)
operator fun times(other: Double3) = Double3(x * other.x, y * other.y, z * other.z)
/** Rotate this vector, and return coordinates in the unrotated frame */
fun rotate(rot: Rotation) = Double3(
rot.rotatedComponent(EAST, x, y, z),
rot.rotatedComponent(UP, x, y, z),
rot.rotatedComponent(SOUTH, x, y, z)
)
// mutable operations
fun setTo(other: Double3): Double3 { x = other.x; y = other.y; z = other.z; return this }
fun setTo(x: Double, y: Double, z: Double): Double3 { this.x = x; this.y = y; this.z = z; return this }
fun setTo(x: Float, y: Float, z: Float) = setTo(x.toDouble(), y.toDouble(), z.toDouble())
fun add(other: Double3): Double3 { x += other.x; y += other.y; z += other.z; return this }
fun add(x: Double, y: Double, z: Double): Double3 { this.x += x; this.y += y; this.z += z; return this }
fun sub(other: Double3): Double3 { x -= other.x; y -= other.y; z -= other.z; return this }
fun sub(x: Double, y: Double, z: Double): Double3 { this.x -= x; this.y -= y; this.z -= z; return this }
fun invert(): Double3 { x = -x; y = -y; z = -z; return this }
fun mul(scale: Double): Double3 { x *= scale; y *= scale; z *= scale; return this }
fun mul(other: Double3): Double3 { x *= other.x; y *= other.y; z *= other.z; return this }
fun rotateMut(rot: Rotation): Double3 {
val rotX = rot.rotatedComponent(EAST, x, y, z)
val rotY = rot.rotatedComponent(UP, x, y, z)
val rotZ = rot.rotatedComponent(SOUTH, x, y, z)
return setTo(rotX, rotY, rotZ)
}
// misc operations
infix fun dot(other: Double3) = x * other.x + y * other.y + z * other.z
infix fun cross(o: Double3) = Double3(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x)
val length: Double get() = Math.sqrt(x * x + y * y + z * z)
val normalize: Double3 get() = (1.0 / length).let { Double3(x * it, y * it, z * it) }
val nearestCardinal: EnumFacing get() = nearestAngle(this, forgeDirs.asIterable()) { it.vec }.first
}
/** 3D vector of [Int]s. Offers both mutable operations, and immutable operations in operator notation. */
data class Int3(var x: Int, var y: Int, var z: Int) {
constructor(dir: EnumFacing) : this(dir.directionVec.x, dir.directionVec.y, dir.directionVec.z)
constructor(offset: Pair<Int, EnumFacing>) : this(
offset.first * offset.second.directionVec.x,
offset.first * offset.second.directionVec.y,
offset.first * offset.second.directionVec.z
)
companion object {
val zero = Int3(0, 0, 0)
}
// immutable operations
operator fun plus(other: Int3) = Int3(x + other.x, y + other.y, z + other.z)
operator fun plus(other: Pair<Int, EnumFacing>) = Int3(
x + other.first * other.second.directionVec.x,
y + other.first * other.second.directionVec.y,
z + other.first * other.second.directionVec.z
)
operator fun unaryMinus() = Int3(-x, -y, -z)
operator fun minus(other: Int3) = Int3(x - other.x, y - other.y, z - other.z)
operator fun times(scale: Int) = Int3(x * scale, y * scale, z * scale)
operator fun times(other: Int3) = Int3(x * other.x, y * other.y, z * other.z)
/** Rotate this vector, and return coordinates in the unrotated frame */
fun rotate(rot: Rotation) = Int3(
rot.rotatedComponent(EAST, x, y, z),
rot.rotatedComponent(UP, x, y, z),
rot.rotatedComponent(SOUTH, x, y, z)
)
// mutable operations
fun setTo(other: Int3): Int3 { x = other.x; y = other.y; z = other.z; return this }
fun setTo(x: Int, y: Int, z: Int): Int3 { this.x = x; this.y = y; this.z = z; return this }
fun add(other: Int3): Int3 { x += other.x; y += other.y; z += other.z; return this }
fun sub(other: Int3): Int3 { x -= other.x; y -= other.y; z -= other.z; return this }
fun invert(): Int3 { x = -x; y = -y; z = -z; return this }
fun mul(scale: Int): Int3 { x *= scale; y *= scale; z *= scale; return this }
fun mul(other: Int3): Int3 { x *= other.x; y *= other.y; z *= other.z; return this }
fun rotateMut(rot: Rotation): Int3 {
val rotX = rot.rotatedComponent(EAST, x, y, z)
val rotY = rot.rotatedComponent(UP, x, y, z)
val rotZ = rot.rotatedComponent(SOUTH, x, y, z)
return setTo(rotX, rotY, rotZ)
}
}
// ================================
// Rotation
// ================================
val EnumFacing.rotations: Array<EnumFacing> get() =
Array(6) { idx -> EnumFacing.values()[ROTATION_MATRIX[ordinal][idx]] }
fun EnumFacing.rotate(rot: Rotation) = rot.forward[ordinal]
fun rot(axis: EnumFacing) = Rotation.rot90[axis.ordinal]
/**
* Class representing an arbitrary rotation (or combination of rotations) around cardinal axes by 90 degrees.
* In effect, a permutation of [ForgeDirection]s.
*/
@Suppress("NOTHING_TO_INLINE")
class Rotation(val forward: Array<EnumFacing>, val reverse: Array<EnumFacing>) {
operator fun plus(other: Rotation) = Rotation(
Array(6) { idx -> forward[other.forward[idx].ordinal] },
Array(6) { idx -> other.reverse[reverse[idx].ordinal] }
)
operator fun unaryMinus() = Rotation(reverse, forward)
operator fun times(num: Int) = when(num % 4) { 1 -> this; 2 -> this + this; 3 -> -this; else -> identity }
inline fun rotatedComponent(dir: EnumFacing, x: Int, y: Int, z: Int) =
when(reverse[dir.ordinal]) { EAST -> x; WEST -> -x; UP -> y; DOWN -> -y; SOUTH -> z; NORTH -> -z; else -> 0 }
inline fun rotatedComponent(dir: EnumFacing, x: Double, y: Double, z: Double) =
when(reverse[dir.ordinal]) { EAST -> x; WEST -> -x; UP -> y; DOWN -> -y; SOUTH -> z; NORTH -> -z; else -> 0.0 }
companion object {
// Forge rotation matrix is left-hand
val rot90 = Array(6) { idx -> Rotation(forgeDirs[idx].opposite.rotations, forgeDirs[idx].rotations) }
val identity = Rotation(forgeDirs, forgeDirs)
}
}
// ================================
// Miscellaneous
// ================================
/** List of all 12 box edges, represented as a [Pair] of [ForgeDirection]s */
val boxEdges = forgeDirs.flatMap { face1 -> forgeDirs.filter { it.axis > face1.axis }.map { face1 to it } }
/**
* Get the closest object to the specified point from a list of objects.
*
* @param[vertex] the reference point
* @param[objs] list of geomertric objects
* @param[objPos] lambda to calculate the position of an object
* @return [Pair] of (object, distance)
*/
fun <T> nearestPosition(vertex: Double3, objs: Iterable<T>, objPos: (T)-> Double3): Pair<T, Double> =
objs.map { it to (objPos(it) - vertex).length }.minBy { it.second }!!
/**
* Get the object closest in orientation to the specified vector from a list of objects.
*
* @param[vector] the reference vector (direction)
* @param[objs] list of geomertric objects
* @param[objAngle] lambda to calculate the orientation of an object
* @return [Pair] of (object, normalized dot product)
*/
fun <T> nearestAngle(vector: Double3, objs: Iterable<T>, objAngle: (T)-> Double3): Pair<T, Double> =
objs.map { it to objAngle(it).dot(vector) }.maxBy { it.second }!!
data class FaceCorners(val topLeft: Pair<EnumFacing, EnumFacing>,
val topRight: Pair<EnumFacing, EnumFacing>,
val bottomLeft: Pair<EnumFacing, EnumFacing>,
val bottomRight: Pair<EnumFacing, EnumFacing>) {
constructor(top: EnumFacing, left: EnumFacing) :
this(top to left, top to left.opposite, top.opposite to left, top.opposite to left.opposite)
val asArray = arrayOf(topLeft, topRight, bottomLeft, bottomRight)
val asList = listOf(topLeft, topRight, bottomLeft, bottomRight)
}
val faceCorners = forgeDirs.map { when(it) {
DOWN -> FaceCorners(SOUTH, WEST)
UP -> FaceCorners(SOUTH, EAST)
NORTH -> FaceCorners(WEST, UP)
SOUTH -> FaceCorners(UP, WEST)
WEST -> FaceCorners(SOUTH, UP)
EAST -> FaceCorners(SOUTH, DOWN)
}}
| mit | fe4d697271f96ee267dd13c93c4eaf28 | 47.968889 | 132 | 0.627246 | 3.296828 | false | false | false | false |
zhudyos/uia | server/src/main/kotlin/io/zhudy/uia/web/v1/WeixinResource.kt | 1 | 2915 | package io.zhudy.uia.web.v1
import io.zhudy.uia.BizCodeException
import io.zhudy.uia.BizCodes
import io.zhudy.uia.Config
import io.zhudy.uia.domain.User
import io.zhudy.uia.domain.UserSource
import io.zhudy.uia.domain.Weixin
import io.zhudy.uia.service.OAuth2Service
import io.zhudy.uia.service.UserService
import io.zhudy.uia.utils.WeixinUtils
import io.zhudy.uia.web.RequestParamException
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Controller
import spark.Request
import spark.Response
/**
* @author Kevin Zou ([email protected])
*/
@Controller
class WeixinResource(
val userService: UserService,
val oauth2Service: OAuth2Service,
val ssoAuthentication: SsoAuthentication
) {
val log = LoggerFactory.getLogger(WeixinResource::class.java)
fun handle(req: Request, resp: Response) {
val label = req.params("label") ?: throw RequestParamException("label")
val code = req.queryParams("code") ?: throw RequestParamException("code")
val app = Config.weixin.apps[label]
val appid = app?.get("app_id") ?: throw IllegalArgumentException("weixin 缺少标签")
val appSecret = app?.get("app_secret") ?: throw IllegalArgumentException("")
val token = WeixinUtils.getAccessToken(appid, appSecret, code)
val profile = WeixinUtils.getProfile(token)
log.debug("weixin profile: {}", profile)
if (profile.unionid.isNotEmpty()) {
var user: User
try {
user = userService.findByUnionid(profile.unionid)
} catch (e: BizCodeException) {
when (e.bizCode) {
BizCodes.C_2002 -> {
user = User(
source = UserSource.WEIXIN,
weixin = Weixin(
appid = appid,
openid = profile.openid,
unionid = profile.unionid
)
)
val uid = userService.save(user)
log.debug("weixin save user success. uid: {}", uid)
user = userService.findByUid(uid)
}
else -> {
throw e
}
}
}
ssoAuthentication.complete(req, resp, user)
return
}
log.warn("weixin 用户没有 unionid - {}", profile)
// ssoAuthentication.complete(req, resp)
// val label = exchange.queryParam("label") ?: throw RequestParamException("label")
// val code = exchange.queryParam("code") ?: throw RequestParamException("code")
// val token = getAccessToken(code, label)
//
// val info = getUserInfo(token)
// exchange.sendJson(info)
}
} | apache-2.0 | 8274552f6dcc6918fa3e49f91ccae23c | 35.25 | 90 | 0.568817 | 4.250733 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/settings/backup/provider/ExternalStorageBackup.kt | 1 | 5157 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.features.settings.backup.provider
import android.content.Context
import android.content.Intent
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.features.settings.backup.BackupEntry
import de.dreier.mytargets.features.settings.backup.BackupException
import de.dreier.mytargets.shared.SharedApplicationInstance.Companion
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.lang.ref.WeakReference
object ExternalStorageBackup {
private const val FOLDER_NAME = "MyTargets"
//If may get a full path that is not the right one, even if we don't have the SD Card there.
//We just need the "/mnt/extSdCard/" i.e and check if it's writable
//do what you need here
val microSdCardPath: File?
get() {
var strSDCardPath: String? = System.getenv("SECONDARY_STORAGE")
if (strSDCardPath == null || strSDCardPath.isEmpty()) {
strSDCardPath = System.getenv("EXTERNAL_SDCARD_STORAGE")
}
if (strSDCardPath != null) {
if (strSDCardPath.contains(":")) {
strSDCardPath = strSDCardPath.substring(0, strSDCardPath.indexOf(":"))
}
Timber.d("getMicroSdCardPath: %s", strSDCardPath)
val externalFilePath = File(strSDCardPath)
if (externalFilePath.exists() && externalFilePath.canWrite()) {
Timber.d("getMicroSdCardPath: %s", externalFilePath.absolutePath)
return externalFilePath
}
}
return null
}
@Throws(IOException::class)
private fun createDirectory(directory: File) {
directory.mkdir()
if (!directory.exists() || !directory.isDirectory) {
throw IOException(Companion.getStr(R.string.dir_not_created))
}
}
class AsyncRestore : IAsyncBackupRestore {
private var context: WeakReference<Context>? = null
override fun connect(context: Context, listener: IAsyncBackupRestore.ConnectionListener) {
this.context = WeakReference(context)
listener.onConnected()
}
override fun getBackups(listener: IAsyncBackupRestore.OnLoadFinishedListener) {
val backupDir = File(microSdCardPath, FOLDER_NAME)
if (backupDir.isDirectory) {
val backups = backupDir.listFiles()
.filter { isBackup(it) }
.map {
BackupEntry(
it.absolutePath,
it.lastModified(),
it.length()
)
}
.sortedByDescending { it.lastModifiedAt }
listener.onLoadFinished(backups)
}
}
private fun isBackup(file: File): Boolean {
return file.isFile && file.name.contains("backup_") && file.name.endsWith(".zip")
}
override fun restoreBackup(
backup: BackupEntry,
listener: IAsyncBackupRestore.BackupStatusListener
) {
val file = File(backup.fileId)
try {
BackupUtils.importZip(context!!.get()!!, FileInputStream(file))
listener.onFinished()
} catch (e: IOException) {
listener.onError(e.localizedMessage)
e.printStackTrace()
}
}
override fun deleteBackup(
backup: BackupEntry,
listener: IAsyncBackupRestore.BackupStatusListener
) {
if (File(backup.fileId).delete()) {
listener.onFinished()
} else {
listener.onError("Backup could not be deleted!")
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
return false
}
}
class Backup : IBlockingBackup {
@Throws(BackupException::class)
override fun performBackup(context: Context) {
try {
val backupDir = File(microSdCardPath, FOLDER_NAME)
createDirectory(backupDir)
val zipFile = File(backupDir, BackupUtils.backupName)
BackupUtils.zip(context, ApplicationInstance.db, FileOutputStream(zipFile))
} catch (e: IOException) {
throw BackupException(e.localizedMessage, e)
}
}
}
}
| gpl-2.0 | 639cfccafbd234faf2f34ed9734f7382 | 35.062937 | 98 | 0.603258 | 4.958654 | false | false | false | false |
Alkaizyr/Trees | src/binarysearchtree/Node.kt | 1 | 944 | package binarysearchtree
class Node<K: Comparable<K>, V>(var key: K, var value: V, var parent: Node<K, V>? = null) {
var left: Node<K, V>? = null
var right: Node<K, V>? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Node<*, *>
if (key != other.key) return false
if (value != other.value) return false
if (parent != other.parent) return false
if (left != other.left) return false
if (right != other.right) return false
return true
}
override fun hashCode(): Int {
var result = key.hashCode()
result = 31 * result + (value?.hashCode() ?: 0)
result = 31 * result + (parent?.hashCode() ?: 0)
result = 31 * result + (left?.hashCode() ?: 0)
result = 31 * result + (right?.hashCode() ?: 0)
return result
}
} | mit | 53f8e2207ed427fb14e52da1ec7e3cac | 29.483871 | 91 | 0.558263 | 3.884774 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/SignInHandler.kt | 1 | 7402 | package se.barsk.park
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import se.barsk.park.analytics.UserProperties
import se.barsk.park.error.FailedToSignInException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
// Google documentation for sign-in: https://developers.google.com/identity/sign-in/android/start
// Also useful: https://stackoverflow.com/questions/38737021/how-to-refresh-id-token-after-it-expires-when-integrating-google-sign-in-on-andr
/**
* Handler for signing in to the app.
*/
open class SignInHandler(context: Context, protected val listener: StatusChangedListener) {
interface StatusChangedListener {
fun onSignedIn()
fun onSignedOut()
fun onSignInFailed(statusCode: Int)
}
companion object {
const val REQUEST_CODE_SIGN_IN = 1
private const val CLIENT_ID = "536672052707-hil8ei6h2m1e6aktfqhva5cjmpk6raoj.apps.googleusercontent.com"
fun getMessageForStatusCode(context: Context, statusCode: Int): String = when (statusCode) {
com.google.android.gms.common.api.CommonStatusCodes.NETWORK_ERROR ->
context.getString(R.string.sign_in_network_error)
else ->
context.getString(R.string.sign_in_unknown_error, statusCode)
}
}
var token: String? = null
private val gso: GoogleSignInOptions
private val client: GoogleSignInClient
private var lastSignedInAccount: GoogleSignInAccount? = null
init {
gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken(CLIENT_ID)
.build()
client = GoogleSignIn.getClient(context, gso)
}
open fun isSignedIn() = lastSignedInAccount != null
open fun getAccountName(): String = lastSignedInAccount?.email ?: ""
/**
* Tries to sign in the user. If the user is already signed in and the idToken is
* valid it will complete immediately. If the user is signed in but the idToken
* has expired it will refresh the token asynchronously. If the user is not signed
* in handleSignInResult will fail with GoogleSignInStatusCodes.SIGN_IN_REQUIRED.
*
* Only tries to sign in if a new enough version of Google play services is installed.
*
* @param activity If onStop is called on the given activity the login will be aborted
* @param onSuccess function to run once the login has finished successfully
*/
open fun silentSignIn(activity: Activity, onSuccess: (() -> Unit)? = null) {
if (GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(activity) !=
com.google.android.gms.common.api.CommonStatusCodes.SUCCESS) {
// If Google play services doesn't exist we know the attempt will fail
// so don't do anything in that case
return
}
check(onSuccess == null || onSignInSuccessCallback == null) {
// If this happens multiple sign in attempts are done at once.
"onSignInSuccessCallback is not null"
}
onSignInSuccessCallback = onSuccess
client.silentSignIn().addOnCompleteListener(activity) { completedTask ->
handleSignInResult(completedTask)
}
}
// Normal non-silent sign in is done trough a separate activity and since it's not
// easy to pass a callback between activities this property is used to hold the
// callback that should be called when the sign in is successful
private var onSignInSuccessCallback: (() -> Unit)? = null
open fun signIn(activity: Activity, onSuccess: (() -> Unit)?) {
val availability = GoogleApiAvailability.getInstance()
val statusCode = availability.isGooglePlayServicesAvailable(activity)
// Have the system show an error dialog if Google play services isn't installed
val errorDialogShown = availability.showErrorDialogFragment(activity, statusCode, 0)
if (!errorDialogShown) {
// Only try to sign in if Google play services is installed.
onSignInSuccessCallback = onSuccess
activity.startActivityForResult(client.signInIntent, REQUEST_CODE_SIGN_IN)
}
}
open fun signOut() {
client.signOut()
lastSignedInAccount = null
token = null
listener.onSignedOut()
ParkApp.analytics.setProperty(UserProperties.propertySignedIn, UserProperties.valueNo)
}
/**
* Fetches an up to date id token or throws an exception if the token can't be fetched.
*/
suspend fun getToken(activity: Activity): String = suspendCoroutine { continuation ->
silentSignIn(activity) {
val idToken = token
if (idToken != null) {
continuation.resume(idToken)
} else {
continuation.resumeWithException(FailedToSignInException("Unable to get id token"))
}
}
}
fun onSignInResult(data: Intent?) {
handleSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data))
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
// Documentation provides no information on when null is returned by getResult
// and it doesn't check for null in any examples. Assume that getResult never
// return null in this case.
val account = completedTask.getResult(ApiException::class.java)
lastSignedInAccount = account
token = account.idToken
listener.onSignedIn()
ParkApp.analytics.setProperty(UserProperties.propertySignedIn, UserProperties.valueYes)
// Do the success callback as a new message so the sign in process can finish completely
val callback = onSignInSuccessCallback
if (callback != null) {
Handler().post { callback.invoke() }
}
} catch (e: ApiException) {
lastSignedInAccount = null
token = null
when (e.statusCode) {
com.google.android.gms.common.api.CommonStatusCodes.SIGN_IN_REQUIRED -> {
// Silent sign in attempt and user is not signed in. No need to
// notify user about that.
}
com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes.SIGN_IN_CANCELLED,
com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes.SIGN_IN_CURRENTLY_IN_PROGRESS -> {
// Failures during sign in that can be silently ignored.
}
else -> {
// Normal sign in attempt failed
listener.onSignInFailed(e.statusCode)
}
}
}
onSignInSuccessCallback = null
}
} | mit | e2b9fa0f90077f71501148c76f3ee03f | 42.804734 | 141 | 0.669008 | 4.85059 | false | false | false | false |
PaulWoitaschek/MaterialAudiobookPlayer | app/src/main/java/de/ph1b/audiobook/features/settings/SettingsController.kt | 1 | 3856 | package de.ph1b.audiobook.features.settings
import androidx.annotation.StringRes
import de.ph1b.audiobook.R
import de.ph1b.audiobook.features.BaseController
import de.ph1b.audiobook.features.bookPlaying.SeekDialogController
import de.ph1b.audiobook.features.settings.dialogs.AutoRewindDialogController
import de.ph1b.audiobook.features.settings.dialogs.SupportDialogController
import de.ph1b.audiobook.features.settings.dialogs.ThemePickerDialogController
import de.ph1b.audiobook.injection.PrefKeys
import de.ph1b.audiobook.injection.appComponent
import de.ph1b.audiobook.misc.tint
import de.ph1b.audiobook.persistence.pref.Pref
import de.ph1b.audiobook.uitools.ThemeUtil
import kotlinx.android.synthetic.main.settings.*
import javax.inject.Inject
import javax.inject.Named
/**
* Controller for the user settings
*/
class SettingsController : BaseController() {
@field:[Inject Named(PrefKeys.THEME)]
lateinit var themePref: Pref<ThemeUtil.Theme>
@field:[Inject Named(PrefKeys.RESUME_ON_REPLUG)]
lateinit var resumeOnReplugPref: Pref<Boolean>
@field:[Inject Named(PrefKeys.AUTO_REWIND_AMOUNT)]
lateinit var autoRewindAmountPref: Pref<Int>
@field:[Inject Named(PrefKeys.SEEK_TIME)]
lateinit var seekTimePref: Pref<Int>
init {
appComponent.inject(this)
}
override val layoutRes = R.layout.settings
override fun onViewCreated() {
setupToolbar()
// theme
setupTextSetting(
doubleSettingView = theme,
titleRes = R.string.pref_theme_title
) {
ThemePickerDialogController().showDialog(router)
}
themePref.stream
.subscribe { theme.setDescription(it.nameId) }
.disposeOnDestroyView()
// resume on playback
setupSwitchSetting(
settingView = resumePlayback,
titleRes = R.string.pref_resume_on_replug,
contentRes = R.string.pref_resume_on_replug_hint,
pref = resumeOnReplugPref
)
// skip amount
setupTextSetting(
doubleSettingView = skipAmount,
titleRes = R.string.pref_seek_time
) {
SeekDialogController().showDialog(router)
}
seekTimePref.stream
.map { resources!!.getQuantityString(R.plurals.seconds, it, it) }
.subscribe { skipAmount.setDescription(it) }
.disposeOnDestroyView()
// auto rewind
setupTextSetting(
doubleSettingView = autoRewind,
titleRes = R.string.pref_auto_rewind_title
) {
AutoRewindDialogController().showDialog(router)
}
autoRewindAmountPref.stream
.map { resources!!.getQuantityString(R.plurals.seconds, it, it) }
.subscribe { autoRewind.setDescription(it) }
.disposeOnDestroyView()
}
private fun setupToolbar() {
toolbar.inflateMenu(R.menu.menu_settings)
toolbar.tint()
toolbar.setOnMenuItemClickListener {
if (it.itemId == R.id.action_contribute) {
SupportDialogController().showDialog(router)
true
} else
false
}
toolbar.setNavigationOnClickListener {
activity.onBackPressed()
}
}
private inline fun setupTextSetting(
doubleSettingView: DoubleSettingView,
@StringRes titleRes: Int,
@StringRes contentRes: Int? = null,
crossinline onClick: () -> Unit
) {
doubleSettingView.setTitle(titleRes)
if (contentRes != null) doubleSettingView.setDescription(contentRes)
doubleSettingView.setOnClickListener {
onClick()
}
}
private fun setupSwitchSetting(
settingView: SwitchSettingView,
@StringRes titleRes: Int,
@StringRes contentRes: Int,
pref: Pref<Boolean>
) {
settingView.setTitle(titleRes)
settingView.setDescription(contentRes)
settingView.onCheckedChanged {
pref.value = it
}
pref.stream
.subscribe { settingView.setChecked(it) }
.disposeOnDestroyView()
settingView.setOnClickListener { settingView.toggle() }
}
}
| lgpl-3.0 | 2d3c4ccc791fd2ffa1ad02f4f933325a | 28.212121 | 78 | 0.721473 | 4.155172 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/pages/RenderTarget.kt | 1 | 9804 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// PdfLayoutMgr 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.pages
import com.planbase.pdf.lm2.attributes.LineStyle
import com.planbase.pdf.lm2.attributes.PageArea
import com.planbase.pdf.lm2.attributes.TextStyle
import com.planbase.pdf.lm2.contents.ScaledImage.WrappedImage
import com.planbase.pdf.lm2.utils.Coord
import com.planbase.pdf.lm2.utils.Dim
import com.planbase.pdf.lm2.utils.LineJoinStyle
import com.planbase.pdf.lm2.utils.LineJoinStyle.MITER
import org.apache.pdfbox.pdmodel.graphics.color.PDColor
/**
* Represents something to be drawn to. For page-breaking, use the [PageGrouping]
* implementation. For a fixed, single page use the [SinglePage] implementation.
*/
interface RenderTarget {
/** the offset and size of the body area. */
val body: PageArea
/**
* Draws a line from (x1, y1) to (x2, y2). Direction is important if using mitering.
*
* @param start the Coord of the starting point
* @param end the Coord of the ending point
* @param lineStyle the style to draw the line with
* @param lineJoinStyle the style for joining the segments (default is [LineJoinStyle.MITER]).
* @param reallyRender Only render this if true (default). Otherwise, just measure and return.
* @return the updated RenderTarget (may be changed to return the lowest y-value instead)
*/
@JvmDefault
fun drawLine(start: Coord,
end: Coord,
lineStyle: LineStyle,
lineJoinStyle: LineJoinStyle = MITER,
reallyRender: Boolean = true): IntRange =
drawLineStrip(listOf(start, end), lineStyle, lineJoinStyle, reallyRender)
/** Draws a line from (x1, y1) to (x2, y2). Convenience function for [drawLine] */
@JvmDefault
fun drawLine(start: Coord,
end: Coord,
lineStyle: LineStyle): IntRange
= drawLine(start, end, lineStyle, MITER, true)
/**
* Draws lines from the first point to the last using the given line style. PDF allows only one line style for
* an entire line strip.
*
* @param points the list of Coord to draw lines between. This does *not* connect the last point to the first.
* If you want that, add the first point again at the end of the list.
* @param lineStyle the style to draw the line with
* @param lineJoinStyle the style for joining the segments (default is [LineJoinStyle.MITER]).
* @param reallyRender Only render this if true. Otherwise, just measure and return.
* @return the updated RenderTarget (may be changed to return the lowest y-value instead)
*/
fun drawLineStrip(points: List<Coord>,
lineStyle: LineStyle,
lineJoinStyle: LineJoinStyle = MITER,
reallyRender: Boolean = true): IntRange
/**
* Draws lines from the first point to the last. Convenience function for [drawLineStrip]
*/
@JvmDefault
fun drawLineStrip(points: List<Coord>,
lineStyle: LineStyle): IntRange =
drawLineStrip(points, lineStyle, MITER, true)
/**
* Draws a closed path.
*
* @param points the list of Coord to draw lines between. The last point is assumed to connect back to the first.
* @param lineStyle the style to draw all lines with. PDF only allows one line width and color per path.
* @param lineJoinStyle the style for joining the segments (default is [LineJoinStyle.MITER]).
* @param fillColor if non-null, fill the closed shape with this color. Uses the "Nonzero Winding Number Rule"
* (8.5.3.3.2) to determine what represents the inside of the shape and must be filled.
* @param reallyRender Only render this if true. Otherwise, just measure and return.
* @return the updated RenderTarget (may be changed to return the lowest y-value instead)
*/
fun drawLineLoop(points: List<Coord>,
lineStyle: LineStyle,
lineJoinStyle: LineJoinStyle = MITER,
fillColor: PDColor? = null,
reallyRender: Boolean): IntRange
/** Draws a closed path. Convenience function for [drawLineLoop]. */
@JvmDefault
fun drawLineLoop(points: List<Coord>,
lineStyle: LineStyle): IntRange =
drawLineLoop(points, lineStyle, MITER, null, true)
/**
* Puts styled text on this RenderTarget
* @param baselineLeft the Coord of the left-hand baseline point. Ascent goes above, descent and leading below.
* @param text the text
* @param textStyle the style
* @param reallyRender Only render this if true. Otherwise, just measure and return.
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
fun drawStyledText(baselineLeft: Coord,
textStyle: TextStyle,
text: String,
reallyRender: Boolean = true): HeightAndPage
/**
* Puts styled text on this RenderTarget
* @param baselineLeft the Coord of the left-hand baseline point. Ascent goes above, descent and leading below.
* @param text the text
* @param textStyle the style
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
@JvmDefault
fun drawStyledText(baselineLeft: Coord,
textStyle: TextStyle,
text: String): HeightAndPage =
drawStyledText(baselineLeft, textStyle, text, true)
/**
* Puts an image on this RenderTarget
* @param bottomLeft the Coord of the lower-left-hand corner
* @param wi the scaled, "wrapped" jpeg/png image
* @param zIdx lower values get drawn earlier.
* @param reallyRender Only render this if true. Otherwise, just measure and return.
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
fun drawImage(bottomLeft: Coord,
wi: WrappedImage,
zIdx:Double,
reallyRender: Boolean = true): HeightAndPage
/**
* Puts an image on this RenderTarget
* @param bottomLeft the Coord of the lower-left-hand corner
* @param wi the scaled, "wrapped" jpeg/png image
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
@JvmDefault
fun drawImage(bottomLeft: Coord,
wi: WrappedImage): HeightAndPage =
drawImage(bottomLeft, wi, DEFAULT_Z_INDEX, true)
/**
* Puts a colored rectangle on this RenderTarget. There is no outline or border (that's drawn
* separately with textLines).
* @param bottomLeft the Coord of the lower-left-hand corner
* @param dim width and height (dim) of rectangle
* @param c color
* @param reallyRender Only render this if true. Otherwise, just measure and return.
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
fun fillRect(bottomLeft: Coord,
dim: Dim,
c: PDColor,
reallyRender: Boolean = true): Double
/**
* Puts a colored rectangle on this RenderTarget. There is no outline or border (that's drawn
* separately with textLines).
* @param bottomLeft the Coord of the lower-left-hand corner
* @param dim width and height (dim) of rectangle
* @param c color
* @return the effective height after page breaking
* (may include some extra space above to push items onto the next page).
*/
@JvmDefault
fun fillRect(bottomLeft: Coord,
dim: Dim,
c: PDColor): Double =
fillRect(bottomLeft, dim, c, true)
/**
* Returns the top margin necessary to push this item onto a new page if it won't fit on this one.
* If it will fit, simply returns 0.
* @param bottomY the un-adjusted (bottom) y value.
* @param height the height
* @param requiredSpaceBelow if there isn't this much space left at the bottom of the page, move chunk to the top
* of the next page.
*/
// TODO: I keep passing y, 0.0, 0.0 instead of y - height, height, 0.0, so maybe I should make it work that way instead!
fun pageBreakingTopMargin(bottomY: Double,
height: Double = 0.0,
requiredSpaceBelow: Double = 0.0): Double
/**
* Returns the correct page for the given Y value but MAY ACTUALLY ADD THAT PAGE, so only call if really rendering
*/
fun pageNumFor(y:Double):Int
companion object {
const val DEFAULT_Z_INDEX = 0.0
}
} | agpl-3.0 | 1302cc9770adfa51a57a03ea07a4036f | 43.977064 | 124 | 0.658609 | 4.434193 | false | false | false | false |
google/intellij-community | platform/usageView/src/com/intellij/usages/similarity/statistics/SimilarUsagesCollector.kt | 1 | 3128 | // 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.usages.similarity.statistics
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.project.Project
import com.intellij.usages.similarity.clustering.ClusteringSearchSession
class SimilarUsagesCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private val GROUP = EventLogGroup("similar.usages", 3)
private val SESSION_ID = EventFields.Int("id")
private val NUMBER_OF_LOADED = EventFields.Int("number_of_loaded")
private val MOST_COMMON_USAGE_PATTERNS_SHOWN = GROUP.registerEvent("most.common.usages.shown", SESSION_ID)
private val MOST_COMMON_USAGE_PATTERNS_REFRESH_CLICKED = GROUP.registerEvent("most.common.usage.patterns.refresh.clicked", SESSION_ID)
private val LINK_TO_SIMILAR_USAGES_FROM_USAGE_PREVIEW_CLICKED = GROUP.registerEvent("link.to.similar.usage.clicked", SESSION_ID)
private val SHOW_SIMILAR_USAGES_LINK_CLICKED = GROUP.registerEvent("show.similar.usages.link.clicked", SESSION_ID)
private val MORE_CLUSTERS_LOADED = GROUP.registerEvent("more.clusters.loaded", SESSION_ID, NUMBER_OF_LOADED)
private val MORE_USAGES_LOADED = GROUP.registerEvent("more.usages.loaded", SESSION_ID, NUMBER_OF_LOADED)
private val MORE_NON_CLUSTERED_USAGES_LOADED = GROUP.registerEvent("more.non.clustered.usage.loaded", SESSION_ID, NUMBER_OF_LOADED)
@JvmStatic
fun logMoreSimilarUsagePatternsShow(project: Project, session: ClusteringSearchSession) {
MOST_COMMON_USAGE_PATTERNS_SHOWN.log(project, session.uniqueId)
}
@JvmStatic
fun logMostCommonUsagePatternsRefreshClicked(project: Project, session: ClusteringSearchSession) {
MOST_COMMON_USAGE_PATTERNS_REFRESH_CLICKED.log(project, session.uniqueId)
}
@JvmStatic
fun logLinkToSimilarUsagesLinkFromUsagePreviewClicked(project: Project, session: ClusteringSearchSession) {
LINK_TO_SIMILAR_USAGES_FROM_USAGE_PREVIEW_CLICKED.log(project, session.uniqueId)
}
@JvmStatic
fun logShowSimilarUsagesLinkClicked(project: Project, session: ClusteringSearchSession) {
SHOW_SIMILAR_USAGES_LINK_CLICKED.log(project, session.uniqueId)
}
@JvmStatic
fun logMoreClustersLoaded(project: Project, session: ClusteringSearchSession, numberOfAddedUsages: Int) {
MORE_CLUSTERS_LOADED.log(project, session.uniqueId, numberOfAddedUsages)
}
@JvmStatic
fun logMoreNonClusteredUsagesLoaded(project: Project, session: ClusteringSearchSession, numberOfAddedUsages: Int) {
MORE_NON_CLUSTERED_USAGES_LOADED.log(project, session.uniqueId, numberOfAddedUsages)
}
@JvmStatic
fun logMoreUsagesLoaded(project: Project, session: ClusteringSearchSession, numberOfAddedUsages: Int) {
MORE_USAGES_LOADED.log(project, session.uniqueId, numberOfAddedUsages)
}
}
} | apache-2.0 | 576dc91c01403de2989c8b34fdd1d7e6 | 51.15 | 138 | 0.780051 | 4.062338 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/to/Link.kt | 2 | 5695 | /*
* 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 org.apache.causeway.client.kroviz.to
import kotlinx.serialization.Serializable
import org.apache.causeway.client.kroviz.utils.StringUtils
@Serializable
data class Link(
val rel: String = "",
val method: String = Method.GET.operation,
val href: String,
val type: String = "",
//RO SPEC OR CAUSEWAY IMPL? can "args" be folded into "arguments"
val args: Map<String, Argument> = emptyMap(),
/* arguments can either be:
* -> empty Map {}
* -> Map with "value": null (cf. SO_PROPERTY)
* -> Map with empty key "" (cf. ACTIONS_DOWNLOAD_META_MODEL)
* -> Map with key,<VALUE> (cf. ACTIONS_RUN_FIXTURE_SCRIPT, ACTIONS_FIND_BY_NAME, ACTIONS_CREATE) */
val arguments: Map<String, Argument?> = emptyMap(),
val title: String = "",
) : TransferObject {
fun argMap(): Map<String, Argument?>? {
return when {
arguments.isNotEmpty() -> arguments
args.isNotEmpty() -> args
else -> null
}
}
fun setArgument(key: String, value: String?) {
val k = StringUtils.enCamel(key)
val arg = argMap()!!.get(k)
arg!!.key = k
arg.value = value
}
fun hasArguments(): Boolean {
return !argMap().isNullOrEmpty()
}
fun isProperty(): Boolean {
return relation() == Relation.PROPERTY
}
fun isAction(): Boolean {
return relation() == Relation.ACTION
}
fun name(): String {
return href.split("/").last()
}
fun relation(): Relation {
val roPrefix = "urn:org.restfulobjects:rels/"
val causewayPrefix = "urn:org.apache.causeway.restfulobjects:rels/"
var raw = rel.replace(roPrefix, "")
raw = raw.replace(causewayPrefix, "")
if (raw.contains(";")) {
raw = raw.split(";").first() //TODO handle args=value separated by ;
}
return Relation.find(raw)!!
}
fun representation(): Represention {
var s = type.replace("application/json", "")
s = s.replace(";", "") // ; may be missing
s = s.replace("profile=\"urn:org.restfulobjects:repr-types/", "")
s = s.replace("\"", "")
val rep = Represention.find(s) ?: Represention.UNKNOWN
if (rep == Represention.UNKNOWN) {
console.log("[Link.representation]")
console.log(s)
}
return rep
}
fun simpleType(): String {
val stringList = type.split("/")
val t = stringList.last()
return t.removeSuffix("\"")
}
}
/**
* RO SPEC restfulobject-spec.pdf §2.7.1
* extends ->
* IANA SPEC http://www.iana.org/assignments/link-relations/link-relations.xml
*/
enum class Relation(val type: String) {
ACTION("action"),
CLEAR("clear"),
DESCRIBED_BY("describedby"), //CAUSEWAY. IANA:"describedBy"
DETAILS("details"),
DOMAIN_TYPE("domain-type"),
DOMAIN_TYPES("domain-types"),
ELEMENT("element"),
ELEMENT_TYPE("element-type"),
HELP("help"), //IANA
ICON("icon"), //IANA
INVOKE("invoke"),
LAYOUT("layout"),
LOGOUT("logout"),
MENU_BARS("menuBars"),
MODIFY("modify"),
NEXT("next"), //IANA
OBJECT_ICON("object-icon"),
OBJECT_LAYOUT("object-layout"),
PREVIOUS("previous"), //IANA
PROPERTY("property"),
RETURN_TYPE("return-type"),
SELF("self"), //IANA
SERVICE("service"), //specified in both IANA & RO
SERVICES("services"),
UP("up"), //IANA
UPDATE("update"),
USER("user"),
VALUE("value"),
VERSION("version");
companion object {
fun find(value: String): Relation? = Relation.values().find { it.type == value }
}
}
/**
* RO SPEC restfulobject-spec.pdf §2.4.1
*/
enum class Represention(val type: String) {
ACTION("action"), // missing in RO SPEC ???
ACTION_DESCRIPTION("action-description"),
ACTION_RESULT("action-result"),
ACTION_PARAM_DESCRIPTION("action-param-description"),
COLLECTION_DESCRIPTION("collection-description"),
DOMAIN_TYPE("domain-type"),
ERROR("error"),
HOMEPAGE("homepage"),
IMAGE_PNG("image/png"),
LAYOUT_MENUBARS("layout-menubars"),
LAYOUT_BS3("layout-bs3"),
LIST("list"),
OBJECT("object"),
OBJECT_ACTION("object-action"),
OBJECT_COLLECTION("object-collection"),
OBJECT_LAYOUT_BS("object-layout-bs"), // missing in RO SPEC ???
OBJECT_PROPERTY("object-property"),
PROPERTY_DESCRIPTION("property-description"),
SELF("self"),
TYPE_LIST("type-list"),
TYPE_ACTION_RESULT("type-action-result"),
UNKNOWN("unknown"), // added by joerg.rade
USER("user"),
VERSION("version");
companion object {
fun find(value: String): Represention? = Represention.values().find { it.type == value }
}
}
| apache-2.0 | b93624a39b7b6bd39c60403b5f4fe9a6 | 30.983146 | 104 | 0.606534 | 3.995088 | false | false | false | false |
JetBrains/intellij-community | plugins/full-line/src/org/jetbrains/completion/full/line/platform/diagnostics/log.kt | 1 | 3152 | package org.jetbrains.completion.full.line.platform.diagnostics
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.Disposer
import com.intellij.util.EventDispatcher
import java.util.*
private val LOG = logger<DiagnosticsService>()
interface FullLineLogger {
fun error(throwable: Throwable)
fun debug(text: String)
fun debug(text: String, throwable: Throwable)
fun info(text: String)
fun warn(text: String, throwable: Throwable)
val isDebugEnabled: Boolean
}
@Service
class DiagnosticsService : Disposable {
private val dispatcher = EventDispatcher.create(DiagnosticsListener::class.java)
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment) {
dispatcher.addListener(object : DiagnosticsListener {
val console = InMemoryLogConsole()
init {
Disposer.register(this@DiagnosticsService, console)
}
override fun messageReceived(message: DiagnosticsListener.Message) {
console.addMessage(message)
}
})
}
}
fun subscribe(listener: DiagnosticsListener, parentDisposable: Disposable) {
dispatcher.addListener(listener, parentDisposable)
}
fun logger(part: FullLinePart, log: Logger = LOG): FullLineLogger {
return object : FullLineLogger {
override fun error(throwable: Throwable) = warn("Error happened", throwable)
override fun debug(text: String) = onMessage(text) { debug(text) }
override fun info(text: String) = onMessage(text) { info(text) }
override fun debug(text: String, throwable: Throwable) = onMessage(text) { debug(text, throwable) }
override fun warn(text: String, throwable: Throwable) = onMessage(text) { warn(text, throwable) }
private fun onMessage(text: String, block: Logger.() -> Unit) {
log.block()
notifyListeners(text)
}
private fun notifyListeners(text: String) {
if (!dispatcher.hasListeners()) return
val message = DiagnosticsListener.Message(text, System.currentTimeMillis(), part)
dispatcher.multicaster.messageReceived(message)
}
override val isDebugEnabled: Boolean = log.isDebugEnabled || dispatcher.hasListeners()
}
}
override fun dispose() {
}
companion object {
fun getInstance(): DiagnosticsService {
return service()
}
}
}
inline fun <reified T : Any> logger(part: FullLinePart): FullLineLogger = DiagnosticsService.getInstance().logger(part, logger<T>())
interface DiagnosticsListener : EventListener {
fun messageReceived(message: Message)
data class Message(val text: String, val time: Long, val part: FullLinePart)
}
enum class FullLinePart {
BEAM_SEARCH, // beam search of local models
NETWORK, // answers and delays for network
PRE_PROCESSING, // preprocessing of FL proposals before showing
POST_PROCESSING, // preprocessing of FL proposals after showing
}
| apache-2.0 | 2ae1aa4ec7f6f18dc7c1631b193e1081 | 30.52 | 132 | 0.726523 | 4.541787 | false | false | false | false |
apollographql/apollo-android | tests/integration-tests/src/commonTest/kotlin/test/FetchPolicyTest.kt | 1 | 6736 | package test
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.cache.normalized.FetchPolicy
import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory
import com.apollographql.apollo3.cache.normalized.executeCacheAndNetwork
import com.apollographql.apollo3.cache.normalized.fetchPolicy
import com.apollographql.apollo3.cache.normalized.isFromCache
import com.apollographql.apollo3.cache.normalized.store
import com.apollographql.apollo3.exception.ApolloCompositeException
import com.apollographql.apollo3.integration.normalizer.HeroNameQuery
import com.apollographql.apollo3.mockserver.MockResponse
import com.apollographql.apollo3.mockserver.MockServer
import com.apollographql.apollo3.mockserver.enqueue
import com.apollographql.apollo3.testing.enqueue
import com.apollographql.apollo3.testing.runTest
import kotlinx.coroutines.flow.toList
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.fail
@OptIn(ApolloExperimental::class)
class FetchPolicyTest {
private lateinit var mockServer: MockServer
private lateinit var apolloClient: ApolloClient
private lateinit var store: ApolloStore
private suspend fun setUp() {
store = ApolloStore(MemoryCacheFactory())
mockServer = MockServer()
apolloClient = ApolloClient.Builder().serverUrl(mockServer.url()).store(store).build()
}
private suspend fun tearDown() {
mockServer.stop()
}
@Test
fun cacheFirst() = runTest(before = { setUp() }, after = { tearDown() }) {
val query = HeroNameQuery()
val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2"))
mockServer.enqueue(query, data)
// First query should hit the network and save in cache
var response = apolloClient.query(query)
.fetchPolicy(FetchPolicy.NetworkFirst)
.execute()
assertNotNull(response.data)
assertFalse(response.isFromCache)
// Second query should only hit the cache
response = apolloClient.query(query).execute()
assertNotNull(response.data)
assertTrue(response.isFromCache)
// Clear the store and offer a malformed response, we should get a composite error
store.clearAll()
mockServer.enqueue("malformed")
try {
apolloClient.query(query).execute()
fail("we expected the query to fail")
} catch (e: Exception) {
assertTrue(e is ApolloCompositeException)
}
}
@Test
fun networkFirst() = runTest(before = { setUp() }, after = { tearDown() }) {
val query = HeroNameQuery()
val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2"))
val call = apolloClient.query(query).fetchPolicy(FetchPolicy.NetworkFirst)
// First query should hit the network and save in cache
mockServer.enqueue(query, data)
var response = call.execute()
assertNotNull(response.data)
assertFalse(response.isFromCache)
// Now data is cached but it shouldn't be used since network will go through
mockServer.enqueue(query, data)
response = call.execute()
assertNotNull(response.data)
assertFalse(response.isFromCache)
// Network error -> we should hit now the cache
mockServer.enqueue("malformed")
response = call.execute()
assertNotNull(response.data)
assertTrue(response.isFromCache)
// Network error and no cache -> we should get an error
mockServer.enqueue("malformed")
store.clearAll()
try {
call.execute()
fail("NETWORK_FIRST should throw the network exception if nothing is in the cache")
} catch (e: Exception) {
}
}
@Test
fun cacheOnly() = runTest(before = { setUp() }, after = { tearDown() }) {
val query = HeroNameQuery()
val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2"))
// First query should hit the network and save in cache
mockServer.enqueue(query, data)
var response = apolloClient.query(query).execute()
assertNotNull(response.data)
assertFalse(response.isFromCache)
// Second query should only hit the cache
response = apolloClient.query(query).fetchPolicy(FetchPolicy.CacheOnly).execute()
// And make sure we don't read the network
assertNotNull(response.data)
assertTrue(response.isFromCache)
}
@Test
fun networkOnly() = runTest(before = { setUp() }, after = { tearDown() }) {
val query = HeroNameQuery()
val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2"))
val call = apolloClient.query(query).fetchPolicy(FetchPolicy.NetworkOnly)
// First query should hit the network and save in cache
mockServer.enqueue(query, data)
val response = call.execute()
assertNotNull(response.data)
assertFalse(response.isFromCache)
// Offer a malformed response, it should fail
mockServer.enqueue("malformed")
try {
call.execute()
fail("we expected a failure")
} catch (e: Exception) {
}
}
@Test
fun queryCacheAndNetwork() = runTest(before = { setUp() }, after = { tearDown() }) {
val query = HeroNameQuery()
val data = HeroNameQuery.Data(HeroNameQuery.Hero("R2-D2"))
// Initial state: everything fails
// Cache Error + Network Error => Error
mockServer.enqueue(MockResponse(statusCode = 500))
assertFailsWith(ApolloCompositeException::class) {
apolloClient.query(query).executeCacheAndNetwork().toList()
}
// Make the network return something
// Cache Error + Nework Success => 1 response
mockServer.enqueue(query, data)
var responses = apolloClient.query(query).executeCacheAndNetwork().toList()
assertEquals(1, responses.size)
assertNotNull(responses[0].data)
assertFalse(responses[0].isFromCache)
assertEquals("R2-D2", responses[0].data?.hero?.name)
// Now cache is populated but make the network fail again
// Cache Success + Network Error => 1 response
mockServer.enqueue(MockResponse(statusCode = 500))
responses = apolloClient.query(query).executeCacheAndNetwork().toList()
assertEquals(1, responses.size)
assertNotNull(responses[0].data)
assertTrue(responses[0].isFromCache)
assertEquals("R2-D2", responses[0].data?.hero?.name)
// Cache Success + Network Success => 1 response
mockServer.enqueue(query, data)
responses = apolloClient.query(query).executeCacheAndNetwork().toList()
assertEquals(2, responses.size)
assertNotNull(responses[0].data)
assertTrue(responses[0].isFromCache)
assertNotNull(responses[1].data)
assertFalse(responses[1].isFromCache)
}
} | mit | b2e5684ec5e9ec62987004e6f0faf05a | 32.517413 | 90 | 0.72981 | 4.472776 | false | true | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/reference/clientlib/provider/CdImportReferenceProvider.kt | 1 | 2137 | package com.aemtools.reference.clientlib.provider
import com.aemtools.lang.clientlib.psi.CdInclude
import com.aemtools.lang.util.basePathElement
import com.aemtools.reference.common.reference.PsiFileReference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceProvider
import com.intellij.util.ProcessingContext
/**
* @author Dmytro_Troynikov
*/
object CdImportReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement,
context: ProcessingContext): Array<PsiReference> {
val include = element.originalElement as? CdInclude
?: return emptyArray()
val path = addBasePath(include.text, include)
val file = include.containingFile.containingDirectory?.myRelativeFile(path)
if (file != null) {
return arrayOf(PsiFileReference(file, include, TextRange(0, include.textLength)))
}
return arrayOf()
}
/**
* Get element relative to current directory.
*
* @return relative element, *null* if no such element exists
*/
private fun PsiDirectory.myRelativeFile(path: String): PsiFile? {
val normalizedPath = if (path.startsWith("./")) {
path.substringAfter("./")
} else {
path
}
when {
normalizedPath.startsWith("../") ->
return this.parentDirectory?.myRelativeFile(path.substringAfter("../"))
normalizedPath.contains("/") -> {
val subdirName = normalizedPath.split("/")[0]
val subdir = this.findSubdirectory(subdirName)
?: return null
val subPath = normalizedPath.substring(normalizedPath.indexOf("/") + 1)
return subdir.myRelativeFile(subPath)
}
else -> return this.findFile(normalizedPath)
}
}
private fun addBasePath(path: String, include: CdInclude): String {
val basePath = include.basePathElement()?.include?.text
return if (basePath != null) {
"$basePath/$path"
} else {
path
}
}
}
| gpl-3.0 | 9a1e6bc17f52fbcae3b202f3c6f8824e | 29.971014 | 88 | 0.690688 | 4.442827 | false | false | false | false |
zdary/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/JavaAbstractUElement.kt | 4 | 5446 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.java
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.java.internal.JavaUElementWithComments
abstract class JavaAbstractUElement(givenParent: UElement?) : JavaUElementWithComments, UElement {
override fun equals(other: Any?): Boolean {
if (other !is UElement || other.javaClass != this.javaClass) return false
return if (this.sourcePsi != null) this.sourcePsi == other.sourcePsi else this === other
}
override fun hashCode(): Int = sourcePsi?.hashCode() ?: System.identityHashCode(this)
override fun asSourceString(): String {
return this.sourcePsi?.text ?: super<JavaUElementWithComments>.asSourceString()
}
override fun toString(): String = asRenderString()
override val uastParent: UElement? by lz { givenParent ?: convertParent() }
protected open fun convertParent(): UElement? =
getPsiParentForLazyConversion()
?.let { JavaConverter.unwrapElements(it).toUElement() }
?.let { unwrapSwitch(it) }
?.let { wrapSingleExpressionLambda(it) }
?.also {
if (it === this) throw IllegalStateException("lazy parent loop for $this")
if (it.sourcePsi != null && it.sourcePsi === this.sourcePsi)
throw IllegalStateException("lazy parent loop: sourcePsi ${this.sourcePsi}(${this.sourcePsi?.javaClass}) for $this of ${this.javaClass}")
}
protected open fun getPsiParentForLazyConversion(): PsiElement? = this.sourcePsi?.parent
//explicitly overridden in abstract class to be binary compatible with Kotlin
override val comments: List<UComment>
get() = super<JavaUElementWithComments>.comments
abstract override val sourcePsi: PsiElement?
override val javaPsi: PsiElement?
get() = super<JavaUElementWithComments>.javaPsi
@Suppress("OverridingDeprecatedMember")
override val psi: PsiElement?
get() = sourcePsi
}
private fun JavaAbstractUElement.wrapSingleExpressionLambda(uParent: UElement): UElement {
val sourcePsi = sourcePsi
return if (uParent is JavaULambdaExpression && sourcePsi is PsiExpression)
(uParent.body as? UBlockExpression)?.expressions?.singleOrNull() ?: uParent
else uParent
}
private fun JavaAbstractUElement.unwrapSwitch(uParent: UElement): UElement {
when (uParent) {
is UBlockExpression -> {
val codeBlockParent = uParent.uastParent
when (codeBlockParent) {
is JavaUSwitchEntryList -> {
if (branchHasElement(sourcePsi, codeBlockParent.sourcePsi) { it is PsiSwitchLabelStatementBase }) {
return codeBlockParent
}
val psiElement = sourcePsi ?: return uParent
return codeBlockParent.findUSwitchEntryForBodyStatementMember(psiElement)?.body ?: return codeBlockParent
}
is UExpressionList -> {
val sourcePsi = codeBlockParent.sourcePsi
if (sourcePsi is PsiSwitchLabeledRuleStatement)
(codeBlockParent.uastParent as? JavaUSwitchEntry)?.let { return it.body }
}
is JavaUSwitchExpression -> return unwrapSwitch(codeBlockParent)
}
return uParent
}
is JavaUSwitchEntry -> {
val parentSourcePsi = uParent.sourcePsi
if (parentSourcePsi is PsiSwitchLabeledRuleStatement && parentSourcePsi.body?.children?.contains(sourcePsi) == true) {
val psi = sourcePsi
return if (psi is PsiExpression && uParent.body.expressions.size == 1)
DummyYieldExpression(psi, uParent.body)
else uParent.body
}
else
return uParent
}
is USwitchExpression -> {
val parentPsi = uParent.sourcePsi as PsiSwitchBlock
return if (this === uParent.body || branchHasElement(sourcePsi, parentPsi) { it === parentPsi.expression })
uParent
else
uParent.body
}
else -> return uParent
}
}
private inline fun branchHasElement(child: PsiElement?, parent: PsiElement?, predicate: (PsiElement) -> Boolean): Boolean {
var current: PsiElement? = child
while (current != null && current != parent) {
if (predicate(current)) return true
current = current.parent
}
return false
}
abstract class JavaAbstractUExpression(givenParent: UElement?) : JavaAbstractUElement(givenParent), UExpression {
override fun evaluate(): Any? {
val project = sourcePsi?.project ?: return null
return JavaPsiFacade.getInstance(project).constantEvaluationHelper.computeConstantExpression(sourcePsi)
}
override val uAnnotations: List<UAnnotation>
get() = emptyList()
override fun getExpressionType(): PsiType? {
val expression = sourcePsi as? PsiExpression ?: return null
return expression.type
}
override fun getPsiParentForLazyConversion(): PsiElement? = super.getPsiParentForLazyConversion()?.let {
when (it) {
is PsiResourceExpression -> it.parent
is PsiReferenceExpression -> (it.parent as? PsiMethodCallExpression) ?: it
else -> it
}
}
override fun convertParent(): UElement? = super.convertParent().let { uParent ->
when (uParent) {
is UAnonymousClass -> uParent.uastParent
else -> uParent
}
}.let(this::unwrapCompositeQualifiedReference)
override val lang: Language
get() = JavaLanguage.INSTANCE
}
| apache-2.0 | 00d3048c5d0729605ab7bce14829bf61 | 34.594771 | 147 | 0.709144 | 5.118421 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/FloatingToolbarComponentImpl.kt | 1 | 3436 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.toolbar.floating
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.util.Disposer
import com.intellij.ui.JBColor
import java.awt.*
import javax.swing.BorderFactory
import javax.swing.JComponent
import javax.swing.JPanel
class FloatingToolbarComponentImpl(
parentComponent: JComponent,
private val contextComponent: JComponent,
actionGroup: ActionGroup,
autoHideable: Boolean,
parentDisposable: Disposable
) : JPanel(), FloatingToolbarComponent, DataProvider {
private val actionToolbar: ActionToolbar
private val visibilityController: VisibilityController
override fun update() = actionToolbar.updateActionsImmediately()
override fun scheduleShow() = visibilityController.scheduleShow()
override fun scheduleHide() = visibilityController.scheduleHide()
override fun getData(dataId: String): Any? {
if (FloatingToolbarComponent.KEY.`is`(dataId)) return this
val dataManager = DataManager.getInstance()
val dataContext = dataManager.getDataContext(contextComponent)
return dataContext.getData(dataId)
}
override fun paintChildren(g: Graphics) {
val graphics = g.create() as Graphics2D
try {
val alpha = visibilityController.opacity * FOREGROUND_ALPHA
graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)
super.paintChildren(graphics)
}
finally {
graphics.dispose()
}
}
override fun paint(g: Graphics) {
paintComponent(g)
super.paint(g)
}
override fun paintComponent(g: Graphics) {
val r = bounds
val graphics = g.create() as Graphics2D
try {
val alpha = visibilityController.opacity * BACKGROUND_ALPHA
graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
graphics.color = BACKGROUND
graphics.fillRoundRect(0, 0, r.width, r.height, 6, 6)
}
finally {
graphics.dispose()
}
}
init {
layout = BorderLayout(0, 0)
border = BorderFactory.createEmptyBorder()
isOpaque = false
isVisible = false
actionToolbar = ActionToolbarImpl(ActionPlaces.CONTEXT_TOOLBAR, actionGroup, true)
actionToolbar.setTargetComponent(this)
actionToolbar.setMinimumButtonSize(Dimension(22, 22))
actionToolbar.setSkipWindowAdjustments(true)
actionToolbar.setReservePlaceAutoPopupIcon(false)
actionToolbar.isOpaque = false
add(actionToolbar, BorderLayout.CENTER)
visibilityController = ToolbarVisibilityController(autoHideable, parentComponent, actionToolbar, this)
visibilityController.scheduleHide()
Disposer.register(parentDisposable, visibilityController)
}
companion object {
val BACKGROUND = JBColor.namedColor("Toolbar.Floating.background", JBColor(0xEDEDED, 0x454A4D))
private const val BACKGROUND_ALPHA = 0.9f
private const val FOREGROUND_ALPHA = 1.0f
}
} | apache-2.0 | 124d916b01a6d75ef528ddb9fb0565c9 | 34.43299 | 140 | 0.767753 | 4.643243 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/core/Meta.kt | 1 | 2801 | package slatekit.apis.core
import org.json.simple.JSONObject
import slatekit.apis.support.JsonSupport
import slatekit.common.*
import slatekit.common.crypto.Encryptor
// import java.time.*
import org.threeten.bp.*
import slatekit.common.convert.Conversions
import slatekit.common.values.Metadata
/**
* Used to represent a request that originates from a json file.
* This is useful for automation purposes and replaying an api action from a file source.
* @param rawSource : Raw source
* @param json : JSON object
* @param enc : Encryptor
*/
data class Meta(
val rawSource: Any,
val json: JSONObject,
val enc: Encryptor?
) : Metadata, JsonSupport {
override val raw: Any = json
override fun toJson(): JSONObject = json
override fun toMap(): Map<String, Any> {
val pairs = json.keys.map { key -> Pair(key?.toString() ?: "", json.get(key) ?: "") }
return pairs.toMap()
}
override fun size(): Int = json.size
override fun get(key: String): Any? = getStringRaw(key)
// override fun getObject(key: String): Any? = getStringRaw(key)
override fun containsKey(key: String): Boolean = json.containsKey(key)
override fun getString(key: String): String = Strings.decrypt(getStringRaw(key).trim()) { it -> enc?.decrypt(it) ?: it }
override fun getBool(key: String): Boolean = Conversions.toBool(getStringRaw(key))
override fun getShort(key: String): Short = Conversions.toShort(getStringRaw(key))
override fun getInt(key: String): Int = Conversions.toInt(getStringRaw(key))
override fun getLong(key: String): Long = Conversions.toLong(getStringRaw(key))
override fun getFloat(key: String): Float = Conversions.toFloat(getStringRaw(key))
override fun getDouble(key: String): Double = Conversions.toDouble(getStringRaw(key))
override fun getInstant(key: String): Instant = Conversions.toInstant(getStringRaw(key))
override fun getDateTime(key: String): DateTime = Conversions.toDateTime(getStringRaw(key))
override fun getLocalDate(key: String): LocalDate = Conversions.toLocalDate(getStringRaw(key))
override fun getLocalTime(key: String): LocalTime = Conversions.toLocalTime(getStringRaw(key))
override fun getLocalDateTime(key: String): LocalDateTime = Conversions.toLocalDateTime(getStringRaw(key))
override fun getZonedDateTime(key: String): ZonedDateTime = Conversions.toZonedDateTime(getStringRaw(key))
override fun getZonedDateTimeUtc(key: String): ZonedDateTime = Conversions.toZonedDateTimeUtc(getStringRaw(key))
private fun getInternalString(key: String): String {
return if (containsKey(key)) {
json.get(key) as String
} else {
""
}
}
private fun getStringRaw(key: String): String = getInternalString(key).trim()
}
| apache-2.0 | a09e1e5e1d22c585ee4740de50f39bb2 | 44.918033 | 124 | 0.721171 | 4.218373 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/Channel.kt | 1 | 2287 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Entity
import com.vimeo.networking2.common.Followable
import java.util.Date
/**
* Channel information.
*
* @param categories The categories to which this channel belongs as specified by the channel moderators.
* @param createdTime The time in ISO 8601 format when the channel was created.
* @param description A brief explanation of the channel's content.
* @param header The banner that appears by default at the top of the channel page.
* @param link The URL to access the channel in a browser.
* @param modifiedTime The time in ISO 8601 format when the album was last modified.
* @param name The display name that identifies the channel.
* @param pictures The active image for the channel; defaults to the thumbnail of the last video added to the channel.
* @param privacy The privacy settings of the channel.
* @param resourceKey The channel resource key.
* @param tags An array of all tags assigned to this channel.
* @param uri The unique identifier to access the channel resource.
* @param user The Vimeo user who owns the channel.
*/
@JsonClass(generateAdapter = true)
data class Channel(
@Json(name = "categories")
val categories: List<Category>? = null,
@Json(name = "created_time")
val createdTime: Date? = null,
@Json(name = "description")
val description: String? = null,
@Json(name = "header")
val header: PictureCollection? = null,
@Json(name = "link")
val link: String? = null,
@Json(name = "metadata")
override val metadata: Metadata<ChannelConnections, ChannelInteractions>? = null,
@Json(name = "modified_time")
val modifiedTime: Date? = null,
@Json(name = "name")
val name: String? = null,
@Json(name = "pictures")
val pictures: PictureCollection? = null,
@Json(name = "privacy")
val privacy: Privacy? = null,
@Json(name = "resource_key")
val resourceKey: String? = null,
@Json(name = "tags")
val tags: List<Tag>? = null,
@Json(name = "uri")
val uri: String? = null,
@Json(name = "user")
val user: User? = null
) : Followable, Entity {
override val identifier: String? = resourceKey
}
| mit | 949f435928bc7e7502c85398a1157d59 | 30.328767 | 118 | 0.697857 | 3.943103 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/SymbolNavigationServiceImpl.kt | 4 | 1809 | // 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.codeInsight.navigation.impl
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiSymbolService
import com.intellij.navigation.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClassExtension
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
@ApiStatus.Internal
class SymbolNavigationServiceImpl : SymbolNavigationService {
private val ourExtension = ClassExtension<SymbolNavigationProvider>("com.intellij.symbolNavigation")
override fun getNavigationTargets(project: Project, symbol: Symbol): Collection<NavigationTarget> {
val result = SmartList<NavigationTarget>()
for (provider: SymbolNavigationProvider in ourExtension.forKey(symbol.javaClass)) {
result += provider.getNavigationTargets(project, symbol)
}
if (symbol is NavigatableSymbol) {
result += symbol.getNavigationTargets(project)
}
val element = PsiSymbolService.getInstance().extractElementFromSymbol(symbol)
if (element != null) {
result += PsiElementNavigationTarget(element)
}
return result
}
override fun psiFileNavigationTarget(file: PsiFile): NavigationTarget {
return PsiFileNavigationTarget(file)
}
override fun psiElementNavigationTarget(element: PsiElement): NavigationTarget {
return PsiElementNavigationTarget(element)
}
override fun presentationBuilder(presentableText: @Nls String): TargetPresentationBuilder {
return TargetPresentationBuilderImpl(presentableText = presentableText)
}
}
| apache-2.0 | 8440b66400a8a6337a9f5632120a8d3c | 38.326087 | 158 | 0.793809 | 4.902439 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/tests/git4idea/push/GitPushNativeResultParserTest.kt | 9 | 7148 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.push
import git4idea.push.GitPushNativeResult.Type.*
import git4idea.push.GitPushNativeResultParser.parse
import org.junit.Assert.assertEquals
import org.junit.Test
class GitPushNativeResultParserTest {
val STANDARD_PREFIX = """
Counting objects: 20, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (20/20), 1.70 KiB | 0 bytes/s, done.
Total 20 (delta 7), reused 0 (delta 0)
To /Users/loki/sandbox/git/parent.git
""".trimIndent()
val TARGET_PREFIX = "To http://example.com/git/parent.git"
val PUSH_DEFAULT_WARNING = """
warning: push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.
Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.
See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)
""".trimIndent()
val SUCCESS_SUFFIX = "Done"
val REJECT_SUFFIX = """
Done
error: failed to push some refs to '/Users/loki/sandbox/git/parent.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
""".trimIndent()
@Test
fun success() {
val output = " \trefs/heads/master:refs/heads/master\t3e62822..a537351"
val results = parse(listOf(STANDARD_PREFIX, TARGET_PREFIX, output, SUCCESS_SUFFIX))
assertSingleResult(SUCCESS, "refs/heads/master", "3e62822..a537351", null, results)
}
@Test
fun successUpToCommit() {
val output = " \t4915ba17cc8b718d58ae77dd25018fccdce322d6:refs/heads/master\t3e62822..4915ba1"
val results = parse(listOf(STANDARD_PREFIX, TARGET_PREFIX, output, SUCCESS_SUFFIX))
assertSingleResult(SUCCESS, "4915ba17cc8b718d58ae77dd25018fccdce322d6", "3e62822..4915ba1", null, results)
}
@Test
fun rejected() {
val output = "!\trefs/heads/master:refs/heads/master\t[rejected] (non-fast-forward)"
val results = parse(listOf(STANDARD_PREFIX, TARGET_PREFIX, output, REJECT_SUFFIX))
assertSingleResult(REJECTED, "refs/heads/master", null, GitPushNativeResult.NO_FF_REJECT_REASON, results)
}
@Test
fun rejected2() {
val output = "!\trefs/heads/master:refs/heads/master\t[rejected] (fetch first)"
val results = parse(listOf(STANDARD_PREFIX, TARGET_PREFIX, output, REJECT_SUFFIX))
assertSingleResult(REJECTED, "refs/heads/master", null, GitPushNativeResult.FETCH_FIRST_REASON, results)
}
@Test
fun forcedUpdate() {
val output = "+\trefs/heads/master:refs/heads/master\tb9b3235...23760f8 (forced update)"
val result = parse(listOf(PUSH_DEFAULT_WARNING, TARGET_PREFIX, output))
assertSingleResult(FORCED_UPDATE, "refs/heads/master", "b9b3235...23760f8", "forced update", result)
}
@Test
fun remoteRejected() {
val output = "!\trefs/heads/master:refs/heads/master\t[remote rejected] (pre-receive hook declined)"
val result = parse(listOf(PUSH_DEFAULT_WARNING, TARGET_PREFIX, output))
assertSingleResult(REJECTED, "refs/heads/master", null, "pre-receive hook declined", result)
}
@Test
fun upToDate() {
val output = "=\trefs/heads/master:refs/heads/master\t[up to date]"
val result = parse(listOf(TARGET_PREFIX, output))
assertSingleResult(UP_TO_DATE, "refs/heads/master", result)
}
@Test
fun newRef() {
val output = "*\trefs/heads/feature:refs/heads/feature2\t[new branch]"
val result = parse(listOf(STANDARD_PREFIX, TARGET_PREFIX, output))
assertSingleResult(NEW_REF, "refs/heads/feature", result)
}
@Test
fun withTags() {
val output = arrayOf(" \trefs/heads/master:refs/heads/master\t7aabf91..d8369de", "*\trefs/tags/some_tag:refs/tags/some_tag\t[new tag]")
val results = parse(listOf(*output))
assertEquals(2, results.size)
assertResult(SUCCESS, "refs/heads/master", "7aabf91..d8369de", null, results[0])
assertResult(NEW_REF, "refs/tags/some_tag", null, null, results[1])
}
@Test
fun withTagsUptoCommit() {
val output = arrayOf(" \t4915ba17cc8b718d58ae77dd25018fccdce322d6:refs/heads/abranch\t3e62822..4915ba1",
"*\trefs/tags/some_tag:refs/tags/some_tag\t[new tag]")
val results = parse(listOf(*output))
assertEquals(2, results.size)
assertResult(SUCCESS, "4915ba17cc8b718d58ae77dd25018fccdce322d6", "3e62822..4915ba1", null, results[0])
assertResult(NEW_REF, "refs/tags/some_tag", null, null, results[1])
}
private fun assertResult(expectedType: GitPushNativeResult.Type,
expectedSource: String,
expectedRange: String?,
expectedReason: String? = null,
actualResult: GitPushNativeResult) {
assertEquals(expectedType, actualResult.type)
assertEquals(expectedSource, actualResult.sourceRef)
assertEquals(expectedRange, actualResult.range)
assertEquals(expectedReason, actualResult.reason)
}
private fun assertSingleResult(expectedType: GitPushNativeResult.Type,
expectedSource: String,
actualResults: List<GitPushNativeResult>) {
assertSingleResult(expectedType, expectedSource, null, null, actualResults)
}
private fun assertSingleResult(expectedType: GitPushNativeResult.Type,
expectedSource: String,
expectedRange: String?,
expectedReason: String?,
actualResults: List<GitPushNativeResult>) {
assertEquals(1, actualResults.size)
val result = actualResults[0]
assertResult(expectedType, expectedSource, expectedRange, expectedReason, result)
}
} | apache-2.0 | 7f482441bbfc84f2d3dec509d0c296a0 | 41.808383 | 139 | 0.695299 | 3.738494 | false | true | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ui/tabs/layout/TabsLayoutSettingsUi.kt | 1 | 4451 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.tabs.layout
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.tabs.impl.tabsLayout.TabsLayoutInfo
import javax.swing.ComboBoxModel
import javax.swing.DefaultComboBoxModel
import javax.swing.JComboBox
import javax.swing.ListCellRenderer
import javax.swing.SwingConstants.TOP
class TabsLayoutSettingsUi {
companion object {
internal fun tabsLayoutComboBox(tabPlacementComboBoxModel: DefaultComboBoxModel<Int>): ComboBox<TabsLayoutInfo> {
val model = DefaultComboBoxModel(TabsLayoutSettingsHolder.instance.installedInfos.toTypedArray())
val comboBox = comboBox(model,
SimpleListCellRenderer.create<TabsLayoutInfo> { label, value, _ ->
label.text = value.name
})
comboBox.addActionListener {
val selectedInfo = getSelectedInfo(comboBox)
if (selectedInfo == null) {
tabPlacementComboBoxModel.removeAllElements()
tabPlacementComboBoxModel.addElement(TOP)
return@addActionListener
}
val availableTabsPositions = selectedInfo.availableTabsPositions
if (availableTabsPositions == null || availableTabsPositions.isEmpty()) {
tabPlacementComboBoxModel.removeAllElements()
tabPlacementComboBoxModel.addElement(TOP)
return@addActionListener
}
var needToResetSelected = true
var selectedValue: Int? = null
if (tabPlacementComboBoxModel.selectedItem is Int) {
val prevSelectedValue = tabPlacementComboBoxModel.selectedItem as Int
if (prevSelectedValue in availableTabsPositions) {
selectedValue = prevSelectedValue
needToResetSelected = false
}
}
if (needToResetSelected) {
selectedValue = availableTabsPositions[0]
}
tabPlacementComboBoxModel.removeAllElements()
for (value in availableTabsPositions) {
tabPlacementComboBoxModel.addElement(value)
}
tabPlacementComboBoxModel.selectedItem = selectedValue
}
return comboBox
}
private fun <T> comboBox(model: ComboBoxModel<T>,
renderer: ListCellRenderer<T?>? = null): ComboBox<T> {
val component = ComboBox(model)
if (renderer != null) {
component.renderer = renderer
}
else {
component.renderer = SimpleListCellRenderer.create("") { it.toString() }
}
return component
}
fun prepare(builder: Cell<JComboBox<TabsLayoutInfo>>,
comboBox: JComboBox<TabsLayoutInfo>) {
builder.onApply {
getSelectedInfo(comboBox)?.let{
UISettings.instance.selectedTabsLayoutInfoId = it.id
}
}
builder.onReset {
val savedSelectedInfoId = calculateSavedSelectedInfoId()
val selectedInfo = getSelectedInfo(comboBox)
val isWrongSelected = selectedInfo == null || selectedInfo.id != UISettings.instance.selectedTabsLayoutInfoId
for (info in TabsLayoutSettingsHolder.instance.installedInfos) {
if (isWrongSelected && info.id == savedSelectedInfoId) {
comboBox.selectedItem = info
}
}
}
builder.onIsModified {
val savedSelectedInfoId = calculateSavedSelectedInfoId()
val selectedInfo = getSelectedInfo(comboBox)
if (selectedInfo != null && selectedInfo.id != savedSelectedInfoId) {
return@onIsModified true
}
return@onIsModified false
}
}
private fun calculateSavedSelectedInfoId(): String? {
var savedSelectedInfoId = UISettings.instance.selectedTabsLayoutInfoId
if (StringUtil.isEmpty(savedSelectedInfoId)) {
savedSelectedInfoId = TabsLayoutSettingsHolder.instance.defaultInfo.id
}
return savedSelectedInfoId
}
fun getSelectedInfo(comboBox: JComboBox<TabsLayoutInfo>) : TabsLayoutInfo? {
val selectedInfo = comboBox.selectedItem
selectedInfo?.let {
return selectedInfo as TabsLayoutInfo
}
return null
}
}
} | apache-2.0 | 477794021297a153eb505a338c1b5af3 | 35.793388 | 140 | 0.67805 | 5.104358 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/Constructors.kt | 3 | 3427 | // 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.j2k.ast
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.j2k.CodeBuilder
import org.jetbrains.kotlin.j2k.Converter
abstract class Constructor(
annotations: Annotations,
modifiers: Modifiers,
parameterList: ParameterList,
body: DeferredElement<Block>
) : FunctionLike(annotations, modifiers, parameterList, body) {
override val parameterList: ParameterList
get() = super.parameterList!!
}
class PrimaryConstructor(
annotations: Annotations,
modifiers: Modifiers,
parameterList: ParameterList,
body: DeferredElement<Block>
) : Constructor(annotations, modifiers, parameterList, body) {
override fun generateCode(builder: CodeBuilder) { throw IncorrectOperationException() }
// Should be lazy, to defer `assignPrototypesFrom(this,...)` a bit,
// cause when `PrimaryConstructor` created prototypes not yet assigned
val initializer: Initializer by
lazy { Initializer(body, Modifiers.Empty).assignPrototypesFrom(this, CommentsAndSpacesInheritance(commentsBefore = false)) }
fun createSignature(converter: Converter): PrimaryConstructorSignature? {
val signature = PrimaryConstructorSignature(annotations, modifiers, parameterList)
// assign prototypes later because we don't know yet whether the body is empty or not
converter.addPostUnfoldDeferredElementsAction {
val inheritance = CommentsAndSpacesInheritance(spacesBefore = SpacesInheritance.NONE, commentsAfter = body!!.isEmpty, commentsInside = body.isEmpty)
signature.assignPrototypesFrom(this, inheritance)
}
return signature
}
}
class PrimaryConstructorSignature(val annotations: Annotations, private val modifiers: Modifiers, val parameterList: ParameterList) : Element() {
val accessModifier: Modifier? = run {
val modifier = modifiers.accessModifier()
if (modifier != Modifier.PUBLIC) modifier else null
}
override fun generateCode(builder: CodeBuilder) {
var needConstructorKeyword = false
if (!annotations.isEmpty) {
builder append " " append annotations
needConstructorKeyword = true
}
if (accessModifier != null) {
builder append " " append Modifiers(listOf(accessModifier)).assignPrototypesFrom(modifiers)
needConstructorKeyword = true
}
if (needConstructorKeyword) {
builder.append(" constructor")
}
builder.append(parameterList)
}
}
class SecondaryConstructor(
annotations: Annotations,
modifiers: Modifiers,
parameterList: ParameterList,
body: DeferredElement<Block>,
private val thisOrSuperCall: DeferredElement<Expression>?
) : Constructor(annotations, modifiers, parameterList, body) {
override fun generateCode(builder: CodeBuilder) {
builder.append(annotations)
.appendWithSpaceAfter(modifiers)
.append("constructor")
.append(parameterList)
if (thisOrSuperCall != null) {
builder append " : " append thisOrSuperCall
}
builder append " " append body!!
}
}
| apache-2.0 | 0bd2bd78ca670a1a469a9b500f4cc5ce | 35.457447 | 160 | 0.695652 | 5.122571 | false | false | false | false |
google/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/WorkspaceModelImpl.kt | 1 | 7426 | // 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.ide.impl
import com.intellij.diagnostic.StartUpMeasurer.startActivity
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.debug
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageImpl
import com.intellij.workspaceModel.storage.impl.assertConsistency
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.system.measureTimeMillis
open class WorkspaceModelImpl(private val project: Project) : WorkspaceModel, Disposable {
@Volatile
var loadedFromCache = false
private set
final override val entityStorage: VersionedEntityStorageImpl
val entityTracer: EntityTracingLogger = EntityTracingLogger()
var userWarningLoggingLevel = false
@TestOnly set
private var projectModelUpdating = AtomicBoolean(false)
init {
log.debug { "Loading workspace model" }
val initialContent = WorkspaceModelInitialTestContent.pop()
val cache = WorkspaceModelCache.getInstance(project)
val projectEntities: MutableEntityStorage = when {
initialContent != null -> initialContent.toBuilder()
cache != null -> {
val activity = startActivity("cache loading")
val previousStorage: MutableEntityStorage?
val loadingCacheTime = measureTimeMillis {
previousStorage = cache.loadCache()?.toBuilder()
}
val storage = if (previousStorage == null) {
MutableEntityStorage.create()
}
else {
log.info("Load workspace model from cache in $loadingCacheTime ms")
loadedFromCache = true
entityTracer.printInfoAboutTracedEntity(previousStorage, "cache")
previousStorage
}
activity.end()
storage
}
else -> MutableEntityStorage.create()
}
@Suppress("LeakingThis")
prepareModel(project, projectEntities)
entityStorage = VersionedEntityStorageImpl(projectEntities.toSnapshot())
entityTracer.subscribe(project)
}
/**
* Used only in Rider IDE
*/
@ApiStatus.Internal
open fun prepareModel(project: Project, storage: MutableEntityStorage) = Unit
fun ignoreCache() {
loadedFromCache = false
}
final override fun <R> updateProjectModel(updater: (MutableEntityStorage) -> R): R {
ApplicationManager.getApplication().assertWriteAccessAllowed()
if (!projectModelUpdating.compareAndSet(false, true)) {
throw RuntimeException("Recursive call to `updateProjectModel` is not allowed")
}
val before = entityStorage.current
val builder = MutableEntityStorage.from(before)
val result = updater(builder)
startPreUpdateHandlers(before, builder)
val changes = builder.collectChanges(before)
val newStorage = builder.toSnapshot()
if (Registry.`is`("ide.workspace.model.assertions.on.update", false)) {
before.assertConsistency()
newStorage.assertConsistency()
}
entityStorage.replace(newStorage, changes, this::onBeforeChanged, this::onChanged, projectModelUpdating)
return result
}
final override fun <R> updateProjectModelSilent(updater: (MutableEntityStorage) -> R): R {
if (!projectModelUpdating.compareAndSet(false, true)) {
//throw RuntimeException("Recursive call to `updateProjectModel` is not allowed")
// Need to fix all cases and change to the runtime exception
log.warn("Recursive call to `updateProjectModel` is not allowed")
}
val before = entityStorage.current
val builder = MutableEntityStorage.from(entityStorage.current)
val result = updater(builder)
val newStorage = builder.toSnapshot()
if (Registry.`is`("ide.workspace.model.assertions.on.update", false)) {
before.assertConsistency()
newStorage.assertConsistency()
}
entityStorage.replaceSilently(newStorage)
projectModelUpdating.set(false)
return result
}
final override fun getBuilderSnapshot(): BuilderSnapshot {
val current = entityStorage.pointer
return BuilderSnapshot(current.version, current.storage)
}
final override fun replaceProjectModel(replacement: StorageReplacement): Boolean {
ApplicationManager.getApplication().assertWriteAccessAllowed()
if (entityStorage.version != replacement.version) return false
entityStorage.replace(replacement.snapshot, replacement.changes, this::onBeforeChanged, this::onChanged, null)
return true
}
final override fun dispose() = Unit
private fun onBeforeChanged(change: VersionedStorageChange) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
if (project.isDisposed) return
/**
* Order of events: initialize project libraries, initialize module bridge + module friends, all other listeners
*/
val workspaceModelTopics = WorkspaceModelTopics.getInstance(project)
logErrorOnEventHandling {
workspaceModelTopics.syncProjectLibs(project.messageBus).beforeChanged(change)
}
logErrorOnEventHandling {
workspaceModelTopics.syncModuleBridge(project.messageBus).beforeChanged(change)
}
logErrorOnEventHandling {
workspaceModelTopics.syncPublisher(project.messageBus).beforeChanged(change)
}
}
private fun onChanged(change: VersionedStorageChange) {
ApplicationManager.getApplication().assertWriteAccessAllowed()
if (project.isDisposed) return
val workspaceModelTopics = WorkspaceModelTopics.getInstance(project)
logErrorOnEventHandling {
workspaceModelTopics.syncProjectLibs(project.messageBus).changed(change)
}
logErrorOnEventHandling {
workspaceModelTopics.syncModuleBridge(project.messageBus).changed(change)
}
logErrorOnEventHandling {
workspaceModelTopics.syncPublisher(project.messageBus).changed(change)
}
}
private fun startPreUpdateHandlers(before: EntityStorage, builder: MutableEntityStorage) {
var startUpdateLoop = true
var updatesStarted = 0
while (startUpdateLoop && updatesStarted < PRE_UPDATE_LOOP_BLOCK) {
updatesStarted += 1
startUpdateLoop = false
PRE_UPDATE_HANDLERS.extensionsIfPointIsRegistered.forEach {
startUpdateLoop = startUpdateLoop or it.update(before, builder)
}
}
if (updatesStarted >= PRE_UPDATE_LOOP_BLOCK) {
log.error("Loop workspace model updating")
}
}
private fun logErrorOnEventHandling(action: () -> Unit) {
try {
action.invoke()
} catch (e: Throwable) {
val message = "Exception at Workspace Model event handling"
if (userWarningLoggingLevel) {
log.warn(message, e)
} else {
log.error(message, e)
}
}
}
companion object {
private val log = logger<WorkspaceModelImpl>()
private val PRE_UPDATE_HANDLERS = ExtensionPointName.create<WorkspaceModelPreUpdateHandler>("com.intellij.workspaceModel.preUpdateHandler")
private const val PRE_UPDATE_LOOP_BLOCK = 100
}
}
| apache-2.0 | bebe5f514871eca73d5ab4b487bc994b | 35.581281 | 143 | 0.741045 | 4.963904 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/PackageManagementPanel.kt | 1 | 9027 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.ui.JBSplitter
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.UIUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction
import com.jetbrains.packagesearch.intellij.plugin.actions.TogglePackageDetailsAction
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.RootDataModelProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SearchClient
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SelectedPackageSetter
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModuleSetter
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.modules.ModulesTree
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails.PackageDetailsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesListPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.computeModuleTreeModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.computePackagesTableItems
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.awt.Dimension
import javax.swing.BorderFactory
import javax.swing.JScrollPane
@Suppress("MagicNumber") // Swing dimension constants
internal class PackageManagementPanel(
rootDataModelProvider: RootDataModelProvider,
selectedPackageSetter: SelectedPackageSetter,
targetModuleSetter: TargetModuleSetter,
searchClient: SearchClient,
operationExecutor: OperationExecutor
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")), CoroutineScope, Disposable {
override val coroutineContext = SupervisorJob() + CoroutineName("PackageManagementPanel")
private val operationFactory = PackageSearchOperationFactory()
private val modulesTree = ModulesTree(targetModuleSetter)
private val modulesScrollPanel = JBScrollPane(
modulesTree,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
)
private val project = rootDataModelProvider.project
private val packagesListPanel = PackagesListPanel(
project = project,
searchClient = searchClient,
operationExecutor = operationExecutor,
operationFactory = operationFactory
) {
launch { selectedPackageSetter.setSelectedPackage(it) }
}
private val packageDetailsPanel = PackageDetailsPanel(operationFactory, operationExecutor)
private val packagesSplitter = JBSplitter(
"PackageSearch.PackageManagementPanel.DetailsSplitter",
PackageSearchGeneralConfiguration.DefaultPackageDetailsSplitterProportion
).apply {
firstComponent = packagesListPanel.content
secondComponent = packageDetailsPanel.content
orientation = false // Horizontal split
dividerWidth = 2.scaled()
}
private val mainSplitter = JBSplitter("PackageSearch.PackageManagementPanel.Splitter", 0.1f).apply {
firstComponent = modulesScrollPanel
secondComponent = packagesSplitter
orientation = false // Horizontal split
dividerWidth = 2.scaled()
}
init {
updatePackageDetailsVisible(PackageSearchGeneralConfiguration.getInstance(project).packageDetailsVisible)
modulesScrollPanel.apply {
border = BorderFactory.createEmptyBorder()
minimumSize = Dimension(250.scaled(), 0)
UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true)
}
packagesListPanel.content.minimumSize = Dimension(250.scaled(), 0)
packagesListPanel.selectedPackage.onEach { selectedPackage ->
selectedPackageSetter.setSelectedPackage(selectedPackage)
}.launchIn(this)
rootDataModelProvider.dataStatusState.onEach { status ->
packagesListPanel.setIsBusy(status.isBusy)
}.launchIn(this)
rootDataModelProvider.dataStatusState.map { it.isExecutingOperations }
.onEach { isExecutingOperations ->
content.isEnabled = !isExecutingOperations
content.updateAndRepaint()
}.launchIn(this)
rootDataModelProvider.dataModelFlow.filter { it.moduleModels.isNotEmpty() }
.onEach { data ->
val (treeModel, selectionPath) = computeModuleTreeModel(
modules = data.moduleModels,
currentTargetModules = data.targetModules,
traceInfo = data.traceInfo
)
modulesTree.display(
ModulesTree.ViewModel(
treeModel = treeModel,
traceInfo = data.traceInfo,
pendingSelectionPath = selectionPath
)
)
}
.launchIn(this)
rootDataModelProvider.dataModelFlow.onEach { data ->
val tableData = computePackagesTableItems(
project,
data.packageModels,
data.filterOptions.onlyStable,
data.targetModules,
data.traceInfo
)
packagesListPanel.display(
PackagesListPanel.ViewModel(
headerData = data.headerData,
packageModels = data.packageModels,
targetModules = data.targetModules,
knownRepositoriesInTargetModules = data.knownRepositoriesInTargetModules,
allKnownRepositories = data.allKnownRepositories,
filterOptions = data.filterOptions,
tableData = tableData,
traceInfo = data.traceInfo,
searchQuery = data.searchQuery
)
)
packageDetailsPanel.display(
PackageDetailsPanel.ViewModel(
selectedPackageModel = data.selectedPackage,
knownRepositoriesInTargetModules = data.knownRepositoriesInTargetModules,
allKnownRepositories = data.allKnownRepositories,
targetModules = data.targetModules,
onlyStable = data.filterOptions.onlyStable,
invokeLaterScope = project.lifecycleScope
)
)
}.launchIn(this)
}
private fun updatePackageDetailsVisible(becomeVisible: Boolean) {
val wasVisible = packagesSplitter.secondComponent.isVisible
packagesSplitter.secondComponent.isVisible = becomeVisible
if (!wasVisible && becomeVisible) {
packagesSplitter.proportion =
PackageSearchGeneralConfiguration.getInstance(project).packageDetailsSplitterProportion
}
if (!becomeVisible) {
PackageSearchGeneralConfiguration.getInstance(project).packageDetailsSplitterProportion =
packagesSplitter.proportion
packagesSplitter.proportion = 1.0f
}
}
private val togglePackageDetailsAction = TogglePackageDetailsAction(project, ::updatePackageDetailsVisible)
override fun build() = mainSplitter
override fun buildGearActions() = DefaultActionGroup(
ShowSettingsAction(project),
togglePackageDetailsAction
)
override fun buildTitleActions(): Array<AnAction> = arrayOf(togglePackageDetailsAction)
override fun dispose() {
logDebug("PackageManagementPanel#dispose()") { "Disposing PackageManagementPanel..." }
cancel("Disposing PackageManagementPanel")
}
}
| apache-2.0 | 4e5ef84d8c1c9efb06727ffee3478ae0 | 43.25 | 135 | 0.722167 | 5.716909 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/ui/recent_updates/RecentChaptersHolder.kt | 2 | 4598 | package eu.kanade.tachiyomi.ui.recent_updates
import android.view.View
import android.widget.PopupMenu
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.ui.base.adapter.FlexibleViewHolder
import eu.kanade.tachiyomi.util.getResourceColor
import kotlinx.android.synthetic.main.item_recent_chapters.view.*
/**
* Holder that contains chapter item
* Uses R.layout.item_recent_chapters.
* UI related actions should be called from here.
*
* @param view the inflated view for this holder.
* @param adapter the adapter handling this holder.
* @param listener a listener to react to single tap and long tap events.
* @constructor creates a new recent chapter holder.
*/
class RecentChaptersHolder(
private val view: View,
private val adapter: RecentChaptersAdapter,
listener: OnListItemClickListener)
: FlexibleViewHolder(view, adapter, listener) {
/**
* Color of read chapter
*/
private var readColor = view.context.theme.getResourceColor(android.R.attr.textColorHint)
/**
* Color of unread chapter
*/
private var unreadColor = view.context.theme.getResourceColor(android.R.attr.textColorPrimary)
/**
* Object containing chapter information
*/
private var chapter: RecentChapter? = null
init {
// We need to post a Runnable to show the popup to make sure that the PopupMenu is
// correctly positioned. The reason being that the view may change position before the
// PopupMenu is shown.
view.chapter_menu.setOnClickListener { it.post({ showPopupMenu(it) }) }
}
/**
* Set values of view
*
* @param chapter item containing chapter information
*/
fun onSetValues(chapter: RecentChapter) {
this.chapter = chapter
// Set chapter title
view.chapter_title.text = chapter.name
// Set manga title
view.manga_title.text = chapter.manga.title
// Check if chapter is read and set correct color
if (chapter.read) {
view.chapter_title.setTextColor(readColor)
view.manga_title.setTextColor(readColor)
} else {
view.chapter_title.setTextColor(unreadColor)
view.manga_title.setTextColor(unreadColor)
}
// Set chapter status
notifyStatus(chapter.status)
}
/**
* Updates chapter status in view.
*
* @param status download status
*/
fun notifyStatus(status: Int) = with(view.download_text) {
when (status) {
Download.QUEUE -> setText(R.string.chapter_queued)
Download.DOWNLOADING -> setText(R.string.chapter_downloading)
Download.DOWNLOADED -> setText(R.string.chapter_downloaded)
Download.ERROR -> setText(R.string.chapter_error)
else -> text = ""
}
}
/**
* Show pop up menu
*
* @param view view containing popup menu.
*/
private fun showPopupMenu(view: View) = chapter?.let { chapter ->
// Create a PopupMenu, giving it the clicked view for an anchor
val popup = PopupMenu(view.context, view)
// Inflate our menu resource into the PopupMenu's Menu
popup.menuInflater.inflate(R.menu.chapter_recent, popup.menu)
// Hide download and show delete if the chapter is downloaded and
if (chapter.isDownloaded) {
popup.menu.findItem(R.id.action_download).isVisible = false
popup.menu.findItem(R.id.action_delete).isVisible = true
}
// Hide mark as unread when the chapter is unread
if (!chapter.read /*&& mangaChapter.chapter.last_page_read == 0*/) {
popup.menu.findItem(R.id.action_mark_as_unread).isVisible = false
}
// Hide mark as read when the chapter is read
if (chapter.read) {
popup.menu.findItem(R.id.action_mark_as_read).isVisible = false
}
// Set a listener so we are notified if a menu item is clicked
popup.setOnMenuItemClickListener { menuItem ->
with(adapter.fragment) {
when (menuItem.itemId) {
R.id.action_download -> downloadChapter(chapter)
R.id.action_delete -> deleteChapter(chapter)
R.id.action_mark_as_read -> markAsRead(listOf(chapter))
R.id.action_mark_as_unread -> markAsUnread(listOf(chapter))
}
}
true
}
// Finally show the PopupMenu
popup.show()
}
} | gpl-3.0 | 8f06c48aa4b21400ccf3927ab70b7d28 | 33.066667 | 98 | 0.637016 | 4.464078 | false | false | false | false |
siosio/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.kt | 1 | 23694 | // 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.ide.ui
import com.intellij.diagnostic.LoadingState
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.NonInjectable
import com.intellij.ui.JreHiDpiUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ComponentTreeEventDispatcher
import com.intellij.util.SystemProperties
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.annotations.Transient
import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval
import org.jetbrains.annotations.NonNls
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.RenderingHints
import javax.swing.JComponent
import javax.swing.SwingConstants
import kotlin.math.roundToInt
private val LOG = logger<UISettings>()
@State(name = "UISettings", storages = [(Storage("ui.lnf.xml"))], useLoadedStateAsExisting = false)
class UISettings @NonInjectable constructor(private val notRoamableOptions: NotRoamableUiSettings) : PersistentStateComponentWithModificationTracker<UISettingsState> {
constructor() : this(ApplicationManager.getApplication().getService(NotRoamableUiSettings::class.java))
private var state = UISettingsState()
private val myTreeDispatcher = ComponentTreeEventDispatcher.create(UISettingsListener::class.java)
var ideAAType: AntialiasingType
get() = notRoamableOptions.state.ideAAType
set(value) {
notRoamableOptions.state.ideAAType = value
}
var editorAAType: AntialiasingType
get() = notRoamableOptions.state.editorAAType
set(value) {
notRoamableOptions.state.editorAAType = value
}
val allowMergeButtons: Boolean
get() = Registry.`is`("ide.allow.merge.buttons", true)
val animateWindows: Boolean
get() = Registry.`is`("ide.animate.toolwindows", false)
var colorBlindness: ColorBlindness?
get() = state.colorBlindness
set(value) {
state.colorBlindness = value
}
var useContrastScrollbars: Boolean
get() = state.useContrastScrollBars
set(value) {
state.useContrastScrollBars = value
}
var hideToolStripes: Boolean
get() = state.hideToolStripes
set(value) {
state.hideToolStripes = value
}
val hideNavigationOnFocusLoss: Boolean
get() = Registry.`is`("ide.hide.navigation.on.focus.loss", false)
var reuseNotModifiedTabs: Boolean
get() = state.reuseNotModifiedTabs
set(value) {
state.reuseNotModifiedTabs = value
}
var openTabsInMainWindow: Boolean
get() = state.openTabsInMainWindow
set(value) {
state.openTabsInMainWindow = value
}
var openInPreviewTabIfPossible: Boolean
get() = state.openInPreviewTabIfPossible
set(value) {
state.openInPreviewTabIfPossible = value
}
var disableMnemonics: Boolean
get() = state.disableMnemonics
set(value) {
state.disableMnemonics = value
}
var disableMnemonicsInControls: Boolean
get() = state.disableMnemonicsInControls
set(value) {
state.disableMnemonicsInControls = value
}
var dndWithPressedAltOnly: Boolean
get() = state.dndWithPressedAltOnly
set(value) {
state.dndWithPressedAltOnly = value
}
var useSmallLabelsOnTabs: Boolean
get() = state.useSmallLabelsOnTabs
set(value) {
state.useSmallLabelsOnTabs = value
}
var smoothScrolling: Boolean
get() = state.smoothScrolling
set(value) {
state.smoothScrolling = value
}
val animatedScrolling: Boolean
get() = state.animatedScrolling
val animatedScrollingDuration: Int
get() = state.animatedScrollingDuration
val animatedScrollingCurvePoints: Int
get() = state.animatedScrollingCurvePoints
val closeTabButtonOnTheRight: Boolean
get() = state.closeTabButtonOnTheRight
val cycleScrolling: Boolean
get() = AdvancedSettings.getBoolean("ide.cycle.scrolling")
var selectedTabsLayoutInfoId: @NonNls String?
get() = state.selectedTabsLayoutInfoId
set(value) {
state.selectedTabsLayoutInfoId = value
}
val scrollTabLayoutInEditor: Boolean
get() = state.scrollTabLayoutInEditor
var showToolWindowsNumbers: Boolean
get() = state.showToolWindowsNumbers
set(value) {
state.showToolWindowsNumbers = value
}
var showEditorToolTip: Boolean
get() = state.showEditorToolTip
set(value) {
state.showEditorToolTip = value
}
var showNavigationBar: Boolean
get() = state.showNavigationBar
set(b) {
ToolbarSettings.getInstance().setNavBarVisible(b)
fireUISettingsChanged()
}
val showToolbarInNavigationBar: Boolean
get() = ToolbarSettings.getInstance().getShowToolbarInNavigationBar()
var showMembersInNavigationBar: Boolean
get() = state.showMembersInNavigationBar
set(value) {
state.showMembersInNavigationBar = value
}
var showStatusBar: Boolean
get() = state.showStatusBar
set(value) {
state.showStatusBar = value
}
var showMainMenu: Boolean
get() = state.showMainMenu
set(value) {
state.showMainMenu = value
}
val showIconInQuickNavigation: Boolean
get() = Registry.`is`("ide.show.icons.in.quick.navigation", false)
var showTreeIndentGuides: Boolean
get() = state.showTreeIndentGuides
set(value) {
state.showTreeIndentGuides = value
}
var compactTreeIndents: Boolean
get() = state.compactTreeIndents
set(value) {
state.compactTreeIndents = value
}
var showMainToolbar: Boolean
get() = state.showMainToolbar
set(value) {
ToolbarSettings.getInstance().setToolbarVisible(value)
fireUISettingsChanged()
}
var showIconsInMenus: Boolean
get() = state.showIconsInMenus
set(value) {
state.showIconsInMenus = value
}
var sortLookupElementsLexicographically: Boolean
get() = state.sortLookupElementsLexicographically
set(value) {
state.sortLookupElementsLexicographically = value
}
val hideTabsIfNeeded: Boolean
get() = state.hideTabsIfNeeded || editorTabPlacement == SwingConstants.LEFT || editorTabPlacement == SwingConstants.RIGHT
var showFileIconInTabs: Boolean
get() = state.showFileIconInTabs
set(value) {
state.showFileIconInTabs = value
}
var hideKnownExtensionInTabs: Boolean
get() = state.hideKnownExtensionInTabs
set(value) {
state.hideKnownExtensionInTabs = value
}
var leftHorizontalSplit: Boolean
get() = state.leftHorizontalSplit
set(value) {
state.leftHorizontalSplit = value
}
var rightHorizontalSplit: Boolean
get() = state.rightHorizontalSplit
set(value) {
state.rightHorizontalSplit = value
}
var wideScreenSupport: Boolean
get() = state.wideScreenSupport
set(value) {
state.wideScreenSupport = value
}
var sortBookmarks: Boolean
get() = state.sortBookmarks
set(value) {
state.sortBookmarks = value
}
val showCloseButton: Boolean
get() = state.showCloseButton
var presentationMode: Boolean
get() = state.presentationMode
set(value) {
state.presentationMode = value
}
var presentationModeFontSize: Int
get() = state.presentationModeFontSize
set(value) {
state.presentationModeFontSize = value
}
var editorTabPlacement: Int
get() = state.editorTabPlacement
set(value) {
state.editorTabPlacement = value
}
var editorTabLimit: Int
get() = state.editorTabLimit
set(value) {
state.editorTabLimit = value
}
var recentFilesLimit: Int
get() = state.recentFilesLimit
set(value) {
state.recentFilesLimit = value
}
var recentLocationsLimit: Int
get() = state.recentLocationsLimit
set(value) {
state.recentLocationsLimit = value
}
var maxLookupWidth: Int
get() = state.maxLookupWidth
set(value) {
state.maxLookupWidth = value
}
var maxLookupListHeight: Int
get() = state.maxLookupListHeight
set(value) {
state.maxLookupListHeight = value
}
var overrideLafFonts: Boolean
get() = state.overrideLafFonts
set(value) {
state.overrideLafFonts = value
}
var fontFace: @NlsSafe String?
get() = notRoamableOptions.state.fontFace
set(value) {
notRoamableOptions.state.fontFace = value
}
var fontSize: Int
get() = notRoamableOptions.state.fontSize
set(value) {
notRoamableOptions.state.fontSize = value
}
var fontScale: Float
get() = notRoamableOptions.state.fontScale
set(value) {
notRoamableOptions.state.fontScale = value
}
var showDirectoryForNonUniqueFilenames: Boolean
get() = state.showDirectoryForNonUniqueFilenames
set(value) {
state.showDirectoryForNonUniqueFilenames = value
}
var pinFindInPath: Boolean
get() = state.pinFindInPath
set(value) {
state.pinFindInPath = value
}
var activeRightEditorOnClose: Boolean
get() = state.activeRightEditorOnClose
set(value) {
state.activeRightEditorOnClose = value
}
var showTabsTooltips: Boolean
get() = state.showTabsTooltips
set(value) {
state.showTabsTooltips = value
}
var markModifiedTabsWithAsterisk: Boolean
get() = state.markModifiedTabsWithAsterisk
set(value) {
state.markModifiedTabsWithAsterisk = value
}
@Suppress("unused")
var overrideConsoleCycleBufferSize: Boolean
get() = state.overrideConsoleCycleBufferSize
set(value) {
state.overrideConsoleCycleBufferSize = value
}
var consoleCycleBufferSizeKb: Int
get() = state.consoleCycleBufferSizeKb
set(value) {
state.consoleCycleBufferSizeKb = value
}
var consoleCommandHistoryLimit: Int
get() = state.consoleCommandHistoryLimit
set(value) {
state.consoleCommandHistoryLimit = value
}
var sortTabsAlphabetically: Boolean
get() = state.sortTabsAlphabetically
set(value) {
state.sortTabsAlphabetically = value
}
var openTabsAtTheEnd: Boolean
get() = state.openTabsAtTheEnd
set(value) {
state.openTabsAtTheEnd = value
}
var showInplaceComments: Boolean
get() = state.showInplaceComments
set(value) {
state.showInplaceComments = value
}
val showInplaceCommentsInternal: Boolean
get() = showInplaceComments && ApplicationManager.getApplication()?.isInternal ?: false
var fullPathsInWindowHeader: Boolean
get() = state.fullPathsInWindowHeader
set(value) {
state.fullPathsInWindowHeader = value
}
var mergeMainMenuWithWindowTitle: Boolean
get() = state.mergeMainMenuWithWindowTitle
set(value) {
state.mergeMainMenuWithWindowTitle = value
}
companion object {
init {
if (JBUIScale.SCALE_VERBOSE) {
LOG.info(String.format("defFontSize=%d, defFontScale=%.2f", defFontSize, defFontScale))
}
}
const val ANIMATION_DURATION = 300 // Milliseconds
/** Not tabbed pane. */
const val TABS_NONE = 0
@Suppress("ObjectPropertyName")
@Volatile
private var cachedInstance: UISettings? = null
@JvmStatic
val instance: UISettings
get() {
var result = cachedInstance
if (result == null) {
LoadingState.CONFIGURATION_STORE_INITIALIZED.checkOccurred()
result = ApplicationManager.getApplication().getService(UISettings::class.java)!!
cachedInstance = result
}
return result
}
@JvmStatic
val instanceOrNull: UISettings?
get() {
val result = cachedInstance
if (result == null && LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred) {
return instance
}
return result
}
/**
* Use this method if you are not sure whether the application is initialized.
* @return persisted UISettings instance or default values.
*/
@JvmStatic
val shadowInstance: UISettings
get() = instanceOrNull ?: UISettings(NotRoamableUiSettings())
private fun calcFractionalMetricsHint(registryKey: String, defaultValue: Boolean): Any {
val hint: Boolean
if (LoadingState.APP_STARTED.isOccurred) {
val registryValue = Registry.get(registryKey)
if (registryValue.isMultiValue) {
val option = registryValue.selectedOption
if (option.equals("Enabled")) hint = true
else if (option.equals("Disabled")) hint = false
else hint = defaultValue
}
else {
hint = if (registryValue.isBoolean && registryValue.asBoolean()) true else defaultValue
}
}
else hint = defaultValue
return if (hint) RenderingHints.VALUE_FRACTIONALMETRICS_ON else RenderingHints.VALUE_FRACTIONALMETRICS_OFF
}
fun getPreferredFractionalMetricsValue(): Any {
val enableByDefault = SystemInfo.isMacOSCatalina || (FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(false) ==
RenderingHints.VALUE_TEXT_ANTIALIAS_ON)
return calcFractionalMetricsHint("ide.text.fractional.metrics", enableByDefault)
}
@JvmStatic
val editorFractionalMetricsHint: Any
get() {
val enableByDefault = FontSubpixelResolution.ENABLED
&& AntialiasingType.getKeyForCurrentScope(true) == RenderingHints.VALUE_TEXT_ANTIALIAS_ON
return calcFractionalMetricsHint("editor.text.fractional.metrics", enableByDefault)
}
@JvmStatic
fun setupFractionalMetrics(g2d: Graphics2D) {
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, getPreferredFractionalMetricsValue())
}
/**
* This method must not be used for set up antialiasing for editor components. To make sure antialiasing settings are taken into account
* when preferred size of component is calculated, [.setupComponentAntialiasing] method should be called from
* `updateUI()` or `setUI()` method of component.
*/
@JvmStatic
fun setupAntialiasing(g: Graphics) {
g as Graphics2D
g.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, UIUtil.getLcdContrastValue())
if (LoadingState.CONFIGURATION_STORE_INITIALIZED.isOccurred && ApplicationManager.getApplication() == null) {
// cannot use services while Application has not been loaded yet, so let's apply the default hints
GraphicsUtil.applyRenderingHints(g)
return
}
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
setupFractionalMetrics(g)
}
@JvmStatic
fun setupComponentAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, AntialiasingType.getAAHintForSwingComponent())
}
@JvmStatic
fun setupEditorAntialiasing(component: JComponent) {
GraphicsUtil.setAntialiasingType(component, instance.editorAAType.textInfo)
}
/**
* Returns the default font scale, which depends on the HiDPI mode (see [com.intellij.ui.scale.ScaleType]).
* <p>
* The font is represented:
* - in relative (dpi-independent) points in the JRE-managed HiDPI mode, so the method returns 1.0f
* - in absolute (dpi-dependent) points in the IDE-managed HiDPI mode, so the method returns the default screen scale
*
* @return the system font scale
*/
@JvmStatic
val defFontScale: Float
get() = when {
JreHiDpiUtil.isJreHiDPIEnabled() -> 1f
else -> JBUIScale.sysScale()
}
/**
* Returns the default font size scaled by #defFontScale
*
* @return the default scaled font size
*/
@JvmStatic
val defFontSize: Int
get() = UISettingsState.defFontSize
@JvmStatic
fun restoreFontSize(readSize: Int, readScale: Float?): Int {
var size = readSize
if (readScale == null || readScale <= 0) {
if (JBUIScale.SCALE_VERBOSE) LOG.info("Reset font to default")
// Reset font to default on switch from IDE-managed HiDPI to JRE-managed HiDPI. Doesn't affect OSX.
if (!SystemInfoRt.isMac && JreHiDpiUtil.isJreHiDPIEnabled()) {
size = UISettingsState.defFontSize
}
}
else if (readScale != defFontScale) {
size = ((readSize / readScale) * defFontScale).roundToInt()
}
if (JBUIScale.SCALE_VERBOSE) LOG.info("Loaded: fontSize=$readSize, fontScale=$readScale; restored: fontSize=$size, fontScale=$defFontScale")
return size
}
const val MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY = "ide.win.frame.decoration"
@JvmStatic
val mergeMainMenuWithWindowTitleOverrideValue = System.getProperty(MERGE_MAIN_MENU_WITH_WINDOW_TITLE_PROPERTY)?.toBoolean()
val isMergeMainMenuWithWindowTitleOverridden = mergeMainMenuWithWindowTitleOverrideValue != null
}
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Please use {@link UISettingsListener#TOPIC}")
@ScheduledForRemoval(inVersion = "2021.3")
fun addUISettingsListener(listener: UISettingsListener, parentDisposable: Disposable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable).subscribe(UISettingsListener.TOPIC, listener)
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
fun fireUISettingsChanged() {
updateDeprecatedProperties()
// todo remove when all old properties will be converted
state._incrementModificationCount()
IconLoader.setFilter(ColorBlindnessSupport.get(state.colorBlindness)?.filter)
// if this is the main UISettings instance (and not on first call to getInstance) push event to bus and to all current components
if (this === cachedInstance) {
myTreeDispatcher.multicaster.uiSettingsChanged(this)
ApplicationManager.getApplication().messageBus.syncPublisher(UISettingsListener.TOPIC).uiSettingsChanged(this)
}
}
@Suppress("DEPRECATION")
private fun updateDeprecatedProperties() {
HIDE_TOOL_STRIPES = hideToolStripes
SHOW_MAIN_TOOLBAR = showMainToolbar
SHOW_CLOSE_BUTTON = showCloseButton
PRESENTATION_MODE = presentationMode
OVERRIDE_NONIDEA_LAF_FONTS = overrideLafFonts
PRESENTATION_MODE_FONT_SIZE = presentationModeFontSize
CONSOLE_COMMAND_HISTORY_LIMIT = state.consoleCommandHistoryLimit
FONT_SIZE = fontSize
FONT_FACE = fontFace
EDITOR_TAB_LIMIT = editorTabLimit
}
override fun getState() = state
override fun loadState(state: UISettingsState) {
this.state = state
updateDeprecatedProperties()
migrateOldSettings()
if (migrateOldFontSettings()) {
notRoamableOptions.fixFontSettings()
}
// Check tab placement in editor
val editorTabPlacement = state.editorTabPlacement
if (editorTabPlacement != TABS_NONE &&
editorTabPlacement != SwingConstants.TOP &&
editorTabPlacement != SwingConstants.LEFT &&
editorTabPlacement != SwingConstants.BOTTOM &&
editorTabPlacement != SwingConstants.RIGHT) {
state.editorTabPlacement = SwingConstants.TOP
}
// Check that alpha delay and ratio are valid
if (state.alphaModeDelay < 0) {
state.alphaModeDelay = 1500
}
if (state.alphaModeRatio < 0.0f || state.alphaModeRatio > 1.0f) {
state.alphaModeRatio = 0.5f
}
fireUISettingsChanged()
}
override fun getStateModificationCount(): Long {
return state.modificationCount
}
@Suppress("DEPRECATION")
private fun migrateOldSettings() {
if (state.ideAAType != AntialiasingType.SUBPIXEL) {
ideAAType = state.ideAAType
state.ideAAType = AntialiasingType.SUBPIXEL
}
if (state.editorAAType != AntialiasingType.SUBPIXEL) {
editorAAType = state.editorAAType
state.editorAAType = AntialiasingType.SUBPIXEL
}
if (state.ideAAType == AntialiasingType.SUBPIXEL && !AntialiasingType.canUseSubpixelAAForIDE()) {
state.ideAAType = AntialiasingType.GREYSCALE
}
if (state.editorAAType == AntialiasingType.SUBPIXEL && !AntialiasingType.canUseSubpixelAAForEditor()) {
state.editorAAType = AntialiasingType.GREYSCALE
}
if (!state.allowMergeButtons) {
Registry.get("ide.allow.merge.buttons").setValue(false)
state.allowMergeButtons = true
}
}
@Suppress("DEPRECATION")
private fun migrateOldFontSettings(): Boolean {
var migrated = false
if (state.fontSize != 0) {
fontSize = restoreFontSize(state.fontSize, state.fontScale)
state.fontSize = 0
migrated = true
}
if (state.fontScale != 0f) {
fontScale = state.fontScale
state.fontScale = 0f
migrated = true
}
if (state.fontFace != null) {
fontFace = state.fontFace
state.fontFace = null
migrated = true
}
return migrated
}
//<editor-fold desc="Deprecated stuff.">
@Suppress("unused", "PropertyName")
@Deprecated("Use fontFace", replaceWith = ReplaceWith("fontFace"))
@JvmField
@Transient
var FONT_FACE: String? = null
@Suppress("unused", "PropertyName")
@Deprecated("Use fontSize", replaceWith = ReplaceWith("fontSize"))
@JvmField
@Transient
var FONT_SIZE: Int? = 0
@Suppress("unused", "PropertyName")
@Deprecated("Use hideToolStripes", replaceWith = ReplaceWith("hideToolStripes"))
@JvmField
@Transient
var HIDE_TOOL_STRIPES = true
@Suppress("unused", "PropertyName")
@Deprecated("Use consoleCommandHistoryLimit", replaceWith = ReplaceWith("consoleCommandHistoryLimit"))
@JvmField
@Transient
var CONSOLE_COMMAND_HISTORY_LIMIT = 300
@Suppress("unused", "PropertyName")
@Deprecated("Use cycleScrolling", replaceWith = ReplaceWith("cycleScrolling"), level = DeprecationLevel.ERROR)
@JvmField
@Transient
var CYCLE_SCROLLING = true
@Suppress("unused", "PropertyName")
@Deprecated("Use showMainToolbar", replaceWith = ReplaceWith("showMainToolbar"))
@JvmField
@Transient
var SHOW_MAIN_TOOLBAR = false
@Suppress("unused", "PropertyName")
@Deprecated("Use showCloseButton", replaceWith = ReplaceWith("showCloseButton"))
@JvmField
@Transient
var SHOW_CLOSE_BUTTON = true
@Suppress("unused", "PropertyName")
@Deprecated("Use presentationMode", replaceWith = ReplaceWith("presentationMode"))
@JvmField
@Transient
var PRESENTATION_MODE = false
@Suppress("unused", "PropertyName", "SpellCheckingInspection")
@Deprecated("Use overrideLafFonts", replaceWith = ReplaceWith("overrideLafFonts"))
@JvmField
@Transient
var OVERRIDE_NONIDEA_LAF_FONTS = false
@Suppress("unused", "PropertyName")
@Deprecated("Use presentationModeFontSize", replaceWith = ReplaceWith("presentationModeFontSize"))
@JvmField
@Transient
var PRESENTATION_MODE_FONT_SIZE = 24
@Suppress("unused", "PropertyName")
@Deprecated("Use editorTabLimit", replaceWith = ReplaceWith("editorTabLimit"))
@JvmField
@Transient
var EDITOR_TAB_LIMIT = editorTabLimit
//</editor-fold>
}
| apache-2.0 | 0d0970e89ed0e4297e1db3062dad1255 | 29.652005 | 167 | 0.708196 | 4.937279 | false | false | false | false |
vovagrechka/fucking-everything | attic/shared-x/src/shared-x.kt | 1 | 1307 | package vgrechka
import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty0
import kotlin.reflect.KProperty
// TODO:vgrechka @unduplicate shared-jvm
fun main(args: Array<String>) {
}
var exhaustive: Any? = null
fun wtf(msg: String = "...WTF didn't you describe this WTF?"): Nothing = throw Exception("WTF: $msg")
fun die(msg: String = "You've just killed me, motherfucker!"): Nothing = throw Exception("Aarrgghh... $msg")
fun imf(what: String = "me"): Nothing = throw Exception("Implement $what, please, fuck you")
fun bitch(msg: String = "Just bitching..."): Nothing = throw Exception(msg)
fun StringBuilder.ln(x: Any?) {
append(x)
append("\n")
}
class notNullOnce<T: Any> : ReadWriteProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("Property `${property.name}` should be initialized before get.")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
check(this.value == null) {"Property `${property.name}` should be assigned only once"}
this.value = value
}
}
inline operator fun <T, FRet> T.minus(f: (T) -> FRet): T { f(this); return this }
| apache-2.0 | 9d58e8e6971f8b3945e7cefd015f36c0 | 26.229167 | 116 | 0.682479 | 3.734286 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/InsertCurlyBracesToTemplateIntention.kt | 5 | 1479 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.RestoreCaret
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtSimpleNameStringTemplateEntry
import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
class InsertCurlyBracesToTemplateIntention : SelfTargetingOffsetIndependentIntention<KtSimpleNameStringTemplateEntry>(
KtSimpleNameStringTemplateEntry::class.java, KotlinBundle.lazyMessage("insert.curly.braces.around.variable")
), LowPriorityAction {
override fun isApplicableTo(element: KtSimpleNameStringTemplateEntry): Boolean = true
override fun applyTo(element: KtSimpleNameStringTemplateEntry, editor: Editor?) {
val expression = element.expression ?: return
with(RestoreCaret(expression, editor)) {
val wrapped = element.replace(KtPsiFactory(element).createBlockStringTemplateEntry(expression))
val afterExpression = (wrapped as? KtStringTemplateEntryWithExpression)?.expression ?: return
restoreCaret(afterExpression, defaultOffset = { it.endOffset })
}
}
}
| apache-2.0 | 3bfdeddb1bccea18cc6a6be7611a9e94 | 48.3 | 158 | 0.799189 | 5.226148 | false | false | false | false |
alexames/flatbuffers | kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt | 6 | 14406 | /*
* Copyright 2021 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.flatbuffers.kotlin
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class JSONTest {
@Test
fun parse2Test() {
val dataStr = """
{ "myKey" : [1, "yay"] }
""".trimIndent()
val data = dataStr.encodeToByteArray()
val buffer = ArrayReadWriteBuffer(data, writePosition = data.size)
val parser = JSONParser()
val root = parser.parse(buffer)
println(root.toJson())
}
@Test
fun parseSample() {
val dataStr = """
{
"ary" : [1, 2, 3],
"boolean_false": false,
"boolean_true": true, "double": 1.2E33,
"hello":"world"
,"interesting": "value",
"null_value": null,
"object" : {
"field1": "hello"
}
}
"""
val data = dataStr.encodeToByteArray()
val root = JSONParser().parse(ArrayReadWriteBuffer(data, writePosition = data.size))
println(root.toJson())
val map = root.toMap()
assertEquals(8, map.size)
assertEquals("world", map["hello"].toString())
assertEquals("value", map["interesting"].toString())
assertEquals(12e32, map["double"].toDouble())
assertArrayEquals(intArrayOf(1, 2, 3), map["ary"].toIntArray())
assertEquals(true, map["boolean_true"].toBoolean())
assertEquals(false, map["boolean_false"].toBoolean())
assertEquals(true, map["null_value"].isNull)
assertEquals("hello", map["object"]["field1"].toString())
val obj = map["object"]
assertEquals(true, obj.isMap)
assertEquals("{\"field1\":\"hello\"}", obj.toJson())
// TODO: Kotlin Double.toString() produce different strings dependending on the platform, so on JVM
// is 1.2E33, while on js is 1.2e+33. For now we are disabling this test.
//
// val minified = data.filterNot { it == ' '.toByte() || it == '\n'.toByte() }.toByteArray().decodeToString()
// assertEquals(minified, root.toJson())
}
@Test
fun testDoubles() {
val values = arrayOf(
"-0.0",
"1.0",
"1.7976931348613157",
"0.0",
"-0.5",
"3.141592653589793",
"2.718281828459045E-3",
"2.2250738585072014E-308",
"4.9E-15",
)
val parser = JSONParser()
assertEquals(-0.0, parser.parse(values[0]).toDouble())
assertEquals(1.0, parser.parse(values[1]).toDouble())
assertEquals(1.7976931348613157, parser.parse(values[2]).toDouble())
assertEquals(0.0, parser.parse(values[3]).toDouble())
assertEquals(-0.5, parser.parse(values[4]).toDouble())
assertEquals(3.141592653589793, parser.parse(values[5]).toDouble())
assertEquals(2.718281828459045e-3, parser.parse(values[6]).toDouble())
assertEquals(2.2250738585072014E-308, parser.parse(values[7]).toDouble())
assertEquals(4.9E-15, parser.parse(values[8]).toDouble())
}
@Test
fun testInts() {
val values = arrayOf(
"-0",
"0",
"-1",
"${Int.MAX_VALUE}",
"${Int.MIN_VALUE}",
"${Long.MAX_VALUE}",
"${Long.MIN_VALUE}",
)
val parser = JSONParser()
assertEquals(parser.parse(values[0]).toInt(), 0)
assertEquals(parser.parse(values[1]).toInt(), 0)
assertEquals(parser.parse(values[2]).toInt(), -1)
assertEquals(parser.parse(values[3]).toInt(), Int.MAX_VALUE)
assertEquals(parser.parse(values[4]).toInt(), Int.MIN_VALUE)
assertEquals(parser.parse(values[5]).toLong(), Long.MAX_VALUE)
assertEquals(parser.parse(values[6]).toLong(), Long.MIN_VALUE)
}
@Test
fun testBooleansAndNull() {
val values = arrayOf(
"true",
"false",
"null"
)
val parser = JSONParser()
assertEquals(true, parser.parse(values[0]).toBoolean())
assertEquals(false, parser.parse(values[1]).toBoolean())
assertEquals(true, parser.parse(values[2]).isNull)
}
@Test
fun testStrings() {
val values = arrayOf(
"\"\"",
"\"a\"",
"\"hello world\"",
"\"\\\"\\\\\\/\\b\\f\\n\\r\\t cool\"",
"\"\\u0000\"",
"\"\\u0021\"",
"\"hell\\u24AC\\n\\ro wor \\u0021 ld\"",
"\"\\/_\\\\_\\\"_\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"",
)
val parser = JSONParser()
// empty
var ref = parser.parse(values[0])
assertEquals(true, ref.isString)
assertEquals("", ref.toString())
// a
ref = parser.parse(values[1])
assertEquals(true, ref.isString)
assertEquals("a", ref.toString())
// hello world
ref = parser.parse(values[2])
assertEquals(true, ref.isString)
assertEquals("hello world", ref.toString())
// "\\\"\\\\\\/\\b\\f\\n\\r\\t\""
ref = parser.parse(values[3])
assertEquals(true, ref.isString)
assertEquals("\"\\/\b${12.toChar()}\n\r\t cool", ref.toString())
// 0
ref = parser.parse(values[4])
assertEquals(true, ref.isString)
assertEquals(0.toChar().toString(), ref.toString())
// u0021
ref = parser.parse(values[5])
assertEquals(true, ref.isString)
assertEquals(0x21.toChar().toString(), ref.toString())
// "\"hell\\u24AC\\n\\ro wor \\u0021 ld\"",
ref = parser.parse(values[6])
assertEquals(true, ref.isString)
assertEquals("hell${0x24AC.toChar()}\n\ro wor ${0x21.toChar()} ld", ref.toString())
ref = parser.parse(values[7])
println(ref.toJson())
assertEquals(true, ref.isString)
assertEquals("/_\\_\"_쫾몾ꮘﳞ볚\b\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?", ref.toString())
}
@Test
fun testUnicode() {
// took from test/unicode_test.json
val data = """
{
"name": "unicode_test",
"testarrayofstring": [
"Цлїςσδε",
"フムアムカモケモ",
"フムヤムカモケモ",
"㊀㊁㊂㊃㊄",
"☳☶☲",
"𡇙𝌆"
],
"testarrayoftables": [
{
"name": "Цлїςσδε"
},
{
"name": "☳☶☲"
},
{
"name": "フムヤムカモケモ"
},
{
"name": "㊀㊁㊂㊃㊄"
},
{
"name": "フムアムカモケモ"
},
{
"name": "𡇙𝌆"
}
]
}
""".trimIndent()
val parser = JSONParser()
val ref = parser.parse(data)
// name
assertEquals(3, ref.toMap().size)
assertEquals("unicode_test", ref["name"].toString())
// testarrayofstring
assertEquals(6, ref["testarrayofstring"].toVector().size)
assertEquals("Цлїςσδε", ref["testarrayofstring"][0].toString())
assertEquals("フムアムカモケモ", ref["testarrayofstring"][1].toString())
assertEquals("フムヤムカモケモ", ref["testarrayofstring"][2].toString())
assertEquals("㊀㊁㊂㊃㊄", ref["testarrayofstring"][3].toString())
assertEquals("☳☶☲", ref["testarrayofstring"][4].toString())
assertEquals("𡇙𝌆", ref["testarrayofstring"][5].toString())
// testarrayoftables
assertEquals(6, ref["testarrayoftables"].toVector().size)
assertEquals("Цлїςσδε", ref["testarrayoftables"][0]["name"].toString())
assertEquals("☳☶☲", ref["testarrayoftables"][1]["name"].toString())
assertEquals("フムヤムカモケモ", ref["testarrayoftables"][2]["name"].toString())
assertEquals("㊀㊁㊂㊃㊄", ref["testarrayoftables"][3]["name"].toString())
assertEquals("フムアムカモケモ", ref["testarrayoftables"][4]["name"].toString())
assertEquals("𡇙𝌆", ref["testarrayoftables"][5]["name"].toString())
}
@Test
fun testArrays() {
val values = arrayOf(
"[]",
"[1]",
"[0,1, 2,3 , 4 ]",
"[1.0, 2.2250738585072014E-308, 4.9E-320]",
"[1.0, 2, \"hello world\"] ",
"[ 1.1, 2, [ \"hello\" ] ]",
"[[[1]]]"
)
val parser = JSONParser()
// empty
var ref = parser.parse(values[0])
assertEquals(true, ref.isVector)
assertEquals(0, parser.parse(values[0]).toVector().size)
// single
ref = parser.parse(values[1])
assertEquals(true, ref.isTypedVector)
assertEquals(1, ref[0].toInt())
// ints
ref = parser.parse(values[2])
assertEquals(true, ref.isTypedVector)
assertEquals(T_VECTOR_INT, ref.type)
assertEquals(5, ref.toVector().size)
for (i in 0..4) {
assertEquals(i, ref[i].toInt())
}
// floats
ref = parser.parse(values[3])
assertEquals(true, ref.isTypedVector)
assertEquals(T_VECTOR_FLOAT, ref.type)
assertEquals(3, ref.toVector().size)
assertEquals(1.0, ref[0].toDouble())
assertEquals(2.2250738585072014E-308, ref[1].toDouble())
assertEquals(4.9E-320, ref[2].toDouble())
// mixed
ref = parser.parse(values[4])
assertEquals(false, ref.isTypedVector)
assertEquals(T_VECTOR, ref.type)
assertEquals(1.0, ref[0].toDouble())
assertEquals(2, ref[1].toInt())
assertEquals("hello world", ref[2].toString())
// nester array
ref = parser.parse(values[5])
assertEquals(false, ref.isTypedVector)
assertEquals(T_VECTOR, ref.type)
assertEquals(1.1, ref[0].toDouble())
assertEquals(2, ref[1].toInt())
assertEquals("hello", ref[2][0].toString())
}
/**
* Several test cases provided by json.org
* For more details, see: http://json.org/JSON_checker/, with only
* one exception. Single strings are considered accepted, whereas on
* the test suit is should fail.
*/
@Test
fun testParseMustFail() {
val failList = listOf(
"[\"Unclosed array\"",
"{unquoted_key: \"keys must be quoted\"}",
"[\"extra comma\",]",
"[\"double extra comma\",,]",
"[ , \"<-- missing value\"]",
"[\"Comma after the close\"],",
"[\"Extra close\"]]",
"{\"Extra comma\": true,}",
"{\"Extra value after close\": true} \"misplaced quoted value\"",
"{\"Illegal expression\": 1 + 2}",
"{\"Illegal invocation\": alert()}",
"{\"Numbers cannot have leading zeroes\": 013}",
"{\"Numbers cannot be hex\": 0x14}",
"[\"Illegal backslash escape: \\x15\"]",
"[\\naked]",
"[\"Illegal backslash escape: \\017\"]",
"[[[[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]]]]",
"{\"Missing colon\" null}",
"{\"Double colon\":: null}",
"{\"Comma instead of colon\", null}",
"[\"Colon instead of comma\": false]",
"[\"Bad value\", truth]",
"['single quote']",
"[\"\ttab\tcharacter\tin\tstring\t\"]",
"[\"tab\\ character\\ in\\ string\\ \"]",
"[\"line\nbreak\"]",
"[\"line\\\nbreak\"]",
"[0e]",
"[0e+]",
"[0e+-1]",
"{\"Comma instead if closing brace\": true,",
"[\"mismatch\"}"
)
for (data in failList) {
try {
JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray()))
assertTrue(false, "SHOULD NOT PASS: $data")
} catch (e: IllegalStateException) {
println("FAIL $e")
}
}
}
@Test
fun testParseMustPass() {
val passList = listOf(
"[\n" +
" \"JSON Test Pattern pass1\",\n" +
" {\"object with 1 member\":[\"array with 1 element\"]},\n" +
" {},\n" +
" [],\n" +
" -42,\n" +
" true,\n" +
" false,\n" +
" null,\n" +
" {\n" +
" \"integer\": 1234567890,\n" +
" \"real\": -9876.543210,\n" +
" \"e\": 0.123456789e-12,\n" +
" \"E\": 1.234567890E+34,\n" +
" \"\": 23456789012E66,\n" +
" \"zero\": 0,\n" +
" \"one\": 1,\n" +
" \"space\": \" \",\n" +
" \"quote\": \"\\\"\",\n" +
" \"backslash\": \"\\\\\",\n" +
" \"controls\": \"\\b\\f\\n\\r\\t\",\n" +
" \"slash\": \"/ & \\/\",\n" +
" \"alpha\": \"abcdefghijklmnopqrstuvwyz\",\n" +
" \"ALPHA\": \"ABCDEFGHIJKLMNOPQRSTUVWYZ\",\n" +
" \"digit\": \"0123456789\",\n" +
" \"0123456789\": \"digit\",\n" +
" \"special\": \"`1~!@#\$%^&*()_+-={':[,]}|;.</>?\",\n" +
" \"hex\": \"\\u0123\\u4567\\u89AB\\uCDEF\\uabcd\\uef4A\",\n" +
" \"true\": true,\n" +
" \"false\": false,\n" +
" \"null\": null,\n" +
" \"array\":[ ],\n" +
" \"object\":{ },\n" +
" \"address\": \"50 St. James Street\",\n" +
" \"url\": \"http://www.JSON.org/\",\n" +
" \"comment\": \"// /* <!-- --\",\n" +
" \"# -- --> */\": \" \",\n" +
" \" s p a c e d \" :[1,2 , 3\n" +
"\n" +
",\n" +
"\n" +
"4 , 5 , 6 ,7 ],\"compact\":[1,2,3,4,5,6,7],\n" +
" \"jsontext\": \"{\\\"object with 1 member\\\":[\\\"array with 1 element\\\"]}\",\n" +
" \"quotes\": \"" \\u0022 %22 0x22 034 "\",\n" +
" \"\\/\\\\\\\"\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\f\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"\n" +
": \"A key can be any string\"\n" +
" },\n" +
" 0.5 ,98.6\n" +
",\n" +
"99.44\n" +
",\n" +
"\n" +
"1066,\n" +
"1e1,\n" +
"0.1e1,\n" +
"1e-1,\n" +
"1e00,2e+00,2e-00\n" +
",\"rosebud\"]",
"{\n" +
" \"JSON Test Pattern pass3\": {\n" +
" \"The outermost value\": \"must be an object or array.\",\n" +
" \"In this test\": \"It is an object.\"\n" +
" }\n" +
"}",
"[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]",
)
for (data in passList) {
JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray()))
}
}
}
| apache-2.0 | 3485f004dbbe953f71cdf8ef8d362d49 | 32.138173 | 126 | 0.523463 | 3.278499 | false | true | false | false |
dkrivoruchko/ScreenStream | mjpeg/src/main/kotlin/info/dvkr/screenstream/mjpeg/state/StreamState.kt | 1 | 1433 | package info.dvkr.screenstream.mjpeg.state
import android.media.projection.MediaProjection
import info.dvkr.screenstream.common.AppError
import info.dvkr.screenstream.mjpeg.MjpegPublicState
import info.dvkr.screenstream.mjpeg.NetInterface
import info.dvkr.screenstream.mjpeg.image.BitmapCapture
data class StreamState(
val state: State = State.CREATED,
val mediaProjection: MediaProjection? = null,
val bitmapCapture: BitmapCapture? = null,
val netInterfaces: List<NetInterface> = emptyList(),
val httpServerAddressAttempt: Int = 0,
val appError: AppError? = null
) {
enum class State { CREATED, ADDRESS_DISCOVERED, SERVER_STARTED, PERMISSION_PENDING, STREAMING, RESTART_PENDING, ERROR, DESTROYED }
internal fun isPublicStatePublishRequired(previousStreamState: StreamState): Boolean =
(state != State.DESTROYED && state != previousStreamState.state) ||
netInterfaces != previousStreamState.netInterfaces ||
appError != previousStreamState.appError
internal fun toPublicState() = MjpegPublicState(
isStreaming(), (canStartStream() || isStreaming()).not(), isWaitingForPermission(), netInterfaces, appError
)
internal fun isStreaming(): Boolean = state == State.STREAMING
private fun canStartStream(): Boolean = state == State.SERVER_STARTED
private fun isWaitingForPermission(): Boolean = state == State.PERMISSION_PENDING
} | mit | 34db3c714fd351ea2577eed9807afe78 | 39.971429 | 134 | 0.74529 | 4.698361 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdets-idea/src/vgrechka/phizdetsidea/reflection/ReflectionUtils.kt | 1 | 5869 | /*
* 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 vgrechka.phizdetsidea.reflection
import com.intellij.util.containers.HashMap
import java.beans.Introspector
import java.beans.PropertyDescriptor
import java.util.*
import kotlin.reflect.KClass
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaType
import kotlin.reflect.memberProperties
/**
* Tools to fetch properties both from Java and Kotlin code and to copy them from one object to another.
* To be a property container class should have kotlin properties, java bean properties or implement [SimplePropertiesProvider].
*
* Properties should be writable except [DelegationProperty]
* @author Ilya.Kazakevich
*/
interface Property {
fun getName(): String
fun getType(): java.lang.reflect.Type
fun get(): Any?
fun set(value: Any?)
}
private class KotlinProperty(val property: KMutableProperty<*>, val instance: Any?) : Property {
override fun getName() = property.name
override fun getType() = property.returnType.javaType
override fun get() = property.getter.call(instance)
override fun set(value: Any?) = property.setter.call(instance, value)
}
private class JavaProperty(val property: PropertyDescriptor, val instance: Any?) : Property {
override fun getName() = property.name!!
override fun getType() = property.propertyType!!
override fun get() = property.readMethod.invoke(instance)!!
override fun set(value: Any?) {
property.writeMethod.invoke(instance, value)
}
}
private class SimpleProperty(private val propertyName: String,
private val provider: SimplePropertiesProvider) : Property {
override fun getName() = propertyName
override fun getType() = String::class.java
override fun get() = provider.getPropertyValue(propertyName)
override fun set(value: Any?) = provider.setPropertyValue(propertyName, value?.toString())
}
/**
* Implement to handle properties manually
*/
interface SimplePropertiesProvider {
val propertyNames: List<String>
fun setPropertyValue(propertyName: String, propertyValue: String?)
fun getPropertyValue(propertyName: String): String?
}
class Properties(val properties: List<Property>, val instance: Any) {
val propertiesMap: MutableMap<String, Property> = HashMap(properties.map { Pair(it.getName(), it) }.toMap())
init {
if (instance is SimplePropertiesProvider) {
instance.propertyNames.forEach { propertiesMap.put(it, SimpleProperty(it, instance)) }
}
}
fun copyTo(dst: Properties) {
propertiesMap.values.forEach {
val dstProperty = dst.propertiesMap[it.getName()]
if (dstProperty != null) {
val value = it.get()
dstProperty.set(value)
}
}
}
}
private fun KProperty<*>.isAnnotated(annotation: KClass<*>): Boolean {
return this.annotations.find { annotation.java.isAssignableFrom(it.javaClass) } != null
}
/**
* @param instance object with properties (see module doc)
* @param annotationToFilterByClass optional annotation class to fetch only kotlin properties annotated with it. Only supported in Kotlin
* @param usePojoProperties search for java-style properties (kotlin otherwise)
* @return properties of some object
*/
fun getProperties(instance: Any, annotationToFilterByClass: Class<*>? = null, usePojoProperties: Boolean = false): Properties {
val annotationToFilterBy = annotationToFilterByClass?.kotlin
if (usePojoProperties) {
// Java props
val javaProperties = Introspector.getBeanInfo(instance.javaClass).propertyDescriptors
assert(annotationToFilterBy == null, { "Filtering java properties is not supported" })
return Properties(javaProperties.map { JavaProperty(it, instance) }, instance)
}
else {
// Kotlin props
val klass = instance.javaClass.kotlin
val allKotlinProperties = LinkedHashSet(klass.memberProperties.filterIsInstance(KProperty::class.java))
val delegatedProperties = ArrayList<Property>() // See DelegationProperty doc
allKotlinProperties.filter { it.isAnnotated(DelegationProperty::class) }.forEach {
val delegatedInstance = it.getter.call(instance)
if (delegatedInstance != null) {
delegatedProperties.addAll(getProperties(delegatedInstance, annotationToFilterBy?.java, false).properties)
allKotlinProperties.remove(it)
}
}
val firstLevelProperties = allKotlinProperties.filterIsInstance(KMutableProperty::class.java)
if (annotationToFilterBy == null) {
return Properties(firstLevelProperties.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
return Properties(
firstLevelProperties.filter { it.isAnnotated(annotationToFilterBy) }.map { KotlinProperty(it, instance) } + delegatedProperties, instance)
}
}
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
/**
* Property marked with it is not considered to be [Property] by itself, but class with properties instead.
* Following structure is example:
* class User:
* +familyName: String
* +lastName: String
* +credentials: Credentials
*
* class Credentials:
* +login: String
* +password: String
*
* Property credentials here is [DelegationProperty]. It can be val, but all other properties should be var
*/
annotation class DelegationProperty | apache-2.0 | 8c57a45a185bc15bd4f9eb29d79cd7f4 | 36.628205 | 144 | 0.746635 | 4.525058 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/request/GHRepoRequestParams.kt | 7 | 1333 | // 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.plugins.github.api.data.request
/**
* Additional params for [`GET /user/repos`](https://developer.github.com/v3/repos/#list-your-repositories) request
*/
enum class Type(private val value: String) {
ALL(""),
OWNER("owner"),
PUBLIC("public"),
PRIVATE("private"),
MEMBER("member");
companion object {
val DEFAULT = ALL
}
override fun toString() = if (value.isEmpty()) value else "type=$value"
}
enum class Visibility(private val value: String) {
ALL(""),
PUBLIC("public"),
PRIVATE("private");
companion object {
val DEFAULT = ALL
}
override fun toString() = if (value.isEmpty()) value else "visibility=$value"
}
class Affiliation private constructor(private val value: String) {
companion object {
val OWNER = Affiliation("owner")
val COLLABORATOR = Affiliation("collaborator")
@Suppress("unused") // API
val ORG_MEMBER = Affiliation("organization_member")
val DEFAULT = Affiliation("")
fun combine(vararg affiliations: Affiliation): Affiliation {
return Affiliation(affiliations.toSet().joinToString(",") { it.value })
}
}
override fun toString() = if (value.isEmpty()) value else "affiliation=$value"
}
| apache-2.0 | 08fb775cc22dcc14caee706a5a4b0a62 | 27.361702 | 120 | 0.687922 | 4.064024 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/autofill/FakeViewStructure.kt | 3 | 8752 | /*
* 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.compose.ui.autofill
import android.graphics.Matrix
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.LocaleList
import android.os.Parcel
import android.view.View
import android.view.ViewStructure
import android.view.autofill.AutofillId
import android.view.autofill.AutofillValue
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
/**
* A fake implementation of [ViewStructure] to use in tests.
*
* @param virtualId An ID that is unique for each viewStructure node in the viewStructure tree.
* @param packageName The package name of the app (Used as an autofill heuristic).
* @param typeName The type name of the view's identifier, or null if there is none.
* @param entryName The entry name of the view's identifier, or null if there is none.
* @param children A list of [ViewStructure]s that are children of the current [ViewStructure].
* @param bounds The bounds (Dimensions) of the component represented by this [ViewStructure].
* @param autofillId The [autofillId] for the parent component. The same autofillId is used for
* other child components.
* @param autofillType The data type. Can be one of the following:
* [View.AUTOFILL_TYPE_DATE],
* [View.AUTOFILL_TYPE_LIST],
* [View.AUTOFILL_TYPE_TEXT],
* [View.AUTOFILL_TYPE_TOGGLE] or
* [View.AUTOFILL_TYPE_NONE].
* @param autofillHints The autofill hint. If this value not specified, we use heuristics to
* determine what data to use while performing autofill.
*
* @suppress
*/
@RequiresApi(Build.VERSION_CODES.O)
internal data class FakeViewStructure(
var virtualId: Int = 0,
var packageName: String? = null,
var typeName: String? = null,
var entryName: String? = null,
var children: MutableList<FakeViewStructure> = mutableListOf(),
var bounds: Rect? = null,
private val autofillId: AutofillId? = generateAutofillId(),
private var autofillType: Int = View.AUTOFILL_TYPE_NONE,
private var autofillHints: Array<out String> = arrayOf()
) : ViewStructure() {
internal companion object {
@GuardedBy("this")
private var previousId = 0
private val NO_SESSION = 0
@Synchronized
private fun generateAutofillId(): AutofillId {
var autofillId: AutofillId? = null
useParcel { parcel ->
parcel.writeInt(++previousId) // View Id.
parcel.writeInt(NO_SESSION) // Flag.
parcel.setDataPosition(0)
autofillId = AutofillId.CREATOR.createFromParcel(parcel)
}
return autofillId ?: error("Could not generate autofill id")
}
}
override fun getChildCount() = children.count()
override fun addChildCount(childCount: Int): Int {
repeat(childCount) { children.add(FakeViewStructure(autofillId = autofillId)) }
return children.count() - childCount
}
override fun newChild(index: Int): FakeViewStructure {
if (index >= children.count()) error("Call addChildCount() before calling newChild()")
return children[index]
}
override fun getAutofillId() = autofillId
override fun setAutofillId(rootId: AutofillId, virtualId: Int) {
this.virtualId = virtualId
}
override fun setId(
virtualId: Int,
packageName: String?,
typeName: String?,
entryName: String?
) {
this.virtualId = virtualId
this.packageName = packageName
this.typeName = typeName
this.entryName = entryName
}
override fun setAutofillType(autofillType: Int) {
this.autofillType = autofillType
}
override fun setAutofillHints(autofillHints: Array<out String>?) {
autofillHints?.let { this.autofillHints = it }
}
override fun setDimens(left: Int, top: Int, x: Int, y: Int, width: Int, height: Int) {
this.bounds = Rect(left, top, width - left, height - top)
}
override fun equals(other: Any?) = other is FakeViewStructure &&
other.virtualId == virtualId &&
other.packageName == packageName &&
other.typeName == typeName &&
other.entryName == entryName &&
other.autofillType == autofillType &&
other.autofillHints.contentEquals(autofillHints) &&
other.bounds.contentEquals(bounds) &&
other.children == children
override fun hashCode() = super.hashCode()
// Unimplemented methods.
override fun setOpaque(p0: Boolean) { TODO("not implemented") }
override fun setHint(p0: CharSequence?) { TODO("not implemented") }
override fun setElevation(p0: Float) { TODO("not implemented") }
override fun getText(): CharSequence { TODO("not implemented") }
override fun setText(p0: CharSequence?) { TODO("not implemented") }
override fun setText(p0: CharSequence?, p1: Int, p2: Int) { TODO("not implemented") }
override fun asyncCommit() { TODO("not implemented") }
override fun setEnabled(p0: Boolean) { TODO("not implemented") }
override fun setLocaleList(p0: LocaleList?) { TODO("not implemented") }
override fun setChecked(p0: Boolean) { TODO("not implemented") }
override fun setContextClickable(p0: Boolean) { TODO("not implemented") }
override fun setAccessibilityFocused(p0: Boolean) { TODO("not implemented") }
override fun setAlpha(p0: Float) { TODO("not implemented") }
override fun setTransformation(p0: Matrix?) { TODO("not implemented") }
override fun setClassName(p0: String?) { TODO("not implemented") }
override fun setLongClickable(p0: Boolean) { TODO("not implemented") }
override fun getHint(): CharSequence { TODO("not implemented") }
override fun setInputType(p0: Int) { TODO("not implemented") }
override fun setWebDomain(p0: String?) { TODO("not implemented") }
override fun setAutofillOptions(p0: Array<out CharSequence>?) { TODO("not implemented") }
override fun setTextStyle(p0: Float, p1: Int, p2: Int, p3: Int) { TODO("not implemented") }
override fun setVisibility(p0: Int) { TODO("not implemented") }
override fun setHtmlInfo(p0: HtmlInfo) { TODO("not implemented") }
override fun setTextLines(p0: IntArray?, p1: IntArray?) { TODO("not implemented") }
override fun getExtras(): Bundle { TODO("not implemented") }
override fun setClickable(p0: Boolean) { TODO("not implemented") }
override fun newHtmlInfoBuilder(p0: String): HtmlInfo.Builder { TODO("not implemented") }
override fun getTextSelectionEnd(): Int { TODO("not implemented") }
override fun setAutofillId(p0: AutofillId) { TODO("not implemented") }
override fun hasExtras(): Boolean { TODO("not implemented") }
override fun setActivated(p0: Boolean) { TODO("not implemented") }
override fun setFocused(p0: Boolean) { TODO("not implemented") }
override fun getTextSelectionStart(): Int { TODO("not implemented") }
override fun setChildCount(p0: Int) { TODO("not implemented") }
override fun setAutofillValue(p0: AutofillValue?) { TODO("not implemented") }
override fun setContentDescription(p0: CharSequence?) { TODO("not implemented") }
override fun setFocusable(p0: Boolean) { TODO("not implemented") }
override fun setCheckable(p0: Boolean) { TODO("not implemented") }
override fun asyncNewChild(p0: Int): ViewStructure { TODO("not implemented") }
override fun setSelected(p0: Boolean) { TODO("not implemented") }
override fun setDataIsSensitive(p0: Boolean) { TODO("not implemented") }
}
private fun Rect?.contentEquals(other: Rect?) = when {
(other == null && this == null) -> true
(other == null || this == null) -> false
else ->
other.left == left &&
other.right == right &&
other.bottom == bottom &&
other.top == top
}
/** Obtains a parcel and then recycles it correctly whether an exception is thrown or not. */
private fun useParcel(block: (Parcel) -> Unit) {
var parcel: Parcel? = null
try {
parcel = Parcel.obtain()
block(parcel)
} finally {
parcel?.recycle()
}
}
| apache-2.0 | cbad15ad6105de5d9cb38925b9daa24e | 35.016461 | 95 | 0.682244 | 4.217831 | false | false | false | false |
androidx/androidx | benchmark/benchmark-macro/src/androidTest/java/androidx/benchmark/macro/MacrobenchmarkScopeTest.kt | 3 | 10616 | /*
* 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.benchmark.macro
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.benchmark.DeviceInfo
import androidx.benchmark.Shell
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import org.junit.Assert.fail
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class MacrobenchmarkScopeTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
@Before
@Suppress("DEPRECATION")
fun setup() {
// validate target is installed with clear error message,
// since error messages from e.g. startActivityAndWait may be less clear
try {
val pm = instrumentation.context.packageManager
pm.getApplicationInfo(Packages.TARGET, 0)
} catch (notFoundException: PackageManager.NameNotFoundException) {
throw IllegalStateException(
"Unable to find target ${Packages.TARGET}, is it installed?"
)
}
}
@Test
fun killTest() {
val scope = MacrobenchmarkScope(Packages.TARGET, launchWithClearTask = true)
scope.pressHome()
scope.startActivityAndWait()
assertTrue(Shell.isPackageAlive(Packages.TARGET))
scope.killProcess()
assertFalse(Shell.isPackageAlive(Packages.TARGET))
}
@SdkSuppress(minSdkVersion = 24)
@Test
fun compile_speedProfile() {
val scope = MacrobenchmarkScope(Packages.TARGET, launchWithClearTask = true)
val iterations = 1
var executions = 0
val compilation = CompilationMode.Partial(
baselineProfileMode = BaselineProfileMode.Disable,
warmupIterations = iterations
)
compilation.resetAndCompile(
Packages.TARGET,
killProcessBlock = scope::killProcess
) {
executions += 1
scope.pressHome()
scope.startActivityAndWait()
}
assertEquals(iterations, executions)
}
@Test
fun compile_full() {
val scope = MacrobenchmarkScope(Packages.TARGET, launchWithClearTask = true)
val compilation = CompilationMode.Full()
compilation.resetAndCompile(
Packages.TARGET,
killProcessBlock = scope::killProcess
) {
fail("Should never be called for $compilation")
}
}
@Test
fun startActivityAndWait_activityNotExported() {
val scope = MacrobenchmarkScope(Packages.TARGET, launchWithClearTask = true)
scope.pressHome()
val intent = Intent()
intent.setPackage(Packages.TARGET)
intent.action = "${Packages.TARGET}.NOT_EXPORTED_ACTIVITY"
// Workaround b/227512788 - isSessionRooted isn't reliable below API 24 on rooted devices
assumeTrue(Build.VERSION.SDK_INT > 23 || !DeviceInfo.isRooted)
if (Shell.isSessionRooted()) {
// while device and adb session are both rooted, doesn't throw
scope.startActivityAndWait(intent)
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
assertTrue(device.hasObject(By.text("NOT EXPORTED ACTIVITY")))
} else {
// should throw, warning to set exported = true
// Note: rooted device will hit this path, unless `adb root` is invoked
val exceptionMessage = assertFailsWith<SecurityException> {
scope.startActivityAndWait(intent)
}.message
assertNotNull(exceptionMessage)
assertTrue(exceptionMessage.contains("Permission Denial"))
assertTrue(exceptionMessage.contains("NotExportedActivity"))
assertTrue(exceptionMessage.contains("not exported"))
}
}
// Note: Test flakes locally on API 23, appears to be UI automation issue. In API 23 CI running
// MRA58K crashes, but haven't repro'd locally, so just skip on API 23.
@SdkSuppress(minSdkVersion = 24)
@Test
fun startActivityAndWait_invalidActivity() {
val scope = MacrobenchmarkScope(Packages.TARGET, launchWithClearTask = true)
scope.pressHome()
val intent = Intent()
intent.setPackage("this.is.not.a.real.package")
intent.action = "${Packages.TARGET}.NOT_EXPORTED_ACTIVITY"
// should throw, unable to resolve Intent
val exceptionMessage = assertFailsWith<IllegalStateException> {
scope.startActivityAndWait(intent)
}.message
assertNotNull(exceptionMessage)
assertTrue(exceptionMessage.contains("unable to resolve Intent"))
}
@Test
fun startActivityAndWait_sameActivity() {
val scope = MacrobenchmarkScope(
Packages.TEST, // self-instrumenting macrobench, so don't kill the process!
launchWithClearTask = true
)
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
// Launch first activity, and validate it is displayed
scope.startActivityAndWait(ConfigurableActivity.createIntent("InitialText"))
assertTrue(device.hasObject(By.text("InitialText")))
// Launch second activity, and validate it is displayed
// By having the activity sleep during launch, we validate that the wait actually occurs,
// and that we're not seeing the previous Activity (which could happen if the wait
// doesn't occur, or if launch is extremely fast).
scope.startActivityAndWait(
ConfigurableActivity.createIntent(
text = "UpdatedText",
sleepDurMs = 1000L
)
)
assertTrue(device.hasObject(By.text("UpdatedText")))
}
private fun validateLaunchAndFrameStats(pressHome: Boolean) {
val scope = MacrobenchmarkScope(
Packages.TEST, // self-instrumenting macrobench, so don't kill the process!
launchWithClearTask = false
)
// check that initial launch (home -> activity) is detected
scope.pressHome()
scope.startActivityAndWait(ConfigurableActivity.createIntent("InitialText"))
val initialFrameStats = scope.getFrameStats()
.sortedBy { it.lastFrameNs }
.first()
assertTrue(initialFrameStats.uniqueName.contains("ConfigurableActivity"))
if (pressHome) {
scope.pressHome()
}
// check that hot startup is detected
scope.startActivityAndWait(ConfigurableActivity.createIntent("InitialText"))
val secondFrameStats = scope.getFrameStats()
.sortedBy { it.lastFrameNs }
.first()
assertTrue(secondFrameStats.uniqueName.contains("ConfigurableActivity"))
if (pressHome) {
assertTrue(secondFrameStats.lastFrameNs!! > initialFrameStats.lastFrameNs!!)
}
}
/** Tests getFrameStats after launch which resumes app */
@Test
fun getFrameStats_home() = validateLaunchAndFrameStats(pressHome = true)
/** Tests getFrameStats after launch which does nothing, as Activity already visible */
@Test
fun getFrameStats_noop() = validateLaunchAndFrameStats(pressHome = false)
private fun validateShaderCache(empty: Boolean, packageName: String) {
val path = MacrobenchmarkScope.getShaderCachePath(packageName)
println("validating shader path $path")
val fileCount = Shell.executeScriptCaptureStdout("find $path -type f | wc -l")
.trim()
.toInt()
if (empty) {
assertEquals(0, fileCount)
} else {
assertNotEquals(0, fileCount)
}
}
private fun validateDropShaderCacheWithRoot(
dropShaderCacheBlock: MacrobenchmarkScope.() -> Unit
) {
// need root to inspect target app's code cache dir, and emulators
// don't seem to store shaders
assumeTrue(Shell.isSessionRooted() && !DeviceInfo.isEmulator)
val scope = MacrobenchmarkScope(
Packages.TARGET,
launchWithClearTask = false
)
// reset to empty to begin with
scope.killProcess()
scope.dropShaderCacheBlock()
validateShaderCache(empty = true, scope.packageName)
// start an activity, expecting shader compilation
scope.pressHome()
// NOTE: if platform fixes default activity to not compile shaders,
// may need to update this test UI to trigger shader creation
scope.startActivityAndWait()
Thread.sleep(5000) // sleep to await flushing cache to disk
scope.killProcess()
validateShaderCache(empty = false, scope.packageName)
// verify deletion
scope.killProcess()
scope.dropShaderCacheBlock()
validateShaderCache(empty = true, scope.packageName)
}
@Test
fun dropShaderCacheBroadcast() = validateDropShaderCacheWithRoot {
// since this test runs on root and the public api falls back to
// a root impl, test the broadcast directly
assertNull(ProfileInstallBroadcast.dropShaderCache(packageName))
}
@Test
fun dropShaderCachePublicApi() = validateDropShaderCacheWithRoot {
dropShaderCache()
}
@Test
fun dropKernelPageCache() {
val scope = MacrobenchmarkScope(
Packages.TARGET,
launchWithClearTask = false
)
scope.dropKernelPageCache() // shouldn't crash
}
}
| apache-2.0 | a05bfb8fdae8a1eaee6f24b01da1ed80 | 36.64539 | 99 | 0.672099 | 4.926218 | false | true | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/solver/transaction/binder/CoroutineTransactionMethodBinder.kt | 3 | 4646 | /*
* Copyright 2019 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.room.solver.transaction.binder
import androidx.room.compiler.codegen.CodeLanguage
import androidx.room.compiler.codegen.XClassName
import androidx.room.compiler.codegen.XCodeBlock
import androidx.room.compiler.codegen.XFunSpec.Builder.Companion.addStatement
import androidx.room.compiler.codegen.XPropertySpec
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.processing.XType
import androidx.room.ext.Function1TypeSpec
import androidx.room.ext.KotlinTypeNames
import androidx.room.ext.RoomMemberNames
import androidx.room.ext.isNotKotlinUnit
import androidx.room.solver.CodeGenScope
import androidx.room.solver.transaction.result.TransactionMethodAdapter
/**
* Binder that knows how to write suspending transaction wrapper methods.
*/
class CoroutineTransactionMethodBinder(
adapter: TransactionMethodAdapter,
private val continuationParamName: String,
private val javaLambdaSyntaxAvailable: Boolean
) : TransactionMethodBinder(adapter) {
override fun executeAndReturn(
returnType: XType,
parameterNames: List<String>,
daoName: XClassName,
daoImplName: XClassName,
dbProperty: XPropertySpec,
scope: CodeGenScope
) {
when (scope.language) {
CodeLanguage.JAVA -> executeAndReturnJava(
returnType, parameterNames, daoName, daoImplName, dbProperty, scope
)
CodeLanguage.KOTLIN -> executeAndReturnKotlin(
returnType, parameterNames, daoName, daoImplName, dbProperty, scope
)
}
}
private fun executeAndReturnJava(
returnType: XType,
parameterNames: List<String>,
daoName: XClassName,
daoImplName: XClassName,
dbProperty: XPropertySpec,
scope: CodeGenScope
) {
val innerContinuationParamName = "__cont"
val adapterScope = scope.fork()
adapter.createDelegateToSuperCode(
parameterNames = parameterNames + innerContinuationParamName,
daoName = daoName,
daoImplName = daoImplName,
returnStmt = !javaLambdaSyntaxAvailable,
scope = adapterScope
)
val functionImpl: Any = if (javaLambdaSyntaxAvailable) {
XCodeBlock.of(
scope.language,
"(%L) -> %L",
innerContinuationParamName, adapterScope.generate()
)
} else {
Function1TypeSpec(
language = scope.language,
parameterTypeName = KotlinTypeNames.CONTINUATION.parametrizedBy(
XTypeName.getConsumerSuperName(returnType.asTypeName())
),
parameterName = innerContinuationParamName,
returnTypeName = KotlinTypeNames.ANY
) {
addStatement("%L", adapterScope.generate())
}
}
scope.builder.addStatement(
"return %M(%N, %L, %L)",
RoomMemberNames.ROOM_DATABASE_WITH_TRANSACTION,
dbProperty,
functionImpl,
continuationParamName
)
}
private fun executeAndReturnKotlin(
returnType: XType,
parameterNames: List<String>,
daoName: XClassName,
daoImplName: XClassName,
dbProperty: XPropertySpec,
scope: CodeGenScope
) {
scope.builder.apply {
if (returnType.isNotKotlinUnit()) {
add("return ")
}
beginControlFlow(
"%N.%M",
dbProperty, RoomMemberNames.ROOM_DATABASE_WITH_TRANSACTION
)
val adapterScope = scope.fork()
adapter.createDelegateToSuperCode(
parameterNames = parameterNames,
daoName = daoName,
daoImplName = daoImplName,
scope = adapterScope
)
addStatement("%L", adapterScope.generate())
endControlFlow()
}
}
} | apache-2.0 | 10daeab0425562b555bf47d9ae4a9c81 | 34.473282 | 83 | 0.642703 | 5.044517 | false | false | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/files/FileDownloadMaintenance.kt | 1 | 3334 | package com.stevenschoen.putionew.files
import android.app.Activity
import android.app.DownloadManager
import android.app.job.JobParameters
import android.app.job.JobService
import android.content.Context
import android.os.AsyncTask
import androidx.annotation.WorkerThread
import com.stevenschoen.putionew.putioApp
class FileDownloadsMaintenanceService : JobService() {
companion object {
const val FILE_DOWNLOADS_MAINTENANCE_JOB_ID = 1
}
override fun onStartJob(job: JobParameters): Boolean {
if (job.jobId != FILE_DOWNLOADS_MAINTENANCE_JOB_ID) return false
val fileDownloads = putioApp.fileDownloadDatabase.fileDownloadsDao()
AsyncTask.execute {
fileDownloads.getAllByStatus(FileDownload.Status.Downloaded)
.forEach { fileDownload ->
if (!isFileDownloaded(this, fileDownload)) {
fileDownloads.delete(fileDownload)
}
}
}
return true
}
override fun onStopJob(job: JobParameters?) = false
}
@WorkerThread
fun isFileDownloaded(context: Context, fileId: Long): Boolean {
val fileDownload = putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId)
?: return false
return isFileDownloaded(context, fileDownload)
}
@WorkerThread
fun isFileDownloaded(context: Context, fileDownload: FileDownload): Boolean {
if (fileDownload.downloadId == null || fileDownload.uri == null) return false
val status = queryDownloadStatus(context, fileDownload)
return status == DownloadManager.STATUS_SUCCESSFUL
}
@WorkerThread
fun isFileDownloadedOrDownloading(context: Context, fileDownload: FileDownload): Boolean {
if (fileDownload.downloadId == null) return false
val status = queryDownloadStatus(context, fileDownload)
return when (status) {
DownloadManager.STATUS_PENDING,
DownloadManager.STATUS_RUNNING,
DownloadManager.STATUS_SUCCESSFUL -> true
else -> false
}
}
private fun queryDownloadStatus(context: Context, fileDownload: FileDownload): Int {
val downloadManager = context.getSystemService(Activity.DOWNLOAD_SERVICE) as DownloadManager
downloadManager.query(
DownloadManager.Query()
.setFilterById(fileDownload.downloadId!!)
).use { query ->
if (query.moveToFirst()) {
return query.getInt(query.getColumnIndex(DownloadManager.COLUMN_STATUS))
} else {
return DownloadManager.STATUS_FAILED
}
}
}
@WorkerThread
fun markFileNotDownloaded(context: Context, fileId: Long) {
putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId)?.let {
markFileNotDownloaded(context, it)
}
}
@WorkerThread
fun markFileNotDownloaded(context: Context, fileDownload: FileDownload) {
putioApp(context).fileDownloadDatabase.fileDownloadsDao().update(fileDownload.apply {
status = FileDownload.Status.NotDownloaded
uri = null
downloadId = null
})
}
@WorkerThread
fun markFileDownloaded(context: Context, fileId: Long) {
putioApp(context).fileDownloadDatabase.fileDownloadsDao().getByFileIdSynchronous(fileId)?.let {
markFileDownloaded(context, it)
}
}
@WorkerThread
fun markFileDownloaded(context: Context, fileDownload: FileDownload) {
putioApp(context).fileDownloadDatabase.fileDownloadsDao().update(fileDownload.apply {
status = FileDownload.Status.Downloaded
})
}
| mit | f79ed365a065fa6538d0c3402da56dc4 | 30.752381 | 109 | 0.759448 | 4.421751 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/platform/Wrapper.skiko.kt | 3 | 2017 | /*
* 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.ui.platform
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Composition
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.node.LayoutNode
/**
* Composes the given composable into [SkiaBasedOwner]
*
* @param parent The parent composition reference to coordinate scheduling of composition updates
* If null then default root composition will be used.
* @param content A `@Composable` function declaring the UI contents
*/
@OptIn(ExperimentalComposeUiApi::class)
internal fun SkiaBasedOwner.setContent(
parent: CompositionContext,
content: @Composable () -> Unit
): Composition {
val composition = Composition(DefaultUiApplier(root), parent)
val owner = this
composition.setContent {
ProvideCommonCompositionLocals(
owner = owner,
uriHandler = PlatformUriHandler(),
content = content
)
if (owner.accessibilityController != null) {
LaunchedEffect(owner) { owner.accessibilityController!!.syncLoop() }
}
}
return composition
}
internal actual fun createSubcomposition(
container: LayoutNode,
parent: CompositionContext
): Composition = Composition(
DefaultUiApplier(container),
parent
)
| apache-2.0 | cdc48b86d2d940d5fcf08f29809735a6 | 33.775862 | 97 | 0.737729 | 4.712617 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/SignedPreKeyDatabase.kt | 2 | 4110 | package org.thoughtcrime.securesms.database
import android.content.Context
import androidx.core.content.contentValuesOf
import org.signal.core.util.SqlUtil
import org.signal.core.util.logging.Log
import org.signal.core.util.requireInt
import org.signal.core.util.requireLong
import org.signal.core.util.requireNonNullString
import org.signal.libsignal.protocol.InvalidKeyException
import org.signal.libsignal.protocol.ecc.Curve
import org.signal.libsignal.protocol.ecc.ECKeyPair
import org.signal.libsignal.protocol.state.SignedPreKeyRecord
import org.thoughtcrime.securesms.util.Base64
import org.whispersystems.signalservice.api.push.ServiceId
import java.io.IOException
import java.util.LinkedList
class SignedPreKeyDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) {
companion object {
private val TAG = Log.tag(SignedPreKeyDatabase::class.java)
const val TABLE_NAME = "signed_prekeys"
const val ID = "_id"
const val ACCOUNT_ID = "account_id"
const val KEY_ID = "key_id"
const val PUBLIC_KEY = "public_key"
const val PRIVATE_KEY = "private_key"
const val SIGNATURE = "signature"
const val TIMESTAMP = "timestamp"
const val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY,
$ACCOUNT_ID TEXT NOT NULL,
$KEY_ID INTEGER UNIQUE,
$PUBLIC_KEY TEXT NOT NULL,
$PRIVATE_KEY TEXT NOT NULL,
$SIGNATURE TEXT NOT NULL,
$TIMESTAMP INTEGER DEFAULT 0,
UNIQUE($ACCOUNT_ID, $KEY_ID)
)
"""
}
fun get(serviceId: ServiceId, keyId: Int): SignedPreKeyRecord? {
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ? AND $KEY_ID = ?", SqlUtil.buildArgs(serviceId, keyId), null, null, null).use { cursor ->
if (cursor.moveToFirst()) {
try {
val publicKey = Curve.decodePoint(Base64.decode(cursor.requireNonNullString(PUBLIC_KEY)), 0)
val privateKey = Curve.decodePrivatePoint(Base64.decode(cursor.requireNonNullString(PRIVATE_KEY)))
val signature = Base64.decode(cursor.requireNonNullString(SIGNATURE))
val timestamp = cursor.requireLong(TIMESTAMP)
return SignedPreKeyRecord(keyId, timestamp, ECKeyPair(publicKey, privateKey), signature)
} catch (e: InvalidKeyException) {
Log.w(TAG, e)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return null
}
fun getAll(serviceId: ServiceId): List<SignedPreKeyRecord> {
val results: MutableList<SignedPreKeyRecord> = LinkedList()
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ?", SqlUtil.buildArgs(serviceId), null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
val keyId = cursor.requireInt(KEY_ID)
val publicKey = Curve.decodePoint(Base64.decode(cursor.requireNonNullString(PUBLIC_KEY)), 0)
val privateKey = Curve.decodePrivatePoint(Base64.decode(cursor.requireNonNullString(PRIVATE_KEY)))
val signature = Base64.decode(cursor.requireNonNullString(SIGNATURE))
val timestamp = cursor.requireLong(TIMESTAMP)
results.add(SignedPreKeyRecord(keyId, timestamp, ECKeyPair(publicKey, privateKey), signature))
} catch (e: InvalidKeyException) {
Log.w(TAG, e)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun insert(serviceId: ServiceId, keyId: Int, record: SignedPreKeyRecord) {
val contentValues = contentValuesOf(
ACCOUNT_ID to serviceId.toString(),
KEY_ID to keyId,
PUBLIC_KEY to Base64.encodeBytes(record.keyPair.publicKey.serialize()),
PRIVATE_KEY to Base64.encodeBytes(record.keyPair.privateKey.serialize()),
SIGNATURE to Base64.encodeBytes(record.signature),
TIMESTAMP to record.timestamp
)
writableDatabase.replace(TABLE_NAME, null, contentValues)
}
fun delete(serviceId: ServiceId, keyId: Int) {
writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $KEY_ID = ?", SqlUtil.buildArgs(serviceId, keyId))
}
}
| gpl-3.0 | eebee5549773df6f0533a63f6e4717ac | 39.294118 | 150 | 0.69635 | 4.077381 | false | false | false | false |
GunoH/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/intentions/AddParenthesesToLambdaParameterIntention.kt | 5 | 2353 | // 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.plugins.groovy.annotator.intentions
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.createSmartPointer
import org.jetbrains.plugins.groovy.GroovyBundle.message
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression
class AddParenthesesToLambdaParameterIntention(parameterList: GrLambdaExpression) : IntentionAction {
private val myLambda: SmartPsiElementPointer<GrLambdaExpression> = parameterList.createSmartPointer()
override fun getText(): String = familyName
override fun getFamilyName(): String = message("add.parenthesis.to.lambda.parameter.list")
override fun startInWriteAction(): Boolean = true
override fun getFileModifierForPreview(target: PsiFile): FileModifier? {
val originalParameterList = PsiTreeUtil.findSameElementInCopy(myLambda.element, target) ?: return null
return AddParenthesesToLambdaParameterIntention(originalParameterList)
}
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
val parameterList = myLambda.element?.parameterList ?: return false
parameterList.lParen ?: return true
return false
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val lambda = myLambda.element ?: return
val closureText = closureText(lambda)
val closure = GroovyPsiElementFactory.getInstance(project).createLambdaFromText(closureText)
lambda.replaceWithExpression(closure, false)
}
private fun closureText(lambda: GrLambdaExpression): String {
val closureText = StringBuilder()
closureText.append("(")
val parameterList = lambda.parameterList
appendTextBetween(closureText, parameterList.text, parameterList.lParen, parameterList.rParen)
closureText.append(")")
appendTextBetween(closureText, lambda.text, parameterList, null)
return closureText.toString()
}
}
| apache-2.0 | 622fe9a0592a76bd79b1aeee7644097a | 42.574074 | 120 | 0.800255 | 4.964135 | false | false | false | false |
siosio/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/IdeaPluginDescriptorImpl.kt | 1 | 19381 | // 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.ide.plugins
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.core.CoreBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.platform.util.plugins.DataLoader
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.PropertyKey
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.time.ZoneOffset
import java.util.*
private val LOG: Logger
get() = PluginManagerCore.getLogger()
@ApiStatus.Internal
class IdeaPluginDescriptorImpl(raw: RawPluginDescriptor,
val path: Path,
private val isBundled: Boolean,
id: PluginId?) : IdeaPluginDescriptor {
val id: PluginId = id ?: PluginId.getId(raw.id ?: raw.name ?: throw RuntimeException("Neither id nor name are specified"))
private val name = raw.name ?: id?.idString ?: raw.id
@Suppress("EnumEntryName")
enum class OS {
mac, linux, windows, unix, freebsd
}
// only for sub descriptors
@JvmField internal var descriptorPath: String? = null
@Volatile private var description: String? = null
private val productCode = raw.productCode
private var releaseDate: Date? = raw.releaseDate?.let { Date.from(it.atStartOfDay(ZoneOffset.UTC).toInstant()) }
private val releaseVersion = raw.releaseVersion
private val isLicenseOptional = raw.isLicenseOptional
private var resourceBundleBaseName: String? = null
private val changeNotes = raw.changeNotes
private var version: String? = raw.version
private var vendor = raw.vendor
private val vendorEmail = raw.vendorEmail
private val vendorUrl = raw.vendorUrl
private var category: String? = raw.category
@JvmField internal val url = raw.url
@JvmField val pluginDependencies: List<PluginDependency>
@JvmField val incompatibilities: List<PluginId> = raw.incompatibilities ?: Collections.emptyList()
init {
// https://youtrack.jetbrains.com/issue/IDEA-206274
val list = raw.depends
if (list != null) {
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (!item.isOptional) {
for (a in list) {
if (a.isOptional && a.pluginId == item.pluginId) {
a.isOptional = false
iterator.remove()
break
}
}
}
}
}
pluginDependencies = list ?: Collections.emptyList()
}
@Transient @JvmField var jarFiles: List<Path>? = null
@JvmField var classLoader: ClassLoader? = null
@JvmField val actions: List<RawPluginDescriptor.ActionDescriptor>? = raw.actions
// extension point name -> list of extension descriptors
val epNameToExtensions: Map<String, MutableList<ExtensionDescriptor>>? = raw.epNameToExtensions
@JvmField val appContainerDescriptor = raw.appContainerDescriptor
@JvmField val projectContainerDescriptor = raw.projectContainerDescriptor
@JvmField val moduleContainerDescriptor = raw.moduleContainerDescriptor
@JvmField val content = raw.content
@JvmField val dependencies = raw.dependencies
@JvmField val modules: List<PluginId> = raw.modules ?: Collections.emptyList()
private val descriptionChildText = raw.description
@JvmField val isUseIdeaClassLoader = raw.isUseIdeaClassLoader
var isUseCoreClassLoader = false
private set
@JvmField val isBundledUpdateAllowed = raw.isBundledUpdateAllowed
@JvmField internal val implementationDetail = raw.implementationDetail
@JvmField internal val isRestartRequired = raw.isRestartRequired
@JvmField val packagePrefix = raw.`package`
private val sinceBuild = raw.sinceBuild
private val untilBuild = raw.untilBuild
private var isEnabled = true
var isDeleted = false
@JvmField internal var isIncomplete = false
override fun getDescriptorPath() = descriptorPath
override fun getDependencies(): List<IdeaPluginDependency> {
return if (pluginDependencies.isEmpty()) Collections.emptyList() else Collections.unmodifiableList(pluginDependencies)
}
override fun getPluginPath() = path
private fun createSub(raw: RawPluginDescriptor,
descriptorPath: String,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
dataLoader: DataLoader): IdeaPluginDescriptorImpl {
raw.name = name
@Suppress("TestOnlyProblems")
val result = IdeaPluginDescriptorImpl(raw, path = path, isBundled = isBundled, id = id)
result.descriptorPath = descriptorPath
result.vendor = vendor
result.version = version
result.resourceBundleBaseName = resourceBundleBaseName
result.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = true, dataLoader = dataLoader)
return result
}
fun readExternal(raw: RawPluginDescriptor,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
isSub: Boolean,
dataLoader: DataLoader) {
// include module file descriptor if not specified as `depends` (old way - xi:include)
// must be first because merged into raw descriptor
if (!isSub) {
for (module in content.modules) {
val subDescriptorFile = module.configFile ?: "${module.name}.xml"
val subDescriptor = createSub(raw = pathResolver.resolveModuleFile(readContext = context,
dataLoader = dataLoader,
path = subDescriptorFile,
readInto = null),
descriptorPath = subDescriptorFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader)
module.descriptor = subDescriptor
}
}
if (raw.resourceBundleBaseName != null) {
if (id == PluginManagerCore.CORE_ID && !isSub) {
LOG.warn("<resource-bundle>${raw.resourceBundleBaseName}</resource-bundle> tag is found in an xml descriptor" +
" included into the platform part of the IDE but the platform part uses predefined bundles " +
"(e.g. ActionsBundle for actions) anyway; this tag must be replaced by a corresponding attribute in some inner tags " +
"(e.g. by 'resource-bundle' attribute in 'actions' tag)")
}
if (resourceBundleBaseName != null && resourceBundleBaseName != raw.resourceBundleBaseName) {
LOG.warn("Resource bundle redefinition for plugin $id. " +
"Old value: $resourceBundleBaseName, new value: ${raw.resourceBundleBaseName}")
}
resourceBundleBaseName = raw.resourceBundleBaseName
}
if (version == null) {
version = context.defaultVersion
}
if (!isSub) {
if (context.isPluginDisabled(id)) {
markAsIncomplete(context, disabledDependency = null, shortMessage = null)
}
else {
for (pluginDependency in dependencies.plugins) {
if (context.isPluginDisabled(pluginDependency.id)) {
markAsIncomplete(context, pluginDependency.id, shortMessage = "plugin.loading.error.short.depends.on.disabled.plugin")
}
else if (context.result.isBroken(pluginDependency.id)) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = pluginDependency.id)
}
}
}
}
processOldDependencies(descriptor = this,
context = context,
pathResolver = pathResolver,
dependencies = pluginDependencies,
dataLoader = dataLoader)
checkCompatibility(context)
}
private fun processOldDependencies(descriptor: IdeaPluginDescriptorImpl,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
dependencies: List<PluginDependency>,
dataLoader: DataLoader) {
var visitedFiles: MutableList<String>? = null
for (dependency in dependencies) {
// context.isPluginIncomplete must be not checked here as another version of plugin maybe supplied later from another source
if (context.isPluginDisabled(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context, dependency.pluginId, "plugin.loading.error.short.depends.on.disabled.plugin")
}
}
else if (context.result.isBroken(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = dependency.pluginId)
}
}
// because of https://youtrack.jetbrains.com/issue/IDEA-206274, configFile maybe not only for optional dependencies
val configFile = dependency.configFile ?: continue
if (pathResolver.isFlat && context.checkOptionalConfigShortName(configFile, descriptor)) {
continue
}
var resolveError: Exception? = null
val raw: RawPluginDescriptor? = try {
pathResolver.resolvePath(readContext = context, dataLoader = dataLoader, relativePath = configFile, readInto = null)
}
catch (e: IOException) {
resolveError = e
null
}
if (raw == null) {
val message = "Plugin $descriptor misses optional descriptor $configFile"
if (context.isMissingSubDescriptorIgnored) {
LOG.info(message)
if (resolveError != null) {
LOG.debug(resolveError)
}
}
else {
throw RuntimeException(message, resolveError)
}
continue
}
if (visitedFiles == null) {
visitedFiles = context.visitedFiles
}
checkCycle(descriptor, configFile, visitedFiles)
visitedFiles.add(configFile)
val subDescriptor = descriptor.createSub(raw = raw,
descriptorPath = configFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader)
dependency.subDescriptor = subDescriptor
visitedFiles.clear()
}
}
private fun checkCompatibility(context: DescriptorListLoadingContext) {
if (isBundled || (sinceBuild == null && untilBuild == null)) {
return
}
val error = PluginManagerCore.checkBuildNumberCompatibility(this, context.result.productBuildNumber.get()) ?: return
// error will be added by reportIncompatiblePlugin
markAsIncomplete(context = context, disabledDependency = null, shortMessage = null)
context.result.reportIncompatiblePlugin(this, error)
}
private fun markAsIncomplete(context: DescriptorListLoadingContext,
disabledDependency: PluginId?,
@PropertyKey(resourceBundle = CoreBundle.BUNDLE) shortMessage: String?,
pluginId: PluginId? = disabledDependency) {
if (isIncomplete) {
return
}
isIncomplete = true
isEnabled = false
val pluginError = if (shortMessage == null) {
null
}
else {
PluginLoadingError(plugin = this,
detailedMessageSupplier = null,
shortMessageSupplier = {
CoreBundle.message(shortMessage, pluginId!!)
},
isNotifyUser = false,
disabledDependency = disabledDependency)
}
context.result.addIncompletePlugin(this, pluginError)
}
fun collectExtensionPoints() {
}
@ApiStatus.Internal
fun registerExtensions(nameToPoint: Map<String, ExtensionPointImpl<*>>,
containerDescriptor: ContainerDescriptor,
listenerCallbacks: List<Runnable>?) {
containerDescriptor.extensions?.let {
if (!it.isEmpty()) {
@Suppress("JavaMapForEach")
it.forEach { name, list ->
nameToPoint.get(name)?.registerExtensions(list, this, listenerCallbacks)
}
}
return
}
val unsortedMap = epNameToExtensions ?: return
// app container: in most cases will be only app-level extensions - to reduce map copying, assume that all extensions are app-level and then filter out
// project container: rest of extensions wil be mostly project level
// module container: just use rest, area will not register unrelated extension anyway as no registered point
if (containerDescriptor == appContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
projectContainerDescriptor.extensions = Collections.emptyMap()
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else if (containerDescriptor == projectContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
containerDescriptor.extensions = unsortedMap
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
else if (registeredCount == (unsortedMap.size - appContainerDescriptor.distinctExtensionPointCount)) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
if (registeredCount == 0) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
}
private fun doRegisterExtensions(unsortedMap: Map<String, MutableList<ExtensionDescriptor>>,
nameToPoint: Map<String, ExtensionPointImpl<*>>,
listenerCallbacks: List<Runnable>?): Int {
var registeredCount = 0
for (entry in unsortedMap) {
val point = nameToPoint.get(entry.key) ?: continue
point.registerExtensions(entry.value, this, listenerCallbacks)
registeredCount++
}
return registeredCount
}
override fun getDescription(): String? {
@Suppress("HardCodedStringLiteral")
var result = description
if (result != null) {
return result
}
val bundle: ResourceBundle? = resourceBundleBaseName?.let { resourceBundleBaseName ->
try {
DynamicBundle.INSTANCE.getResourceBundle(resourceBundleBaseName, pluginClassLoader)
}
catch (e: MissingResourceException) {
LOG.info("Cannot find plugin $id resource-bundle: $resourceBundleBaseName")
null
}
}
if (bundle == null) {
result = descriptionChildText
}
else {
result = AbstractBundle.messageOrDefault(bundle, "plugin.$id.description", descriptionChildText ?: "")
}
description = result
return result
}
override fun getChangeNotes() = changeNotes
override fun getName(): String = name!!
override fun getProductCode() = productCode
override fun getReleaseDate() = releaseDate
override fun getReleaseVersion() = releaseVersion
override fun isLicenseOptional() = isLicenseOptional
override fun getOptionalDependentPluginIds(): Array<PluginId> {
val pluginDependencies = pluginDependencies
if (pluginDependencies.isEmpty()) {
return PluginId.EMPTY_ARRAY
}
else {
return pluginDependencies.asSequence().filter { it.isOptional }.map { it.pluginId }.toList().toTypedArray()
}
}
override fun getVendor() = vendor
override fun getVersion() = version
override fun getResourceBundleBaseName() = resourceBundleBaseName
override fun getCategory() = category
/*
This setter was explicitly defined to be able to set a category for a
descriptor outside its loading from the xml file.
Problem was that most commonly plugin authors do not publish the plugin's
category in its .xml file so to be consistent in plugins representation
(e.g. in the Plugins form) we have to set this value outside.
*/
fun setCategory(category: String?) {
this.category = category
}
val unsortedEpNameToExtensionElements: Map<String, List<ExtensionDescriptor>>
get() {
return Collections.unmodifiableMap(epNameToExtensions ?: return Collections.emptyMap())
}
override fun getVendorEmail() = vendorEmail
override fun getVendorUrl() = vendorUrl
override fun getUrl() = url
override fun getPluginId() = id
override fun getPluginClassLoader(): ClassLoader = classLoader ?: javaClass.classLoader
fun setUseCoreClassLoader() {
isUseCoreClassLoader = true
}
override fun isEnabled() = isEnabled
override fun setEnabled(enabled: Boolean) {
isEnabled = enabled
}
override fun getSinceBuild() = sinceBuild
override fun getUntilBuild() = untilBuild
override fun isBundled() = isBundled
override fun allowBundledUpdate() = isBundledUpdateAllowed
override fun isImplementationDetail() = implementationDetail
override fun isRequireRestart() = isRestartRequired
override fun equals(other: Any?) = this === other || id == if (other is IdeaPluginDescriptorImpl) other.id else null
override fun hashCode() = id.hashCode()
override fun toString(): String {
return "PluginDescriptor(name=$name, id=$id, descriptorPath=${descriptorPath ?: "plugin.xml"}, " +
"path=${pluginPathToUserString(path)}, version=$version, package=$packagePrefix), isBundled=$isBundled"
}
}
// don't expose user home in error messages
internal fun pluginPathToUserString(file: Path): String {
return file.toString().replace("${System.getProperty("user.home")}${File.separatorChar}", "~${File.separatorChar}")
}
private fun checkCycle(descriptor: IdeaPluginDescriptorImpl, configFile: String, visitedFiles: List<String>) {
var i = 0
val n = visitedFiles.size
while (i < n) {
if (configFile == visitedFiles[i]) {
val cycle = visitedFiles.subList(i, visitedFiles.size)
throw RuntimeException("Plugin $descriptor optional descriptors form a cycle: ${java.lang.String.join(", ", cycle)}")
}
i++
}
} | apache-2.0 | c2d4c852121fd38901a63cd2c3434fc6 | 37.228797 | 158 | 0.658325 | 5.321527 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/compose-5.kt | 1 | 17460 | package alraune
import pieces100.*
import vgrechka.*
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import alraune.Al.*
import alraune.Gender.*
import alraune.entity.*
import com.fasterxml.jackson.annotation.JsonIgnore
import java.sql.Timestamp
import kotlin.reflect.*
fun ooInsideIgnoreWhenCheckingForStaleness_2(block: () -> Unit) {
oo(rawHtml("<!--${BTFConst.begin_ignoreWhenCheckingForStaleness_2}-->"))
block()
oo(rawHtml("<!--${BTFConst.end_ignoreWhenCheckingForStaleness_2}-->"))
}
class StyleSheet {
val classNamePrefix = AlGlobal.nextPuid()
var classNameSuffix = 1
val packs = mutableListOf<AlCSS.Pack>()
inner class DeClass(val pack: AlCSS.Pack) {
constructor(style: String) : this(AlCSS.Pack(style))
operator fun provideDelegate(thisRef: Any?, prop: KProperty<*>): ReadOnlyProperty<Any?, String> {
val value = addClass(pack, nameSuffix = prop.name)
return object : ReadOnlyProperty<Any?, String> {
override fun getValue(thisRef: Any?, property: KProperty<*>) = value
}
}
}
fun addClass(pack: AlCSS.Pack, nameSuffix: String? = null): String {
val className = "$classNamePrefix--${nameSuffix ?: classNameSuffix++}"
pack.autoClassName = className
packs += pack
return className
}
fun compose(): Renderable {
val shit = stringBuild {s->
packs.forEach {it.renderInto(s)}
}
return rawHtml("<style>$shit</style>")
}
}
fun drooOrderShit(order: AlUAOrder) {
oo(Row().with {
oo(composeCreatedAtCol(3, order.createdAt))
oo(composeOrderStateColumn(order))
oo(composeTimestampCol(3, t("TOTE", "Срок"), order.dataPile.deadline))
})
oo(Row().with {
oo(col(3, AlText.Order.contactName, order.contactName))
oo(col(3, AlText.Order.email, order.email))
oo(col(3, AlText.Order.phone, order.phone))
})
oo(Row().with {
oo(composeOrderDocumentTypeColumn(order))
oo(composeOrderDocumentCategoryColumn(order))
})
oo(composeOrderNumsRow(order))
oo(DetailsRow().content(order.documentDetails))
AlRender2.drawAdminNotes_ifAny_andPretendingAdmin(order.adminNotes)
}
class ooItemTitle(title: String,
tinySubtitle: String,
addIcons: (AddIcons) -> Unit = {},
buildDropdown: ((MenuBuilder) -> Unit)? = null,
val iconWithStyle: FAIconWithStyle? = null,
val icon: FA.Icon? = null,
val amendTitleBarDiv: (AlTag) -> Unit = {},
val afterTinySubtitle: () -> Unit = {},
val belowTitle: Renderable? = null) {
val c = AlCSS.carla
val rightIconsContainer = div()
inner class AddIcons {
fun item(icon: FA.Icon, hint: String): AlTag {
val tag = tagi().className(icon.className + " " + c.titleRightIcon).title(hint)
oo(tag)
return tag
}
}
init {
checkAtMostOneNotNull(this::iconWithStyle, this::icon)
val _iconAndStyle = when {
iconWithStyle != null -> iconWithStyle
icon != null -> FAIconWithStyle(icon)
else -> FAIconWithStyle(FA.file)
}
oo(div().className(c.titleBar).also(amendTitleBarDiv).also{_iconAndStyle.amendTitleBar(it)}.with {
oo(div().with {
// oo(tagi().classes(_iconAndStyle.icon.className, c.titleIcon).style(_iconAndStyle.style))
val titleIcon = FA.file()
if (titleIcon != null)
oo(span().classes(c.titleIcon).add(titleIcon))
oo(span().classes(c.title).add(title))
oo(span().classes(c.tinySubtitle).text(tinySubtitle))
afterTinySubtitle()
oo(rightIconsContainer.classes(c.titleRightIcons).with {
addIcons(AddIcons())
if (buildDropdown != null)
ooHamburgerDropdown(buildDropdown).appendClassName(c.titleRightIcon)
})
})
oo(belowTitle)
})
}
}
fun ooHamburgerDropdown(buildDropdown: (MenuBuilder) -> Unit): AlTag {
val tagi = tagi().classes(FA.bars.className)
ooDropdown(tagi, block = buildDropdown)
return tagi
}
fun ooButtonDropdown(title: String, buildDropdown: (MenuBuilder) -> Unit): AlTag {
val trigger = button().classes("btn", "btn-default").with {
oo(span(title))
oo(span().classes("caret").marginLeft05Em())
}
ooDropdown(trigger, block = buildDropdown)
return trigger
}
fun AlTag.transparent_noPadding_noBorder() = this.also {
it.appendStyle("padding: 0; background: transparent; border: none;")
}
fun shitOrderById(q: AlQueryBuilder, ordering: Ordering) {
q.text("order by id " + when (ordering) {
Ordering.NewerFirst -> "desc"
Ordering.OlderFirst -> "asc"
})
}
abstract class OoUsualPaginatedShit<Item : Any>(
val itemClass: KClass<Item>,
val table: String,
val pageSize: Int = AlConst.pageSize,
var ordering: Ordering = GetParams().ordering.get()!!,
// val url: AmendableUrlProvider,
val notDeleted: Boolean = true,
val pizda: Pizda = Pizda())
: DancerBase<Renderable>() {
class Pizda(
val composeBeforeItems: () -> Renderable? = {null},
val composeAfterItems: () -> Renderable? = {null})
open fun initShitGivenItems(items: List<Item>) {}
abstract fun composeItem(item: Item, index: Int): Renderable
abstract fun shitIntoWhere(q: AlQueryBuilder)
open fun shitOrderBy(q: AlQueryBuilder) {shitOrderById(q, ordering)}
override fun dance(): Renderable {
val crap = UsualPaginationPussy(itemClass, pageSize, table, notDeleted, ::shitIntoWhere, ::shitOrderBy)
return dance(object : ComposePaginatedShit<Item>(crap) {
init {pizda = [email protected]}
override fun initShitGivenItems(items: List<Item>) = [email protected](items)
override fun renderItem(item: Item, index: Int) = [email protected](item, index)
override fun makePageHref(pageFrom1: Int) = defaultPaginationPageHref(pageFrom1)
})
}
}
fun defaultPaginationPageHref(pageFrom1: Int): String {
return makeUrlBasedOnCurrent {
it.page.set(pageFrom1)
}
}
interface PaginationPussy<Item> {
fun count(): Long
fun selectItems(offset: Long): List<Item>
fun pageSize(): Int
}
class UsualPaginationPussy<Item : Any>(
val itemClass: KClass<Item>,
val pageSize: Int = AlConst.pageSize,
val table: String,
val notDeleted: Boolean = false,
val shitIntoWhere: (AlQueryBuilder) -> Unit,
val shitOrderBy: (AlQueryBuilder) -> Unit)
:PaginationPussy<Item> {
override fun pageSize() = pageSize
override fun selectItems(offset: Long): List<Item> {
return AlQueryBuilder()
.text("select * from $table")
.text("where true")
.text(notDeleted.thenElseEmpty {"and not deleted"})
.accept {shitIntoWhere(it)}
.accept {shitOrderBy(it)}
.text("limit").param(pageSize)
.text("offset").param(offset)
.selectSimple(itemClass.java)
}
override fun count() = AlQueryBuilder()
.text("select count(*) from $table")
.text("where true")
.text(notDeleted.thenElseEmpty {"and not deleted"})
.accept {shitIntoWhere(it)}
.selectOneLong()
}
class PaginationBoobs<Item>(@JsonIgnore val pussy: PaginationPussy<Item>) {
var items by notNullOnce<List<Item>>()
var pages by notNullOnce<Int>()
var page by notNull<Int>()
var count by notNullOnce<Long>()
fun fart(_page: Int? = null) {
count = pussy.count()
pages = Math.toIntExact(
count / pussy.pageSize()
+ (if ((count % pussy.pageSize()) > 0) 1 else 0))
page = _page ?: GetParams().page.get()!!
if (page < 1)
page = 1
else if (page > pages)
page = if (pages > 0) pages else 1
val offset = (page - 1) * pussy.pageSize()
items = pussy.selectItems(offset.toLong())
}
}
class ShitIntoPageHeader(val block: () -> Unit)
class DrooSelect(val jsOnChange: (jsValue: String) -> String, val style: String? = null) {
fun data(items: List<TitledValue_killme>, currentValue: String) = object : DancerBase<Unit>() {
override fun dance() {
val selectDomid by nextJsIdentDel()
val jsValue = "${jsByIdSingle(selectDomid)}.val()"
oo(select().id(selectDomid).style(style).className("form-control").onChange(jsOnChange(jsValue)).with {
for (item in items) {
oo(option()
.selected(currentValue == item.value)
.value(item.value)
.text(item.title))
}
})
}
}
fun <E> data(items: Array<E>, currentValue: E)
where E : Enum<E>, E : JTitled =
data(items = items.map {TitledValue_killme(it.name, it.title)},
currentValue = currentValue.name)
}
fun spitPageWithUsualShit(w: Params_spitPageWithUsualShit) {
spitUsualPage {div().className("container").with {
addPageHeaderWithControls(w.getHeaderTitle(), w::buildTopRightControls)
w.drawBody()
}}
}
interface Params_spitPageWithUsualShit {
fun drawBody()
fun getHeaderTitle(): String
fun buildTopRightControls(trb: TopRightControls)
}
fun spitTitledPage(title: String, build: () -> Unit) {
rctx0.htmlHeadTitle = title
spitUsualPage {div().className("container").with {
oo(pageHeader(title))
build()
}}
}
class Col(val size: Int) : RenderableRelatingItsCreationStackToRendering() {
private var title: String? = null; fun title(x: String): Col {this.title = x; return this;}
private var colClassName = ""; fun colClassName(x: String): Col {this.colClassName = x; return this;}
private var labelStyle = ""; fun labelStyle(x: String): Col {this.labelStyle = x; return this;}
private var contentClassName = ""; fun contentClassName(x: String): Col {this.contentClassName = x; return this;}
private var contentStyle = ""; fun contentStyle(x: String): Col {this.contentStyle = x; return this;}
private var with: (() -> Unit)? = null; fun with(x: () -> Unit): Col {this.with = x; return this;}
fun amend(f: ((Col) -> Unit)?): Col {
if (f != null) f(this)
return this
}
override fun compose(): Renderable {
return div().className("col-md-" + size).with {
if (title != null)
oo(label().style(labelStyle + "margin-bottom: 0;").text(title))
oo(div().className(contentClassName).style(contentStyle).with(with))
}
}
}
fun col(size: Int, content: Renderable): Col {
return Col(size).with {oo(content)}
}
fun col(size: Int, title: String, content: String): Col {
return Col(size).title(title).with {oo(span(content))}
}
fun composeMinimalMainContainer(build: () -> Unit): Renderable {
rctx0.compositionPlace.belowRootContainer = div()
return div().with {
oo(div().id(BTFConst.Domid.mainContainer).className("container").with {
oo(div().style("margin-top: 1rem;"))
build()
})
oo(rctx0.compositionPlace.belowRootContainer)
}
}
// 2bd38503-ee2b-41e7-b5a6-97cbdde8dfd8
fun composeWaitingBanner(text: String): AlTag {
val waitingAdminApprovalBannerStyle = """
background-color: ${Color.Gray100};
border-left: 3px solid ${Color.Gray500};
height: 44.4px;
margin-bottom: 1rem;
padding-left: 1rem;
padding-right: 0;
padding-top: 0.5rem;
padding-bottom: 0.5rem;
display: flex;
align-items: center;
"""
return div().style(waitingAdminApprovalBannerStyle).with {
oo(tagi().className(FA.hourglassHalf.className).style("margin-right: 0.75rem;"))
oo(div().style("flex-grow: 1;").text(text))
}
}
fun composeCreatedAtCol(size: Int, value: Timestamp, gender: Gender = Masculine) =
composeTimestampCol(size, t(
"Created",
when (gender) {
Masculine -> "Создан"
Feminine -> "Создана"
Neuter -> "Создано"
}), value)
fun composeTimestampCol(size: Int, title: String, value: Timestamp) =
col(size, title, TimePile.kievTimeString(value))
fun composeOrderDocumentTypeColumn(order: AlUAOrder) =
col(3, AlText.documentType, order.documentType.title)
fun composeOrderDocumentTypeColumn_a2(order: Order) =
col(3, AlText.documentType, order.data.documentType.title)
fun composeOrderDocumentCategoryColumn(order: AlUAOrder) =
col(6, AlText.documentCategory, longDocumentCategoryTitle(order.documentCategory))
fun composeOrderDocumentCategoryColumn_a2(order: Order) =
col(6, AlText.documentCategory, longDocumentCategoryTitle(order.data.documentCategory))
fun longDocumentCategoryTitle(categoryID: String): String {
var cat = AlUADocumentCategories.findByIDOrBitch(categoryID)
val steps = mutableListOf<String>()
while (!cat.id.equals(AlUADocumentCategories.root.id)) {
steps.add(cat.title)
cat = bang(cat.parent)
}
steps.reverse()
return steps.joinToString(AlText0.rightDoubleAngleQuotationSpaced)
}
fun composeOrderStateColumn(order: AlUAOrder) =
col(3, AlText.status, order.state.title)
fun composeOrderStateColumn_a2(order: Order) =
col(3, AlText.status, order.state.title)
fun composeOrderNumSourcesColumn(order: AlUAOrder) =
col(3, AlText.Order.numSources, "" + order.numSources)
fun composeOrderNumSourcesColumn_a2(order: Order) =
col(3, AlText.Order.numSources, "" + order.data.numSources)
fun composeOrderNumPagesColumn(order: AlUAOrder) =
col(3, AlText.Order.numPages, "" + order.numPages)
fun composeOrderNumPagesColumn_a2(order: Order) =
col(3, AlText.Order.numPages, "" + order.data.numPages)
class Row : RenderableRelatingItsCreationStackToRendering() {
private var marginBottom = "0.5em"; fun marginBottom(x: String): Row {this.marginBottom = x; return this;}
private var additionalClassNames = ""; fun appendClassName(x: String): Row {additionalClassNames += " " + x; return this;}
private var with: (() -> Unit)? = null; fun with(x: () -> Unit): Row {this.with = x; return this;}
override fun compose(): Renderable {
var style = ""
if (marginBottom.isNotBlank())
style += "margin-bottom: $marginBottom;"
return div().className("row $additionalClassNames").style(style).with(with)
}
}
fun composeOrderNumsRow(order: AlUAOrder) = Row().with {
oo(composeOrderNumPagesColumn(order))
oo(composeOrderNumSourcesColumn(order))
}
fun composeOrderNumsRow_a2(order: Order) = Row().with {
oo(composeOrderNumPagesColumn_a2(order))
oo(composeOrderNumSourcesColumn_a2(order))
}
fun AlTag.render(block: () -> Unit): String = this.with(block).render()
fun AlTag.displayNone() = this.also {this.appendStyle("display: none;")}!!
fun composeOrderParams(order: Order) = div().with {
val data = order.data
oo(Row().with {
oo(composeCreatedAtCol(3, data.createdAt))
ooUpdatedAtColIfDiffersFromCreatedAt(order.data.updatedAt, data.createdAt)
oo(col(3, AlText.status, order.state.title))
oo(composeTimestampCol(3, t("TOTE", "Срок"), order.deadline))
})
// if (rctx.pretending == AlUserKind.Admin) {
// data.bidding?.let {bidding->
// oo(Row().with {
// oo(col(3, t("TOTE", "Нижняя граница ставки"), displayMoney(bidding.minWriterMoney)))
// oo(col(3, t("TOTE", "Верхняя граница ставки"), displayMoney(bidding.maxWriterMoney)))
// oo(composeTimestampCol(3, t("TOTE", "Напомнить закрыть торги"), bidding.closeBiddingAdviceNotificationTime))
// })
// }
// }
if (Context1.get().projectStuff.composeOrderParams_showCustomerInfo) {
oo(Row().with {
oo(col(3, AlText.Order.contactName, data.contactName))
oo(col(3, AlText.Order.email, data.email))
oo(col(3, AlText.Order.phone, data.phone))
})
}
oo(Row().with {
oo(col(3, AlText.documentType, data.documentType.title))
oo(col(6, AlText.documentCategory, longDocumentCategoryTitle(data.documentCategory)))
})
oo(Row().with {
oo(col(3, AlText.Order.numPages, "" + data.numPages))
oo(col(3, AlText.Order.numSources, "" + data.numSources))
})
oo(DetailsRow().content(data.documentDetails))
AlRender2.drawAdminNotes_ifAny_andPretendingAdmin(data.adminNotes)
}
fun ooUpdatedAtColIfDiffersFromCreatedAt(updatedAt: Timestamp, createdAt: Timestamp, gender: Gender = Masculine) {
if (updatedAt != createdAt)
oo(composeTimestampCol(3, t(
"Updated",
when (gender) {
Masculine -> "Обновлен"
Feminine -> "Обновлена"
Neuter -> "Обновлено"
}), updatedAt))
}
| apache-2.0 | 28f5561ebd7ecd6e2267ba8c9d242af7 | 32.04 | 126 | 0.6315 | 3.791475 | false | false | false | false |
GunoH/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/NotRoamableUiSettings.kt | 3 | 3176 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.ui
import com.intellij.openapi.components.*
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.FontUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.SerializationFilter
import com.intellij.util.xmlb.annotations.Property
import java.awt.Font
@State(name = "NotRoamableUiSettings", storages = [(Storage(StoragePathMacros.NON_ROAMABLE_FILE))])
class NotRoamableUiSettings : PersistentStateComponent<NotRoamableUiOptions> {
private var state = NotRoamableUiOptions()
override fun getState() = state
override fun loadState(state: NotRoamableUiOptions) {
this.state = state
state.fontSize = UISettings.restoreFontSize(state.fontSize, state.fontScale)
state.fontScale = UISettings.defFontScale
fixFontSettings()
}
internal fun fixFontSettings() {
val state = state
// 1. Sometimes system font cannot display standard ASCII symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
var fontIsValid = FontUtil.isValidFont(Font(state.fontFace, Font.PLAIN, 1).deriveFont(state.fontSize))
if (!fontIsValid) {
for (preferredFont in arrayOf("dialog", "Arial", "Tahoma")) {
if (FontUtil.isValidFont(Font(preferredFont, Font.PLAIN, 1).deriveFont(state.fontSize))) {
state.fontFace = preferredFont
fontIsValid = true
break
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if (!fontIsValid) {
val fontNames = UIUtil.getValidFontNames(false)
if (fontNames.isNotEmpty()) {
state.fontFace = fontNames[0]
}
}
}
}
}
class NotRoamableUiOptions : BaseState() {
var ideAAType by enum(
if (AntialiasingType.canUseSubpixelAAForIDE())
AntialiasingType.SUBPIXEL else AntialiasingType.GREYSCALE)
var editorAAType by enum(
if (AntialiasingType.canUseSubpixelAAForEditor())
AntialiasingType.SUBPIXEL else AntialiasingType.GREYSCALE)
@get:Property(filter = FontFilter::class)
var fontFace by string()
@get:Property(filter = FontFilter::class)
var fontSize by property(0f)
@get:Property(filter = FontFilter::class)
var fontScale by property(0f)
init {
val fontData = JBUIScale.getSystemFontData(null)
fontFace = fontData.first
fontSize = fontData.second.toFloat()
fontScale = UISettings.defFontScale
}
}
private class FontFilter : SerializationFilter {
override fun accepts(accessor: Accessor, bean: Any): Boolean {
val settings = bean as NotRoamableUiOptions
val fontData = JBUIScale.getSystemFontData(null)
if ("fontFace" == accessor.name) {
return fontData.first != settings.fontFace
}
// fontSize/fontScale should either be stored in pair or not stored at all
// otherwise the fontSize restore logic gets broken (see loadState)
return !(fontData.second.toFloat() == settings.fontSize && 1f == settings.fontScale)
}
} | apache-2.0 | 85dd23bc4cf236db1599c85c4c218c27 | 33.912088 | 120 | 0.722607 | 4.350685 | false | false | false | false |
adriangl/Dev-QuickSettings | app/src/main/kotlin/com/adriangl/devquicktiles/tiles/usbdebug/UsbDebuggingTileService.kt | 1 | 1855 | /*
* Copyright (C) 2017 Adrián García
*
* 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.adriangl.devquicktiles.tiles.usbdebug
import android.graphics.drawable.Icon
import android.provider.Settings
import com.adriangl.devquicktiles.R
import com.adriangl.devquicktiles.tiles.DevelopmentTileService
import com.adriangl.devquicktiles.utils.SettingsUtils
class UsbDebuggingTileService : DevelopmentTileService<Int>() {
companion object {
val SETTING = Settings.Global.ADB_ENABLED
}
override fun isActive(value: Int): Boolean {
return value != 0
}
override fun queryValue(): Int {
var value = SettingsUtils.getIntFromGlobalSettings(contentResolver, SETTING)
if (value > 1) value = 1
return value
}
override fun saveValue(value: Int) : Boolean {
return SettingsUtils.setIntToGlobalSettings(contentResolver, SETTING, value)
}
override fun getValueList(): List<Int> {
return listOf(0, 1)
}
override fun getIcon(value: Int): Icon? {
return Icon.createWithResource(applicationContext,
if (value != 0) R.drawable.ic_qs_usb_debugging_enabled else R.drawable.ic_qs_usb_debugging_disabled)
}
override fun getLabel(value: Int): CharSequence? {
return getString(R.string.qs_usb_debugging)
}
}
| apache-2.0 | f88c992441c4029e2904596e751aa4ee | 32.089286 | 116 | 0.713977 | 4.164045 | false | false | false | false |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/manager/appanalysis/InstalledAppsManager.kt | 1 | 1476 | package sk.styk.martin.apkanalyzer.manager.appanalysis
import android.content.pm.PackageManager
import sk.styk.martin.apkanalyzer.model.list.AppListData
import sk.styk.martin.apkanalyzer.util.AppBasicInfoComparator
import java.util.*
import javax.inject.Inject
class InstalledAppsManager @Inject constructor(val packageManager: PackageManager) {
fun getAll(): List<AppListData> {
val applications = packageManager.getInstalledPackages(0)
val packages = ArrayList<AppListData>(applications.size)
applications.forEach {
if (it.applicationInfo != null)
packages.add(AppListData(it, packageManager))
}
return packages.sortedWith(AppBasicInfoComparator.INSTANCE)
}
fun getForPackageNames(packageNames: List<String>): List<AppListData> {
val packages = ArrayList<AppListData>(packageNames.size)
packageNames.forEach {
try {
val packageInfo = packageManager.getPackageInfo(it, 0)
if (packageInfo?.applicationInfo != null)
packages.add(AppListData(packageInfo, packageManager))
} catch (e: PackageManager.NameNotFoundException) {
// continue
}
}
return packages.sortedWith(AppBasicInfoComparator.INSTANCE)
}
fun preload(appListData: List<AppListData>) {
appListData.forEach {
it.icon
it.packageName
}
}
}
| gpl-3.0 | 2987aebcbeac6b5b0e4d65bb197154c5 | 30.404255 | 84 | 0.663957 | 4.903654 | false | false | false | false |
suitougreentea/f-c-p-l-c | src/io/github/suitougreentea/util/AngelCodeFontXML.kt | 1 | 5391 | package io.github.suitougreentea.util
import java.io.File
import org.newdawn.slick.Image
import org.newdawn.slick.Color
import java.util.HashMap
import kotlinx.dom.get
import kotlinx.dom.parseXml
class AngelCodeFontXML (fntPath: String){
val fntFile = File(fntPath)
val fnt = parseXml(fntFile)
val pages: Array<Image> = Array((fnt.get("common").get(0).getAttribute("pages").toInt()), { Image(0, 0) })
val chars: HashMap<Int, Glyph> = HashMap()
val lineHeight = fnt.get("common").get(0).getAttribute("lineHeight").toInt()
val base = fnt.get("common").get(0).getAttribute("base").toInt()
init {
for (e in fnt.get("pages").get(0).get("page")) {
val file = File(fntFile.getParent(), (e.getAttribute("file")))
pages[e.getAttribute("id").toInt()] = Image(file.getPath())
}
for (e in fnt.get("chars").get(0).get("char")) {
var id = e.getAttribute("id").toInt()
var x = e.getAttribute("x").toInt()
var y = e.getAttribute("y").toInt()
var width = e.getAttribute("width").toInt()
var height = e.getAttribute("height").toInt()
var xoffset = e.getAttribute("xoffset").toInt()
var yoffset = e.getAttribute("yoffset").toInt()
var xadvance = e.getAttribute("xadvance").toInt()
var page = pages[e.getAttribute("page").toInt()]
chars.put(id, Glyph(x, y, width, height, xoffset, yoffset, xadvance, page))
}
}
fun measureString(str: String): Int {
var cx = 0
for(c in str){
cx += measureChar(c)
}
return cx
}
fun measureChar(c: Char): Int {
val glyph = chars.get(c.toInt())
if(glyph != null){
return glyph.xadvance
} else return 0
}
fun drawChar(c: Char, x: Int, y: Int, color: Color = Color(1f, 1f, 1f)): Int {
val glyph = chars.get(c.toInt())
if(glyph != null){
glyph.page.draw(
(x + glyph.xoffset).toFloat(),
(y + glyph.yoffset + lineHeight - base).toFloat(),
(x + glyph.xoffset + glyph.width).toFloat(),
(y + glyph.yoffset + lineHeight - base + glyph.height).toFloat(),
glyph.x.toFloat(),
glyph.y.toFloat(),
(glyph.x + glyph.width).toFloat(),
(glyph.y + glyph.height).toFloat(),
color
)
return glyph.xadvance
} else {
return 0
}
}
fun drawStringEmbedded(str: String, x: Int, y: Int, color: Color = Color(1f, 1f, 1f)) {
var cx = 0
for(c in str){
cx += drawChar(c, x + cx, y, color)
}
}
fun drawString(str: String, x: Int, y: Int, align: TextAlign = TextAlign.LEFT, color: Color = Color(1f, 1f, 1f)) {
var cy = 0
for(s in str.split("\n")){
when(align) {
TextAlign.LEFT -> drawStringEmbedded(s, x, y + cy, color)
TextAlign.CENTER -> drawStringEmbedded(s, x - (measureString(s) / 2), y + cy, color)
TextAlign.RIGHT -> drawStringEmbedded(s, x - measureString(s), y + cy, color)
}
cy += lineHeight
}
}
fun measureStringFormatted(str: String): Int {
var cx = 0
var i = 0
while(i < str.length){
var c = str[i]
if(c == '@'){
when(str[i + 1]) {
'#' -> {
if(str[i + 8] == '#') {
i += 9
} else {
i += 11
}
}
'@' -> {
cx += measureChar('@')
i += 2
}
}
} else {
cx += measureChar(c)
i += 1
}
}
return cx
}
fun drawStringFormattedEmbedded(str: String, x: Int, y: Int, startColor: Color) : Color {
var cx = 0
var cc = startColor
var i = 0
while(i < str.length){
var c = str[i]
if(c == '@'){
when(str[i + 1]) {
'#' -> {
if(str[i + 8] == '#') {
cc = Color(
Integer.parseInt(str.substring(i + 2, i + 4), 16) / 255f,
Integer.parseInt(str.substring(i + 4, i + 6), 16) / 255f,
Integer.parseInt(str.substring(i + 6, i + 8), 16) / 255f)
i += 9
} else {
cc = Color(
Integer.parseInt(str.substring(i + 2, i + 4), 16) / 255f,
Integer.parseInt(str.substring(i + 4, i + 6), 16) / 255f,
Integer.parseInt(str.substring(i + 6, i + 8), 16) / 255f,
Integer.parseInt(str.substring(i + 8, i + 10), 16) / 255f)
i += 11
}
}
'@' -> {
cx += drawChar('@', x + cx, y, cc)
i += 2
}
}
} else {
cx += drawChar(c, x + cx, y, cc)
i += 1
}
}
return cc
}
fun drawStringFormatted(str: String, x: Int, y: Int, align: TextAlign = TextAlign.LEFT) {
var cy = 0
var lastColor = Color(1f, 1f, 1f)
for(s in str.split("\n")){
when(align) {
TextAlign.LEFT -> lastColor = drawStringFormattedEmbedded(s, x, y + cy, lastColor)
TextAlign.CENTER -> lastColor = drawStringFormattedEmbedded(s, x - (measureStringFormatted(s) / 2), y + cy, lastColor)
TextAlign.RIGHT -> lastColor = drawStringFormattedEmbedded(s, x - measureStringFormatted(s), y + cy, lastColor)
}
cy += lineHeight
}
}
}
class Glyph(val x: Int, val y: Int, val width: Int, val height: Int, val xoffset: Int, val yoffset: Int, val xadvance: Int, val page: Image){
}
enum class TextAlign {
LEFT,
CENTER,
RIGHT,
}
| mit | f00e23c794eea64caf7b4b3f995eeefe | 28.620879 | 141 | 0.533296 | 3.41635 | false | false | false | false |
paoloach/zdomus | ZTopology/app/src/main/java/it/achdjian/paolo/ztopology/activities/node/fragments/clusters/DeviceTemperatureClusterFragments.kt | 1 | 915 | package it.achdjian.paolo.ztopology.activities.node.fragments.clusters
import android.os.Bundle
import it.achdjian.paolo.ztopology.R
import it.achdjian.paolo.ztopology.activities.NodeActivity
import it.achdjian.paolo.ztopology.zigbee.Cluster
import it.achdjian.paolo.ztopology.zigbee.ZEndpoint
/**
* Created by Paolo Achdjian on 2/26/18.
*/
class DeviceTemperatureClusterFragments: ClusterFragment() {
override fun layoutResource() : Int = R.layout.device_temperature_cluster
override fun clusterId() = Cluster.DEVICE_TEMPERATURE_CONFIGURATION_CLUSTER
companion object {
fun newInstance(endpoint: ZEndpoint): DeviceTemperatureClusterFragments {
val fragment = DeviceTemperatureClusterFragments()
val args = Bundle()
args.putSerializable(NodeActivity.ENDPOINT, endpoint)
fragment.arguments = args
return fragment
}
}
} | gpl-2.0 | 4dda8376e116847e763108835cd81978 | 35.64 | 81 | 0.739891 | 4.485294 | false | false | false | false |
Adven27/Exam | exam-db/src/main/java/io/github/adven27/concordion/extensions/exam/db/commands/TableParsers.kt | 1 | 3411 | package io.github.adven27.concordion.extensions.exam.db.commands
import io.github.adven27.concordion.extensions.exam.core.commands.SuitableCommandParser
import io.github.adven27.concordion.extensions.exam.core.html.DbRowParser
import io.github.adven27.concordion.extensions.exam.core.html.Html
import io.github.adven27.concordion.extensions.exam.core.html.html
import io.github.adven27.concordion.extensions.exam.db.MarkedHasNoDefaultValue
import io.github.adven27.concordion.extensions.exam.db.TableData
import io.github.adven27.concordion.extensions.exam.db.builder.DataSetBuilder
import io.github.adven27.concordion.extensions.exam.db.builder.ExamTable
import org.concordion.api.CommandCall
import org.concordion.api.Element
import org.concordion.api.Evaluator
import org.dbunit.dataset.DefaultTable
import org.dbunit.dataset.IDataSet
import org.dbunit.dataset.ITable
interface TableParser : SuitableCommandParser<ITable>
class MdTableParser : TableParser {
override fun isSuitFor(element: Element): Boolean = element.localName != "div"
override fun parse(command: CommandCall, evaluator: Evaluator): ITable {
val builder = DataSetBuilder()
val tableName = command.expression
root(command).let { parseCols(it) to parseValues(it) }.let { (cols, rows) ->
rows.forEach { row -> builder.newRowTo(tableName).withFields(cols.zip(row).toMap()).add() }
return ExamTable(tableFrom(builder.build(), tableName), evaluator)
}
}
private fun root(command: CommandCall) = command.element.parentElement.parentElement
private fun tableFrom(dataSet: IDataSet, tableName: String) =
if (dataSet.tableNames.isEmpty()) DefaultTable(tableName) else dataSet.getTable(tableName)
private fun parseCols(it: Element) =
it.getFirstChildElement("thead").getFirstChildElement("tr").childElements.map { it.text.trim() }
private fun parseValues(it: Element) =
it.getFirstChildElement("tbody").childElements.map { tr -> tr.childElements.map { it.text.trim() } }
}
class HtmlTableParser(
private val remarks: MutableMap<String, Int> = mutableMapOf(),
private val colParser: ColParser = ColParser()
) : TableParser {
override fun isSuitFor(element: Element): Boolean = element.localName == "div"
override fun parse(command: CommandCall, evaluator: Evaluator): ITable = command.html().let {
TableData.filled(
it.takeAwayAttr("table", evaluator)!!,
DbRowParser(it, "row", null, null).parse(),
parseCols(it),
evaluator
)
}
private fun parseCols(el: Html): Map<String, Any?> {
val attr = el.takeAwayAttr("cols")
return if (attr == null) emptyMap()
else {
val remarkAndVal = colParser.parse(attr)
remarks += remarkAndVal.map { it.key to it.value.first }.filter { it.second > 0 }
remarkAndVal.mapValues { if (it.value.second == null) MarkedHasNoDefaultValue() else it.value.second }
}
}
}
class ColParser {
fun parse(attr: String): Map<String, Pair<Int, String?>> {
return attr.split(",")
.map {
val (r, n, v) = ("""(\**)([^=]+)=?(.*)""".toRegex()).matchEntire(it.trim())!!.destructured
mapOf(n to (r.length to (if (v.isBlank()) null else v)))
}
.reduce { acc, next -> acc + next }
}
}
| mit | cd6a8253acef6b63dff6c4281f69d10f | 42.177215 | 114 | 0.686895 | 3.952491 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/listener/PlayerJoinListener.kt | 1 | 2139 | /*
* Copyright 2018 Ross 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.unconsciousness.bukkit.listener
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import com.rpkit.unconsciousness.bukkit.RPKUnconsciousnessBukkit
import com.rpkit.unconsciousness.bukkit.unconsciousness.RPKUnconsciousnessProvider
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
class PlayerJoinListener(private val plugin: RPKUnconsciousnessBukkit): Listener {
@EventHandler
fun onPlayerJoin(event: PlayerJoinEvent) {
val bukkitPlayer = event.player
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val unconsciousnessProvider = plugin.core.serviceManager.getServiceProvider(RPKUnconsciousnessProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
if (!unconsciousnessProvider.isUnconscious(character)) {
event.player.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 0,0), true)
}
}
}
}
} | apache-2.0 | 18ef81904201da946262fd04f7f03931 | 42.673469 | 120 | 0.762038 | 4.639913 | false | false | false | false |
square/sqldelight | sqldelight-compiler/src/test/kotlin/com/squareup/sqldelight/core/queries/ExpressionTest.kt | 1 | 14866 | package com.squareup.sqldelight.core.queries
import com.alecstrong.sql.psi.core.DialectPreset
import com.google.common.truth.Truth.assertThat
import com.squareup.burst.BurstJUnit4
import com.squareup.kotlinpoet.DOUBLE
import com.squareup.kotlinpoet.INT
import com.squareup.kotlinpoet.LONG
import com.squareup.kotlinpoet.asClassName
import com.squareup.sqldelight.core.compiler.SelectQueryGenerator
import com.squareup.sqldelight.test.util.FixtureCompiler
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
@RunWith(BurstJUnit4::class)
class ExpressionTest {
@get:Rule val tempFolder = TemporaryFolder()
@Test fun `and has lower precedence than like`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| TestId INTEGER NOT NULL,
| TestText TEXT NOT NULL COLLATE NOCASE,
| SecondId INTEGER NOT NULL,
| PRIMARY KEY (TestId)
|);
|
|testQuery:
|SELECT *
|FROM test
|WHERE SecondId = ? AND TestText LIKE ? ESCAPE '\' COLLATE NOCASE;
""".trimMargin(),
tempFolder
)
val generator = SelectQueryGenerator(file.namedQueries.first())
assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo(
"""
|public override fun testQuery(SecondId: kotlin.Long, value: kotlin.String): com.squareup.sqldelight.Query<com.example.Test> = testQuery(SecondId, value) { TestId, TestText, SecondId_ ->
| com.example.Test(
| TestId,
| TestText,
| SecondId_
| )
|}
|""".trimMargin()
)
}
@Test fun `case expression has correct type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| id INTEGER PRIMARY KEY AUTOINCREMENT,
| some_text TEXT NOT NULL
|);
|
|someSelect:
|SELECT CASE id WHEN 0 THEN some_text ELSE some_text + id END AS indexed_text
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(String::class.asClassName())
}
@Test fun `cast expression has correct type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
|);
|
|selectStuff:
|SELECT id, CAST (id AS TEXT)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
LONG, String::class.asClassName()
).inOrder()
}
@Test fun `like expression has correct type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE employee (
| id INTEGER NOT NULL PRIMARY KEY,
| department TEXT NOT NULL,
| name TEXT NOT NULL,
| title TEXT NOT NULL,
| bio TEXT NOT NULL
|);
|
|someSelect:
|SELECT *
|FROM employee
|WHERE department = ?
|AND (
| name LIKE '%' || ? || '%'
| OR title LIKE '%' || ? || '%'
| OR bio LIKE '%' || ? || '%'
|)
|ORDER BY department;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.arguments.map { it.type.javaType }).containsExactly(
String::class.asClassName(), String::class.asClassName(), String::class.asClassName(),
String::class.asClassName()
).inOrder()
}
@Test fun `round function has correct type`() {
val file = FixtureCompiler.parseSql(
"""
|someSelect:
|SELECT round(1.123123), round(1.12312, 3);
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
LONG, DOUBLE
).inOrder()
}
@Test fun `sum function has right type for all non-null ints`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value INTEGER NOT NULL
|);
|
|someSelect:
|SELECT sum(value)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(LONG.copy(nullable = true))
}
@Test fun `sum function has right type for nullable values`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value INTEGER
|);
|
|someSelect:
|SELECT sum(value)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(DOUBLE.copy(nullable = true))
}
@Test fun `string functions return nullable string only if parameter is nullable`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 TEXT,
| value2 TEXT NOT NULL
|);
|
|someSelect:
|SELECT lower(value1), lower(value2)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
String::class.asClassName().copy(nullable = true), String::class.asClassName()
).inOrder()
}
@Test fun `datettime functions return non null string`() {
val file = FixtureCompiler.parseSql(
"""
|someSelect:
|SELECT date('now');
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(String::class.asClassName())
}
@Test fun `count function returns non null integer`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 TEXT
|);
|
|someSelect:
|SELECT count(*)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(LONG)
}
@Test fun `instr function returns nullable int if any of the args are null`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 TEXT,
| value2 TEXT NOT NULL
|);
|
|someSelect:
|SELECT instr(value1, value2), instr(value2, value1), instr(value2, value2)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
LONG.copy(nullable = true), LONG.copy(nullable = true), LONG
).inOrder()
}
@Test fun `blob functions return blobs`() {
val file = FixtureCompiler.parseSql(
"""
|someSelect:
|SELECT randomblob(), zeroblob(10);
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
ByteArray::class.asClassName(), ByteArray::class.asClassName()
).inOrder()
}
@Test fun `total function returns non null real`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value INTEGER
|);
|
|someSelect:
|SELECT total(value)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
DOUBLE
).inOrder()
}
/**
* avg's output is nullable because it returns NULL for an input that's empty
* or only contains NULLs.
*
* https://www.sqlite.org/lang_aggfunc.html#avg:
* >> The result of avg() is NULL if and only if there are no non-NULL inputs.
*/
@Test fun `avg function returns nullable real`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value INTEGER
|);
|
|someSelect:
|SELECT avg(value)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
DOUBLE.copy(nullable = true)
).inOrder()
}
@Test fun `abs function returns the same type as given`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value INTEGER,
| value2 REAL NOT NULL
|);
|
|someSelect:
|SELECT abs(value), abs(value2)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
LONG.copy(nullable = true), DOUBLE
).inOrder()
}
@Test fun `coalesce takes the proper type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| integerVal INTEGER NOT NULL,
| realVal REAL NOT NULL,
| nullableRealVal REAL,
| textVal TEXT,
| blobVal BLOB
|);
|
|someSelect:
|SELECT coalesce(integerVal, realVal, textVal, blobVal),
| coalesce(integerVal, nullableRealVal, textVal, blobVal),
| coalesce(integerVal, nullableRealVal, textVal),
| coalesce(nullableRealVal),
| coalesce(integerVal)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
ByteArray::class.asClassName(),
ByteArray::class.asClassName(),
String::class.asClassName(),
DOUBLE.copy(nullable = true),
LONG
).inOrder()
}
@Test fun `max takes the proper type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| integerVal INTEGER NOT NULL,
| realVal REAL NOT NULL,
| nullableRealVal REAL,
| textVal TEXT,
| blobVal BLOB
|);
|
|someSelect:
|SELECT max(integerVal, realVal, textVal, blobVal),
| max(integerVal, nullableRealVal, textVal, blobVal),
| max(integerVal, nullableRealVal, textVal),
| max(nullableRealVal),
| max(integerVal)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
ByteArray::class.asClassName().copy(nullable = true),
ByteArray::class.asClassName().copy(nullable = true),
String::class.asClassName().copy(nullable = true),
DOUBLE.copy(nullable = true),
LONG.copy(nullable = true)
).inOrder()
}
@Test fun `case expression part of limit infers type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value TEXT
|);
|
|someSelect:
|SELECT value
|FROM test
|LIMIT CASE WHEN (SELECT 1) < :arg1
| THEN :arg2
| ELSE :arg3
| END
|;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.parameters.size).isEqualTo(3)
assertThat(query.parameters[0].javaType).isEqualTo(LONG)
assertThat(query.parameters[1].javaType).isEqualTo(LONG)
assertThat(query.parameters[2].javaType).isEqualTo(LONG)
}
@Test fun `min takes the proper type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| integerVal INTEGER NOT NULL,
| realVal REAL NOT NULL,
| nullableRealVal REAL,
| textVal TEXT NOT NULL,
| blobVal BLOB NOT NULL
|);
|
|someSelect:
|SELECT min(integerVal, textVal, blobVal),
| min(integerVal, nullableRealVal, textVal, blobVal),
| min(nullableRealVal),
| min(blobVal, textVal),
| min(blobVal)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }).containsExactly(
LONG.copy(nullable = true),
DOUBLE.copy(nullable = true),
DOUBLE.copy(nullable = true),
String::class.asClassName().copy(nullable = true),
ByteArray::class.asClassName().copy(nullable = true)
).inOrder()
}
@Test fun `arithmetic on nullable type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE Test(
| id INTEGER PRIMARY KEY NOT NULL,
| timestamp INTEGER NOT NULL
|);
|
|selectTimestamp:
|SELECT MIN(timestamp) - 1 FROM Test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.map { it.javaType }.single()).isEqualTo(LONG.copy(nullable = true))
}
@Test fun `nullif take nullable version of given type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 INTEGER NOT NULL,
| value2 REAL NOT NULL
|);
|
|someSelect:
|SELECT nullif(value1, value2)
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedQueries.first()
assertThat(query.resultColumns.single().javaType).isEqualTo(LONG.copy(nullable = true))
}
@Test fun `insert expression gets the right type`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 TEXT,
| value2 TEXT
|);
|
|insert:
|INSERT INTO test
|SELECT ?, value2
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedMutators.first()
assertThat(query.parameters.single().javaType).isEqualTo(String::class.asClassName().copy(nullable = true))
}
@Test fun `insert expression gets the right type from inner query`() {
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| value1 TEXT,
| value2 TEXT
|);
|
|insert:
|INSERT INTO test
|SELECT (SELECT ?), value2
|FROM test;
""".trimMargin(),
tempFolder
)
val query = file.namedMutators.first()
assertThat(query.parameters.single().javaType).isEqualTo(String::class.asClassName().copy(nullable = true))
}
@Test fun `null keyword makes column nullable`(dialect: DialectPreset) {
assumeTrue(dialect == DialectPreset.MYSQL)
val file = FixtureCompiler.parseSql(
"""
|CREATE TABLE test (
| integerVal INTEGER NULL
|);
|
|someSelect:
|SELECT integerVal
|FROM test;
""".trimMargin(),
tempFolder,
dialectPreset = dialect
)
val query = file.namedQueries.first()
assertThat(query.resultColumns[0].javaType).isEqualTo(INT.copy(nullable = true))
}
}
| apache-2.0 | 0e37b808274e76997fa74b103940165f | 26.029091 | 192 | 0.605812 | 4.198249 | false | true | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/service/mutator/genemutation/ArchiveGeneMutator.kt | 1 | 24023 | package org.evomaster.core.search.service.mutator.genemutation
import com.google.inject.Inject
import org.evomaster.client.java.instrumentation.shared.TaintInputName
import org.evomaster.core.EMConfig
import org.evomaster.core.Lazy
import org.evomaster.core.search.Action
import org.evomaster.core.search.Individual
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.numeric.*
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.Impact
import org.evomaster.core.search.impact.impactinfocollection.ImpactUtils
import org.evomaster.core.search.impact.impactinfocollection.value.StringGeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.BinaryGeneImpact
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.EvaluatedMutation
import org.evomaster.core.search.service.mutator.MutatedGeneSpecification
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.mutationupdate.DoubleMutationUpdate
import org.evomaster.core.search.service.mutator.genemutation.mutationupdate.LongMutationUpdate
import org.evomaster.core.search.service.mutator.genemutation.mutationupdate.MutationBoundaryUpdate
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import kotlin.math.abs
import kotlin.math.max
/**
* created by manzh on 2020-07-01
*/
class ArchiveGeneMutator{
@Inject
private lateinit var randomness: Randomness
@Inject
private lateinit var config: EMConfig
@Inject
lateinit var apc: AdaptiveParameterControl
@Inject
lateinit var mwc : MutationWeightControl
@Inject
lateinit var ags : ArchiveImpactSelector
companion object{
private val log: Logger = LoggerFactory.getLogger(ArchiveGeneMutator::class.java)
}
private fun manageHistory(additionalGeneMutationInfo: AdditionalGeneMutationInfo, targets: Set<Int>) : List<Pair<Gene, EvaluatedInfo>> {
return when (config.archiveGeneMutation.withTargets) {
1 -> additionalGeneMutationInfo.history.filter { it.second.targets.any { t-> targets.contains(t) } && it.second.result?.isImpactful()?:true }
2 -> additionalGeneMutationInfo.history.filter { it.second.specificTargets.any { t-> targets.contains(t) } && it.second.result?.isImpactful()?:true }
else -> additionalGeneMutationInfo.history
}
}
/**
* apply mutation based on tracked history
* @param additionalGeneMutationInfo history of gene
* @param gene to mutate
* @param allGenes are other genes in the same individual
*/
fun historyBasedValueMutation(additionalGeneMutationInfo: AdditionalGeneMutationInfo, gene: Gene, allGenes: List<Gene>) {
val history = manageHistory(additionalGeneMutationInfo, additionalGeneMutationInfo.targets)
when (gene) {
is StringGene -> {
val applied = deriveMutatorForStringValue(history, gene, allGenes)
if (!applied) gene.standardValueMutation(randomness, allGenes, apc)
}
is IntegerGene -> gene.value = sampleValue(
history = history.map {
((it.first as? IntegerGene)
?: throw DifferentGeneInHistory(gene, it.first)
).value.toLong() to (it.second.result?.value?:-2)
},
value = gene.value.toLong(),
valueUpdate = LongMutationUpdate(config.archiveGeneMutation.withDirection, min = gene.getMinimum(), max = gene.getMaximum()),
start = GeneUtils.intpow2.size, end = 10
).toInt()
is LongGene -> gene.value = sampleValue(
history = history.map {
((it.first as? LongGene)
?: throw DifferentGeneInHistory(gene, it.first)).value to (it.second.result?.value?:-2)
},
value = gene.value,
valueUpdate = LongMutationUpdate(config.archiveGeneMutation.withDirection, min = gene.getMinimum(), max = gene.getMaximum()),
start = GeneUtils.intpow2.size, end = 10
)
is DoubleGene -> gene.value = sampleValue(
history = history.map {
((it.first as? DoubleGene)?: throw DifferentGeneInHistory(gene, it.first)).value to (it.second.result?.value?:-2)
},
value = gene.value,
valueUpdate = DoubleMutationUpdate(
config.archiveGeneMutation.withDirection,
min = gene.getMinimum(), max = gene.getMaximum(), precision = gene.precision, scale = gene.scale),
start = GeneUtils.intpow2.size, end = 10
)
is FloatGene -> gene.value = sampleValue(
history = history.map {
((it.first as? FloatGene)?: throw DifferentGeneInHistory(gene, it.first)).value.toDouble() to (it.second.result?.value?:-2)
},
value = gene.value.toDouble(),
valueUpdate = DoubleMutationUpdate(
config.archiveGeneMutation.withDirection,
min = gene.getMinimum().toDouble(), max = gene.getMaximum().toDouble(), precision = gene.precision, scale = gene.scale),
start = GeneUtils.intpow2.size, end = 10
).toFloat()
is BigIntegerGene -> {
val bihistory = history.map {
((it.first as? BigIntegerGene)?: throw DifferentGeneInHistory(gene, it.first)).value.toLong() to (it.second.result?.value?:EvaluatedMutation.UNSURE.value)
}
val lvalue = sampleValue(
history = bihistory,
value = gene.toLong(),
valueUpdate = LongMutationUpdate(config.archiveGeneMutation.withDirection, min = gene.min?.toLong()?: Long.MIN_VALUE, max = gene.max?.toLong()?: Long.MAX_VALUE),
start = GeneUtils.intpow2.size, end = 10
)
gene.setValueWithLong(lvalue)
}
is BigDecimalGene ->{
if (gene.floatingPointMode){
val bdhistory = history.map {
((it.first as? BigDecimalGene)?: throw DifferentGeneInHistory(gene, it.first)).value.toDouble() to (it.second.result?.value?:EvaluatedMutation.UNSURE.value)
}
val fvalue = sampleValue(
history = bdhistory,
value = gene.toDouble(),
valueUpdate = DoubleMutationUpdate(config.archiveGeneMutation.withDirection,
min = gene.getMinimum().toDouble(), max = gene.getMaximum().toDouble(), precision = gene.precision, scale = gene.scale),
start = GeneUtils.intpow2.size, end = 10)
gene.setValueWithDouble(fvalue)
}else{
val bdhistory = history.map {
((it.first as? BigDecimalGene)?: throw DifferentGeneInHistory(gene, it.first)).value.toLong() to (it.second.result?.value?:EvaluatedMutation.UNSURE.value)
}
val lvalue = sampleValue(
history = bdhistory,
value = gene.toLong(),
valueUpdate = LongMutationUpdate(config.archiveGeneMutation.withDirection, min = gene.min?.toLong()?: Long.MIN_VALUE, max = gene.max?.toLong()?: Long.MAX_VALUE),
start = GeneUtils.intpow2.size, end = 10
)
gene.setValueWithLong(lvalue)
}
}
else -> throw IllegalArgumentException("history-based value mutation is not applicable for ${gene::class.java.simpleName}")
}
}
private fun probOfMiddle(update : MutationBoundaryUpdate<*>) : Double{
return when {
update.counter > 3 || update.updateTimes < 3 -> apc.getExploratoryValue(0.8, 0.5)
update.counter > 1 || update.updateTimes in 3..5 -> apc.getExploratoryValue(0.5, 0.1)
else -> 0.1
}
}
private fun<T: Number> sampleValue(history : List<Pair<T, Int>>, value: T, valueUpdate: MutationBoundaryUpdate<T>, start: Int, end: Int) : T {
(0 until history.size).forEach {i->
valueUpdate.updateOrRestBoundary(
index = i,
current = history[i].first,
evaluatedResult = history[i].second
)
}
return valueUpdate.random(
randomness = randomness,
apc = apc,
current = value,
probOfMiddle = probOfMiddle(valueUpdate),
start = start,
end = end,
minimalTimeForUpdate = 5
)
}
/**************************** String Gene ********************************************/
private fun deriveMutatorForStringValue(history : List<Pair<Gene, EvaluatedInfo>>, gene: StringGene, allGenes: List<Gene>) : Boolean{
val others = allGenes.flatMap { it.flatView() }
.filterIsInstance<StringGene>()
.map { it.getValueAsRawString() }
.filter { it != gene.value }
.filter { !TaintInputName.isTaintInput(it) }
val lenMutationUpdate = LongMutationUpdate(config.archiveGeneMutation.withDirection, gene.minLength.toLong(), gene.maxLength.toLong())
val charsMutationUpdate = (0 until gene.value.length).map { createCharMutationUpdate() }
(0 until history.size).forEach { i ->
val c = ( history[i].first as? StringGene)?.value ?: throw IllegalStateException("invalid extracted history element")
val better = history[i].second.result?.value?:-2
lenMutationUpdate.updateOrRestBoundary(
index = i,
current = c.length.toLong(),
evaluatedResult = better
)
charsMutationUpdate.forEachIndexed { index, intMutationUpdate ->
if (c.elementAtOrNull(index) != null){
intMutationUpdate.updateOrRestBoundary(
index = i,
current = c.elementAt(index).toLong(),
evaluatedResult = better
)
}
}
}
val p = randomness.nextDouble()
val pOfLen = apc.getExploratoryValue(0.6, 0.2)
val anyCharToMutate = charsMutationUpdate.filterIndexed {
index, longMutationUpdate -> !longMutationUpdate.isReached(gene.value[index].toLong()) }.isNotEmpty() && charsMutationUpdate.isNotEmpty()
if (!anyCharToMutate && lenMutationUpdate.isReached(gene.value.length.toLong())) return false
if (p < 0.02 && others.isNotEmpty()){
gene.value = randomness.choose(others)
return true
}
if (lenMutationUpdate.isReached(gene.value.length.toLong()) || !lenMutationUpdate.isUpdatable() || (p < (1.0 - pOfLen) && anyCharToMutate && gene.value.isNotBlank())){
return mutateChars(charsMutationUpdate, gene)
}
val pLength = lenMutationUpdate.random(
apc = apc,
randomness = randomness,
current = gene.value.length.toLong(),
probOfMiddle = probOfMiddle(lenMutationUpdate),
start = 6,
end = 3,
minimalTimeForUpdate = 2
)
val append = pLength.toInt() > gene.value.length || (pLength.toInt() == gene.value.length && p < 1.0 - pOfLen/2.0)
if (append){
gene.value += randomness.nextWordChar() //(0 until (pLength.toInt() - gene.value.length)).map {randomness.nextWordChar()}.joinToString("")
}else{
gene.value = gene.value.dropLast(1)
}
return true
}
/**
* select a char of [gene] to mutate based on a number of char candidates using weight based solution
* ie, less candidates, higher weight
* @param charsMutationUpdate collects the candidates
* @param gene that is String to mutate
*/
private fun mutateChars(charsMutationUpdate : List<LongMutationUpdate>, gene : StringGene) : Boolean {
val weightsMap = charsMutationUpdate.mapIndexed { index, intMutationUpdate ->
index to intMutationUpdate
}.filter{ !it.second.isReached(gene.value[it.first].toLong()) }.map { it.first to it.second.candidatesBoundary().toDouble() }.toMap()
if (weightsMap.isEmpty()) {
log.warn("none of chars to select for the mutation")
return false
}
val chars = mwc.selectSubsetWithWeight(weightsMap, true, mwc.getNGeneToMutate(weightsMap.size, 1))
chars.forEach {
val mc = charsMutationUpdate[it].random(
current = gene.value[it].toLong(),
randomness = randomness,
apc = apc,
start = 6,
end = 3,
probOfMiddle = probOfMiddle(charsMutationUpdate[it]),
minimalTimeForUpdate = 3
).toChar()
gene.value = modifyIndex(gene.value, index = it, char = mc)
}
return true
}
/**
* archive-based gene mutation for string gene
* @param gene to mutate
* @param targets for this mutation
* @param allGenes are other genes in the same individual
* @param selectionStrategy indicates the startegy to select a specialization of the gene
* @param additionalGeneMutationInfo contains addtional info for applying archive-based gene mutation, e.g., impact, history of the gene
*/
fun mutateStringGene(
gene: StringGene, targets: Set<Int>,
allGenes : List<Gene>, selectionStrategy: SubsetGeneMutationSelectionStrategy, additionalGeneMutationInfo: AdditionalGeneMutationInfo, changeSpecSetting: Double){
var employBinding = true
if (additionalGeneMutationInfo.impact == null){
val ds = gene.standardSpecializationMutation(
randomness = randomness,
allGenes = allGenes,
selectionStrategy = selectionStrategy,
additionalGeneMutationInfo = additionalGeneMutationInfo,
apc = apc,
mwc = mwc,
enableAdaptiveGeneMutation = true
)
if (ds){
return
}
}else{
if (additionalGeneMutationInfo.impact !is StringGeneImpact)
throw IllegalArgumentException("mismatched GeneImpact for StringGene, ${additionalGeneMutationInfo.impact}")
val impact = additionalGeneMutationInfo.impact
val preferSpec = gene.specializationGenes.isNotEmpty()
val specializationGene = gene.getSpecializationGene()
val employSpec = doEmploy(impact = impact.employSpecialization, targets = targets)
employBinding = doEmploy(impact = impact.employBinding, targets = targets)
if (preferSpec && employSpec){
if (specializationGene == null){
gene.selectedSpecialization = randomness.nextInt(0, gene.specializationGenes.size - 1)
}else {
var selected = selectSpec(gene, impact, targets)
val currentImpact = impact.getSpecializationImpacts().getOrNull(gene.selectedSpecialization)
val selectCurrent = gene.selectedSpecialization == selected || (currentImpact?.recentImprovement() == true && randomness.nextBoolean(1.0-changeSpecSetting))
if (selectCurrent && specializationGene.isMutable()){
specializationGene.standardMutation(
randomness, apc, mwc,selectionStrategy, true, additionalGeneMutationInfo.copyFoInnerGene(currentImpact as? GeneImpact)
)
}else if (gene.selectedSpecialization == selected){
selected = (selected + 1) % gene.specializationGenes.size
gene.selectedSpecialization = selected
} else{
gene.selectedSpecialization = selected
}
}
if (employBinding) gene.handleBinding(allGenes = allGenes)
return
}else if (specializationGene != null){
gene.selectedSpecialization = -1
if (employBinding) gene.handleBinding(allGenes = allGenes)
return
}
}
if (gene.redoTaint(apc, randomness)) return
if(additionalGeneMutationInfo.hasHistory())
historyBasedValueMutation(additionalGeneMutationInfo, gene, allGenes)
else
gene.standardValueMutation(randomness, allGenes, apc)
gene.repair()
if (employBinding) gene.handleBinding(allGenes = allGenes)
}
private fun doEmploy(impact: BinaryGeneImpact, targets: Set<Int>) : Boolean{
val list = listOf(true, false)
val weights = ags.impactBasedOnWeights(
impacts = listOf(impact.trueValue, impact.falseValue),
targets = targets)
val employSpec = mwc.selectSubsetWithWeight(weights = weights.mapIndexed { index, w -> list[index] to w}.toMap(), forceNotEmpty = true, numToMutate = 1.0)
return randomness.choose(employSpec)
}
private fun selectSpec(gene: StringGene, impact: StringGeneImpact, targets: Set<Int>) : Int{
val impacts = mutableListOf<Impact>()
if (impact.getSpecializationImpacts().size != gene.specializationGenes.size){
log.warn("mismatched specialization impacts, {} impact but {} spec", impact.getSpecializationImpacts().size, gene.specializationGenes.size)
if(impact.getSpecializationImpacts().isEmpty()){
return randomness.nextInt(0, gene.specializationGenes.size - 1)
}
}
if (gene.specializationGenes.size <= impact.getSpecializationImpacts().size){
impacts.addAll(
impact.getSpecializationImpacts().subList(0, gene.specializationGenes.size)
)
}else{
(impact.getSpecializationImpacts().size-1 until gene.specializationGenes.size).forEach {
val ms = gene.specializationGenes[it]
impacts.add(ImpactUtils.createGeneImpact(ms,ms.name))
}
}
val weights = ags.impactBasedOnWeights(impacts = impacts, targets = targets)
val selected = mwc.selectSubsetWithWeight(
weights = weights.mapIndexed { index, d -> index to d }.toMap(),
forceNotEmpty = true,
numToMutate = 1.0
)
return randomness.choose(selected)
}
/**
* during later phase of search, modify char/int with relative close genes
*/
private fun randomFromCurrentAdaptively(
current: Int, minValue: Int, maxValue: Int, hardMinValue: Int, hardMaxValue: Int, start: Int, end: Int): Int {
val prefer = true
val range = max(abs((if (prefer) maxValue else hardMaxValue) - current), abs((if (prefer) minValue else hardMinValue) - current)).toLong()
val delta = GeneUtils.getDelta(randomness, apc, range = range, start = start, end = end)
val value = if (prefer && current + delta > maxValue)
current - delta
else if (prefer && current - delta < minValue)
current + delta
else
current + delta * randomness.choose(listOf(-1, 1))
return when {
value < hardMinValue -> if (current == hardMinValue) hardMinValue + 1 else hardMinValue
value > hardMaxValue -> if (current == hardMaxValue) hardMaxValue - 1 else hardMaxValue
else -> value
}
}
private fun modifyIndex(value: String, index: Int, char: Char): String {
if (index >= value.length) throw IllegalArgumentException("$index exceeds the length of $value")
return value.toCharArray().also { it[index] = char }.joinToString("")
}
/**
* [min] and [max] are inclusive
*/
fun validateCandidates(min: Int, max: Int, exclude: List<Int>): Int {
if (max < min)
return 0
if (max == min && exclude.contains(min)) return 0
if (max == min)
return 1
return max - min + 1 - exclude.filter { it in min..max }.size
}
/**
* extract mutated info only for standard mutation
*/
private fun mutatedGenePairForIndividualWithActions(
originalActions: List<Action>, mutatedActions : List<Action>, mutatedGenes: List<Gene>, genesAtActionIndex: List<Int>
) : MutableList<Pair<Gene, Gene>>{
Lazy.assert {
mutatedActions.isEmpty() || mutatedActions.size > genesAtActionIndex.maxOrNull()!!
mutatedActions.isEmpty() || mutatedGenes.size == genesAtActionIndex.size
originalActions.size == mutatedActions.size
}
val pairs = mutatedGenes.mapIndexed { index, gene ->
ImpactUtils.findMutatedGene(originalActions[genesAtActionIndex[index]], gene) to ImpactUtils.findMutatedGene(mutatedActions[genesAtActionIndex[index]], gene)
}
if (pairs.isEmpty())
log.warn("none of genes is mutated!")
if (pairs.none { it.first == null || it.second == null }){
return pairs as MutableList<Pair<Gene, Gene>>
}
val ipairs = mutableListOf<Pair<Gene, Gene>>()
originalActions.forEachIndexed { index, action ->
val maction = mutatedActions.elementAt(index)
action.seeTopGenes().filter { it.isMutable()}.forEach { g->
val m = ImpactUtils.findMutatedGene(maction, g)
if (m != null)
ipairs.add(g to m)
}
}
if (pairs.isEmpty())
log.warn("none of genes is mutated!")
return ipairs
}
private fun createCharMutationUpdate() = LongMutationUpdate(config.archiveGeneMutation.withDirection,getDefaultCharMin(), getDefaultCharMax())
private fun getCharPool() = CharPool.WORD
private fun getDefaultCharMin() = when(getCharPool()){
CharPool.ALL -> Char.MIN_VALUE.toInt()
CharPool.WORD -> randomness.wordCharPool().first()
}
private fun getDefaultCharMax() = when(getCharPool()){
CharPool.ALL -> Char.MAX_VALUE.toInt()
CharPool.WORD -> randomness.wordCharPool().last()
}
/**
* save detailed mutated gene over search which is useful for debugging
* @param mutatedGenes contains what gene are mutated in this evaluation
* @param individual is the individual to mutate
* @param index indicates timepoint over search
* @param evaluatedMutation is evaluated result of this mutation
* @param targets are targets for this mutation
*/
fun saveMutatedGene(mutatedGenes: MutatedGeneSpecification?, individual: Individual, index : Int, evaluatedMutation : EvaluatedMutation, targets: Set<Int>){
ArchiveMutationUtils.saveMutatedGene(config, mutatedGenes, individual, index, evaluatedMutation, targets)
}
}
/**
* which chars are used for sampling string gene
* this might need to be further improved
*/
enum class CharPool {
ALL,
WORD
} | lgpl-3.0 | d0a2908d09f6f917bdbac0484fc96ba5 | 45.378378 | 185 | 0.609999 | 4.784505 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/testdata/inspections/missingFlush/Test.kt | 1 | 2182 | import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Preferences
val prefs: Preferences by lazy {
<warning>Gdx.app.getPreferences("a").putBoolean("a", true)</warning>
}
fun fun1() {
val preferences = Gdx.app.getPreferences("sdf")
<warning>preferences.putBoolean("fds", true)</warning>
}
fun fun1a() {
val preferences = Gdx.app.getPreferences("sdf")
preferences.putBoolean("fds", true)
if (true) {
preferences.flush()
}
preferences.flush()
}
fun fun2() {
val p = Gdx.app.getPreferences("a")
p.remove("dfs")
<warning>p.putBoolean("a", true)</warning>
}
fun fun3() {
val p = Gdx.app.getPreferences("a")
for (i in listOf(1,2,3)) <warning>p.putString("a", "b")</warning>
listOf(1,2,3).map { it -> <warning>p.putInteger("a", it)</warning> }
listOf(1,2,3).map { it -> p.putInteger("a", it); p.flush() }
}
fun fun3a() {
val p = Gdx.app.getPreferences("a")
for (i in listOf(1,2,3)) p.putString("a", "b")
listOf(1,2,3).map { it -> <warning>p.putInteger("a", it)</warning> }
p.flush()
listOf(1,2,3).map { it -> p.putInteger("a", it); p.flush() }
}
fun fun4() {
for (i in listOf(1,2,3)) {
Gdx.app.getPreferences("a").putString("a", "b")
Gdx.app.getPreferences("a").flush();
<warning>Gdx.app.getPreferences("a").putBoolean("a", true)</warning>
}
}
fun fun5() {
prefs.let {
<warning>it.putBoolean("a", true)</warning>
}
prefs.flush()
}
fun fun6() {
prefs.let {
it.putBoolean("a", true)
it.flush()
}
}
class TestPrefs {
val p = Gdx.app.getPreferences("a")
var c: (() -> Unit)? = null
init {
<warning>p.putBoolean("a", true)</warning>
}
fun fun1() {
p.remove("a")
Gdx.app.getPreferences("b").flush()
<warning>p.remove("a")</warning>
}
fun fun2() {
setCallback { <warning>Gdx.app.getPreferences("a").putBoolean("a", true)</warning> }
Gdx.app.getPreferences("f").flush()
}
fun fun3() {
setCallback { Gdx.app.getPreferences("a").putBoolean("a", true); Gdx.app.getPreferences("a").flush() }
}
fun fun4() {
c = {
<warning>Gdx.app.getPreferences("a").remove("a")</warning>
}
}
fun setCallback(f: ()->Unit) {
c = f
}
}
| apache-2.0 | 3b0ad7a6556228f8928f3c01937fbf07 | 18.482143 | 106 | 0.598992 | 2.980874 | false | false | false | false |
d9n/trypp.support | src/test/code/trypp/support/pattern/observer/EventTest.kt | 1 | 4717 | package trypp.support.pattern.observer
import com.google.common.truth.Truth.assertThat
import org.testng.annotations.Test
class EventTest {
class CancelParams {
var shouldCancel = false;
}
class Window {
val onOpening = Event2<Window, CancelParams>()
val onOpened = Event1<Window>()
fun open() {
val p = CancelParams()
onOpening(this, p);
if (!p.shouldCancel) {
onOpened(this)
}
}
}
@Test
fun eventsCanBeUsedToPreventOrAllowBehavior() {
val w = Window()
var opened = false
w.onOpened += { opened = true }
w.onOpening += { w, params -> params.shouldCancel = true }
w.open()
assertThat(opened).isFalse()
w.onOpening.clearListeners()
w.open()
assertThat(opened).isTrue()
}
@Test
fun addThenRemoveListenerWorks() {
val event = Event0()
var listenCount = 0
val handle = event.addListener { listenCount++ }
event()
assertThat(listenCount).isEqualTo(1)
event -= handle
event()
assertThat(listenCount).isEqualTo(1)
}
@Test
fun addThenClearListenersWorks() {
val event = Event0()
var listenCount = 0
event += { ++listenCount }
event += { listenCount += 10 }
event()
assertThat(listenCount).isEqualTo(11)
event.clearListeners()
event()
assertThat(listenCount).isEqualTo(11)
}
@Test
fun event0Works() {
val event = Event0()
var handled = false
event += { handled = true }
assertThat(handled).isFalse()
event()
assertThat(handled).isTrue()
}
@Test
fun event1Works() {
val event = Event1<String>()
var value = ""
event += { value = it }
assertThat(value).isEmpty()
event("1")
assertThat(value).isEqualTo("1")
}
@Test
fun event2Works() {
val event = Event2<String, String>()
var value = ""
event += { s1, s2 -> value = s1 + s2 }
assertThat(value).isEmpty()
event("1", "2")
assertThat(value).isEqualTo("12")
}
@Test
fun event3Works() {
val event = Event3<String, String, String>()
var value = ""
event += { s1, s2, s3 -> value = s1 + s2 + s3 }
assertThat(value).isEmpty()
event("1", "2", "3")
assertThat(value).isEqualTo("123")
}
@Test
fun event4Works() {
val event = Event4<String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4 -> value = s1 + s2 + s3 + s4 }
assertThat(value).isEmpty()
event("1", "2", "3", "4")
assertThat(value).isEqualTo("1234")
}
@Test
fun event5Works() {
val event = Event5<String, String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4, s5 -> value = s1 + s2 + s3 + s4 + s5 }
assertThat(value).isEmpty()
event("1", "2", "3", "4", "5")
assertThat(value).isEqualTo("12345")
}
@Test
fun event6Works() {
val event = Event6<String, String, String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4, s5, s6 -> value = s1 + s2 + s3 + s4 + s5 + s6 }
assertThat(value).isEmpty()
event("1", "2", "3", "4", "5", "6")
assertThat(value).isEqualTo("123456")
}
@Test
fun event7Works() {
val event = Event7<String, String, String, String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4, s5, s6, s7 -> value = s1 + s2 + s3 + s4 + s5 + s6 + s7 }
assertThat(value).isEmpty()
event("1", "2", "3", "4", "5", "6", "7")
assertThat(value).isEqualTo("1234567")
}
@Test
fun event8Works() {
val event = Event8<String, String, String, String, String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4, s5, s6, s7, s8 -> value = s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 }
assertThat(value).isEmpty()
event("1", "2", "3", "4", "5", "6", "7", "8")
assertThat(value).isEqualTo("12345678")
}
@Test
fun event9Works() {
val event = Event9<String, String, String, String, String, String, String, String, String>()
var value = ""
event += { s1, s2, s3, s4, s5, s6, s7, s8, s9 -> value = s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 }
assertThat(value).isEmpty()
event("1", "2", "3", "4", "5", "6", "7", "8", "9")
assertThat(value).isEqualTo("123456789")
}
} | mit | 0a11b9eeef91582063d74c053d4832af | 25.505618 | 109 | 0.514946 | 3.568079 | false | true | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/psi/impl/mixins/GdxJsonStringMixin.kt | 1 | 2000 | package com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.impl.mixins
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonString
import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.impl.GdxJsonElementImpl
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.openapi.util.text.StringUtil
import javax.swing.Icon
/*
* Copyright 2019 Blue Box Ware
*
* 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.
*/
abstract class GdxJsonStringMixin(node: ASTNode) : GdxJsonString, GdxJsonElementImpl(node) {
override fun isQuoted(): Boolean = text.length > 1 && text.first() == '"' && text.last() == '"'
override fun getValue(): String =
if (isQuoted) {
text.substring(1, text.length - 1)
} else {
text
}
override fun toFloatOrNull(): Float? = getValue().toFloatOrNull()
override fun isKeyword(): Boolean = !isQuoted && getValue() in KEYWORDS
override fun isNumber(): Boolean =
getValue().toFloatOrNull() != null || getValue().toLongOrNull() != null
override fun getPresentation(): ItemPresentation? = object : ItemPresentation {
override fun getLocationString(): String? = null
override fun getIcon(unused: Boolean): Icon? = null
override fun getPresentableText(): String = StringUtil.unescapeStringCharacters(getValue())
}
companion object {
val KEYWORDS = listOf("null", "true", "false")
}
}
| apache-2.0 | d5bcdc005b82bf196aed8db8e128d911 | 33.482759 | 99 | 0.709 | 4.484305 | false | false | false | false |
misty000/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/bindings/Bindings.kt | 2 | 9034 | // Overloaded operators like in ScalaFX
// https://code.google.com/p/scalafx/#Natural_Language_Bind_Expressions
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/package-summary.html
package kotlinfx.bindings
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/When.html
// -------------------------------------------------------------------------
// Usage: fillProperty() bind (if_(hoverProperty()) { Color.GREEN } else_{ Color.RED })
// TODO: http://youtrack.jetbrains.com/issue/KT-1686
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> Boolean): javafx.beans.binding.When.BooleanConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> Double): javafx.beans.binding.When.NumberConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> Float): javafx.beans.binding.When.NumberConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> Int): javafx.beans.binding.When.NumberConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> Long): javafx.beans.binding.When.NumberConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> javafx.beans.value.ObservableBooleanValue): javafx.beans.binding.When.BooleanConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> javafx.beans.value.ObservableNumberValue): javafx.beans.binding.When.NumberConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> javafx.beans.value.ObservableStringValue): javafx.beans.binding.When.StringConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//
//fun if_(condition: javafx.beans.value.ObservableBooleanValue, f: () -> String): javafx.beans.binding.When.StringConditionBuilder =
// javafx.beans.binding.When(condition).then(f())!!
//fun if_<T>(condition: javafx.beans.value.ObservableBooleanValue, f: () -> javafx.beans.value.ObservableObjectValue<T>): javafx.beans.binding.When.ObjectConditionBuilder<T> =
// javafx.beans.binding.When(condition).then(f())!!
fun if_<T>(condition: javafx.beans.value.ObservableBooleanValue, f: () -> T): javafx.beans.binding.When.ObjectConditionBuilder<T> =
javafx.beans.binding.When(condition).then(f())!!
// TODO: http://youtrack.jetbrains.com/issue/KT-1686
//fun javafx.beans.binding.When.BooleanConditionBuilder.else_(f: () -> Boolean): javafx.beans.binding.BooleanBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.BooleanConditionBuilder.else_(f: () -> javafx.beans.value.ObservableBooleanValue): javafx.beans.binding.BooleanBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.NumberConditionBuilder.else_(f: () -> Double): javafx.beans.binding.DoubleBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.NumberConditionBuilder.else_(f: () -> Float): javafx.beans.binding.NumberBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.NumberConditionBuilder.else_(f: () -> Int): javafx.beans.binding.NumberBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.NumberConditionBuilder.else_(f: () -> Long): javafx.beans.binding.NumberBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.NumberConditionBuilder.else_(f: () -> javafx.beans.value.ObservableNumberValue): javafx.beans.binding.NumberBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.StringConditionBuilder.else_(f: () -> String): javafx.beans.binding.StringBinding =
// this.otherwise(f())!!
//
//fun javafx.beans.binding.When.StringConditionBuilder.else_(f: () -> javafx.beans.value.ObservableStringValue): javafx.beans.binding.StringBinding =
// this.otherwise(f())!!
//fun <T> javafx.beans.binding.When.ObjectConditionBuilder<T>.else_(f: () -> javafx.beans.value.ObservableObjectValue<T>): javafx.beans.binding.ObjectBinding<T> =
// this.otherwise(f())!!
fun <T> javafx.beans.binding.When.ObjectConditionBuilder<T>.else_(f: () -> T): javafx.beans.binding.ObjectBinding<T> =
this.otherwise(f())!!
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/NumberExpression.html
// -------------------------------------------------------------------------------------
// We cannot use comparison operators for greaterThan etc. because of the way Kotlin handles the translation of these operators
// The same is true for (in)equality operators.
fun javafx.beans.binding.NumberExpression.plus(other: Double): javafx.beans.binding.NumberBinding =
this.add(other)!!
fun javafx.beans.binding.NumberExpression.plus(other: Float): javafx.beans.binding.NumberBinding =
this.add(other)!!
fun javafx.beans.binding.NumberExpression.plus(other: Int): javafx.beans.binding.NumberBinding =
this.add(other)!!
fun javafx.beans.binding.NumberExpression.plus(other: Long): javafx.beans.binding.NumberBinding =
this.add(other)!!
fun javafx.beans.binding.NumberExpression.plus(other: javafx.beans.value.ObservableNumberValue): javafx.beans.binding.NumberBinding =
this.add(other)!!
fun javafx.beans.binding.NumberExpression.div(other: Double): javafx.beans.binding.NumberBinding =
this.divide(other)!!
fun javafx.beans.binding.NumberExpression.div(other: Float): javafx.beans.binding.NumberBinding =
this.divide(other)!!
fun javafx.beans.binding.NumberExpression.div(other: Int): javafx.beans.binding.NumberBinding =
this.divide(other)!!
fun javafx.beans.binding.NumberExpression.div(other: Long): javafx.beans.binding.NumberBinding =
this.divide(other)!!
fun javafx.beans.binding.NumberExpression.div(other: javafx.beans.value.ObservableNumberValue): javafx.beans.binding.NumberBinding =
this.divide(other)!!
fun javafx.beans.binding.NumberExpression.times(other: Double): javafx.beans.binding.NumberBinding =
this.multiply(other)!!
fun javafx.beans.binding.NumberExpression.times(other: Float): javafx.beans.binding.NumberBinding =
this.multiply(other)!!
fun javafx.beans.binding.NumberExpression.times(other: Int): javafx.beans.binding.NumberBinding =
this.multiply(other)!!
fun javafx.beans.binding.NumberExpression.times(other: Long): javafx.beans.binding.NumberBinding =
this.multiply(other)!!
fun javafx.beans.binding.NumberExpression.times(other: javafx.beans.value.ObservableNumberValue): javafx.beans.binding.NumberBinding =
this.multiply(other)!!
fun javafx.beans.binding.NumberExpression.minus(other: Double): javafx.beans.binding.NumberBinding =
this.subtract(other)!!
fun javafx.beans.binding.NumberExpression.minus(other: Float): javafx.beans.binding.NumberBinding =
this.subtract(other)!!
fun javafx.beans.binding.NumberExpression.minus(other: Int): javafx.beans.binding.NumberBinding =
this.subtract(other)!!
fun javafx.beans.binding.NumberExpression.minus(other: Long): javafx.beans.binding.NumberBinding =
this.subtract(other)!!
fun javafx.beans.binding.NumberExpression.minus(other: javafx.beans.value.ObservableNumberValue): javafx.beans.binding.NumberBinding =
this.subtract(other)!!
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/BooleanExpression.html
// --------------------------------------------------------------------------------------
// There is no way to override boolean operators in Kotlin.
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/StringExpression.html
// -------------------------------------------------------------------------------------
fun javafx.beans.binding.StringExpression.plus(other: Any?): javafx.beans.binding.StringExpression =
this.concat(other)!!
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ObjectExpression.html
// -------------------------------------------------------------------------------------
// No opportunity to provide overriden operators.
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ListExpression.html
// -----------------------------------------------------------------------------------
// No opportunity to provide overriden operators.
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/MapExpression.html
// ----------------------------------------------------------------------------------
// No opportunity to provide overriden operators.
// http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/SetExpression.html
// ----------------------------------------------------------------------------------
// No opportunity to provide overriden operators.
| mit | 586ef0c85dbe7086862315ca3a41653f | 47.569892 | 175 | 0.696148 | 3.844255 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-shops-bukkit/src/main/kotlin/com/rpkit/shops/bukkit/command/RestockCommand.kt | 1 | 2535 | /*
* Copyright 2020 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.shops.bukkit.command
import com.rpkit.shops.bukkit.RPKShopsBukkit
import org.bukkit.Material
import org.bukkit.block.Chest
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
class RestockCommand(private val plugin: RPKShopsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (sender.hasPermission("rpkit.shops.command.restock")) {
if (sender is Player) {
val transparent: Set<Material>? = null
val targetBlock = sender.getTargetBlock(transparent, 8)
val chest = targetBlock.state
if (chest is Chest) {
if (args.isNotEmpty()) {
val material = Material.matchMaterial(args.joinToString(" "))
if (material != null) {
for (i in 0 until chest.inventory.size) {
chest.inventory.setItem(i, ItemStack(material, material.maxStackSize))
}
sender.sendMessage(plugin.messages["restock-valid"])
} else {
sender.sendMessage(plugin.messages["restock-invalid-material"])
}
} else {
sender.sendMessage(plugin.messages["restock-usage"])
}
} else {
sender.sendMessage(plugin.messages["restock-invalid-chest"])
}
} else {
sender.sendMessage(plugin.messages["not-from-console"])
}
} else {
sender.sendMessage(plugin.messages["no-permission-restock"])
}
return true
}
} | apache-2.0 | 5d4566da879ebc8d523b9206a4c137be | 40.57377 | 118 | 0.602367 | 4.819392 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-professions-bukkit/src/main/kotlin/com/rpkit/professions/bukkit/listener/RPKCharacterDeleteListener.kt | 1 | 2582 | /*
* 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.professions.bukkit.listener
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterDeleteEvent
import com.rpkit.professions.bukkit.RPKProfessionsBukkit
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionChangeCooldownTable
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionExperienceTable
import com.rpkit.professions.bukkit.database.table.RPKCharacterProfessionTable
import com.rpkit.professions.bukkit.database.table.RPKProfessionHiddenTable
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class RPKCharacterDeleteListener(private val plugin: RPKProfessionsBukkit) : Listener {
@EventHandler
fun onCharacterDelete(event: RPKBukkitCharacterDeleteEvent) {
val characterProfessionChangeCooldownTable = plugin.database.getTable(RPKCharacterProfessionChangeCooldownTable::class.java)
val characterProfessionChangeCooldown = characterProfessionChangeCooldownTable.get(event.character).join()
if (characterProfessionChangeCooldown != null) {
characterProfessionChangeCooldownTable.delete(characterProfessionChangeCooldown).join()
}
val characterProfessionExperienceTable = plugin.database.getTable(RPKCharacterProfessionExperienceTable::class.java)
characterProfessionExperienceTable.delete(event.character).join()
val characterProfessionTable = plugin.database.getTable(RPKCharacterProfessionTable::class.java)
characterProfessionTable[event.character].join().forEach { characterProfession ->
characterProfessionTable.delete(characterProfession).join()
}
val professionHiddenTable = plugin.database.getTable(RPKProfessionHiddenTable::class.java)
professionHiddenTable[event.character].thenAccept { professionHidden ->
if (professionHidden != null) {
professionHiddenTable.delete(professionHidden).join()
}
}
}
} | apache-2.0 | 1ceaf04531b5e87fbb97cd576e6a4dd8 | 45.125 | 132 | 0.780015 | 4.918095 | false | false | false | false |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/geocaching4locus/settings/fragment/AboutPreferenceFragment.kt | 1 | 3913 | package com.arcao.geocaching4locus.settings.fragment
import android.app.Dialog
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.core.net.toUri
import androidx.preference.Preference
import com.arcao.feedback.FeedbackHelper
import com.arcao.geocaching4locus.App
import com.arcao.geocaching4locus.BuildConfig
import com.arcao.geocaching4locus.R
import com.arcao.geocaching4locus.base.constants.AppConstants
import com.arcao.geocaching4locus.base.constants.PrefConstants.ABOUT_DONATE_PAYPAL
import com.arcao.geocaching4locus.base.constants.PrefConstants.ABOUT_FACEBOOK
import com.arcao.geocaching4locus.base.constants.PrefConstants.ABOUT_FEEDBACK
import com.arcao.geocaching4locus.base.constants.PrefConstants.ABOUT_VERSION
import com.arcao.geocaching4locus.base.constants.PrefConstants.ABOUT_WEBSITE
import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider
import com.arcao.geocaching4locus.base.fragment.AbstractDialogFragment
import com.arcao.geocaching4locus.base.fragment.AbstractPreferenceFragment
import com.arcao.geocaching4locus.base.util.showWebPage
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get
import org.koin.android.ext.android.inject
import kotlin.coroutines.CoroutineContext
class AboutPreferenceFragment : AbstractPreferenceFragment(), CoroutineScope {
private val dispatcherProvider by inject<CoroutinesDispatcherProvider>()
private val feedbackHelper by inject<FeedbackHelper>()
private val job = SupervisorJob()
override val coroutineContext: CoroutineContext
get() = job + dispatcherProvider.main
override val preferenceResource: Int
get() = R.xml.preference_category_about
override fun preparePreference() {
super.preparePreference()
preference<Preference>(ABOUT_VERSION).summary =
"${get<App>().version} (${BuildConfig.GIT_SHA})"
preference<Preference>(ABOUT_WEBSITE).apply {
summary = AppConstants.WEBSITE_URI.toString()
setOnPreferenceClickListener {
requireActivity().showWebPage(AppConstants.WEBSITE_URI)
}
}
preference<Preference>(ABOUT_FACEBOOK).apply {
summary = AppConstants.FACEBOOK_URI.toString()
setOnPreferenceClickListener {
requireActivity().showWebPage(AppConstants.FACEBOOK_URI)
}
}
preference<Preference>(ABOUT_FEEDBACK).setOnPreferenceClickListener {
launch {
val intent = feedbackHelper.createFeedbackIntent(
R.string.feedback_email,
R.string.feedback_subject,
R.string.feedback_body
)
startActivity(intent)
}
true
}
preference<Preference>(ABOUT_DONATE_PAYPAL).setOnPreferenceClickListener {
DonatePaypalDialogFragment().show(parentFragmentManager, DonatePaypalDialogFragment.TAG)
true
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
class DonatePaypalDialogFragment : AbstractDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setTitle(R.string.pref_donate_paypal_choose_currency)
.setItems(R.array.currency) { _, which ->
requireActivity().showWebPage(
AppConstants.DONATE_PAYPAL_URI.format(resources.getStringArray(R.array.currency)[which]).toUri()
)
}
.setCancelable(true)
.create()
}
companion object {
const val TAG = "DonatePaypalDialogFragment"
}
}
}
| gpl-3.0 | 3bb7d42698cf85a16c20f6a6652861b4 | 37.362745 | 120 | 0.699208 | 5.081818 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/database/table/RPKSnooperTable.kt | 1 | 5913 | /*
* 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.chat.bukkit.database.table
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.database.create
import com.rpkit.chat.bukkit.database.jooq.Tables.RPKIT_SNOOPER
import com.rpkit.chat.bukkit.snooper.RPKSnooper
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileId
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.*
import java.util.logging.Level.SEVERE
/**
* Represents the snooper table.
*/
class RPKSnooperTable(
private val database: Database,
private val plugin: RPKChatBukkit
) : Table {
private val cache = if (plugin.config.getBoolean("caching.rpkit_snooper.minecraft_profile_id.enabled")) {
database.cacheManager.createCache(
"rpk-chat-bukkit.rpkit_snooper.minecraft_profile_id",
Int::class.javaObjectType,
RPKSnooper::class.java,
plugin.config.getLong("caching.rpkit_snooper.minecraft_profile_id.size")
)
} else {
null
}
fun insert(entity: RPKSnooper): CompletableFuture<Void> {
val minecraftProfileId = entity.minecraftProfile.id ?: return completedFuture(null)
return runAsync {
database.create
.insertInto(
RPKIT_SNOOPER,
RPKIT_SNOOPER.MINECRAFT_PROFILE_ID
)
.values(minecraftProfileId.value)
.execute()
cache?.set(minecraftProfileId.value, entity)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to insert snooper", exception)
throw exception
}
}
/**
* Gets the snooper instance for a Minecraft profile.
* If the player does not have a snooper entry, null is returned.
*
* @param minecraftProfile The player
* @return The snooper instance, or null if none exists
*/
fun get(minecraftProfile: RPKMinecraftProfile): CompletableFuture<RPKSnooper?> {
val minecraftProfileId = minecraftProfile.id ?: return completedFuture(null)
if (cache?.containsKey(minecraftProfileId.value) == true) {
return completedFuture(cache[minecraftProfileId.value])
} else {
return supplyAsync {
database.create
.selectDistinct(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID)
.from(RPKIT_SNOOPER)
.where(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.fetchOne() ?: return@supplyAsync null
val snooper = RPKSnooper(
minecraftProfile
)
cache?.set(minecraftProfileId.value, snooper)
return@supplyAsync snooper
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get snooper", exception)
throw exception
}
}
}
/**
* Gets all snoopers
*
* @return A list containing all snoopers
*/
fun getAll(): CompletableFuture<List<RPKSnooper>> {
return supplyAsync {
val results = database.create
.selectDistinct(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID)
.from(RPKIT_SNOOPER)
.fetch()
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return@supplyAsync emptyList()
return@supplyAsync results.mapNotNull { result ->
val minecraftProfile =
minecraftProfileService.getMinecraftProfile(RPKMinecraftProfileId(result.get(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID)))
.join()
?: return@mapNotNull null
return@mapNotNull RPKSnooper(minecraftProfile)
}
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to get all snoopers", exception)
throw exception
}
}
fun delete(entity: RPKSnooper): CompletableFuture<Void> {
val minecraftProfileId = entity.minecraftProfile.id ?: return completedFuture(null)
return runAsync {
database.create
.deleteFrom(RPKIT_SNOOPER)
.where(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.execute()
cache?.remove(minecraftProfileId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete snooper", exception)
throw exception
}
}
fun delete(minecraftProfileId: RPKMinecraftProfileId): CompletableFuture<Void> = runAsync {
database.create
.deleteFrom(RPKIT_SNOOPER)
.where(RPKIT_SNOOPER.MINECRAFT_PROFILE_ID.eq(minecraftProfileId.value))
.execute()
cache?.remove(minecraftProfileId.value)
}.exceptionally { exception ->
plugin.logger.log(SEVERE, "Failed to delete snooper for Minecraft profile id", exception)
throw exception
}
} | apache-2.0 | beeb21738dbdcce332ae24a0bcc58f2b | 38.691275 | 134 | 0.645019 | 4.846721 | false | false | false | false |
BenjaminSutter/genera | src/main/kotlin/net/bms/genera/item/ItemSeedNightshade.kt | 1 | 1702 | package net.bms.genera.item
import net.bms.genera.Genera
import net.bms.genera.init.GeneraBlocks
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.init.Blocks
import net.minecraft.item.Item
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
import net.minecraftforge.common.EnumPlantType
import net.minecraftforge.common.IPlantable
/**
* Created by ben on 3/18/17.
*/
class ItemSeedNightshade: Item(), IPlantable {
init {
setRegistryName("nightshade_seed")
unlocalizedName = "nightshade_seed"
creativeTab = Genera.TabGenera
}
override fun getPlantType(world: IBlockAccess, pos: BlockPos): EnumPlantType {
return EnumPlantType.Crop
}
override fun getPlant(world: IBlockAccess, pos: BlockPos): IBlockState {
return GeneraBlocks.BlockNightshadeCrop.defaultState
}
override fun onItemUse(player: EntityPlayer?, worldIn: World?, pos: BlockPos?, hand: EnumHand?, facing: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult {
val state = worldIn!!.getBlockState(pos!!)
val stateUp = worldIn.getBlockState(pos.up())
if (state.block.canSustainPlant(state, worldIn, pos, facing!!, this) && stateUp.block === Blocks.AIR) {
worldIn.setBlockState(pos.up(), GeneraBlocks.BlockNightshadeCrop.defaultState)
player!!.getHeldItem(hand!!).count = player.getHeldItem(hand).count - 1
}
return EnumActionResult.PASS
}
}
| mit | 01cfe3e95500b3e6904e0454a4666fb0 | 35.212766 | 179 | 0.73443 | 3.976636 | false | false | false | false |
EvidentSolutions/dalesbred | dalesbred/src/test/kotlin/org/dalesbred/DatabaseBatchUpdatesTest.kt | 1 | 3277 | /*
* Copyright (c) 2017 Evident Solutions Oy
*
* 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 org.dalesbred
import org.dalesbred.query.SqlQuery.query
import org.dalesbred.result.ResultSetProcessor
import org.dalesbred.testutils.mapRows
import org.junit.Assert.assertArrayEquals
import org.junit.Rule
import org.junit.Test
import java.sql.ResultSet
import kotlin.test.assertEquals
import kotlin.test.fail
class DatabaseBatchUpdatesTest {
private val db = TestDatabaseProvider.createInMemoryHSQLDatabase()
@get:Rule val rule = TransactionalTestsRule(db)
@Test
fun batchUpdate() {
db.update("drop table if exists dictionary")
db.update("create temporary table dictionary (word varchar(64) primary key)")
val data = listOf("foo", "bar", "baz").map { listOf(it) }
val result = db.updateBatch("insert into dictionary (word) values (?)", data)
assertArrayEquals(intArrayOf(1, 1, 1), result)
assertEquals(listOf("bar", "baz", "foo"), db.findAll(String::class.java, "select word from dictionary order by word"))
}
@Test
fun batchUpdateWithGeneratedKeys() {
db.update("drop table if exists my_table")
db.update("create temporary table my_table (id identity primary key, str varchar(64), num int)")
val argLists = listOf(
listOf("foo", 1),
listOf("bar", 2),
listOf("baz", 3))
val result = db.updateBatchAndProcessGeneratedKeys(CollectKeysResultSetProcessor, listOf("ID"), "INSERT INTO my_table (str, num) VALUES (?,?)", argLists)
assertEquals(listOf(0, 1, 2), result)
}
@Test
fun exceptionsContainReferenceToOriginalQuery() {
val data = listOf(listOf("foo"))
try {
db.updateBatch("insert into nonexistent_table (foo) values (?)", data)
fail("Expected DatabaseException")
} catch (e: DatabaseException) {
assertEquals(query("insert into nonexistent_table (foo) values (?)", "<batch-update>"), e.query)
}
}
private object CollectKeysResultSetProcessor : ResultSetProcessor<List<Int>> {
override fun process(resultSet: ResultSet) = resultSet.mapRows { it.getInt((1)) }
}
}
| mit | 47c781b265a29483659c9e132cb4eff5 | 38.481928 | 161 | 0.698505 | 4.363515 | false | true | false | false |
ajalt/clikt | clikt/src/commonMain/kotlin/com/github/ajalt/clikt/core/Context.kt | 1 | 11391 | package com.github.ajalt.clikt.core
import com.github.ajalt.clikt.mpp.readEnvvar
import com.github.ajalt.clikt.output.*
import com.github.ajalt.clikt.sources.ChainedValueSource
import com.github.ajalt.clikt.sources.ValueSource
import kotlin.jvm.JvmOverloads
import kotlin.properties.ReadOnlyProperty
typealias TypoSuggestor = (enteredValue: String, possibleValues: List<String>) -> List<String>
/**
* A object used to control command line parsing and pass data between commands.
*
* A new Context instance is created for each command each time the command line is parsed.
*
* @property parent If this context is the child of another command, [parent] is the parent command's context.
* @property command The command that this context associated with.
* @property allowInterspersedArgs If false, options and arguments cannot be mixed; the first time an argument is
* encountered, all remaining tokens are parsed as arguments.
* @property autoEnvvarPrefix The prefix to add to inferred envvar names. If null, the prefix is based on the
* parent's prefix, if there is one. If no command specifies, a prefix, envvar lookup is disabled.
* @property printExtraMessages Set this to false to prevent extra messages from being printed automatically.
* You can still access them at [CliktCommand.messages] inside of [CliktCommand.run].
* @property helpOptionNames The names to use for the help option. If any names in the set conflict with other
* options, the conflicting name will not be used for the help option. If the set is empty, or contains no
* unique names, no help option will be added.
* @property helpFormatter The help formatter for this command.
* @property tokenTransformer An optional transformation function that is called to transform command line
* tokens (options and commands) before parsing. This can be used to implement e.g. case insensitive
* behavior.
* @property console The console to use to print messages.
* @property expandArgumentFiles If true, arguments starting with `@` will be expanded as argument
* files. If false, they will be treated as normal arguments.
* @property correctionSuggestor A callback called when the command line contains an invalid option or
* subcommand name. It takes the entered name and a list of all registered names option/subcommand
* names and filters the list down to values to suggest to the user.
*/
class Context @JvmOverloads constructor(
val parent: Context?,
val command: CliktCommand,
val allowInterspersedArgs: Boolean,
val autoEnvvarPrefix: String?,
val printExtraMessages: Boolean,
val helpOptionNames: Set<String>,
val helpFormatter: HelpFormatter,
val tokenTransformer: Context.(String) -> String,
val console: CliktConsole,
val expandArgumentFiles: Boolean,
val readEnvvarBeforeValueSource: Boolean,
val valueSource: ValueSource?,
val correctionSuggestor: TypoSuggestor,
val localization: Localization,
val readEnvvar: (String) -> String? = ::readEnvvar,
val originalArgv: List<String> = emptyList(),
) {
var invokedSubcommand: CliktCommand? = null
internal set
var obj: Any? = null
/** Find the closest object of type [T] */
inline fun <reified T : Any> findObject(): T? {
return ancestors().mapNotNull { it.obj as? T }.firstOrNull()
}
/** Find the closest object of type [T], setting `this.`[obj] if one is not found. */
inline fun <reified T : Any> findOrSetObject(defaultValue: () -> T): T {
return findObject() ?: defaultValue().also { obj = it }
}
/** Find the outermost context */
fun findRoot(): Context {
var ctx = this
while (ctx.parent != null) {
ctx = ctx.parent!!
}
return ctx
}
/** Return a list of command names, starting with the topmost command and ending with this Context's parent. */
fun parentNames(): List<String> {
return ancestors().drop(1)
.map { it.command.commandName }
.toList().asReversed()
}
/** Return a list of command names, starting with the topmost command and ending with this Context's command. */
fun commandNameWithParents(): List<String> {
return parentNames() + command.commandName
}
/** Throw a [UsageError] with the given message */
fun fail(message: String = ""): Nothing = throw UsageError(message)
@PublishedApi
internal fun ancestors() = generateSequence(this) { it.parent }
class Builder(command: CliktCommand, parent: Context? = null) {
/**
* If false, options and arguments cannot be mixed; the first time an argument is encountered, all
* remaining tokens are parsed as arguments.
*/
var allowInterspersedArgs: Boolean = parent?.allowInterspersedArgs ?: true
/**
* Set this to false to prevent extra messages from being printed automatically.
*
* You can still access them at [CliktCommand.messages] inside of [CliktCommand.run].
*/
var printExtraMessages: Boolean = parent?.printExtraMessages ?: true
/**
* The names to use for the help option.
*
* If any names in the set conflict with other options, the conflicting name will not be used for the
* help option. If the set is empty, or contains no unique names, no help option will be added.
*/
var helpOptionNames: Set<String> = parent?.helpOptionNames ?: setOf("-h", "--help")
/** The help formatter for this command, or null to use the default */
var helpFormatter: HelpFormatter? = parent?.helpFormatter
/** An optional transformation function that is called to transform command line */
var tokenTransformer: Context.(String) -> String = parent?.tokenTransformer ?: { it }
/**
* The prefix to add to inferred envvar names.
*
* If null, the prefix is based on the parent's prefix, if there is one. If no command specifies, a
* prefix, envvar lookup is disabled.
*/
var autoEnvvarPrefix: String? = parent?.autoEnvvarPrefix?.let {
it + "_" + command.commandName.replace(Regex("\\W"), "_").uppercase()
}
/**
* The console that will handle reading and writing text.
*
* The default uses stdin and stdout.
*/
var console: CliktConsole = parent?.console ?: defaultCliktConsole()
/**
* If true, arguments starting with `@` will be expanded as argument files. If false, they
* will be treated as normal arguments.
*/
var expandArgumentFiles: Boolean = parent?.expandArgumentFiles ?: true
/**
* If `false`,the [valueSource] is searched before environment variables.
*
* By default, environment variables will be searched for option values before the [valueSource].
*/
var readEnvvarBeforeValueSource: Boolean = parent?.readEnvvarBeforeValueSource ?: true
/**
* The source that will attempt to read values for options that aren't present on the command line.
*
* You can set multiple sources with [valueSources]
*/
var valueSource: ValueSource? = parent?.valueSource
/**
* Set multiple sources that will attempt to read values for options not present on the command line.
*
* Values are read from the first source, then if it doesn't return a value, later sources
* are read successively until one returns a value or all sources have been read.
*/
fun valueSources(vararg sources: ValueSource) {
valueSource = ChainedValueSource(sources.toList())
}
/**
* A callback called when the command line contains an invalid option or
* subcommand name. It takes the entered name and a list of all registered names option/subcommand
* names and filters the list down to values to suggest to the user.
*/
var correctionSuggestor: TypoSuggestor = DEFAULT_CORRECTION_SUGGESTOR
/**
* Localized strings to use for help output and error reporting.
*/
var localization: Localization = defaultLocalization
/**
* A function called by Clikt to get a parameter value from a given environment variable
*
* The function returns `null` if the envvar is not defined.
*
* You can set this to read from a map or other source during tests.
*/
var envvarReader: (key: String) -> String? = parent?.readEnvvar ?: ::readEnvvar
}
companion object {
fun build(command: CliktCommand, parent: Context? = null, block: Builder.() -> Unit): Context {
return build(command, parent, emptyList(), block)
}
internal fun build(
command: CliktCommand,
parent: Context?,
argv: List<String>,
block: Builder.() -> Unit,
): Context {
with(Builder(command, parent)) {
block()
val interspersed = allowInterspersedArgs && !command.allowMultipleSubcommands &&
parent?.let { p -> p.ancestors().any { it.command.allowMultipleSubcommands } } != true
val formatter = helpFormatter ?: CliktHelpFormatter(localization)
return Context(
parent, command, interspersed, autoEnvvarPrefix, printExtraMessages,
helpOptionNames, formatter, tokenTransformer, console, expandArgumentFiles,
readEnvvarBeforeValueSource, valueSource, correctionSuggestor, localization,
envvarReader, argv
)
}
}
}
}
/** Find the closest object of type [T], or throw a [NullPointerException] */
@Suppress("unused") // these extensions don't use their receiver, but we want to limit where they can be called
inline fun <reified T : Any> CliktCommand.requireObject(): ReadOnlyProperty<CliktCommand, T> {
return ReadOnlyProperty { thisRef, _ -> thisRef.currentContext.findObject()!! }
}
/** Find the closest object of type [T], or null */
@Suppress("unused")
inline fun <reified T : Any> CliktCommand.findObject(): ReadOnlyProperty<CliktCommand, T?> {
return ReadOnlyProperty { thisRef, _ -> thisRef.currentContext.findObject() }
}
/**
* Find the closest object of type [T], setting `context.obj` if one is not found.
*
* Note that this function returns a delegate, and so the object will not be set on the context
* until the delegated property's value is accessed. If you want to set a value for subcommands
* without accessing the property, call [Context.findOrSetObject] in your [run][CliktCommand.run]
* function instead.
*/
@Suppress("unused")
inline fun <reified T : Any> CliktCommand.findOrSetObject(crossinline default: () -> T): ReadOnlyProperty<CliktCommand, T> {
return ReadOnlyProperty { thisRef, _ -> thisRef.currentContext.findOrSetObject(default) }
}
private val DEFAULT_CORRECTION_SUGGESTOR: TypoSuggestor = { enteredValue, possibleValues ->
possibleValues.map { it to jaroWinklerSimilarity(enteredValue, it) }
.filter { it.second > 0.8 }
.sortedByDescending { it.second }
.map { it.first }
}
| apache-2.0 | de58d37405af1eb55b404b69c0ebbfeb | 44.023715 | 124 | 0.667808 | 4.632371 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/main/kotlin/com/github/kittinunf/reactiveandroid/widget/CalendarViewProperty.kt | 1 | 618 | package com.github.kittinunf.reactiveandroid.widget
import android.widget.CalendarView
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Properties
//================================================================================
val CalendarView.rx_date: MutableProperty<Long>
get() {
val getter = { date }
val setter: (Long) -> Unit = { date = it }
return createMainThreadMutableProperty(getter, setter)
}
| mit | aa3e9ae07902373d954c70ae61a5c449 | 33.333333 | 82 | 0.548544 | 6.18 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/auth/TokenCheckFragment.kt | 1 | 5804 | package app.opass.ccip.ui.auth
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import app.opass.ccip.R
import app.opass.ccip.databinding.FragmentTokenCheckBinding
import app.opass.ccip.databinding.IncludeAuthHeaderBinding
import app.opass.ccip.extension.asyncExecute
import app.opass.ccip.extension.getFastPassUrl
import app.opass.ccip.extension.isInverted
import app.opass.ccip.network.CCIPClient
import app.opass.ccip.util.PreferenceUtil
import com.onesignal.OneSignal
import com.squareup.picasso.Picasso
import kotlinx.coroutines.launch
import org.json.JSONException
import org.json.JSONObject
class TokenCheckFragment : AuthActivity.PageFragment() {
private var hasRequestEnd = false
private var hasErrorOccurred = false
private val isRetryDisabled: Boolean by lazy { requireArguments().getBoolean(EXTRA_DISABLE_RETRY) }
private val mActivity: AuthActivity by lazy { requireActivity() as AuthActivity }
private var _binding: FragmentTokenCheckBinding? = null
private val binding get() = _binding!!
override fun shouldShowNextButton() = hasRequestEnd
override fun shouldShowPreviousButton() = false
override fun getNextButtonText() =
if (hasErrorOccurred && !isRetryDisabled) R.string.try_again
else R.string.kontinue
override fun onBackPressed(): Boolean {
if (hasRequestEnd) {
if (hasErrorOccurred && !isRetryDisabled) return false
else mActivity.onAuthFinished()
}
// Don't pop the fragment before the request end
return true
}
override fun onNextButtonClicked() {
if (hasErrorOccurred) mActivity.onBackPressed()
else mActivity.onAuthFinished()
}
override fun onSelected() {
mActivity.hideKeyboard()
val token = requireArguments().getString(EXTRA_TOKEN)
val baseUrl = PreferenceUtil.getCurrentEvent(mActivity).getFastPassUrl() ?: return mActivity.finish()
lifecycleScope.launch {
try {
val response = CCIPClient.withBaseUrl(baseUrl).status(token).asyncExecute()
when {
response.isSuccessful -> {
val attendee = response.body()!!
binding.title.text = getString(R.string.hi) + attendee.userId
binding.message.text = getString(
R.string.login_success,
PreferenceUtil.getCurrentEvent(mActivity).displayName.findBestMatch(mActivity)
)
binding.message.isGone = false
val header = IncludeAuthHeaderBinding.bind(binding.root)
header.confName.isGone = true
PreferenceUtil.setToken(mActivity, token)
PreferenceUtil.setRole(mActivity, attendee.role)
try {
JSONObject()
.put(attendee.eventId + attendee.role, attendee.token)
.let(OneSignal::sendTags)
} catch (e: JSONException) {
e.printStackTrace()
}
}
response.code() == 403 -> {
binding.title.setText(R.string.couldnt_verify_your_identity)
binding.message.setText(R.string.connect_to_conference_wifi)
binding.message.isGone = false
hasErrorOccurred = true
}
else -> {
binding.title.setText(R.string.couldnt_verify_your_identity)
binding.message.setText(R.string.invalid_token)
binding.message.isGone = false
hasErrorOccurred = true
}
}
} catch (t: Throwable) {
t.printStackTrace()
binding.title.setText(R.string.couldnt_verify_your_identity)
binding.message.setText(R.string.offline)
binding.message.isGone = false
hasErrorOccurred = true
} finally {
binding.progress.isGone = true
hasRequestEnd = true
mActivity.updateButtonState()
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentTokenCheckBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val header = IncludeAuthHeaderBinding.bind(binding.root)
header.notThisEvent.isVisible = false
val context = requireContext()
val event = PreferenceUtil.getCurrentEvent(context)
header.confName.text = event.displayName.findBestMatch(context)
header.confLogo.isInverted = true
Picasso.get().load(event.logoUrl).into(header.confLogo)
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
companion object {
private const val EXTRA_TOKEN = "EXTRA_TOKEN"
private const val EXTRA_DISABLE_RETRY = "EXTRA_DISABLE_RETRY"
fun newInstance(token: String, disableRetry: Boolean) = TokenCheckFragment().apply {
arguments = Bundle().apply {
putString(EXTRA_TOKEN, token)
putBoolean(EXTRA_DISABLE_RETRY, disableRetry)
}
}
}
}
| gpl-3.0 | e19e35432cecbc094d4fb2e45f1f4709 | 39.027586 | 109 | 0.607684 | 5.127208 | false | false | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/generation/GeneratorAdapterExtensions.kt | 1 | 5850 | /*
* Copyright 2019 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.generation
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.signature.GenericType
import io.michaelrocks.lightsaber.LightsaberTypes
import io.michaelrocks.lightsaber.processor.commons.GeneratorAdapter
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.commons.boxed
import io.michaelrocks.lightsaber.processor.commons.rawType
import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor
import io.michaelrocks.lightsaber.processor.generation.model.Key
import io.michaelrocks.lightsaber.processor.generation.model.KeyRegistry
import io.michaelrocks.lightsaber.processor.model.Converter
import io.michaelrocks.lightsaber.processor.model.Dependency
import io.michaelrocks.lightsaber.processor.model.Injectee
import io.michaelrocks.lightsaber.processor.model.Provider
import io.michaelrocks.lightsaber.processor.model.Scope
private val ADAPTER_CONSTRUCTOR = MethodDescriptor.forConstructor(Types.PROVIDER_TYPE)
private val GET_PROVIDER_FOR_CLASS_METHOD =
MethodDescriptor.forMethod("getProvider", Types.PROVIDER_TYPE, Types.CLASS_TYPE)
private val GET_PROVIDER_FOR_TYPE_METHOD =
MethodDescriptor.forMethod("getProvider", Types.PROVIDER_TYPE, Types.TYPE_TYPE)
private val GET_PROVIDER_FOR_KEY_METHOD =
MethodDescriptor.forMethod("getProvider", Types.PROVIDER_TYPE, Types.KEY_TYPE)
private val GET_INSTANCE_FOR_CLASS_METHOD =
MethodDescriptor.forMethod("getInstance", Types.OBJECT_TYPE, Types.CLASS_TYPE)
private val GET_INSTANCE_FOR_TYPE_METHOD =
MethodDescriptor.forMethod("getInstance", Types.OBJECT_TYPE, Types.TYPE_TYPE)
private val GET_INSTANCE_FOR_KEY_METHOD =
MethodDescriptor.forMethod("getInstance", Types.OBJECT_TYPE, Types.KEY_TYPE)
private val REGISTER_PROVIDER_FOR_CLASS_METHOD =
MethodDescriptor.forMethod("registerProvider", Type.Primitive.Void, Types.CLASS_TYPE, Types.PROVIDER_TYPE)
private val REGISTER_PROVIDER_FOR_TYPE_METHOD =
MethodDescriptor.forMethod("registerProvider", Type.Primitive.Void, Types.TYPE_TYPE, Types.PROVIDER_TYPE)
private val REGISTER_PROVIDER_FOR_KEY_METHOD =
MethodDescriptor.forMethod("registerProvider", Type.Primitive.Void, Types.KEY_TYPE, Types.PROVIDER_TYPE)
private val DELEGATE_PROVIDER_CONSTRUCTOR = MethodDescriptor.forConstructor(Types.PROVIDER_TYPE)
fun GeneratorAdapter.getDependency(keyRegistry: KeyRegistry, injectee: Injectee) {
when (injectee.converter) {
is Converter.Identity -> {
getProvider(keyRegistry, injectee.dependency)
}
is Converter.Instance -> {
if (injectee.dependency.type.rawType != Types.INJECTOR_TYPE || injectee.dependency.qualifier != null) {
getInstance(keyRegistry, injectee.dependency)
unbox(injectee.dependency.type.rawType)
}
}
is Converter.Adapter -> {
getProvider(keyRegistry, injectee.dependency)
newInstance(injectee.converter.adapterType)
dupX1()
swap()
invokeConstructor(injectee.converter.adapterType, ADAPTER_CONSTRUCTOR)
}
}
}
fun GeneratorAdapter.getProvider(keyRegistry: KeyRegistry, dependency: Dependency) {
val key = pushTypeOrKey(keyRegistry, dependency)
when (key) {
null -> invokeInterface(Types.INJECTOR_TYPE, GET_PROVIDER_FOR_CLASS_METHOD)
is Key.Type -> invokeInterface(Types.INJECTOR_TYPE, GET_PROVIDER_FOR_TYPE_METHOD)
is Key.QualifiedType -> invokeInterface(Types.INJECTOR_TYPE, GET_PROVIDER_FOR_KEY_METHOD)
}
}
fun GeneratorAdapter.getInstance(keyRegistry: KeyRegistry, dependency: Dependency) {
val key = pushTypeOrKey(keyRegistry, dependency)
when (key) {
null -> invokeInterface(Types.INJECTOR_TYPE, GET_INSTANCE_FOR_CLASS_METHOD)
is Key.Type -> invokeInterface(Types.INJECTOR_TYPE, GET_INSTANCE_FOR_TYPE_METHOD)
is Key.QualifiedType -> invokeInterface(Types.INJECTOR_TYPE, GET_INSTANCE_FOR_KEY_METHOD)
}
}
fun GeneratorAdapter.registerProvider(keyRegistry: KeyRegistry, provider: Provider, providerCreator: () -> Unit) {
val key = pushTypeOrKey(keyRegistry, provider.dependency)
when (provider.scope) {
is Scope.Class -> newDelegator(provider.scope.scopeType, providerCreator)
is Scope.None -> providerCreator()
}
when (key) {
null -> invokeVirtual(LightsaberTypes.LIGHTSABER_INJECTOR_TYPE, REGISTER_PROVIDER_FOR_CLASS_METHOD)
is Key.Type -> invokeVirtual(LightsaberTypes.LIGHTSABER_INJECTOR_TYPE, REGISTER_PROVIDER_FOR_TYPE_METHOD)
is Key.QualifiedType -> invokeVirtual(LightsaberTypes.LIGHTSABER_INJECTOR_TYPE, REGISTER_PROVIDER_FOR_KEY_METHOD)
}
}
private fun GeneratorAdapter.newDelegator(scopeType: Type, providerCreator: () -> Unit) {
newInstance(scopeType)
dup()
providerCreator()
invokeConstructor(scopeType, DELEGATE_PROVIDER_CONSTRUCTOR)
}
private fun GeneratorAdapter.pushTypeOrKey(keyRegistry: KeyRegistry, dependency: Dependency): Key? {
val key = keyRegistry.keys[dependency.boxed()]
if (key == null) {
push(dependency.type)
} else {
getStatic(keyRegistry.type, key.field)
}
return key
}
private fun GeneratorAdapter.push(type: GenericType) {
when (type) {
is GenericType.Raw -> push(type.type.boxed())
else -> error("Cannot push a generic type $type")
}
}
| apache-2.0 | 790565207b380b0b3fcb3af75acea37b | 40.785714 | 117 | 0.777436 | 3.985014 | false | false | false | false |
kmizu/kollection | src/main/kotlin/com/github/kmizu/kollection/RedBlackTree.kt | 1 | 22052 | package com.github.kmizu.kollection
import java.util.*
import com.github.kmizu.kollection.RedBlackTree.Tree.RedTree
import com.github.kmizu.kollection.RedBlackTree.Tree.BlackTree
object RedBlackTree {
fun isEmpty(tree: Tree<*, *>?): Boolean = tree === null
fun <A> contains(tree: Tree<A, *>?, x: A, comparator: Comparator<A>): Boolean = lookup(tree, x, comparator) !== null
fun <A, B> get(tree: Tree<A, B>?, x: A, comparator: Comparator<A>): B? = run {
if(tree == null) {
null
} else {
val result = lookup(tree, x, comparator)
if(result == null) {
null
} else {
result.value
}
}
}
fun <A, B> sizeOf(tree: Tree<A, B>?): Int = run {
if(tree === null) {
0
} else {
sizeOf(tree.left) + 1 + sizeOf(tree.right)
}
}
tailrec
fun <A, B> lookup(tree: Tree<A, B>?, x: A, comparator: Comparator<A>): Tree<A, B>? = if (tree === null) null else {
val cmp = comparator.compare(x, tree.key)
if (cmp < 0) lookup(tree.left, x, comparator)
else if (cmp > 0) lookup(tree.right, x, comparator)
else tree
}
fun count(tree: Tree<*, *>?): Int = if (tree === null) 0 else tree.count
fun <A> countInRange(tree: Tree<A, *>?, from: A?, to: A?, comparator: Comparator<A>) : Int = run {
if (tree === null)
0
else {
when {
from === null && to === null ->
tree.count
from !== null && comparator.compare(tree.key, from) < 0 ->
countInRange(tree.right, from, to, comparator)
to !== null && comparator.compare(tree.key, to) >= 0 ->
countInRange(tree.left, from, to, comparator)
else ->
1 + countInRange(tree.left, from, null, comparator) + countInRange(tree.right, null, to, comparator)
}
}
}
fun <A, B> update(tree: Tree<A, B>?, k: A, v: B, overwrite: Boolean, comparator: Comparator<A>): Tree<A, B>? = run {
blacken(upd(tree, k, v, overwrite, comparator))
}
fun <A, B> delete(tree: Tree<A, B>?, k: A, comparator: Comparator<A>): Tree<A, B>? = blacken(del(tree, k, comparator))
fun <A, B> rangeImpl(tree: Tree<A, B>?, from: A?, until: A?, comparator: Comparator<A>): Tree<A, B>? = when {
from !== null && until !== null -> this.range(tree, from, until, comparator)
from !== null && until === null -> this.from(tree, from, comparator)
from === null && until !== null -> this.until(tree, until, comparator)
else -> tree
}
fun <A, B> range(tree: Tree<A, B>?, from: A, until: A, comparator: Comparator<A>): Tree<A, B>? = blacken(doRange(tree, from, until, comparator))
fun <A, B> from(tree: Tree<A, B>?, from: A, comparator: Comparator<A>): Tree<A, B>? = blacken(doFrom(tree, from, comparator))
fun <A, B> to(tree: Tree<A, B>?, to: A, comparator: Comparator<A>): Tree<A, B>? = blacken(doTo(tree, to, comparator))
fun <A, B> until(tree: Tree<A, B>?, key: A, comparator: Comparator<A>): Tree<A, B>? = blacken(doUntil(tree, key, comparator))
fun <A, B> drop(tree: Tree<A, B>?, n: Int): Tree<A, B>? = blacken(doDrop(tree, n))
fun <A, B> take(tree: Tree<A, B>?, n: Int): Tree<A, B>? = blacken(doTake(tree, n))
fun <A, B> slice(tree: Tree<A, B>?, from: Int, until: Int): Tree<A, B>? = blacken(doSlice(tree, from, until))
fun <A, B> smallest(tree: Tree<A, B>?): Tree<A, B> = run {
if (tree === null) throw NoSuchElementException("empty map")
tailrec
fun loop(node: Tree<A, B>): Tree<A, B> {
if(node.left !== null) {
return loop(node.left)
} else {
return node
}
}
loop(tree)
}
fun <A, B> greatest(tree: Tree<A, B>?): Tree<A, B> = run {
if (tree === null) throw NoSuchElementException("empty map")
tailrec
fun loop(node: Tree<A, B>): Tree<A, B> {
if(node.right !== null) {
return loop(node.right)
} else {
return node
}
}
loop(tree)
}
tailrec
fun <A, B> nth(tree: Tree<A, B>?, n: Int): Tree<A, B>? {
if(tree === null) {
return null
} else {
val count = this.count(tree.left)
if (n < count) return nth(tree.left, n)
else if (n > count) return nth(tree.right, n - count - 1)
else return tree
}
}
fun isBlack(tree: Tree<*, *>?) = (tree === null) || isBlackTree(tree)
private fun isRedTree(tree: Tree<*, *>) = tree is RedBlackTree.Tree.RedTree<*, *>
private fun isBlackTree(tree: Tree<*, *>) = tree is RedBlackTree.Tree.BlackTree<*, *>
private fun <A, B> blacken(t: Tree<A, B>?): Tree<A, B>? = if (t === null) null else t.black
private fun <A, B> mkTree(isBlack: Boolean, k: A, v: B, l: Tree<A, B>?, r: Tree<A, B>?): Tree<A, B> = run {
if (isBlack) BlackTree(k, v, l, r) else RedTree(k, v, l, r)
}
private fun <A, B> balanceLeft(isBlack: Boolean, z: A, zv: B, l: Tree<A, B>?, d: Tree<A, B>?): Tree<A, B> = run {
if (l is RedTree<A, B> && l.left is RedTree<A, B>)
RedTree(l.key, l.value, BlackTree(l.left.key, l.left.value, l.left.left, l.left.right), BlackTree(z, zv, l.right, d))
else if (l is RedTree<A, B> && l.right is RedTree<A, B>)
RedTree(l.right.key, l.right.value, BlackTree(l.key, l.value, l.left, l.right.left), BlackTree(z, zv, l.right.right, d))
else
mkTree(isBlack, z, zv, l, d)
}
private fun <A, B> balanceRight(isBlack: Boolean, x: A, xv: B, a: Tree<A, B>?, r: Tree<A, B>?): Tree<A, B> = run {
if (r is RedTree<A, B> && r.left is RedTree<A, B>)
RedTree(r.left.key, r.left.value, BlackTree(x, xv, a, r.left.left), BlackTree(r.key, r.value, r.left.right, r.right))
else if (r is RedTree<A, B> && r.right is RedTree<A, B>)
RedTree(r.key, r.value, BlackTree(x, xv, a, r.left), BlackTree(r.right.key, r.right.value, r.right.left, r.right.right))
else
mkTree(isBlack, x, xv, a, r)
}
private fun <A, B> upd(tree: Tree<A, B>?, k: A, v: B, overwrite: Boolean, comparator: Comparator<A>): Tree<A, B> = if (tree === null) {
RedTree(k, v, null, null)
} else {
val cmp = comparator.compare(k, tree.key)
if (cmp < 0) balanceLeft(isBlackTree(tree), tree.key, tree.value, upd(tree.left, k, v, overwrite, comparator), tree.right)
else if (cmp > 0) balanceRight(isBlackTree(tree), tree.key, tree.value, tree.left, upd(tree.right, k, v, overwrite, comparator))
else if (overwrite || k != tree.key) mkTree(isBlackTree(tree), k, v, tree.left, tree.right)
else tree
}
private fun <A, B> updNth(tree: Tree<A, B>?, idx: Int, k: A, v: B, overwrite: Boolean): Tree<A, B> = if (tree === null) {
RedTree(k, v, null, null)
} else {
val rank = count(tree.left) + 1
if (idx < rank) balanceLeft(isBlackTree(tree), tree.key, tree.value, updNth(tree.left, idx, k, v, overwrite), tree.right)
else if (idx > rank) balanceRight(isBlackTree(tree), tree.key, tree.value, tree.left, updNth(tree.right, idx - rank, k, v, overwrite))
else if (overwrite) mkTree(isBlackTree(tree), k, v, tree.left, tree.right)
else tree
}
/* Based on Stefan Kahrs' Haskell version of Okasaki's Red&Black Trees
* Constructing Red-Black Trees, Ralf Hinze: http://www.cs.ox.ac.uk/ralf.hinze/publications/WAAAPL99b.ps.gz
* Red-Black Trees in a Functional Setting, Chris Okasaki: https://wiki.rice.edu/confluence/download/attachments/2761212/Okasaki-Red-Black.pdf */
private fun <A, B> del(tree: Tree<A, B>?, k: A, comparator: Comparator<A>): Tree<A, B>? = if (tree === null) null else {
fun balance(x: A, xv: B, tl: Tree<A, B>?, tr: Tree<A, B>?) = if (tl is RedTree<A, B>) {
if (tr is RedTree<A, B>) {
RedTree(x, xv, tl.black, tr.black)
} else if (tl.left is RedTree<A, B>) {
RedTree(tl.key, tl.value, tl.left.black, BlackTree(x, xv, tl.right, tr))
} else if (tl.right is RedTree<A, B>) {
RedTree(tl.right.key, tl.right.value, BlackTree(tl.key, tl.value, tl.left, tl.right.left), BlackTree(x, xv, tl.right.right, tr))
} else {
BlackTree(x, xv, tl, tr)
}
} else if (tr is RedTree<A, B>) {
if (tr.right is RedTree<A, B>) {
RedTree(tr.key, tr.value, BlackTree(x, xv, tl, tr.left), tr.right.black)
} else if (tr.left is RedTree<A, B>) {
RedTree(tr.left.key, tr.left.value, BlackTree(x, xv, tl, tr.left.left), BlackTree(tr.key, tr.value, tr.left.right, tr.right))
} else {
BlackTree(x, xv, tl, tr)
}
} else {
BlackTree(x, xv, tl, tr)
}
fun subl(t: Tree<A, B>?): Tree<A, B> = run {
if (t is BlackTree<A, B>) t.red
else throw Exception("Defect: invariance violation; expected black, got "+t)
}
fun balLeft(x: A, xv: B, tl: Tree<A, B>?, tr: Tree<A, B>?) = if (tl is RedTree<A, B>) {
RedTree(x, xv, tl.black, tr)
} else if (tr is BlackTree<A, B>) {
balance(x, xv, tl, tr.red)
} else if (tr is RedTree<A, B> && tr.left is BlackTree<A, B>) {
RedTree(tr.left.key, tr.left.value, BlackTree(x, xv, tl, tr.left.left), balance(tr.key, tr.value, tr.left.right, subl(tr.right)))
} else {
throw Exception("Defect: invariance violation")
}
fun balRight(x: A, xv: B, tl: Tree<A, B>?, tr: Tree<A, B>?) = if (tr is RedTree<A, B>) {
RedTree(x, xv, tl, tr.black)
} else if (tl is BlackTree<A, B>) {
balance(x, xv, tl.red, tr)
} else if (tl is RedTree<A, B> && tl.right is BlackTree<A, B>) {
RedTree(tl.right.key, tl.right.value, balance(tl.key, tl.value, subl(tl.left), tl.right.left), BlackTree(x, xv, tl.right.right, tr))
} else {
throw Exception("Defect: invariance violation")
}
fun delLeft() = run {
if (tree.left is BlackTree<A, B>) balLeft(tree.key, tree.value, del(tree.left, k, comparator), tree.right) else RedTree(tree.key, tree.value, del(tree.left, k, comparator), tree.right)
}
fun delRight() = run {
if (tree.right is BlackTree<A, B>) balRight(tree.key, tree.value, tree.left, del(tree.right, k, comparator)) else RedTree(tree.key, tree.value, tree.left, del(tree.right, k, comparator))
}
fun append(tl: Tree<A, B>?, tr: Tree<A, B>?): Tree<A, B>? = if (tl === null) {
tr
} else if (tr === null) {
tl
} else if (tl is RedTree<A, B> && tr is RedTree<A, B>) {
val bc = append(tl.right, tr.left)
if (bc is RedTree<A, B>) {
RedTree(bc.key, bc.value, RedTree(tl.key, tl.value, tl.left, bc.left), RedTree(tr.key, tr.value, bc.right, tr.right))
} else {
RedTree(tl.key, tl.value, tl.left, RedTree(tr.key, tr.value, bc, tr.right))
}
} else if (isBlackTree(tl) && isBlackTree(tr)) {
val bc = append(tl.right, tr.left)
if (bc is RedTree<A, B>) {
RedTree(bc.key, bc.value, BlackTree(tl.key, tl.value, tl.left, bc.left), BlackTree(tr.key, tr.value, bc.right, tr.right))
} else {
balLeft(tl.key, tl.value, tl.left, BlackTree(tr.key, tr.value, bc, tr.right))
}
} else if (tr is RedTree<A, B>) {
RedTree(tr.key, tr.value, append(tl, tr.left), tr.right)
} else if (tl is RedTree<A, B>) {
RedTree(tl.key, tl.value, tl.left, append(tl.right, tr))
} else {
throw Exception("unmatched tree on append: " + tl + ", " + tr)
}
val cmp = comparator.compare(k, tree.key)
if (cmp < 0) delLeft()
else if (cmp > 0) delRight()
else append(tree.left, tree.right)
}
private fun <A, B> doFrom(tree: Tree<A, B>?, from: A, comparator: Comparator<A>): Tree<A, B>? = run {
if (tree == null) return null
if (comparator.compare(tree.key, from) < 0) return doFrom(tree.right, from, comparator)
val newLeft = doFrom(tree.left, from, comparator)
if (newLeft === tree.left) tree
else if (newLeft === null) upd(tree.right, tree.key, tree.value, false, comparator)
else rebalance(tree, newLeft, tree.right)
}
private fun <A, B> doTo(tree: Tree<A, B>?, to: A, comparator: Comparator<A>): Tree<A, B>? = run {
if (tree === null) return null
if (comparator.compare(to, tree.key) < 0) return doTo(tree.left, to, comparator)
val newRight = doTo(tree.right, to, comparator)
if (newRight === tree.right) tree
else if (newRight === null) upd(tree.left, tree.key, tree.value, false, comparator)
else rebalance(tree, tree.left, newRight)
}
private fun <A, B> doUntil(tree: Tree<A, B>?, until: A, comparator: Comparator<A>): Tree<A, B>? = run {
if (tree === null) return null
if (comparator.compare(until, tree.key) <= 0) return doUntil(tree.left, until, comparator)
val newRight = doUntil(tree.right, until, comparator)
if (newRight === tree.right) tree
else if (newRight === null) upd(tree.left, tree.key, tree.value, false, comparator)
else rebalance(tree, tree.left, newRight)
}
private fun <A, B> doRange(tree: Tree<A, B>?, from: A, until: A, comparator: Comparator<A>): Tree<A, B>? = run {
if (tree === null) return null
if (comparator.compare(tree.key ,from) < 0) return doRange(tree.right, from, until, comparator)
if (comparator.compare(until, tree.key) <= 0) return doRange(tree.left, from, until, comparator)
val newLeft = doFrom(tree.left, from, comparator)
val newRight = doUntil(tree.right, until, comparator)
if ((newLeft === tree.left) && (newRight === tree.right)) tree
else if (newLeft === null) upd(newRight, tree.key, tree.value, false, comparator)
else if (newRight === null) upd(newLeft, tree.key, tree.value, false, comparator)
else rebalance(tree, newLeft, newRight)
}
private fun <A, B> doDrop(tree: Tree<A, B>?, n: Int): Tree<A, B>? = run {
if (n <= 0) return tree
if (n >= this.count(tree)) return null
if(tree === null) return tree
val count = this.count(tree.left)
if (n > count) return doDrop(tree.right, n - count - 1)
val newLeft = doDrop(tree.left, n)
if (newLeft === tree.left) tree
else if (newLeft === null) updNth(tree.right, n - count - 1, tree.key, tree.value, overwrite = false)
else rebalance(tree, newLeft, tree.right)
}
private fun <A, B> doTake(tree: Tree<A, B>?, n: Int): Tree<A, B>? = run {
if (n <= 0) return null
if (n >= this.count(tree)) return tree
if(tree === null) return tree
val count = this.count(tree.left)
if (n <= count) return doTake(tree.left, n)
val newRight = doTake(tree.right, n - count - 1)
if (newRight === tree.right) tree
else if (newRight === null) updNth(tree.left, n, tree.key, tree.value, overwrite = false)
else rebalance(tree, tree.left, newRight)
}
private fun <A, B> doSlice(tree: Tree<A, B>?, from: Int, until: Int): Tree<A, B>? = run {
if (tree === null) return null
val count = this.count(tree.left)
if (from > count) return doSlice(tree.right, from - count - 1, until - count - 1)
if (until <= count) return doSlice(tree.left, from, until)
val newLeft = doDrop(tree.left, from)
val newRight = doTake(tree.right, until - count - 1)
if ((newLeft === tree.left) && (newRight === tree.right)) tree
else if (newLeft === null) updNth(newRight, from - count - 1, tree.key, tree.value, overwrite = false)
else if (newRight === null) updNth(newLeft, until, tree.key, tree.value, overwrite = false)
else rebalance(tree, newLeft, newRight)
}
data class Result<A, B>(val _1: KList<Tree<A, B>>, val _2: Boolean, val _3: Boolean, val _4: Int)
private fun <A, B> compareDepth(left: Tree<A, B>?, right: Tree<A, B>?): Result<A, B> = run {
fun unzip(zipper: KList<Tree<A, B>>, leftMost: Boolean): KList<Tree<A, B>> = run {
val next = if (leftMost) zipper.hd.left else zipper.hd.right
if (next === null) zipper
else unzip(next cons zipper, leftMost)
}
fun unzipBoth(
lhs: Tree<A, B>?,
rhs: Tree<A, B>?,
lhsZipper: KList<Tree<A, B>>,
rhsZipper: KList<Tree<A, B>>,
smallerDepth: Int
): Result<A, B> = run {
if (lhs is BlackTree<A, B> && rhs is BlackTree<A, B>) {
unzipBoth(lhs.right, rhs.left, lhs cons lhsZipper, rhs cons rhsZipper, smallerDepth + 1)
} else if (lhs is RedTree<A, B> && rhs is RedTree<A, B>) {
unzipBoth(lhs.right, rhs.left, lhs cons lhsZipper, rhs cons rhsZipper, smallerDepth)
} else if (rhs is RedTree<A, B>) {
unzipBoth(lhs, rhs.left, lhsZipper, rhs cons rhsZipper, smallerDepth)
} else if (lhs is RedTree<A, B>) {
unzipBoth(lhs.right, rhs, lhs cons lhsZipper, rhsZipper, smallerDepth)
} else if (lhs === null && rhs === null) {
Result(KList.Nil, true, false, smallerDepth)
} else if (lhs === null && rhs is BlackTree<A, B>) {
val leftMost = true
Result(unzip(rhs cons rhsZipper, leftMost), false, leftMost, smallerDepth)
} else if (lhs is BlackTree<A, B> && rhs === null) {
val leftMost = false
Result(unzip(lhs cons lhsZipper, leftMost), false, leftMost, smallerDepth)
} else {
throw Exception("unmatched trees in unzip: $lhs, $rhs")
}
}
unzipBoth(left, right, KList.Nil, KList.Nil, 0)
}
private fun <A, B> rebalance(tree: Tree<A, B>, newLeft: Tree<A, B>?, newRight: Tree<A, B>?): Tree<A, B>? = run {
tailrec
fun findDepth(zipper: KList<Tree<A, B>>, depth: Int): KList<Tree<A, B>> =
if (zipper === KList.Nil) {
throw Exception("Defect: unexpected empty zipper while computing range")
} else if (zipper.hd is BlackTree<A, B>) {
if (depth == 1) zipper else findDepth(zipper.tl, depth - 1)
} else {
findDepth(zipper.tl, depth)
}
// Blackening the smaller tree avoids balancing problems on union;
// this can't be done later, though, or it would change the result of compareDepth
val blkNewLeft = blacken(newLeft)
val blkNewRight = blacken(newRight)
val (zipper, levelled, leftMost, smallerDepth) = compareDepth(blkNewLeft, blkNewRight)
if (levelled) {
BlackTree(tree.key, tree.value, blkNewLeft, blkNewRight)
} else {
val zipFrom = findDepth(zipper, smallerDepth)
val union: Tree<A, B> = if (leftMost) {
RedTree(tree.key, tree.value, blkNewLeft, zipFrom.hd)
} else {
RedTree(tree.key, tree.value, zipFrom.hd, blkNewRight)
}
val zippedTree = zipFrom.tl.foldLeft(union) { acc, node ->
if (leftMost)
balanceLeft(isBlackTree(node), node.key, node.value, acc, node.right)
else
balanceRight(isBlackTree(node), node.key, node.value, node.left, acc)
}
zippedTree
}
}
/*
* Forcing direct fields access using the @inline annotation helps speed up
* various operations (especially smallest/greatest and update/delete).
*
* Unfortunately the direct field access is not guaranteed to work (but
* works on the current implementation of the Scala compiler).
*
* An alternative is to implement the these classes using plain old Java code...
*/
sealed class Tree<A, out B>(
val key: A,
val value: B,
val left: Tree<A, B>?,
val right: Tree<A, B>?
) {
val count: Int = 1 + RedBlackTree.count(left) + RedBlackTree.count(right)
abstract val black: Tree<A, B>
abstract val red: Tree<A, B>
class RedTree<A, out B>(
key: A,
value: B,
left: Tree<A, B>?,
right: Tree<A, B>?
) : Tree<A, B>(key, value, left, right) {
companion object {
fun <A, B> invoke(key: A, value: B, left: Tree<A, B>?, right: Tree<A, B>?) = RedTree(key, value, left, right)
}
override val black: Tree<A, B>
get() = BlackTree(key, value, left, right)
override val red: Tree<A, B>
get() = this
override fun toString(): String = "RedTree($key, $value, $left, $right)"
}
class BlackTree<A, out B>(
key: A,
value: B,
left: Tree<A, B>?,
right: Tree<A, B>?
) : Tree<A, B>(key, value, left, right) {
companion object {
fun <A, B> invoke(key: A, value: B, left: Tree<A, B>?, right: Tree<A, B>?) = BlackTree(key, value, left, right)
}
override val black: Tree<A, B>
get() = this
override val red: Tree<A, B>
get() = RedTree(key, value, left, right)
override fun toString(): String = "BlackTree($key, $value, $left, $right)"
}
}
} | mit | ae1ff09f840a362b4dd7b4b599f9a052 | 47.898004 | 198 | 0.549746 | 3.279595 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/property.kt | 1 | 2628 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import java.net.URL
import org.apache.tools.ant.taskdefs.Property
import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun Ant.property(
name: String? = null,
value: String? = null,
location: String? = null,
resource: String? = null,
file: String? = null,
url: String? = null,
environment: String? = null,
classpath: String? = null,
classpathref: String? = null,
prefix: String? = null,
prefixvalues: Boolean? = null,
relative: Boolean? = null,
basedir: String? = null,
nested: (KProperty.() -> Unit)? = null)
{
Property().execute("property") { task ->
if (name != null)
task.setName(name)
if (value != null)
task.setValue(value)
if (location != null)
task.setLocation(project.resolveFile(location))
if (resource != null)
task.setResource(resource)
if (file != null)
task.setFile(project.resolveFile(file))
if (url != null)
task.setUrl(URL(url))
if (environment != null)
task.setEnvironment(environment)
if (classpath != null)
task.setClasspath(Path(project, classpath))
if (classpathref != null)
task.setClasspathRef(Reference(project, classpathref))
if (prefix != null)
task.setPrefix(prefix)
if (prefixvalues != null)
task.setPrefixValues(prefixvalues)
if (relative != null)
task.setRelative(relative)
if (basedir != null)
task.setBasedir(project.resolveFile(basedir))
if (nested != null)
nested(KProperty(task))
}
}
class KProperty(val component: Property) {
fun classpath(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) {
component.createClasspath().apply {
component.project.setProjectReference(this)
_init(location, path, cache, nested)
}
}
operator fun String.unaryPlus() = component.addText(this)
}
| apache-2.0 | 4d5c0cc82f8f8aea643b9974869afd41 | 30.285714 | 124 | 0.662861 | 3.585266 | false | false | false | false |
jhavatar/mythos | kotlinexample/src/main/java/io/chthonic/mythos/kotlinexample/ui/presenters/FusPresenter.kt | 1 | 754 | package io.chthonic.mythos.kotlinexample.ui.presenters
import android.os.Bundle
import io.chthonic.mythos.kotlinexample.ui.vus.FusVu
/**
* Created by jhavatar on 3/3/2016.
*/
class FusPresenter : BasePresenter<FusVu>() {
var showRo: Boolean = true
var showDah: Boolean = true
override fun onLink(vu: FusVu, inState: Bundle?, args: Bundle) {
super.onLink(vu, inState, args)
vu.updateRoDisplay(showRo)
vu.updateDahDisplay(showDah)
vu.toggleRoListener = {
showRo = !showRo
this.vu?.updateRoDisplay(showRo)
}
vu.toggleDahListener = {
showDah = !showDah
this.vu?.updateDahDisplay(showDah)
}
vu.setText(getText("FUS"))
}
} | apache-2.0 | 6b89ac8b83cde529b16b981de165b51f | 23.354839 | 68 | 0.625995 | 3.57346 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/accessors/KotlinMetadataIntegrationTest.kt | 1 | 3134 | /*
* Copyright 2018 the original author or authors.
*
* 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.gradle.kotlin.dsl.accessors
import kotlinx.metadata.jvm.KotlinClassHeader
import kotlinx.metadata.jvm.KotlinClassMetadata
import kotlinx.metadata.jvm.KotlinModuleMetadata
import org.gradle.api.Action
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.kotlin.dsl.fixtures.TestWithTempFiles
import org.gradle.kotlin.dsl.fixtures.testRuntimeClassPath
import org.gradle.kotlin.dsl.support.compileToDirectory
import org.gradle.kotlin.dsl.support.loggerFor
import org.junit.Test
/**
* This definition is here so its metadata can be inspected.
*/
@Suppress("unused_parameter")
fun <T : Dependency> DependencyHandler.foo(
dependency: T,
action: Action<T>
): T = TODO()
class KotlinMetadataIntegrationTest : TestWithTempFiles() {
@Test
fun `extract file metadata`() {
val fileFacadeHeader = javaClass.classLoader
.loadClass(javaClass.name + "Kt")
.readKotlinClassHeader()
val metadata = KotlinClassMetadata.read(fileFacadeHeader) as KotlinClassMetadata.FileFacade
metadata.accept(KotlinMetadataPrintingVisitor.ForPackage)
}
@Test
fun `extract module metadata`() {
val outputDir = newFolder("main")
val moduleName = outputDir.name
require(
compileToDirectory(
outputDir,
moduleName,
listOf(
newFile("ConfigurationAccessors.kt", """
package org.gradle.kotlin.dsl
import org.gradle.api.artifacts.*
val ConfigurationContainer.api: Configuration
inline get() = TODO()
""")
),
loggerFor<KotlinMetadataIntegrationTest>(),
testRuntimeClassPath.asFiles
)
)
val bytes = outputDir.resolve("META-INF/$moduleName.kotlin_module").readBytes()
val metadata = KotlinModuleMetadata.read(bytes)!!
metadata.accept(KotlinMetadataPrintingVisitor.ForModule)
}
private
fun Class<*>.readKotlinClassHeader(): KotlinClassHeader =
getAnnotation(Metadata::class.java).run {
KotlinClassHeader(
kind,
metadataVersion,
bytecodeVersion,
data1,
data2,
extraString,
packageName,
extraInt
)
}
}
| apache-2.0 | 5265534e64297d79c57fcca1671f6559 | 30.029703 | 99 | 0.645501 | 4.966719 | false | true | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/accessors/Emitter.kt | 1 | 6362 | /*
* Copyright 2018 the original author or authors.
*
* 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.gradle.kotlin.dsl.accessors
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.artifacts.Configuration
import org.gradle.kotlin.dsl.concurrent.IO
import org.gradle.kotlin.dsl.concurrent.writeFile
import org.gradle.kotlin.dsl.support.bytecode.InternalName
import org.gradle.kotlin.dsl.support.bytecode.beginFileFacadeClassHeader
import org.gradle.kotlin.dsl.support.bytecode.beginPublicClass
import org.gradle.kotlin.dsl.support.bytecode.closeHeader
import org.gradle.kotlin.dsl.support.bytecode.endKotlinClass
import org.gradle.kotlin.dsl.support.bytecode.moduleFileFor
import org.gradle.kotlin.dsl.support.bytecode.moduleMetadataBytesFor
import java.io.File
internal
fun IO.emitAccessorsFor(
projectSchema: ProjectSchema<TypeAccessibility>,
srcDir: File,
binDir: File?,
outputPackage: OutputPackage,
format: AccessorFormat
): List<InternalName> {
makeAccessorOutputDirs(srcDir, binDir, outputPackage.path)
val emittedClassNames =
accessorsFor(projectSchema).map { accessor ->
emitClassFor(
accessor,
srcDir,
binDir,
outputPackage,
format
)
}.toList()
if (binDir != null) {
writeFile(
moduleFileFor(binDir),
moduleMetadataBytesFor(emittedClassNames)
)
}
return emittedClassNames
}
internal
fun IO.makeAccessorOutputDirs(srcDir: File, binDir: File?, packagePath: String) = io {
srcDir.resolve(packagePath).mkdirs()
binDir?.apply {
resolve(packagePath).mkdirs()
resolve("META-INF").mkdir()
}
}
internal
data class OutputPackage(val name: String) {
val path by lazy {
name.replace('.', '/')
}
}
private
fun IO.emitClassFor(
accessor: Accessor,
srcDir: File,
binDir: File?,
outputPackage: OutputPackage,
format: AccessorFormat
): InternalName {
val (simpleClassName, fragments) = fragmentsFor(accessor)
val className = InternalName("${outputPackage.path}/$simpleClassName")
val sourceCode = mutableListOf<String>()
fun collectSourceFragment(source: String) {
sourceCode.add(format(source))
}
if (binDir != null) {
writeAccessorsBytecodeTo(
binDir,
className,
fragments,
::collectSourceFragment
)
} else {
for ((source, _, _, _) in fragments) {
collectSourceFragment(source)
}
}
writeAccessorsTo(
sourceFileFor(className, srcDir),
sourceCode,
importsRequiredBy(accessor),
outputPackage.name
)
return className
}
private
fun sourceFileFor(className: InternalName, srcDir: File) =
srcDir.resolve("${className.value.removeSuffix("Kt")}.kt")
private
fun IO.writeAccessorsBytecodeTo(
binDir: File,
className: InternalName,
fragments: Sequence<AccessorFragment>,
collectSourceFragment: (String) -> Unit
) {
val metadataWriter = beginFileFacadeClassHeader()
val classWriter = beginPublicClass(className)
for ((source, bytecode, metadata, signature) in fragments) {
collectSourceFragment(source)
MetadataFragmentScope(signature, metadataWriter).run(metadata)
BytecodeFragmentScope(signature, classWriter).run(bytecode)
}
val classHeader = metadataWriter.closeHeader()
val classBytes = classWriter.endKotlinClass(classHeader)
val classFile = binDir.resolve("$className.class")
writeFile(classFile, classBytes)
}
private
fun importsRequiredBy(accessor: Accessor): List<String> = accessor.run {
when (this) {
is Accessor.ForExtension -> importsRequiredBy(spec.receiver, spec.type)
is Accessor.ForConvention -> importsRequiredBy(spec.receiver, spec.type)
is Accessor.ForTask -> importsRequiredBy(spec.type)
is Accessor.ForContainerElement -> importsRequiredBy(spec.receiver, spec.type)
else -> emptyList()
}
}
private
fun importsRequiredBy(vararg candidateTypes: TypeAccessibility): List<String> =
importsRequiredBy(candidateTypes.asList())
internal
sealed class Accessor {
data class ForConfiguration(val name: AccessorNameSpec) : Accessor()
data class ForExtension(val spec: TypedAccessorSpec) : Accessor()
data class ForConvention(val spec: TypedAccessorSpec) : Accessor()
data class ForContainerElement(val spec: TypedAccessorSpec) : Accessor()
data class ForTask(val spec: TypedAccessorSpec) : Accessor()
}
internal
fun accessorsFor(schema: ProjectSchema<TypeAccessibility>): Sequence<Accessor> = sequence {
schema.run {
AccessorScope().run {
yieldAll(uniqueAccessorsFor(extensions).map(Accessor::ForExtension))
yieldAll(uniqueAccessorsFor(conventions).map(Accessor::ForConvention))
yieldAll(uniqueAccessorsFor(tasks).map(Accessor::ForTask))
yieldAll(uniqueAccessorsFor(containerElements).map(Accessor::ForContainerElement))
val configurationNames = configurations.map(::AccessorNameSpec).asSequence()
yieldAll(
uniqueAccessorsFrom(
configurationNames.map(::configurationAccessorSpec)
).map(Accessor::ForContainerElement)
)
yieldAll(configurationNames.map(Accessor::ForConfiguration))
}
}
}
private
fun configurationAccessorSpec(nameSpec: AccessorNameSpec) =
TypedAccessorSpec(
accessibleType<NamedDomainObjectContainer<Configuration>>(),
nameSpec,
accessibleType<Configuration>()
)
private
inline fun <reified T> accessibleType() =
TypeAccessibility.Accessible(SchemaType.of<T>())
| apache-2.0 | d66c54b2aa7426c871c34199db3fd5aa | 27.657658 | 94 | 0.696951 | 4.531339 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/util/LazyGridLayout.kt | 1 | 924 | package app.lawnchair.ui.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
class LazyGridLayout(
val minWidth: Dp,
private val gapWidth: Dp,
private val density: Density
) {
private val _numColumns = mutableStateOf(0)
val numColumns: State<Int> = _numColumns
@Composable
fun onSizeChanged() = Modifier.onSizeChanged {
with(density) {
val minWidth = minWidth.roundToPx()
val gapWidth = gapWidth.roundToPx()
val availableWidth = (it.width - minWidth).coerceAtLeast(0)
val additionalCols = availableWidth / (minWidth + gapWidth)
_numColumns.value = 1 + additionalCols
}
}
}
| gpl-3.0 | 9e7fe87eb02ede75235216da86aa0efb | 30.862069 | 71 | 0.70671 | 4.379147 | false | false | false | false |
fython/PackageTracker | mobile/src/main/kotlin/info/papdt/express/helper/ui/items/PackageItemViewBinder.kt | 1 | 9205 | package info.papdt.express.helper.ui.items
import android.app.Activity
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import androidx.core.content.ContextCompat
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import android.text.style.ForegroundColorSpan
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import de.hdodenhof.circleimageview.CircleImageView
import info.papdt.express.helper.R
import info.papdt.express.helper.dao.PackageDatabase
import info.papdt.express.helper.dao.SRDatabase
import info.papdt.express.helper.event.EventIntents
import info.papdt.express.helper.model.Category
import info.papdt.express.helper.model.Kuaidi100Package
import info.papdt.express.helper.model.MaterialIcon
import info.papdt.express.helper.support.Spanny
import info.papdt.express.helper.support.isFontProviderEnabled
import info.papdt.express.helper.support.localBroadcastManager
import info.papdt.express.helper.ui.DetailsActivity
import kotlinx.coroutines.runBlocking
import me.drakeet.multitype.ItemViewBinder
import moe.feng.kotlinyan.common.set
import java.text.DateFormat
object PackageItemViewBinder
: ItemViewBinder<Kuaidi100Package, PackageItemViewBinder.ViewHolder>() {
private var statusTitleColor: Int = 0
private var statusSubtextColor = -1
private var STATUS_STRING_ARRAY: Array<String>? = null
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder {
if (STATUS_STRING_ARRAY == null) {
STATUS_STRING_ARRAY = parent.context.resources
.getStringArray(R.array.item_status_description)
}
if (statusSubtextColor == -1) {
statusTitleColor = ContextCompat.getColor(parent.context,
R.color.package_list_status_title_color)
statusSubtextColor = ContextCompat.getColor(parent.context,
R.color.package_list_status_subtext_color)
}
return ViewHolder(inflater.inflate(R.layout.item_home_package, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, item: Kuaidi100Package) {
val context = holder.itemView.context
holder.itemData = item
if (item.name?.isNotEmpty() == true) {
holder.titleText.text = item.name
} else {
holder.titleText.text = item.companyChineseName
}
if (item.data != null && item.data!!.size > 0) {
val status = item.data!![0]
val spanny = Spanny(STATUS_STRING_ARRAY!![item.getState()], ForegroundColorSpan(statusTitleColor))
.append(" - " + status.context, ForegroundColorSpan(statusSubtextColor))
holder.descText.text = spanny
holder.timeText.text = status.getTimeDate()?.let {
DateFormat.getDateTimeInstance().format(it)
} ?: status.ftime
holder.timeText.visibility = View.VISIBLE
} else {
/** Set placeholder when cannot get data */
holder.descText.setText(R.string.item_text_cannot_get_package_status)
holder.timeText.visibility = View.GONE
}
/** Set bold text when unread */
holder.descText.paint.isFakeBoldText = item.unreadNew
holder.titleText.paint.isFakeBoldText = item.unreadNew || !isFontProviderEnabled
/** Set CircleImageView */
holder.bigCharView.apply {
runBlocking {
val category: Category? = item.categoryTitle?.let {
SRDatabase.categoryDao.get(it)
}
if (category?.iconCode != null) {
typeface = MaterialIcon.iconTypeface
paint.isFakeBoldText = false
text = category.iconCode
} else {
typeface = Typeface.DEFAULT
paint.isFakeBoldText = true
if (item.name?.isNotEmpty() == true) {
text = item.getFirstChar()
} else if (item.companyChineseName?.isNotEmpty() == true) {
text = item.companyChineseName!!.substring(0, 1).toUpperCase()
}
}
}
}
item.getPaletteFromId().let {
holder.logoView.setImageDrawable(ColorDrawable(it.getPackageIconBackground(context)))
holder.bigCharView.setTextColor(it.getPackageIconForeground(context))
holder.statusIcon.imageTintList = ColorStateList.valueOf(it.getStatusIconTint(context))
}
holder.statusIcon.setImageResource(when (item.getState()) {
Kuaidi100Package.STATUS_FAILED -> R.drawable.ic_error_outline_black_24dp
Kuaidi100Package.STATUS_DELIVERED -> R.drawable.ic_done_black_24dp
Kuaidi100Package.STATUS_RETURNED -> R.drawable.ic_done_black_24dp
Kuaidi100Package.STATUS_NORMAL -> R.drawable.ic_local_shipping_black_24dp
Kuaidi100Package.STATUS_ON_THE_WAY -> R.drawable.ic_local_shipping_black_24dp
Kuaidi100Package.STATUS_RETURNING -> R.drawable.ic_local_shipping_black_24dp
Kuaidi100Package.STATUS_OTHER -> R.drawable.ic_help_outline_black_24dp
else -> R.drawable.ic_help_outline_black_24dp
})
}
class ViewHolder(itemView: View)
: RecyclerView.ViewHolder(itemView), View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
internal val logoView: CircleImageView = itemView.findViewById(R.id.iv_logo)
internal val titleText: AppCompatTextView = itemView.findViewById(R.id.tv_title)
internal val descText: AppCompatTextView = itemView.findViewById(R.id.tv_other)
internal val timeText: AppCompatTextView = itemView.findViewById(R.id.tv_time)
internal val bigCharView: TextView = itemView.findViewById(R.id.tv_first_char)
internal val statusIcon: ImageView = itemView.findViewById(R.id.status_icon)
val containerView: View = itemView.findViewById(R.id.item_container)
var itemData: Kuaidi100Package? = null
init {
containerView.setOnCreateContextMenuListener(this)
containerView.setOnClickListener {
if (itemData!!.unreadNew) {
itemData!!.unreadNew = false
val database = PackageDatabase.getInstance(itemView.context)
val position = database.indexOf(itemData!!)
if (position != -1) {
database[position] = itemData!!
adapter.notifyItemChanged(adapterPosition)
}
}
DetailsActivity.launch(it.context as Activity, itemData!!)
}
}
override fun onCreateContextMenu(menu: ContextMenu,
v: View, info: ContextMenu.ContextMenuInfo?) {
menu.setHeaderTitle(itemData!!.name)
val menuItems = mutableListOf<MenuItem>()
if (!itemData!!.unreadNew) {
menuItems += menu.add(Menu.NONE, R.id.action_set_unread, 0, R.string.action_set_unread)
}
menuItems += menu.add(Menu.NONE, R.id.action_share, 0, R.string.action_share)
menuItems += menu.add(Menu.NONE, R.id.action_delete, 0, R.string.action_remove)
menuItems.forEach { it.setOnMenuItemClickListener(this) }
}
override fun onMenuItemClick(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_set_unread -> {
val database = PackageDatabase.getInstance(itemView.context)
itemData!!.unreadNew = true
val position = database.indexOf(itemData!!)
if (position != -1) {
database[position] = itemData!!
adapter.notifyItemChanged(adapterPosition)
}
true
}
R.id.action_share -> {
val text = itemView.context.getString(R.string.share_info_format,
itemData!!.name,
itemData!!.number,
itemData!!.companyChineseName,
if (itemData!!.data!!.size > 0) itemData!!.data!![0].context else "Unknown",
if (itemData!!.data!!.size > 0) itemData!!.data!![0].time else ""
)
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent[Intent.EXTRA_TEXT] = text
itemView.context.startActivity(Intent.createChooser(
intent, itemView.context.getString(R.string.dialog_share_title)))
true
}
R.id.action_delete -> {
itemData?.let { EventIntents.requestDeletePackage(it) }
?.let { itemView.context.localBroadcastManager.sendBroadcast(it) }
true
}
else -> false
}
}
} | gpl-3.0 | 4abd22cc908dee9ffb4b36009e773f5b | 44.574257 | 113 | 0.624117 | 4.663121 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/comment/CommentsRestClient.kt | 2 | 8812 | package org.wordpress.android.fluxc.network.rest.wpcom.comment
import android.content.Context
import com.android.volley.RequestQueue
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.endpoint.WPCOMREST
import org.wordpress.android.fluxc.model.CommentStatus
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.comments.CommentsMapper
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.common.comments.CommentsApiPayload
import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentWPComRestResponse.CommentsWPComRestResponse
import org.wordpress.android.fluxc.persistence.comments.CommentEntityList
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.utils.CommentErrorUtilsWrapper
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class CommentsRestClient @Inject constructor(
appContext: Context?,
dispatcher: Dispatcher,
@Named("regular") requestQueue: RequestQueue,
accessToken: AccessToken,
userAgent: UserAgent,
private val wpComGsonRequestBuilder: WPComGsonRequestBuilder,
private val commentErrorUtilsWrapper: CommentErrorUtilsWrapper,
private val commentsMapper: CommentsMapper
) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) {
suspend fun fetchCommentsPage(
site: SiteModel,
number: Int,
offset: Int,
status: CommentStatus
): CommentsApiPayload<CommentEntityList> {
val url = WPCOMREST.sites.site(site.siteId).comments.urlV1_1
val params = mutableMapOf(
"status" to status.toString(),
"offset" to offset.toString(),
"number" to number.toString(),
"force" to "wpcom"
)
val response = wpComGsonRequestBuilder.syncGetRequest(
this,
url,
params,
CommentsWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(response.data.comments?.map { commentDto ->
commentsMapper.commentDtoToEntity(commentDto, site)
} ?: listOf())
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun pushComment(site: SiteModel, comment: CommentEntity): CommentsApiPayload<CommentEntity> {
val request = mutableMapOf(
"content" to comment.content.orEmpty(),
"date" to comment.datePublished.orEmpty(),
"status" to comment.status.orEmpty()
)
return updateCommentFields(site, comment, request)
}
suspend fun updateEditComment(site: SiteModel, comment: CommentEntity): CommentsApiPayload<CommentEntity> {
val request = mutableMapOf(
"content" to comment.content.orEmpty(),
"author" to comment.authorName.orEmpty(),
"author_email" to comment.authorEmail.orEmpty(),
"author_url" to comment.authorUrl.orEmpty()
)
return updateCommentFields(site, comment, request)
}
private suspend fun updateCommentFields(
site: SiteModel,
comment: CommentEntity,
request: Map<String, String>
): CommentsApiPayload<CommentEntity> {
val url = WPCOMREST.sites.site(site.siteId).comments.comment(comment.remoteCommentId).urlV1_1
val response = wpComGsonRequestBuilder.syncPostRequest(
this,
url,
null,
request,
CommentWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(commentsMapper.commentDtoToEntity(response.data, site))
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun fetchComment(site: SiteModel, remoteCommentId: Long): CommentsApiPayload<CommentEntity> {
val url = WPCOMREST.sites.site(site.siteId).comments.comment(remoteCommentId).urlV1_1
val response = wpComGsonRequestBuilder.syncGetRequest(
this,
url,
mapOf(),
CommentWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(commentsMapper.commentDtoToEntity(response.data, site))
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun deleteComment(site: SiteModel, remoteCommentId: Long): CommentsApiPayload<CommentEntity> {
val url = WPCOMREST.sites.site(site.siteId).comments.comment(remoteCommentId).delete.urlV1_1
val response = wpComGsonRequestBuilder.syncPostRequest(
this,
url,
null,
null,
CommentWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(commentsMapper.commentDtoToEntity(response.data, site))
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun createNewReply(
site: SiteModel,
remoteCommentId: Long,
replayContent: String?
): CommentsApiPayload<CommentEntity> {
val url = WPCOMREST.sites.site(site.siteId).comments.comment(remoteCommentId).replies.new_.urlV1_1
val request = mutableMapOf(
"content" to replayContent.orEmpty()
)
val response = wpComGsonRequestBuilder.syncPostRequest(
this,
url,
null,
request,
CommentWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(commentsMapper.commentDtoToEntity(response.data, site))
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun createNewComment(
site: SiteModel,
remotePostId: Long,
content: String?
): CommentsApiPayload<CommentEntity> {
val url = WPCOMREST.sites.site(site.siteId).posts.post(remotePostId).replies.new_.urlV1_1
val request = mutableMapOf(
"content" to content.orEmpty()
)
val response = wpComGsonRequestBuilder.syncPostRequest(
this,
url,
null,
request,
CommentWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(commentsMapper.commentDtoToEntity(response.data, site))
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
suspend fun likeComment(
site: SiteModel,
remoteCommentId: Long,
isLike: Boolean
): CommentsApiPayload<CommentLikeWPComRestResponse> {
val url = if (isLike) {
WPCOMREST.sites.site(site.siteId).comments.comment(remoteCommentId).likes.new_.urlV1_1
} else {
WPCOMREST.sites.site(site.siteId).comments.comment(remoteCommentId).likes.mine.delete.urlV1_1
}
val response = wpComGsonRequestBuilder.syncPostRequest(
this,
url,
null,
null,
CommentLikeWPComRestResponse::class.java
)
return when (response) {
is Success -> {
CommentsApiPayload(response.data)
}
is Error -> {
CommentsApiPayload(commentErrorUtilsWrapper.networkToCommentError(response.error))
}
}
}
}
| gpl-2.0 | 4452b80e7c53aa6555d5a1fdfb584f5d | 35.263374 | 112 | 0.629823 | 5.038308 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/sdk/add/PyAddSdkDialog.kt | 1 | 10957 | /*
* 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.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Splitter
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.ui.popup.ListItemDescriptorAdapter
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.JBCardLayout
import com.intellij.ui.components.JBList
import com.intellij.ui.popup.list.GroupedItemsListRenderer
import com.intellij.util.PlatformUtils
import com.intellij.util.ui.JBUI
import com.jetbrains.python.sdk.PreferredSdkComparator
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.add.PyAddSdkDialog.Companion.create
import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.*
import com.jetbrains.python.sdk.detectVirtualEnvs
import com.jetbrains.python.sdk.isAssociatedWithProject
import icons.PythonIcons
import java.awt.CardLayout
import java.awt.event.ActionEvent
import javax.swing.Action
import javax.swing.JComponent
import javax.swing.JPanel
/**
* The dialog may look like the normal dialog with OK, Cancel and Help buttons
* or the wizard dialog with Next, Previous, Finish, Cancel and Help buttons.
*
* Use [create] to instantiate the dialog.
*
* @author vlan
*/
class PyAddSdkDialog private constructor(private val project: Project?,
private val existingSdks: List<Sdk>,
private val newProjectPath: String?) : DialogWrapper(project) {
/**
* This is the main panel that supplies sliding effect for the wizard states.
*/
private val mainPanel: JPanel = JPanel(JBCardLayout())
private var selectedPanel: PyAddSdkView? = null
private var panels: List<PyAddSdkView> = emptyList()
init {
title = "Add Python Interpreter"
}
override fun createCenterPanel(): JComponent {
val sdks = existingSdks
.filter { it.sdkType is PythonSdkType && !PythonSdkType.isInvalid(it) }
.sortedWith(PreferredSdkComparator())
val panels = arrayListOf<PyAddSdkView>(createVirtualEnvPanel(project, sdks, newProjectPath),
createAnacondaPanel(project),
PyAddSystemWideInterpreterPanel(existingSdks))
val extendedPanels = PyAddSdkProvider.EP_NAME.extensions
.map { it.createView(project = project, newProjectPath = newProjectPath, existingSdks = existingSdks) }
.mapNotNull { it }
panels.addAll(extendedPanels)
mainPanel.add(SPLITTER_COMPONENT_CARD_PANE, createCardSplitter(panels))
return mainPanel
}
private var navigationPanelCardLayout: CardLayout? = null
private var southPanel: JPanel? = null
override fun createSouthPanel(): JComponent {
val regularDialogSouthPanel = super.createSouthPanel()
val wizardDialogSouthPanel = createWizardSouthPanel()
navigationPanelCardLayout = CardLayout()
val result = JPanel(navigationPanelCardLayout).apply {
add(regularDialogSouthPanel, REGULAR_CARD_PANE)
add(wizardDialogSouthPanel, WIZARD_CARD_PANE)
}
southPanel = result
return result
}
private fun createWizardSouthPanel(): JPanel {
assert(value = style != DialogStyle.COMPACT,
lazyMessage = { "${PyAddSdkDialog::class.java} is not ready for ${DialogStyle.COMPACT} dialog style" })
return doCreateSouthPanel(leftButtons = listOf(),
rightButtons = listOf(previousButton.value, nextButton.value,
cancelButton.value))
}
private val nextAction: Action = object : DialogWrapperAction("Next") {
override fun doAction(e: ActionEvent) {
selectedPanel?.let {
if (it.actions.containsKey(NEXT)) onNext()
else if (it.actions.containsKey(FINISH)) {
onFinish()
}
}
}
}
private val nextButton = lazy { createJButtonForAction(nextAction) }
private val previousAction = object : DialogWrapperAction("Previous") {
override fun doAction(e: ActionEvent) = onPrevious()
}
private val previousButton = lazy { createJButtonForAction(previousAction) }
private val cancelButton = lazy { createJButtonForAction(cancelAction) }
override fun postponeValidation() = false
override fun doValidateAll(): List<ValidationInfo> = selectedPanel?.validateAll() ?: emptyList()
fun getOrCreateSdk(): Sdk? = selectedPanel?.getOrCreateSdk()
private fun createCardSplitter(panels: List<PyAddSdkView>): Splitter {
this.panels = panels
return Splitter(false, 0.25f).apply {
val cardLayout = CardLayout()
val cardPanel = JPanel(cardLayout).apply {
preferredSize = JBUI.size(640, 480)
for (panel in panels) {
add(panel.component, panel.panelName)
panel.addStateListener(object : PyAddSdkStateListener {
override fun onComponentChanged() {
show(mainPanel, panel.component)
selectedPanel?.let { updateWizardActionButtons(it) }
}
override fun onActionsStateChanged() {
selectedPanel?.let { updateWizardActionButtons(it) }
}
})
}
}
val cardsList = JBList(panels).apply {
val descriptor = object : ListItemDescriptorAdapter<PyAddSdkView>() {
override fun getTextFor(value: PyAddSdkView) = StringUtil.toTitleCase(value.panelName)
override fun getIconFor(value: PyAddSdkView) = value.icon
}
cellRenderer = object : GroupedItemsListRenderer<PyAddSdkView>(descriptor) {
override fun createItemComponent() = super.createItemComponent().apply {
border = JBUI.Borders.empty(4, 4, 4, 10)
}
}
addListSelectionListener {
selectedPanel = selectedValue
cardLayout.show(cardPanel, selectedValue.panelName)
southPanel?.let {
if (selectedValue.actions.containsKey(NEXT)) {
navigationPanelCardLayout?.show(it, WIZARD_CARD_PANE)
rootPane.defaultButton = nextButton.value
updateWizardActionButtons(selectedValue)
}
else {
navigationPanelCardLayout?.show(it, REGULAR_CARD_PANE)
rootPane.defaultButton = getButton(okAction)
}
}
selectedValue.onSelected()
}
selectedPanel = panels.getOrNull(0)
selectedIndex = 0
}
firstComponent = cardsList
secondComponent = cardPanel
}
}
private fun createVirtualEnvPanel(project: Project?,
existingSdks: List<Sdk>,
newProjectPath: String?): PyAddSdkPanel {
val newVirtualEnvPanel = when {
allowCreatingNewEnvironments(project) -> PyAddNewVirtualEnvPanel(project, existingSdks, newProjectPath)
else -> null
}
val existingVirtualEnvPanel = PyAddExistingVirtualEnvPanel(project, existingSdks, newProjectPath)
val panels = listOf(newVirtualEnvPanel,
existingVirtualEnvPanel)
.filterNotNull()
val defaultPanel = when {
detectVirtualEnvs(project, existingSdks).any { it.isAssociatedWithProject(project) } -> existingVirtualEnvPanel
newVirtualEnvPanel != null -> newVirtualEnvPanel
else -> existingVirtualEnvPanel
}
return PyAddSdkGroupPanel("Virtualenv environment", PythonIcons.Python.Virtualenv, panels, defaultPanel)
}
private fun createAnacondaPanel(project: Project?): PyAddSdkPanel {
val newCondaEnvPanel = when {
allowCreatingNewEnvironments(project) -> PyAddNewCondaEnvPanel(project, existingSdks, newProjectPath)
else -> null
}
val panels = listOf(newCondaEnvPanel,
PyAddExistingCondaEnvPanel(project, existingSdks, newProjectPath))
.filterNotNull()
return PyAddSdkGroupPanel("Conda environment", PythonIcons.Python.Anaconda, panels, panels[0])
}
/**
* Navigates to the next step of the current wizard view.
*/
private fun onNext() {
selectedPanel?.let {
it.next()
// sliding effect
swipe(mainPanel, it.component, JBCardLayout.SwipeDirection.FORWARD)
updateWizardActionButtons(it)
}
}
/**
* Navigates to the previous step of the current wizard view.
*/
private fun onPrevious() {
selectedPanel?.let {
it.previous()
// sliding effect
if (it.actions.containsKey(PREVIOUS)) {
val stepContent = it.component
val stepContentName = stepContent.hashCode().toString()
(mainPanel.layout as JBCardLayout).swipe(mainPanel, stepContentName, JBCardLayout.SwipeDirection.BACKWARD)
}
else {
// this is the first wizard step
(mainPanel.layout as JBCardLayout).swipe(mainPanel, SPLITTER_COMPONENT_CARD_PANE, JBCardLayout.SwipeDirection.BACKWARD)
}
updateWizardActionButtons(it)
}
}
private fun onFinish() {
try {
selectedPanel?.finish()
}
catch (e: Exception) {
Messages.showErrorDialog(e.localizedMessage, "Error")
return
}
doOKAction()
}
private fun updateWizardActionButtons(it: PyAddSdkView) {
previousButton.value.isEnabled = false
it.actions.forEach { (action, isEnabled) ->
val actionButton = when (action) {
PREVIOUS -> previousButton.value
NEXT -> nextButton.value.apply { text = "Next" }
FINISH -> nextButton.value.apply { text = "Finish" }
else -> null
}
actionButton?.isEnabled = isEnabled
}
}
companion object {
private fun allowCreatingNewEnvironments(project: Project?) =
project != null || !PlatformUtils.isPyCharm() || PlatformUtils.isPyCharmEducational()
private const val SPLITTER_COMPONENT_CARD_PANE = "Splitter"
private const val REGULAR_CARD_PANE = "Regular"
private const val WIZARD_CARD_PANE = "Wizard"
@JvmStatic
fun create(project: Project?, existingSdks: List<Sdk>, newProjectPath: String?): PyAddSdkDialog {
return PyAddSdkDialog(project = project, existingSdks = existingSdks, newProjectPath = newProjectPath).apply { init() }
}
}
}
| apache-2.0 | fd7ab04b36c42948dac1e2d1c582cf5c | 34.80719 | 127 | 0.681117 | 4.980455 | false | false | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/bottomsheet_dialog/menu_items/MenuItemsFactory.kt | 1 | 1721 | /*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.bottomsheet_dialog.menu_items
import com.github.vase4kin.teamcityapp.bottomsheet_dialog.model.BottomSheetItem
/**
* Menu items factory
*/
interface MenuItemsFactory {
/**
* @return list of menu items
*/
fun createMenuItems(): List<BottomSheetItem>
companion object {
/**
* Default menu type
*/
const val TYPE_DEFAULT = 0
/**
* Branch menu type
*/
const val TYPE_BRANCH = 1
/**
* Artifact default menu type
*/
const val TYPE_ARTIFACT_DEFAULT = 2
/**
* Artifact browser menu type
*/
const val TYPE_ARTIFACT_BROWSER = 3
/**
* Artifact folder menu type
*/
const val TYPE_ARTIFACT_FOLDER = 4
/**
* Artifact full menu type
*/
const val TYPE_ARTIFACT_FULL = 5
/**
* Build type menu type
*/
const val TYPE_BUILD_TYPE = 6
/**
* Project menu type
*/
const val TYPE_PROJECT = 7
}
}
| apache-2.0 | ac0795e197f98b33ce0458398220954f | 22.575342 | 79 | 0.596165 | 4.540897 | false | false | false | false |
google/ksp | test-utils/testData/api/builtInTypes.kt | 1 | 1337 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// WITH_RUNTIME
// TEST PROCESSOR: BuiltInTypesProcessor
// EXPECTED:
// Annotation: OK
// Any: OK
// Array<*>: OK
// Boolean: OK
// Byte: OK
// Char: OK
// Double: OK
// Float: OK
// Int: OK
// Iterable<*>: OK
// Long: OK
// Nothing: OK
// Number: OK
// Short: OK
// String: OK
// Unit: OK
// END
val a: Any = 0
val b: Unit = Unit
val c: Number = 0
val d: Byte = 0
val e: Short = 0
val f: Int = 0
val g: Long = 0
val h: Float = 0.0f
val i: Double = 0.0
val j: Char = '0'
val k: Boolean = false
val l: String = ""
val m: Iterable<*> = listOf<Any>()
val n: Annotation = object: Annotation {}
fun foo(): Nothing = throw Error()
val o: Array<*> = arrayOf<Any>()
| apache-2.0 | 27c72cca14c1041b20d37fc758df0f91 | 23.759259 | 85 | 0.673897 | 3.38481 | false | false | false | false |
vsch/idea-multimarkdown | src/test/java/com/vladsch/md/nav/settings/SerializersTest.kt | 1 | 4498 | /*
* Copyright (c) 2015-2019 Vladimir Schneider <[email protected]>
*
* 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 com.vladsch.md.nav.settings
import com.vladsch.md.nav.testUtil.TestCaseUtils
import org.jdom.Element
import org.junit.Test
import kotlin.test.assertEquals
class SerializersTest {
class Container : TagItemHolder("Container") {
var boolValue1 = false
var boolValue2 = false
var intValue = 0
var floatValue = 0f
var doubleValue = 0.0
var stringValue = ""
var stringContent = ""
var stringArray = arrayListOf<String>()
var intArray = arrayListOf<Int>()
var intSet = hashSetOf<Int>()
var stringIntMap = hashMapOf<String, Int>()
init {
addItems(
BooleanAttribute("boolValue1", { boolValue1 }, { boolValue1 = it }),
BooleanAttribute("boolValue2", { boolValue2 }, { boolValue2 = it }),
IntAttribute("intValue", { intValue }, { intValue = it }),
FloatAttribute("floatValue", { floatValue }, { floatValue = it }),
DoubleAttribute("doubleValue", { doubleValue }, { doubleValue = it }),
StringAttribute("stringValue", { stringValue }, { stringValue = it }),
StringContent("stringContent", { stringContent }, { stringContent = it }),
ArrayListItem("stringArray", { stringArray }, { stringArray = it }, { it }, { it }),
ArrayListItem("intArray", { intArray }, { intArray = it }, Int::toString, String::toInt),
HashSetItem<Int>("intSet", { intSet }, { intSet = it }, Int::toString, String::toInt),
HashMapItem<String, Int>("stringIntMap", { stringIntMap }, { stringIntMap = it }, { key, value -> Pair(key, value.toString()) }, { key, value ->
Pair(key, value?.toInt() ?: 0)
})
)
}
}
@Test
fun test_BasicSave() {
val element = Element("root")
val container = Container()
val container2 = Container()
container.boolValue1 = false
container.boolValue2 = true
container.intValue = 5
container.floatValue = 10f
container.doubleValue = 100.0
container.stringValue = "Test"
container.stringContent = "Test2"
container.stringArray = arrayListOf("Test1", "Test2", "Test3")
container.intArray = arrayListOf(1, 2, 3, 4, 5)
container.intSet = hashSetOf(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
container.stringIntMap = hashMapOf(Pair("1", 1), Pair("2", 2), Pair("3", 3), Pair("4", 4))
container.saveState(element)
container2.loadState(element)
assertEquals(container.boolValue1, container2.boolValue1)
assertEquals(container.boolValue2, container2.boolValue2)
assertEquals(container.intValue, container2.intValue)
assertEquals(container.floatValue, container2.floatValue)
assertEquals(container.doubleValue, container2.doubleValue)
assertEquals(container.stringValue, container2.stringValue)
assertEquals(container.stringContent, container2.stringContent)
TestCaseUtils.compareOrderedLists("", container.stringArray, container2.stringArray)
TestCaseUtils.compareOrderedLists("", container.intArray.toTypedArray(), container2.intArray.toTypedArray())
TestCaseUtils.compareUnorderedLists("", container.intSet.toTypedArray(), container2.intSet.toTypedArray())
TestCaseUtils.compareUnorderedLists("", container.stringIntMap.map({ "\"${it.key}\", ${it.value}" }).toTypedArray(), container2.stringIntMap.map({ "\"${it.key}\", ${it.value}" }).toTypedArray())
}
}
| apache-2.0 | 2f81d795cea4dead01cd43bea9ed9d82 | 46.347368 | 202 | 0.648733 | 4.53885 | false | true | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/collections/CollectionTemplates.kt | 1 | 1096 | package com.openlattice.collections
import com.google.common.collect.Maps
import java.util.*
/**
* A Hazelcast-serializable wrapper around a MutableMap<UUID, MutableMap<UUID, UUID>>
* for processing entity set collection templates.
*
* @param templates A map from entity set collection ids to their templates,
* where their templates are maps from collection template type ids to entity set ids
*/
data class CollectionTemplates(
val templates: MutableMap<UUID, MutableMap<UUID, UUID>> = mutableMapOf()
) {
fun put(entitySetCollectionId: UUID, templateTypeId: UUID, entitySetId: UUID) {
val template = templates.getOrDefault(entitySetCollectionId, Maps.newConcurrentMap())
template[templateTypeId] = entitySetId
templates[entitySetCollectionId] = template
}
fun putAll(templateValues: Map<UUID, MutableMap<UUID, UUID>>) {
templateValues.forEach { (key, value) ->
val template = templates.getOrDefault(key, Maps.newConcurrentMap())
template.putAll(value)
templates[key] = template
}
}
} | gpl-3.0 | 42c5bf03a162f607bcc912ff4b49463c | 34.387097 | 93 | 0.710766 | 4.724138 | false | false | false | false |
dataloom/conductor-client | src/main/java/com/openlattice/organizations/processors/OrganizationEntryProcessor.kt | 1 | 1079 | package com.openlattice.organizations.processors
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.organizations.Organization
import org.slf4j.LoggerFactory
import java.util.*
private val logger = LoggerFactory.getLogger(OrganizationEntryProcessor::class.java)
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class OrganizationEntryProcessor(
val update: (Organization) -> Result
) : AbstractRhizomeEntryProcessor<UUID, Organization, Any?>() {
override fun process(entry: MutableMap.MutableEntry<UUID, Organization?>): Any? {
val organization = entry.value
if (organization != null) {
val (value, modified) = update(organization)
if (modified) {
entry.setValue(organization)
}
return value
} else {
logger.warn("Organization not found when trying to update value.")
}
return null
}
data class Result( val value: Any? , val modified: Boolean = true )
}
| gpl-3.0 | 04091033a7db2f5af0e7e7e752ea746c | 27.394737 | 85 | 0.680259 | 4.732456 | false | false | false | false |
MyDogTom/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/out/TestDetektion.kt | 1 | 1010 | package io.gitlab.arturbosch.detekt.cli.out
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.Notification
import io.gitlab.arturbosch.detekt.api.ProjectMetric
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
/**
* @author Artur Bosch
*/
class TestDetektion(vararg findings: Finding) : Detektion {
override val metrics: Collection<ProjectMetric> = listOf()
override val findings: Map<String, List<Finding>> = findings.groupBy { it.id }
override val notifications: List<Notification> = listOf()
override fun add(notification: Notification) = throw UnsupportedOperationException("not implemented")
override fun add(projectMetric: ProjectMetric) = throw UnsupportedOperationException("not implemented")
override fun <V> getData(key: Key<V>) = throw UnsupportedOperationException("not implemented")
override fun <V> addData(key: Key<V>, value: V) = throw UnsupportedOperationException("not implemented")
}
| apache-2.0 | e8aa15a0fb211e553e8ba239e789bdd1 | 42.913043 | 105 | 0.794059 | 4.139344 | false | false | false | false |
Budincsevity/opensubtitles-api | src/test/kotlin/io/github/budincsevity/OpenSubtitlesAPI/model/builder/OpenSubtitlesSearchParamsBuilderTest.kt | 1 | 3321 | package io.github.budincsevity.OpenSubtitlesAPI.model.builder
import io.github.budincsevity.OpenSubtitlesAPI.exception.SearchParamMissingException
import io.github.budincsevity.OpenSubtitlesAPI.util.TestDataProvider
import io.github.budincsevity.OpenSubtitlesAPI.util.SearchParam
import org.testng.Assert.assertEquals
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class OpenSubtitlesSearchParamsBuilderTest {
val openSubtitlesSearchParamsBuilderWithMovieHashMovieBytes = TestDataProvider().createOpenSubtitlesSearchParamBuilderWithMovieHashMovieBytes()
val openSubtitlesSearchParamsBuilderWithTag = TestDataProvider().createOpenSubtitlesSearchParamBuilderWithTag()
val openSubtitlesSearchParamsBuilderWithQuery = TestDataProvider().createOpenSubtitlesSearchParamBuilderWithQuery()
val openSubtitlesSearchParamsBuilderWithImdbId = TestDataProvider().createOpenSubtitlesSearchParamBuilderWithImdbId()
val openSubtitlesEmptySearchParamsBuilder = TestDataProvider().createEmptyOpenSubtitlesSearchParamBuilder()
lateinit var paramsMap: HashMap<*, *>
companion object {
val TOKEN = "token"
val FIRST = "1"
val ALIEN = "Alien"
val HASH = "HASH"
val BYTESIZE = "12345"
val IMDBID = "555555"
val QUERY = "The.Big.Bang.Theory.S10E10.720p.HDTV.X264-DIMENSION[ettv]"
}
@DataProvider
fun testData(): Array<Array<out Any?>> = arrayOf(
arrayOf(openSubtitlesSearchParamsBuilderWithMovieHashMovieBytes, HASH, BYTESIZE, null, null, null),
arrayOf(openSubtitlesSearchParamsBuilderWithTag, null, null, ALIEN, null, null),
arrayOf(openSubtitlesSearchParamsBuilderWithImdbId, null, null, null, IMDBID, null),
arrayOf(openSubtitlesSearchParamsBuilderWithQuery, null, null, null, null, QUERY)
)
@Test(dataProvider = "testData")
fun testBuild_ShouldBuildSearchResultAsExpected(searchParamsBuilder: OpenSubtitlesSearchParamsBuilder, movieHash: String?,
movieBytes: String?, tag: String?, imdbId: String?, query: String?) {
whenBuildMethodIsCalled(searchParamsBuilder)
thenBuiltSearchParamsShouldBeAsExpected(movieHash, movieBytes, query, tag, imdbId)
}
@Test(expectedExceptions = arrayOf(SearchParamMissingException::class))
fun testBuild_ShouldThrowSearchParamMissingException() {
openSubtitlesEmptySearchParamsBuilder.build(TOKEN)
}
private fun whenBuildMethodIsCalled(searchParamsBuilder: OpenSubtitlesSearchParamsBuilder) {
val openSubtitlesSearchParams = searchParamsBuilder.build(TOKEN)
val containerMap = openSubtitlesSearchParams[1] as HashMap<*, *>
paramsMap = containerMap[FIRST] as HashMap<*, *>
}
private fun thenBuiltSearchParamsShouldBeAsExpected(movieHash: String?, movieBytes: String?, query: String?, tag: String?, imdbId: String?) {
assertEquals(paramsMap[SearchParam.MOVIE_HASH.paramName], movieHash)
assertEquals(paramsMap[SearchParam.MOVIE_BYTE_SIZE.paramName], movieBytes)
assertEquals(paramsMap[SearchParam.QUERY.paramName], query)
assertEquals(paramsMap[SearchParam.TAG.paramName], tag)
assertEquals(paramsMap[SearchParam.IMDBID.paramName], imdbId)
}
}
| mit | 9987cfba972e282b0f796708e646d1cb | 51.714286 | 147 | 0.75941 | 4.72404 | false | true | false | false |
ItsPriyesh/chroma | chroma/src/main/kotlin/me/priyesh/chroma/ColorMode.kt | 1 | 2387 | /*
* Copyright 2016 Priyesh Patel
*
* 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.priyesh.chroma
import android.graphics.Color
enum class ColorMode {
ARGB {
override val channels: List<Channel> = listOf(
Channel(R.string.channel_alpha, 0, 255, Color::alpha),
Channel(R.string.channel_red, 0, 255, Color::red),
Channel(R.string.channel_green, 0, 255, Color::green),
Channel(R.string.channel_blue, 0, 255, Color::blue)
)
override fun evaluateColor(channels: List<Channel>): Int = Color.argb(
channels[0].progress, channels[1].progress, channels[2].progress, channels[3].progress)
},
RGB {
override val channels: List<Channel> = ARGB.channels.drop(1)
override fun evaluateColor(channels: List<Channel>): Int = Color.rgb(
channels[0].progress, channels[1].progress, channels[2].progress)
},
HSV {
override val channels: List<Channel> = listOf(
Channel(R.string.channel_hue, 0, 360, ::hue),
Channel(R.string.channel_saturation, 0, 100, ::saturation),
Channel(R.string.channel_value, 0, 100, ::value)
)
override fun evaluateColor(channels: List<Channel>): Int = Color.HSVToColor(
floatArrayOf(
(channels[0].progress).toFloat(),
(channels[1].progress / 100.0).toFloat(),
(channels[2].progress / 100.0).toFloat()
))
};
abstract internal val channels: List<Channel>
abstract internal fun evaluateColor(channels: List<Channel>): Int
internal data class Channel(val nameResourceId: Int,
val min: Int, val max: Int,
val extractor: (color: Int) -> Int,
var progress: Int = 0)
companion object {
@JvmStatic fun fromName(name: String) = values().find { it.name == name } ?: ColorMode.RGB
}
} | apache-2.0 | d60b4e0afe2b827c0a3bb11bb32e852d | 33.608696 | 95 | 0.64977 | 3.958541 | false | false | false | false |
msebire/intellij-community | plugins/devkit/devkit-core/src/inspections/StatefulEpInspection.kt | 1 | 3504 | // Copyright 2000-2018 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 org.jetbrains.idea.devkit.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.lang.jvm.DefaultJvmElementVisitor
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmField
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.types.JvmReferenceType
import com.intellij.lang.jvm.util.JvmInheritanceUtil.isInheritor
import com.intellij.lang.jvm.util.JvmUtil
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import org.jetbrains.idea.devkit.util.ExtensionCandidate
import org.jetbrains.idea.devkit.util.ExtensionLocator
class StatefulEpInspection : DevKitJvmInspection() {
override fun buildVisitor(project: Project, sink: HighlightSink, isOnTheFly: Boolean): DefaultJvmElementVisitor<Boolean?> = object : DefaultJvmElementVisitor<Boolean?> {
override fun visitField(field: JvmField): Boolean? {
val clazz = field.containingClass ?: return null
val fieldTypeClass = JvmUtil.resolveClass(field.type as? JvmReferenceType) ?: return null
val isQuickFix by lazy(LazyThreadSafetyMode.NONE) { isInheritor(clazz, localQuickFixFqn) }
val targets = findEpCandidates(project, clazz)
if (targets.isEmpty() && !isQuickFix) return null
if (isInheritor(fieldTypeClass, PsiElement::class.java.canonicalName)) {
sink.highlight(
"Potential memory leak: don't hold PsiElement, use SmartPsiElementPointer instead${if (isQuickFix) "; also see LocalQuickFixOnPsiElement" else ""}"
)
return false
}
if (isInheritor(fieldTypeClass, PsiReference::class.java.canonicalName)) {
sink.highlight(message(PsiReference::class.java.simpleName, isQuickFix))
return false
}
if (!isProjectFieldAllowed(field, clazz, targets) && isInheritor(fieldTypeClass, Project::class.java.canonicalName)) {
sink.highlight(message(Project::class.java.simpleName, isQuickFix))
return false
}
return false
}
}
companion object {
private val localQuickFixFqn = LocalQuickFix::class.java.canonicalName
private val projectComponentFqn = ProjectComponent::class.java.canonicalName
private fun findEpCandidates(project: Project, clazz: JvmClass): Collection<ExtensionCandidate> {
val name = clazz.name ?: return emptyList()
return ExtensionLocator.byClass(project, clazz).findCandidates().filter { candidate ->
val forClass = candidate.pointer.element?.getAttributeValue("forClass")
forClass == null || !forClass.contains(name)
}
}
private fun isProjectFieldAllowed(field: JvmField, clazz: JvmClass, targets: Collection<ExtensionCandidate>): Boolean {
val finalField = field.hasModifier(JvmModifier.FINAL)
if (finalField) return true
val isProjectEP = targets.any { candidate ->
val name = candidate.pointer.element?.name
"projectService" == name || "projectConfigurable" == name
}
if (isProjectEP) return true
return isInheritor(clazz, projectComponentFqn)
}
private fun message(what: String, quickFix: Boolean): String {
val where = if (quickFix) "quick fix" else "extension"
return "Don't use $what as a field in $where"
}
}
}
| apache-2.0 | 524f1eb7f37bb8ee85fe9736d5467d7d | 41.216867 | 171 | 0.738014 | 4.647215 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/event/model/Event.kt | 1 | 1392 | package mixit.event.model
import mixit.user.model.Link
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.time.LocalDate
@Document
data class Event(
@Id val id: String = "",
val start: LocalDate = LocalDate.now(),
val end: LocalDate = LocalDate.now(),
val current: Boolean = false,
val sponsors: List<EventSponsoring> = emptyList(),
val organizations: List<EventOrganization> = emptyList(),
val volunteers: List<EventVolunteer> = emptyList(),
val photoUrls: List<Link> = emptyList(),
val videoUrl: Link? = null,
val schedulingFileUrl: String? = null,
val year: Int = start.year
)
@Document
data class EventOrganization(
val organizationLogin: String
)
data class EventSponsoring(
val level: SponsorshipLevel = SponsorshipLevel.NONE,
val sponsorId: String = "",
val subscriptionDate: LocalDate = LocalDate.now()
)
data class EventVolunteer(
val volunteerLogin: String
)
enum class SponsorshipLevel {
GOLD,
SILVER,
BRONZE,
LANYARD,
PARTY,
BREAKFAST,
LUNCH,
HOSTING,
ECOLOGY,
VIDEO,
COMMUNITY,
MIXTEEN,
ECOCUP,
ACCESSIBILITY,
NONE;
companion object {
fun sponsorshipLevels() =
listOf(GOLD, SILVER, HOSTING, ECOLOGY, LANYARD, ACCESSIBILITY, MIXTEEN, PARTY, VIDEO)
}
}
| apache-2.0 | 16c6aa21978e3f281c9fec0608caec99 | 22.59322 | 97 | 0.6875 | 3.845304 | false | false | false | false |
pdvrieze/ProcessManager | PMEditor/src/main/java/nl/adaptivity/process/ui/main/ProcessBaseActivity.kt | 1 | 12928 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.ui.main
import android.accounts.Account
import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.annotation.CallSuper
import android.util.Log
import nl.adaptivity.android.compat.Compat
import nl.adaptivity.android.darwin.AuthenticatedWebClientFactory
import nl.adaptivity.android.graphics.AndroidTextMeasurer
import nl.adaptivity.diagram.svg.SVGCanvas
import nl.adaptivity.process.diagram.DrawableProcessModel
import nl.adaptivity.process.diagram.RootDrawableProcessModel
import nl.adaptivity.process.editor.android.BuildConfig
import nl.adaptivity.process.editor.android.PMParcelable
import nl.adaptivity.process.editor.android.PMParser
import nl.adaptivity.process.editor.android.PMProcessesFragment.ProcessesCallback
import nl.adaptivity.process.editor.android.R
import nl.adaptivity.process.ui.ProcessSyncManager
import nl.adaptivity.process.ui.UIConstants
import nl.adaptivity.xmlutil.AndroidXmlWriter
import nl.adaptivity.xmlutil.XmlException
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlSerializer
import java.io.*
/**
* Created by pdvrieze on 11/01/16.
*/
abstract class ProcessBaseActivity : AuthenticatedActivity(), ProcessesCallback {
/** Process model that needs to be saved/exported. */
private var mProcessModel: DrawableProcessModel? = null
/** Temporary file for sharing. */
protected var mTmpFile: File? = null
var syncManager: ProcessSyncManager? = null
private set
private inner class FileStoreListener(private val mMimeType: String, private val mRequestCode: Int) {
internal fun afterSave(result: File) {
mTmpFile = result
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = mMimeType
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(result))
startActivityForResult(shareIntent, mRequestCode)
}
}
private inner class FileStoreTask @JvmOverloads constructor(private val mType: Int,
private val mPostSave: FileStoreListener,
private var mFile: File? = null) : AsyncTask<DrawableProcessModel, Any, File>() {
override fun doInBackground(vararg params: DrawableProcessModel): File {
val file:File = mFile ?: run {
val ext = if (mType == TYPE_SVG) ".svg" else ".pm"
File.createTempFile("tmp_", ext, externalCacheDir).also { mFile = it }
}
try {
val out = FileOutputStream(file)
try {
if (mType == TYPE_SVG) {
doExportSVG(out, params[0].rootModel)
} else {
doSaveFile(out, params[0].rootModel)
}
} finally {
out.close()
}
} catch (e: IOException) {
throw RuntimeException(e)
}
return file
}
override fun onPostExecute(result: File) {
mPostSave.afterSave(result)
}
override fun onCancelled(result: File) {
if (mFile != null) {
mFile!!.delete()
}
}
}
override fun doAccountDetermined(account: Account?) {
if (account == null) {
syncManager = null
} else if (syncManager == null) {
syncManager = ProcessSyncManager(this, AuthenticatedWebClientFactory.getStoredAccount(this))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(UIConstants.KEY_TMPFILE)) {
mTmpFile = File(savedInstanceState.getString(UIConstants.KEY_TMPFILE)!!)
}
if (savedInstanceState.containsKey(UIConstants.KEY_PROCESSMODEL)) {
val pm = savedInstanceState.getParcelable<PMParcelable>(UIConstants.KEY_PROCESSMODEL)
if (pm != null) {
mProcessModel = RootDrawableProcessModel.get(pm.processModel)
}
}
}
}
@CallSuper
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
UIConstants.REQUEST_SHARE_PROCESSMODEL_FILE, UIConstants.REQUEST_SHARE_PROCESSMODEL_SVG -> mTmpFile!!.delete()
UIConstants.REQUEST_SAVE_PROCESSMODEL -> if (resultCode == Activity.RESULT_OK) {
doSaveFile(data, mProcessModel!!.rootModel)
}
UIConstants.REQUEST_EXPORT_PROCESSMODEL_SVG -> if (resultCode == Activity.RESULT_OK) {
doExportSVG(data, mProcessModel!!)
}
}
}
@Throws(FileNotFoundException::class)
private fun getOutputStreamFromSave(data: Intent?): OutputStream? {
return contentResolver.openOutputStream(data?.data!!)
}
protected fun doSaveFile(data: Intent?, processModel: RootDrawableProcessModel) {
try {
val out = getOutputStreamFromSave(data)!!
try {
doSaveFile(out, processModel)
} finally {
out.close()
}
} catch (e: RuntimeException) {
Log.e(TAG, "Failure to save file", e)
} catch (e: IOException) {
Log.e(TAG, "Failure to save file", e)
}
}
@Throws(IOException::class)
private fun doSaveFile(out: Writer, processModel: RootDrawableProcessModel) {
try {
PMParser.exportProcessModel(out, processModel)
} catch (e: XmlPullParserException) {
throw IOException(e)
} catch (e: XmlException) {
throw IOException(e)
}
}
@Throws(IOException::class)
private fun doSaveFile(out: OutputStream, processModel: RootDrawableProcessModel) {
try {
PMParser.exportProcessModel(out, processModel)
} catch (e: XmlException) {
throw IOException(e)
} catch (e: XmlPullParserException) {
throw IOException(e)
}
}
override fun requestShareFile(processModel: RootDrawableProcessModel?) {
if (BuildConfig.DEBUG && processModel == null) {
throw NullPointerException()
}
val task = FileStoreTask(TYPE_FILE, FileStoreListener("*/*", UIConstants.REQUEST_SHARE_PROCESSMODEL_FILE))
task.execute((processModel as DrawableProcessModel?))
}
override fun requestSaveFile(processModel: RootDrawableProcessModel?) {
if (BuildConfig.DEBUG && processModel == null) {
throw NullPointerException()
}
mProcessModel = processModel
requestSaveFile("*/*", UIConstants.REQUEST_SAVE_PROCESSMODEL)
}
override fun requestShareSVG(processModel: DrawableProcessModel) {
val task = FileStoreTask(TYPE_SVG, FileStoreListener("image/svg", UIConstants.REQUEST_SHARE_PROCESSMODEL_SVG))
task.execute(processModel)
}
override fun requestExportSVG(processModel: DrawableProcessModel?) {
if (BuildConfig.DEBUG && processModel == null) {
throw NullPointerException()
}
mProcessModel = processModel
requestSaveFile("image/svg", UIConstants.REQUEST_EXPORT_PROCESSMODEL_SVG)
}
private fun requestSaveFile(type: String, request: Int) {
val prefs = PreferenceManager.getDefaultSharedPreferences(this)
if (prefs.getBoolean(SettingsActivity.PREF_KITKATFILE,
true) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
startKitkatSaveActivity(type, request)
} else {
var intent = Intent("org.openintents.action.PICK_FILE")
if (supportsIntent(intent)) {
intent.putExtra("org.openintents.extra.TITLE", getString(R.string.title_saveas))
intent.putExtra("org.openintents.extra.BUTTON_TEXT", getString(R.string.btn_save))
intent.data = Uri.withAppendedPath(Uri.fromFile(Compat.getDocsDirectory()), "/")
} else {
intent = Intent("com.estrongs.action.PICK_FILE")
if (supportsIntent(intent)) {
intent.putExtra("com.estrongs.intent.extra.TITLE", getString(R.string.title_saveas))
// intent.setData(Uri.withAppendedPath(Uri.fromFile(Compat.getDocsDirectory()),"/"));
} else {
requestShareFile(mProcessModel!!.rootModel)
// Toast.makeText(getActivity(), "Saving not yet supported without implementation", Toast.LENGTH_LONG).show();
return
}
}
startActivityForResult(intent, request)
}
}
private fun doExportSVG(data: Intent?, processModel: DrawableProcessModel) {
try {
val out = getOutputStreamFromSave(data)!!
try {
doExportSVG(out, processModel)
} finally {
out.close()
}
} catch (e: RuntimeException) {
Log.e(TAG, "Failure to save file", e)
} catch (e: IOException) {
Log.e(TAG, "Failure to save file", e)
}
}
@Throws(IOException::class)
private fun doExportSVG(out: OutputStream, processModel: DrawableProcessModel) {
try {
val serializer = PMParser.getSerializer(out)
doExportSVG(serializer, processModel.builder())
} catch (e: XmlPullParserException) {
throw IOException(e)
}
}
@Throws(IOException::class)
private fun doExportSVG(out: Writer, processModel: DrawableProcessModel.Builder) {
try {
val serializer = PMParser.getSerializer(out)
doExportSVG(serializer, processModel)
} catch (e: XmlPullParserException) {
throw IOException(e)
}
}
@Throws(IOException::class)
private fun doExportSVG(serializer: XmlSerializer, processModel: DrawableProcessModel.Builder) {
val canvas = SVGCanvas(AndroidTextMeasurer())
val modelBounds = processModel.bounds
val offsetCanvas = canvas
.childCanvas(-modelBounds.left, -modelBounds.top, 1.0)
modelBounds.left = 0.0// set the origin to the actual top left corner of the image.
modelBounds.top = 0.0
canvas.bounds = modelBounds
processModel.draw(offsetCanvas, null)
serializer.startDocument(null, null)
serializer.ignorableWhitespace("\n")
serializer.comment("Generated by PMEditor")
serializer.ignorableWhitespace("\n")
canvas.serialize(AndroidXmlWriter(serializer))
serializer.ignorableWhitespace("\n")
serializer.flush()
}
private fun supportsIntent(intent: Intent): Boolean {
return !packageManager.queryIntentActivities(intent, 0).isEmpty()
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private fun startKitkatSaveActivity(type: String, request: Int) {
val i = Intent(Intent.ACTION_CREATE_DOCUMENT)
i.type = type
i.addCategory(Intent.CATEGORY_OPENABLE)
startActivityForResult(i, request)
}
@CallSuper
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
if (mProcessModel != null) {
outState.putParcelable(UIConstants.KEY_PROCESSMODEL, PMParcelable(mProcessModel!!.rootModel))
}
if (mTmpFile != null) {
outState.putString(UIConstants.KEY_TMPFILE, mTmpFile!!.path)
}
}
companion object {
private val TAG = "ProcessBaseActivity"
private val TYPE_FILE = 0
private val TYPE_SVG = 1
}
}
| lgpl-3.0 | f6084892341c7d1dd0425afe74130898 | 36.690962 | 142 | 0.629564 | 4.851032 | false | false | false | false |
debop/debop4k | debop4k-redis/src/test/kotlin/debop4k/redisson/kotlin/spring/cache/UserRepository.kt | 1 | 1974 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.redisson.kotlin.spring.cache
import debop4k.core.AbstractValueObject
import debop4k.core.utils.hashOf
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.CachePut
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Component
import java.io.Serializable
/**
* NOTE: Kotlin 으로 Spring Compoent 를 만들려면 모두 open 을 지정해주어야 합니다.
* @author [email protected]
*/
@Component
@CacheConfig(cacheNames = arrayOf("kotlinUsers"))
open class UserRepository {
@CachePut(key = "#key")
open fun save(key: String, obj: UserObject?): UserObject? {
return obj
}
@CachePut(key = "#key")
open fun saveNull(key: String): UserObject? {
return null
}
@CacheEvict(key = "#key")
open fun remove(key: String) {
}
@Cacheable(key = "#key")
open fun get(key: String): UserObject? {
throw IllegalStateException()
}
@Cacheable(key = "#key")
open fun getNull(key: String): UserObject? {
return null
}
open class UserObject(var name: String? = null,
var value: String? = null) : AbstractValueObject(), Serializable {
override fun hashCode(): Int {
return hashOf(name, value)
}
}
} | apache-2.0 | 129a96d7c1b1b56ada7db185554072de | 27.910448 | 90 | 0.716942 | 3.796078 | false | false | false | false |
PaulWoitaschek/Voice | bookOverview/src/main/kotlin/voice/bookOverview/fileCover/FileCoverViewModel.kt | 1 | 1101 | package voice.bookOverview.fileCover
import android.net.Uri
import com.squareup.anvil.annotations.ContributesMultibinding
import voice.bookOverview.bottomSheet.BottomSheetItem
import voice.bookOverview.bottomSheet.BottomSheetItemViewModel
import voice.bookOverview.di.BookOverviewScope
import voice.common.BookId
import voice.common.navigation.Destination
import voice.common.navigation.Navigator
import javax.inject.Inject
@BookOverviewScope
@ContributesMultibinding(BookOverviewScope::class, boundType = BottomSheetItemViewModel::class)
class FileCoverViewModel
@Inject
constructor(
private val navigator: Navigator,
) : BottomSheetItemViewModel {
private var bookId: BookId? = null
override suspend fun items(bookId: BookId): List<BottomSheetItem> {
return listOf(BottomSheetItem.FileCover)
}
override suspend fun onItemClicked(bookId: BookId, item: BottomSheetItem) {
if (item == BottomSheetItem.FileCover) {
this.bookId = bookId
}
}
fun onImagePicked(uri: Uri) {
val bookId = bookId ?: return
navigator.goTo(Destination.EditCover(bookId, uri))
}
}
| gpl-3.0 | 2abb1d1b3dda81118a9b6fe9429ddebc | 28.756757 | 95 | 0.797457 | 4.512295 | false | false | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/ui/screens/artist/detail/ArtistDetailFragment.kt | 1 | 27900 | package com.simplecity.amp_library.ui.screens.artist.detail
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.SharedElementCallback
import android.support.v4.util.Pair
import android.support.v4.view.ViewCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.Toolbar
import android.transition.Transition
import android.transition.TransitionInflater
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.Toast
import butterknife.ButterKnife
import butterknife.Unbinder
import com.afollestad.aesthetic.Aesthetic
import com.afollestad.aesthetic.Rx.distinctToMainThread
import com.bumptech.glide.Priority
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.android.gms.cast.framework.CastButtonFactory
import com.simplecity.amp_library.R
import com.simplecity.amp_library.cast.CastManager
import com.simplecity.amp_library.data.Repository
import com.simplecity.amp_library.glide.utils.AlwaysCrossFade
import com.simplecity.amp_library.model.Album
import com.simplecity.amp_library.model.AlbumArtist
import com.simplecity.amp_library.model.ArtworkProvider
import com.simplecity.amp_library.model.Playlist
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.ui.common.BaseFragment
import com.simplecity.amp_library.ui.common.TransitionListenerAdapter
import com.simplecity.amp_library.ui.dialog.AlbumBiographyDialog
import com.simplecity.amp_library.ui.dialog.ArtistBiographyDialog
import com.simplecity.amp_library.ui.dialog.DeleteDialog
import com.simplecity.amp_library.ui.dialog.SongInfoDialog
import com.simplecity.amp_library.ui.modelviews.AlbumView
import com.simplecity.amp_library.ui.modelviews.EmptyView
import com.simplecity.amp_library.ui.modelviews.HorizontalAlbumView
import com.simplecity.amp_library.ui.modelviews.HorizontalRecyclerView
import com.simplecity.amp_library.ui.modelviews.SelectableViewModel
import com.simplecity.amp_library.ui.modelviews.SongView
import com.simplecity.amp_library.ui.modelviews.SubheaderView
import com.simplecity.amp_library.ui.screens.album.detail.AlbumDetailFragment
import com.simplecity.amp_library.ui.screens.drawer.DrawerLockManager
import com.simplecity.amp_library.ui.screens.playlist.dialog.CreatePlaylistDialog
import com.simplecity.amp_library.ui.screens.tagger.TaggerDialog
import com.simplecity.amp_library.ui.views.ContextualToolbar
import com.simplecity.amp_library.ui.views.ContextualToolbarHost
import com.simplecity.amp_library.utils.ActionBarUtils
import com.simplecity.amp_library.utils.ArtworkDialog
import com.simplecity.amp_library.utils.ContextualToolbarHelper
import com.simplecity.amp_library.utils.Operators
import com.simplecity.amp_library.utils.PlaceholderProvider
import com.simplecity.amp_library.utils.ResourceUtils
import com.simplecity.amp_library.utils.RingtoneManager
import com.simplecity.amp_library.utils.SettingsManager
import com.simplecity.amp_library.utils.ShuttleUtils
import com.simplecity.amp_library.utils.StringUtils
import com.simplecity.amp_library.utils.TypefaceManager
import com.simplecity.amp_library.utils.extensions.getSongsSingle
import com.simplecity.amp_library.utils.extensions.share
import com.simplecity.amp_library.utils.menu.album.AlbumMenuUtils
import com.simplecity.amp_library.utils.menu.albumartist.AlbumArtistMenuUtils
import com.simplecity.amp_library.utils.menu.song.SongMenuUtils
import com.simplecity.amp_library.utils.playlists.PlaylistMenuHelper
import com.simplecity.amp_library.utils.sorting.AlbumSortHelper
import com.simplecity.amp_library.utils.sorting.SongSortHelper
import com.simplecity.amp_library.utils.sorting.SortManager
import com.simplecityapps.recycler_adapter.adapter.CompletionListUpdateCallbackAdapter
import com.simplecityapps.recycler_adapter.adapter.ViewModelAdapter
import com.simplecityapps.recycler_adapter.model.ViewModel
import com.simplecityapps.recycler_adapter.recyclerview.RecyclerListener
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_detail.background
import kotlinx.android.synthetic.main.fragment_detail.fab
import kotlinx.android.synthetic.main.fragment_detail.recyclerView
import kotlinx.android.synthetic.main.fragment_detail.textProtectionScrim
import kotlinx.android.synthetic.main.fragment_detail.textProtectionScrim2
import kotlinx.android.synthetic.main.fragment_detail.toolbar
import kotlinx.android.synthetic.main.fragment_detail.toolbar_layout
import java.util.ArrayList
import javax.inject.Inject
import kotlinx.android.synthetic.main.fragment_detail.contextualToolbar as ctxToolbar
@SuppressLint("RestrictedApi")
class ArtistDetailFragment :
BaseFragment(),
ArtistDetailView,
Toolbar.OnMenuItemClickListener,
DrawerLockManager.DrawerLock,
ContextualToolbarHost {
private lateinit var albumArtist: AlbumArtist
private lateinit var adapter: ViewModelAdapter
private lateinit var presenter: ArtistDetailPresenter
@Inject lateinit var presenterFactory: ArtistDetailPresenter.Factory
@Inject lateinit var requestManager: RequestManager
@Inject lateinit var songsRepository: Repository.SongsRepository
@Inject lateinit var sortManager: SortManager
@Inject lateinit var settingsManager: SettingsManager
@Inject lateinit var playlistMenuHelper: PlaylistMenuHelper
private val disposables = CompositeDisposable()
private var collapsingToolbarTextColor: ColorStateList? = null
private var collapsingToolbarSubTextColor: ColorStateList? = null
private val emptyView = EmptyView(R.string.empty_songlist)
private val horizontalRecyclerView = HorizontalRecyclerView("BaseDetail - horizontal")
private var setHorizontalItemsDisposable: Disposable? = null
private var setItemsDisposable: Disposable? = null
private var contextualToolbarHelper: ContextualToolbarHelper<Single<List<Song>>>? = null
private var unbinder: Unbinder? = null
private var isFirstLoad = true
private val sharedElementEnterTransitionListenerAdapter: TransitionListenerAdapter
get() = object : TransitionListenerAdapter() {
override fun onTransitionEnd(transition: Transition) {
transition.removeListener(this)
fadeInUi()
}
}
private val songClickListener = object : SongView.ClickListener {
override fun onSongClick(position: Int, songView: SongView) {
if (!contextualToolbarHelper!!.handleClick(songView, Single.just(listOf(songView.song)))) {
presenter.songClicked(songView.song)
}
}
override fun onSongLongClick(position: Int, songView: SongView): Boolean {
return contextualToolbarHelper!!.handleLongClick(songView, Single.just(listOf(songView.song)))
}
override fun onSongOverflowClick(position: Int, v: View, song: Song) {
val popupMenu = PopupMenu(v.context, v)
SongMenuUtils.setupSongMenu(popupMenu, false, true, playlistMenuHelper)
popupMenu.setOnMenuItemClickListener(SongMenuUtils.getSongMenuClickListener(song, presenter))
popupMenu.show()
}
override fun onStartDrag(holder: SongView.ViewHolder) {
}
}
private val albumClickListener = object : AlbumView.ClickListener {
override fun onAlbumClick(position: Int, albumView: AlbumView, viewHolder: AlbumView.ViewHolder) {
if (!contextualToolbarHelper!!.handleClick(albumView, albumView.album.getSongsSingle(songsRepository))) {
pushDetailFragment(AlbumDetailFragment.newInstance(albumView.album, ViewCompat.getTransitionName(viewHolder.imageOne)!!), viewHolder.imageOne)
}
}
override fun onAlbumLongClick(position: Int, albumView: AlbumView): Boolean {
return contextualToolbarHelper!!.handleLongClick(albumView, albumView.album.getSongsSingle(songsRepository))
}
override fun onAlbumOverflowClicked(v: View, album: Album) {
val popupMenu = PopupMenu(v.context, v)
AlbumMenuUtils.setupAlbumMenu(popupMenu, playlistMenuHelper, false)
popupMenu.setOnMenuItemClickListener(AlbumMenuUtils.getAlbumMenuClickListener(album, presenter))
popupMenu.show()
}
}
private val enterSharedElementCallback = object : SharedElementCallback() {
override fun onSharedElementStart(sharedElementNames: List<String>?, sharedElements: List<View>?, sharedElementSnapshots: List<View>?) {
super.onSharedElementStart(sharedElementNames, sharedElements, sharedElementSnapshots)
fab?.visibility = View.GONE
}
}
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
albumArtist = arguments!!.getSerializable(ARG_ALBUM_ARTIST) as AlbumArtist
}
override fun onCreate(icicle: Bundle?) {
super.onCreate(icicle)
presenter = presenterFactory.create(albumArtist)
adapter = ViewModelAdapter()
setHasOptionsMenu(true)
setEnterSharedElementCallback(enterSharedElementCallback)
isFirstLoad = true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_detail, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
unbinder = ButterKnife.bind(this, view)
toolbar.setNavigationOnClickListener { navigationController.popViewController() }
if (ShuttleUtils.canDrawBehindStatusBar()) {
toolbar.layoutParams.height = (ActionBarUtils.getActionBarHeight(context!!) + ActionBarUtils.getStatusBarHeight(context!!)).toInt()
toolbar.setPadding(toolbar.paddingLeft, (toolbar.paddingTop + ActionBarUtils.getStatusBarHeight(context!!)).toInt(), toolbar.paddingRight, toolbar.paddingBottom)
}
setupToolbarMenu(toolbar)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setRecyclerListener(RecyclerListener())
recyclerView.adapter = adapter
if (isFirstLoad) {
recyclerView.layoutAnimation = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_from_bottom)
}
toolbar_layout.title = albumArtist.name
toolbar_layout.setSubtitle(null)
toolbar_layout.setExpandedTitleTypeface(TypefaceManager.getInstance().getTypeface(context, TypefaceManager.SANS_SERIF_LIGHT))
toolbar_layout.setCollapsedTitleTypeface(TypefaceManager.getInstance().getTypeface(context, TypefaceManager.SANS_SERIF))
setupContextualToolbar()
val transitionName = arguments!!.getString(ARG_TRANSITION_NAME)
ViewCompat.setTransitionName(background, transitionName)
if (isFirstLoad) {
fab!!.visibility = View.GONE
}
fab.setOnClickListener {
presenter.shuffleAll()
}
if (transitionName == null) {
fadeInUi()
}
loadBackgroundImage()
disposables.add(Aesthetic.get(context)
.colorPrimary()
.compose(distinctToMainThread())
.subscribe { primaryColor ->
toolbar_layout.setContentScrimColor(primaryColor!!)
toolbar_layout.setBackgroundColor(primaryColor)
})
presenter.bindView(this)
}
override fun onResume() {
super.onResume()
presenter.loadData()
DrawerLockManager.getInstance().addDrawerLock(this)
}
override fun onPause() {
DrawerLockManager.getInstance().removeDrawerLock(this)
super.onPause()
}
override fun onDestroyView() {
if (setItemsDisposable != null) {
setItemsDisposable!!.dispose()
}
if (setHorizontalItemsDisposable != null) {
setHorizontalItemsDisposable!!.dispose()
}
disposables.clear()
presenter.unbindView(this)
unbinder!!.unbind()
isFirstLoad = false
super.onDestroyView()
}
private fun setupToolbarMenu(toolbar: Toolbar) {
toolbar.inflateMenu(R.menu.menu_detail_sort)
if (CastManager.isCastAvailable(context!!, settingsManager)) {
val menuItem = CastButtonFactory.setUpMediaRouteButton(context, toolbar.menu, R.id.media_route_menu_item)
menuItem.isVisible = true
}
toolbar.setOnMenuItemClickListener(this)
// Create playlist menu
val sub = toolbar.menu.findItem(R.id.addToPlaylist).subMenu
disposables.add(playlistMenuHelper.createUpdatingPlaylistMenu(sub).subscribe())
// Inflate sorting menus
val item = toolbar.menu.findItem(R.id.sorting)
activity!!.menuInflater.inflate(R.menu.menu_detail_sort_albums, item.subMenu)
activity!!.menuInflater.inflate(R.menu.menu_detail_sort_songs, item.subMenu)
toolbar.menu.findItem(R.id.editTags).isVisible = true
toolbar.menu.findItem(R.id.info).isVisible = true
toolbar.menu.findItem(R.id.artwork).isVisible = true
AlbumSortHelper.updateAlbumSortMenuItems(toolbar.menu, sortManager.artistDetailAlbumsSortOrder, sortManager.artistDetailAlbumsAscending)
SongSortHelper.updateSongSortMenuItems(toolbar.menu, sortManager.artistDetailSongsSortOrder, sortManager.artistDetailSongsAscending)
}
override fun onMenuItemClick(item: MenuItem): Boolean {
if (!AlbumArtistMenuUtils.getAlbumArtistClickListener(albumArtist, presenter).onMenuItemClick(item)) {
val albumSortOrder = AlbumSortHelper.handleAlbumDetailMenuSortOrderClicks(item)
if (albumSortOrder != null) {
sortManager.artistDetailAlbumsSortOrder = albumSortOrder
presenter.loadData()
}
val albumsAsc = AlbumSortHelper.handleAlbumDetailMenuSortOrderAscClicks(item)
if (albumsAsc != null) {
sortManager.artistDetailAlbumsAscending = albumsAsc
presenter.loadData()
}
val songSortOrder = SongSortHelper.handleSongMenuSortOrderClicks(item)
if (songSortOrder != null) {
sortManager.artistDetailSongsSortOrder = songSortOrder
presenter.loadData()
}
val songsAsc = SongSortHelper.handleSongDetailMenuSortOrderAscClicks(item)
if (songsAsc != null) {
sortManager.artistDetailSongsAscending = songsAsc
presenter.loadData()
}
AlbumSortHelper.updateAlbumSortMenuItems(toolbar.menu, sortManager.artistDetailAlbumsSortOrder, sortManager.artistDetailAlbumsAscending)
SongSortHelper.updateSongSortMenuItems(toolbar.menu, sortManager.artistDetailSongsSortOrder, sortManager.artistDetailSongsAscending)
}
return super.onOptionsItemSelected(item)
}
private fun loadBackgroundImage() {
val width = ResourceUtils.getScreenSize().width + ResourceUtils.toPixels(60f)
val height = resources.getDimensionPixelSize(R.dimen.header_view_height)
requestManager.load<ArtworkProvider>(albumArtist as ArtworkProvider?)
// Need to override the height/width, as the shared element transition tricks Glide into thinking this ImageView has
// the same dimensions as the ImageView that the transition starts with.
// So we'll set it to screen width (plus a little extra, which might fix an issue on some devices..)
.override(width, height)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.priority(Priority.HIGH)
.placeholder(PlaceholderProvider.getInstance(context).getPlaceHolderDrawable(albumArtist.name, true, settingsManager))
.centerCrop()
.animate(AlwaysCrossFade(false))
.into(background!!)
}
override fun setSharedElementEnterTransition(transition: Any?) {
super.setSharedElementEnterTransition(transition)
(transition as Transition).addListener(sharedElementEnterTransitionListenerAdapter)
}
private fun fadeInUi() {
if (textProtectionScrim == null || textProtectionScrim2 == null || fab == null) {
return
}
//Fade in the text protection scrim
textProtectionScrim!!.alpha = 0f
textProtectionScrim!!.visibility = View.VISIBLE
var fadeAnimator = ObjectAnimator.ofFloat(textProtectionScrim, View.ALPHA, 0f, 1f)
fadeAnimator.duration = 600
fadeAnimator.start()
textProtectionScrim2!!.alpha = 0f
textProtectionScrim2!!.visibility = View.VISIBLE
fadeAnimator = ObjectAnimator.ofFloat(textProtectionScrim2, View.ALPHA, 0f, 1f)
fadeAnimator.duration = 600
fadeAnimator.start()
//Fade & grow the FAB
fab!!.alpha = 0f
fab!!.visibility = View.VISIBLE
fadeAnimator = ObjectAnimator.ofFloat(fab, View.ALPHA, 0.5f, 1f)
val scaleXAnimator = ObjectAnimator.ofFloat(fab, View.SCALE_X, 0f, 1f)
val scaleYAnimator = ObjectAnimator.ofFloat(fab, View.SCALE_Y, 0f, 1f)
val animatorSet = AnimatorSet()
animatorSet.playTogether(fadeAnimator, scaleXAnimator, scaleYAnimator)
animatorSet.duration = 250
animatorSet.start()
}
override fun getContextualToolbar(): ContextualToolbar? {
return ctxToolbar as ContextualToolbar
}
private fun setupContextualToolbar() {
val contextualToolbar = ContextualToolbar.findContextualToolbar(this)
if (contextualToolbar != null) {
contextualToolbar.setTransparentBackground(true)
contextualToolbar.menu.clear()
contextualToolbar.inflateMenu(R.menu.context_menu_general)
val subMenu = contextualToolbar.menu.findItem(R.id.addToPlaylist).subMenu
disposables.add(playlistMenuHelper.createUpdatingPlaylistMenu(subMenu).subscribe())
contextualToolbar.setOnMenuItemClickListener(SongMenuUtils.getSongMenuClickListener(Single.defer { Operators.reduceSongSingles(contextualToolbarHelper!!.items) }, presenter))
contextualToolbarHelper = object : ContextualToolbarHelper<Single<List<Song>>>(context!!, contextualToolbar, object : ContextualToolbarHelper.Callback {
override fun notifyItemChanged(viewModel: SelectableViewModel) {
if (adapter.items.contains(viewModel as ViewModel<*>)) {
val index = adapter.items.indexOf(viewModel as ViewModel<*>)
if (index >= 0) {
adapter.notifyItemChanged(index, 0)
}
} else if (horizontalRecyclerView.viewModelAdapter.items.contains(viewModel as ViewModel<*>)) {
val index = horizontalRecyclerView.viewModelAdapter.items.indexOf(viewModel as ViewModel<*>)
if (index >= 0) {
horizontalRecyclerView.viewModelAdapter.notifyItemChanged(index, 0)
}
}
}
override fun notifyDatasetChanged() {
adapter.notifyItemRangeChanged(0, adapter.items.size, 0)
horizontalRecyclerView.viewModelAdapter.notifyItemRangeChanged(0, horizontalRecyclerView.viewModelAdapter.items.size, 0)
}
}) {
override fun start() {
super.start()
// Need to hide the collapsed text, as it overlaps the contextual toolbar
collapsingToolbarTextColor = toolbar_layout.collapsedTitleTextColor
collapsingToolbarSubTextColor = toolbar_layout.collapsedSubTextColor
toolbar_layout.setCollapsedTitleTextColor(0x01FFFFFF)
toolbar_layout.setCollapsedSubTextColor(0x01FFFFFF)
toolbar.visibility = View.GONE
}
override fun finish() {
if (toolbar_layout != null && collapsingToolbarTextColor != null && collapsingToolbarSubTextColor != null) {
toolbar_layout.collapsedTitleTextColor = collapsingToolbarTextColor!!
toolbar_layout.collapsedSubTextColor = collapsingToolbarSubTextColor!!
}
if (toolbar != null) {
toolbar.visibility = View.VISIBLE
}
super.finish()
}
}
}
}
public override fun screenName(): String {
return "ArtistDetailFragment"
}
internal fun pushDetailFragment(fragment: Fragment, transitionView: View?) {
val transitions = ArrayList<Pair<View, String>>()
if (transitionView != null) {
val transitionName = ViewCompat.getTransitionName(transitionView)
transitions.add(Pair(transitionView, transitionName))
// transitions.add(new Pair<>(toolbar, "toolbar"));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
val moveTransition = TransitionInflater.from(context).inflateTransition(R.transition.image_transition)
fragment.sharedElementEnterTransition = moveTransition
fragment.sharedElementReturnTransition = moveTransition
}
}
navigationController.pushViewController(fragment, "DetailFragment", transitions)
}
// ArtistDetailView implementation
override fun setData(albums: List<Album>, songs: List<Song>) {
val viewModels = ArrayList<ViewModel<*>>()
if (!albums.isEmpty()) {
val items = ArrayList<ViewModel<*>>()
if (setHorizontalItemsDisposable != null) {
setHorizontalItemsDisposable!!.dispose()
}
setHorizontalItemsDisposable = horizontalRecyclerView.setItems(albums
.map { album ->
val horizontalAlbumView = HorizontalAlbumView(album, requestManager, sortManager, settingsManager)
horizontalAlbumView.setClickListener(albumClickListener)
horizontalAlbumView.showYear(true)
horizontalAlbumView
})
items.add(SubheaderView(StringUtils.makeAlbumsLabel(context!!, albums.size)))
items.add(horizontalRecyclerView)
viewModels.addAll(items)
}
if (!songs.isEmpty()) {
val items = ArrayList<ViewModel<*>>()
items.add(SubheaderView(StringUtils.makeSongsAndTimeLabel(context!!, songs.size, songs.map { song -> song.duration / 1000 }.sum())))
items.addAll(
songs
.map { song ->
val songView = SongView(song, requestManager, sortManager, settingsManager)
songView.showArtistName(false)
songView.setClickListener(songClickListener)
songView
}.toList()
)
viewModels.addAll(items)
}
if (viewModels.isEmpty()) {
viewModels.add(emptyView)
}
setItemsDisposable = adapter.setItems(viewModels, object : CompletionListUpdateCallbackAdapter() {
override fun onComplete() {
recyclerView?.scheduleLayoutAnimation()
}
})
}
override fun closeContextualToolbar() {
if (contextualToolbarHelper != null) {
contextualToolbarHelper!!.finish()
}
}
// AlbumArtistMenuContract.View Implementation
override fun presentTagEditorDialog(albumArtist: AlbumArtist) {
TaggerDialog.newInstance(albumArtist).show(childFragmentManager)
}
override fun presentArtistDeleteDialog(albumArtists: List<AlbumArtist>) {
DeleteDialog.newInstance(DeleteDialog.ListArtistsRef { albumArtists }).show(childFragmentManager)
}
override fun presentAlbumArtistInfoDialog(albumArtist: AlbumArtist) {
ArtistBiographyDialog.newInstance(albumArtist).show(childFragmentManager)
}
override fun presentArtworkEditorDialog(albumArtist: AlbumArtist) {
ArtworkDialog.build(context, albumArtist).show()
}
// AlbumMenuContract.View Implementation
override fun presentTagEditorDialog(album: Album) {
TaggerDialog.newInstance(album).show(childFragmentManager)
}
override fun presentDeleteAlbumsDialog(albums: List<Album>) {
DeleteDialog.newInstance(DeleteDialog.ListAlbumsRef { albums }).show(childFragmentManager)
}
override fun presentAlbumInfoDialog(album: Album) {
AlbumBiographyDialog.newInstance(album).show(childFragmentManager)
}
override fun presentArtworkEditorDialog(album: Album) {
ArtworkDialog.build(context, album).show()
}
override fun onPlaybackFailed() {
// Todo: Improve error message
Toast.makeText(context, R.string.empty_playlist, Toast.LENGTH_SHORT).show()
}
// SongMenuContract.View Implementation
override fun presentCreatePlaylistDialog(songs: List<Song>) {
CreatePlaylistDialog.newInstance(songs).show(childFragmentManager, "CreatePlaylistDialog")
}
override fun presentSongInfoDialog(song: Song) {
SongInfoDialog.newInstance(song).show(childFragmentManager)
}
override fun onSongsAddedToPlaylist(playlist: Playlist, numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoplaylist, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun onSongsAddedToQueue(numSongs: Int) {
Toast.makeText(context, context!!.resources.getQuantityString(R.plurals.NNNtrackstoqueue, numSongs, numSongs), Toast.LENGTH_SHORT).show()
}
override fun presentTagEditorDialog(song: Song) {
TaggerDialog.newInstance(song).show(childFragmentManager)
}
override fun presentDeleteDialog(songs: List<Song>) {
DeleteDialog.newInstance(DeleteDialog.ListSongsRef { songs }).show(childFragmentManager)
}
override fun shareSong(song: Song) {
song.share(context!!)
}
override fun presentRingtonePermissionDialog() {
RingtoneManager.getDialog(context!!).show()
}
override fun showRingtoneSetMessage() {
Toast.makeText(context, R.string.ringtone_set_new, Toast.LENGTH_SHORT).show()
}
companion object {
private const val TAG = "ArtistDetailFragment"
private const val ARG_TRANSITION_NAME = "transition_name"
private const val ARG_ALBUM_ARTIST = "album_artist"
fun newInstance(albumArtist: AlbumArtist, transitionName: String?): ArtistDetailFragment {
val args = Bundle()
val fragment = ArtistDetailFragment()
args.putSerializable(ARG_ALBUM_ARTIST, albumArtist)
args.putString(ARG_TRANSITION_NAME, transitionName)
fragment.arguments = args
return fragment
}
}
} | gpl-3.0 | af1d7ce0534a15a951ba07fcf1ac406b | 40.151917 | 186 | 0.705591 | 4.970604 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-pushnotifications-kotlin/app/src/main/java/com/quickblox/sample/pushnotifications/kotlin/activities/SplashActivity.kt | 1 | 2095 | package com.quickblox.sample.pushnotifications.kotlin.activities
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.widget.TextView
import com.quickblox.sample.pushnotifications.kotlin.R
import com.quickblox.sample.pushnotifications.kotlin.utils.EXTRA_FCM_MESSAGE
import com.quickblox.sample.pushnotifications.kotlin.utils.SharedPrefsHelper
private const val SPLASH_DELAY = 1500
class SplashActivity : BaseActivity() {
private val TAG = SplashActivity::class.java.simpleName
private var message: String? = null
private val packageInfo: PackageInfo
get() {
try {
return packageManager.getPackageInfo(packageName, 0)
} catch (e: PackageManager.NameNotFoundException) {
throw RuntimeException("Could not get package name: $e")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
supportActionBar?.hide()
val extras = intent.extras
if (extras != null) {
message = intent.extras?.getString(EXTRA_FCM_MESSAGE)
}
fillUI()
startNextScreen()
}
private fun fillUI() {
val versionName = packageInfo.versionName
val appNameTextView = findViewById<TextView>(R.id.text_splash_app_title)
val versionTextView = findViewById<TextView>(R.id.text_splash_app_version)
appNameTextView.text = getString(R.string.app_title)
versionTextView.text = getString(R.string.splash_app_version, versionName)
}
private fun startNextScreen() {
val qbUser = SharedPrefsHelper.getQbUser()
if (qbUser != null) {
MessagesActivity.start(this@SplashActivity, message)
finish()
} else {
Handler().postDelayed({
LoginActivity.start(this@SplashActivity, message)
finish()
}, SPLASH_DELAY.toLong())
}
}
} | bsd-3-clause | 7f4c67f3a3df327348e5b1a59c92dab2 | 31.75 | 82 | 0.66778 | 4.761364 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/Principal.kt | 1 | 1044 | package org.tasks.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "principals",
foreignKeys = [
ForeignKey(
entity = CaldavAccount::class,
parentColumns = arrayOf("cda_id"),
childColumns = arrayOf("account"),
onDelete = ForeignKey.CASCADE
)
],
indices = [Index(value = ["account", "href"], unique = true)]
)
data class Principal(
@PrimaryKey(autoGenerate = true) var id: Long = 0,
val account: Long,
val href: String,
var email: String? = null,
@ColumnInfo(name = "display_name") var displayName: String? = null
) {
val name: String
get() = displayName
?: href
.replace(MAILTO, "")
.replaceFirst(LAST_SEGMENT, "$1")
companion object {
private val MAILTO = "^mailto:".toRegex()
private val LAST_SEGMENT = ".*/([^/]+).*".toRegex()
}
} | gpl-3.0 | 36acf26adf52edb8e794e21ff9e71ebf | 26.5 | 70 | 0.595785 | 4.278689 | false | false | false | false |
dafi/photoshelf | app/src/main/java/com/ternaryop/photoshelf/service/PhotoShelfJobService.kt | 1 | 1740 | package com.ternaryop.photoshelf.service
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import com.ternaryop.photoshelf.birthday.service.BirthdayJob
import java.util.concurrent.TimeUnit
class PhotoShelfJobService : AbsJobService() {
override fun onStartJob(params: JobParameters?): Boolean {
return when (params?.jobId) {
BIRTHDAY_JOB_ID -> BirthdayJob.runJob(this, params)
EXPORT_JOB_ID -> ExportJob.runJob(this, params)
else -> false
}
}
companion object {
const val BIRTHDAY_JOB_ID = 1
const val EXPORT_JOB_ID = 2
private val PERIODIC_BIRTHDAY_MILLIS = TimeUnit.DAYS.toMillis(1)
private val PERIODIC_EXPORT_MILLIS = TimeUnit.HOURS.toMillis(3)
fun scheduleBirthday(context: Context) {
val jobInfo = JobInfo.Builder(BIRTHDAY_JOB_ID, ComponentName(context, PhotoShelfJobService::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPeriodic(PERIODIC_BIRTHDAY_MILLIS)
.build()
(context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(jobInfo)
}
fun scheduleExport(context: Context) {
val jobInfo = JobInfo.Builder(EXPORT_JOB_ID, ComponentName(context, PhotoShelfJobService::class.java))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPeriodic(PERIODIC_EXPORT_MILLIS)
.build()
(context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler).schedule(jobInfo)
}
}
}
| mit | 4cf7bc2f6134a282129960e2c2e013b0 | 38.545455 | 116 | 0.681609 | 4.371859 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/graphs/dataproviders/GraphDataProvider.kt | 1 | 1179 | package nl.sogeti.android.gpstracker.ng.features.graphs.dataproviders
import android.content.Context
import androidx.annotation.WorkerThread
import nl.sogeti.android.gpstracker.ng.features.graphs.widgets.GraphPoint
import nl.sogeti.android.gpstracker.ng.features.summary.Summary
interface GraphDataCalculator {
@WorkerThread
fun calculateGraphPoints(summary: Summary): List<GraphPoint>
val xLabel: Int
val yLabel: Int
fun describeXvalue(context: Context, xValue: Float): String {
return ""
}
fun describeYvalue(context: Context, yValue: Float): String {
return ""
}
fun prettyMinYValue(context: Context, yValue: Float): Float
fun prettyMaxYValue(context: Context, yValue: Float): Float
object DefaultGraphValueDescriptor : GraphDataCalculator {
override fun calculateGraphPoints(summary: Summary) = emptyList<GraphPoint>()
override fun prettyMinYValue(context: Context, yValue: Float) = yValue
override fun prettyMaxYValue(context: Context, yValue: Float) = yValue
override val xLabel: Int
get() = 0
override val yLabel: Int
get() = 1
}
}
| gpl-3.0 | 91fda8a8f4a2564f83e61d9718c3cea4 | 28.475 | 85 | 0.712468 | 4.271739 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/measures/SonarQubeMeasuresSettings.kt | 1 | 837 | package net.nemerosa.ontrack.extension.sonarqube.measures
import net.nemerosa.ontrack.extension.sonarqube.SonarQubeMeasuresList
/**
* List of measures to collect, configured globally.
*
* @property measures List of measures to collect
*/
class SonarQubeMeasuresSettings(
override val measures: List<String>,
val disabled: Boolean,
val coverageThreshold: Int,
val blockerThreshold: Int
) : SonarQubeMeasuresList {
companion object {
const val BLOCKER_VIOLATIONS = "blocker_violations"
const val COVERAGE = "coverage"
val DEFAULT_MEASURES = listOf(
BLOCKER_VIOLATIONS,
COVERAGE
)
const val DEFAULT_DISABLED = false
const val DEFAULT_COVERAGE_THRESHOLD = 80
const val DEFAULT_BLOCKER_THRESHOLD = 5
}
} | mit | 9923a2ff3b8913c7d8c6b35efd3be9cc | 25.1875 | 69 | 0.670251 | 4.702247 | false | false | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/util/HtmlParser.kt | 1 | 1689 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.util
import android.content.res.ColorStateList
import android.os.Build
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.style.URLSpan
import androidx.annotation.ColorInt
class HtmlParser {
/**
* Parse the given input using [TouchableUrlSpan]s rather than vanilla [URLSpan]s
* so that they respond to touch.
*/
fun parse(
input: String,
linkTextColor: ColorStateList,
@ColorInt linkHighlightColor: Int
): SpannableStringBuilder {
var spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(input, Html.FROM_HTML_MODE_LEGACY) as SpannableStringBuilder
} else {
Html.fromHtml(input) as SpannableStringBuilder
}
// strip any trailing newlines
while (spanned.isNotEmpty() && spanned[spanned.length - 1] == '\n') {
spanned = spanned.delete(spanned.length - 1, spanned.length)
}
return HtmlUtils.linkifyPlainLinks(spanned, linkTextColor, linkHighlightColor)
}
}
| apache-2.0 | 84be4d506f9b474a2915a4b9b4e754be | 32.78 | 86 | 0.700414 | 4.421466 | false | false | false | false |
NyaaPantsu/NyaaPantsu-android-app | app/src/main/java/cat/pantsu/nyaapantsu/ui/activity/TorrentActivity.kt | 1 | 2092 | package cat.pantsu.nyaapantsu.ui.activity
import android.os.Bundle
import android.support.v4.view.ViewPager
import cat.pantsu.nyaapantsu.R
import cat.pantsu.nyaapantsu.adapter.ViewPagerAdapter
import cat.pantsu.nyaapantsu.helper.QueryHelper
import cat.pantsu.nyaapantsu.helper.getRecentPlaylistAsArray
import cat.pantsu.nyaapantsu.model.Torrent
import cat.pantsu.nyaapantsu.ui.fragment.TorrentListFragment
import kotlinx.android.synthetic.main.activity_torrent.*
import org.json.JSONArray
import java.util.*
import com.github.se_bastiaan.torrentstream.Torrent as TorrentLib
class TorrentActivity : BaseActivity() {
private var list: LinkedList<Torrent> = LinkedList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_torrent)
val type = intent.getStringExtra("type")
when (type) {
"search" -> {
list = TorrentListFragment.mList
}
"recent" -> {
list = QueryHelper.parseTorrents(getRecentPlaylistAsArray())
}
"upload" -> {
val arr = JSONArray().put(intent.getStringExtra("torrent"))
list = QueryHelper.parseTorrents(arr)
}
}
val adapter = ViewPagerAdapter(supportFragmentManager, list)
val current = intent.getIntExtra("position", 0)
view_pager.adapter = adapter
view_pager.setCurrentItem(current, false)
view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
title = list[position].name + " - " + getString(R.string.nyaapantsu)
}
})
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
title = list[current].name + " - " + getString(R.string.nyaapantsu)
}
}
| mit | cdc6f882193cece36ed3cb973c5f14a2 | 37.036364 | 106 | 0.668738 | 4.787185 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/tasker/ItemFragment.kt | 1 | 3067 | package treehou.se.habit.tasker
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import treehou.se.habit.R
import treehou.se.habit.tasker.items.CommandActionFragment
import treehou.se.habit.tasker.items.IncDecActionFragment
import treehou.se.habit.tasker.items.SwitchActionFragment
import treehou.se.habit.ui.adapter.MenuAdapter
import treehou.se.habit.ui.adapter.MenuItem
class ItemFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_item, container, false)
val menuAdapter = MenuAdapter()
menuAdapter.addItem(MenuItem(getString(R.string.command), MENU_ITEM_COMMAND, R.drawable.ic_icon_sitemap))
menuAdapter.addItem(MenuItem(getString(R.string.label_switch), MENU_ITEM_SWITCH, R.drawable.ic_icon_sitemap))
menuAdapter.addItem(MenuItem(getString(R.string.inc_dec), MENU_ITEM_INC_DEC, R.drawable.ic_icon_sitemap))
val listener = object: MenuAdapter.OnItemSelectListener{
override fun itemClicked(id: Int) {
when (id) {
MENU_ITEM_SWITCH -> activity!!.supportFragmentManager
.beginTransaction()
.replace(container!!.id, SwitchActionFragment.newInstance())
.addToBackStack(null)
.commit()
MENU_ITEM_COMMAND -> activity!!.supportFragmentManager
.beginTransaction()
.replace(container!!.id, CommandActionFragment.newInstance())
.addToBackStack(null)
.commit()
MENU_ITEM_INC_DEC -> activity!!.supportFragmentManager
.beginTransaction()
.replace(container!!.id, IncDecActionFragment.newInstance())
.addToBackStack(null)
.commit()
}
}
}
menuAdapter.setOnItemSelectListener(listener)
val lstItems = rootView.findViewById<View>(R.id.list) as RecyclerView
val gridLayoutManager = GridLayoutManager(activity, 1)
lstItems.layoutManager = gridLayoutManager
lstItems.itemAnimator = DefaultItemAnimator()
lstItems.adapter = menuAdapter
return rootView
}
companion object {
val MENU_ITEM_SWITCH = 0
val MENU_ITEM_COMMAND = 1
val MENU_ITEM_INC_DEC = 2
fun newInstance(): ItemFragment {
val fragment = ItemFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
}
| epl-1.0 | 40db2ae7baafd844aafb124b18a63f9c | 38.320513 | 117 | 0.62341 | 5.036125 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/bungeecord/WaterfallModuleType.kt | 1 | 1396 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.bungeecord
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.facet.MinecraftFacet
import com.demonwav.mcdev.platform.AbstractModuleType
import com.demonwav.mcdev.platform.PlatformType
import com.demonwav.mcdev.platform.bungeecord.generation.BungeeCordEventGenerationPanel
import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants
import com.demonwav.mcdev.util.CommonColors
import com.intellij.psi.PsiClass
object WaterfallModuleType :
AbstractModuleType<BungeeCordModule<WaterfallModuleType>>("io.github.waterfallmc", "waterfall-api") {
private const val ID = "WATERFALL_MODULE_TYPE"
init {
CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS)
}
override val platformType = PlatformType.WATERFALL
override val icon = PlatformAssets.WATERFALL_ICON
override val id = ID
override val ignoredAnnotations = BungeeCordModuleType.IGNORED_ANNOTATIONS
override val listenerAnnotations = BungeeCordModuleType.LISTENER_ANNOTATIONS
override fun generateModule(facet: MinecraftFacet) = BungeeCordModule(facet, this)
override fun getEventGenerationPanel(chosenClass: PsiClass) = BungeeCordEventGenerationPanel(chosenClass)
}
| mit | e364333cd27e3e0dbf13c166665663e3 | 34.794872 | 109 | 0.803725 | 4.474359 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/models/collections/Kotsu.kt | 1 | 3580 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[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 dev.yuriel.kotmahjan.models.collections
import dev.yuriel.kotmahjan.models.Hai
/**
* Created by yuriel on 8/13/16.
* 刻子に関するクラスです
* 暗刻と明刻の両方を扱います
*/
class Kotsu(override var identifierTile: Hai?) : Mentsu() {
/**
* 刻子であることがわかっている場合に利用します
* @param isOpen 暗刻ならばfalse 明刻ならばtrue
* @param identifierTile どの牌の刻子なのか
*/
constructor(isOpen: Boolean, identifierTile: Hai?): this(identifierTile) {
this.isOpen = isOpen
this.isMentsu = true
}
/**
* 刻子であるかのチェックも伴います
* すべての牌(t1~3)が同じ場合にisMentsuがtrueになります
* @param isOpen 暗刻の場合false, 明刻の場合はtrueを入れて下さい
* @param tile1 1枚目
* @param tile2 2枚目
* @param tile3 3枚目
*/
constructor(isOpen: Boolean, tile1: Hai, tile2: Hai, tile3: Hai): this(tile1) {
this.isOpen = isOpen
this.isMentsu = check(tile1, tile2, tile3)
if (!isMentsu) {
identifierTile = null
}
}
override val fu: Int
get() {
var mentsuFu = 2
if (!isOpen) {
mentsuFu *= 2
}
if (identifierTile?.isYaochu() == true) {
mentsuFu *= 2
}
return mentsuFu
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is Kotsu) return false
if (isMentsu !== o.isMentsu) return false
if (isOpen !== o.isOpen) return false
return identifierTile === o.identifierTile
}
override fun hashCode(): Int {
var result: Int = if (identifierTile != null) identifierTile!!.hashCode() else 0
result = 31 * result + if (isMentsu) 1 else 0
result = 31 * result + if (isOpen) 1 else 0
return result
}
companion object {
/**
* 刻子であるかの判定を行ないます
* @param tile1 1枚目
* @param tile2 2枚目
* @param tile3 3枚目
* @return 刻子であればtrue 刻子でなければfalse
*/
fun check(tile1: Hai, tile2: Hai, tile3: Hai): Boolean {
return tile1 sameAs tile2 && tile2 sameAs tile3
}
}
} | mit | 72bc28f2d405e5471a78e553cbdcb4e2 | 30.432692 | 88 | 0.628825 | 3.567686 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/RecursivePictureMenu.kt | 1 | 7992 | /*
* Copyright (c) 2020 David Allison <[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.dialogs
import android.app.Dialog
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.CheckResult
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.DialogFragment
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.AnkiActivity
import com.ichi2.anki.R
import com.ichi2.anki.analytics.UsageAnalytics
import timber.log.Timber
import java.util.*
/** A Dialog displaying The various options for "Help" in a nested structure */
class RecursivePictureMenu : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val items: List<Item> = requireArguments().getParcelableArrayList("bundle")!!
val title = requireContext().getString(requireArguments().getInt("titleRes"))
val adapter: RecyclerView.Adapter<*> = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val root = layoutInflater.inflate(R.layout.material_dialog_list_item, parent, false)
return object : RecyclerView.ViewHolder(root) {}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val textView = holder.itemView as TextView
val item = items[position]
textView.setText(item.title)
textView.setOnClickListener { item.execute(requireActivity() as AnkiActivity) }
val icon = item.mIcon
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(icon, 0, 0, 0)
}
override fun getItemCount(): Int {
return items.size
}
}
val dialog = MaterialDialog.Builder(requireContext())
.adapter(adapter, null)
.title(title)
.show()
setMenuBreadcrumbHeader(dialog)
val v = dialog.findViewById(R.id.md_contentRecyclerView)
v.setPadding(v.paddingLeft, v.paddingTop, v.paddingRight, 0)
// DEFECT: There is 9dp of bottom margin which I can't seem to get rid of.
return dialog
}
protected fun setMenuBreadcrumbHeader(dialog: MaterialDialog) {
try {
val titleFrame = dialog.findViewById(R.id.md_titleFrame)
titleFrame.setPadding(10, 22, 10, 10)
titleFrame.setOnClickListener { dismiss() }
val icon = dialog.findViewById(R.id.md_icon) as ImageView
icon.visibility = View.VISIBLE
val iconValue = AppCompatResources.getDrawable(requireContext(), R.drawable.ic_menu_back_black_24dp)
iconValue!!.isAutoMirrored = true
icon.setImageDrawable(iconValue)
} catch (e: Exception) {
Timber.w(e, "Failed to set Menu title/icon")
}
}
abstract class Item : Parcelable {
@get:StringRes
@StringRes
val title: Int
@DrawableRes
val mIcon: Int
private val mAnalyticsId: String?
constructor(@StringRes titleString: Int, @DrawableRes iconDrawable: Int, analyticsId: String?) {
title = titleString
mIcon = iconDrawable
mAnalyticsId = analyticsId
}
open val children: List<Item?>
get() = ArrayList(0)
protected constructor(parcel: Parcel) {
title = parcel.readInt()
mIcon = parcel.readInt()
mAnalyticsId = parcel.readString()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeInt(title)
dest.writeInt(mIcon)
dest.writeString(mAnalyticsId)
}
protected abstract fun onClicked(activity: AnkiActivity)
fun sendAnalytics() {
UsageAnalytics.sendAnalyticsEvent(UsageAnalytics.Category.LINK_CLICKED, mAnalyticsId!!)
}
/* This method calls onClicked method to handle click event in a suitable manner and
* the analytics of the item clicked are send.
*/
fun execute(activity: AnkiActivity) {
sendAnalytics()
onClicked(activity)
}
abstract fun remove(toRemove: Item?)
}
class ItemHeader : Item, Parcelable {
private val mChildren: MutableList<Item?>?
constructor(@StringRes titleString: Int, i: Int, analyticsStringId: String?, vararg children: Item?) : super(titleString, i, analyticsStringId) {
mChildren = ArrayList(listOf(*children))
}
override val children: List<Item?>
get() = ArrayList(mChildren!!.toMutableList())
public override fun onClicked(activity: AnkiActivity) {
val children = ArrayList(children)
val nextFragment: DialogFragment = createInstance(children, title)
activity.showDialogFragment(nextFragment)
}
override fun remove(toRemove: Item?) {
mChildren!!.remove(toRemove)
for (i in mChildren) {
i!!.remove(toRemove)
}
}
protected constructor(parcel: Parcel) : super(parcel) {
if (parcel.readByte().toInt() == 0x01) {
mChildren = ArrayList()
parcel.readList(mChildren, Item::class.java.classLoader)
} else {
mChildren = ArrayList(0)
}
}
override fun writeToParcel(dest: Parcel, flags: Int) {
super.writeToParcel(dest, flags)
if (mChildren == null) {
dest.writeByte(0x00.toByte())
} else {
dest.writeByte(0x01.toByte())
dest.writeList(mChildren)
}
}
companion object {
val CREATOR: Parcelable.Creator<ItemHeader?> = object : Parcelable.Creator<ItemHeader?> {
override fun createFromParcel(parcel: Parcel): ItemHeader {
return ItemHeader(parcel)
}
override fun newArray(size: Int): Array<ItemHeader?> {
return arrayOfNulls(size)
}
}
}
}
companion object {
@JvmStatic
@CheckResult
fun createInstance(itemList: ArrayList<Item?>?, @StringRes title: Int): RecursivePictureMenu {
val helpDialog = RecursivePictureMenu()
val args = Bundle()
args.putParcelableArrayList("bundle", itemList)
args.putInt("titleRes", title)
helpDialog.arguments = args
return helpDialog
}
@JvmStatic
fun removeFrom(allItems: List<Item>, toRemove: Item?) {
// Note: currently doesn't remove the top-level elements.
for (i in allItems) {
i.remove(toRemove)
}
}
}
}
| gpl-3.0 | a43b08f0aafc67a0ffd698685ff213e0 | 36.345794 | 153 | 0.625 | 4.979439 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/noteeditor/FieldState.kt | 1 | 8699 | /*
* Copyright (c) 2020 David Allison <[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.noteeditor
import android.content.Context
import android.os.Bundle
import android.util.Pair
import android.util.SparseArray
import android.view.View
import com.ichi2.anki.FieldEditLine
import com.ichi2.anki.NoteEditor
import com.ichi2.anki.R
import com.ichi2.libanki.Model
import com.ichi2.libanki.Models
import com.ichi2.utils.JSONObject
import com.ichi2.utils.MapUtil.getKeyByValue
import java.util.*
/** Responsible for recreating EditFieldLines after NoteEditor operations
* This primarily exists so we can use saved instance state to repopulate the dynamically created FieldEditLine
*/
class FieldState private constructor(private val editor: NoteEditor) {
private var mSavedFieldData: List<View.BaseSavedState>? = null
fun loadFieldEditLines(type: FieldChangeType): List<FieldEditLine> {
val fieldEditLines: List<FieldEditLine>
if (type.type == Type.INIT && mSavedFieldData != null) {
fieldEditLines = recreateFieldsFromState()
mSavedFieldData = null
} else {
fieldEditLines = createFields(type)
}
for (l in fieldEditLines) {
l.id = View.generateViewId()
}
if (type.type == Type.CLEAR_KEEP_STICKY) {
// we use the UI values here as the model will post-processing steps (newline -> br).
val currentFieldStrings = editor.currentFieldStrings
val flds = editor.currentFields
for (fldIdx in 0 until flds.length()) {
if (flds.getJSONObject(fldIdx).getBoolean("sticky")) {
fieldEditLines[fldIdx].setContent(currentFieldStrings[fldIdx], type.replaceNewlines)
}
}
}
if (type.type == Type.CHANGE_FIELD_COUNT) {
val currentFieldStrings = editor.currentFieldStrings
for (i in 0 until Math.min(currentFieldStrings.size, fieldEditLines.size)) {
fieldEditLines[i].setContent(currentFieldStrings[i], type.replaceNewlines)
}
}
return fieldEditLines
}
private fun recreateFieldsFromState(): List<FieldEditLine> {
val editLines: MutableList<FieldEditLine> = ArrayList(mSavedFieldData!!.size)
for (state in mSavedFieldData!!) {
val edit_line_view = FieldEditLine(editor)
if (edit_line_view.id == 0) {
edit_line_view.id = View.generateViewId()
}
edit_line_view.loadState(state)
editLines.add(edit_line_view)
}
return editLines
}
protected fun createFields(type: FieldChangeType): List<FieldEditLine> {
val fields = getFields(type)
val editLines: MutableList<FieldEditLine> = ArrayList(fields.size)
for (i in fields.indices) {
val edit_line_view = FieldEditLine(editor)
editLines.add(edit_line_view)
edit_line_view.name = fields[i][0]
edit_line_view.setContent(fields[i][1], type.replaceNewlines)
edit_line_view.setOrd(i)
}
return editLines
}
private fun getFields(type: FieldChangeType): Array<Array<String?>> {
if (type.type == Type.REFRESH_WITH_MAP) {
val items = editor.fieldsFromSelectedNote
val fMapNew = Models.fieldMap(type.newModel!!)
return fromFieldMap(editor, items, fMapNew, type.modelChangeFieldMap)
}
return editor.fieldsFromSelectedNote
}
fun setInstanceState(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
return
}
if (!savedInstanceState.containsKey("customViewIds") || !savedInstanceState.containsKey("android:viewHierarchyState")) {
return
}
val customViewIds = savedInstanceState.getIntegerArrayList("customViewIds")
val viewHierarchyState = savedInstanceState.getBundle("android:viewHierarchyState")
if (customViewIds == null || viewHierarchyState == null) {
return
}
val views = viewHierarchyState["android:views"] as SparseArray<*>? ?: return
val important: MutableList<View.BaseSavedState> = ArrayList(customViewIds.size)
for (i in customViewIds) {
important.add(views[i!!] as View.BaseSavedState)
}
mSavedFieldData = important
}
/** How fields should be changed when the UI is rebuilt */
class FieldChangeType(val type: Type, val replaceNewlines: Boolean) {
var modelChangeFieldMap: Map<Int, Int>? = null
var newModel: Model? = null
companion object {
@JvmStatic
fun refreshWithMap(newModel: Model?, modelChangeFieldMap: Map<Int, Int>?, replaceNewlines: Boolean): FieldChangeType {
val typeClass = FieldChangeType(Type.REFRESH_WITH_MAP, replaceNewlines)
typeClass.newModel = newModel
typeClass.modelChangeFieldMap = modelChangeFieldMap
return typeClass
}
@JvmStatic
fun refresh(replaceNewlines: Boolean): FieldChangeType {
return frotype(Type.REFRESH, replaceNewlines)
}
@JvmStatic
fun refreshWithStickyFields(replaceNewlines: Boolean): FieldChangeType {
return frotype(Type.CLEAR_KEEP_STICKY, replaceNewlines)
}
@JvmStatic
fun changeFieldCount(replaceNewlines: Boolean): FieldChangeType {
return frotype(Type.CHANGE_FIELD_COUNT, replaceNewlines)
}
@JvmStatic
fun onActivityCreation(replaceNewlines: Boolean): FieldChangeType {
return frotype(Type.INIT, replaceNewlines)
}
private fun frotype(type: Type, replaceNewlines: Boolean): FieldChangeType {
return FieldChangeType(type, replaceNewlines)
}
}
}
enum class Type {
INIT, CLEAR_KEEP_STICKY, CHANGE_FIELD_COUNT, REFRESH, REFRESH_WITH_MAP
}
companion object {
private fun allowFieldRemapping(oldFields: Array<Array<String>>): Boolean {
return oldFields.size > 2
}
@JvmStatic
fun fromEditor(editor: NoteEditor): FieldState {
return FieldState(editor)
}
private fun fromFieldMap(context: Context, oldFields: Array<Array<String>>, fMapNew: Map<String, Pair<Int, JSONObject>>, modelChangeFieldMap: Map<Int, Int>?): Array<Array<String?>> {
// Build array of label/values to provide to field EditText views
val fields = Array(fMapNew.size) { arrayOfNulls<String>(2) }
for (fname in fMapNew.keys) {
val fieldPair = fMapNew[fname] ?: continue
// Field index of new note type
val i = fieldPair.first
// Add values from old note type if they exist in map, otherwise make the new field empty
if (modelChangeFieldMap!!.containsValue(i)) {
// Get index of field from old note type given the field index of new note type
val j = getKeyByValue(modelChangeFieldMap, i) ?: continue
// Set the new field label text
if (allowFieldRemapping(oldFields)) {
// Show the content of old field if remapping is enabled
fields[i][0] = String.format(context.resources.getString(R.string.field_remapping), fname, oldFields[j][0])
} else {
fields[i][0] = fname
}
// Set the new field label value
fields[i][1] = oldFields[j][1]
} else {
// No values from old note type exist in the mapping
fields[i][0] = fname
fields[i][1] = ""
}
}
return fields
}
}
}
| gpl-3.0 | cd128e22cce02edc9680af4d6af0883b | 41.024155 | 190 | 0.622255 | 4.884335 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-github/mvp/src/main/java/com/bennyhuo/mvp/impl/BaseFragment.kt | 2 | 2966 | package com.bennyhuo.mvp.impl
import android.os.Bundle
import android.support.v4.app.Fragment
import com.bennyhuo.mvp.IMvpView
import com.bennyhuo.mvp.IPresenter
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import kotlin.coroutines.experimental.buildSequence
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.primaryConstructor
import kotlin.reflect.jvm.jvmErasure
abstract class BaseFragment<out P: BasePresenter<BaseFragment<P>>>: IMvpView<P>,Fragment() {
override val presenter: P
init {
presenter = createPresenterKt()
presenter.view = this
}
private fun createPresenterKt(): P {
buildSequence {
var thisClass: KClass<*> = this@BaseFragment::class
while (true){
yield(thisClass.supertypes)
//jvmErasure:返回表示在JVM上将此类型擦除到的运行时类的KClass实例
thisClass = thisClass.supertypes.firstOrNull()?.jvmErasure?: break
}
}.flatMap {
//arguments 表示类型参数
it.flatMap { it.arguments }.asSequence()
}.first {
//KTypeProjection 表示类型投影
it.type?.jvmErasure?.isSubclassOf(IPresenter::class) ?: false
}.let {
return it.type!!.jvmErasure.primaryConstructor!!.call() as P
}
}
private fun createPresenter(): P {
buildSequence<Type> {
var thisClass: Class<*> = [email protected]
while (true) {
yield(thisClass.genericSuperclass)
thisClass = thisClass.superclass ?: break
}
}.filter {
it is ParameterizedType
}.flatMap {
(it as ParameterizedType).actualTypeArguments.asSequence()
}.first {
it is Class<*> && IPresenter::class.java.isAssignableFrom(it)
}.let {
return (it as Class<P>).newInstance()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
presenter.onCreate(savedInstanceState)
}
override fun onStart() {
super.onStart()
presenter.onStart()
}
override fun onResume() {
super.onResume()
presenter.onResume()
}
override fun onPause() {
super.onPause()
presenter.onPause()
}
override fun onStop() {
super.onStop()
presenter.onStop()
}
override fun onDestroy() {
presenter.onDestroy()
super.onDestroy()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
presenter.onSaveInstanceState(outState)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
presenter.onViewStateRestored(savedInstanceState)
}
} | apache-2.0 | 935654bb6413e896dad8ca8c76085fd7 | 27.99 | 92 | 0.629745 | 4.962329 | false | false | false | false |
edvin/tornadofx | src/test/kotlin/tornadofx/tests/AsyncTest.kt | 2 | 3399 | package tornadofx.tests
import javafx.scene.control.Button
import javafx.scene.layout.BorderPane
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.stage.Stage
import org.junit.Assert
import org.junit.Test
import org.testfx.api.FxToolkit
import tornadofx.*
import java.util.concurrent.CountDownLatch
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class AsyncTest {
val primaryStage: Stage = FxToolkit.registerPrimaryStage()
@Test
fun runAsyncWithOverlay() {
//Initially container has embedded node
val container = BorderPane()
val node = Pane()
val mask = Pane()
container.center = node
assertEquals(container.center, node)
//This latch will be used to control asynchronously executed task, it's a part of the test
val latch = Latch()
assertTrue(latch.locked)
//This is a standard CountDownLatch and will be used to synchronize test thread with application thread
val appThreadLatch = CountDownLatch(1)
//ui is needed here because only after task is executed we can check if overlay is removed propertly
//and it can only be used from within a UIComponent, so we need a temporary object
val component = object : Controller() {
fun run() = node.runAsyncWithOverlay(latch, null, mask) ui { appThreadLatch.countDown() }
}
component.run()
//Until latch is released, a node is replaced with StackPane containing both the original component and the mask
assertNotEquals(node, container.center)
assertTrue(container.center is StackPane)
assertTrue((container.center as StackPane).children.containsAll(setOf(node, mask)))
//The working thread (test thread in this case) proceeds, which should result in removing overlay
latch.release()
assertFalse(latch.locked)
//Waiting until we have confirmed post-task ui execution
appThreadLatch.await()
//At this point overlay should be removed and node should be again in its original place
assertEquals(node, container.center)
}
@Test
fun latch() {
//Latch set for 5 concurrent tasks
val count = 5
val latch = Latch(count)
val button = Button()
assertFalse(button.disabledProperty().value)
//Button should stay disabled until all tasks are over
button.disableWhen(latch.lockedProperty())
(1..count).forEach {
assertTrue(button.disabledProperty().value)
assertTrue(latch.locked)
assertTrue(latch.lockedProperty().value)
latch.countDown()
//Latch count should decrease after each iteration
Assert.assertEquals(count, (it + latch.count).toInt())
}
assertFalse(button.disabledProperty().value)
assertFalse(latch.locked)
//Should have no effect anyway
latch.release()
assertFalse(button.disabledProperty().value)
assertFalse(latch.locked)
}
@Test
fun runAsync() {
tornadofx.runAsync(daemon = true) {
assertTrue { Thread.currentThread().isDaemon }
}
tornadofx.runAsync {
assertFalse { Thread.currentThread().isDaemon }
}
}
} | apache-2.0 | 432fc0b5fcee5af165782b33bcb2c1f6 | 32.663366 | 120 | 0.672257 | 4.904762 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.