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
hermantai/samples
android/cheesefinder-starter/app/src/main/java/com/raywenderlich/android/cheesefinder/database/CheeseDatabase.kt
1
2406
package com.raywenderlich.android.cheesefinder.database /* * Copyright (c) 2019 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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. */ import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import android.content.Context @Database(entities = [(Cheese::class)], version = 1) abstract class CheeseDatabase : RoomDatabase() { abstract fun cheeseDao(): CheeseDao companion object { private var INSTANCE: CheeseDatabase? = null fun getInstance(context: Context): CheeseDatabase { if (INSTANCE == null) { synchronized(this) { INSTANCE = Room.databaseBuilder(context, CheeseDatabase::class.java, "cheese.db") .build() } } return INSTANCE as CheeseDatabase } fun destroyInstance() { INSTANCE = null } } }
apache-2.0
ab267367696ce726e6bc25473afb7fdc
37.806452
82
0.736076
4.514071
false
false
false
false
hzsweers/CatchUp
libraries/util/src/main/kotlin/io/sweers/catchup/util/TimberExt.kt
1
2898
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package io.sweers.catchup.util import timber.log.Timber /* * Adapted from [Slimber](https://github.com/PaulWoitaschek/Slimber/blob/bea76b32563906edc8cf196ce4b6cfce8d12d6e6/slimber/src/main/kotlin/de/paul_woitaschek/slimber/Slimber.kt) */ /** Invokes an action if any trees are planted */ inline fun ifPlanted(action: () -> Unit) { if (Timber.treeCount != 0) { action() } } /** Delegates the provided message to [Timber.e] if any trees are planted. */ inline fun e(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.e(it, message()) } ?: run { Timber.e(message()) } } /** Delegates the provided message to [Timber.w] if any trees are planted. */ inline fun w(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.w(it, message()) } ?: run { Timber.w(message()) } } /** Delegates the provided message to [Timber.i] if any trees are planted. */ inline fun i(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.i(it, message()) } ?: run { Timber.i(message()) } } /** Delegates the provided message to [Timber.d] if any trees are planted. */ inline fun d(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.d(it, message()) } ?: run { Timber.d(message()) } } /** Delegates the provided message to [Timber.v] if any trees are planted. */ inline fun v(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.v(it, message()) } ?: run { Timber.v(message()) } } /** Delegates the provided message to [Timber.wtf] if any trees are planted. */ inline fun wtf(throwable: Throwable? = null, message: () -> String) = ifPlanted { throwable?.let { Timber.wtf(it, message()) } ?: run { Timber.wtf(message()) } } /** Delegates the provided message to [Timber.log] if any trees are planted. */ inline fun log(priority: Int, t: Throwable, message: () -> String) = ifPlanted { Timber.log(priority, t, message()) } /** Delegates the provided message to [Timber.log] if any trees are planted. */ inline fun log(priority: Int, message: () -> String) = ifPlanted { Timber.log(priority, message()) }
apache-2.0
b1afa775e7158c1b567204d92dea29d5
29.505263
176
0.670462
3.389474
false
false
false
false
andgate/Ikou
core/src/com/andgate/ikou/input/PlayerControllerListener.kt
1
2706
/* This file is part of Ikou. Ikou 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 2 of the License. Ikou 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 Ikou. If not, see <http://www.gnu.org/licenses/>. */ package com.andgate.ikou.input import com.andgate.ikou.actor.Scene import com.andgate.ikou.actor.camera.CameraActor import com.andgate.ikou.actor.maze.messages.MovePlayerMessage import com.andgate.ikou.input.mappings.OuyaPad import com.andgate.ikou.input.mappings.Xbox360Pad import com.andgate.ikou.utility.math.ScreenSpaceTranslator import com.badlogic.gdx.controllers.Controller import com.badlogic.gdx.controllers.ControllerAdapter class PlayerControllerListener(private val scene: Scene, private val playerId: String) : ControllerAdapter() { private val trans = ScreenSpaceTranslator() private val cam = scene.actors["camera"] as CameraActor private var xAxisLeft: Int = -1 private var yAxisLeft: Int = -1 private var xAxisValue: Float = 0.0f private var yAxisValue: Float = 0.0f fun update(delta_time: Float) { if(!(xAxisValue == 0f && yAxisValue == 0f)) { val dir = trans.toMaxDirection(xAxisValue, yAxisValue, cam.angleX) scene.dispatcher.push(MovePlayerMessage(dir, playerId)) xAxisValue = 0f yAxisValue = 0f } } override fun axisMoved(controller: Controller, axisIndex: Int, value: Float): Boolean { mapToController(controller) val validValue: Float = if (Math.abs(value) >= 0.9f) value else 0f if(axisIndex == xAxisLeft) { xAxisValue = validValue } else if(axisIndex == yAxisLeft) { yAxisValue = validValue } return false; } private fun mapToController(controller: Controller) { if(Xbox360Pad.isXbox360Controller(controller)) { xAxisLeft = Xbox360Pad.AXIS_LEFT_X yAxisLeft = Xbox360Pad.AXIS_LEFT_Y } else if(OuyaPad.isOuyaController(controller)) { xAxisLeft = OuyaPad.AXIS_LEFT_X yAxisLeft = OuyaPad.AXIS_LEFT_Y } else { xAxisLeft = -1 yAxisLeft = -1 } } }
gpl-2.0
5787e76f325277108dfead54caaea0af
30.465116
89
0.652993
4.150307
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/GitNotificationIdsHolder.kt
4
10296
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea import com.intellij.notification.impl.NotificationIdsHolder class GitNotificationIdsHolder : NotificationIdsHolder { override fun getNotificationIds(): List<String> { return listOf( BRANCH_CHECKOUT_FAILED, BRANCH_CREATION_FAILED, BRANCH_DELETED, BRANCH_DELETION_ROLLBACK_ERROR, BRANCH_OPERATION_ERROR, BRANCH_OPERATION_SUCCESS, BRANCH_SET_UPSTREAM_ERROR, BRANCH_RENAME_ROLLBACK_FAILED, BRANCH_RENAME_ROLLBACK_SUCCESS, BRANCHES_UPDATE_SUCCESSFUL, CANNOT_RESOLVE_CONFLICT, CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_ERROR, CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_SUCCESSFUL, CHECKOUT_ROLLBACK_ERROR, CHECKOUT_SUCCESS, CHERRY_PICK_ABORT_FAILED, CHERRY_PICK_ABORT_SUCCESS, CLONE_FAILED, CLONE_ERROR_UNABLE_TO_CREATE_DESTINATION_DIR, COLLECT_UPDATED_CHANGES_ERROR, COMMIT_CANCELLED, COMMIT_EDIT_SUCCESS, CONFLICT_RESOLVING_ERROR, COULD_NOT_COMPARE_WITH_BRANCH, COULD_NOT_LOAD_CHANGES_OF_COMMIT, COULD_NOT_LOAD_CHANGES_OF_COMMIT_LOG, COULD_NOT_SAVE_UNCOMMITTED_CHANGES, BRANCH_CREATE_ROLLBACK_SUCCESS, BRANCH_CREATE_ROLLBACK_ERROR, DELETE_BRANCH_ON_MERGE, FETCH_ERROR, FETCH_SUCCESS, FETCH_CANCELLED, FETCH_DETAILS, FETCH_RESULT, FETCH_RESULT_ERROR, FILES_UPDATED_AFTER_MERGE, FILES_UP_TO_DATE, FIX_TRACKED_NOT_ON_BRANCH, INIT_ERROR, INIT_FAILED, INIT_STAGE_FAILED, LOCAL_CHANGES_NOT_RESTORED, MERGE_ABORT_FAILED, MERGE_ABORT_SUCCESS, MERGE_ERROR, MERGE_FAILED, LOCAL_CHANGES_DETECTED, MERGE_RESET_ERROR, MERGE_ROLLBACK_ERROR, PROJECT_UPDATED, PROJECT_PARTIALLY_UPDATED, PULL_FAILED, PUSH_RESULT, PUSH_NOT_SUPPORTED, REBASE_ABORT_FAILED, REBASE_ABORT, REBASE_ABORT_SUCCESS, REBASE_CANNOT_ABORT, REBASE_CANNOT_CONTINUE, REBASE_COMMIT_EDIT_UNDO_ERROR, REBASE_COMMIT_EDIT_UNDO_ERROR_PROTECTED_BRANCH, REBASE_COMMIT_EDIT_UNDO_ERROR_REPO_CHANGES, REBASE_NOT_ALLOWED, REBASE_NOT_STARTED, REBASE_ROLLBACK_FAILED, REBASE_SUCCESSFUL, REBASE_UPDATE_PROJECT_ERROR, REMOTE_BRANCH_DELETION_ERROR, REMOTE_BRANCH_DELETION_SUCCESS, REPOSITORY_CREATED, RESET_FAILED, RESET_PARTIALLY_FAILED, RESET_SUCCESSFUL, REVERT_ABORT_FAILED, REVERT_ABORT_SUCCESS, STAGE_COMMIT_ERROR, STAGE_COMMIT_SUCCESS, STASH_FAILED, STASH_LOCAL_CHANGES_DETECTED, TAG_CREATED, TAG_NOT_CREATED, TAG_DELETED, TAG_DELETION_ROLLBACK_ERROR, TAG_REMOTE_DELETION_ERROR, TAG_REMOTE_DELETION_SUCCESS, TAG_RESTORED, UNRESOLVED_CONFLICTS, UNSTASH_FAILED, UNSTASH_PATCH_APPLIED, UNSTASH_WITH_CONFLICTS, UNSTASH_UNRESOLVED_CONFLICTS, UPDATE_DETACHED_HEAD_ERROR, UPDATE_ERROR, UPDATE_NO_TRACKED_BRANCH, UPDATE_NOTHING_TO_UPDATE, BAD_EXECUTABLE, REBASE_STOPPED_ON_CONFLICTS, REBASE_STOPPED_ON_EDITING, REBASE_FAILED, UNTRACKED_FIES_OVERWITTEN, TAGS_LOADING_FAILED ) } companion object { const val BRANCH_CHECKOUT_FAILED = "git.branch.checkout.failed" const val BRANCH_CREATION_FAILED = "git.branch.creation.failed" const val BRANCH_DELETED = "git.branch.deleted" const val BRANCH_DELETION_ROLLBACK_ERROR = "git.branch.deletion.rollback.error" const val BRANCH_OPERATION_ERROR = "git.branch.operation.error" const val BRANCH_OPERATION_SUCCESS = "git.branch.operation.success" const val BRANCH_SET_UPSTREAM_ERROR = "git.branch.set.upstream.failed" const val BRANCH_RENAME_ROLLBACK_FAILED = "git.branch.rename.rollback.failed" const val BRANCH_RENAME_ROLLBACK_SUCCESS = "git.branch.rename.rollback.success" const val BRANCHES_UPDATE_SUCCESSFUL = "git.branches.update.successful" const val CANNOT_RESOLVE_CONFLICT = "git.cannot.resolve.conflict" const val CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_ERROR = "git.checkout.new.branch.operation.rollback.error" const val CHECKOUT_NEW_BRANCH_OPERATION_ROLLBACK_SUCCESSFUL = "git.checkout.new.branch.operation.rollback.successful" const val CHECKOUT_ROLLBACK_ERROR = "git.checkout.rollback.error" const val CHECKOUT_SUCCESS = "git.checkout.success" const val CHERRY_PICK_ABORT_FAILED = "git.cherry.pick.abort.failed" const val CHERRY_PICK_ABORT_SUCCESS = "git.cherry.pick.abort.success" const val CLONE_FAILED = "git.clone.failed" const val CLONE_ERROR_UNABLE_TO_CREATE_DESTINATION_DIR = "git.clone.unable.to.create.destination.dir" const val COLLECT_UPDATED_CHANGES_ERROR = "git.rebase.collect.updated.changes.error" const val COMMIT_CANCELLED = "git.commit.cancelled" const val COMMIT_EDIT_SUCCESS = "git.commit.edit.success" const val CONFLICT_RESOLVING_ERROR = "git.conflict.resolving.error" const val COULD_NOT_COMPARE_WITH_BRANCH = "git.could.not.compare.with.branch" const val COULD_NOT_LOAD_CHANGES_OF_COMMIT = "git.could.not.load.changes.of.commit" const val COULD_NOT_LOAD_CHANGES_OF_COMMIT_LOG = "git.log.could.not.load.changes.of.commit" const val COULD_NOT_SAVE_UNCOMMITTED_CHANGES = "git.could.not.save.uncommitted.changes" const val BRANCH_CREATE_ROLLBACK_SUCCESS = "git.create.branch.rollback.successful" const val BRANCH_CREATE_ROLLBACK_ERROR = "git.create.branch.rollback.error" const val DELETE_BRANCH_ON_MERGE = "git.delete.branch.on.merge" const val FETCH_ERROR = "git.fetch.error" const val FETCH_SUCCESS = "git.fetch.success" const val FETCH_CANCELLED = "git.fetch.cancelled" const val FETCH_DETAILS = "git.fetch.details" const val FETCH_RESULT = "git.fetch.result" const val FETCH_RESULT_ERROR = "git.fetch.result.error" const val FILES_UPDATED_AFTER_MERGE = "git.files.updated.after.merge" const val FILES_UP_TO_DATE = "git.all.files.are.up.to.date" const val FIX_TRACKED_NOT_ON_BRANCH = "git.fix.tracked.not.on.branch" const val INIT_ERROR = "git.init.error" const val INIT_FAILED = "git.init.failed" const val INIT_STAGE_FAILED = "git.init.stage.failed" const val LOCAL_CHANGES_NOT_RESTORED = "git.local.changes.not.restored" const val MERGE_ABORT_FAILED = "git.merge.abort.failed" const val MERGE_ABORT_SUCCESS = "git.merge.abort.success" const val MERGE_ERROR = "git.merge.error" const val MERGE_FAILED = "git.merge.failed" const val LOCAL_CHANGES_DETECTED = "git.merge.local.changes.detected" const val MERGE_RESET_ERROR = "git.merge.reset.error" const val MERGE_ROLLBACK_ERROR = "git.merge.rollback.error" const val PROJECT_UPDATED = "git.project.updated" const val PROJECT_PARTIALLY_UPDATED = "git.project.partially.updated" const val PULL_FAILED = "git.pull.failed" const val PUSH_RESULT = "git.push.result" const val PUSH_NOT_SUPPORTED = "git.push.not.supported" const val REBASE_ABORT_FAILED = "git.rebase.abort.failed" const val REBASE_ABORT = "git.rebase.abort" const val REBASE_ABORT_SUCCESS = "git.rebase.abort.succeeded" const val REBASE_CANNOT_ABORT = "git.rebase.cannot.abort" const val REBASE_CANNOT_CONTINUE = "git.rebase.cannot.continue" const val REBASE_COMMIT_EDIT_UNDO_ERROR = "git.rebase.commit.edit.undo.error" const val REBASE_COMMIT_EDIT_UNDO_ERROR_PROTECTED_BRANCH = "git.rebase.commit.edit.undo.error.protected.branch" const val REBASE_COMMIT_EDIT_UNDO_ERROR_REPO_CHANGES = "git.rebase.commit.edit.undo.error.repo.changed" const val REBASE_NOT_ALLOWED = "git.rebase.not.allowed" const val REBASE_NOT_STARTED = "git.rebase.not.started" const val REBASE_ROLLBACK_FAILED = "git.rebase.rollback.failed" const val REBASE_SUCCESSFUL = "git.rebase.successful" const val REBASE_UPDATE_PROJECT_ERROR = "git.rebase.update.project.error" const val REMOTE_BRANCH_DELETION_ERROR = "git.remote.branch.deletion.error" const val REMOTE_BRANCH_DELETION_SUCCESS = "git.remote.branch.deletion.success" const val REPOSITORY_CREATED = "git.repository.created" const val RESET_FAILED = "git.reset.failed" const val RESET_PARTIALLY_FAILED = "git.reset.partially.failed" const val RESET_SUCCESSFUL = "git.reset.successful" const val REVERT_ABORT_FAILED = "git.revert.abort.failed" const val REVERT_ABORT_SUCCESS = "git.revert.abort.success" const val STAGE_COMMIT_ERROR = "git.stage.commit.error" const val STAGE_COMMIT_SUCCESS = "git.stage.commit.successful" const val STASH_FAILED = "git.stash.failed" const val STASH_LOCAL_CHANGES_DETECTED = "git.stash.local.changes.detected" const val TAG_CREATED = "git.tag.created" const val TAG_NOT_CREATED = "git.tag.not.created" const val TAG_DELETED = "git.tag.deleted" const val TAG_DELETION_ROLLBACK_ERROR = "git.tag.deletion.rollback.error" const val TAG_REMOTE_DELETION_ERROR = "git.tag.remote.deletion.error" const val TAG_REMOTE_DELETION_SUCCESS = "git.tag.remote.deletion.success" const val TAG_RESTORED = "git.tag.restored" const val UNRESOLVED_CONFLICTS = "git.unresolved.conflicts" const val UNSTASH_FAILED = "git.unstash.failed" const val UNSTASH_PATCH_APPLIED = "git.unstash.patch.applied" const val UNSTASH_WITH_CONFLICTS = "git.unstash.with.conflicts" const val UNSTASH_UNRESOLVED_CONFLICTS = "git.unstash.with.unresolved.conflicts" const val UPDATE_DETACHED_HEAD_ERROR = "git.update.detached.head.error" const val UPDATE_ERROR = "git.update.error" const val UPDATE_NO_TRACKED_BRANCH = "git.update.no.tracked.branch.error" const val UPDATE_NOTHING_TO_UPDATE = "git.update.nothing.to.update" const val BAD_EXECUTABLE = "git.bad.executable" const val REBASE_STOPPED_ON_CONFLICTS = "git.rebase.stopped.due.to.conflicts" const val REBASE_STOPPED_ON_EDITING = "git.rebase.stopped.for.editing" const val REBASE_FAILED = "git.rebase.failed" const val UNTRACKED_FIES_OVERWITTEN = "untracked.files.overwritten" const val TAGS_LOADING_FAILED = "git.tags.loading.failed" } }
apache-2.0
9ed0799c94e0e2089db8f274cd04c909
46.233945
121
0.715521
3.579972
false
false
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/common/NotificationStatus.kt
1
3135
package com.czbix.v2ex.common import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.annotation.IntDef import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.czbix.v2ex.AppCtx import com.czbix.v2ex.R import com.czbix.v2ex.event.BaseEvent.NewUnreadEvent import com.czbix.v2ex.helper.RxBus import com.czbix.v2ex.ui.MainActivity import com.czbix.v2ex.util.MiscUtils import com.google.common.eventbus.Subscribe object NotificationStatus { private val mNtfManager: NotificationManagerCompat @Retention(AnnotationRetention.SOURCE) @IntDef(ID_NOTIFICATIONS, ID_APP_UPDATE) annotation class NotificationId const val ID_NOTIFICATIONS = 0 const val ID_APP_UPDATE = 1 private val context: Context get() = AppCtx.instance init { mNtfManager = NotificationManagerCompat.from(context) RxBus.subscribe<NewUnreadEvent> { onNewUnread(it) } } fun init() { // empty for init } fun showAppUpdate() { val pendingIntent = PendingIntent.getActivity(context, 0, MiscUtils.appUpdateIntent, 0) val notification = NotificationCompat.Builder(context).apply { setSmallIcon(R.drawable.ic_update_black_24dp) setTicker(context.getString(R.string.ntf_title_app_update)) setContentTitle(context.getString(R.string.ntf_title_app_update)) setContentText(context.getString(R.string.ntf_desc_new_version_of_app)) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setAutoCancel(true) setOnlyAlertOnce(true) setLocalOnly(true) setContentIntent(pendingIntent) }.build() mNtfManager.notify(ID_APP_UPDATE, notification) } fun onNewUnread(e: NewUnreadEvent) { if (!e.hasNew()) { cancelNotification(ID_NOTIFICATIONS) return } val intent = Intent(context, MainActivity::class.java).apply { putExtra(MainActivity.BUNDLE_GOTO, MainActivity.GOTO_NOTIFICATIONS) addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) } val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0) val notification = NotificationCompat.Builder(context).apply { setSmallIcon(R.drawable.ic_notifications_white_24dp) setTicker(context.getString(R.string.ntf_title_new_notifications)) setContentTitle(context.getString(R.string.ntf_title_new_notifications)) setContentText(context.getString(R.string.ntf_desc_from_v2ex)) setVisibility(NotificationCompat.VISIBILITY_PUBLIC) setDefaults(NotificationCompat.DEFAULT_ALL) setNumber(e.mCount) setAutoCancel(true) setOnlyAlertOnce(true) setContentIntent(pendingIntent) }.build() mNtfManager.notify(ID_NOTIFICATIONS, notification) } fun cancelNotification(@NotificationId id: Int) { mNtfManager.cancel(id) } }
apache-2.0
3212fda7307df6052180ac1d56cfdbe7
32.709677
95
0.689952
4.348128
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http1/NettyHttp1ApplicationResponse.kt
1
4404
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.netty.http1 import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.netty.* import io.ktor.server.netty.cio.* import io.ktor.server.response.* import io.ktor.utils.io.* import io.netty.buffer.* import io.netty.channel.* import io.netty.handler.codec.http.* import kotlinx.coroutines.CancellationException import kotlin.coroutines.* internal class NettyHttp1ApplicationResponse constructor( call: NettyApplicationCall, context: ChannelHandlerContext, engineContext: CoroutineContext, userContext: CoroutineContext, val protocol: HttpVersion ) : NettyApplicationResponse(call, context, engineContext, userContext) { private var responseStatus: HttpResponseStatus = HttpResponseStatus.OK private val responseHeaders = DefaultHttpHeaders() override fun setStatus(statusCode: HttpStatusCode) { val statusCodeInt = statusCode.value val cached = if (statusCodeInt in 1..responseStatusCache.lastIndex) responseStatusCache[statusCodeInt] else null responseStatus = cached?.takeIf { cached.reasonPhrase() == statusCode.description } ?: HttpResponseStatus(statusCode.value, statusCode.description) } override val headers: ResponseHeaders = object : ResponseHeaders() { override fun engineAppendHeader(name: String, value: String) { if (responseMessageSent) { if (responseReady.isCancelled) throw CancellationException("Call execution has been cancelled") throw UnsupportedOperationException( "Headers can no longer be set because response was already completed" ) } responseHeaders.add(name, value) } override fun get(name: String): String? = responseHeaders.get(name) override fun getEngineHeaderNames(): List<String> = responseHeaders.map { it.key } override fun getEngineHeaderValues(name: String): List<String> = responseHeaders.getAll(name) ?: emptyList() } override fun responseMessage(chunked: Boolean, last: Boolean): Any { val responseMessage = DefaultHttpResponse(protocol, responseStatus, responseHeaders) if (chunked) { setChunked(responseMessage) } return responseMessage } override fun responseMessage(chunked: Boolean, data: ByteArray): Any { val responseMessage = DefaultFullHttpResponse( protocol, responseStatus, Unpooled.wrappedBuffer(data), responseHeaders, EmptyHttpHeaders.INSTANCE ) if (chunked) { setChunked(responseMessage) } return responseMessage } override suspend fun respondUpgrade(upgrade: OutgoingContent.ProtocolUpgrade) { val nettyContext = context val nettyChannel = nettyContext.channel() val userAppContext = userContext + NettyDispatcher.CurrentContext(nettyContext) val bodyHandler = nettyContext.pipeline().get(RequestBodyHandler::class.java) val upgradedReadChannel = bodyHandler.upgrade() val upgradedWriteChannel = ByteChannel() sendResponse(chunked = false, content = upgradedWriteChannel) with(nettyChannel.pipeline()) { if (get(NettyHttp1Handler::class.java) != null) { remove(NettyHttp1Handler::class.java) addFirst(NettyDirectDecoder()) } else { cancel() val cause = CancellationException("HTTP upgrade has been cancelled") upgradedWriteChannel.cancel(cause) throw cause } } val job = upgrade.upgrade(upgradedReadChannel, upgradedWriteChannel, engineContext, userAppContext) job.invokeOnCompletion { upgradedWriteChannel.close() bodyHandler.close() upgradedReadChannel.cancel() } (call as NettyApplicationCall).responseWriteJob.join() job.join() context.channel().close() } private fun setChunked(message: HttpResponse) { if (message.status().code() != HttpStatusCode.SwitchingProtocols.value) { HttpUtil.setTransferEncodingChunked(message, true) } } }
apache-2.0
d226ca72235ee24385998ae3b5b80006
36.008403
120
0.673025
5.169014
false
false
false
false
ktorio/ktor
ktor-client/ktor-client-plugins/ktor-client-auth/common/src/io/ktor/client/plugins/auth/Auth.kt
1
3230
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.plugins.auth import io.ktor.client.* import io.ktor.client.plugins.* import io.ktor.client.request.* import io.ktor.http.* import io.ktor.http.auth.* import io.ktor.util.* /** * A client's plugin that handles authentication and authorization. * Typical usage scenarios include logging in users and gaining access to specific resources. * * You can learn more from [Authentication and authorization](https://ktor.io/docs/auth.html). * * [providers] - list of auth providers to use. */ @KtorDsl public class Auth private constructor( public val providers: MutableList<AuthProvider> = mutableListOf() ) { public companion object Plugin : HttpClientPlugin<Auth, Auth> { /** * Shows that request should skip auth and refresh token procedure. */ public val AuthCircuitBreaker: AttributeKey<Unit> = AttributeKey("auth-request") override val key: AttributeKey<Auth> = AttributeKey("DigestAuth") override fun prepare(block: Auth.() -> Unit): Auth { return Auth().apply(block) } @OptIn(InternalAPI::class) override fun install(plugin: Auth, scope: HttpClient) { scope.requestPipeline.intercept(HttpRequestPipeline.State) { plugin.providers.filter { it.sendWithoutRequest(context) }.forEach { it.addRequestHeaders(context) } } scope.plugin(HttpSend).intercept { context -> val origin = execute(context) if (origin.response.status != HttpStatusCode.Unauthorized) return@intercept origin if (origin.request.attributes.contains(AuthCircuitBreaker)) return@intercept origin var call = origin val candidateProviders = HashSet(plugin.providers) while (call.response.status == HttpStatusCode.Unauthorized) { val headerValue = call.response.headers[HttpHeaders.WWWAuthenticate] val authHeader = headerValue?.let { parseAuthorizationHeader(headerValue) } val provider = when { authHeader == null && candidateProviders.size == 1 -> candidateProviders.first() authHeader == null -> return@intercept call else -> candidateProviders.find { it.isApplicable(authHeader) } ?: return@intercept call } if (!provider.refreshToken(call.response)) return@intercept call candidateProviders.remove(provider) val request = HttpRequestBuilder() request.takeFromWithExecutionContext(context) provider.addRequestHeaders(request, authHeader) request.attributes.put(AuthCircuitBreaker, Unit) call = execute(request) } return@intercept call } } } } /** * Install [Auth] plugin. */ public fun HttpClientConfig<*>.Auth(block: Auth.() -> Unit) { install(Auth, block) }
apache-2.0
bf6a1f2f1307e06bce2cd8ce352e3cab
36.126437
119
0.620124
4.992272
false
false
false
false
code-disaster/lwjgl3
modules/generator/src/main/kotlin/org/lwjgl/generator/Constants.kt
4
12886
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator import java.io.* import kotlin.math.* import kotlin.reflect.* // Extension properties for numeric literals. inline val Int.b get() = this.toByte() inline val Int.s get() = this.toShort() inline val Long.i get() = this.toInt() open class ConstantType<T : Any>( val javaType: String, val print: (T) -> String ) { constructor( type: KClass<T>, print: (T) -> String ) : this(type.java.simpleName, print) } val ByteConstant = ConstantType(Byte::class) { value -> val i = value.toInt() and 0xFF "0x%X".format(i).let { if (i < 0x80) it else "(byte)$it" } } val CharConstant = ConstantType(Char::class) { "'$it'" } val ShortConstant = ConstantType(Short::class) { value -> val i = value.toInt() and 0xFFFF "0x%X".format(i).let { if (i < 0x8000) it else "(short)$it" } } val IntConstant = ConstantType(Int::class) { "0x%X".format(it) } val LongConstant = ConstantType(Long::class) { "0x%XL".format(it) } val FloatConstant = ConstantType(Float::class) { "%sf".format(it) } val DoubleConstant = ConstantType(Double::class) { "%sd".format(it) } val StringConstant = ConstantType(String::class) { if (it.contains(" + \"")) it else "\"$it\"" } abstract class EnumValue(val documentation: (() -> String?) = { null }) open class EnumIntValue( documentation: (() -> String?) = { null }, val value: Int? = null ) : EnumValue(documentation) class EnumIntValueExpression( documentation: () -> String?, val expression: String ) : EnumIntValue(documentation, null) val EnumConstant = ConstantType(EnumIntValue::class) { "0x%X".format(it) } // TODO: this is ugly, try new DSL? open class EnumByteValue( documentation: (() -> String?) = { null }, val value: Byte? = null ) : EnumValue(documentation) class EnumByteValueExpression( documentation: () -> String?, val expression: String ) : EnumByteValue(documentation, null) val EnumConstantByte = ConstantType(EnumByteValue::class) { "0x%X".format(it) } open class EnumLongValue( documentation: (() -> String?) = { null }, val value: Long? = null ) : EnumValue(documentation) class EnumLongValueExpression( documentation: () -> String?, val expression: String ) : EnumLongValue(documentation, null) val EnumConstantLong = ConstantType(EnumLongValue::class) { "0x%X".format(it) } open class Constant<out T : Any>(val name: String, val value: T?) internal class ConstantExpression<out T : Any>( name: String, val expression: String, // Used for StringConstants only, false: wrap in quotes, true: print as is val unwrapped: Boolean ) : Constant<T>(name, null) class ConstantBlock<T : Any>( val nativeClass: NativeClass, var access: Access, private val constantType: ConstantType<T>, val documentation: () -> String, val see: Array<String>?, vararg val constants: Constant<T> ) { private var noPrefix = false fun noPrefix(): ConstantBlock<T> { noPrefix = true return this } private fun getConstantName(name: String) = if (noPrefix) name else "${nativeClass.prefixConstant}$name" internal fun getClassLink(name: String) = if (noPrefix && nativeClass.prefixConstant.isNotEmpty()) "${nativeClass.className}#$name" else "${nativeClass.className}#${nativeClass.prefixConstant}$name" private fun generateEnumInt(rootBlock: ArrayList<Constant<Number>>) { var value = 0 var formatType = 1 // 0: hex, 1: decimal for (c in constants) { if (c is ConstantExpression) { @Suppress("UNCHECKED_CAST") rootBlock.add(c as ConstantExpression<Int>) continue } (c.value as EnumIntValue).let { ev -> rootBlock.add(when { ev is EnumIntValueExpression -> { try { value = Integer.parseInt(ev.expression) + 1 // decimal formatType = 1 // next values will be decimal } catch(e: NumberFormatException) { try { value = Integer.parseInt(ev.expression, 16) + 1 // hex } catch(e: Exception) { // ignore } formatType = 0 // next values will be hex } ConstantExpression(c.name, ev.expression, false) } ev.value != null -> { value = ev.value + 1 formatType = 0 Constant(c.name, ev.value) } else -> { if (formatType == 1) ConstantExpression(c.name, (value++).toString(), false) else Constant(c.name, value++) } }) } } } private fun generateEnumByte(rootBlock: ArrayList<Constant<Number>>) { var value = 0L var formatType = 1 // 0: hex, 1: decimal for (c in constants) { if (c is ConstantExpression) { @Suppress("UNCHECKED_CAST") rootBlock.add(c as ConstantExpression<Byte>) continue } (c.value as EnumByteValue).let { ev -> rootBlock.add(when { ev is EnumByteValueExpression -> { try { value = java.lang.Byte.parseByte(ev.expression) + 1L // decimal formatType = 1 // next values will be decimal } catch(e: NumberFormatException) { try { value = java.lang.Byte.parseByte(ev.expression, 16) + 1L // hex } catch(e: Exception) { // ignore } formatType = 0 // next values will be hex } ConstantExpression(c.name, ev.expression, false) } ev.value != null -> { value = ev.value + 1L formatType = 0 Constant(c.name, ev.value) } else -> { if (formatType == 1) ConstantExpression(c.name, (value++).toString(), false) else Constant(c.name, value++) } }) } } } private fun generateEnumLong(rootBlock: ArrayList<Constant<Number>>) { var value = 0L var formatType = 1 // 0: hex, 1: decimal for (c in constants) { if (c is ConstantExpression) { @Suppress("UNCHECKED_CAST") rootBlock.add(c as ConstantExpression<Long>) continue } (c.value as EnumLongValue).let { ev -> rootBlock.add(when { ev is EnumLongValueExpression -> { try { value = java.lang.Long.parseLong(ev.expression) + 1L // decimal formatType = 1 // next values will be decimal } catch(e: NumberFormatException) { try { value = java.lang.Long.parseLong(ev.expression, 16) + 1L // hex } catch(e: Exception) { // ignore } formatType = 0 // next values will be hex } ConstantExpression(c.name, ev.expression, false) } ev.value != null -> { value = ev.value + 1L formatType = 0 Constant(c.name, ev.value) } else -> { if (formatType == 1) ConstantExpression(c.name, (value++).toString(), false) else Constant(c.name, value++) } }) } } } internal fun generate(writer: PrintWriter) { if (constantType === EnumConstant || constantType === EnumConstantByte || constantType === EnumConstantLong) { // Increment/update the current enum value while iterating the enum constants. // Constants without documentation are added to the root block. // Constants with documentation go to their own block. val rootBlock = ArrayList<Constant<Number>>() val constantTypeRender = if (constantType === EnumConstant) { generateEnumInt(rootBlock) IntConstant } else if (constantType === EnumConstantByte) { generateEnumByte(rootBlock) ByteConstant } else { generateEnumLong(rootBlock) LongConstant } ConstantBlock(nativeClass, access, constantTypeRender, documentation().let { doc -> constants.asSequence() .mapNotNull { (if (it is ConstantExpression) null else (it.value as EnumValue).documentation() ).let { enumDoc -> val link = "#${getConstantName(it.name)}" if (enumDoc == null) { if ((doc.contains(link)) || constants.size == 1) null else "<li>{@link $link ${it.name}}</li>" } else "<li>{@link $link ${it.name}} - $enumDoc</li>" } } .joinToString("\n$t$t$t") .let { enumDoc -> { if (enumDoc.isEmpty()) doc else """${if (doc.isEmpty()) "" else "$t$doc\n\n"} <h5>Enum values:</h5> <ul> $enumDoc </ul> """ } } }, see, *rootBlock.toArray(emptyArray())).let { it.noPrefix = noPrefix it.generate(writer) } } else { writer.generateBlock() } } private fun PrintWriter.generateBlock() { println() val doc = documentation() if (doc.isNotEmpty() || see != null) println(doc.toJavaDoc(see = see)) print("$t${access.modifier}static final ${constantType.javaType}") val indent = if (constants.size == 1) { " " } else { print('\n') "$t$t" } // Find maximum constant name length val alignment = constants.map { it.name.length }.fold(0) { left, right -> max(left, right) } constants.forEachWithMore { it, more -> if (more) println(',') printConstant(it, indent, alignment) } println(";") } private fun PrintWriter.printConstant(constant: Constant<T>, indent: String, alignment: Int) { print("$indent${getConstantName(constant.name)}") for (i in 0 until alignment - constant.name.length) print(' ') print(" = ") if (constant is ConstantExpression) { print(if (constantType !== StringConstant || constant.unwrapped) constant.expression else constantType.print(constant.expression) ) } else print(constantType.print(constant.value!!)) } val javaDocLinks get() = javaDocLinks(null) val javaDocLinksSkipCount get() = javaDocLinks { !it.name.endsWith("_COUNT") } fun javaDocLinks(predicate: ((Constant<T>) -> Boolean)?) = constants.asSequence() .let { constants -> if (predicate == null) constants else constants.filter { predicate(it) } } .map { it.name } .joinToString(" #", prefix = "#") }
bsd-3-clause
867ddcede6a1e4301c5b37fcce5226ef
35.7151
118
0.479745
4.994574
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/xxhash/src/templates/kotlin/xxhash/templates/xxhash.kt
4
25904
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package xxhash.templates import org.lwjgl.generator.* import xxhash.* val xxhash = "XXHash".nativeClass(Module.XXHASH, prefix = "XXH", prefixMethod = "XXH") { nativeDirective( """DISABLE_WARNINGS() #include "lwjgl_malloc.h" #if defined(LWJGL_arm64) || defined(LWJGL_arm32) #define XXH_INLINE_ALL #include "xxhash.h" #else #include "xxh_x86dispatch.c" #include "xxh_x86dispatch.h" #endif ENABLE_WARNINGS()""") documentation = """ Native bindings to ${url("https://github.com/Cyan4973/xxHash", "xxhash")}. xxHash is an extremely fast Hash algorithm, running at RAM speed limits. It also successfully passes all tests from the SMHasher suite. A 64-bit version, named XXH64, is available since r35. It offers much better speed, but for 64-bit applications only. <h3>Streaming</h3> Streaming functions generate the xxHash value from an incremental input. This method is slower than single-call functions, due to state management. For small inputs, prefer #32() and #64(), which are better optimized. XXH state must first be allocated, using #32_createState(). Start a new hash by initializing state with a seed, using #32_reset(). Then, feed the hash state by calling #32_update() as many times as necessary. Obviously, input must be allocated and read accessible. The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. Finally, a hash value can be produced anytime, by using #32_digest(). This function returns the 32-bits hash as an int. It's still possible to continue inserting input into the hash state after a digest, and generate some new hash values later on, by calling again #32_digest(). When done, release the state, using #32_freeState(). Example code for incrementally hashing a file: ${codeBlock(""" \#include <stdio.h> \#include <xxhash.h> \#define BUFFER_SIZE 256 // Note: XXH64 and XXH3 use the same interface. XXH32_hash_t hashFile(FILE* stream) { XXH32_state_t* state; unsigned char buf[BUFFER_SIZE]; size_t amt; XXH32_hash_t hash; state = XXH32_createState(); // Create a state assert(state != NULL); // Error check here XXH32_reset(state, 0xbaad5eed); // Reset state with our seed while ((amt = fread(buf, 1, sizeof(buf), stream)) != 0) { XXH32_update(state, buf, amt); // Hash the file in chunks } hash = XXH32_digest(state); // Finalize the hash XXH32_freeState(state); // Clean up return hash; }""")} <h3>Canonical representation</h3> The default return values from XXH functions are unsigned 32 and 64 bit integers. This the simplest and fastest format for further post-processing. However, this leaves open the question of what is the order on the byte level, since little and big endian conventions will store the same number differently. The canonical representation settles this issue by mandating big-endian convention, the same convention as human-readable numbers (large digits first). When writing hash values to storage, sending them over a network, or printing them, it's highly recommended to use the canonical representation to ensure portability across a wider range of systems, present and future. <h3>XXH3</h3> XXH3 is a more recent hash algorithm featuring: ${ul( "Improved speed for both small and large inputs", "True 64-bit and 128-bit outputs", "SIMD acceleration", "Improved 32-bit viability" )} Speed analysis methodology is explained here: ${url("https://fastcompression.blogspot.com/2019/03/presenting-xxh3.html")} Compared to XXH64, expect XXH3 to run approximately ~2x faster on large inputs and &gt;3x faster on small ones, exact differences vary depending on platform. XXH3's speed benefits greatly from SIMD and 64-bit arithmetic, but does not require it. Any 32-bit and 64-bit targets that can run XXH32 smoothly can run XXH3 at competitive speeds, even without vector support. Further details are explained in the implementation. Optimized implementations are provided for AVX512, AVX2, SSE2, NEON, POWER8, ZVector and scalar targets. This can be controlled via the XXH_VECTOR macro. XXH3 implementation is portable: ${ul( "it has a generic C90 formulation that can be compiled on any platform,", "all implementations generage exactly the same hash value on all platforms.", "Starting from v0.8.0, it's also labelled \"stable\", meaning that any future version will also generate the same hash value." )} XXH3 offers 2 variants, {@code _64bits} and {@code _128bits}. When only 64 bits are needed, prefer invoking the {@code _64bits} variant, as it reduces the amount of mixing, resulting in faster speed on small inputs. It's also generally simpler to manipulate a scalar return type than a struct. The API supports one-shot hashing, streaming mode, and custom secrets. <h3>*_withSecretandSeed()</h3> These variants generate hash values using either {@code seed} for "short" keys (&lt; {@code XXH3_MIDSIZE_MAX = 240 bytes}) or {@code secret} for "large" keys (&ge; {@code XXH3_MIDSIZE_MAX}). This generally benefits speed, compared to {@code _withSeed()} or {@code _withSecret()}. {@code _withSeed()} has to generate the secret on the fly for "large" keys. It's fast, but can be perceptible for "not so large" keys (&lt; 1 KB). {@code _withSecret()} has to generate the masks on the fly for "small" keys, which requires more instructions than {@code _withSeed()} variants. Therefore, {@code _withSecretandSeed} variant combines the best of both worlds. When {@code secret} has been generated by #3_generateSecret_fromSeed(), this variant produces <b>exactly</b> the same results as {@code _withSeed()`} variant, hence offering only a pure speed benefit on "large" input, by skipping the need to regenerate the secret for every large input. Another usage scenario is to hash the secret to a 64-bit hash value, for example with #3_64bits(), which then becomes the seed, and then employ both the seed and the secret in {@code _withSecretandSeed()}. On top of speed, an added benefit is that each bit in the secret has a 50% chance to swap each bit in the output, via its impact to the seed. This is not guaranteed when using the secret directly in "small data" scenarios, because only portions of the secret are employed for small data. """ EnumConstant( "Error codes.", "OK".enum, "ERROR".enum ) IntConstant("The major version number.", "VERSION_MAJOR".."0") IntConstant("The minor version number.", "VERSION_MINOR".."8") IntConstant("The release version number.", "VERSION_RELEASE".."1") IntConstant( "The version number", "VERSION_NUMBER".."(XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)" ) IntConstant("The bare minimum size for a custom secret.", "XXH3_SECRET_SIZE_MIN"..136).noPrefix() IntConstant( """ The size of the internal XXH3 buffer. This is the optimal update size for incremental hashing. """, "XXH3_INTERNALBUFFER_SIZE".."256" ).noPrefix() IntConstant( """ Default size of the secret buffer (and {@code XXH3_kSecret}). This is the size used in {@code XXH3_kSecret} and the seeded functions. Not to be confused with #XXH3_SECRET_SIZE_MIN. """, "XXH3_SECRET_DEFAULT_SIZE".."192" ).noPrefix() // 32-bits hash val XXH32 = XXH32_hash_t( "32", """ Calculates the 32-bit hash of {@code input} using xxHash32. Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark): 5.4 GB/s The memory between {@code input} and {@code input + length} must be valid, readable, contiguous memory. However, if {@code length} is {@code 0}, {@code input} may be #NULL. """, nullable..void.const.p("input", "the block of data to be hashed, at least {@code length} bytes in size"), AutoSize("input")..size_t("length", "the length of {@code input}, in bytes"), XXH32_hash_t("seed", "the 32-bit seed to alter the hash's output predictably"), returnDoc = "the calculated 32-bit hash value" ) XXH32_state_t.p( "32_createState", """ Allocates an {@code XXH32_state_t}. Must be freed with #32_freeState(). <b>LWJGL note</b>: This function delegates to the memory allocator configured by LWJGL. """, void(), returnDoc = "an allocated {@code XXH32_state_t} on success, #NULL on failure" ) XXH_errorcode( "32_freeState", """ Frees an {@code XXH32_state_t}. Must be allocated with #32_createState(). """, XXH32_state_t.p("statePtr", "the state to free") ) void( "32_copyState", """ Copies one {@code XXH32_state_t} to another. {@code dst_state} and {@code src_state} must not be #NULL and must not overlap. """, XXH32_state_t.p("dst_state", "the state to copy to"), XXH32_state_t.const.p("src_state", "the state to copy from") ) XXH_errorcode( "32_reset", """ Resets an {@code XXH32_state_t} to begin a new hash. This function resets and seeds a state. Call it before #32_update(). """, XXH32_state_t.p("statePtr", "the state struct to reset"), XXH32_hash_t("seed", "the 32-bit seed to alter the hash result predictably"), returnDoc = "#OK on success, #ERROR on failure" ) XXH_errorcode( "32_update", """ Consumes a block of {@code input} to an {@code XXH32_state_t}. Call this to incrementally consume blocks of data. The memory between {@code input} and {@code input + length} must be valid, readable, contiguous memory. However, if {@code length} is {@code 0}, {@code input} may be #NULL. """, XXH32_state_t.p("statePtr", "the state struct to update"), XXH32["input"], XXH32["length"], returnDoc = "#OK on success, #ERROR on failure" ) XXH32_hash_t( "32_digest", """ Returns the calculated hash value from an {@code XXH32_state_t}. Calling {@code XXH32_digest()} will not affect {@code statePtr}, so you can update, digest, and update again. """, XXH32_state_t.const.p("statePtr", "the state struct to calculate the hash from"), returnDoc = "the calculated xxHash32 value from that state" ) void( "32_canonicalFromHash", "Converts an {@code XXH32_hash_t} to a big endian {@code XXH32_canonical_t}.", XXH32_canonical_t.p("dst", "the {@code XXH32_canonical_t} pointer to be stored to."), XXH32_hash_t("hash", "the {@code XXH32_hash_t} to be converted") ) XXH32_hash_t( "32_hashFromCanonical", "Converts an {@code XXH32_canonical_t} to a native {@code XXH32_hash_t}.", XXH32_canonical_t.const.p("src", "the {@code XXH32_canonical_t} to convert") ) // 64-bits hash XXH64_hash_t( "64", """ Calculates the 64-bit hash of {@code input} using xxHash64. This function usually runs faster on 64-bit systems, but slower on 32-bit systems. The memory between {@code input} and {@code input + length} must be valid, readable, contiguous memory. However, if {@code length} is {@code 0}, {@code input} may be #NULL. """, XXH32["input"], XXH32["length"], XXH64_hash_t("seed", "the 64-bit seed to alter the hash's output predictably"), returnDoc = "the calculated 64-bit hash" ) XXH64_state_t.p( "64_createState", """ Allocates an {@code XXH64_state_t}. Must be freed with #64_freeState(). <b>LWJGL note</b>: This function delegates to the memory allocator configured by LWJGL. """, void(), returnDoc = "an allocated {@code XXH64_state_t} on success, #NULL on failure" ) XXH_errorcode( "64_freeState", """ Frees an {@code XXH64_state_t}. Must be allocated with #64_createState(). """, XXH64_state_t.p("statePtr", "the state to free") ) void( "64_copyState", """ Copies one {@code XXH64_state_t} to another. {@code dst_state} and {@code src_state} must not be #NULL and must not overlap. """, XXH64_state_t.p("dst_state", "the state to copy to"), XXH64_state_t.const.p("src_state", "the state to copy from") ) XXH_errorcode( "64_reset", """ Resets an {@code XXH64_state_t} to begin a new hash. This function resets and seeds a state. Call it before #64_update(). """, XXH64_state_t.p("statePtr", "the state struct to reset"), XXH64_hash_t("seed", "the 64-bit seed to alter the hash result predictably") ) XXH_errorcode( "64_update", """ Consumes a block of {@code input} to an {@code XXH64_state_t}. Call this to incrementally consume blocks of data. The memory between {@code input} and {@code input + length} must be valid, readable, contiguous memory. However, if {@code length} is {@code 0}, {@code input} may be #NULL. """, XXH64_state_t.p("statePtr", "the state struct to update"), XXH32["input"], XXH32["length"] ) XXH64_hash_t( "64_digest", """ Returns the calculated hash value from an {@code XXH64_state_t}. Calling {@code XXH64_digest()} will not affect {@code statePtr}, so you can update, digest, and update again. """, XXH64_state_t.const.p("statePtr", "the state struct to calculate the hash from"), returnDoc = "the calculated xxHash64 value from that state" ) void( "64_canonicalFromHash", "Converts an {@code XXH64_hash_t} to a big endian {@code XXH64_canonical_t}.", XXH64_canonical_t.p("dst", "the {@code XXH64_canonical_t} pointer to be stored to."), XXH64_hash_t("hash", "the {@code XXH64_hash_t} to be converted") ) XXH64_hash_t( "64_hashFromCanonical", "Converts an {@code XXH64_canonical_t} to a native {@code XXH64_hash_t}.", XXH64_canonical_t.const.p("src", "the {@code XXH64_canonical_t} to convert") ) XXH64_hash_t( "3_64bits", """ Default 64-bit variant, using default secret and default seed of 0. It's the fastest variant. """, void.const.p("data", ""), AutoSize("data")..size_t("len", "") ) XXH64_hash_t( "3_64bits_withSeed", """ This variant generates on the fly a custom secret, based on the default secret, altered using the {@code seed} value. While this operation is decently fast, note that it's not completely free. Note {@code seed==0} produces same results as #3_64bits(). """, void.const.p("data", ""), AutoSize("data")..size_t("len", ""), XXH64_hash_t("seed", "") ) XXH64_hash_t( "3_64bits_withSecret", """ It's possible to provide any blob of bytes as a "secret" to generate the hash. This makes it more difficult for an external actor to prepare an intentional collision. The main condition is that {@code secretSize} <b>must</b> be large enough (&ge; #XXH3_SECRET_SIZE_MIN). However, the quality of the secret impacts the dispersion of the hash algorithm. Therefore, the secret <b>must</b> look like a bunch of random bytes. Avoid "trivial" or structured data such as repeated sequences or a text document. Whenever in doubt about the "randomness" of the blob of bytes, consider employing #3_generateSecret() instead. It will generate a proper high entropy secret derived from the blob of bytes. Another advantage of using {@code XXH3_generateSecret()} is that it guarantees that all bits within the initial blob of bytes will impact every bit of the output. This is not necessarily the case when using the blob of bytes directly because, when hashing <b>small</b> inputs, only a portion of the secret is employed. """, void.const.p("data", ""), AutoSize("data")..size_t("len", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", "") ) XXH3_state_t.p( "3_createState", "", void() ) XXH_errorcode( "3_freeState", "", XXH3_state_t.p("statePtr", "") ) void( "3_copyState", "", XXH3_state_t.p("dst_state", ""), XXH3_state_t.const.p("srct_state", "") ) XXH_errorcode( "3_64bits_reset", """ Initialize with default parameters. Result will be equivalent to #3_64bits(). """, XXH3_state_t.p("statePtr", "") ) XXH_errorcode( "3_64bits_reset_withSeed", """ Generate a custom secret from {@code seed}, and store it into {@code state}. Digest will be equivalent to #3_64bits_withSeed(). """, XXH3_state_t.p("statePtr", ""), XXH64_hash_t("seed", "") ) XXH_errorcode( "3_64bits_reset_withSecret", """ {@code secret} is referenced, and must outlive the hash streaming session. Similar to one-shot API, {@code secretSize} must be &ge; #XXH3_SECRET_SIZE_MIN, and the quality of produced hash values depends on secret's entrop (secret's content should look like a bunch of random bytes). When in doubt about the randomness of a candidate {@code secret}, consider employing #3_generateSecret() instead (see below). """, XXH3_state_t.p("statePtr", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", "") ) XXH_errorcode( "3_64bits_update", "", XXH3_state_t.p("statePtr", ""), void.const.p("input", ""), AutoSize("input")..size_t("length", "") ) XXH64_hash_t( "3_64bits_digest", "", XXH3_state_t.const.p("statePtr", "") ) XXH128_hash_t( "3_128bits", "", void.const.p("data", ""), AutoSize("data")..size_t("len", "") ) XXH128_hash_t( "3_128bits_withSeed", "", void.const.p("data", ""), AutoSize("data")..size_t("len", ""), XXH64_hash_t("seed", "") ) XXH128_hash_t( "3_128bits_withSecret", "", void.const.p("data", ""), AutoSize("data")..size_t("len", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", "") ) XXH_errorcode( "3_128bits_reset", "", XXH3_state_t.p("statePtr", "") ) XXH_errorcode( "3_128bits_reset_withSeed", "", XXH3_state_t.p("statePtr", ""), XXH64_hash_t("seed", "") ) XXH_errorcode( "3_128bits_reset_withSecret", "", XXH3_state_t.p("statePtr", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", "") ) XXH_errorcode( "3_128bits_update", "", XXH3_state_t.p("statePtr", ""), void.const.p("input", ""), AutoSize("input")..size_t("length", "") ) XXH128_hash_t( "3_128bits_digest", "", XXH3_state_t.const.p("statePtr", "") ) intb( "128_isEqual", "Returns 1 if equal, 0 if different.", XXH128_hash_t("h1", ""), XXH128_hash_t("h2", "") ) int( "128_cmp", "This comparator is compatible with stdlib's {@code qsort()/bsearch()}.", Check("XXH128Hash.SIZEOF")..void.const.p("h128_1", ""), Check("XXH128Hash.SIZEOF")..void.const.p("h128_2", "") ) void( "128_canonicalFromHash", "", XXH128_canonical_t.p("dst", ""), XXH128_hash_t("hash", "") ) XXH128_hash_t( "128_hashFromCanonical", "", XXH128_canonical_t.const.p("src", "") ) void( "3_INITSTATE", """ Initializes a stack-allocated {@code XXH3_state_t}. When the {@code XXH3_state_t} structure is merely emplaced on stack, it should be initialized with {@code XXH3_INITSTATE()} or a {@code memset()} in case its first reset uses {@code XXH3_NNbits_reset_withSeed()}. This init can be omitted if the first reset uses default or {@code _withSecret} mode. This operation isn't necessary when the state is created with #3_createState(). Note that this doesn't prepare the state for a streaming operation, it's still necessary to use {@code XXH3_NNbits_reset*()} afterwards. """, XXH3_state_t.p("statePtr", "") ) XXH128_hash_t( "128", "Simple alias to pre-selected {@code XXH3_128bits} variant.", void.const.p("data", ""), AutoSize("data")..size_t("len", ""), XXH64_hash_t("seed", "") ) XXH_errorcode( "3_generateSecret", """ Derives a high-entropy secret from any user-defined content, named {@code customSeed}. The generated secret can be used in combination with {@code *_withSecret()} functions. The {@code _withSecret()} variants are useful to provide a higher level of protection than 64-bit seed, as it becomes much more difficult for an external actor to guess how to impact the calculation logic. The function accepts as input a custom seed of any length and any content, and derives from it a high-entropy secret of length {@code secretSize} into an already allocated buffer {@code secretBuffer}. {@code secretSize} must be &ge; #XXH3_SECRET_SIZE_MIN. The generated secret can then be used with any {@code *_withSecret()} variant. Functions #3_128bits_withSecret(), #3_64bits_withSecret(), #3_128bits_reset_withSecret() and #3_64bits_reset_withSecret() are part of this list. They all accept a {@code secret} parameter which must be large enough for implementation reasons (&ge; #XXH3_SECRET_SIZE_MIN) <i>and</i> feature very high entropy (consist of random-looking bytes). These conditions can be a high bar to meet, so {@code XXH3_generateSecret()} can be employed to ensure proper quality. {@code customSeed} can be anything. It can have any size, even small ones, and its content can be anything, even "poor entropy" sources such as a bunch of zeroes. The resulting {@code secret} will nonetheless provide all required qualities. When {@code customSeedSize} &gt; 0, supplying #NULL as {@code customSeed} is undefined behavior. """, Check("XXH3_SECRET_SIZE_MIN")..void.p("secretBuffer", ""), AutoSize("secretBuffer")..size_t("secretSize", ""), nullable..void.const.p("customSeed", ""), AutoSize("customSeed")..size_t("customSeedSize", "") ) void( "3_generateSecret_fromSeed", """ Generate the same secret as the {@code _withSeed()} variants. The resulting secret has a length of #XXH3_SECRET_DEFAULT_SIZE (necessarily). {@code secretBuffer} must be already allocated, of size at least {@code XXH3_SECRET_DEFAULT_SIZE} bytes. The generated secret can be used in combination with {@code *_withSecret()} and {@code _withSecretandSeed()} variants. This generator is notably useful in combination with {@code _withSecretandSeed()}, as a way to emulate a faster {@code _withSeed()} variant. """, Check("XXH3_SECRET_DEFAULT_SIZE")..void.p("secretBuffer", ""), XXH64_hash_t("seed", "") ) XXH64_hash_t( "3_64bits_withSecretandSeed", "", nullable..void.const.p("data", ""), AutoSize("data")..size_t("len", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", ""), XXH64_hash_t("seed", "") ) XXH128_hash_t( "3_128bits_withSecretandSeed", "", nullable..void.const.p("data", ""), AutoSize("data")..size_t("len", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", ""), XXH64_hash_t("seed", "") ) XXH_errorcode( "3_64bits_reset_withSecretandSeed", "", XXH3_state_t.p("statePtr", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", ""), XXH64_hash_t("seed64", "") ) XXH_errorcode( "3_128bits_reset_withSecretandSeed", "", XXH3_state_t.p("statePtr", ""), Check("XXH3_SECRET_SIZE_MIN")..void.const.p("secret", ""), AutoSize("secret")..size_t("secretSize", ""), XXH64_hash_t("seed64", "") ) }
bsd-3-clause
62d1026c4a4859d8f2b21eed47663769
34.197011
163
0.604231
3.9065
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/nanovg/src/templates/kotlin/nanovg/templates/nanovg.kt
3
38722
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package nanovg.templates import org.lwjgl.generator.* import nanovg.* val nanovg = "NanoVG".nativeClass(Module.NANOVG, prefix = "NVG") { includeNanoVGAPI("""#define STBI_MALLOC(sz) org_lwjgl_malloc(sz) #define STBI_REALLOC(p,sz) org_lwjgl_realloc(p,sz) #define STBI_FREE(p) org_lwjgl_free(p) #define STBI_FAILURE_USERMSG #define STBI_ASSERT(x) #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_STATIC #define STBTT_malloc(x,u) ((void)(u),org_lwjgl_malloc(x)) #define STBTT_free(x,u) ((void)(u),org_lwjgl_free(x)) #define STBTT_assert #define STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC #include "nanovg.c"""") documentation = """ NanoVG is a small antialiased vector graphics rendering library for OpenGL. It has lean API modeled after HTML5 canvas API. It is aimed to be a practical and fun toolset for building scalable user interfaces and visualizations. <h3>Color utils</h3> Colors in NanoVG are stored as unsigned ints in ABGR format. <h3>State Handling</h3> NanoVG contains state which represents how paths will be rendered. The state contains transform, fill and stroke styles, text and font styles, and scissor clipping. <h3>Render styles</h3> Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern. Solid color is simply defined as a color value, different kinds of paints can be created using #LinearGradient(), #BoxGradient(), #RadialGradient() and #ImagePattern(). Current render style can be saved and restored using #Save() and #Restore(). <h3>Transforms</h3> The paths, gradients, patterns and scissor region are transformed by an transformation matrix at the time when they are passed to the API. The current transformation matrix is a affine matrix: ${codeBlock(""" [sx kx tx] [ky sy ty] [ 0 0 1]""")} Where: {@code sx,sy} define scaling, {@code kx,ky} skewing, and {@code tx,ty} translation. The last row is assumed to be {@code 0,0,1} and is not stored. Apart from #ResetTransform(), each transformation function first creates specific transformation matrix and pre-multiplies the current transformation by it. Current coordinate system (transformation) can be saved and restored using #Save() and #Restore(). <h3>Images</h3> NanoVG allows you to load jpg, png, psd, tga, pic and gif files to be used for rendering. In addition you can upload your own image. The image loading is provided by {@code stb_image}. <h3>Paints</h3> NanoVG supports four types of paints: linear gradient, box gradient, radial gradient and image pattern. These can be used as paints for strokes and fills. <h3>Scissoring</h3> Scissoring allows you to clip the rendering into a rectangle. This is useful for various user interface cases like rendering a text edit or a timeline. <h3>Paths</h3> Drawing a new shape starts with #BeginPath(), it clears all the currently defined paths. Then you define one or more paths and sub-paths which describe the shape. The are functions to draw common shapes like rectangles and circles, and lower level step-by-step functions, which allow to define a path curve by curve. NanoVG uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise winding and holes should have counter clockwise order. To specify winding of a path you can call #PathWinding(). This is useful especially for the common shapes, which are drawn #CCW. Finally you can fill the path using current fill style by calling #Fill(), and stroke it with current stroke style by calling #Stroke(). The curve segments and sub-paths are transformed by the current transform. <h3>Text</h3> NanoVG allows you to load .ttf files and use the font to render text. The appearance of the text can be defined by setting the current text style and by specifying the fill color. Common text and font settings such as font size, letter spacing and text align are supported. Font blur allows you to create simple text effects such as drop shadows. At render time the font face can be set based on the font handles or name. Font measure functions return values in local space, the calculations are carried in the same resolution as the final rendering. This is done because the text glyph positions are snapped to the nearest pixels sharp rendering. The local space means that values are not rotated or scale as per the current transformation. For example if you set font size to 12, which would mean that line height is 16, then regardless of the current scaling and rotation, the returned line height is always 16. Some measures may vary because of the scaling since aforementioned pixel snapping. While this may sound a little odd, the setup allows you to always render the same way regardless of scaling. I.e. following works regardless of scaling: ${codeBlock(""" const char* txt = "Text me up."; nvgTextBounds(vg, x,y, txt, NULL, bounds); nvgBeginPath(vg); nvgRoundedRect(vg, bounds[0],bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1]); nvgFill(vg);""")} Note: currently only solid color fill is supported for text. """ FloatConstant( "PI", "PI"..3.14159265358979323846264338327f ) EnumConstant( "Winding order.", "CCW".enum("Winding for solid shapes", 1), "CW".enum("Winding for holes", 2) ) EnumConstant( "Solidity.", "SOLID".enum("CCW", 1), "HOLE".enum("CW", 2) ) EnumConstant( "Line caps and joins.", "BUTT".enum, "ROUND".enum, "SQUARE".enum, "BEVEL".enum, "MITER".enum ) val TexAlign = EnumConstant( "Alignments.", "ALIGN_LEFT".enum("Default, align text horizontally to left.", "1<<0"), "ALIGN_CENTER".enum("Align text horizontally to center.", "1<<1"), "ALIGN_RIGHT".enum("Align text horizontally to right.", "1<<2"), "ALIGN_TOP".enum("Align text vertically to top.", "1<<3"), "ALIGN_MIDDLE".enum("Align text vertically to middle.", "1<<4"), "ALIGN_BOTTOM".enum("Align text vertically to bottom.", "1<<5"), "ALIGN_BASELINE".enum("Default, align text vertically to baseline.", "1<<6") ).javaDocLinks val BlendFactor = EnumConstant( "Blend factors.", "ZERO".enum("", "1<<0"), "ONE".enum("", "1<<1"), "SRC_COLOR".enum("", "1<<2"), "ONE_MINUS_SRC_COLOR".enum("", "1<<3"), "DST_COLOR".enum("", "1<<4"), "ONE_MINUS_DST_COLOR".enum("", "1<<5"), "SRC_ALPHA".enum("", "1<<6"), "ONE_MINUS_SRC_ALPHA".enum("", "1<<7"), "DST_ALPHA".enum("", "1<<8"), "ONE_MINUS_DST_ALPHA".enum("", "1<<9"), "SRC_ALPHA_SATURATE".enum("", "1<<10") ).javaDocLinks val CompositeOperation = EnumConstant( "Composite operations.", "SOURCE_OVER".enum, "SOURCE_IN".enum, "SOURCE_OUT".enum, "ATOP".enum, "DESTINATION_OVER".enum, "DESTINATION_IN".enum, "DESTINATION_OUT".enum, "DESTINATION_ATOP".enum, "LIGHTER".enum, "COPY".enum, "XOR".enum ).javaDocLinks val ImageFlags = EnumConstant( "Image flags.", "IMAGE_GENERATE_MIPMAPS".enum("Generate mipmaps during creation of the image.", "1<<0"), "IMAGE_REPEATX".enum("Repeat image in X direction.", "1<<1"), "IMAGE_REPEATY".enum("Repeat image in Y direction.", "1<<2"), "IMAGE_FLIPY".enum("Flips (inverses) image in Y direction when rendered.", "1<<3"), "IMAGE_PREMULTIPLIED".enum("Image data has premultiplied alpha.", "1<<4"), "IMAGE_NEAREST".enum("Image interpolation is Nearest instead Linear.", "1<<5") ).javaDocLinks val ctx = NVGcontext.p("ctx", "the NanoVG context") void( "BeginFrame", """ Begins drawing a new frame. Calls to nanovg drawing API should be wrapped in #BeginFrame() &amp; #EndFrame(). #BeginFrame() defines the size of the window to render to in relation currently set viewport (i.e. {@code glViewport} on GL backends). Device pixel ration allows to control the rendering on Hi-DPI devices. For example, GLFW returns two dimension for an opened window: window size and frame buffer size. In that case you would set {@code windowWidth/Height} to the window size {@code devicePixelRatio} to: {@code frameBufferWidth / windowWidth}. """, ctx, float("windowWidth", "the window width"), float("windowHeight", "the window height"), float("devicePixelRatio", "the device pixel ratio") ) void( "CancelFrame", "Cancels drawing the current frame.", ctx ) void( "EndFrame", "Ends drawing flushing remaining render state.", ctx ) // Composite operation void( "GlobalCompositeOperation", "Sets the composite operation.", ctx, int("op", "the composite operation", CompositeOperation) ) void( "GlobalCompositeBlendFunc", "Sets the composite operation with custom pixel arithmetic.", ctx, int("sfactor", "the source blend factor", BlendFactor), int("dfactor", "the destination blend factor", BlendFactor) ) void( "GlobalCompositeBlendFuncSeparate", "Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately.", ctx, int("srcRGB", "the source RGB blend factor", BlendFactor), int("dstRGB", "the destination RGB blend factor", BlendFactor), int("srcAlpha", "the source alpha blend factor", BlendFactor), int("dstAlpha", "the destination alpha blend factor", BlendFactor) ) // Color utils NVGcolor( "RGB", "Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).", unsigned_char("r", "the red value"), unsigned_char("g", "the green value"), unsigned_char("b", "the blue value") ) NVGcolor( "RGBf", "Returns a color value from red, green, blue values. Alpha will be set to 1.0f.", float("r", "the red value"), float("g", "the green value"), float("b", "the blue value") ) NVGcolor( "RGBA", "Returns a color value from red, green, blue and alpha values.", unsigned_char("r", "the red value"), unsigned_char("g", "the green value"), unsigned_char("b", "the blue value"), unsigned_char("a", "the alpha value") ) NVGcolor( "RGBAf", "Returns a color value from red, green, blue and alpha values.", float("r", "the red value"), float("g", "the green value"), float("b", "the blue value"), float("a", "the alpha value") ) NVGcolor( "LerpRGBA", "Linearly interpolates from color {@code c0} to {@code c1}, and returns resulting color value.", NVGcolor("c0", "the first color"), NVGcolor("c1", "the second color"), float("u", "the interpolation factor") ) NVGcolor( "TransRGBA", "Sets transparency of a color value.", NVGcolor("c0", "the color"), unsigned_char("a", "the alpha value") ) NVGcolor( "TransRGBAf", "Sets transparency of a color value.", NVGcolor("c0", "the color"), float("a", "the alpha value") ) NVGcolor( "HSL", """ Returns color value specified by hue, saturation and lightness. HSL values are all in range {@code [0..1]}, alpha will be set to 255. """, float("h", "the hue value"), float("s", "the saturation value"), float("l", "the lightness value") ) NVGcolor( "HSLA", """ Returns color value specified by hue, saturation and lightness and alpha. HSL values are all in range {@code [0..1]}, alpha in range {@code [0..255]} """, float("h", "the hue value"), float("s", "the saturation value"), float("l", "the lightness value"), unsigned_char("a", "the alpha value") ) // State Handling void( "Save", "Pushes and saves the current render state into a state stack. A matching #Restore() must be used to restore the state.", ctx ) void( "Restore", "Pops and restores current render state.", ctx ) void( "Reset", "Resets current render state to default values. Does not affect the render state stack.", ctx ) // Render styles void( "ShapeAntiAlias", "Sets whether to draw antialias for #Stroke() and #Fill(). It's enabled by default.", ctx, intb("enabled", "the flag to set") ) void( "StrokeColor", "Sets current stroke style to a solid color.", ctx, NVGcolor("color", "the color to set") ) void( "StrokePaint", "Sets current stroke style to a paint, which can be a one of the gradients or a pattern.", ctx, NVGpaint("paint", "the paint to set") ) void( "FillColor", "Sets current fill style to a solid color.", ctx, NVGcolor("color", "the color to set") ) void( "FillPaint", "Sets current fill style to a paint, which can be a one of the gradients or a pattern.", ctx, NVGpaint("paint", "the paint to set") ) void( "MiterLimit", "Sets the miter limit of the stroke style. Miter limit controls when a sharp corner is beveled.", ctx, float("limit", "the miter limit to set") ) void( "StrokeWidth", "Sets the stroke width of the stroke style.", ctx, float("size", "the stroke width to set") ) void( "LineCap", """ Sets how the end of the line (cap) is drawn. The default line cap is #BUTT. """, ctx, int("cap", "the line cap to set", "#BUTT #ROUND #SQUARE") ) void( "LineJoin", """ Sets how sharp path corners are drawn. The default line join is #MITER. """, ctx, int("join", "the line join to set", "#MITER #ROUND #BEVEL") ) void( "GlobalAlpha", """ Sets the transparency applied to all rendered shapes. Already transparent paths will get proportionally more transparent as well. """, ctx, float("alpha", "the alpha value to set") ) // Transforms void( "ResetTransform", "Resets current transform to an identity matrix.", ctx ) void( "Transform", """ Premultiplies current coordinate system by specified matrix. The parameters are interpreted as matrix as follows: ${codeBlock(""" [a c e] [b d f] [0 0 1]""")} """, ctx, float("a", "the a value"), float("b", "the b value"), float("c", "the c value"), float("d", "the d value"), float("e", "the e value"), float("f", "the f value") ) void( "Translate", "Translates current coordinate system.", ctx, float("x", "the X axis translation amount"), float("y", "the Y axis translation amount") ) void( "Rotate", "Rotates current coordinate system.", ctx, float("angle", "the rotation angle, in radians") ) void( "SkewX", "Skews the current coordinate system along X axis.", ctx, float("angle", "the skew angle, in radians") ) void( "SkewY", "Skews the current coordinate system along Y axis.", ctx, float("angle", "the skew angle, in radians") ) void( "Scale", "Scales the current coordinate system.", ctx, float("x", "the X axis scale factor"), float("y", "the Y axis scale factor") ) void( "CurrentTransform", """ Stores the top part (a-f) of the current transformation matrix in to the specified buffer. ${codeBlock(""" [a c e] [b d f] [0 0 1]""")} There should be space for 6 floats in the return buffer for the values {@code a-f}. """, ctx, Check(6)..float.p("xform", "the destination buffer") ) val TransformIdentity = void( "TransformIdentity", "Sets the transform to identity matrix.", Check(6)..float.p("dst", "the destination buffer") ) void( "TransformTranslate", "Sets the transform to translation matrix matrix.", TransformIdentity["dst"], float("tx", "the X axis translation amount"), float("ty", "the Y axis translation amount") ) void( "TransformScale", "Sets the transform to scale matrix.", TransformIdentity["dst"], float("sx", "the X axis scale factor"), float("sy", "the Y axis scale factor") ) void( "TransformRotate", "Sets the transform to rotate matrix.", TransformIdentity["dst"], float("a", "the rotation angle, in radians") ) void( "TransformSkewX", "Sets the transform to skew-x matrix.", TransformIdentity["dst"], float("a", "the skew angle, in radians") ) void( "TransformSkewY", "Sets the transform to skew-y matrix.", TransformIdentity["dst"], float("a", "the skew angle, in radians") ) void( "TransformMultiply", "Sets the transform to the result of multiplication of two transforms, of {@code A = A*B}.", TransformIdentity["dst"], Check(6)..float.const.p("src", "the {@code B} transformation matrix") ) void( "TransformPremultiply", "Sets the transform to the result of multiplication of two transforms, of {@code A = B*A}.", TransformIdentity["dst"], Check(6)..float.const.p("src", "the {@code B} transformation matrix") ) intb( "TransformInverse", "Sets the destination to inverse of specified transform.", TransformIdentity["dst"], Check(6)..float.const.p("src", "the transformation matrix to inverse"), returnDoc = "1 if the inverse could be calculated, else 0" ) void( "TransformPoint", "Transform a point by given transform.", Check(1)..float.p("dstx", "returns the transformed X axis coordinate"), Check(1)..float.p("dsty", "returns the transformed Y axis coordinate"), Check(6)..float.const.p("xform", "the transformation matrix"), float("srcx", "the point X axis coordinate"), float("srcy", "the point Y axis coordinate") ) float( "DegToRad", "Converts degrees to radians.", float("deg", "the rotation value, in degrees") ) float( "RadToDeg", "Converts radians to degrees.", float("rad", "the rotation value, in radians") ) // Images val imageFlags = int("imageFlags", "the image flags", ImageFlags) int( "CreateImage", "Creates image by loading it from the disk from specified file name.", ctx, charASCII.const.p("filename", "the image file name"), imageFlags, returnDoc = "a handle to the image" ) int( "CreateImageMem", "Creates image by loading it from the specified chunk of memory.", ctx, imageFlags, unsigned_char.p("data", "the image data"), AutoSize("data")..int("ndata", "the image data size, in bytes"), returnDoc = "a handle to the image" ) int( "CreateImageRGBA", "Creates image from specified image data.", ctx, int("w", "the image width"), int("h", "the image height"), imageFlags, Check("w * h * 4")..unsigned_char.const.p("data", "the image data"), returnDoc = "a handle to the image" ) void( "UpdateImage", "Updates image data specified by image handle.", ctx, int("image", "the image handle"), Unsafe..unsigned_char.const.p("data", "the image data") ) void( "ImageSize", "Returns the dimensions of a created image.", ctx, int("image", "the image handle"), Check(1)..int.p("w", "returns the image width"), Check(1)..int.p("h", "returns the image height") ) void( "DeleteImage", "Deletes created image.", ctx, int("image", "the image handle to delete") ) // Paints NVGpaint( "LinearGradient", """ Creates and returns a linear gradient. The gradient is transformed by the current transform when it is passed to #FillPaint() or #StrokePaint(). """, ctx, float("sx", "the X axis start coordinate"), float("sy", "the Y axis start coordinate"), float("ex", "the X axis end coordinate"), float("ey", "the Y axis end coordinate"), NVGcolor("icol", "the start color"), NVGcolor("ocol", "the end color") ) NVGpaint( "BoxGradient", """ Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering drop shadows or highlights for boxes. The gradient is transformed by the current transform when it is passed to #FillPaint() or #StrokePaint(). """, ctx, float("x", "the rectangle left coordinate"), float("y", "the rectangle top coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height"), float("r", "the corner radius"), float("f", "the feather value. Feather defines how blurry the border of the rectangle is."), NVGcolor("icol", "the inner color"), NVGcolor("ocol", "the outer color") ) NVGpaint( "RadialGradient", """ Creates and returns a radial gradient. The gradient is transformed by the current transform when it is passed to #FillPaint() or #StrokePaint(). """, ctx, float("cx", "the X axis center coordinate"), float("cy", "the Y axis center coordinate"), float("inr", "the inner radius"), float("outr", "the outer radius"), NVGcolor("icol", "the start color"), NVGcolor("ocol", "the end color") ) NVGpaint( "ImagePattern", """ Creates and returns an image patter. The gradient is transformed by the current transform when it is passed to #FillPaint() or #StrokePaint(). """, ctx, float("ox", "the image pattern left coordinate"), float("oy", "the image pattern top coordinate"), float("ex", "the image width"), float("ey", "the image height"), float("angle", "the rotation angle around the top-left corner"), int("image", "the image to render"), float("alpha", "the alpha value") ) // Scissoring void( "Scissor", """ Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform. """, ctx, float("x", "the rectangle X axis coordinate"), float("y", "the rectangle Y axis coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height") ) void( "IntersectScissor", """ Intersects current scissor rectangle with the specified rectangle. The scissor rectangle is transformed by the current transform. Note: in case the rotation of previous scissor rect differs from the current one, the intersection will be done between the specified rectangle and the previous scissor rectangle transformed in the current transform space. The resulting shape is always rectangle. """, ctx, float("x", "the rectangle X axis coordinate"), float("y", "the rectangle Y axis coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height") ) void( "ResetScissor", "Resets and disables scissoring.", ctx ) // Paths void( "BeginPath", "Clears the current path and sub-paths.", ctx ) void( "MoveTo", "Starts new sub-path with specified point as first point.", ctx, float("x", "the point X axis coordinate"), float("y", "the point Y axis coordinate") ) void( "LineTo", "Adds line segment from the last point in the path to the specified point.", ctx, float("x", "the point X axis coordinate"), float("y", "the point Y axis coordinate") ) void( "BezierTo", "Adds cubic bezier segment from last point in the path via two control points to the specified point.", ctx, float("c1x", "the first control point X axis coordinate"), float("c1y", "the first control point Y axis coordinate"), float("c2x", "the second control point X axis coordinate"), float("c2y", "the second control point Y axis coordinate"), float("x", "the point X axis coordinate"), float("y", "the point Y axis coordinate") ) void( "QuadTo", "Adds quadratic bezier segment from last point in the path via a control point to the specified point.", ctx, float("cx", "the control point X axis coordinate"), float("cy", "the control point Y axis coordinate"), float("x", "the point X axis coordinate"), float("y", "the point Y axis coordinate") ) void( "ArcTo", "Adds an arc segment at the corner defined by the last path point, and two specified points.", ctx, float("x1", "the first point X axis coordinate"), float("y1", "the first point Y axis coordinate"), float("x2", "the second point X axis coordinate"), float("y2", "the second point Y axis coordinate"), float("radius", "the arc radius, in radians") ) void( "ClosePath", "Closes current sub-path with a line segment.", ctx ) void( "PathWinding", "Sets the current sub-path winding.", ctx, int("dir", "the sub-path winding", "#CCW #CW") ) void( "Arc", "Creates new circle arc shaped sub-path.", ctx, float("cx", "the arc center X axis coordinate"), float("cy", "the arc center Y axis coordinate"), float("r", "the arc radius"), float("a0", "the arc starting angle, in radians"), float("a1", "the arc ending angle, in radians"), int("dir", "the arc direction", "#CCW #CW") ) void( "Rect", "Creates new rectangle shaped sub-path.", ctx, float("x", "the rectangle X axis coordinate"), float("y", "the rectangle Y axis coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height") ) void( "RoundedRect", "Creates new rounded rectangle shaped sub-path.", ctx, float("x", "the rectangle X axis coordinate"), float("y", "the rectangle Y axis coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height"), float("r", "the corner radius") ) void( "RoundedRectVarying", "Creates new rounded rectangle shaped sub-path with varying radii for each corner.", ctx, float("x", "the rectangle X axis coordinate"), float("y", "the rectangle Y axis coordinate"), float("w", "the rectangle width"), float("h", "the rectangle height"), float("radTopLeft", "the top-left corner radius"), float("radTopRight", "the top-right corner radius"), float("radBottomRight", "the bottom-right corner radius"), float("radBottomLeft", "the bottom-left corner radius") ) void( "Ellipse", "Creates new ellipse shaped sub-path.", ctx, float("cx", "the ellipse center X axis coordinate"), float("cy", "the ellipse center Y axis coordinate"), float("rx", "the ellipse X axis radius"), float("ry", "the ellipse Y axis radius") ) void( "Circle", "Creates new circle shaped sub-path.", ctx, float("cx", "the circle center X axis coordinate"), float("cy", "the circle center Y axis coordinate"), float("r", "the circle radius") ) void( "Fill", "Fills the current path with current fill style.", ctx ) void( "Stroke", "Fills the current path with current stroke style.", ctx ) // Text int( "CreateFont", "Creates font by loading it from the disk from specified file name.", ctx, charASCII.const.p("name", "the font name"), charASCII.const.p("filename", "the font file name"), returnDoc = "a handle to the font" ) int( "CreateFontAtIndex", "Creates font by loading it from the disk from specified file name.", ctx, charASCII.const.p("name", "the font name"), charASCII.const.p("filename", "the font file name"), int("fontIndex", "specifies which font face to load from a .ttf/.ttc file"), returnDoc = "a handle to the font" ) int( "CreateFontMem", """ Creates font by loading it from the specified memory chunk. The memory chunk must remain valid for as long as the font is used by NanoVG. """, ctx, charASCII.const.p("name", "the font name"), unsigned_char.p("data", "the font data"), AutoSize("data")..int("ndata", "the font data size, in bytes"), intb("freeData", "1 if the font data should be freed automatically, 0 otherwise"), returnDoc = "a handle to the font" ) int( "CreateFontMemAtIndex", """ Creates font by loading it from the specified memory chunk. The memory chunk must remain valid for as long as the font is used by NanoVG. """, ctx, charASCII.const.p("name", "the font name"), unsigned_char.p("data", "the font data"), AutoSize("data")..int("ndata", "the font data size, in bytes"), intb("freeData", "1 if the font data should be freed automatically, 0 otherwise"), int("fontIndex", "specifies which font face to load from a .ttf/.ttc file"), returnDoc = "a handle to the font" ) int( "FindFont", "Finds a loaded font of specified name, and returns handle to it, or -1 if the font is not found.", ctx, charASCII.const.p("name", "the font name") ) int( "AddFallbackFontId", "Adds fallback font by handle.", ctx, int("baseFont", ""), int("fallbackFont", "") ) int( "AddFallbackFont", "Adds fallback font by name.", ctx, charASCII.const.p("baseFont", ""), charASCII.const.p("fallbackFont", "") ) void( "ResetFallbackFontsId", "Resets fallback fonts by handle.", ctx, int("baseFont", "") ) void( "ResetFallbackFonts", "Resets fallback fonts by name.", ctx, charASCII.const.p("baseFont", "") ) void( "FontSize", "Sets the font size of current text style.", ctx, float("size", "the font size to set") ) void( "FontBlur", "Sets the blur of current text style.", ctx, float("blur", "the blur amount to set") ) void( "TextLetterSpacing", "Sets the letter spacing of current text style.", ctx, float("spacing", "the letter spacing amount to set") ) void( "TextLineHeight", "Sets the proportional line height of current text style. The line height is specified as multiple of font size.", ctx, float("lineHeight", "the line height to set") ) void( "TextAlign", "Sets the text align of current text style.", ctx, int("align", "the text align to set", TexAlign) ) void( "FontFaceId", "Sets the font face based on specified id of current text style.", ctx, int("font", "the font id") ) void( "FontFace", "Sets the font face based on specified name of current text style.", ctx, charASCII.const.p("font", "the font name") ) float( "Text", "Draws text string at specified location. If {@code end} is specified only the sub-string up to the {@code end} is drawn.", ctx, float("x", "the text X axis coordinate"), float("y", "the text Y axis coordinate"), charUTF8.const.p("string", "the text string to draw"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to draw, or #NULL") ) void( "TextBox", """ Draws multi-line text string at specified location wrapped at the specified width. If {@code end} is specified only the sub-string up to the {@code end} is drawn. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation). """, ctx, float("x", "the text box X axis coordinate"), float("y", "the text box Y axis coordinate"), float("breakRowWidth", "the maximum row width"), charUTF8.const.p("string", "the text string to draw"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to draw, or #NULL") ) float( "TextBounds", """ Measures the specified text string. Parameter {@code bounds} should be a pointer to {@code float[4]}, if the bounding box of the text should be returned. The bounds value are {@code [xmin,ymin, xmax,ymax]}. Measured values are returned in local coordinate space. """, ctx, float("x", "the text X axis coordinate"), float("y", "the text Y axis coordinate"), charUTF8.const.p("string", "the text string to measure"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to measure, or #NULL"), nullable..Check(4)..float.p("bounds", "returns the bounding box of the text"), returnDoc = "the horizontal advance of the measured text (i.e. where the next character should drawn)" ) void( "TextBoxBounds", """ Measures the specified multi-text string. Parameter {@code bounds} should be a pointer to {@code float[4]}, if the bounding box of the text should be returned. The bounds value are {@code [xmin,ymin, xmax,ymax]}. Measured values are returned in local coordinate space. """, ctx, float("x", "the text box X axis coordinate"), float("y", "the text box Y axis coordinate"), float("breakRowWidth", "the maximum row width"), charUTF8.const.p("string", "the text string to measure"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to measure, or #NULL"), nullable..Check(4)..float.p("bounds", "returns the bounding box of the text box") ) int( "TextGlyphPositions", """ Calculates the glyph x positions of the specified text. If {@code end} is specified only the sub-string will be used. Measured values are returned in local coordinate space. """, ctx, float("x", "the text X axis coordinate"), float("y", "the text Y axis coordinate"), charUTF8.const.p("string", "the text string to measure"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to measure, or #NULL"), NVGglyphPosition.p("positions", "returns the glyph x positions"), AutoSize("positions")..int("maxPositions", "the maximum number of glyph positions to return") ) void( "TextMetrics", """ Returns the vertical metrics based on the current text style. Measured values are returned in local coordinate space. """, ctx, nullable..Check(1)..float.p("ascender", "the line ascend"), nullable..Check(1)..float.p("descender", "the line descend"), nullable..Check(1)..float.p("lineh", "the line height") ) int( "TextBreakLines", """ Breaks the specified text into lines. If {@code end} is specified only the sub-string will be used. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation). """, ctx, charUTF8.const.p("string", "the text string to measure"), AutoSize("string")..nullable..charptr.const.p("end", "a pointer to the end of the sub-string to measure, or #NULL"), float("breakRowWidth", "the maximum row width"), NVGtextRow.p("rows", "returns the text rows"), AutoSize("rows")..int("maxRows", "the maximum number of text rows to return") ) // Rendering back-end integration internal..macro..Address..opaque_p("CreateInternal", "", void()) internal..macro..Address..opaque_p("InternalParams", "", void()) internal..macro..Address..opaque_p("DeleteInternal", "", void()) }
bsd-3-clause
fe78a44f78adc4e2bfb8a364d6974b70
29.041117
160
0.589019
4.258909
false
false
false
false
FountainMC/FountainAPI
src/main/kotlin/org/fountainmc/api/chat/values/Translatable.kt
1
2225
package org.fountainmc.api.chat.values import com.google.common.collect.ImmutableList import org.fountainmc.api.internal.utils.immutableListOf import org.fountainmc.api.internal.utils.toImmutableList /** * Represents a translatable Minecraft message. */ data class Translatable internal constructor( /** * The message ID for this translatable. */ val message: String, /** * An immutable list of substitutions used for the message. */ val substitutions: List<String> ) : ComponentValue { /** * Creates a new instance of `Translatable` with new substitutions. * @param substitutions substitutions to use * * * @return a new `Translatable` with new substitutions */ fun withSubstitutions(substitutions: Collection<String>): Translatable { return copy(substitutions = substitutions.toImmutableList()) } /** * Creates a new instance of `Translatable` with new substitutions. * @param substitutions substitutions to use * * * @return a new `Translatable` with new substitutions */ fun withSubstitutions(vararg substitutions: String): Translatable { return Translatable(message, ImmutableList.copyOf(substitutions)) } override fun toPlainText(buffer: StringBuilder) = buffer.also { // TODO: Actually utilize translation data instead of printing a debug string it.append("\${") it.append(message) if (substitutions.isNotEmpty()) { buffer.append("::") substitutions.joinTo( buffer = it, separator = ",", prefix = "[", postfix = "]" ) { '"' + it + '"' } } it.append("}") } override fun toString() = "Translatable" + toPlainText() companion object { /** * Creates a translatable message with a specific message ID (i.e. demo.day.2). * @param message the message ID to use * * * @return a Translatable */ fun withId(message: String): Translatable { return Translatable(message, immutableListOf()) } } }
mit
16e3cee310d2909ca845441cd31abd74
29.902778
87
0.604944
5.022573
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/NotificationWithProgressBar.kt
1
5828
package org.wikipedia.views import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.util.MathUtil.percentage class NotificationWithProgressBar { lateinit var channelId: String lateinit var targetClass: Class<*> var channelName = 0 var channelDescription = 0 var notificationId = 0 var notificationIcon = 0 var notificationTitle = 0 var notificationDescription = 0 var isEnableCancelButton = false var isEnablePauseButton = false var isCanceled = false var isPaused = false fun setNotificationProgress(context: Context, itemsTotal: Int, itemsProgress: Int) { isCanceled = false isPaused = false val builder = NotificationCompat.Builder(context, channelId) build(context, builder, itemsTotal, itemsProgress) builder.setProgress(itemsTotal, itemsProgress, itemsProgress == 0) showNotification(context, builder) } fun setNotificationPaused(context: Context, itemsTotal: Int, itemsProgress: Int) { val builder = NotificationCompat.Builder(context, channelId) build(context, builder, itemsTotal, itemsProgress) builder.setProgress(itemsTotal, itemsProgress, true) showNotification(context, builder) } private fun build(context: Context, builder: NotificationCompat.Builder, total: Int, progress: Int) { // Notification channel ( >= API 26 ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name: CharSequence = context.resources.getQuantityString(channelName, total) val description = context.getString(channelDescription) val importance = NotificationManager.IMPORTANCE_LOW val mChannel = NotificationChannel(channelId, name, importance) mChannel.description = description mChannel.setSound(null, null) getNotificationManager(context).createNotificationChannel(mChannel) } val builderIcon = notificationIcon val builderTitle = context.resources.getQuantityString(notificationTitle, total, total) val builderInfo = "${percentage(progress.toFloat(), total.toFloat()).toInt()}%" val builderDescription = context.resources.getQuantityString(notificationDescription, total - progress, total - progress) builder.setSmallIcon(builderIcon) .setLargeIcon(BitmapFactory.decodeResource(context.resources, builderIcon)) .setStyle(NotificationCompat.BigTextStyle().bigText(builderDescription)) .setContentTitle(builderTitle) .setContentText(builderDescription) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setSound(null) .setContentInfo(builderInfo) .setOngoing(true) // build action buttons if (isEnablePauseButton) { val actionPause = actionBuilder(context, targetClass, Constants.INTENT_EXTRA_NOTIFICATION_SYNC_PAUSE_RESUME, if (isPaused) R.drawable.ic_play_arrow_black_24dp else R.drawable.ic_pause_black_24dp, if (isPaused) R.string.notification_syncing_resume_button else R.string.notification_syncing_pause_button, 0) builder.addAction(actionPause) } if (isEnableCancelButton) { val actionCancel = actionBuilder(context, targetClass, Constants.INTENT_EXTRA_NOTIFICATION_SYNC_CANCEL, R.drawable.ic_close_black_24dp, R.string.notification_syncing_cancel_button, 1) builder.addAction(actionCancel) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { builder.setSubText(builderInfo) } } fun cancelNotification(context: Context) { getNotificationManager(context).cancel(notificationId) } private fun showNotification(context: Context, builder: NotificationCompat.Builder) { if (!isCanceled) { getNotificationManager(context).notify(notificationId, builder.build()) } } private fun getNotificationManager(context: Context): NotificationManager { return context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } private fun actionBuilder(context: Context, targetClass: Class<*>, intentExtra: String, @DrawableRes buttonDrawable: Int, @StringRes buttonText: Int, requestCode: Int): NotificationCompat.Action { return NotificationCompat.Action.Builder(buttonDrawable, context.getString(buttonText), pendingIntentBuilder(context, targetClass, intentExtra, requestCode)).build() } private fun pendingIntentBuilder(context: Context, targetClass: Class<*>, intentExtra: String, requestCode: Int): PendingIntent { val resultIntent = Intent(context, targetClass) resultIntent.putExtra(intentExtra, true) resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) return PendingIntent.getBroadcast(context, requestCode, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT) } }
apache-2.0
7a412941324b4dc051bc77ca3edd9987
43.48855
129
0.660261
5.421395
false
false
false
false
dahlstrom-g/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitMalformedDeclarationInspection.kt
1
54441
// 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.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInsight.AnnotationUtil import com.intellij.codeInsight.MetaAnnotationUtil import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.* import com.intellij.codeInspection.test.junit.references.MethodSourceReference import com.intellij.codeInspection.util.InspectionMessage import com.intellij.codeInspection.util.SpecialAnnotationsUtil import com.intellij.lang.Language import com.intellij.lang.jvm.JvmMethod import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.JvmModifiersOwner import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.types.JvmPrimitiveTypeKind import com.intellij.lang.jvm.types.JvmType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.psi.impl.source.tree.java.PsiNameValuePairImpl import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.psi.util.InheritanceUtil import com.intellij.psi.util.PsiUtil import com.intellij.psi.util.TypeConversionUtil import com.intellij.psi.util.isAncestor import com.intellij.uast.UastHintedVisitorAdapter import com.intellij.util.castSafelyTo import com.siyeh.ig.junit.JUnitCommonClassNames.* import com.siyeh.ig.psiutils.TestUtils import org.jetbrains.uast.* import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor import javax.swing.JComponent import kotlin.streams.asSequence import kotlin.streams.toList class JUnitMalformedDeclarationInspection : AbstractBaseUastLocalInspectionTool() { @JvmField val ignorableAnnotations: List<String> = ArrayList(listOf("mockit.Mocked", "org.junit.jupiter.api.io.TempDir")) override fun createOptionsPanel(): JComponent = SpecialAnnotationsUtil.createSpecialAnnotationsListControl( ignorableAnnotations, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.option.ignore.test.parameter.if.annotated.by") ) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = UastHintedVisitorAdapter.create( holder.file.language, JUnitMalformedSignatureVisitor(holder, isOnTheFly, ignorableAnnotations), arrayOf(UClass::class.java, UField::class.java, UMethod::class.java), directOnly = true ) } private class JUnitMalformedSignatureVisitor( private val holder: ProblemsHolder, private val isOnTheFly: Boolean, private val ignorableAnnotations: List<String> ) : AbstractUastNonRecursiveVisitor() { override fun visitClass(node: UClass): Boolean { checkMalformedNestedClass(node) return true } override fun visitField(node: UField): Boolean { checkMalformedExtension(node) dataPoint.report(holder, node) ruleSignatureProblem.report(holder, node) classRuleSignatureProblem.report(holder, node) return true } override fun visitMethod(node: UMethod): Boolean { checkMalformedParameterized(node) checkRepeatedTestNonPositive(node) checkIllegalCombinedAnnotations(node) dataPoint.report(holder, node) checkSuite(node) checkedMalformedSetupTeardown(node) beforeAfterProblem.report(holder, node) beforeAfterEachProblem.report(holder, node) beforeAfterClassProblem.report(holder, node) beforeAfterAllProblem.report(holder, node) ruleSignatureProblem.report(holder, node) classRuleSignatureProblem.report(holder, node) checkJUnit3Test(node) junit4TestProblem.report(holder, node) junit5TestProblem.report(holder, node) return true } private fun checkMalformedNestedClass(aClass: UClass) { val javaClass = aClass.javaPsi val containingClass = javaClass.containingClass if (containingClass != null && aClass.isStatic && javaClass.hasAnnotation(ORG_JUNIT_JUPITER_API_NESTED)) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.nested.class.descriptor") val fixes = createModifierQuickfixes(aClass, modifierRequest(JvmModifier.STATIC, shouldBePresent = false)) ?: return holder.registerUProblem(aClass, message, *fixes) } } private val dataPoint = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINT, ORG_JUNIT_EXPERIMENTAL_THEORIES_DATAPOINTS), shouldBeStatic = true, validVisibility = { UastVisibility.PUBLIC }, ) private val ruleSignatureProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_RULE), shouldBeStatic = false, shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE, ORG_JUNIT_RULES_METHOD_RULE), validVisibility = { UastVisibility.PUBLIC } ) private val classRuleSignatureProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_CLASS_RULE), shouldBeStatic = true, shouldBeSubTypeOf = listOf(ORG_JUNIT_RULES_TEST_RULE), validVisibility = { UastVisibility.PUBLIC } ) private val beforeAfterProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_BEFORE, ORG_JUNIT_AFTER), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterEachProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_EACH, ORG_JUNIT_JUPITER_API_AFTER_EACH), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_REPETITION_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterClassProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_BEFORE_CLASS, ORG_JUNIT_AFTER_CLASS), shouldBeStatic = true, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val beforeAfterAllProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_BEFORE_ALL, ORG_JUNIT_JUPITER_API_AFTER_ALL), shouldBeInTestInstancePerClass = true, shouldBeStatic = true, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val junit4TestProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_TEST), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = { UastVisibility.PUBLIC }, validParameters = { method -> method.uastParameters.filter { MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private val junit5TestProblem = AnnotatedSignatureProblem( annotations = listOf(ORG_JUNIT_JUPITER_API_TEST), shouldBeStatic = false, shouldBeVoidType = true, validVisibility = ::notPrivate, validParameters = { method -> if (method.uastParameters.isEmpty()) emptyList() else if (MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf( ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE))) null // handled in parameterized test check else if (method.hasParameterResolver()) listOf(method.uastParameters.first()) else method.uastParameters.filter { it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_INFO || it.type.canonicalText == ORG_JUNIT_JUPITER_API_TEST_REPORTER || MetaAnnotationUtil.isMetaAnnotated(it, ignorableAnnotations) } } ) private fun notPrivate(method: UDeclaration): UastVisibility? = if (method.visibility == UastVisibility.PRIVATE) UastVisibility.PUBLIC else null private fun UMethod.hasParameterResolver(): Boolean { val sourcePsi = this.sourcePsi ?: return false val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val extension = alternatives.mapNotNull { it.javaPsi.containingClass }.flatMap { MetaAnnotationUtil.findMetaAnnotations(it, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH)).asSequence() }.firstOrNull()?.findAttributeValue("value")?.toUElement() ?: return false if (extension is UClassLiteralExpression) return InheritanceUtil.isInheritor(extension.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) if (extension is UCallExpression && extension.kind == UastCallKind.NESTED_ARRAY_INITIALIZER) return extension.valueArguments.any { it is UClassLiteralExpression && InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) } return false } private fun checkMalformedExtension(field: UField) { val javaField = field.javaPsi?.castSafelyTo<PsiField>() ?: return val type = javaField.type if (javaField.hasAnnotation(ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION)) { if (!type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION)) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.extension.registration.descriptor", javaField.type.canonicalText, ORG_JUNIT_JUPITER_API_EXTENSION ) holder.registerUProblem(field, message) } else if (!field.isStatic && (type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_BEFORE_ALL_CALLBACK) || type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_AFTER_ALL_CALLBACK))) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.extension.class.level.descriptor", javaField.type.presentableText ) val fixes = createModifierQuickfixes(field, modifierRequest(JvmModifier.STATIC, shouldBePresent = true)) ?: return holder.registerUProblem(field, message, *fixes) } } } private fun UMethod.isNoArg(): Boolean = uastParameters.isEmpty() || uastParameters.all { param -> param.javaPsi?.castSafelyTo<PsiParameter>()?.let { AnnotationUtil.isAnnotated(it, ignorableAnnotations, 0) } == true } private fun checkSuspendFunction(method: UMethod): Boolean { return if (method.lang == Language.findLanguageByID("kotlin") && method.javaPsi.modifierList.text.contains("suspend")) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.suspend.function.descriptor") holder.registerUProblem(method, message) true } else false } private fun checkJUnit3Test(method: UMethod) { val sourcePsi = method.sourcePsi ?: return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (method.isConstructor) return if (!TestUtils.isJUnit3TestMethod(javaMethod.javaPsi)) return val containingClass = method.javaPsi.containingClass ?: return if (AnnotationUtil.isAnnotated(containingClass, TestUtils.RUN_WITH, AnnotationUtil.CHECK_HIERARCHY)) return if (checkSuspendFunction(method)) return if (PsiType.VOID != method.returnType || method.visibility != UastVisibility.PUBLIC || javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.void.descriptor", "public", "non-static") return holder.registerUProblem(method, message, MethodSignatureQuickfix(method.name, false, newVisibility = JvmModifier.PUBLIC)) } } private fun checkedMalformedSetupTeardown(method: UMethod) { if ("setUp" != method.name && "tearDown" != method.name) return if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return val sourcePsi = method.sourcePsi ?: return if (checkSuspendFunction(method)) return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (PsiType.VOID != method.returnType || method.visibility == UastVisibility.PRIVATE || javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.void.descriptor", "non-private", "non-static") val quickFix = MethodSignatureQuickfix( method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = false, shouldBeVoidType = true, inCorrectParams = emptyMap() ) return holder.registerUProblem(method, message, quickFix) } } private fun checkSuite(method: UMethod) { if ("suite" != method.name) return if (!InheritanceUtil.isInheritor(method.javaPsi.containingClass, JUNIT_FRAMEWORK_TEST_CASE)) return val sourcePsi = method.sourcePsi ?: return if (checkSuspendFunction(method)) return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val javaMethod = alternatives.firstOrNull { it.isStatic } ?: alternatives.firstOrNull() ?: return if (method.visibility == UastVisibility.PRIVATE || !javaMethod.isStatic || !method.isNoArg()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.method.no.arg.descriptor", "non-private", "static") val quickFix = MethodSignatureQuickfix( method.name, newVisibility = JvmModifier.PUBLIC, makeStatic = true, shouldBeVoidType = false, inCorrectParams = emptyMap() ) return holder.registerUProblem(method, message, quickFix) } } private fun checkIllegalCombinedAnnotations(decl: UDeclaration) { val javaPsi = decl.javaPsi.castSafelyTo<PsiModifierListOwner>() ?: return val annotatedTest = NON_COMBINED_TEST.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) } if (annotatedTest.size > 1) { val last = annotatedTest.last().substringAfterLast('.') val annText = annotatedTest.dropLast(1).joinToString { "'@${it.substringAfterLast('.')}'" } val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", annText, last) return holder.registerUProblem(decl, message) } else if (annotatedTest.size == 1 && annotatedTest.first() != ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST) { val annotatedArgSource = PARAMETERIZED_SOURCES.filter { MetaAnnotationUtil.isMetaAnnotated(javaPsi, listOf(it)) } if (annotatedArgSource.isNotEmpty()) { val testAnnText = annotatedTest.first().substringAfterLast('.') val argAnnText = annotatedArgSource.joinToString { "'@${it.substringAfterLast('.')}'" } val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.test.combination.descriptor", argAnnText, testAnnText) return holder.registerUProblem(decl, message) } } } private fun checkRepeatedTestNonPositive(method: UMethod) { val repeatedAnno = method.findAnnotation(ORG_JUNIT_JUPITER_API_REPEATED_TEST) ?: return val repeatedNumber = repeatedAnno.findDeclaredAttributeValue("value") ?: return val repeatedSrcPsi = repeatedNumber.sourcePsi ?: return val constant = repeatedNumber.evaluate() if (constant is Int && constant <= 0) { holder.registerProblem(repeatedSrcPsi, JvmAnalysisBundle.message("jvm.inspections.junit.malformed.repetition.number.descriptor")) } } private fun checkMalformedParameterized(method: UMethod) { if (!MetaAnnotationUtil.isMetaAnnotated(method.javaPsi, listOf(ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST))) return val usedSourceAnnotations = MetaAnnotationUtil.findMetaAnnotations(method.javaPsi, SOURCE_ANNOTATIONS).toList() checkConflictingSourceAnnotations(usedSourceAnnotations.associateWith { it.qualifiedName }, method) usedSourceAnnotations.forEach { when (it.qualifiedName) { ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE -> checkMethodSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE -> checkValuesSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE -> checkEnumSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE -> checkCsvSource(it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE -> checkNullSource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE -> checkEmptySource(method, it) ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE -> { checkNullSource(method, it) checkEmptySource(method, it) } } } } private fun checkConflictingSourceAnnotations(annMap: Map<PsiAnnotation, @NlsSafe String?>, method: UMethod) { val singleParameterProviders = annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE) val multipleParametersProvider = annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE) || annMap.containsValue(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_SOURCE) if (!multipleParametersProvider && !singleParameterProviders && hasCustomProvider(annMap)) return if (!multipleParametersProvider) { val message = if (!singleParameterProviders) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.sources.are.provided.descriptor") } else if (hasMultipleParameters(method.javaPsi)) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.multiple.parameters.are.not.supported.by.this.source.descriptor") } else return holder.registerUProblem(method, message) } } private fun hasCustomProvider(annotations: Map<PsiAnnotation, String?>): Boolean { annotations.forEach { (anno, qName) -> when (qName) { ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCE -> return@hasCustomProvider true ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS_SOURCES -> { val attributes = anno.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) if ((attributes as? PsiArrayInitializerMemberValue)?.initializers?.isNotEmpty() == true) return@hasCustomProvider true } } } return false } private fun checkMethodSource(method: UMethod, methodSource: PsiAnnotation) { val psiMethod = method.javaPsi val containingClass = psiMethod.containingClass ?: return val annotationMemberValue = methodSource.findDeclaredAttributeValue("value") if (annotationMemberValue == null) { if (methodSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) == null) return val foundMethod = containingClass.findMethodsByName(method.name, true).singleOrNull { it.parameters.isEmpty() } val uFoundMethod = foundMethod.toUElementOfType<UMethod>() if (uFoundMethod != null) { return checkSourceProvider(uFoundMethod, containingClass, methodSource, method) } else { return highlightAbsentSourceProvider(containingClass, methodSource, method.name, method) } } else { annotationMemberValue.nestedValues().forEach { attributeValue -> for (reference in attributeValue.references) { if (reference is MethodSourceReference) { val resolve = reference.resolve() if (resolve !is PsiMethod) { return highlightAbsentSourceProvider(containingClass, attributeValue, reference.value, method) } else { val sourceProvider: PsiMethod = resolve val uSourceProvider = sourceProvider.toUElementOfType<UMethod>() ?: return return checkSourceProvider(uSourceProvider, containingClass, attributeValue, method) } } } } } } private fun highlightAbsentSourceProvider( containingClass: PsiClass, attributeValue: PsiElement, sourceProviderName: String, method: UMethod ) { if (isOnTheFly) { val modifiers = mutableListOf(JvmModifier.PUBLIC) if (!TestUtils.testInstancePerClass(containingClass)) modifiers.add(JvmModifier.STATIC) val typeFromText = JavaPsiFacade.getElementFactory(containingClass.project).createTypeFromText( METHOD_SOURCE_RETURN_TYPE, containingClass ) val request = methodRequest(containingClass.project, sourceProviderName, modifiers, typeFromText) val actions = createMethodActions(containingClass, request) val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, containingClass.containingFile).toTypedArray() val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.method.source.unresolved.descriptor", sourceProviderName) val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return return holder.registerProblem(place, message, *quickFixes) } } private fun checkSourceProvider(sourceProvider: UMethod, containingClass: PsiClass?, attributeValue: PsiElement, method: UMethod) { val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return val providerName = sourceProvider.name if (!sourceProvider.isStatic && containingClass != null && !TestUtils.testInstancePerClass(containingClass) && !implementationsTestInstanceAnnotated(containingClass) ) { val annotation = JavaPsiFacade.getElementFactory(containingClass.project).createAnnotationFromText( TEST_INSTANCE_PER_CLASS, containingClass ) val actions = mutableListOf<IntentionAction>() val value = (annotation.attributes.first() as PsiNameValuePairImpl).value if (value != null) { actions.addAll(createAddAnnotationActions( containingClass, annotationRequest(ORG_JUNIT_JUPITER_API_TEST_INSTANCE, constantAttribute("value", value.text)) )) } actions.addAll(createModifierActions(sourceProvider, modifierRequest(JvmModifier.STATIC, true))) val quickFixes = IntentionWrapper.wrapToQuickFixes(actions, sourceProvider.javaPsi.containingFile).toTypedArray() val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.method.source.static.descriptor", providerName) holder.registerProblem(place, message, *quickFixes) } else if (sourceProvider.uastParameters.isNotEmpty() && !classHasParameterResolverField(containingClass)) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.no.params.descriptor", providerName) holder.registerProblem(place, message) } else { val componentType = getComponentType(sourceProvider.returnType, method.javaPsi) if (componentType == null) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.return.type.descriptor", providerName) holder.registerProblem(place, message) } else if (hasMultipleParameters(method.javaPsi) && !InheritanceUtil.isInheritor(componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS) && !componentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) && !componentType.deepComponentType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) ) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.wrapped.in.arguments.descriptor") holder.registerProblem(place, message) } } } private fun classHasParameterResolverField(aClass: PsiClass?): Boolean { if (aClass == null) return false if (aClass.isInterface) return false return aClass.fields.any { field -> AnnotationUtil.isAnnotated(field, ORG_JUNIT_JUPITER_API_EXTENSION_REGISTER_EXTENSION, 0) && field.type.isInheritorOf(ORG_JUNIT_JUPITER_API_EXTENSION_PARAMETER_RESOLVER) } } private fun implementationsTestInstanceAnnotated(containingClass: PsiClass): Boolean = ClassInheritorsSearch.search(containingClass, containingClass.resolveScope, true).any { TestUtils.testInstancePerClass(it) } private fun getComponentType(returnType: PsiType?, method: PsiMethod): PsiType? { val collectionItemType = JavaGenericsUtil.getCollectionItemType(returnType, method.resolveScope) if (collectionItemType != null) return collectionItemType if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_INT_STREAM)) return PsiType.INT if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_LONG_STREAM)) return PsiType.LONG if (InheritanceUtil.isInheritor(returnType, CommonClassNames.JAVA_UTIL_STREAM_DOUBLE_STREAM)) return PsiType.DOUBLE val streamItemType = PsiUtil.substituteTypeParameter(returnType, CommonClassNames.JAVA_UTIL_STREAM_STREAM, 0, true) if (streamItemType != null) return streamItemType return PsiUtil.substituteTypeParameter(returnType, CommonClassNames.JAVA_UTIL_ITERATOR, 0, true) } private fun hasMultipleParameters(method: PsiMethod): Boolean { val containingClass = method.containingClass return containingClass != null && method.parameterList.parameters.count { !InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_TEST_INFO) && !InheritanceUtil.isInheritor(it.type, ORG_JUNIT_JUPITER_API_TEST_REPORTER) } > 1 && !MetaAnnotationUtil.isMetaAnnotatedInHierarchy( containingClass, listOf(ORG_JUNIT_JUPITER_API_EXTENSION_EXTEND_WITH) ) } private fun checkNullSource( method: UMethod, psiAnnotation: PsiAnnotation ) { val size = method.uastParameters.size if (size != 1) { val sourcePsi = (if (method.javaPsi.isAncestor(psiAnnotation, true)) psiAnnotation else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return return checkFormalParameters(size, sourcePsi, psiAnnotation.qualifiedName) } } private fun checkEmptySource( method: UMethod, psiAnnotation: PsiAnnotation ) { val sourcePsi = (if (method.javaPsi.isAncestor(psiAnnotation, true)) psiAnnotation else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return val size = method.uastParameters.size val shortName = psiAnnotation.qualifiedName ?: return if (size == 1) { var type = method.uastParameters.first().type if (type is PsiClassType) type = type.rawType() if (type is PsiArrayType || type.equalsToText(CommonClassNames.JAVA_LANG_STRING) || type.equalsToText(CommonClassNames.JAVA_UTIL_LIST) || type.equalsToText(CommonClassNames.JAVA_UTIL_SET) || type.equalsToText(CommonClassNames.JAVA_UTIL_MAP) ) return val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.empty.source.cannot.provide.argument.descriptor", StringUtil.getShortName(shortName), type.presentableText) holder.registerProblem(sourcePsi, message) } else { checkFormalParameters(size, sourcePsi, shortName) } } private fun checkFormalParameters( size: Int, sourcePsi: PsiElement, sourceName: String? ) { if (sourceName == null) return val message = if (size == 0) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.null.source.cannot.provide.argument.no.params.descriptor", StringUtil.getShortName(sourceName)) } else { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.null.source.cannot.provide.argument.too.many.params.descriptor", StringUtil.getShortName(sourceName)) } holder.registerProblem(sourcePsi, message) } private fun checkEnumSource(method: UMethod, enumSource: PsiAnnotation) { // @EnumSource#value type is Class<?>, not an array val value = enumSource.findAttributeValue(PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME) if (value is PsiClassObjectAccessExpression) { val enumType = value.operand.type checkSourceTypeAndParameterTypeAgree(method, value, enumType) checkEnumConstants(enumSource, enumType, method) } return } private fun checkSourceTypeAndParameterTypeAgree(method: UMethod, attributeValue: PsiAnnotationMemberValue, componentType: PsiType) { val parameters = method.uastParameters if (parameters.size == 1) { val paramType = parameters.first().type if (!paramType.isAssignableFrom(componentType) && !InheritanceUtil.isInheritor( componentType, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ARGUMENTS) ) { if (componentType.equalsToText(CommonClassNames.JAVA_LANG_STRING)) { //implicit conversion to primitive/wrapper if (TypeConversionUtil.isPrimitiveAndNotNullOrWrapper(paramType)) return val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType) //implicit conversion to enum if (psiClass != null) { if (psiClass.isEnum && psiClass.findFieldByName((attributeValue as PsiLiteral).value as String?, false) != null) return //implicit java time conversion val qualifiedName = psiClass.qualifiedName if (qualifiedName != null) { if (qualifiedName.startsWith("java.time.")) return if (qualifiedName == "java.nio.file.Path") return } val factoryMethod: (PsiMethod) -> Boolean = { !it.hasModifier(JvmModifier.PRIVATE) && it.parameterList.parametersCount == 1 && it.parameterList.parameters.first().type.equalsToText(CommonClassNames.JAVA_LANG_STRING) } if (!psiClass.hasModifier(JvmModifier.ABSTRACT) && psiClass.constructors.find(factoryMethod) != null) return if (psiClass.methods.find { it.hasModifier(JvmModifier.STATIC) && factoryMethod(it) } != null) return } } else if (componentType.equalsToText(ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM)) { val psiClass = PsiUtil.resolveClassInClassTypeOnly(paramType) if (psiClass != null && psiClass.isEnum) return } val param = parameters.first() val default = param.sourcePsi as PsiNameIdentifierOwner val place = (if (method.javaPsi.isAncestor(attributeValue, true)) attributeValue else default.nameIdentifier ?: default).toUElement()?.sourcePsi ?: return if (param.findAnnotation(ORG_JUNIT_JUPITER_PARAMS_CONVERTER_CONVERT_WITH) != null) return val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.method.source.assignable.descriptor", componentType.presentableText, paramType.presentableText ) holder.registerProblem(place, message) } } } private fun checkValuesSource(method: UMethod, valuesSource: PsiAnnotation) { val psiMethod = method.javaPsi val possibleValues = mapOf( "strings" to PsiType.getJavaLangString(psiMethod.manager, psiMethod.resolveScope), "ints" to PsiType.INT, "longs" to PsiType.LONG, "doubles" to PsiType.DOUBLE, "shorts" to PsiType.SHORT, "bytes" to PsiType.BYTE, "floats" to PsiType.FLOAT, "chars" to PsiType.CHAR, "booleans" to PsiType.BOOLEAN, "classes" to PsiType.getJavaLangClass(psiMethod.manager, psiMethod.resolveScope) ) possibleValues.keys.forEach { valueKey -> valuesSource.nestedAttributeValues(valueKey)?.forEach { value -> possibleValues[valueKey]?.let { checkSourceTypeAndParameterTypeAgree(method, value, it) } } } val attributesNumber = valuesSource.parameterList.attributes.size val annotation = (if (method.javaPsi.isAncestor(valuesSource, true)) valuesSource else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElementOfType<UAnnotation>() ?: return val message = if (attributesNumber == 0) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.no.value.source.is.defined.descriptor") } else if (attributesNumber > 1) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.param.exactly.one.type.of.input.must.be.provided.descriptor") } else return return holder.registerUProblem(annotation, message) } private fun checkEnumConstants( enumSource: PsiAnnotation, enumType: PsiType, method: UMethod ) { val mode = enumSource.findAttributeValue("mode") val uMode = mode.toUElement() if (uMode is UReferenceExpression && ("INCLUDE" == uMode.resolvedName || "EXCLUDE" == uMode.resolvedName)) { var validType = enumType if (enumType.canonicalText == ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_ENUM) { val parameters = method.uastParameters if (parameters.isNotEmpty()) validType = parameters.first().type } val allEnumConstants = (PsiUtil.resolveClassInClassTypeOnly(validType) ?: return).fields .filterIsInstance<PsiEnumConstant>() .map { it.name } .toSet() val definedConstants = mutableSetOf<String>() enumSource.nestedAttributeValues("names")?.forEach { name -> if (name is PsiLiteralExpression) { val value = name.value if (value is String) { val sourcePsi = (if (method.javaPsi.isAncestor(name, true)) name else method.javaPsi.nameIdentifier ?: method.javaPsi).toUElement()?.sourcePsi ?: return@forEach val message = if (!allEnumConstants.contains(value)) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.unresolved.enum.descriptor") } else if (!definedConstants.add(value)) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.duplicated.enum.descriptor") } else return@forEach holder.registerProblem(sourcePsi, message) } } } } } private fun checkCsvSource(methodSource: PsiAnnotation) { methodSource.nestedAttributeValues("resources")?.forEach { attributeValue -> for (ref in attributeValue.references) { if (ref.isSoft) continue if (ref is FileReference && ref.multiResolve(false).isEmpty()) { val message = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.param.file.source.descriptor", attributeValue.text) holder.registerProblem(ref.element, message, *ref.quickFixes) } } } } private fun PsiAnnotation.nestedAttributeValues(value: String) = findAttributeValue(value)?.nestedValues() private fun PsiAnnotationMemberValue.nestedValues(): List<PsiAnnotationMemberValue> { return if (this is PsiArrayInitializerMemberValue) initializers.flatMap { it.nestedValues() } else listOf(this) } class AnnotatedSignatureProblem( private val annotations: List<String>, private val shouldBeStatic: Boolean, private val shouldBeInTestInstancePerClass: Boolean = false, private val shouldBeVoidType: Boolean? = null, private val shouldBeSubTypeOf: List<String>? = null, private val validVisibility: ((UDeclaration) -> UastVisibility?)? = null, private val validParameters: ((UMethod) -> List<UParameter>?)? = null, ) { private fun modifierProblems( validVisibility: UastVisibility?, decVisibility: UastVisibility, isStatic: Boolean, isInstancePerClass: Boolean ): List<@NlsSafe String> { val problems = mutableListOf<String>() if (shouldBeInTestInstancePerClass) { if (!isStatic && !isInstancePerClass) problems.add("static") } else if (shouldBeStatic) { if (!isStatic) problems.add("static") } else if (!shouldBeStatic) { if (isStatic) problems.add("non-static") } if (validVisibility != null && validVisibility != decVisibility) problems.add(validVisibility.text) return problems } fun report(holder: ProblemsHolder, element: UField) { val javaPsi = element.javaPsi.castSafelyTo<PsiField>() ?: return val annotation = annotations.firstOrNull { MetaAnnotationUtil.isMetaAnnotated(javaPsi, annotations) } ?: return val visibility = validVisibility?.invoke(element) val problems = modifierProblems(visibility, element.visibility, element.isStatic, false) if (shouldBeVoidType == true && element.type != PsiType.VOID) { return holder.fieldTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.type, it) } == false) { return holder.fieldTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first()) } if (problems.isNotEmpty()) return holder.fieldModifierProblem(element, visibility, annotation, problems) } private fun ProblemsHolder.fieldModifierProblem( element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String> ) { val message = if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.single.descriptor", annotation.substringAfterLast('.'), problems.first() ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last() ) } reportFieldProblem(message, element, visibility) } private fun ProblemsHolder.fieldTypeProblem( element: UField, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String ) { val message = if (problems.isEmpty()) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.field.typed.descriptor", annotation.substringAfterLast('.'), type) } else if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.single.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), type ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.field.double.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type ) } reportFieldProblem(message, element, visibility) } private fun ProblemsHolder.reportFieldProblem(message: @InspectionMessage String, element: UField, visibility: UastVisibility?) { val quickFix = FieldSignatureQuickfix(element.name, shouldBeStatic, visibilityToModifier[visibility]) return registerUProblem(element, message, quickFix) } fun report(holder: ProblemsHolder, element: UMethod) { val javaPsi = element.javaPsi.castSafelyTo<PsiMethod>() ?: return val sourcePsi = element.sourcePsi ?: return val annotation = annotations.firstOrNull { AnnotationUtil.isAnnotated(javaPsi, it, AnnotationUtil.CHECK_HIERARCHY) } ?: return val alternatives = UastFacade.convertToAlternatives(sourcePsi, arrayOf(UMethod::class.java)) val elementIsStatic = alternatives.any { it.isStatic } val visibility = validVisibility?.invoke(element) val params = validParameters?.invoke(element) val problems = modifierProblems( visibility, element.visibility, elementIsStatic, javaPsi.containingClass?.let { cls -> TestUtils.testInstancePerClass(cls) } == true ) if (element.lang == Language.findLanguageByID("kotlin") && element.javaPsi.modifierList.text.contains("suspend")) { val message = JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.suspend.function.descriptor", annotation.substringAfterLast('.') ) return holder.registerUProblem(element, message) } if (params != null && params.size != element.uastParameters.size) { if (shouldBeVoidType == true && element.returnType != PsiType.VOID) { return holder.methodParameterTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name, params) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) { return holder.methodParameterTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first(), params) } if (params.isNotEmpty()) holder.methodParameterProblem(element, visibility, annotation, problems, params) return holder.methodParameterProblem(element, visibility, annotation, problems, params) } if (shouldBeVoidType == true && element.returnType != PsiType.VOID) { return holder.methodTypeProblem(element, visibility, annotation, problems, PsiType.VOID.name) } if (shouldBeSubTypeOf?.any { InheritanceUtil.isInheritor(element.returnType, it) } == false) { return holder.methodTypeProblem(element, visibility, annotation, problems, shouldBeSubTypeOf.first()) } if (problems.isNotEmpty()) return holder.methodModifierProblem(element, visibility, annotation, problems) } private fun ProblemsHolder.methodParameterProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, parameters: List<UParameter> ) { val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) } val message = when { problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.param.single.descriptor", annotation.substringAfterLast('.'), invalidParams.first().name ) problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.param.double.descriptor", annotation.substringAfterLast('.'), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), invalidParams.first().name ) problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), invalidParams.first().name ) problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) else -> error("Non valid problem.") } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodParameterTypeProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String, parameters: List<UParameter> ) { val invalidParams = element.uastParameters.toMutableList().apply { removeAll(parameters) } val message = when { problems.isEmpty() && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.param.single.descriptor", annotation.substringAfterLast('.'), type, invalidParams.first().name ) problems.isEmpty() && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.param.double.descriptor", annotation.substringAfterLast('.'), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 1 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.typed.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), type, invalidParams.first().name ) problems.size == 1 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.single.typed.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) problems.size == 2 && invalidParams.size == 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.typed.param.single.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type, invalidParams.first().name ) problems.size == 2 && invalidParams.size > 1 -> JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.double.typed.param.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type, invalidParams.joinToString { "'$it'" }, invalidParams.last().name ) else -> error("Non valid problem.") } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodTypeProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String>, type: String ) { val message = if (problems.isEmpty()) { JvmAnalysisBundle.message( "jvm.inspections.junit.malformed.annotated.method.typed.descriptor", annotation.substringAfterLast('.'), type ) } else if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.single.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), type ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.double.typed.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last(), type ) } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.methodModifierProblem( element: UMethod, visibility: UastVisibility?, annotation: String, problems: List<@NlsSafe String> ) { val message = if (problems.size == 1) { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.single.descriptor", annotation.substringAfterLast('.'), problems.first() ) } else { JvmAnalysisBundle.message("jvm.inspections.junit.malformed.annotated.method.double.descriptor", annotation.substringAfterLast('.'), problems.first(), problems.last() ) } reportMethodProblem(message, element, visibility) } private fun ProblemsHolder.reportMethodProblem(message: @InspectionMessage String, element: UMethod, visibility: UastVisibility? = null, params: List<UParameter>? = null) { val quickFix = MethodSignatureQuickfix( element.name, shouldBeStatic, shouldBeVoidType, visibilityToModifier[visibility], params?.associate { it.name to it.type } ?: emptyMap() ) return registerUProblem(element, message, quickFix) } } class FieldSignatureQuickfix( private val name: @NlsSafe String, private val makeStatic: Boolean, private val newVisibility: JvmModifier? = null ) : LocalQuickFix { override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature") override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.field.signature.descriptor", name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val containingFile = descriptor.psiElement.containingFile ?: return val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.castSafelyTo<UField>()?.javaPsi ?: return val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration) if (newVisibility != null) { declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach { it.invoke(project, null, containingFile) } } } declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach { it.invoke(project, null, containingFile) } } } } class MethodSignatureQuickfix( private val name: @NlsSafe String, private val makeStatic: Boolean, private val shouldBeVoidType: Boolean? = null, private val newVisibility: JvmModifier? = null, @SafeFieldForPreview private val inCorrectParams: Map<String, JvmType>? = null ) : LocalQuickFix { override fun getFamilyName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature") override fun getName(): String = JvmAnalysisBundle.message("jvm.inspections.junit.malformed.fix.method.signature.descriptor", name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val containingFile = descriptor.psiElement.containingFile ?: return val javaDeclaration = getUParentForIdentifier(descriptor.psiElement)?.castSafelyTo<UMethod>()?.javaPsi ?: return val declPtr = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(javaDeclaration) if (shouldBeVoidType == true) { declPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod -> createChangeTypeActions(jvmMethod, typeRequest(JvmPrimitiveTypeKind.VOID.name, emptyList())).forEach { it.invoke(project, null, containingFile) } } } if (newVisibility != null) { declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(newVisibility, true)).forEach { it.invoke(project, null, containingFile) } } } if (inCorrectParams != null) { declPtr.element?.castSafelyTo<JvmMethod>()?.let { jvmMethod -> createChangeParametersActions(jvmMethod, setMethodParametersRequest(inCorrectParams.entries)).forEach { it.invoke(project, null, containingFile) } } } declPtr.element?.castSafelyTo<JvmModifiersOwner>()?.let { jvmMethod -> createModifierActions(jvmMethod, modifierRequest(JvmModifier.STATIC, makeStatic)).forEach { it.invoke(project, null, containingFile) } } } } companion object { private const val TEST_INSTANCE_PER_CLASS = "@org.junit.jupiter.api.TestInstance(TestInstance.Lifecycle.PER_CLASS)" private const val METHOD_SOURCE_RETURN_TYPE = "java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>" private val visibilityToModifier = mapOf( UastVisibility.PUBLIC to JvmModifier.PUBLIC, UastVisibility.PROTECTED to JvmModifier.PROTECTED, UastVisibility.PRIVATE to JvmModifier.PRIVATE, UastVisibility.PACKAGE_LOCAL to JvmModifier.PACKAGE_LOCAL ) private val NON_COMBINED_TEST = listOf( ORG_JUNIT_JUPITER_API_TEST, ORG_JUNIT_JUPITER_API_TEST_FACTORY, ORG_JUNIT_JUPITER_API_REPEATED_TEST, ORG_JUNIT_JUPITER_PARAMS_PARAMETERIZED_TEST ) private val PARAMETERIZED_SOURCES = listOf( ORG_JUNIT_JUPITER_PARAMS_PROVIDER_METHOD_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_VALUE_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_ENUM_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_CSV_FILE_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_EMPTY_SOURCE, ORG_JUNIT_JUPITER_PARAMS_PROVIDER_NULL_AND_EMPTY_SOURCE ) } }
apache-2.0
58832c0216efaf4640151918898cb7e2
50.602844
140
0.712882
4.778041
false
true
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/TryStatementBase.kt
1
4282
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.Instructions /** * Try-catch-finally statement. * * @property body Body of try statement * @property catchStatements Catch clauses/exception handlers. * @property finallyStatement Finally block (Obs: for bytecode generation, finally blocks is always inlined). */ data class TryStatement( override val body: Instructions, override val catchStatements: List<CatchStatement>, override val finallyStatement: Instructions ) : TryStatementBase { init { BodyHolder.checkBody(this) } override fun builder(): Builder = Builder(this) class Builder() : TryStatementBase.Builder<TryStatement, Builder> { var body: Instructions = Instructions.empty() var catchStatements: List<CatchStatement> = emptyList() var finallyStatement: Instructions = Instructions.empty() constructor(defaults: TryStatement) : this() { this.body = defaults.body this.catchStatements = defaults.catchStatements this.finallyStatement = defaults.finallyStatement } override fun body(value: Instructions): Builder { this.body = value return this } override fun catchStatements(value: List<CatchStatement>): Builder { this.catchStatements = value return this } override fun finallyStatement(value: Instructions): Builder { this.finallyStatement = value return this } override fun build(): TryStatement = TryStatement(this.body, this.catchStatements, this.finallyStatement) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: TryStatement): Builder = Builder(defaults) } } } /** * Try-catch-finally statement */ interface TryStatementBase : BodyHolder, Instruction { /** * Exception handler statements */ val catchStatements: List<CatchStatement> /** * Finally block statement */ val finallyStatement: Instructions override fun builder(): Builder<TryStatementBase, *> interface Builder<out T : TryStatementBase, S : Builder<T, S>> : BodyHolder.Builder<T, S> { /** * See [TryStatementBase.catchStatements] */ fun catchStatements(value: List<CatchStatement>): S /** * See [TryStatementBase.catchStatements] */ fun catchStatements(vararg values: CatchStatement): S = catchStatements(values.toList()) /** * See [TryStatementBase.finallyStatement] */ fun finallyStatement(value: Instructions): S } }
mit
5c71a61bd2437b520565cf380833316f
32.20155
118
0.66581
4.871445
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/checker/ExposedInferredType.fir.kt
10
1058
private class A open class B<T>(val x: T) class C(<error descr="[EXPOSED_PARAMETER_TYPE] public function exposes its private-in-file parameter type 'A'">x: A</error>): <error descr="[EXPOSED_SUPER_CLASS] public subclass exposes its private-in-file supertype 'A'">B<A></error>(x) private class D { class E } fun <error descr="[EXPOSED_FUNCTION_RETURN_TYPE] public function exposes its private-in-file return type 'A'">create</error>() = A() fun <error descr="[EXPOSED_FUNCTION_RETURN_TYPE] public function exposes its private-in-file return type 'A'">create</error>(<error descr="[EXPOSED_PARAMETER_TYPE] public function exposes its private-in-file parameter type 'A'">a: A</error>) = B(a) val <error descr="[EXPOSED_PROPERTY_TYPE] public property exposes its private-in-file type 'A'">x</error> = create() val <error descr="[EXPOSED_PROPERTY_TYPE] public property exposes its private-in-file type 'A'">y</error> = create(x) val <error descr="[EXPOSED_PROPERTY_TYPE] public property exposes its private-in-file type 'E'">z</error>: B<D.E>? = null
apache-2.0
f1c2e8bcca61d7925ebc8526d1ba8aab
54.684211
248
0.726843
3.327044
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/streaming/StreamGroup.kt
1
1848
package jp.juggler.subwaytooter.streaming import jp.juggler.subwaytooter.api.entity.TimelineItem import jp.juggler.util.JsonArray import jp.juggler.util.LogCategory import java.util.concurrent.ConcurrentHashMap // 同じ種類のストリーミングを複数のカラムで受信する場合がある // subscribe/unsubscribe はまとめて行いたい class StreamGroup(val spec: StreamSpec) { companion object { private val log = LogCategory("StreamGroup") } val destinations = ConcurrentHashMap<Int, StreamRelation>() override fun hashCode(): Int = spec.keyString.hashCode() override fun equals(other: Any?): Boolean { if (other is StreamGroup) return spec.keyString == other.spec.keyString return false } fun eachCallback( channelId: String?, stream: JsonArray?, item: TimelineItem?, block: (callback: StreamCallback) -> Unit, ) { // skip if channel id is provided and not match if (channelId?.isNotEmpty() == true && channelId != spec.channelId) { if (StreamManager.traceDelivery) log.v("${spec.name} channelId not match.") return } destinations.values.forEach { dst -> try { if (stream != null && item != null) { val column = dst.refColumn.get() ?: return@forEach if (!dst.spec.streamFilter(column, stream, item)) { if (StreamManager.traceDelivery) log.v("${spec.name} streamFilter not match. stream=$stream") return@forEach } } dst.refCallback.get()?.let { block(it) } } catch (ex: Throwable) { log.trace(ex) } } } }
apache-2.0
a5231d88803d0456e52dee609a473d2f
32.745098
117
0.574492
4.375309
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/domain/user/network/RateCountJsonMapper.kt
2
481
package quickbeer.android.domain.user.network import quickbeer.android.domain.user.User import quickbeer.android.util.JsonMapper object RateCountJsonMapper : JsonMapper<Int, User, RateCountJson> { override fun map(key: Int, source: RateCountJson): User { return User( id = key, username = null, rateCount = source.rateCount, tickCount = source.tickCount, placeCount = source.placeRatings ) } }
gpl-3.0
747089805540f35a6077c4ac214bdbbf
27.294118
67
0.650728
4.256637
false
false
false
false
google/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewState.kt
2
3757
// 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.projectView.impl import com.intellij.ide.projectView.ProjectViewSettings import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.registry.Registry import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "ProjectViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))]) class ProjectViewState : PersistentStateComponent<ProjectViewState> { companion object { @JvmStatic fun getInstance(project: Project): ProjectViewState = project.service() @JvmStatic fun getDefaultInstance(): ProjectViewState = ProjectManager.getInstance().defaultProject.service() } var abbreviatePackageNames = ProjectViewSettings.Immutable.DEFAULT.isAbbreviatePackageNames var autoscrollFromSource = false var autoscrollToSource = UISettings.getInstance().state.defaultAutoScrollToSource var compactDirectories = ProjectViewSettings.Immutable.DEFAULT.isCompactDirectories var flattenModules = ProjectViewSettings.Immutable.DEFAULT.isFlattenModules var flattenPackages = ProjectViewSettings.Immutable.DEFAULT.isFlattenPackages var foldersAlwaysOnTop = ProjectViewSettings.Immutable.DEFAULT.isFoldersAlwaysOnTop var hideEmptyMiddlePackages = ProjectViewSettings.Immutable.DEFAULT.isHideEmptyMiddlePackages var manualOrder = false var showExcludedFiles = ProjectViewSettings.Immutable.DEFAULT.isShowExcludedFiles var showLibraryContents = ProjectViewSettings.Immutable.DEFAULT.isShowLibraryContents var showMembers = ProjectViewSettings.Immutable.DEFAULT.isShowMembers var showModules = ProjectViewSettings.Immutable.DEFAULT.isShowModules var showURL = ProjectViewSettings.Immutable.DEFAULT.isShowURL var showVisibilityIcons = ProjectViewSettings.Immutable.DEFAULT.isShowVisibilityIcons var sortByType = false var useFileNestingRules = ProjectViewSettings.Immutable.DEFAULT.isUseFileNestingRules override fun noStateLoaded() { val application = getApplication() if (application == null || application.isUnitTestMode) return // for backward compatibility abbreviatePackageNames = ProjectViewSharedSettings.instance.abbreviatePackages autoscrollFromSource = ProjectViewSharedSettings.instance.autoscrollFromSource autoscrollToSource = ProjectViewSharedSettings.instance.autoscrollToSource compactDirectories = ProjectViewSharedSettings.instance.compactDirectories flattenModules = ProjectViewSharedSettings.instance.flattenModules flattenPackages = ProjectViewSharedSettings.instance.flattenPackages foldersAlwaysOnTop = ProjectViewSharedSettings.instance.foldersAlwaysOnTop hideEmptyMiddlePackages = ProjectViewSharedSettings.instance.hideEmptyPackages manualOrder = ProjectViewSharedSettings.instance.manualOrder showExcludedFiles = ProjectViewSharedSettings.instance.showExcludedFiles showLibraryContents = ProjectViewSharedSettings.instance.showLibraryContents showMembers = ProjectViewSharedSettings.instance.showMembers showModules = ProjectViewSharedSettings.instance.showModules showURL = Registry.`is`("project.tree.structure.show.url") showVisibilityIcons = ProjectViewSharedSettings.instance.showVisibilityIcons sortByType = ProjectViewSharedSettings.instance.sortByType } override fun loadState(state: ProjectViewState) { XmlSerializerUtil.copyBean(state, this) } override fun getState(): ProjectViewState { return this } }
apache-2.0
54e31e02b835879363975536a54b32d9
52.671429
120
0.835507
5.247207
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/KotlinAddImportAction.kt
2
17043
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.actions import com.intellij.codeInsight.daemon.QuickFixBundle import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass import com.intellij.codeInsight.daemon.impl.actions.AddImportAction import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.QuestionAction import com.intellij.ide.util.DefaultPsiElementCellRenderer import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.WeighingService import com.intellij.psi.statistics.StatisticsManager import com.intellij.psi.util.ProximityLocation import com.intellij.psi.util.proximity.PsiProximityComparator import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinDescriptorIconProvider import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.completion.ImportableFqNameClassifier import org.jetbrains.kotlin.idea.completion.KotlinStatisticsInfo import org.jetbrains.kotlin.idea.completion.isDeprecatedAtCallSite import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode import org.jetbrains.kotlin.idea.util.application.underModalProgressOrUnderWriteActionWithNonCancellableProgressInDispatchThread import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.isOneSegmentFQN import org.jetbrains.kotlin.name.parentOrNull import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.ImportPath import java.awt.BorderLayout import javax.swing.Icon import javax.swing.JPanel import javax.swing.ListCellRenderer internal fun createSingleImportAction( project: Project, editor: Editor, element: KtElement, fqNames: Collection<FqName> ): KotlinAddImportAction { val file = element.containingKtFile val prioritizer = Prioritizer(file) val variants = fqNames.asSequence().mapNotNull { fqName -> val sameFqNameDescriptors = file.resolveImportReference(fqName) val priority = sameFqNameDescriptors.minOfOrNull { prioritizer.priority(it, file.languageVersionSettings) } ?: return@mapNotNull null VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors, project), priority) } return KotlinAddImportAction(project, editor, element, variants) } internal fun createSingleImportActionForConstructor( project: Project, editor: Editor, element: KtElement, fqNames: Collection<FqName> ): KotlinAddImportAction { val file = element.containingKtFile val prioritizer = Prioritizer(file) val variants = fqNames.asSequence().mapNotNull { fqName -> val sameFqNameDescriptors = file.resolveImportReference(fqName.parent()) .filterIsInstance<ClassDescriptor>() .flatMap { it.constructors } val priority = sameFqNameDescriptors.minOfOrNull { prioritizer.priority(it, file.languageVersionSettings) } ?: return@mapNotNull null VariantWithPriority(SingleImportVariant(fqName, sameFqNameDescriptors, project), priority) } return KotlinAddImportAction(project, editor, element, variants) } internal fun createGroupedImportsAction( project: Project, editor: Editor, element: KtElement, autoImportDescription: String, fqNames: Collection<FqName> ): KotlinAddImportAction { val file = element.containingKtFile val prioritizer = DescriptorGroupPrioritizer(file) val variants = fqNames.groupBy { it.parentOrNull() ?: FqName.ROOT }.asSequence().map { val samePackageFqNames = it.value val descriptors = samePackageFqNames.flatMap { fqName -> file.resolveImportReference(fqName) } val variant = if (samePackageFqNames.size > 1) { GroupedImportVariant(autoImportDescription, descriptors, project) } else { SingleImportVariant(samePackageFqNames.first(), descriptors, project) } val priority = prioritizer.priority(descriptors, file.languageVersionSettings) VariantWithPriority(variant, priority) } return KotlinAddImportAction(project, editor, element, variants) } /** * Automatically adds import directive to the file for resolving reference. * Based on {@link AddImportAction} */ class KotlinAddImportAction internal constructor( private val project: Project, private val editor: Editor, private val element: KtElement, private val variants: Sequence<VariantWithPriority> ) : QuestionAction { private var singleImportVariant: AutoImportVariant? = null private fun variantsList(): List<AutoImportVariant> { if (singleImportVariant != null && !isUnitTestMode()) return listOf(singleImportVariant!!) return project.runSynchronouslyWithProgress(KotlinBundle.message("import.progress.text.resolve.imports"), true) { runReadAction { variants.sortedBy { it.priority }.map { it.variant }.toList() } }.orEmpty() } fun showHint(): Boolean { val iterator = variants.iterator() if (!iterator.hasNext()) return false val first = iterator.next().variant val multiple = if (iterator.hasNext()) { true } else { singleImportVariant = first false } val hintText = ShowAutoImportPass.getMessage(multiple, first.hint) HintManager.getInstance().showQuestionHint(editor, hintText, element.startOffset, element.endOffset, this) return true } fun isUnambiguous(): Boolean { singleImportVariant = variants.singleOrNull()?.variant?.takeIf { variant -> variant.descriptorsToImport.all { it is ClassDescriptor } || variant.descriptorsToImport.all { it is FunctionDescriptor } || variant.descriptorsToImport.all { it is PropertyDescriptor } } return singleImportVariant != null } override fun execute(): Boolean { PsiDocumentManager.getInstance(project).commitAllDocuments() if (!element.isValid) return false val variantsList = variantsList() if (variantsList.isEmpty()) return false if (variantsList.size == 1 || isUnitTestMode()) { addImport(variantsList.first()) return true } JBPopupFactory.getInstance().createListPopup(project, getVariantSelectionPopup(variantsList)) { val psiRenderer = DefaultPsiElementCellRenderer() ListCellRenderer<AutoImportVariant> { list, value, index, isSelected, cellHasFocus -> JPanel(BorderLayout()).apply { add( psiRenderer.getListCellRendererComponent( list, value.declarationToImport, index, isSelected, cellHasFocus ) ) } } }.showInBestPositionFor(editor) return true } private fun getVariantSelectionPopup(variants: List<AutoImportVariant>): BaseListPopupStep<AutoImportVariant> { return object : BaseListPopupStep<AutoImportVariant>(KotlinBundle.message("action.add.import.chooser.title"), variants) { override fun isAutoSelectionEnabled() = false override fun isSpeedSearchEnabled() = true override fun onChosen(selectedValue: AutoImportVariant?, finalChoice: Boolean): PopupStep<String>? { if (selectedValue == null || project.isDisposed) return null if (finalChoice) { addImport(selectedValue) return null } val toExclude = AddImportAction.getAllExcludableStrings(selectedValue.excludeFqNameCheck.asString()) return object : BaseListPopupStep<String>(null, toExclude) { override fun getTextFor(value: String): String { return KotlinBundle.message("fix.import.exclude", value) } override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<Any>? { if (finalChoice && !project.isDisposed) { AddImportAction.excludeFromImport(project, selectedValue) } return null } } } override fun hasSubstep(selectedValue: AutoImportVariant?) = true override fun getTextFor(value: AutoImportVariant) = value.hint override fun getIconFor(value: AutoImportVariant) = value.icon } } private fun addImport(variant: AutoImportVariant) { val psiDocumentManager = PsiDocumentManager.getInstance(project) psiDocumentManager.commitAllDocuments() project.executeWriteCommand(QuickFixBundle.message("add.import")) { if (!element.isValid) return@executeWriteCommand val file = element.containingKtFile val statisticsManager = StatisticsManager.getInstance() variant.descriptorsToImport.forEach { descriptor -> val statisticsInfo = KotlinStatisticsInfo.forDescriptor(descriptor) statisticsManager.incUseCount(statisticsInfo) // for class or package we use ShortenReferences because we not necessary insert an import but may want to // insert partly qualified name val importableFqName = descriptor.importableFqName val importAlias = importableFqName?.let { file.findAliasByFqName(it) } if (importableFqName?.isOneSegmentFQN() != true && (importAlias != null || descriptor is ClassDescriptor || descriptor is PackageViewDescriptor) ) { if (element is KtSimpleNameExpression) { if (importAlias != null) { importAlias.nameIdentifier?.copy()?.let { element.getIdentifier()?.replace(it) } val resultDescriptor = element.resolveMainReferenceToDescriptors().firstOrNull() if (importableFqName == resultDescriptor?.importableFqName) { return@forEach } } if (importableFqName != null) { underModalProgressOrUnderWriteActionWithNonCancellableProgressInDispatchThread( project, progressTitle = KotlinBundle.message("add.import.for.0", importableFqName.asString()), computable = { element.mainReference.bindToFqName(importableFqName, ShorteningMode.FORCED_SHORTENING) } ) } } } else { ImportInsertHelper.getInstance(project).importDescriptor(file, descriptor) } } } } } internal interface ComparablePriority : Comparable<ComparablePriority> internal data class VariantWithPriority(val variant: AutoImportVariant, val priority: ComparablePriority) private class Prioritizer(private val file: KtFile, private val compareNames: Boolean = true) { private val classifier = ImportableFqNameClassifier(file){ ImportInsertHelper.getInstance(file.project).isImportedWithDefault(ImportPath(it, false), file) } private val statsManager = StatisticsManager.getInstance() private val proximityLocation = ProximityLocation(file, file.module) inner class Priority(descriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings) : ComparablePriority { private val isDeprecated = isDeprecatedAtCallSite(descriptor) { languageVersionSettings } private val fqName = descriptor.importableFqName!! private val classification = classifier.classify(fqName, false) private val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(file.project, descriptor) private val lastUseRecency = statsManager.getLastUseRecency(KotlinStatisticsInfo.forDescriptor(descriptor)) private val proximityWeight = WeighingService.weigh(PsiProximityComparator.WEIGHER_KEY, declaration, proximityLocation) override fun compareTo(other: ComparablePriority): Int { other as Priority if (isDeprecated != other.isDeprecated) { return if (isDeprecated) +1 else -1 } val c1 = classification.compareTo(other.classification) if (c1 != 0) return c1 val c2 = lastUseRecency.compareTo(other.lastUseRecency) if (c2 != 0) return c2 val c3 = proximityWeight.compareTo(other.proximityWeight) if (c3 != 0) return -c3 // n.b. reversed if (compareNames) { return fqName.asString().compareTo(other.fqName.asString()) } return 0 } } fun priority( descriptor: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings, ) = Priority(descriptor, languageVersionSettings) } private class DescriptorGroupPrioritizer(file: KtFile) { private val prioritizer = Prioritizer(file, false) inner class Priority( val descriptors: List<DeclarationDescriptor>, languageVersionSettings: LanguageVersionSettings ) : ComparablePriority { val ownDescriptorsPriority = descriptors.maxOf { prioritizer.priority(it, languageVersionSettings) } override fun compareTo(other: ComparablePriority): Int { other as Priority val c1 = ownDescriptorsPriority.compareTo(other.ownDescriptorsPriority) if (c1 != 0) return c1 return other.descriptors.size - descriptors.size } } fun priority( descriptors: List<DeclarationDescriptor>, languageVersionSettings: LanguageVersionSettings ) = Priority(descriptors, languageVersionSettings) } internal abstract class AutoImportVariant( val descriptorsToImport: Collection<DeclarationDescriptor>, val excludeFqNameCheck: FqName, project: Project, ) { abstract val hint: String val declarationToImport: PsiElement? = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptorsToImport.first()) val icon: Icon? = KotlinDescriptorIconProvider.getIcon(descriptorsToImport.first(), declarationToImport, 0) } private class GroupedImportVariant( val autoImportDescription: String, descriptors: Collection<DeclarationDescriptor>, project: Project ) : AutoImportVariant( descriptorsToImport = descriptors, excludeFqNameCheck = descriptors.first().importableFqName!!.parent(), project = project, ) { override val hint: String get() = KotlinBundle.message("0.from.1", autoImportDescription, excludeFqNameCheck) } private class SingleImportVariant( excludeFqNameCheck: FqName, descriptors: Collection<DeclarationDescriptor>, project: Project ) : AutoImportVariant( descriptorsToImport = listOf( descriptors.singleOrNull() ?: descriptors.minByOrNull { if (it is ClassDescriptor) 0 else 1 } ?: error("we create the class with not-empty descriptors always") ), excludeFqNameCheck = excludeFqNameCheck, project = project, ) { override val hint: String get() = excludeFqNameCheck.asString() }
apache-2.0
3f7c1201e931f3063e1153cac612dd1b
41.395522
158
0.691897
5.36112
false
false
false
false
google/intellij-community
build/tasks/test/org/jetbrains/intellij/build/tasks/ReorderJarsTest.kt
1
4821
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("UsePropertyAccessSyntax") package org.jetbrains.intellij.build.tasks import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.rules.InMemoryFsExtension import com.intellij.util.io.inputStream import com.intellij.util.lang.ImmutableZipFile import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.apache.commons.compress.archivers.zip.ZipFile import org.assertj.core.api.Assertions.assertThat import org.jetbrains.intellij.build.io.AddDirEntriesMode import org.jetbrains.intellij.build.io.zip import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.io.TempDir import java.nio.file.Files import java.nio.file.Path import java.util.zip.ZipEntry import kotlin.random.Random private val testDataPath: Path get() = Path.of(PlatformTestUtil.getPlatformTestDataPath(), "plugins/reorderJars") class ReorderJarsTest { @RegisterExtension @JvmField val fs = InMemoryFsExtension() @Test fun `keep all dirs with resources`() { // check that not only immediate parent of resource file is preserved, but also any dir in a path val random = Random(42) val rootDir = fs.root.resolve("dir") val dir = rootDir.resolve("dir2/dir3") Files.createDirectories(dir) Files.write(dir.resolve("resource.txt"), random.nextBytes(random.nextInt(128))) val dir2 = rootDir.resolve("anotherDir") Files.createDirectories(dir2) Files.write(dir2.resolve("resource2.txt"), random.nextBytes(random.nextInt(128))) val archiveFile = fs.root.resolve("archive.jar") zip(archiveFile, mapOf(rootDir to ""), compress = false, addDirEntriesMode = AddDirEntriesMode.RESOURCE_ONLY) runBlocking { doReorderJars(mapOf(archiveFile to emptyList()), archiveFile.parent, archiveFile.parent) } ImmutableZipFile.load(archiveFile).use { zipFile -> assertThat(zipFile.getResource("anotherDir")).isNotNull() assertThat(zipFile.getResource("dir2")).isNotNull() assertThat(zipFile.getResource("dir2/dir3")).isNotNull() } ImmutableZipFile.load(archiveFile).use { zipFile -> assertThat(zipFile.getResource("anotherDir")).isNotNull() } } @Test fun testReordering(@TempDir tempDir: Path) { val path = testDataPath ZipFile("$path/annotations.jar").use { zipFile1 -> zipFile1.entries.toList() } Files.createDirectories(tempDir) runBlocking { doReorderJars(readClassLoadingLog(path.resolve("order.txt").inputStream(), path, "idea.jar"), path, tempDir) } val files = tempDir.toFile().listFiles()!! assertThat(files).isNotNull() assertThat(files).hasSize(1) val file = files[0].toPath() assertThat(file.fileName.toString()).isEqualTo("annotations.jar") var data: ByteArray ZipFile(Files.newByteChannel(file)).use { zipFile2 -> val entries = zipFile2.entriesInPhysicalOrder.toList() val entry = entries[0] data = zipFile2.getInputStream(entry).readNBytes(entry.size.toInt()) assertThat(data).hasSize(548) assertThat(entry.name).isEqualTo("org/jetbrains/annotations/Nullable.class") assertThat(entries[1].name).isEqualTo("org/jetbrains/annotations/NotNull.class") assertThat(entries[2].name).isEqualTo("META-INF/MANIFEST.MF") } } @Test fun testPluginXml(@TempDir tempDir: Path) { Files.createDirectories(tempDir) val path = testDataPath runBlocking { doReorderJars(readClassLoadingLog(path.resolve("zkmOrder.txt").inputStream(), path, "idea.jar"), path, tempDir) } val files = tempDir.toFile().listFiles()!! assertThat(files).isNotNull() val file = files[0] assertThat(file.name).isEqualTo("zkm.jar") ZipFile(file).use { zipFile -> val entries: List<ZipEntry> = zipFile.entries.toList() assertThat(entries.first().name).isEqualTo("META-INF/plugin.xml") } } } private suspend fun doReorderJars(sourceToNames: Map<Path, List<String>>, sourceDir: Path, targetDir: Path) { withContext(Dispatchers.IO) { for ((jarFile, orderedNames) in sourceToNames) { if (Files.notExists(jarFile)) { Span.current().addEvent("cannot find jar", Attributes.of(AttributeKey.stringKey("file"), sourceDir.relativize(jarFile).toString())) continue } launch { reorderJar(jarFile, orderedNames, if (targetDir == sourceDir) jarFile else targetDir.resolve(sourceDir.relativize(jarFile))) } } } }
apache-2.0
3019a4b6ac88e07f94e21b7b939adaea
36.671875
139
0.733458
4.177643
false
true
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/SelectionDebug.kt
1
1861
package org.runestar.client.plugins.dev import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.api.game.ComponentId import org.runestar.client.api.game.live.Canvas import org.runestar.client.raw.CLIENT import org.runestar.client.api.plugins.PluginSettings import java.awt.Color import java.awt.Font class SelectionDebug : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() val font = Font(Font.SANS_SERIF, Font.BOLD, 15) override fun onStart() { add(Canvas.repaints.subscribe { g -> val x = 5 var y = 40 g.font = font g.color = Color.WHITE val strings = listOf( "item: ${CLIENT.selectedItemName}", "isSpellSelected: ${CLIENT.isSpellSelected}", "spellAction: ${CLIENT.selectedSpellActionName}", "spellName: ${CLIENT.selectedSpellName}", "isItemSelected: ${CLIENT.isItemSelected}", "selectedItemId: ${CLIENT.selectedItemId}", "selectedItemSlot: ${CLIENT.selectedItemSlot}", "selectedItemComponent: ${CLIENT.selectedItemComponent}", "itemDragDuration: ${CLIENT.itemDragDuration}", "isDraggingComponent: ${CLIENT.isDraggingComponent}", "componentDragDuration: ${CLIENT.componentDragDuration}", "dragItemSlotSource: ${CLIENT.dragItemSlotSource}", "dragItemSlotDestination: ${CLIENT.dragItemSlotDestination}", "dragInventoryComponent: ${CLIENT.dragInventoryComponent?.let { ComponentId(it.id) }}" ) strings.forEach { s -> g.drawString(s, x, y) y += 20 } }) } }
mit
91b4097d3daf2a7319279de32660cbe1
40.377778
106
0.596454
4.796392
false
false
false
false
JetBrains/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/OptimizeImportsBeforeCheckinHandler.kt
1
1980
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.checkin import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.actions.AbstractLayoutCodeProcessor import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.CheckinHandlerUtil.getPsiFiles import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.vfs.VirtualFile class OptimizeOptionsCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler = OptimizeImportsBeforeCheckinHandler(panel.project) } class OptimizeImportsBeforeCheckinHandler(project: Project) : CodeProcessorCheckinHandler(project) { override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = BooleanCommitOption(project, VcsBundle.message("checkbox.checkin.options.optimize.imports"), true, settings::OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT) .withCheckinHandler(this) override fun isEnabled(): Boolean = settings.OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT override fun getProgressMessage(): String = VcsBundle.message("progress.text.optimizing.imports") override fun createCodeProcessor(files: List<VirtualFile>): AbstractLayoutCodeProcessor = OptimizeImportsProcessor(project, getPsiFiles(project, files), COMMAND_NAME, null) companion object { @JvmField @NlsSafe val COMMAND_NAME: String = CodeInsightBundle.message("process.optimize.imports.before.commit") } }
apache-2.0
4c198de16a81feef09107341895b1571
47.317073
140
0.818182
4.771084
false
false
false
false
jeeshell/je2sh
core/src/main/kotlin/net/je2sh/core/JeeShell.kt
1
2868
/* * MIT License * * Copyright (c) 2017 JeeSh * * 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 net.je2sh.core import net.je2sh.core.plugins.PluginContext import org.jline.reader.EndOfFileException import org.jline.reader.LineReaderBuilder import org.jline.reader.UserInterruptException import org.jline.terminal.Terminal import org.jline.terminal.TerminalBuilder import java.lang.Exception class JeeShell(val context: PluginContext, val terminal: Terminal = TerminalBuilder.terminal(), val commandManager: CommandManager = context.commandManager) { private val EXIT_CMD = "exit" private var running = false fun run() { val prompt: String = "${context.attributes["prompt"]?.toString() ?: context.principal?.name ?: "jeesh"} $ " val reader = LineReaderBuilder.builder() .terminal(terminal) .build() running = true while (running) { try { val line = reader.readLine(prompt, null, null, null).trim { it <= ' ' } if (line.isEmpty()) { continue } val args = line.split(" ") val cmdStr = args[0] if (EXIT_CMD == cmdStr) { break } commandManager.runCommand(cmdStr, CommandContext(context, terminal), *args.toTypedArray()) } catch (e: UserInterruptException) { // Ignore } catch (e: EndOfFileException) { break } catch (e: Exception) { terminal.writer().println("Command failed with \"" + e.message + "\"") } } terminal.writer().println("See you next time") terminal.writer().flush() terminal.close() } }
mit
20624a79c1a935b1b8339479e94952ce
34.85
115
0.638424
4.574163
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/model/FullTextParser.kt
1
4068
package com.nononsenseapps.feeder.model import android.content.Context import android.util.Log import androidx.work.CoroutineWorker import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.nononsenseapps.feeder.archmodel.Repository import com.nononsenseapps.feeder.blob.blobFullFile import com.nononsenseapps.feeder.blob.blobFullOutputStream import com.nononsenseapps.feeder.db.room.FeedItemForFetching import java.io.File import java.net.URL import java.util.concurrent.TimeUnit import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.fold import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import net.dankito.readability4j.extended.Readability4JExtended import okhttp3.OkHttpClient import org.kodein.di.DI import org.kodein.di.DIAware import org.kodein.di.android.closestDI import org.kodein.di.instance fun scheduleFullTextParse( di: DI, ) { Log.i("FeederFullText", "Scheduling a full text parse work") val workRequest = OneTimeWorkRequestBuilder<FullTextWorker>() .addTag("feeder") .keepResultsForAtLeast(1, TimeUnit.MINUTES) val workManager by di.instance<WorkManager>() workManager.enqueue(workRequest.build()) } class FullTextWorker( val context: Context, workerParams: WorkerParameters ) : CoroutineWorker(context, workerParams), DIAware { override val di: DI by closestDI(context) private val okHttpClient: OkHttpClient by instance() private val repository: Repository by instance() override suspend fun doWork(): Result { Log.i("FeederFullText", "Parsing full texts for articles if missing") val itemsToSync: List<FeedItemForFetching> = repository.getFeedsItemsWithDefaultFullTextParse() .firstOrNull() ?: return Result.success() val success: Boolean = itemsToSync .map { feedItem -> parseFullArticleIfMissing( feedItem = feedItem, okHttpClient = okHttpClient, filesDir = context.filesDir ) } .fold(true) { acc, value -> acc && value } return when (success) { true -> Result.success() false -> Result.failure() } } } suspend fun parseFullArticleIfMissing( feedItem: FeedItemForFetching, okHttpClient: OkHttpClient, filesDir: File ): Boolean { val fullArticleFile = blobFullFile(itemId = feedItem.id, filesDir = filesDir) return fullArticleFile.isFile || parseFullArticle( feedItem = feedItem, okHttpClient = okHttpClient, filesDir = filesDir ).first } suspend fun parseFullArticle( feedItem: FeedItemForFetching, okHttpClient: OkHttpClient, filesDir: File ): Pair<Boolean, Throwable?> = withContext(Dispatchers.Default) { return@withContext try { val url = feedItem.link ?: return@withContext false to null Log.d("FeederFullText", "Fetching full page ${feedItem.link}") val html: String = okHttpClient.curl(URL(url)) ?: return@withContext false to null // TODO verify encoding is respected in reader Log.i("FeederFullText", "Parsing article ${feedItem.link}") val article = Readability4JExtended(url, html).parse() // TODO set image on item if none already // naiveFindImageLink(article.content)?.let { Parser.unescapeEntities(it, true) } Log.d("FeederFullText", "Writing article ${feedItem.link}") withContext(Dispatchers.IO) { blobFullOutputStream(feedItem.id, filesDir).bufferedWriter().use { writer -> writer.write(article.contentWithUtf8Encoding) } } true to null } catch (e: Throwable) { Log.e( "FeederFullText", "Failed to get fulltext for ${feedItem.link}: ${e.message}", e ) false to e } }
gpl-3.0
4a45b4ce115ff44ff43bc344b9d11f6e
32.9
90
0.681416
4.550336
false
false
false
false
Kotlin/kotlinx.coroutines
benchmarks/src/jmh/kotlin/benchmarks/scheduler/actors/StatefulActorBenchmark.kt
1
4947
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package benchmarks.scheduler.actors import benchmarks.* import benchmarks.akka.* import kotlinx.coroutines.* import kotlinx.coroutines.channels.* import org.openjdk.jmh.annotations.* import java.util.concurrent.* /* * kotlinx-based counterpart of [StatefulActorAkkaBenchmark] * * Benchmark (dispatcher) Mode Cnt Score Error Units * StatefulActorBenchmark.multipleComputationsMultipleRequestors fjp avgt 10 81.649 ± 9.671 ms/op * StatefulActorBenchmark.multipleComputationsMultipleRequestors ftp_1 avgt 10 160.590 ± 50.342 ms/op * StatefulActorBenchmark.multipleComputationsMultipleRequestors ftp_8 avgt 10 275.798 ± 32.795 ms/op * * StatefulActorBenchmark.multipleComputationsSingleRequestor fjp avgt 10 67.206 ± 4.023 ms/op * StatefulActorBenchmark.multipleComputationsSingleRequestor ftp_1 avgt 10 17.883 ± 1.314 ms/op * StatefulActorBenchmark.multipleComputationsSingleRequestor ftp_8 avgt 10 77.052 ± 10.132 ms/op * * StatefulActorBenchmark.singleComputationMultipleRequestors fjp avgt 10 488.003 ± 53.014 ms/op * StatefulActorBenchmark.singleComputationMultipleRequestors ftp_1 avgt 10 120.445 ± 24.659 ms/op * StatefulActorBenchmark.singleComputationMultipleRequestors ftp_8 avgt 10 527.118 ± 51.139 ms/op * * StatefulActorBenchmark.singleComputationSingleRequestor fjp avgt 10 95.030 ± 23.850 ms/op * StatefulActorBenchmark.singleComputationSingleRequestor ftp_1 avgt 10 16.005 ± 0.629 ms/op * StatefulActorBenchmark.singleComputationSingleRequestor ftp_8 avgt 10 76.435 ± 5.076 ms/op */ @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(value = 1) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @State(Scope.Benchmark) open class StatefulActorBenchmark : ParametrizedDispatcherBase() { data class Letter(val message: Any, val sender: SendChannel<Letter>) @Param("fjp", "ftp_1", "ftp_8", "scheduler") override var dispatcher: String = "fjp" @Benchmark fun singleComputationSingleRequestor() = runBlocking { run(1, 1) } @Benchmark fun singleComputationMultipleRequestors() = runBlocking { run(1, CORES_COUNT) } @Benchmark fun multipleComputationsSingleRequestor() = runBlocking { run(CORES_COUNT, 1) } @Benchmark fun multipleComputationsMultipleRequestors() = runBlocking { run(CORES_COUNT, CORES_COUNT) } private suspend fun run(computationActorsCount: Int, requestorActorsCount: Int) { val resultChannel: Channel<Unit> = Channel(requestorActorsCount) val computations = (0 until computationActorsCount).map { computationActor() } val requestors = (0 until requestorActorsCount).map { requestorActor(computations, resultChannel) } for (requestor in requestors) { requestor.send(Letter(1L, Channel())) } repeat(requestorActorsCount) { resultChannel.receive() } } private fun CoroutineScope.requestorActor(computations: List<SendChannel<Letter>>, stopChannel: Channel<Unit>) = actor<Letter>(capacity = 1024) { var received = 0 for (letter in channel) with(letter) { when (message) { is Long -> { if (++received >= ROUNDS) { stopChannel.send(Unit) return@actor } else { computations[ThreadLocalRandom.current().nextInt(0, computations.size)] .send(Letter(ThreadLocalRandom.current().nextLong(), channel)) } } else -> error("Cannot happen: $letter") } } } } fun CoroutineScope.computationActor(stateSize: Int = STATE_SIZE) = actor<StatefulActorBenchmark.Letter>(capacity = 1024) { val coefficients = LongArray(stateSize) { ThreadLocalRandom.current().nextLong(0, 100) } for (letter in channel) with(letter) { when (message) { is Long -> { var result = 0L for (coefficient in coefficients) { result += message * coefficient } sender.send(StatefulActorBenchmark.Letter(result, channel)) } is Stop -> return@actor else -> error("Cannot happen: $letter") } } }
apache-2.0
3fb43041969e68158fc753f334b19811
40.470588
116
0.617427
4.466063
false
false
false
false
DeflatedPickle/Quiver
filepanel/src/main/kotlin/com/deflatedpickle/quiver/filepanel/FilePanelPlugin.kt
1
6577
/* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */ @file:Suppress("MemberVisibilityCanBePrivate") package com.deflatedpickle.quiver.filepanel import com.deflatedpickle.haruhi.api.Registry import com.deflatedpickle.haruhi.api.plugin.Plugin import com.deflatedpickle.haruhi.api.plugin.PluginType import com.deflatedpickle.haruhi.event.EventProgramFinishSetup import com.deflatedpickle.haruhi.util.ConfigUtil import com.deflatedpickle.haruhi.util.RegistryUtil import com.deflatedpickle.quiver.backend.event.EventSelectFile import com.deflatedpickle.quiver.filepanel.api.Program import com.deflatedpickle.quiver.filepanel.api.Viewer import com.deflatedpickle.quiver.filepanel.config.FilePanelSettings import com.deflatedpickle.quiver.filepanel.event.EventChangeViewWidget import org.apache.commons.io.FileUtils import org.jdesktop.swingx.JXPanel import org.jdesktop.swingx.JXRadioGroup import java.awt.BorderLayout import java.awt.event.ActionEvent import javax.swing.JToolBar import javax.swing.SwingUtilities @Suppress("unused") @Plugin( value = "$[name]", author = "$[author]", version = "$[version]", description = """ <br> Provides a panel on which a given file can be configured """, type = PluginType.COMPONENT, component = FilePanel::class, settings = FilePanelSettings::class ) object FilePanelPlugin { private val radioButtonGroup = JXRadioGroup<String>() private val viewerToolbar = JToolBar("Viewer").apply { add(radioButtonGroup) } internal val viewerRegistry = Registry<String, MutableList<Viewer<Any>>>() internal val programRegistry = Registry<String, MutableList<Program>>() init { RegistryUtil.register("viewer", viewerRegistry) RegistryUtil.register("program", programRegistry) EventProgramFinishSetup.addListener { FilePanel.widgetPanel.add(this.viewerToolbar, BorderLayout.NORTH) ConfigUtil.getSettings<FilePanelSettings>("deflatedpickle@file_panel#>=1.0.0")?.let { settings -> for (program in settings.linkedPrograms) { putProgramToRegistry(program) } } } EventSelectFile.addListener { it -> FilePanel.nameField.text = it.nameWithoutExtension FilePanel.typeField.text = it.extension FilePanel.fileSize.text = FileUtils.byteCountToDisplaySize(it.length()) FilePanel.openButton.regenMenu() for (component in FilePanel.widgetPanel.components) { // Remove everything but the toolbar to change viewers if (component != this.viewerToolbar) { FilePanel.widgetPanel.remove(component) } } radioButtonGroup.setValues(arrayOf()) val registry = RegistryUtil.get("viewer") val viewerList = registry?.get(it.extension) as MutableList<Viewer<Any>>? // If there there are viewers for this extension... if (viewerList != null) { for (viewer in viewerList) { // Add a button to switch to it radioButtonGroup.add(viewer::class.simpleName) // Get that button and listen to clicks, to set radioButtonGroup.getChildButton(viewer::class.simpleName).addActionListener { _ -> for (component in FilePanel.widgetPanel.components) { if (component !is JToolBar) { FilePanel.widgetPanel.remove(component) } } EventChangeViewWidget.trigger(Pair(it, FilePanel.widgetPanel)) // Refresh the content in the viewer SwingUtilities.invokeLater { viewer.refresh(it) } // Add the viewer wrapped by it's scroller FilePanel.widgetPanel.add( JXPanel(BorderLayout()).apply { add(viewer.getScroller() ?: viewer.getComponent(), BorderLayout.CENTER) viewer.getToolBars()?.let { bar -> bar.north?.let { add(it, BorderLayout.NORTH) } bar.east?.let { add(it, BorderLayout.EAST) } bar.south?.let { add(it, BorderLayout.SOUTH) } bar.west?.let { add(it, BorderLayout.WEST) } } }, BorderLayout.CENTER ) // We added the viewer, so we have to repaint it FilePanel.widgetPanel.repaint() FilePanel.widgetPanel.revalidate() } } } if (radioButtonGroup.childButtonCount > 0) { // This selects the first viewer radioButtonGroup .getChildButton(0).apply { isSelected = true } .actionListeners .first() // The action isn't performed when we select it (silly, right?) // So we have to send out an event for it .actionPerformed( ActionEvent( this, ActionEvent.ACTION_PERFORMED, null ) ) } // Radio buttons we're added/removed, we need to repaint radioButtonGroup.repaint() radioButtonGroup.revalidate() // We'll also repaint this FilePanel.widgetPanel.repaint() FilePanel.widgetPanel.revalidate() } /*EventCreateFile.addListener { EventSelectFile.trigger(it) } EventReplaceFile.addListener { EventSelectFile.trigger(it) } EventDeleteFile.addListener { EventSelectFolder.trigger(it.parentFile) }*/ } fun putProgramToRegistry(program: Program) { for (ext in program.extensions) { if (programRegistry.get(ext) == null) { programRegistry.register(ext, mutableListOf(program)) } else { programRegistry.get(ext)!!.add(program) } } } }
mit
1017cf416a3282c7e167824512b1adc1
38.383234
109
0.566064
5.249002
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/tools/code/CodeRules.kt
1
925
package slatekit.apis.tools.code import slatekit.apis.Access import slatekit.apis.routes.Action import slatekit.apis.routes.Api import slatekit.common.Source class CodeRules(val settings: CodeGenSettings) { fun isValidApi(api: Api): Boolean { val isValidProtocol = api.protocol == Source.API || api.protocol == Source.All val isValidAccess = api.access == Access.Public return isValidAccess && isValidProtocol } fun isValidAction(api: Api, action: Action, declaredMemberLookup: Map<String, Boolean>):Boolean { // Only include declared items val isValidProtocol = action.protocol == Source.API || action.protocol == Source.All val isValidAccess = action.access == Access.Public val isDeclared = declaredMemberLookup.containsKey(action.name) return isValidProtocol && isValidAccess && ( !this.settings.declaredMethodsOnly || isDeclared ) } }
apache-2.0
f3099bacf91ed40211138882bf7521ff
37.541667
103
0.717838
4.404762
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/KotlinSearchSupport.kt
1
7905
// 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.search import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsSafe import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.SearchScope import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.util.application.getServiceSafe import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.ImportPath interface KotlinSearchUsagesSupport { interface ConstructorCallHandle { fun referencedTo(element: KtElement): Boolean } companion object { fun getInstance(project: Project): KotlinSearchUsagesSupport = project.getServiceSafe() val KtParameter.dataClassComponentMethodName: String? get() = getInstance(project).dataClassComponentMethodName(this) val KtExpression.hasType: Boolean get() = getInstance(project).hasType(this) val PsiClass.isSamInterface: Boolean get() = getInstance(project).isSamInterface(this) fun <T : PsiNamedElement> List<T>.filterDataClassComponentsIfDisabled(kotlinOptions: KotlinReferencesSearchOptions): List<T> = firstOrNull()?.let { getInstance(it.project).filterDataClassComponentsIfDisabled(this, kotlinOptions) } ?: this fun PsiReference.isCallableOverrideUsage(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isCallableOverrideUsage(this, declaration) fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isUsageInContainingDeclaration(this, declaration) fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclaration): Boolean = getInstance(declaration.project).isExtensionOfDeclarationClassUsage(this, declaration) fun PsiElement.getReceiverTypeSearcherInfo(isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? = getInstance(project).getReceiverTypeSearcherInfo(this, isDestructionDeclarationSearch) fun KtFile.forceResolveReferences(elements: List<KtElement>) = getInstance(project).forceResolveReferences(this, elements) fun PsiFile.scriptDefinitionExists(): Boolean = getInstance(project).scriptDefinitionExists(this) fun KtFile.getDefaultImports(): List<ImportPath> = getInstance(project).getDefaultImports(this) fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean = getInstance(ktClass.project).forEachKotlinOverride(ktClass, members, scope, searchDeeply, processor) fun PsiMethod.forEachOverridingMethod( scope: SearchScope = runReadAction { useScope() }, processor: (PsiMethod) -> Boolean ): Boolean = getInstance(project).forEachOverridingMethod(this, scope, processor) fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> = getInstance(method.project).findDeepestSuperMethodsNoWrapping(method) fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> = getInstance(project).findTypeAliasByShortName(shortName, project, scope) fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean = getInstance(element.project).isInProjectSource(element, includeScriptsOutsideSourceRoots) fun KtDeclaration.isOverridable(): Boolean = getInstance(project).isOverridable(this) fun KtClass.isInheritable(): Boolean = getInstance(project).isInheritable(this) @NlsSafe fun formatJavaOrLightMethod(method: PsiMethod): String = getInstance(method.project).formatJavaOrLightMethod(method) @NlsSafe fun formatClass(classOrObject: KtClassOrObject): String = getInstance(classOrObject.project).formatClass(classOrObject) fun KtDeclaration.expectedDeclarationIfAny(): KtDeclaration? = getInstance(project).expectedDeclarationIfAny(this) fun KtDeclaration.isExpectDeclaration(): Boolean = getInstance(project).isExpectDeclaration(this) fun KtDeclaration.actualsForExpected(module: Module? = null): Set<KtDeclaration> = getInstance(project).actualsForExpected(this, module) fun PsiElement.canBeResolvedWithFrontEnd(): Boolean = getInstance(project).canBeResolvedWithFrontEnd(this) fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle = getInstance(ktDeclaration.project).createConstructorHandle(ktDeclaration) fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle = getInstance(psiMethod.project).createConstructorHandle(psiMethod) } fun actualsForExpected(declaration: KtDeclaration, module: Module? = null): Set<KtDeclaration> fun dataClassComponentMethodName(element: KtParameter): String? fun hasType(element: KtExpression): Boolean fun isSamInterface(psiClass: PsiClass): Boolean fun <T : PsiNamedElement> filterDataClassComponentsIfDisabled(elements: List<T>, kotlinOptions: KotlinReferencesSearchOptions): List<T> fun isCallableOverrideUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun isUsageInContainingDeclaration(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun isExtensionOfDeclarationClassUsage(reference: PsiReference, declaration: KtNamedDeclaration): Boolean fun getReceiverTypeSearcherInfo(psiElement: PsiElement, isDestructionDeclarationSearch: Boolean): ReceiverTypeSearcherInfo? fun forceResolveReferences(file: KtFile, elements: List<KtElement>) fun scriptDefinitionExists(file: PsiFile): Boolean fun getDefaultImports(file: KtFile): List<ImportPath> fun forEachKotlinOverride( ktClass: KtClass, members: List<KtNamedDeclaration>, scope: SearchScope, searchDeeply: Boolean, processor: (superMember: PsiElement, overridingMember: PsiElement) -> Boolean ): Boolean fun forEachOverridingMethod( method: PsiMethod, scope: SearchScope, processor: (PsiMethod) -> Boolean ): Boolean fun findDeepestSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> fun findSuperMethodsNoWrapping(method: PsiElement): List<PsiElement> fun findTypeAliasByShortName(shortName: String, project: Project, scope: GlobalSearchScope): Collection<KtTypeAlias> fun isInProjectSource(element: PsiElement, includeScriptsOutsideSourceRoots: Boolean = false): Boolean fun isOverridable(declaration: KtDeclaration): Boolean fun isInheritable(ktClass: KtClass): Boolean fun formatJavaOrLightMethod(method: PsiMethod): String fun formatClass(classOrObject: KtClassOrObject): String fun expectedDeclarationIfAny(declaration: KtDeclaration): KtDeclaration? fun isExpectDeclaration(declaration: KtDeclaration): Boolean fun canBeResolvedWithFrontEnd(element: PsiElement): Boolean fun createConstructorHandle(ktDeclaration: KtDeclaration): ConstructorCallHandle fun createConstructorHandle(psiMethod: PsiMethod): ConstructorCallHandle }
apache-2.0
a1ce05b22a883f82093c0320131381e6
43.167598
158
0.750917
5.957046
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/unaryExpression/not.kt
12
101
val a = true val b = <warning descr="SSR">!a</warning> val c = <warning descr="SSR">a.not()</warning>
apache-2.0
788cd1a2e63e32089627e3bc7dda84f8
33
46
0.643564
2.885714
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/textBuilder/buildDecompiledText.kt
1
7309
// 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.decompiler.textBuilder import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.contracts.description.ContractProviderKey import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.core.quoteIfNeeded import org.jetbrains.kotlin.idea.decompiler.navigation.ByDescriptorIndexer import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.DescriptorRendererModifier import org.jetbrains.kotlin.renderer.DescriptorRendererOptions import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.DescriptorUtils.isEnumEntry import org.jetbrains.kotlin.resolve.descriptorUtil.secondaryConstructors import org.jetbrains.kotlin.types.isFlexible private const val DECOMPILED_CODE_COMMENT = "/* compiled code */" private const val DECOMPILED_COMMENT_FOR_PARAMETER = "/* = compiled code */" private const val FLEXIBLE_TYPE_COMMENT = "/* platform type */" private const val DECOMPILED_CONTRACT_STUB = "contract { /* compiled contract */ }" fun DescriptorRendererOptions.defaultDecompilerRendererOptions() { withDefinedIn = false classWithPrimaryConstructor = true secondaryConstructorsAsPrimary = false modifiers = DescriptorRendererModifier.ALL excludedTypeAnnotationClasses = emptySet() alwaysRenderModifiers = true parameterNamesInFunctionalTypes = false // to support parameters names in decompiled text we need to load annotation arguments } fun buildDecompiledText( packageFqName: FqName, descriptors: List<DeclarationDescriptor>, descriptorRenderer: DescriptorRenderer, indexers: Collection<DecompiledTextIndexer<*>> = listOf(ByDescriptorIndexer) ): DecompiledText { val builder = StringBuilder() fun appendDecompiledTextAndPackageName() { builder.append("// IntelliJ API Decompiler stub source generated from a class file\n" + "// Implementation of methods is not available") builder.append("\n\n") if (!packageFqName.isRoot) { builder.append("package ").append(packageFqName.quoteIfNeeded()).append("\n\n") } } val textIndex = DecompiledTextIndex(indexers) fun indexDescriptor(descriptor: DeclarationDescriptor, startOffset: Int, endOffset: Int) { textIndex.addToIndex(descriptor, TextRange(startOffset, endOffset)) } fun CallableMemberDescriptor.isConsideredSynthetic(): Boolean { return when (kind) { CallableMemberDescriptor.Kind.DECLARATION -> false CallableMemberDescriptor.Kind.FAKE_OVERRIDE, CallableMemberDescriptor.Kind.DELEGATION -> true CallableMemberDescriptor.Kind.SYNTHESIZED -> { // Of all synthesized functions, only `component*` functions are rendered (for historical reasons) !DataClassDescriptorResolver.isComponentLike(name) } } } fun appendDescriptor(descriptor: DeclarationDescriptor, indent: String, lastEnumEntry: Boolean? = null) { val startOffset = builder.length if (isEnumEntry(descriptor)) { for (annotation in descriptor.annotations) { builder.append(descriptorRenderer.renderAnnotation(annotation)) builder.append(" ") } builder.append(descriptor.name.asString().quoteIfNeeded()) builder.append(if (lastEnumEntry!!) ";" else ",") } else { builder.append(descriptorRenderer.render(descriptor).replace("= ...", DECOMPILED_COMMENT_FOR_PARAMETER)) } var endOffset = builder.length if (descriptor is CallableDescriptor) { //NOTE: assuming that only return types can be flexible if (descriptor.returnType!!.isFlexible()) { builder.append(" ").append(FLEXIBLE_TYPE_COMMENT) } } if (descriptor is FunctionDescriptor || descriptor is PropertyDescriptor) { if ((descriptor as MemberDescriptor).modality != Modality.ABSTRACT) { if (descriptor is FunctionDescriptor) { with(builder) { append(" { ") if (descriptor.getUserData(ContractProviderKey)?.getContractDescription() != null) { append(DECOMPILED_CONTRACT_STUB).append("; ") } append(DECOMPILED_CODE_COMMENT).append(" }") } } else { // descriptor instanceof PropertyDescriptor builder.append(" ").append(DECOMPILED_CODE_COMMENT) } endOffset = builder.length } } else if (descriptor is ClassDescriptor && !isEnumEntry(descriptor)) { builder.append(" {\n") val subindent = "$indent " var firstPassed = false fun newlineExceptFirst() { if (firstPassed) { builder.append("\n") } else { firstPassed = true } } val allDescriptors = descriptor.secondaryConstructors + descriptor.defaultType.memberScope.getContributedDescriptors() val (enumEntries, members) = allDescriptors.partition(::isEnumEntry) for ((index, enumEntry) in enumEntries.withIndex()) { newlineExceptFirst() builder.append(subindent) appendDescriptor(enumEntry, subindent, index == enumEntries.lastIndex) } val companionObject = descriptor.companionObjectDescriptor if (companionObject != null) { newlineExceptFirst() builder.append(subindent) appendDescriptor(companionObject, subindent) } for (member in members) { if (member.containingDeclaration != descriptor) { continue } if (member == companionObject) { continue } if (member is CallableMemberDescriptor && member.isConsideredSynthetic()) { continue } newlineExceptFirst() builder.append(subindent) appendDescriptor(member, subindent) } builder.append(indent).append("}") endOffset = builder.length } builder.append("\n") indexDescriptor(descriptor, startOffset, endOffset) if (descriptor is ClassDescriptor) { val primaryConstructor = descriptor.unsubstitutedPrimaryConstructor if (primaryConstructor != null) { indexDescriptor(primaryConstructor, startOffset, endOffset) } } } appendDecompiledTextAndPackageName() for (member in descriptors) { appendDescriptor(member, "") builder.append("\n") } return DecompiledText(builder.toString(), textIndex) }
apache-2.0
b8dfd7160045910ecb5ab3c80b8f7c7b
40.765714
158
0.640854
5.562405
false
false
false
false
kohesive/kohesive-iac
model-aws/src/main/kotlin/uy/kohesive/iac/model/aws/cloudformation/resources/builders/WaitCondition.kt
1
854
package uy.kohesive.iac.model.aws.cloudformation.resources.builders import com.amazonaws.AmazonWebServiceRequest import uy.kohesive.iac.model.aws.cloudformation.ResourcePropertiesBuilder import uy.kohesive.iac.model.aws.cloudformation.resources.CloudFormation import uy.kohesive.iac.model.aws.cloudformation.wait.CreateWaitConditionRequest class WaitConditionPropertiesBuilder : ResourcePropertiesBuilder<CreateWaitConditionRequest> { override val requestClazz = CreateWaitConditionRequest::class override fun buildResource(request: AmazonWebServiceRequest, relatedObjects: List<Any>) = (request as CreateWaitConditionRequest).let { CloudFormation.WaitCondition( Handle = it.handle, Timeout = it.timeout.toString(), Count = it.count?.toString() ) } }
mit
6872517e6de96d7d89866740624b4673
41.7
94
0.748244
5.053254
false
false
false
false
QuixomTech/DeviceInfo
app/src/main/java/com/quixom/apps/deviceinfo/service/AppWidgetService.kt
1
3532
package com.quixom.apps.deviceinfo.service import android.annotation.SuppressLint import android.app.ActivityManager import android.app.Service import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.os.IBinder import android.support.annotation.Nullable import android.widget.RemoteViews import com.quixom.apps.deviceinfo.R import com.quixom.apps.deviceinfo.Widget.MyWidgetProvider import com.quixom.apps.deviceinfo.utilities.Methods import java.text.DecimalFormat import java.util.* /** * Created by D46 on 3/26/2018. */ class AppWidgetService : Service() { var totalRamValue: Long? = null var freeRamValue: Long? = null var usedRamValue: Long? = null @Nullable override fun onBind(intent: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val appWidgetManager: AppWidgetManager = AppWidgetManager.getInstance(this@AppWidgetService) val allWidgetIds = intent?.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS) val timer = Timer() val hourlyTask = object : TimerTask() { override fun run() { val cm: ConnectivityManager = [email protected](Context.CONNECTIVITY_SERVICE) as ConnectivityManager showRAMUsage() val view = RemoteViews(packageName, R.layout.widget_layout) view.setTextViewText(R.id.tv_free_memory, "Free: " + formatSize(freeRamValue!!)) view.setTextViewText(R.id.tv_total_memory, "Total: " + formatSize(totalRamValue!!)) view.setTextViewText(R.id.tv_used_memory, "Used: " + formatSize(usedRamValue!!)) view.setProgressBar(R.id.widgetProgressBar, 100, Methods.calculatePercentage(usedRamValue!!.toDouble(), totalRamValue!!.toDouble()).toFloat().toInt(), false) val theWidget = ComponentName(this@AppWidgetService, MyWidgetProvider::class.java!!) val manager = AppWidgetManager.getInstance(this@AppWidgetService) manager.updateAppWidget(theWidget, view) } } // schedule the task to run starting now and then every half-an-hour... timer.schedule(hourlyTask, 0L, 1000) return START_STICKY } @SuppressLint("SetTextI18n") private fun showRAMUsage() { totalRamValue = totalRamMemorySize() freeRamValue = freeRamMemorySize() usedRamValue = totalRamValue!! - freeRamValue!! } private fun totalRamMemorySize(): Long { val mi = ActivityManager.MemoryInfo() val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.getMemoryInfo(mi) return mi.totalMem } private fun freeRamMemorySize(): Long { val mi = ActivityManager.MemoryInfo() val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager activityManager.getMemoryInfo(mi) return mi.availMem } private fun formatSize(size: Long): String { if (size <= 0) return "0" val units = arrayOf("B", "KB", "MB", "GB", "TB") val digitGroups = (Math.log10(size.toDouble()) / Math.log10(1024.0)).toInt() return DecimalFormat("#,##0.#").format(size / Math.pow(1024.0, digitGroups.toDouble())) + " " + units[digitGroups] } }
apache-2.0
0064aa0782f5f3ac61c2cee0679e311c
36.585106
173
0.68573
4.587013
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/GithubCredentialsUI.kt
1
10681
// 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.plugins.github.authentication.ui import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBTextField import com.intellij.ui.components.fields.ExtendableTextField import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.layout.* import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.UIUtil import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.util.GHAccessTokenCreator import org.jetbrains.plugins.github.authentication.util.GHSecurityUtil import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException import org.jetbrains.plugins.github.exceptions.GithubParseException import org.jetbrains.plugins.github.ui.util.DialogValidationUtils import org.jetbrains.plugins.github.ui.util.Validator import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.net.UnknownHostException import java.util.function.Supplier import javax.swing.* sealed class GithubCredentialsUI { abstract fun getPanel(): JPanel abstract fun getPreferredFocus(): JComponent abstract fun getValidator(): Validator abstract fun createExecutor(): GithubApiRequestExecutor abstract fun acquireLoginAndToken(server: GithubServerPath, executor: GithubApiRequestExecutor, indicator: ProgressIndicator): Pair<String, String> abstract fun handleAcquireError(error: Throwable): ValidationInfo abstract fun setBusy(busy: Boolean) protected val loginButton = JButton("Log In").apply { isVisible = false } protected val cancelButton = JButton("Cancel").apply { isVisible = false } open fun setLoginAction(actionListener: ActionListener) { loginButton.addActionListener(actionListener) loginButton.setMnemonic('l') } fun setCancelAction(actionListener: ActionListener) { cancelButton.addActionListener(actionListener) cancelButton.setMnemonic('c') } fun setLoginButtonVisible(visible: Boolean) { loginButton.isVisible = visible } fun setCancelButtonVisible(visible: Boolean) { cancelButton.isVisible = visible } internal class PasswordUI(private val serverTextField: ExtendableTextField, private val clientName: String, switchUi: () -> Unit, private val executorFactory: GithubApiRequestExecutor.Factory, private val isAccountUnique: (login: String, server: GithubServerPath) -> Boolean, private val dialogMode: Boolean) : GithubCredentialsUI() { private val loginTextField = JBTextField() private val passwordField = JPasswordField() private val switchUiLink = LinkLabel.create("Use Token", switchUi) fun setLogin(login: String, editable: Boolean = true) { loginTextField.text = login loginTextField.isEditable = editable } fun setPassword(password: String) { passwordField.text = password } override fun setLoginAction(actionListener: ActionListener) { super.setLoginAction(actionListener) passwordField.setEnterPressedAction(actionListener) loginTextField.setEnterPressedAction(actionListener) serverTextField.setEnterPressedAction(actionListener) } override fun getPanel(): JPanel = panel { buildTitleAndLinkRow(this, dialogMode, switchUiLink) row("Server:") { serverTextField(pushX, growX) } row("Login:") { loginTextField(pushX, growX) } row("Password:") { passwordField(comment = "The password is not saved and is only used to generate a GitHub token", constraints = *arrayOf(pushX, growX)) } row("") { cell { loginButton() cancelButton() } } }.apply { border = JBEmptyBorder(UIUtil.getRegularPanelInsets()) } override fun getPreferredFocus() = if (loginTextField.isEditable && loginTextField.text.isEmpty()) loginTextField else passwordField override fun getValidator() = DialogValidationUtils.chain( { DialogValidationUtils.notBlank(loginTextField, "Login cannot be empty") }, { DialogValidationUtils.notBlank(passwordField, "Password cannot be empty") }) override fun createExecutor(): GithubApiRequestExecutor.WithBasicAuth { val modalityState = ModalityState.stateForComponent(passwordField) return executorFactory.create(loginTextField.text, passwordField.password, Supplier { invokeAndWaitIfNeeded(modalityState) { Messages.showInputDialog(passwordField, "Authentication code:", "GitHub Two-Factor Authentication", null) } }) } override fun acquireLoginAndToken(server: GithubServerPath, executor: GithubApiRequestExecutor, indicator: ProgressIndicator): Pair<String, String> { val login = loginTextField.text.trim() if (!isAccountUnique(login, server)) throw LoginNotUniqueException(login) val token = GHAccessTokenCreator(server, executor, indicator).createMaster(clientName).token return login to token } override fun handleAcquireError(error: Throwable): ValidationInfo { return when (error) { is LoginNotUniqueException -> ValidationInfo("Account already added", loginTextField).withOKEnabled() is UnknownHostException -> ValidationInfo("Server is unreachable").withOKEnabled() is GithubAuthenticationException -> ValidationInfo("Incorrect credentials. ${error.message.orEmpty()}").withOKEnabled() is GithubParseException -> ValidationInfo(error.message ?: "Invalid server path", serverTextField) else -> ValidationInfo("Invalid authentication data.\n ${error.message}").withOKEnabled() } } override fun setBusy(busy: Boolean) { loginTextField.isEnabled = !busy passwordField.isEnabled = !busy switchUiLink.isEnabled = !busy } } internal class TokenUI(val factory: GithubApiRequestExecutor.Factory, val isAccountUnique: (name: String, server: GithubServerPath) -> Boolean, private val serverTextField: ExtendableTextField, switchUi: () -> Unit, private val dialogMode: Boolean) : GithubCredentialsUI() { private val tokenTextField = JBTextField() private val switchUiLink = LinkLabel.create("Use Credentials", switchUi) private var fixedLogin: String? = null fun setToken(token: String) { tokenTextField.text = token } override fun getPanel() = panel { buildTitleAndLinkRow(this, dialogMode, switchUiLink) row("Server:") { serverTextField(pushX, growX) } row("Token:") { tokenTextField( comment = "The following scopes must be granted to the access token: " + GHSecurityUtil.MASTER_SCOPES, constraints = *arrayOf(pushX, growX)) } row("") { cell { loginButton() cancelButton() } } }.apply { border = JBEmptyBorder(UIUtil.getRegularPanelInsets()) } override fun getPreferredFocus() = tokenTextField override fun getValidator(): () -> ValidationInfo? = { DialogValidationUtils.notBlank(tokenTextField, "Token cannot be empty") } override fun createExecutor() = factory.create(tokenTextField.text) override fun acquireLoginAndToken(server: GithubServerPath, executor: GithubApiRequestExecutor, indicator: ProgressIndicator): Pair<String, String> { val (details, scopes) = GHSecurityUtil.loadCurrentUserWithScopes(executor, indicator, server) if (scopes == null || !GHSecurityUtil.isEnoughScopes(scopes)) throw GithubAuthenticationException("Insufficient scopes granted to token.") val login = details.login fixedLogin?.let { if (it != login) throw GithubAuthenticationException("Token should match username \"$it\"") } if (!isAccountUnique(login, server)) throw LoginNotUniqueException(login) return login to tokenTextField.text } override fun handleAcquireError(error: Throwable): ValidationInfo { return when (error) { is LoginNotUniqueException -> ValidationInfo("Account ${error.login} already added").withOKEnabled() is UnknownHostException -> ValidationInfo("Server is unreachable").withOKEnabled() is GithubAuthenticationException -> ValidationInfo("Incorrect credentials. ${error.message.orEmpty()}").withOKEnabled() is GithubParseException -> ValidationInfo(error.message ?: "Invalid server path", serverTextField) else -> ValidationInfo("Invalid authentication data.\n ${error.message}").withOKEnabled() } } override fun setBusy(busy: Boolean) { tokenTextField.isEnabled = !busy switchUiLink.isEnabled = !busy } fun setFixedLogin(fixedLogin: String?) { this.fixedLogin = fixedLogin } override fun setLoginAction(actionListener: ActionListener) { super.setLoginAction(actionListener) tokenTextField.setEnterPressedAction(actionListener) serverTextField.setEnterPressedAction(actionListener) } } } private fun buildTitleAndLinkRow(layoutBuilder: LayoutBuilder, dialogMode: Boolean, linkLabel: LinkLabel<*>) { layoutBuilder.row { cell(isFullWidth = true) { if (!dialogMode) { val jbLabel = JBLabel("Log In to GitHub", UIUtil.ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) } jbLabel() } JLabel(" ")(pushX, growX) // just to be able to align link to the right linkLabel() } } } private fun JComponent.setEnterPressedAction(actionListener: ActionListener) { registerKeyboardAction(actionListener, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED) }
apache-2.0
68f554e1898e1a947ddbe70ef00794d6
40.886275
140
0.693194
5.142513
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/tests/test/org/jetbrains/kotlin/gradle/ResolveModulesPerSourceSetInMppBuildIssueTest.kt
1
2863
// 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.gradle import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.project.Project import com.intellij.testFramework.LightPlatformTestCase import org.jetbrains.kotlin.idea.configuration.ResolveModulesPerSourceSetInMppBuildIssue import org.jetbrains.plugins.gradle.service.project.open.setupGradleSettings import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.settings.GradleSettings import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicInteger class ResolveModulesPerSourceSetInMppBuildIssueTest : LightPlatformTestCase() { override fun tearDown() { GradleSettings.getInstance(project).apply { linkedProjectsSettings.forEach { projectSetting -> unlinkExternalProject(projectSetting.externalProjectPath) } } super.tearDown() } fun `test description contains QuickFix id`() { val buildIssue = ResolveModulesPerSourceSetInMppBuildIssue() assertTrue( "Expected link to the QuickFix in the build issues description", buildIssue.quickFixes.single().id in buildIssue.description ) } fun `test quickFix updates GradleProjectSettings`() { val gradleSettings = GradleSettings.getInstance(project) gradleSettings.setupGradleSettings() gradleSettings.linkProject(GradleProjectSettings().apply { externalProjectPath = project.basePath isResolveModulePerSourceSet = false }) assertFalse( "Expected isResolveModulePerSourceSet is false before running QuickFix", gradleSettings.linkedProjectsSettings.single().isResolveModulePerSourceSet ) val testProjectRefresher = TestProjectRefresher() ResolveModulesPerSourceSetInMppBuildIssue(testProjectRefresher) .quickFixes.single() .runQuickFix(project, DataProvider {}) .get() assertTrue( "Expected isResolveModulePerSourceSet is true after running QuickFix", gradleSettings.linkedProjectsSettings.single().isResolveModulePerSourceSet ) assertEquals( "Expect single invocation of project refresher", 1, testProjectRefresher.invocationCount.get() ) } } private class TestProjectRefresher( ) : ResolveModulesPerSourceSetInMppBuildIssue.ProjectRefresher { val invocationCount = AtomicInteger(0) override fun invoke(project: Project): CompletableFuture<*> { invocationCount.getAndIncrement() return CompletableFuture.completedFuture(null) } }
apache-2.0
a6acd725b18a9ebe4d95047715519205
38.763889
158
0.729305
6.091489
false
true
false
false
akosyakov/intellij-community
platform/script-debugger/protocol/protocol-reader/src/TextOutput.kt
3
2685
package org.jetbrains.protocolReader import java.util.Arrays public val EMPTY_CHARS: CharArray = CharArray(0) private val indentGranularity = 2 public class TextOutput(public val out: StringBuilder) { private var identLevel: Int = 0 private var indents = array(EMPTY_CHARS) private var justNewLined: Boolean = false public fun indentIn(): TextOutput { ++identLevel if (identLevel >= indents.size) { // Cache a new level of indentation string. val newIndentLevel = CharArray(identLevel * indentGranularity) Arrays.fill(newIndentLevel, ' ') val newIndents = arrayOfNulls<CharArray>(indents.size + 1) System.arraycopy(indents, 0, newIndents, 0, indents.size) newIndents[identLevel] = newIndentLevel indents = newIndents as Array<CharArray> } return this } public fun indentOut(): TextOutput { --identLevel return this } public fun newLine(): TextOutput { out.append('\n') justNewLined = true return this } public fun append(value: Double): TextOutput { maybeIndent() out.append(value) return this } public fun append(value: Boolean): TextOutput { maybeIndent() out.append(value) return this } public fun append(value: Int): TextOutput { maybeIndent() out.append(value) return this } public fun append(c: Char): TextOutput { maybeIndent() out.append(c) return this } public fun append(s: CharArray) { maybeIndent() out.append(s) } public fun append(s: CharSequence): TextOutput { maybeIndent() out.append(s) return this } public fun append(s: CharSequence, start: Int): TextOutput { maybeIndent() out.append(s, start, s.length()) return this } public fun openBlock(): TextOutput { openBlock(true) return this } public fun openBlock(addNewLine: Boolean) { space().append('{') if (addNewLine) { newLine() } indentIn() } public fun closeBlock() { indentOut().newLine().append('}') } public fun comma(): TextOutput { return append(',').space() } public fun space(): TextOutput { return append(' ') } public fun semi(): TextOutput { return append(';') } public fun doc(description: String?): TextOutput { if (description == null) { return this } return append("/**").newLine().append(" * ").append(description).newLine().append(" */").newLine() } public fun quote(s: CharSequence): TextOutput { return append('"').append(s).append('"') } public fun maybeIndent() { if (justNewLined) { out.append(indents[identLevel]) justNewLined = false } } }
apache-2.0
673a4710a901d3ac228089eb69a8f65b
20.48
102
0.641713
4.080547
false
false
false
false
jwren/intellij-community
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesDashboardActions.kt
2
27949
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.ui.branch.dashboard import com.intellij.dvcs.DvcsUtil import com.intellij.dvcs.DvcsUtil.disableActionIfAnyRepositoryIsFresh import com.intellij.dvcs.branch.GroupingKey import com.intellij.dvcs.diverged import com.intellij.dvcs.getCommonCurrentBranch import com.intellij.dvcs.repo.Repository import com.intellij.dvcs.ui.DvcsBundle import com.intellij.dvcs.ui.RepositoryChangesBrowserNode import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.service import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.vcs.log.VcsLogProperties import com.intellij.vcs.log.impl.VcsLogUiProperties import com.intellij.vcs.log.impl.VcsProjectLog import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcs.log.ui.actions.BooleanPropertyToggleAction import com.intellij.vcs.log.util.VcsLogUtil.HEAD import git4idea.GitUtil import git4idea.actions.GitFetch import git4idea.actions.branch.GitBranchActionsUtil.calculateNewBranchInitialName import git4idea.branch.GitBranchType import git4idea.branch.GitBrancher import git4idea.config.GitVcsSettings import git4idea.fetch.GitFetchResult import git4idea.fetch.GitFetchSupport import git4idea.i18n.GitBundle.message import git4idea.i18n.GitBundleExtensions.messagePointer import git4idea.isRemoteBranchProtected import git4idea.remote.editRemote import git4idea.remote.removeRemotes import git4idea.repo.GitRemote import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.branch.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import java.util.function.Supplier import javax.swing.Icon internal object BranchesDashboardActions { class BranchesTreeActionGroup(private val project: Project, private val tree: FilteringBranchesTree) : ActionGroup(), DumbAware { init { isPopup = true } override fun hideIfNoVisibleChildren() = true override fun getChildren(e: AnActionEvent?): Array<AnAction> = BranchActionsBuilder(project, tree).build()?.getChildren(e) ?: AnAction.EMPTY_ARRAY } class MultipleLocalBranchActions : ActionGroup(), DumbAware { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayOf(ShowArbitraryBranchesDiffAction(), UpdateSelectedBranchAction(), DeleteBranchAction()) } class CurrentBranchActions(project: Project, repositories: List<GitRepository>, branchName: String, selectedRepository: GitRepository) : GitBranchPopupActions.CurrentBranchActions(project, repositories, branchName, selectedRepository) { override fun getChildren(e: AnActionEvent?): Array<AnAction> { val children = arrayListOf<AnAction>(*super.getChildren(e)) if (myRepositories.diverged()) { children.add(1, CheckoutAction(myProject, myRepositories, myBranchName)) } return children.toTypedArray() } } class LocalBranchActions(project: Project, repositories: List<GitRepository>, branchName: String, selectedRepository: GitRepository) : GitBranchPopupActions.LocalBranchActions(project, repositories, branchName, selectedRepository) { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayListOf<AnAction>(*super.getChildren(e)).toTypedArray() } class RemoteBranchActions(project: Project, repositories: List<GitRepository>, @NonNls branchName: String, selectedRepository: GitRepository) : GitBranchPopupActions.RemoteBranchActions(project, repositories, branchName, selectedRepository) { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayListOf<AnAction>(*super.getChildren(e)).toTypedArray() } class GroupActions : ActionGroup(), DumbAware { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayListOf<AnAction>(EditRemoteAction(), RemoveRemoteAction()).toTypedArray() } class MultipleGroupActions : ActionGroup(), DumbAware { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayListOf<AnAction>(RemoveRemoteAction()).toTypedArray() } class RemoteGlobalActions : ActionGroup(), DumbAware { override fun getChildren(e: AnActionEvent?): Array<AnAction> = arrayListOf<AnAction>(ActionManager.getInstance().getAction("Git.Configure.Remotes")).toTypedArray() } class BranchActionsBuilder(private val project: Project, private val tree: FilteringBranchesTree) { fun build(): ActionGroup? { val selectedBranches = tree.getSelectedBranches() val multipleBranchSelection = selectedBranches.size > 1 val guessRepo = DvcsUtil.guessCurrentRepositoryQuick(project, GitUtil.getRepositoryManager(project), GitVcsSettings.getInstance(project).recentRootPath) ?: return null if (multipleBranchSelection) { return MultipleLocalBranchActions() } val branchInfo = selectedBranches.singleOrNull() val headSelected = tree.getSelectedBranchFilters().contains(HEAD) if (branchInfo != null && !headSelected) { val selectedRepositories = tree.getSelectedRepositories(branchInfo) val selectedRepository = selectedRepositories.singleOrNull() ?: guessRepo return when { branchInfo.isCurrent -> CurrentBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository) branchInfo.isLocal -> LocalBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository) else -> RemoteBranchActions(project, selectedRepositories, branchInfo.branchName, selectedRepository) } } val selectedRemotes = tree.getSelectedRemotes() if (selectedRemotes.size == 1) { return GroupActions() } else if (selectedRemotes.isNotEmpty()) { return MultipleGroupActions() } val selectedBranchNodes = tree.getSelectedBranchNodes() if (selectedBranchNodes.size == 1 && selectedBranchNodes.first().type == NodeType.REMOTE_ROOT) { return RemoteGlobalActions() } val currentBranchName = guessRepo.currentBranchName if (currentBranchName != null && headSelected) { return CurrentBranchActions(project, listOf(guessRepo), currentBranchName, guessRepo) } return null } } class NewBranchAction : BranchesActionBase({ DvcsBundle.message("new.branch.action.text") }, { DvcsBundle.message("new.branch.action.text") }, com.intellij.dvcs.ui.NewBranchAction.icon) { override fun update(e: AnActionEvent) { val branchFilters = e.getData(GIT_BRANCH_FILTERS) if (branchFilters != null && branchFilters.contains(HEAD)) { e.presentation.isEnabled = true } else { super.update(e) } } override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { if (branches.size > 1) { e.presentation.isEnabled = false e.presentation.description = message("action.Git.New.Branch.description") return } val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = branches.flatMap(controller::getSelectedRepositories).distinct() disableActionIfAnyRepositoryIsFresh(e, repositories, DvcsBundle.message("action.not.possible.in.fresh.repo.new.branch")) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val branchFilters = e.getData(GIT_BRANCH_FILTERS) if (branchFilters != null && branchFilters.contains(HEAD)) { val repositories = GitRepositoryManager.getInstance(project).repositories createOrCheckoutNewBranch(project, repositories, HEAD, initialName = repositories.getCommonCurrentBranch()) } else { val branches = e.getData(GIT_BRANCHES)!! val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = branches.flatMap(controller::getSelectedRepositories).distinct() val branchInfo = branches.first() val branchName = branchInfo.branchName createOrCheckoutNewBranch(project, repositories, "$branchName^0", message("action.Git.New.Branch.dialog.title", branchName), calculateNewBranchInitialName(branchName, !branchInfo.isLocal)) } } } class UpdateSelectedBranchAction : BranchesActionBase(text = messagePointer("action.Git.Update.Selected.text"), icon = AllIcons.Actions.CheckOut) { override fun update(e: AnActionEvent) { val enabledAndVisible = e.project?.let(::hasRemotes) ?: false e.presentation.isEnabledAndVisible = enabledAndVisible if (enabledAndVisible) { super.update(e) } } override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { val presentation = e.presentation if (GitFetchSupport.fetchSupport(project).isFetchRunning) { presentation.isEnabled = false presentation.description = message("action.Git.Update.Selected.description.already.running") return } val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = branches.flatMap(controller::getSelectedRepositories).distinct() val branchNames = branches.map(BranchInfo::branchName) val updateMethodName = GitVcsSettings.getInstance(project).updateMethod.name.toLowerCase() presentation.description = message("action.Git.Update.Selected.description", branches.size, updateMethodName) val trackingInfosExist = isTrackingInfosExist(branchNames, repositories) presentation.isEnabled = trackingInfosExist if (!trackingInfosExist) { presentation.description = message("action.Git.Update.Selected.description.tracking.not.configured", branches.size) } } override fun actionPerformed(e: AnActionEvent) { val branches = e.getData(GIT_BRANCHES)!! val project = e.project!! val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = branches.flatMap(controller::getSelectedRepositories).distinct() val branchNames = branches.map(BranchInfo::branchName) updateBranches(project, repositories, branchNames) } } class DeleteBranchAction : BranchesActionBase(icon = AllIcons.Actions.GC) { override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { e.presentation.text = message("action.Git.Delete.Branch.title", branches.size) val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val disabled = branches.any { it.isCurrent || (!it.isLocal && isRemoteBranchProtected(controller.getSelectedRepositories(it), it.branchName)) } e.presentation.isEnabled = !disabled } override fun actionPerformed(e: AnActionEvent) { val branches = e.getData(GIT_BRANCHES)!! val project = e.project!! val controller = e.getData(BRANCHES_UI_CONTROLLER)!! delete(project, branches, controller) } private fun delete(project: Project, branches: Collection<BranchInfo>, controller: BranchesDashboardController) { val gitBrancher = GitBrancher.getInstance(project) val (localBranches, remoteBranches) = branches.partition { it.isLocal && !it.isCurrent } with(gitBrancher) { val branchesToContainingRepositories: Map<String, List<GitRepository>> = localBranches.associate { it.branchName to controller.getSelectedRepositories(it) } val deleteRemoteBranches = { deleteRemoteBranches(remoteBranches.map(BranchInfo::branchName), remoteBranches.flatMap(BranchInfo::repositories).distinct()) } val localBranchNames = branchesToContainingRepositories.keys if (localBranchNames.isNotEmpty()) { //delete local (possible tracked) branches first if any deleteBranches(branchesToContainingRepositories, deleteRemoteBranches) } else { deleteRemoteBranches() } } } } class ShowBranchDiffAction : BranchesActionBase(text = messagePointer("action.Git.Compare.With.Current.title"), icon = AllIcons.Actions.Diff) { override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { if (branches.none { !it.isCurrent }) { e.presentation.isEnabled = false e.presentation.description = message("action.Git.Update.Selected.description.select.non.current") } } override fun actionPerformed(e: AnActionEvent) { val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val branches = e.getData(GIT_BRANCHES)!! val project = e.project!! val gitBrancher = GitBrancher.getInstance(project) for (branch in branches.filterNot(BranchInfo::isCurrent)) { gitBrancher.compare(branch.branchName, controller.getSelectedRepositories(branch)) } } } class ShowArbitraryBranchesDiffAction : BranchesActionBase(text = messagePointer("action.Git.Compare.Selected.title"), icon = AllIcons.Actions.Diff) { override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { if (branches.size != 2) { e.presentation.isEnabledAndVisible = false e.presentation.description = "" } else { e.presentation.description = message("action.Git.Compare.Selected.description") val branchOne = branches.elementAt(0) val branchTwo = branches.elementAt(1) val controller = e.getData(BRANCHES_UI_CONTROLLER)!! if (branchOne.branchName == branchTwo.branchName || controller.commonRepositories(branchOne, branchTwo).isEmpty()) { e.presentation.isEnabled = false e.presentation.description = message("action.Git.Compare.Selected.description.disabled") } } } override fun actionPerformed(e: AnActionEvent) { val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val branches = e.getData(GIT_BRANCHES)!! val branchOne = branches.elementAt(0) val branchTwo = branches.elementAt(1) val commonRepositories = controller.commonRepositories(branchOne, branchTwo) GitBrancher.getInstance(e.project!!).compareAny(branchOne.branchName, branchTwo.branchName, commonRepositories.toList()) } private fun BranchesDashboardController.commonRepositories(branchOne: BranchInfo, branchTwo: BranchInfo): Collection<GitRepository>{ return getSelectedRepositories(branchOne) intersect getSelectedRepositories(branchTwo) } } class ShowMyBranchesAction(private val uiController: BranchesDashboardController) : ToggleAction(messagePointer("action.Git.Show.My.Branches.title"), AllIcons.Actions.Find), DumbAware { override fun isSelected(e: AnActionEvent) = uiController.showOnlyMy override fun setSelected(e: AnActionEvent, state: Boolean) { uiController.showOnlyMy = state } override fun update(e: AnActionEvent) { super.update(e) val project = e.getData(CommonDataKeys.PROJECT) if (project == null) { e.presentation.isEnabled = false return } val log = VcsProjectLog.getInstance(project) val supportsIndexing = log.dataManager?.logProviders?.all { VcsLogProperties.SUPPORTS_INDEXING.getOrDefault(it.value) } ?: false val isGraphReady = log.dataManager?.dataPack?.isFull ?: false val allRootsIndexed = GitRepositoryManager.getInstance(project).repositories.all { log.dataManager?.index?.isIndexed(it.root) ?: false } e.presentation.isEnabled = supportsIndexing && isGraphReady && allRootsIndexed e.presentation.description = when { !supportsIndexing -> { message("action.Git.Show.My.Branches.description.not.support.indexing") } !allRootsIndexed -> { message("action.Git.Show.My.Branches.description.not.all.roots.indexed") } !isGraphReady -> { message("action.Git.Show.My.Branches.description.not.graph.ready") } else -> { message("action.Git.Show.My.Branches.description.is.my.branch") } } } } class FetchAction(private val ui: BranchesDashboardUi) : GitFetch() { override fun update(e: AnActionEvent) { super.update(e) with(e.presentation) { text = message("action.Git.Fetch.title") icon = AllIcons.Vcs.Fetch description = "" val project = e.project ?: return@with if (GitFetchSupport.fetchSupport(project).isFetchRunning) { isEnabled = false description = message("action.Git.Fetch.description.fetch.in.progress") } } } override fun actionPerformed(e: AnActionEvent) { ui.startLoadingBranches() super.actionPerformed(e) } override fun onFetchFinished(result: GitFetchResult) { ui.stopLoadingBranches() } } class ToggleFavoriteAction : BranchesActionBase(text = messagePointer("action.Git.Toggle.Favorite.title"), icon = AllIcons.Nodes.Favorite) { override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val branches = e.getData(GIT_BRANCHES)!! val gitBranchManager = project.service<GitBranchManager>() for (branch in branches) { val type = if (branch.isLocal) GitBranchType.LOCAL else GitBranchType.REMOTE val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = controller.getSelectedRepositories(branch) for (repository in repositories) { gitBranchManager.setFavorite(type, repository, branch.branchName, !branch.isFavorite) } } } } class ChangeBranchFilterAction : BooleanPropertyToggleAction() { override fun setSelected(e: AnActionEvent, state: Boolean) { super.setSelected(e, state) e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY] = false } override fun getProperty(): VcsLogUiProperties.VcsLogUiProperty<Boolean> = CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY } class NavigateLogToBranchAction : BooleanPropertyToggleAction() { override fun isSelected(e: AnActionEvent): Boolean { return super.isSelected(e) && !e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY] } override fun setSelected(e: AnActionEvent, state: Boolean) { super.setSelected(e, state) e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES)[CHANGE_LOG_FILTER_ON_BRANCH_SELECTION_PROPERTY] = false } override fun getProperty(): VcsLogUiProperties.VcsLogUiProperty<Boolean> = NAVIGATE_LOG_TO_BRANCH_ON_BRANCH_SELECTION_PROPERTY } class GroupingSettingsGroup: DefaultActionGroup(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isPopupGroup = GroupBranchByRepositoryAction.isEnabledAndVisible(e) } } class GroupBranchByDirectoryAction : GroupBranchAction(GroupingKey.GROUPING_BY_DIRECTORY) { override fun update(e: AnActionEvent) { super.update(e) val groupByDirectory: Supplier<String> = DvcsBundle.messagePointer("action.text.branch.group.by.directory") val groupingSeparator: () -> String = messagePointer("group.Git.Log.Branches.Grouping.Settings.text") e.presentation.text = if (GroupBranchByRepositoryAction.isEnabledAndVisible(e)) groupByDirectory.get() //NON-NLS else groupingSeparator() + " " + groupByDirectory.get() //NON-NLS } } class GroupBranchByRepositoryAction : GroupBranchAction(GroupingKey.GROUPING_BY_REPOSITORY) { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isEnabledAndVisible = isEnabledAndVisible(e) } companion object { fun isEnabledAndVisible(e: AnActionEvent): Boolean = e.project?.let(RepositoryChangesBrowserNode.Companion::getColorManager)?.hasMultiplePaths() ?: false } } abstract class GroupBranchAction(key: GroupingKey) : BranchGroupingAction(key) { override fun setSelected(e: AnActionEvent, key: GroupingKey, state: Boolean) { e.getData(BRANCHES_UI_CONTROLLER)?.toggleGrouping(key, state) } } class HideBranchesAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val properties = e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES) e.presentation.isEnabledAndVisible = properties != null && properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY) super.update(e) } override fun actionPerformed(e: AnActionEvent) { val properties = e.getData(VcsLogInternalDataKeys.LOG_UI_PROPERTIES) if (properties != null && properties.exists(SHOW_GIT_BRANCHES_LOG_PROPERTY)) { properties.set(SHOW_GIT_BRANCHES_LOG_PROPERTY, false) } } } class RemoveRemoteAction : RemoteActionBase() { override fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) { e.presentation.text = message("action.Git.Log.Remove.Remote.text", selectedRemotes.size) } override fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) { for ((repository, remotes) in selectedRemotes) { removeRemotes(service(), repository, remotes) } } } class EditRemoteAction : RemoteActionBase(messagePointer("action.Git.Log.Edit.Remote.text")) { override fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) { if (selectedRemotes.size != 1) { e.presentation.isEnabledAndVisible = false } } override fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) { val (repository, remotes) = selectedRemotes.entries.first() editRemote(service(), repository, remotes.first()) } } abstract class RemoteActionBase(@Nls(capitalization = Nls.Capitalization.Title) text: () -> String = { "" }, @Nls(capitalization = Nls.Capitalization.Sentence) private val description: () -> String = { "" }, icon: Icon? = null) : DumbAwareAction(text, description, icon) { open fun update(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) {} abstract fun doAction(e: AnActionEvent, project: Project, selectedRemotes: Map<GitRepository, Set<GitRemote>>) override fun update(e: AnActionEvent) { val project = e.project val controller = e.getData(BRANCHES_UI_CONTROLLER) val selectedRemotes = controller?.getSelectedRemotes() ?: emptyMap() val enabled = project != null && selectedRemotes.isNotEmpty() e.presentation.isEnabled = enabled e.presentation.description = description() if (enabled) { update(e, project!!, selectedRemotes) } } override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val selectedRemotes = controller.getSelectedRemotes() doAction(e, project, selectedRemotes) } } abstract class BranchesActionBase(@Nls(capitalization = Nls.Capitalization.Title) text: () -> String = { "" }, @Nls(capitalization = Nls.Capitalization.Sentence) private val description: () -> String = { "" }, icon: Icon? = null) : DumbAwareAction(text, description, icon) { open fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) {} override fun update(e: AnActionEvent) { val controller = e.getData(BRANCHES_UI_CONTROLLER) val branches = e.getData(GIT_BRANCHES) val project = e.project val enabled = project != null && controller != null && !branches.isNullOrEmpty() e.presentation.isEnabled = enabled e.presentation.description = description() if (enabled) { update(e, project!!, branches!!) } } } class CheckoutSelectedBranchAction : BranchesActionBase() { override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { if (branches.size > 1) { e.presentation.isEnabled = false return } } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val branch = e.getData(GIT_BRANCHES)!!.firstOrNull() ?: return val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = controller.getSelectedRepositories(branch) if (branch.isLocal) { GitBranchPopupActions.LocalBranchActions.CheckoutAction .checkoutBranch(project, repositories, branch.branchName) } else { GitBranchPopupActions.RemoteBranchActions.CheckoutRemoteBranchAction .checkoutRemoteBranch(project, repositories, branch.branchName) } } } class UpdateBranchFilterInLogAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val branchFilters = e.getData(GIT_BRANCH_FILTERS) val uiController = e.getData(BRANCHES_UI_CONTROLLER) val project = e.project val enabled = project != null && uiController != null && !branchFilters.isNullOrEmpty() && e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) is BranchesTreeComponent e.presentation.isEnabled = enabled } override fun actionPerformed(e: AnActionEvent) { e.getRequiredData(BRANCHES_UI_CONTROLLER).updateLogBranchFilter() } } class NavigateLogToSelectedBranchAction : DumbAwareAction() { override fun update(e: AnActionEvent) { val branchFilters = e.getData(GIT_BRANCH_FILTERS) val uiController = e.getData(BRANCHES_UI_CONTROLLER) val project = e.project val visible = project != null && uiController != null if (!visible) { e.presentation.isEnabledAndVisible = visible return } val enabled = branchFilters != null && branchFilters.size == 1 e.presentation.isEnabled = enabled } override fun actionPerformed(e: AnActionEvent) { e.getRequiredData(BRANCHES_UI_CONTROLLER).navigateLogToSelectedBranch() } } class RenameLocalBranch : BranchesActionBase() { override fun update(e: AnActionEvent, project: Project, branches: Collection<BranchInfo>) { if (branches.size > 1) { e.presentation.isEnabled = false return } val branch = branches.first() val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = controller.getSelectedRepositories(branch) if (!branch.isLocal || repositories.any(Repository::isFresh)) { e.presentation.isEnabled = false } } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val branch = e.getData(GIT_BRANCHES)!!.firstOrNull() ?: return val controller = e.getData(BRANCHES_UI_CONTROLLER)!! val repositories = controller.getSelectedRepositories(branch) GitBranchPopupActions.LocalBranchActions.RenameBranchAction.rename(project, repositories, branch.branchName) } } }
apache-2.0
ea435a63f36d22f791757ec394991b28
40.222714
142
0.697807
4.796465
false
false
false
false
dkrivoruchko/ScreenStream
app/src/main/kotlin/info/dvkr/screenstream/di/migration/SettingsDataMigration.kt
1
7121
package info.dvkr.screenstream.di.migration import android.content.Context import androidx.datastore.core.DataMigration import androidx.datastore.preferences.core.Preferences import com.elvishew.xlog.XLog import info.dvkr.screenstream.common.getLog import info.dvkr.screenstream.common.settings.AppSettings import info.dvkr.screenstream.mjpeg.settings.MjpegSettings import java.io.File class SettingsDataMigration( private val appContext: Context, private val binaryPreferences: com.ironz.binaryprefs.Preferences) : DataMigration<Preferences> { override suspend fun shouldMigrate(currentData: Preferences): Boolean { val shouldMigrate = binaryPreferences.keys().isNullOrEmpty().not() XLog.i(getLog("shouldMigrate", "shouldMigrate: $shouldMigrate")) XLog.i(getLog("shouldMigrate", "Saved settings: ${binaryPreferences.keys().joinToString()}")) return shouldMigrate } override suspend fun migrate(currentData: Preferences): Preferences { XLog.i(getLog("migrate")) val currentMutablePrefs = currentData.toMutablePreferences() currentMutablePrefs.clear() SettingsOldImpl(binaryPreferences).let { settingsOld -> if (settingsOld.nightMode != AppSettings.Default.NIGHT_MODE) currentMutablePrefs[AppSettings.Key.NIGHT_MODE] = settingsOld.nightMode if (settingsOld.keepAwake != AppSettings.Default.KEEP_AWAKE) currentMutablePrefs[AppSettings.Key.KEEP_AWAKE] = settingsOld.keepAwake if (settingsOld.stopOnSleep != AppSettings.Default.STOP_ON_SLEEP) currentMutablePrefs[AppSettings.Key.STOP_ON_SLEEP] = settingsOld.stopOnSleep if (settingsOld.startOnBoot != AppSettings.Default.START_ON_BOOT) currentMutablePrefs[AppSettings.Key.START_ON_BOOT] = settingsOld.startOnBoot if (settingsOld.autoStartStop != AppSettings.Default.AUTO_START_STOP) currentMutablePrefs[AppSettings.Key.AUTO_START_STOP] = settingsOld.startOnBoot if (settingsOld.notifySlowConnections != MjpegSettings.Default.NOTIFY_SLOW_CONNECTIONS) currentMutablePrefs[MjpegSettings.Key.NOTIFY_SLOW_CONNECTIONS] = settingsOld.notifySlowConnections if (settingsOld.htmlEnableButtons != MjpegSettings.Default.HTML_ENABLE_BUTTONS) currentMutablePrefs[MjpegSettings.Key.HTML_ENABLE_BUTTONS] = settingsOld.htmlEnableButtons if (settingsOld.htmlShowPressStart != MjpegSettings.Default.HTML_SHOW_PRESS_START) currentMutablePrefs[MjpegSettings.Key.HTML_SHOW_PRESS_START] = settingsOld.htmlShowPressStart if (settingsOld.htmlBackColor != MjpegSettings.Default.HTML_BACK_COLOR) currentMutablePrefs[MjpegSettings.Key.HTML_BACK_COLOR] = settingsOld.htmlBackColor if (settingsOld.vrMode != MjpegSettings.Default.VR_MODE_DISABLE) currentMutablePrefs[MjpegSettings.Key.VR_MODE] = settingsOld.vrMode if (settingsOld.imageCrop != MjpegSettings.Default.IMAGE_CROP) currentMutablePrefs[MjpegSettings.Key.IMAGE_CROP] = settingsOld.imageCrop if (settingsOld.imageCropTop != MjpegSettings.Default.IMAGE_CROP_TOP) currentMutablePrefs[MjpegSettings.Key.IMAGE_CROP_TOP] = settingsOld.imageCropTop if (settingsOld.imageCropBottom != MjpegSettings.Default.IMAGE_CROP_BOTTOM) currentMutablePrefs[MjpegSettings.Key.IMAGE_CROP_BOTTOM] = settingsOld.imageCropBottom if (settingsOld.imageCropLeft != MjpegSettings.Default.IMAGE_CROP_LEFT) currentMutablePrefs[MjpegSettings.Key.IMAGE_CROP_LEFT] = settingsOld.imageCropLeft if (settingsOld.imageCropRight != MjpegSettings.Default.IMAGE_CROP_RIGHT) currentMutablePrefs[MjpegSettings.Key.IMAGE_CROP_RIGHT] = settingsOld.imageCropRight if (settingsOld.imageGrayscale != MjpegSettings.Default.IMAGE_GRAYSCALE) currentMutablePrefs[MjpegSettings.Key.IMAGE_GRAYSCALE] = settingsOld.imageGrayscale if (settingsOld.jpegQuality != MjpegSettings.Default.JPEG_QUALITY) currentMutablePrefs[MjpegSettings.Key.JPEG_QUALITY] = settingsOld.jpegQuality if (settingsOld.resizeFactor != MjpegSettings.Default.RESIZE_FACTOR) currentMutablePrefs[MjpegSettings.Key.RESIZE_FACTOR] = settingsOld.resizeFactor if (settingsOld.rotation != MjpegSettings.Default.ROTATION) currentMutablePrefs[MjpegSettings.Key.ROTATION] = settingsOld.rotation if (settingsOld.maxFPS != MjpegSettings.Default.MAX_FPS) currentMutablePrefs[MjpegSettings.Key.MAX_FPS] = settingsOld.maxFPS if (settingsOld.enablePin != MjpegSettings.Default.ENABLE_PIN) currentMutablePrefs[MjpegSettings.Key.ENABLE_PIN] = settingsOld.enablePin if (settingsOld.hidePinOnStart != MjpegSettings.Default.HIDE_PIN_ON_START) currentMutablePrefs[MjpegSettings.Key.HIDE_PIN_ON_START] = settingsOld.hidePinOnStart if (settingsOld.newPinOnAppStart != MjpegSettings.Default.NEW_PIN_ON_APP_START) currentMutablePrefs[MjpegSettings.Key.NEW_PIN_ON_APP_START] = settingsOld.newPinOnAppStart if (settingsOld.autoChangePin != MjpegSettings.Default.AUTO_CHANGE_PIN) currentMutablePrefs[MjpegSettings.Key.AUTO_CHANGE_PIN] = settingsOld.autoChangePin if (settingsOld.pin != MjpegSettings.Default.PIN) currentMutablePrefs[MjpegSettings.Key.PIN] = settingsOld.pin if (settingsOld.blockAddress != MjpegSettings.Default.BLOCK_ADDRESS) currentMutablePrefs[MjpegSettings.Key.BLOCK_ADDRESS] = settingsOld.blockAddress if (settingsOld.useWiFiOnly != MjpegSettings.Default.USE_WIFI_ONLY) currentMutablePrefs[MjpegSettings.Key.USE_WIFI_ONLY] = settingsOld.useWiFiOnly if (settingsOld.enableIPv6 != MjpegSettings.Default.ENABLE_IPV6) currentMutablePrefs[MjpegSettings.Key.ENABLE_IPV6] = settingsOld.enableIPv6 if (settingsOld.enableLocalHost != MjpegSettings.Default.ENABLE_LOCAL_HOST) currentMutablePrefs[MjpegSettings.Key.ENABLE_LOCAL_HOST] = settingsOld.enableLocalHost if (settingsOld.localHostOnly != MjpegSettings.Default.LOCAL_HOST_ONLY) currentMutablePrefs[MjpegSettings.Key.LOCAL_HOST_ONLY] = settingsOld.localHostOnly if (settingsOld.severPort != MjpegSettings.Default.SERVER_PORT) currentMutablePrefs[MjpegSettings.Key.SERVER_PORT] = settingsOld.severPort if (settingsOld.loggingVisible != AppSettings.Default.LOGGING_VISIBLE) currentMutablePrefs[AppSettings.Key.LOGGING_VISIBLE] = settingsOld.loggingVisible } return currentMutablePrefs.toPreferences() } override suspend fun cleanUp() { XLog.i(getLog("cleanUp")) File(appContext.filesDir, "preferences").deleteRecursively() } }
mit
1cdb9a15b1918585b1f160d03fa7c779
50.985401
114
0.714366
4.442296
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/util/project-model-updater/src/org/jetbrains/tools/model/updater/kotlincLibraries.kt
2
8529
// 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.tools.model.updater import org.jetbrains.tools.model.updater.GeneratorPreferences.ArtifactMode import org.jetbrains.tools.model.updater.impl.* private const val ktGroup = "org.jetbrains.kotlin" private class ArtifactCoordinates(val version: String, val mode: ArtifactMode) private val GeneratorPreferences.kotlincArtifactCoordinates: ArtifactCoordinates get() = ArtifactCoordinates(kotlincVersion, kotlincArtifactsMode) private val GeneratorPreferences.jpsArtifactCoordinates: ArtifactCoordinates get() = ArtifactCoordinates(jpsPluginVersion, jpsPluginArtifactsMode) internal fun generateKotlincLibraries(preferences: GeneratorPreferences, isCommunity: Boolean): List<JpsLibrary> { val kotlincCoordinates = preferences.kotlincArtifactCoordinates val jpsPluginCoordinates = preferences.jpsArtifactCoordinates.takeIf { it.version != "dev" } ?: kotlincCoordinates return buildLibraryList(isCommunity) { kotlincForIdeWithStandardNaming("kotlinc.allopen-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.android-extensions-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api-fir-tests", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api-fir", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api-fe10", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api-impl-base", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.high-level-api-impl-base-tests", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.analysis-api-providers", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.analysis-project-structure", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.symbol-light-classes", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.incremental-compilation-impl-tests", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-build-common-tests", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-cli", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-tests", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-common", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-fe10", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-fir", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-compiler-ir", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-gradle-statistics", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-stdlib-minimal-for-test", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlinx-serialization-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.lombok-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.low-level-api-fir", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.noarg-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.parcelize-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.sam-with-receiver-compiler-plugin", kotlincCoordinates) kotlincForIdeWithStandardNaming("kotlinc.kotlin-jps-common", kotlincCoordinates) if (!isCommunity) { kotlincForIdeWithStandardNaming("kotlinc.kotlin-backend-native", kotlincCoordinates) } kotlincWithStandardNaming("kotlinc.kotlin-scripting-common", kotlincCoordinates) kotlincWithStandardNaming("kotlinc.kotlin-scripting-compiler-impl", kotlincCoordinates) kotlincWithStandardNaming("kotlinc.kotlin-scripting-jvm", kotlincCoordinates) kotlincWithStandardNaming("kotlinc.kotlin-script-runtime", kotlincCoordinates, transitive = true) kotlincForIdeWithStandardNaming("kotlinc.kotlin-jps-plugin-tests", jpsPluginCoordinates) kotlincWithStandardNaming("kotlinc.kotlin-dist", jpsPluginCoordinates, postfix = "-for-ide") kotlincWithStandardNaming("kotlinc.kotlin-jps-plugin-classpath", jpsPluginCoordinates) kotlincWithStandardNaming( "kotlinc.kotlin-reflect", kotlincCoordinates, transitive = true, excludes = listOf(MavenId(ktGroup, "kotlin-stdlib")) ) run { val mavenIds = listOf( MavenId.parse("$ktGroup:kotlin-stdlib-jdk8:${kotlincCoordinates.version}"), MavenId.parse("$ktGroup:kotlin-stdlib:${kotlincCoordinates.version}"), MavenId.parse("$ktGroup:kotlin-stdlib-common:${kotlincCoordinates.version}"), MavenId.parse("$ktGroup:kotlin-stdlib-jdk7:${kotlincCoordinates.version}") ) val annotationLibrary = JpsLibrary( "kotlinc.kotlin-stdlib", JpsLibrary.LibraryType.Repository(mavenIds.first(), excludes = listOf(MavenId("org.jetbrains", "annotations"))), annotations = listOf(JpsUrl.File(JpsPath.ProjectDir("lib/annotations/kotlin", isCommunity))), classes = mavenIds.map { JpsUrl.Jar(JpsPath.MavenRepository(it)) }, sources = mavenIds.map { JpsUrl.Jar(JpsPath.MavenRepository(it, "sources")) } ) addLibrary(annotationLibrary.convertMavenUrlToCooperativeIfNeeded(kotlincCoordinates.mode, isCommunity)) } } } private class LibraryListBuilder(val isCommunity: Boolean) { private val libraries = mutableListOf<JpsLibrary>() fun addLibrary(library: JpsLibrary) { libraries += library } fun build(): List<JpsLibrary> = libraries.toList() } private fun buildLibraryList(isCommunity: Boolean, builder: LibraryListBuilder.() -> Unit): List<JpsLibrary> = LibraryListBuilder(isCommunity).apply(builder).build() private fun LibraryListBuilder.kotlincForIdeWithStandardNaming( name: String, coordinates: ArtifactCoordinates, includeSources: Boolean = true ) { kotlincWithStandardNaming(name, coordinates, includeSources, "-for-ide") } private fun LibraryListBuilder.kotlincWithStandardNaming( name: String, coordinates: ArtifactCoordinates, includeSources: Boolean = true, postfix: String = "", transitive: Boolean = false, excludes: List<MavenId> = emptyList(), ) { require(name.startsWith("kotlinc.")) val jpsLibrary = singleJarMavenLibrary( name = name, mavenCoordinates = "$ktGroup:${name.removePrefix("kotlinc.")}$postfix:${coordinates.version}", transitive = transitive, includeSources = includeSources, excludes = excludes, ) addLibrary(jpsLibrary.convertMavenUrlToCooperativeIfNeeded(coordinates.mode, isCommunity)) } private fun singleJarMavenLibrary( name: String, mavenCoordinates: String, excludes: List<MavenId> = emptyList(), transitive: Boolean = true, includeSources: Boolean = true, ): JpsLibrary { val mavenId = MavenId.parse(mavenCoordinates) return JpsLibrary( name, JpsLibrary.LibraryType.Repository(mavenId, includeTransitive = transitive, excludes = excludes), classes = listOf(JpsUrl.Jar(JpsPath.MavenRepository(mavenId))), sources = listOf(JpsUrl.Jar(JpsPath.MavenRepository(mavenId, classifier = "sources"))).takeIf { includeSources } ?: emptyList() ) } private fun JpsLibrary.convertMavenUrlToCooperativeIfNeeded(artifactsMode: ArtifactMode, isCommunity: Boolean): JpsLibrary { fun convertUrl(url: JpsUrl): JpsUrl { require(url.path is JpsPath.MavenRepository) return JpsUrl.Jar(JpsPath.ProjectDir("../build/repo/${url.path}", isCommunity)) } return when (artifactsMode) { ArtifactMode.MAVEN -> this ArtifactMode.BOOTSTRAP -> JpsLibrary( name = name, type = JpsLibrary.LibraryType.Plain, annotations = annotations.map(::convertUrl), classes = classes.map(::convertUrl), javadoc = javadoc.map(::convertUrl), sources = sources.map(::convertUrl) ) } }
apache-2.0
e9ae679e419f83630be0b7b9a26cbd41
50.69697
135
0.738891
4.650491
false
false
false
false
Atsky/haskell-idea-plugin
plugin/src/org/jetbrains/cabal/tool/CabalToolWindowFactory.kt
1
7697
package org.jetbrains.cabal.tool import com.intellij.openapi.project.Project import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.ui.components.JBList import com.intellij.ui.content.Content import com.intellij.ui.content.ContentFactory import org.jetbrains.cabal.CabalInterface import javax.swing.* import java.awt.event.ActionEvent import java.util.ArrayList import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.vcs.changes.RunnableBackgroundableWrapper import com.intellij.ui.TreeUIHelper import com.intellij.ui.SearchTextField import com.intellij.ui.components.JBScrollPane import javax.swing.tree.TreeNode import javax.swing.tree.MutableTreeNode import javax.swing.tree.DefaultMutableTreeNode import org.jetbrains.cabal.CabalPackageShort import java.awt.BorderLayout import javax.swing.tree.DefaultTreeModel import com.intellij.ui.DocumentAdapter import javax.swing.event.DocumentEvent import com.intellij.ui.treeStructure.Tree import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.ide.CommonActionsManager import com.intellij.ide.actions.ContextHelpAction import com.intellij.openapi.actionSystem.ActionToolbar import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.util.IconUtil import com.intellij.openapi.actionSystem.AnActionEvent import org.jetbrains.haskell.icons.HaskellIcons import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import com.intellij.openapi.progress.ProgressIndicator import javax.swing.tree.TreeCellRenderer import java.awt.Component import org.jetbrains.cabal.tool.CabalToolWindowFactory.PackageData import java.awt.Color class CabalToolWindowFactory : ToolWindowFactory { private var toolWindow: ToolWindow? = null private var packages: JTree? = null private var project: Project? = null private var treeModel: DefaultTreeModel? = null class PackageData(val text : String, val installed : Boolean) override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { this.project = project this.toolWindow = toolWindow val contentFactory = ContentFactory.SERVICE.getInstance() val content = contentFactory!!.createContent(createToolWindowPanel(), "", false) toolWindow.contentManager!!.addContent(content) } private fun createToolWindowPanel(): JComponent { val panel = JPanel(BorderLayout()) panel.add(getToolbar(), BorderLayout.PAGE_START) val packagesList = CabalInterface(project!!).getPackagesList() val installedPackagesList = CabalInterface(project!!).getInstalledPackagesList() treeModel = DefaultTreeModel(getTree(packagesList, installedPackagesList, "")) val tree = Tree(treeModel) tree.cellRenderer = object : TreeCellRenderer { override fun getTreeCellRendererComponent(tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component { val userObject = (value as DefaultMutableTreeNode).userObject if (userObject == null) { return JLabel() } val packageData = userObject as PackageData val label = JLabel(packageData.text) if (packageData.installed) { label.foreground = Color(0, 140, 0) } return label } } tree.addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent) { if (SwingUtilities.isRightMouseButton(e)) { val path = tree.getPathForLocation(e.x, e.y) if (path == null) { return } val pathArray = path.path val packageName = pathArray[1] as DefaultMutableTreeNode val packageVersion: DefaultMutableTreeNode? = if (pathArray.size == 3) { (pathArray[2] as DefaultMutableTreeNode) } else { null } val menu = JPopupMenu() menu.add(JMenuItem(object: AbstractAction("Install") { override fun actionPerformed(e: ActionEvent) { install((packageName.userObject as PackageData).text, (packageVersion?.userObject as PackageData?)?.text) } })) menu.show(tree, e.x, e.y) } } }) tree.isRootVisible = false packages = tree panel.add(JBScrollPane(packages), BorderLayout.CENTER) return panel } fun getTree(packagesList: List<CabalPackageShort>, installedPackagesList: List<CabalPackageShort>, text: String): TreeNode { val root = DefaultMutableTreeNode() for (pkg in packagesList) { if (text != "" && !pkg.name.capitalize().contains(text.capitalize())) { continue } val installed = installedPackagesList.firstOrNull { it.name == pkg.name } val pkgNode = DefaultMutableTreeNode(PackageData(pkg.name, installed != null)) for (version in pkg.availableVersions) { val installedVersions = installed?.availableVersions ?: listOf() pkgNode.add(DefaultMutableTreeNode(PackageData(version, installedVersions.contains(version)))) } root.add(pkgNode) } return root } fun updateTree(text: String) { val packagesList = CabalInterface(project!!).getPackagesList() val installedPackagesList = CabalInterface(project!!).getInstalledPackagesList() treeModel!!.setRoot(getTree(packagesList, installedPackagesList, text)) } fun install(packageName: String, packageVersion: String?) { val cmd = if (packageVersion == null) { packageName } else { packageName + "-" + packageVersion } CabalInterface(project!!).install(cmd) } private fun getToolbar(): JComponent { val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.X_AXIS) val group = DefaultActionGroup() group.add(UpdateAction()) val actionToolBar = ActionManager.getInstance()!!.createActionToolbar("CabalTool", group, true)!! panel.add(actionToolBar.component!!) val searchTextField = SearchTextField() searchTextField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent?) { updateTree(searchTextField.text!!) } }) panel.add(searchTextField) return panel } inner class UpdateAction : AnAction("Update", "Update packages list", HaskellIcons.UPDATE) { override fun actionPerformed(e: AnActionEvent?) { CabalInterface(project!!).update() } } }
apache-2.0
50f7b782d3d456faa179c17e4357eae9
36.55122
110
0.628816
5.393833
false
false
false
false
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/ui/reservation/SwapReservationDialogFragment.kt
3
3749
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.reservation import android.app.Dialog import android.content.res.Resources import android.os.Bundle import androidx.appcompat.app.AppCompatDialogFragment import androidx.lifecycle.coroutineScope import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.shared.domain.users.SwapActionUseCase import com.google.samples.apps.iosched.shared.domain.users.SwapRequestParameters import com.google.samples.apps.iosched.util.makeBold import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import javax.inject.Inject /** * Dialog that confirms the user wants to replace their reservations */ @AndroidEntryPoint class SwapReservationDialogFragment : AppCompatDialogFragment() { companion object { const val DIALOG_SWAP_RESERVATION = "dialog_swap_reservation" private const val USER_ID_KEY = "user_id" private const val FROM_ID_KEY = "from_id" private const val FROM_TITLE_KEY = "from_title" private const val TO_ID_KEY = "to_id" private const val TO_TITLE_KEY = "to_title" fun newInstance(parameters: SwapRequestParameters): SwapReservationDialogFragment { val bundle = Bundle().apply { putString(USER_ID_KEY, parameters.userId) putString(FROM_ID_KEY, parameters.fromId) putString(FROM_TITLE_KEY, parameters.fromTitle) putString(TO_ID_KEY, parameters.toId) putString(TO_TITLE_KEY, parameters.toTitle) } return SwapReservationDialogFragment().apply { arguments = bundle } } } @Inject lateinit var swapActionUseCase: SwapActionUseCase override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val args = requireNotNull(arguments) val userId = requireNotNull(args.getString(USER_ID_KEY)) val fromId = requireNotNull(args.getString(FROM_ID_KEY)) val fromTitle = requireNotNull(args.getString(FROM_TITLE_KEY)) val toId = requireNotNull(args.getString(TO_ID_KEY)) val toTitle = requireNotNull(args.getString(TO_TITLE_KEY)) return MaterialAlertDialogBuilder(context) .setTitle(R.string.swap_reservation_title) .setMessage(formatSwapReservationMessage(context.resources, fromTitle, toTitle)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.swap) { _, _ -> viewLifecycleOwner.lifecycle.coroutineScope.launch { swapActionUseCase( SwapRequestParameters(userId, fromId, fromTitle, toId, toTitle) ) } } .create() } private fun formatSwapReservationMessage( res: Resources, fromTitle: String, toTitle: String ): CharSequence { val text = res.getString(R.string.swap_reservation_content, fromTitle, toTitle) return text.makeBold(fromTitle).makeBold(toTitle) } }
apache-2.0
c0abaab594f29675bce10c47c1b0e03c
39.311828
92
0.694585
4.527778
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/impl/TrustedProjects.kt
2
10810
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("TrustedProjects") @file:ApiStatus.Experimental package com.intellij.ide.impl import com.intellij.ide.IdeBundle import com.intellij.ide.lightEdit.LightEdit import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.EDT import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DoNotAskOption import com.intellij.openapi.ui.MessageDialogBuilder import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.io.FileUtil.getLocationRelativeToUserHome import com.intellij.util.ThreeState import com.intellij.util.messages.Topic import com.intellij.util.xmlb.annotations.Attribute import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.function.Consumer import kotlin.io.path.pathString /** * Shows the "Trust this project?" dialog, if the user wasn't asked yet if they trust this project, * and sets the project trusted state according to the user choice. * * @return false if the user chose not to open the project at all; * true otherwise, i.e. if the user chose to open the project either in trust or in the safe mode, * or if the confirmation wasn't shown because the project trust state was already known. */ @ApiStatus.Internal suspend fun confirmOpeningAndSetProjectTrustedStateIfNeeded(projectFileOrDir: Path): Boolean { val projectDir = if (Files.isDirectory(projectFileOrDir)) projectFileOrDir else projectFileOrDir.parent val trustedPaths = TrustedPaths.getInstance() val trustedState = trustedPaths.getProjectPathTrustedState(projectDir) if (trustedState == ThreeState.UNSURE) { when (confirmOpeningUntrustedProject(projectDir)) { OpenUntrustedProjectChoice.TRUST_AND_OPEN -> trustedPaths.setProjectPathTrusted(projectDir, true) OpenUntrustedProjectChoice.OPEN_IN_SAFE_MODE -> trustedPaths.setProjectPathTrusted(projectDir, false) OpenUntrustedProjectChoice.CANCEL -> return false } } return true } private suspend fun confirmOpeningUntrustedProject(projectDir: Path): OpenUntrustedProjectChoice { val fileName = projectDir.fileName ?: projectDir.pathString return confirmOpeningUntrustedProject( projectDir, IdeBundle.message("untrusted.project.open.dialog.title", fileName), IdeBundle.message("untrusted.project.open.dialog.text", ApplicationNamesInfo.getInstance().fullProductName), IdeBundle.message("untrusted.project.dialog.trust.button"), IdeBundle.message("untrusted.project.open.dialog.distrust.button"), IdeBundle.message("untrusted.project.open.dialog.cancel.button") ) } private suspend fun confirmOpeningUntrustedProject( projectDir: Path, @NlsContexts.DialogTitle title: String, @NlsContexts.DialogMessage message: String, @NlsContexts.Button trustButtonText: String, @NlsContexts.Button distrustButtonText: String, @NlsContexts.Button cancelButtonText: String ): OpenUntrustedProjectChoice { if (isProjectImplicitlyTrusted(projectDir)) { return OpenUntrustedProjectChoice.TRUST_AND_OPEN } val doNotAskOption = projectDir.parent?.let(::createDoNotAskOptionForLocation) val choice = withContext(Dispatchers.EDT) { MessageDialogBuilder.Message(title, message) .buttons(trustButtonText, distrustButtonText, cancelButtonText) .defaultButton(trustButtonText) .focusedButton(distrustButtonText) .doNotAsk(doNotAskOption) .asWarning() .help(TRUSTED_PROJECTS_HELP_TOPIC) .show() } val openChoice = when (choice) { trustButtonText -> OpenUntrustedProjectChoice.TRUST_AND_OPEN distrustButtonText -> OpenUntrustedProjectChoice.OPEN_IN_SAFE_MODE cancelButtonText, null -> OpenUntrustedProjectChoice.CANCEL else -> { LOG.error("Illegal choice $choice") return OpenUntrustedProjectChoice.CANCEL } } TrustedProjectsStatistics.NEW_PROJECT_OPEN_OR_IMPORT_CHOICE.log(openChoice) return openChoice } fun confirmLoadingUntrustedProject( project: Project, @NlsContexts.DialogTitle title: String, @NlsContexts.DialogMessage message: String, @NlsContexts.Button trustButtonText: String, @NlsContexts.Button distrustButtonText: String ): Boolean = invokeAndWaitIfNeeded { if (isProjectImplicitlyTrusted(project)) { project.setTrusted(true) return@invokeAndWaitIfNeeded true } val answer = MessageDialogBuilder.yesNo(title, message) .yesText(trustButtonText) .noText(distrustButtonText) .asWarning() .help(TRUSTED_PROJECTS_HELP_TOPIC) .ask(project) project.setTrusted(answer) TrustedProjectsStatistics.LOAD_UNTRUSTED_PROJECT_CONFIRMATION_CHOICE.log(project, answer) return@invokeAndWaitIfNeeded answer } @ApiStatus.Internal enum class OpenUntrustedProjectChoice { TRUST_AND_OPEN, OPEN_IN_SAFE_MODE, CANCEL; } fun Project.isTrusted() = getTrustedState () == ThreeState.YES @ApiStatus.Internal fun Project.getTrustedState(): ThreeState { val projectPath = basePath if (projectPath != null) { val explicit = TrustedPaths.getInstance().getProjectPathTrustedState(Paths.get(projectPath)) if (explicit != ThreeState.UNSURE) { return explicit } } if (isProjectImplicitlyTrusted(this)) { return ThreeState.YES } @Suppress("DEPRECATION") return this.service<TrustedProjectSettings>().trustedState } fun Project.setTrusted(value: Boolean) { val projectPath = basePath if (projectPath != null) { val path = Paths.get(projectPath) val trustedPaths = TrustedPaths.getInstance() val oldValue = trustedPaths.getProjectPathTrustedState(path) trustedPaths.setProjectPathTrusted(path, value) if (value && oldValue != ThreeState.YES) { ApplicationManager.getApplication().messageBus.syncPublisher(TrustStateListener.TOPIC).onProjectTrusted(this) } } } private fun createDoNotAskOptionForLocation(projectLocation: Path): DoNotAskOption { val projectLocationPath = projectLocation.toString() return object : DoNotAskOption.Adapter() { override fun rememberChoice(isSelected: Boolean, exitCode: Int) { if (isSelected && exitCode == Messages.YES) { TrustedProjectsStatistics.TRUST_LOCATION_CHECKBOX_SELECTED.log() service<TrustedPathsSettings>().addTrustedPath(projectLocationPath) } } override fun getDoNotShowMessage(): String { val path = getLocationRelativeToUserHome(projectLocationPath, false) return IdeBundle.message("untrusted.project.warning.trust.location.checkbox", path) } } } @ApiStatus.Internal fun isTrustedCheckDisabled() = ApplicationManager.getApplication().isUnitTestMode || ApplicationManager.getApplication().isHeadlessEnvironment || ApplicationManagerEx.isInIntegrationTest() || java.lang.Boolean.getBoolean("idea.trust.all.projects") private fun isTrustedCheckDisabledForProduct(): Boolean = java.lang.Boolean.getBoolean("idea.trust.disabled") private fun isProjectImplicitlyTrusted(project: Project): Boolean { return isProjectImplicitlyTrusted(project.basePath?.let { Path.of(it) }, project) } @JvmOverloads @ApiStatus.Internal fun isProjectImplicitlyTrusted(projectDir: Path?, project: Project? = null): Boolean { if (isTrustedCheckDisabled() || isTrustedCheckDisabledForProduct()) { return true } if (LightEdit.owns(project)) { return true } if (projectDir != null && isPathTrustedInSettings(projectDir)) { TrustedProjectsStatistics.PROJECT_IMPLICITLY_TRUSTED_BY_PATH.log(project) return true } return false } /** * Per-project "is this project trusted" setting from the previous version of the trusted API. * It shouldn't be used and is kept for migration purposes only. */ @State(name = "Trusted.Project.Settings", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)]) @Service(Service.Level.PROJECT) @ApiStatus.Internal @Deprecated("Use TrustedPaths instead") internal class TrustedProjectSettings : SimplePersistentStateComponent<TrustedProjectSettings.State>(State()) { class State : BaseState() { @get:Attribute var isTrusted by enum(ThreeState.UNSURE) } var trustedState: ThreeState get() = state.isTrusted set(value) { state.isTrusted = value } } /** * Listens to the change of the project trusted state, i.e. when a non-trusted project becomes trusted (the vice versa is not possible). * * Consider using the helper method [whenProjectTrusted] which accepts a lambda. */ @ApiStatus.Experimental interface TrustStateListener { /** * Executed when the project becomes trusted. */ fun onProjectTrusted(project: Project) { } /** * Executed when the user clicks to the "Trust Project" button in the [editor notification][UntrustedProjectEditorNotificationPanel]. * Use this method if you need to know that the project has become trusted exactly because the user has clicked to that button. * * NB: [onProjectTrusted] is also called in this case, and most probably you want to use that method. */ fun onProjectTrustedFromNotification(project: Project) { } companion object { @JvmField @Topic.AppLevel val TOPIC = Topic(TrustStateListener::class.java, Topic.BroadcastDirection.NONE) } } /** * Adds a one-time listener of the project's trust state change: when the project becomes trusted, the listener is called and disconnected. */ @JvmOverloads fun whenProjectTrusted(parentDisposable: Disposable? = null, listener: (Project) -> Unit) { val messageBus = ApplicationManager.getApplication().messageBus val connection = if (parentDisposable == null) messageBus.connect() else messageBus.connect(parentDisposable) connection.subscribe(TrustStateListener.TOPIC, object : TrustStateListener { override fun onProjectTrusted(project: Project) { listener(project) connection.disconnect() } }) } @JvmOverloads fun whenProjectTrusted(parentDisposable: Disposable? = null, listener: Consumer<Project>) { whenProjectTrusted(parentDisposable) { project -> listener.accept(project) } } const val TRUSTED_PROJECTS_HELP_TOPIC = "Project_security" private val LOG = Logger.getInstance("com.intellij.ide.impl.TrustedProjects")
apache-2.0
d2abd2ede4895135bbd584db35878019
36.275862
139
0.766235
4.509804
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/navigator/ObjectNavigator.kt
2
4534
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.navigator import com.intellij.diagnostic.hprof.classstore.ClassDefinition import com.intellij.diagnostic.hprof.classstore.ClassStore import com.intellij.diagnostic.hprof.classstore.HProfMetadata import com.intellij.diagnostic.hprof.parser.HProfEventBasedParser import com.intellij.diagnostic.hprof.visitors.CreateAuxiliaryFilesVisitor import it.unimi.dsi.fastutil.longs.LongList import org.jetbrains.annotations.NonNls import java.nio.channels.FileChannel abstract class ObjectNavigator(val classStore: ClassStore, val instanceCount: Long) { enum class ReferenceResolution { ALL_REFERENCES, ONLY_STRONG_REFERENCES, NO_REFERENCES } data class RootObject(val id: Long, val reason: RootReason) class NavigationException(message: String) : RuntimeException(message) abstract val id: Long abstract fun createRootsIterator(): Iterator<RootObject> abstract fun goTo(id: Long, referenceResolution: ReferenceResolution = ReferenceResolution.ONLY_STRONG_REFERENCES) abstract fun getClass(): ClassDefinition abstract fun getReferencesCopy(): LongList abstract fun copyReferencesTo(outReferences: LongList) abstract fun getClassForObjectId(id: Long): ClassDefinition abstract fun getRootReasonForObjectId(id: Long): RootReason? abstract fun getObjectSize(): Int abstract fun getSoftReferenceId(): Long abstract fun getWeakReferenceId(): Long abstract fun getSoftWeakReferenceIndex(): Int fun goToInstanceField(@NonNls className: String?, @NonNls fieldName: String) { val objectId = getInstanceFieldObjectId(className, fieldName) goTo(objectId, ReferenceResolution.ALL_REFERENCES) } fun getInstanceFieldObjectId(@NonNls className: String?, @NonNls name: String): Long { val refs = getReferencesCopy() if (className != null && className != getClass().undecoratedName) { throw NavigationException("Expected $className, got ${getClass().undecoratedName}") } val indexOfField = getClass().allRefFieldNames(classStore).indexOfFirst { it == name } if (indexOfField == -1) { throw NavigationException("Missing field $name in ${getClass().name}") } return refs.getLong(indexOfField) } fun goToStaticField(@NonNls className: String, @NonNls fieldName: String) { val objectId = getStaticFieldObjectId(className, fieldName) goTo(objectId, ReferenceResolution.ALL_REFERENCES) } private fun getStaticFieldObjectId(className: String, fieldName: String): Long { val staticField = classStore[className].objectStaticFields.firstOrNull { it.name == fieldName } ?: throw NavigationException("Missing static field $fieldName in class $className") return staticField.value } companion object { fun createOnAuxiliaryFiles(parser: HProfEventBasedParser, auxOffsetsChannel: FileChannel, auxChannel: FileChannel, hprofMetadata: HProfMetadata, instanceCount: Long): ObjectNavigator { val createAuxiliaryFilesVisitor = CreateAuxiliaryFilesVisitor(auxOffsetsChannel, auxChannel, hprofMetadata.classStore, parser) parser.accept(createAuxiliaryFilesVisitor, "auxFiles") val auxBuffer = auxChannel.map(FileChannel.MapMode.READ_ONLY, 0, auxChannel.size()) val auxOffsetsBuffer = auxOffsetsChannel.map(FileChannel.MapMode.READ_ONLY, 0, auxOffsetsChannel.size()) return ObjectNavigatorOnAuxFiles(hprofMetadata.roots, auxOffsetsBuffer, auxBuffer, hprofMetadata.classStore, instanceCount, parser.idSize) } } abstract fun isNull(): Boolean // Some objects may have additional data (varies by type). Only available when referenceResolution != NO_REFERENCES. abstract fun getExtraData(): Int abstract fun getStringInstanceFieldValue(): String? }
apache-2.0
05e77bfc4c1c064e14f0b33129927dfd
38.77193
132
0.743494
4.688728
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceSizeCheckIntention.kt
3
2436
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory abstract class ReplaceSizeCheckIntention(textGetter: () -> String) : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, textGetter ) { override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val target = getTargetExpression(element) ?: return val replacement = getReplacement(target) element.replaced(replacement.newExpression()) } override fun isApplicableTo(element: KtBinaryExpression): Boolean { val targetExpression = getTargetExpression(element) ?: return false val isSizeOrLength = targetExpression.isSizeOrLength() val isCountCall = targetExpression.isTargetCountCall() if (!isSizeOrLength && !isCountCall) return false val replacement = getReplacement(targetExpression, isCountCall) replacement.intentionTextGetter?.let { setTextGetter(it) } return true } protected abstract fun getTargetExpression(element: KtBinaryExpression): KtExpression? protected abstract fun getReplacement(expression: KtExpression, isCountCall: Boolean = expression.isTargetCountCall()): Replacement protected class Replacement( private val targetExpression: KtExpression, private val newFunctionCall: String, private val negate: Boolean = false, val intentionTextGetter: (() -> String)? = null ) { fun newExpression(): KtExpression { val excl = if (negate) "!" else "" val receiver = if (targetExpression is KtDotQualifiedExpression) "${targetExpression.receiverExpression.text}." else "" return KtPsiFactory(targetExpression).createExpression("$excl$receiver$newFunctionCall") } } private fun KtExpression.isTargetCountCall() = isCountCall { it.valueArguments.isEmpty() } }
apache-2.0
baf458990abddf12813dde54141a8ff6
44.981132
158
0.748768
5.318777
false
false
false
false
alt236/Bluetooth-LE-Library---Android
sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/binder/RssiBinder.kt
1
1566
package uk.co.alt236.btlescan.ui.details.recyclerview.binder import android.content.Context import uk.co.alt236.btlescan.R import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewBinder import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder import uk.co.alt236.btlescan.ui.common.recyclerview.RecyclerViewItem import uk.co.alt236.btlescan.ui.details.recyclerview.holder.RssiInfoHolder import uk.co.alt236.btlescan.ui.details.recyclerview.model.RssiItem import uk.co.alt236.btlescan.util.TimeFormatter class RssiBinder(context: Context) : BaseViewBinder<RssiItem>(context) { override fun bind(holder: BaseViewHolder<RssiItem>, item: RssiItem) { val actualHolder = holder as RssiInfoHolder actualHolder.firstTimestamp.text = formatTime(item.firstTimestamp) actualHolder.firstRssi.text = formatRssi(item.firstRssi) actualHolder.lastTimestamp.text = formatTime(item.timestamp) actualHolder.lastRssi.text = formatRssi(item.rssi) actualHolder.runningAverageRssi.text = formatRssi(item.runningAverageRssi) } override fun canBind(item: RecyclerViewItem): Boolean { return item is RssiItem } private fun formatRssi(rssi: Double): String { return getString(R.string.formatter_db, rssi.toString()) } private fun formatRssi(rssi: Int): String { return getString(R.string.formatter_db, rssi.toString()) } companion object { private fun formatTime(time: Long): String { return TimeFormatter.getIsoDateTime(time) } } }
apache-2.0
57674c4c2dfc817bf99ba564f79059eb
38.175
82
0.747126
3.782609
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/highlighter/ScriptExternalHighlightingPass.kt
1
5525
// 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.highlighter import com.intellij.codeHighlighting.* import com.intellij.codeInsight.daemon.impl.HighlightInfo import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil import com.intellij.lang.annotation.Annotation import com.intellij.lang.annotation.HighlightSeverity import com.intellij.lang.annotation.HighlightSeverity.* import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.psi.PsiFile import com.intellij.util.ui.UIUtil import org.jetbrains.kotlin.idea.core.script.IdeScriptReportSink import org.jetbrains.kotlin.idea.script.ScriptDiagnosticFixProvider import org.jetbrains.kotlin.psi.KtFile import kotlin.script.experimental.api.ScriptDiagnostic import kotlin.script.experimental.api.SourceCode class ScriptExternalHighlightingPass( private val file: KtFile, document: Document ) : TextEditorHighlightingPass(file.project, document), DumbAware { override fun doCollectInformation(progress: ProgressIndicator) = Unit override fun doApplyInformationToEditor() { val document = document ?: return if (!file.isScript()) return val reports = IdeScriptReportSink.getReports(file) val annotations = reports.mapNotNull { scriptDiagnostic -> val (startOffset, endOffset) = scriptDiagnostic.location?.let { computeOffsets(document, it) } ?: (0 to 0) val exception = scriptDiagnostic.exception val exceptionMessage = if (exception != null) " ($exception)" else "" val message = scriptDiagnostic.message + exceptionMessage val annotation = Annotation( startOffset, endOffset, scriptDiagnostic.severity.convertSeverity() ?: return@mapNotNull null, message, message ) // if range is empty, show notification panel in editor annotation.isFileLevelAnnotation = startOffset == endOffset for (provider in ScriptDiagnosticFixProvider.EP_NAME.extensions) { provider.provideFixes(scriptDiagnostic).forEach { annotation.registerFix(it) } } annotation } val infos = annotations.map { HighlightInfo.fromAnnotation(it) } UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument!!, 0, file.textLength, infos, colorsScheme, id) } private fun computeOffsets(document: Document, position: SourceCode.Location): Pair<Int, Int> { val startLine = position.start.line.coerceLineIn(document) val startOffset = document.offsetBy(startLine, position.start.col) val endLine = position.end?.line?.coerceAtLeast(startLine)?.coerceLineIn(document) ?: startLine val endOffset = document.offsetBy( endLine, position.end?.col ?: document.getLineEndOffset(endLine) ).coerceAtLeast(startOffset) return startOffset to endOffset } private fun Int.coerceLineIn(document: Document) = coerceIn(0, document.lineCount - 1) private fun Document.offsetBy(line: Int, col: Int): Int { return (getLineStartOffset(line) + col).coerceIn(getLineStartOffset(line), getLineEndOffset(line)) } private fun ScriptDiagnostic.Severity.convertSeverity(): HighlightSeverity? { return when (this) { ScriptDiagnostic.Severity.FATAL -> ERROR ScriptDiagnostic.Severity.ERROR -> ERROR ScriptDiagnostic.Severity.WARNING -> WARNING ScriptDiagnostic.Severity.INFO -> INFORMATION ScriptDiagnostic.Severity.DEBUG -> if (ApplicationManager.getApplication().isInternal) INFORMATION else null } } private fun showNotification(file: KtFile, message: String) { UIUtil.invokeLaterIfNeeded { val ideFrame = WindowManager.getInstance().getIdeFrame(file.project) if (ideFrame != null) { val statusBar = ideFrame.statusBar as StatusBarEx statusBar.notifyProgressByBalloon( MessageType.WARNING, message, null, null ) } } } class Registrar : TextEditorHighlightingPassFactoryRegistrar { override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) { registrar.registerTextEditorHighlightingPass( Factory(), TextEditorHighlightingPassRegistrar.Anchor.BEFORE, Pass.UPDATE_FOLDING, false, false ) } } class Factory : TextEditorHighlightingPassFactory { override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { if (file !is KtFile) return null return ScriptExternalHighlightingPass(file, editor.document) } } }
apache-2.0
dc9f575939120567474eefff9a7777dc
40.856061
158
0.688507
5.236967
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ReplaceInfixOrOperatorCallFixFactory.kt
4
4021
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.inspections.collections.isMap import org.jetbrains.kotlin.idea.intentions.canBeReplacedWithInvokeCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtArrayAccessExpression import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.expressions.OperatorConventions import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.utils.addToStdlib.safeAs object ReplaceInfixOrOperatorCallFixFactory : KotlinSingleIntentionActionFactory() { private fun findArrayAccessExpression(expression: PsiElement): KtArrayAccessExpression? { return expression.safeAs<KtArrayAccessExpression>() ?: expression.parent?.safeAs<KtArrayAccessExpression>() } override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement val arrayAccessExpression = findArrayAccessExpression(expression) if (arrayAccessExpression != null && diagnostic.factory != Errors.UNSAFE_IMPLICIT_INVOKE_CALL) { if (arrayAccessExpression.arrayExpression == null) return null return ReplaceInfixOrOperatorCallFix(arrayAccessExpression, arrayAccessExpression.shouldHaveNotNullType()) } when (val parent = expression.parent) { is KtBinaryExpression -> { val left = parent.left when { left == null || parent.right == null -> return null parent.operationToken == KtTokens.EQ -> return null parent.operationToken in OperatorConventions.COMPARISON_OPERATIONS -> return null else -> { if (parent.operationToken in KtTokens.AUGMENTED_ASSIGNMENTS && left is KtArrayAccessExpression) { val type = left.arrayExpression?.getType(left.analyze()) ?: return null if (type.isMap(type.builtIns) && type.arguments.lastOrNull()?.type?.isNullable() != true) return null } val binaryOperatorName = if (parent.operationToken == KtTokens.IDENTIFIER) { // Get name of infix function call parent.operationReference.text } else { parent.resolveToCall(BodyResolveMode.FULL)?.candidateDescriptor?.name?.asString() } return binaryOperatorName?.let { ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType(), binaryOperatorName) } } } } is KtCallExpression -> { if (parent.calleeExpression == null || parent.valueArgumentList == null) return null val resolvedCall = parent.resolveToCall(BodyResolveMode.FULL) ?: return null if (!resolvedCall.canBeReplacedWithInvokeCall() || resolvedCall.getImplicitReceiverValue() != null) return null return ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType()) } else -> return null } } }
apache-2.0
a85504767fc9bf2e1903cc765bb6c020
55.633803
158
0.67993
5.631653
false
false
false
false
sureshg/kotlin-starter
buildSrc/src/main/kotlin/Commons.kt
1
10404
import sun.misc.HexDumpEncoder import java.io.File import java.io.IOException import java.net.JarURLConnection import java.net.URL import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.Path import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.security.MessageDigest import java.util.* import java.util.jar.Attributes import java.util.jar.Attributes.Name.* import java.util.jar.Manifest import javax.crypto.Cipher import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec import kotlin.reflect.KClass import kotlin.text.Charsets.US_ASCII import kotlin.text.Charsets.UTF_8 /** * Common extension functions. * * @author Suresh G (@sur3shg) */ const val SPACE = " " val LINE_SEP = System.lineSeparator() val FILE_SEP = File.separator /** * Prints the [Any.toString] to console. */ inline val Any?.p get() = println(this) /** * Pseudo Random number generator. */ val RAND = Random(System.nanoTime()) /** * Prepend an empty string of size [col] to the string. * * Doesn't preserve original line endings. */ fun String.indent(col: Int) = prependIndent(SPACE.repeat(col)) /** * Prepend an empty string of size [col] to each string in the list by skipping first [skip] strings. * * @param skip number of head elements to skip from indentation. * Default to 0 if it's out of bound of list size [0..size] */ fun List<String>.indent(col: Int, skip: Int = 0): List<String> { val skipCount = if (skip in 0..size) skip else 0 return mapIndexed { idx, str -> if (idx < skipCount) str else str.indent(col) } } /** * Convert [Byte] to hex. '0x100' OR is used to preserve the leading zero in case of single hex digit. */ val Byte.hex get() = Integer.toHexString(toInt() and 0xFF or 0x100).substring(1, 3).toUpperCase() /** * Convert [Byte] to octal. '0x200' OR is used to preserve the leading zero in case of two digit octal. */ val Byte.oct get() = Integer.toOctalString(toInt() and 0xFF or 0x200).substring(1, 4) /** * Convert [ByteArray] to hex. */ val ByteArray.hex get() = map(Byte::hex).joinToString(" ") /** * Convert [ByteArray] into the classic: "Hexadecimal Dump". */ val ByteArray.hexDump get() = HexDumpEncoder().encode(this) /** * Convert [ByteArray] to octal */ val ByteArray.oct get() = map(Byte::oct).joinToString(" ") /** * Hex and Octal util methods for Int and Byte */ val Int.hex get() = Integer.toHexString(this).toUpperCase() val Int.oct get() = Integer.toOctalString(this) val Byte.hi get() = toInt() and 0xF0 shr 4 val Byte.lo get() = toInt() and 0x0F /** * Convert string to hex. */ val String.hex: String get() = toByteArray(UTF_8).hex /** * Convert String to octal */ val String.oct: String get() = toByteArray(UTF_8).oct /** * IPV4 regex pattern */ val ip_regex = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$".toRegex() val String.isIPv4 get() = matches(ip_regex) /** * Create an MD5 hash of a string. */ val String.md5 get() = hash(toByteArray(UTF_8), "MD5") /** * Create an SHA1 hash of a string. */ val String.sha1 get() = hash(toByteArray(UTF_8), "SHA-1") /** * Create an SHA256 hash of a string. */ val String.sha256 get() = hash(toByteArray(UTF_8), "SHA-256") /** * Encodes the string into Base64 encoded one. */ inline val String.base64 get() = Base64.getEncoder().encodeToString(toByteArray(US_ASCII)) /** * Decodes the base64 string. */ inline val String.base64Decode get() = base64DecodeBytes.toString(US_ASCII) /** * Decodes the base64 string to byte array. It removes all extra spaces in the * input string before doing the base64 decode operation. */ inline val String.base64DecodeBytes: ByteArray get() { val str = replace("\\s+".toRegex(), "") return Base64.getDecoder().decode(str) } /** * Create an MD5 hash of [ByteArray]. */ val ByteArray.md5 get() = hash(this, "MD5") /** * Create an SHA1 hash of [ByteArray]. */ val ByteArray.sha1 get() = hash(this, "SHA-1") /** * Create an SHA256 hash of [ByteArray]. */ val ByteArray.sha256 get() = hash(this, "SHA-256") /** * Encodes all bytes from the byte array into a newly-allocated byte array using the Base64 encoding scheme. */ inline val ByteArray.base64: ByteArray get() = Base64.getEncoder().encode(this) /** * Decodes base64 byte array. */ inline val ByteArray.base64Decode: ByteArray get() = Base64.getDecoder().decode(this) /** * Returns human readable binary prefix for multiples of bytes. * * @param si [true] if it's SI unit, else it will be treated as Binary Unit. */ fun Long.toBinaryPrefixString(si: Boolean = false): String { // SI and Binary Units val unit = if (si) 1_000 else 1_024 return when { this < unit -> "$this B" else -> { val (prefix, suffix) = when (si) { true -> "kMGTPEZY" to "B" false -> "KMGTPEZY" to "iB" } // Get only the integral part of the decimal val exp = (Math.log(this.toDouble()) / Math.log(unit.toDouble())).toInt() // Binary Prefix mnemonic that is prepended to the units. val binPrefix = "${prefix[exp - 1]}$suffix" // Count => (unit^0.x * unit^exp)/unit^exp String.format("%.2f %s", this / Math.pow(unit.toDouble(), exp.toDouble()), binPrefix) } } } /** * Returns human readable binary prefix for multiples of bytes. * * @param si [true] if it's SI unit, else it will be treated as Binary Unit. */ fun Int.toBinaryPrefixString(si: Boolean = false) = toLong().toBinaryPrefixString(si) /** * Get the root cause by walks through the exception chain to the last element, * "root" of the tree, using [Throwable.getCause], and returns that exception. */ val Throwable?.rootCause: Throwable? get() { var cause = this while (cause?.cause != null) { cause = cause.cause } return cause } /** * Find the [msg] hash using the given hashing [algo] */ private fun hash(msg: ByteArray, algo: String): String { val md = MessageDigest.getInstance(algo) md.reset() md.update(msg) val msgDigest = md.digest() return msgDigest.hex } /** * Encrypt this string with HMAC-SHA1 using the specified [key]. * * @param key Encryption key * @return Encrypted output */ fun String.hmacSHA1(key: String): ByteArray { val mac = Mac.getInstance("HmacSHA1") mac.init(SecretKeySpec(key.toByteArray(UTF_8), "HmacSHA1")) return mac.doFinal(toByteArray(UTF_8)) } /** * Pad this String to a desired multiple on the right using a specified character. * * @param padding Padding character. * @param multipleOf Number which the length must be a multiple of. */ fun String.rightPadString(padding: Char, multipleOf: Int): String { if (isEmpty()) throw IllegalArgumentException("Must supply non-empty string") if (multipleOf < 2) throw IllegalArgumentException("Multiple ($multipleOf) must be greater than one.") val needed = multipleOf - (length % multipleOf) return padEnd(length + needed, padding) } /** * Normalize a string to a desired length by repeatedly appending itself and/or truncating. * * @param desiredLength Desired length of string. */ fun String.normalizeString(desiredLength: Int): String { if (isEmpty()) throw IllegalArgumentException("Must supply non-empty string") if (desiredLength < 0) throw IllegalArgumentException("Desired length ($desiredLength) must be greater than zero.") var buf = this if (length < desiredLength) { buf = repeat(desiredLength / length + 1) } return buf.substring(0, desiredLength) } /** * Encrypt this string with AES-128 using the specified [key]. * Ported from - https://goo.gl/J1H3e5 * * @param key Encryption key. * @return Encrypted output. */ fun String.aes128Encrypt(key: String): ByteArray { val nkey = key.normalizeString(16) val msg = rightPadString('{', 16) val cipher = Cipher.getInstance("AES/ECB/NoPadding") cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(nkey.toByteArray(UTF_8), "AES")) return cipher.doFinal(msg.toByteArray(UTF_8)) } /** * Deletes the files or directory (recursively) represented by this path. */ fun Path.delete() { if (Files.notExists(this)) { return } if (Files.isDirectory(this)) { Files.walkFileTree(this, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes) = let { Files.delete(file) FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, exc: IOException) = let { Files.delete(dir) FileVisitResult.CONTINUE } }) } else { Files.delete(this) } } /** * Exits the system with [msg] */ fun exit(status: Int, msg: (() -> String)? = null) { if (msg != null) { println(msg()) } System.exit(status) } /** * Returns the jar [Manifest] of the class. Returns [null] if the class * is not bundled in a jar (Classes in an unpacked class hierarchy). */ inline val <T : Any> KClass<T>.jarManifest: Manifest? get() { val res = java.getResource("${java.simpleName}.class") val conn = res.openConnection() return if (conn is JarURLConnection) conn.manifest else null } /** * Returns the jar url of the class. Returns the class file url * if the class is not bundled in a jar. */ inline val <T : Any> KClass<T>.jarFileURL: URL get() { val res = java.getResource("${java.simpleName}.class") val conn = res.openConnection() return if (conn is JarURLConnection) conn.jarFileURL else conn.url } /** * Common build info attributes */ enum class BuildInfo(val attr: String) { Author("Built-By"), Date("Built-Date"), JDK("Build-Jdk"), BuildTarget("Build-Target"), OS("Build-OS"), KotlinVersion("Kotlin-Version"), CreatedBy("Created-By"), Title(IMPLEMENTATION_TITLE.toString()), Vendor(IMPLEMENTATION_VENDOR.toString()), AppVersion(IMPLEMENTATION_VERSION.toString()), MainClass(MAIN_CLASS.toString()), ClassPath(CLASS_PATH.toString()), ContentType(CONTENT_TYPE.toString()) } /** * Returns the [BuildInfo] attribute value from jar manifest [Attributes] */ fun Attributes?.getVal(name: BuildInfo): String = this?.getValue(name.attr) ?: "N/A"
apache-2.0
96c1f9e9a05441b2b5425ecdfbce5cbe
27.822715
119
0.667243
3.54239
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetadataStubBuilder.kt
1
2180
// 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.klib import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.compiled.ClsStubBuilder import com.intellij.psi.impl.compiled.ClassFileStubBuilder import com.intellij.psi.stubs.PsiFileStub import com.intellij.util.indexing.FileContent import org.jetbrains.kotlin.idea.decompiler.stubBuilder.createIncompatibleAbiVersionFileStub import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import org.jetbrains.kotlin.serialization.js.DynamicTypeDeserializer open class KlibMetadataStubBuilder( private val version: Int, private val fileType: FileType, private val serializerProtocol: () -> SerializerExtensionProtocol, private val readFile: (VirtualFile) -> FileWithMetadata? ) : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + version override fun buildFileStub(content: FileContent): PsiFileStub<*>? { val virtualFile = content.file assert(FileTypeRegistry.getInstance().isFileOfType(virtualFile, fileType)) { "Unexpected file type ${virtualFile.fileType}" } val file = readFile(virtualFile) ?: return null return when (file) { is FileWithMetadata.Incompatible -> createIncompatibleAbiVersionFileStub() is FileWithMetadata.Compatible -> { //todo: this part is implemented in our own way val renderer = DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() } val ktFileText = decompiledText( file, serializerProtocol(), DynamicTypeDeserializer, renderer ) createFileStub(content.project, ktFileText.text) } } } }
apache-2.0
0f2bd873c64ee30b3a4e911ce8eaffd8
45.382979
158
0.73578
5.165877
false
false
false
false
BenWoodworth/FastCraft
fastcraft-bukkit/bukkit-1.7/src/main/kotlin/net/benwoodworth/fastcraft/bukkit/text/FcTextColor_Bukkit_1_7.kt
1
3849
package net.benwoodworth.fastcraft.bukkit.text import net.benwoodworth.fastcraft.platform.text.FcTextColor import org.bukkit.ChatColor import javax.inject.Inject import javax.inject.Singleton object FcTextColor_Bukkit_1_7 { @Singleton class Operations @Inject constructor( ) : FcTextColor_Bukkit.Operations { override val FcTextColor.chatColor: ChatColor get() = value as ChatColor override val FcTextColor.id: String get() = when (chatColor) { ChatColor.BLACK -> "black" ChatColor.DARK_BLUE -> "dark_blue" ChatColor.DARK_GREEN -> "dark_green" ChatColor.DARK_AQUA -> "dark_aqua" ChatColor.DARK_RED -> "dark_red" ChatColor.DARK_PURPLE -> "dark_purple" ChatColor.GOLD -> "gold" ChatColor.GRAY -> "gray" ChatColor.DARK_GRAY -> "dark_gray" ChatColor.BLUE -> "blue" ChatColor.GREEN -> "green" ChatColor.AQUA -> "aqua" ChatColor.RED -> "red" ChatColor.LIGHT_PURPLE -> "light_purple" ChatColor.YELLOW -> "yellow" ChatColor.WHITE -> "white" ChatColor.RESET -> "reset" else -> error("$chatColor is not a color") } } @Singleton class Factory @Inject constructor( ) : FcTextColor_Bukkit.Factory { override val black: FcTextColor get() = FcTextColor(ChatColor.BLACK) override val darkBlue: FcTextColor get() = FcTextColor(ChatColor.DARK_BLUE) override val darkGreen: FcTextColor get() = FcTextColor(ChatColor.DARK_GREEN) override val darkAqua: FcTextColor get() = FcTextColor(ChatColor.DARK_AQUA) override val darkRed: FcTextColor get() = FcTextColor(ChatColor.DARK_RED) override val darkPurple: FcTextColor get() = FcTextColor(ChatColor.DARK_PURPLE) override val gold: FcTextColor get() = FcTextColor(ChatColor.GOLD) override val gray: FcTextColor get() = FcTextColor(ChatColor.GRAY) override val darkGray: FcTextColor get() = FcTextColor(ChatColor.DARK_GRAY) override val blue: FcTextColor get() = FcTextColor(ChatColor.BLUE) override val green: FcTextColor get() = FcTextColor(ChatColor.GREEN) override val aqua: FcTextColor get() = FcTextColor(ChatColor.AQUA) override val red: FcTextColor get() = FcTextColor(ChatColor.RED) override val lightPurple: FcTextColor get() = FcTextColor(ChatColor.LIGHT_PURPLE) override val yellow: FcTextColor get() = FcTextColor(ChatColor.YELLOW) override val white: FcTextColor get() = FcTextColor(ChatColor.WHITE) override val default: FcTextColor get() = FcTextColor(ChatColor.RESET) override fun fromId(id: String): FcTextColor { return when (id) { "black" -> black "dark_blue" -> darkBlue "dark_green" -> darkGreen "dark_aqua" -> darkAqua "dark_red" -> darkRed "dark_purple" -> darkPurple "gold" -> gold "gray" -> gray "dark_gray" -> darkGray "blue" -> blue "green" -> green "aqua" -> aqua "red" -> red "light_purple" -> lightPurple "yellow" -> yellow "white" -> white "reset" -> default else -> throw IllegalArgumentException("Invalid color ID: $id") } } } }
gpl-3.0
8aea347adc46961149e7121c6b3037e4
32.469565
79
0.548454
4.775434
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/fragments/terms/AcceptTermsViewModel.kt
2
4553
/* * Copyright 2019 New Vector Ltd * * 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 im.vector.fragments.terms import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import im.vector.R import im.vector.util.state.MxAsync import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.core.Log import org.matrix.androidsdk.core.callback.ApiCallback import org.matrix.androidsdk.core.model.MatrixError import org.matrix.androidsdk.features.terms.GetTermsResponse import org.matrix.androidsdk.features.terms.TermsManager class AcceptTermsViewModel : ViewModel() { lateinit var termsArgs: ServiceTermsArgs val termsList: MutableLiveData<MxAsync<List<Term>>> = MutableLiveData() val acceptTerms: MutableLiveData<MxAsync<Unit>> = MutableLiveData() var mxSession: MXSession? = null var termsManager: TermsManager? = null fun markTermAsAccepted(url: String, accepted: Boolean) { termsList.value?.invoke()?.map { if (it.url == url) { it.copy(accepted = accepted) } else it }?.let { termsList.postValue(MxAsync.Success(it)) } } fun initSession(session: MXSession?) { mxSession = session termsManager = mxSession?.termsManager } fun acceptTerms() { val acceptedTerms = termsList.value?.invoke() ?: return acceptTerms.postValue(MxAsync.Loading()) val agreedUrls = acceptedTerms.map { it.url } termsManager?.agreeToTerms(termsArgs.type, termsArgs.baseURL, agreedUrls, termsArgs.token, object : ApiCallback<Unit> { override fun onSuccess(info: Unit) { acceptTerms.postValue(MxAsync.Success(Unit)) } override fun onUnexpectedError(e: java.lang.Exception?) { acceptTerms.postValue(MxAsync.Error(R.string.unknown_error)) Log.e(LOG_TAG, "Failed to agree to terms ", e) } override fun onNetworkError(e: java.lang.Exception?) { acceptTerms.postValue(MxAsync.Error(R.string.unknown_error)) Log.e(LOG_TAG, "Failed to agree to terms ", e) } override fun onMatrixError(e: MatrixError?) { acceptTerms.postValue(MxAsync.Error(R.string.unknown_error)) Log.e(LOG_TAG, "Failed to agree to terms " + e?.message) } } ) } fun loadTerms(preferredLanguageCode: String) { termsList.postValue(MxAsync.Loading()) termsManager?.get(termsArgs.type, termsArgs.baseURL, object : ApiCallback<GetTermsResponse> { override fun onSuccess(info: GetTermsResponse) { val terms = info.serverResponse.getLocalizedTerms(preferredLanguageCode).map { Term(it.localizedUrl ?: "", it.localizedName ?: "", it.version, accepted = info.alreadyAcceptedTermUrls.contains(it.localizedUrl) ) } termsList.postValue(MxAsync.Success(terms)) } override fun onUnexpectedError(e: Exception?) { termsList.postValue(MxAsync.Error(R.string.unknown_error)) } override fun onNetworkError(e: Exception?) { termsList.postValue(MxAsync.Error(R.string.unknown_error)) } override fun onMatrixError(e: MatrixError?) { termsList.postValue(MxAsync.Error(R.string.unknown_error)) } }) } companion object { private val LOG_TAG = AcceptTermsViewModel::javaClass.name } } data class Term( val url: String, val name: String, val version: String? = null, val accepted: Boolean = false )
apache-2.0
2df92720dc80bf2522af93f27ab524d3
33.763359
101
0.607512
4.617647
false
false
false
false
mikepenz/MaterialDrawer
materialdrawer-nav/src/main/java/com/mikepenz/materialdrawer/model/NavigationDrawerItem.kt
1
2119
package com.mikepenz.materialdrawer.model import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.CallSuper import androidx.annotation.IdRes import androidx.navigation.NavOptions import androidx.recyclerview.widget.RecyclerView import com.mikepenz.materialdrawer.R import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem class NavigationDrawerItem<VH : RecyclerView.ViewHolder>( @IdRes val resId: Int, val item: IDrawerItem<VH>, val args: Bundle? = null, val options: NavOptions? = defaultOptions ) : IDrawerItem<VH> by item { init { item.identifier = resId.toLong() } /** * generates a view by the defined LayoutRes */ override fun generateView(ctx: Context): View { val viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(layoutRes, null, false) as ViewGroup) bindView(viewHolder, mutableListOf()) return viewHolder.itemView } /** * generates a view by the defined LayoutRes and pass the LayoutParams from the parent */ override fun generateView(ctx: Context, parent: ViewGroup): View { val viewHolder = getViewHolder(LayoutInflater.from(ctx).inflate(layoutRes, parent, false) as ViewGroup) bindView(viewHolder, mutableListOf()) return viewHolder.itemView } @CallSuper override fun bindView(holder: VH, payloads: List<Any>) { item.bindView(holder, payloads) holder.itemView.setTag(R.id.material_drawer_item, this) } companion object { val defaultOptions = NavOptions.Builder() .setLaunchSingleTop(true) .setEnterAnim(androidx.navigation.ui.R.anim.nav_default_enter_anim) .setExitAnim(androidx.navigation.ui.R.anim.nav_default_exit_anim) .setPopEnterAnim(androidx.navigation.ui.R.anim.nav_default_pop_enter_anim) .setPopExitAnim(androidx.navigation.ui.R.anim.nav_default_pop_exit_anim) .build() } }
apache-2.0
25f7506a5a930d163f5ba764ab144c6f
34.932203
111
0.697499
4.396266
false
false
false
false
odnoklassniki/ok-android-sdk
odnoklassniki-android-sdk/src/main/java/ru/ok/android/sdk/ContextOkListener.kt
2
1048
package ru.ok.android.sdk import android.content.Context import org.json.JSONObject import java.lang.ref.WeakReference /** * Listener that validates that only holds a weak reference to a context, * so will not be called if context no longer available */ class ContextOkListener( context: Context, private val onSuccess: ((ctx: Context, json: JSONObject) -> Unit?)? = null, private val onCancel: ((ctx: Context, err: String?) -> Unit)? = null, private val onError: ((ctx: Context, err: String?) -> Unit)? = null) : OkAuthListener { private val contextRef = WeakReference(context) override fun onSuccess(json: JSONObject) { val ctx = contextRef.get() if (ctx != null) onSuccess?.invoke(ctx, json) } override fun onCancel(error: String?) { val ctx = contextRef.get() if (ctx != null) onCancel?.invoke(ctx, error) } override fun onError(error: String?) { val ctx = contextRef.get() if (ctx != null) onError?.invoke(ctx, error) } }
apache-2.0
3e7e2ac6c40c6dafeca8e42a19e2f02c
28.971429
83
0.64313
4.062016
false
false
false
false
ognev-zair/Kotlin-AgendaCalendarView
kotlin-agendacalendarview/src/main/java/com/ognev/kotlin/agendacalendarview/agenda/AgendaAdapter.kt
1
3056
package com.ognev.kotlin.agendacalendarview.agenda import android.support.annotation.NonNull import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import com.ognev.kotlin.agendacalendarview.CalendarManager import com.ognev.kotlin.agendacalendarview.R import com.ognev.kotlin.agendacalendarview.models.CalendarEvent import com.ognev.kotlin.agendacalendarview.render.EventAdapter import com.ognev.kotlin.agendacalendarview.utils.DateHelper import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter import java.text.SimpleDateFormat import java.util.* /** * Adapter for the agenda, implements StickyListHeadersAdapter. * Days as sections and CalendarEvents as list items. */ class AgendaAdapter: BaseAdapter(), StickyListHeadersAdapter { override fun getCount(): Int { return CalendarManager.instance!!.events.size } private val mRenderers = ArrayList<EventAdapter<CalendarEvent>>() fun updateEvents() { notifyDataSetChanged() } override fun getHeaderView(position: Int, convertView: View?, parent: ViewGroup): View { var agendaHeaderView = convertView var eventAdapter: EventAdapter<CalendarEvent> ? = mRenderers[0] if (agendaHeaderView == null) { agendaHeaderView = LayoutInflater.from(parent.context). inflate(eventAdapter!!.getHeaderLayout(), parent, false) } if (!CalendarManager.instance!!.events.isEmpty()) { eventAdapter!!.getHeaderItemView(agendaHeaderView!!, getItem(position).instanceDay) } return agendaHeaderView!! } override fun getHeaderId(position: Int): Long { return (if (CalendarManager.instance!!.events.isEmpty()) 0 else CalendarManager.instance!!.events[position].instanceDay.timeInMillis).toLong() } override fun getItem(position: Int): CalendarEvent { return CalendarManager.instance!!.events[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView var eventAdapter: EventAdapter<CalendarEvent> = mRenderers[0] val event = getItem(position) // Search for the correct event renderer for (renderer in mRenderers) { if (event.javaClass.isAssignableFrom(renderer.renderType)) { eventAdapter = renderer break } } convertView = LayoutInflater.from(parent.context) .inflate(eventAdapter.getEventLayout(CalendarManager. instance!!.events[position].hasEvent()), parent, false) eventAdapter.getEventItemView(convertView, event, position) return convertView } fun addEventRenderer(@NonNull adapter: EventAdapter<CalendarEvent>) { mRenderers.add(adapter) } }
apache-2.0
fe7089b7196e0210457f4914fd5cc76e
30.833333
95
0.698953
4.921095
false
false
false
false
hannesa2/TouchImageView
app/src/main/java/info/touchimage/demo/ChangeSizeExampleActivity.kt
1
9021
package info.touchimage.demo import android.animation.ValueAnimator import android.annotation.SuppressLint import android.graphics.Color import android.os.Bundle import android.view.View import android.widget.Button import android.widget.ImageView import androidx.appcompat.app.AppCompatActivity import androidx.core.view.updateLayoutParams import com.ortiz.touchview.TouchImageView import kotlinx.android.synthetic.main.activity_change_size.* import kotlin.math.max import kotlin.math.min import kotlin.math.pow /** * An example Activity for how to handle a TouchImageView that might be resized. * * If you want your image to look like it's being cropped or sliding when you resize it, instead of * changing its zoom level, you probably want ScaleType.CENTER. Here's an example of how to use it: * * imageChangeSize.setScaleType(CENTER); * imageChangeSize.setMinZoom(TouchImageView.AUTOMATIC_MIN_ZOOM); * imageChangeSize.setMaxZoomRatio(3.0f); * float widthRatio = (float) imageChangeSize.getMeasuredWidth() / imageChangeSize.getDrawable().getIntrinsicWidth(); * float heightRatio = (float) imageChangeSize.getMeasuredHeight() / imageChangeSize.getDrawable().getIntrinsicHeight(); * imageChangeSize.setZoom(Math.max(widthRatio, heightRatio)); // For an initial view that looks like CENTER_CROP * imageChangeSize.setZoom(Math.min(widthRatio, heightRatio)); // For an initial view that looks like FIT_CENTER * * That code is run when the button displays "CENTER (with X zoom)". * * You can use other ScaleTypes, but for all of them, the size of the image depends somehow on the * size of the TouchImageView, just like it does in ImageView. You can thus expect your image to * change magnification as its View changes sizes. */ class ChangeSizeExampleActivity : AppCompatActivity() { private var xSizeAnimator = ValueAnimator() private var ySizeAnimator = ValueAnimator() private var xSizeAdjustment = 0 private var ySizeAdjustment = 0 private var scaleTypeIndex = 0 private var imageIndex = 0 private lateinit var resizeAdjuster: SizeBehaviorAdjuster private lateinit var rotateAdjuster: SizeBehaviorAdjuster override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_change_size) imageChangeSize.setBackgroundColor(Color.LTGRAY) imageChangeSize.minZoom = TouchImageView.AUTOMATIC_MIN_ZOOM imageChangeSize.setMaxZoomRatio(6.0f) left.setOnClickListener(SizeAdjuster(-1, 0)) right.setOnClickListener(SizeAdjuster(1, 0)) up.setOnClickListener(SizeAdjuster(0, -1)) down.setOnClickListener(SizeAdjuster(0, 1)) resizeAdjuster = SizeBehaviorAdjuster(false, "resize: ") rotateAdjuster = SizeBehaviorAdjuster(true, "rotate: ") resize.setOnClickListener(resizeAdjuster) rotate.setOnClickListener(rotateAdjuster) switch_scaletype_button.setOnClickListener { scaleTypeIndex = (scaleTypeIndex + 1) % scaleTypes.size processScaleType(scaleTypes[scaleTypeIndex], true) } findViewById<View>(R.id.switch_image_button).setOnClickListener { imageIndex = (imageIndex + 1) % images.size imageChangeSize.setImageResource(images[imageIndex]) } savedInstanceState?.let { savedState -> scaleTypeIndex = savedState.getInt("scaleTypeIndex") resizeAdjuster.setIndex(findViewById<View>(R.id.resize) as Button, savedState.getInt("resizeAdjusterIndex")) rotateAdjuster.setIndex(findViewById<View>(R.id.rotate) as Button, savedState.getInt("rotateAdjusterIndex")) imageIndex = savedState.getInt("imageIndex") imageChangeSize.setImageResource(images[imageIndex]) } imageChangeSize.post { processScaleType(scaleTypes[scaleTypeIndex], false) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) with (outState) { putInt("scaleTypeIndex", scaleTypeIndex) putInt("resizeAdjusterIndex", resizeAdjuster.index) putInt("rotateAdjusterIndex", rotateAdjuster.index) putInt("imageIndex", imageIndex) } } @SuppressLint("SetTextI18n") private fun processScaleType(scaleType: ImageView.ScaleType, resetZoom: Boolean) { when (scaleType) { ImageView.ScaleType.FIT_END -> { switch_scaletype_button.text = ImageView.ScaleType.CENTER.name + " (with " + ImageView.ScaleType.CENTER_CROP.name + " zoom)" imageChangeSize.scaleType = ImageView.ScaleType.CENTER val widthRatio = imageChangeSize.measuredWidth.toFloat() / imageChangeSize.drawable.intrinsicWidth val heightRatio = imageChangeSize.measuredHeight.toFloat() / imageChangeSize.drawable.intrinsicHeight if (resetZoom) { imageChangeSize.setZoom(max(widthRatio, heightRatio)) } } ImageView.ScaleType.FIT_START -> { switch_scaletype_button.text = ImageView.ScaleType.CENTER.name + " (with " + ImageView.ScaleType.FIT_CENTER.name + " zoom)" imageChangeSize.scaleType = ImageView.ScaleType.CENTER val widthRatio = imageChangeSize.measuredWidth.toFloat() / imageChangeSize.drawable.intrinsicWidth val heightRatio = imageChangeSize.measuredHeight.toFloat() / imageChangeSize.drawable.intrinsicHeight if (resetZoom) { imageChangeSize.setZoom(min(widthRatio, heightRatio)) } } else -> { switch_scaletype_button.text = scaleType.name imageChangeSize.scaleType = scaleType if (resetZoom) { imageChangeSize.resetZoom() } } } } private fun adjustImageSize() { val width = image_container.measuredWidth * 1.1.pow(xSizeAdjustment.toDouble()) val height = image_container.measuredHeight * 1.1.pow(ySizeAdjustment.toDouble()) xSizeAnimator.cancel() ySizeAnimator.cancel() xSizeAnimator = ValueAnimator.ofInt(imageChangeSize.width, width.toInt()) ySizeAnimator = ValueAnimator.ofInt(imageChangeSize.height, height.toInt()) xSizeAnimator.addUpdateListener { animation -> imageChangeSize.updateLayoutParams { this.width = animation.animatedValue as Int } } ySizeAnimator.addUpdateListener { animation -> imageChangeSize.updateLayoutParams { this.height = animation.animatedValue as Int } } xSizeAnimator.duration = 200 ySizeAnimator.duration = 200 xSizeAnimator.start() ySizeAnimator.start() } private inner class SizeAdjuster constructor(internal var dx: Int, internal var dy: Int) : View.OnClickListener { override fun onClick(v: View) { val newXScale = min(0, xSizeAdjustment + dx) val newYScale = min(0, ySizeAdjustment + dy) if (newXScale == xSizeAdjustment && newYScale == ySizeAdjustment) { return } xSizeAdjustment = newXScale ySizeAdjustment = newYScale adjustImageSize() } } private inner class SizeBehaviorAdjuster internal constructor(private val forOrientationChanges: Boolean, private val buttonPrefix: String) : View.OnClickListener { private val values = TouchImageView.FixedPixel.values() var index = 0 private set override fun onClick(v: View) { setIndex(v as Button, (index + 1) % values.size) } @SuppressLint("SetTextI18n") internal fun setIndex(b: Button, index: Int) { this.index = index if (forOrientationChanges) { imageChangeSize.orientationChangeFixedPixel = values[index] } else { imageChangeSize.viewSizeChangeFixedPixel = values[index] } b.text = buttonPrefix + values[index].name } } companion object { // // Two of the ScaleTypes are stand-ins for CENTER with different initial zoom levels. This is // special-cased in processScaleType. // private val scaleTypes = arrayOf(ImageView.ScaleType.CENTER, ImageView.ScaleType.CENTER_CROP, ImageView.ScaleType.FIT_START, // stand-in for CENTER with initial zoom that looks like FIT_CENTER ImageView.ScaleType.FIT_END, // stand-in for CENTER with initial zoom that looks like CENTER_CROP ImageView.ScaleType.CENTER_INSIDE, ImageView.ScaleType.FIT_XY, ImageView.ScaleType.FIT_CENTER) private val images = intArrayOf(R.drawable.nature_1, R.drawable.nature_2, R.drawable.nature_6, R.drawable.nature_7, R.drawable.nature_8) } }
mit
5140d56e96dd9ac85fed4294a7b41cc3
44.105
200
0.67753
4.674093
false
false
false
false
hazuki0x0/YuzuBrowser
module/favicon/src/main/java/jp/hazuki/yuzubrowser/favicon/FaviconManager.kt
1
7374
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.favicon import android.content.Context import android.database.sqlite.SQLiteException import android.graphics.Bitmap import android.graphics.BitmapFactory import android.text.TextUtils import jp.hazuki.yuzubrowser.core.android.utils.calcImageHash import jp.hazuki.yuzubrowser.core.cache.DiskLruCache import jp.hazuki.yuzubrowser.core.utility.hash.formatHashString import jp.hazuki.yuzubrowser.core.utility.hash.parseHashString import java.io.ByteArrayOutputStream import java.io.IOException import java.io.OutputStream import java.util.* class FaviconManager(context: Context) : FaviconCache.OnIconCacheOverFlowListener, DiskLruCache.OnTrimCacheListener { private val diskCache = DiskLruCache.open(context.getDir(CACHE_FOLDER, Context.MODE_PRIVATE), 1, 1, DISK_CACHE_SIZE.toLong()) private val diskCacheIndex = FaviconCacheIndex(context.applicationContext, CACHE_FOLDER) private val ramCache = FaviconCache(RAM_CACHE_SIZE, this) private val ramCacheIndex: MutableMap<String, Long> = HashMap() init { diskCache.setOnTrimCacheListener(this) } operator fun set(url: String, icon: Bitmap?) { if (icon == null || TextUtils.isEmpty(url)) return val normalizedUrl = getNormalUrl(url) val vec = icon.calcImageHash() val hash = formatHashString(vec) if (!ramCache.containsKey(vec)) { ramCache[vec] = icon addToDiskCache(hash, icon) } diskCacheIndex.add(normalizedUrl, vec) synchronized(ramCacheIndex) { ramCacheIndex.put(normalizedUrl, vec) } } operator fun get(url: String): Bitmap? { if (TextUtils.isEmpty(url)) return null val normalizedUrl = getNormalUrl(url) synchronized(ramCacheIndex) { val icon = ramCacheIndex[normalizedUrl] if (icon != null) { return ramCache[icon] } } val result = diskCacheIndex[normalizedUrl] if (result.exists) { val icon = getFromDiskCache(formatHashString(result.hash)) if (icon != null) { ramCache[result.hash] = icon synchronized(ramCacheIndex) { ramCacheIndex.put(normalizedUrl, result.hash) } } else { try { diskCacheIndex.remove(result.hash) } catch (e: SQLiteException) { e.printStackTrace() } } return icon } return null } fun getFaviconBytes(url: String): ByteArray? { if (TextUtils.isEmpty(url)) return null val normalizedUrl = getNormalUrl(url) synchronized(ramCacheIndex) { val icon = ramCacheIndex[normalizedUrl] if (icon != null) { val os = ByteArrayOutputStream() ramCache[icon]!!.compress(Bitmap.CompressFormat.PNG, 100, os) return os.toByteArray() } } val result = diskCacheIndex[normalizedUrl] return if (result.exists) { getFromDiskCacheBytes(formatHashString(result.hash)) } else null } fun save() { try { diskCache.flush() } catch (e: IOException) { e.printStackTrace() } } fun clear() { diskCacheIndex.clear() diskCache.clear() ramCacheIndex.clear() ramCache.clear() } fun destroy() { ramCache.clear() ramCacheIndex.clear() try { diskCache.close() } catch (e: IOException) { e.printStackTrace() } } private fun getNormalUrl(url: String): String { var resolveUrl = url var index = resolveUrl.indexOf('?') if (index > -1) { resolveUrl = resolveUrl.substring(0, index) } index = resolveUrl.indexOf('#') if (index > -1) { resolveUrl = resolveUrl.substring(0, index) } return resolveUrl } private fun addToDiskCache(key: String, bitmap: Bitmap) { synchronized(diskCache) { var out: OutputStream? = null try { val snapshot = diskCache.get(key) if (snapshot == null) { val editor = diskCache.edit(key) if (editor != null) { out = editor.newOutputStream(DISK_CACHE_INDEX) bitmap.compress(Bitmap.CompressFormat.PNG, 100, out) editor.commit() out!!.close() } } else { snapshot.getInputStream(DISK_CACHE_INDEX).close() } } catch (e: Exception) { e.printStackTrace() } finally { try { out?.close() } catch (e: IOException) { e.printStackTrace() } } } } private fun getFromDiskCache(key: String): Bitmap? { synchronized(diskCache) { try { val snapshot = diskCache.get(key) if (snapshot != null) { snapshot.getInputStream(DISK_CACHE_INDEX)?.use { return BitmapFactory.decodeStream(it) } } } catch (e: IOException) { e.printStackTrace() } return null } } private fun getFromDiskCacheBytes(key: String): ByteArray? { synchronized(diskCache) { try { val snapshot = diskCache.get(key) if (snapshot != null) { snapshot.getInputStream(DISK_CACHE_INDEX)?.use { return it.readBytes() } } } catch (e: IOException) { e.printStackTrace() } } return null } override fun onCacheOverflow(hash: Long) { synchronized(ramCacheIndex) { val iterator = ramCacheIndex.entries.iterator() while (iterator.hasNext()) { val item = iterator.next() if (hash == item.value) { iterator.remove() } } } } override fun onTrim(key: String) { diskCacheIndex.remove(parseHashString(key)) } companion object { private const val DISK_CACHE_SIZE = 10 * 1024 * 1024 private const val RAM_CACHE_SIZE = 1024 * 1024 private const val CACHE_FOLDER = "favicon" private const val DISK_CACHE_INDEX = 0 } }
apache-2.0
0158f657968e537c426dc7eda6bfcec8
29.59751
129
0.557771
4.646503
false
false
false
false
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/data/Mail.kt
1
977
package org.triplepy.sh8email.sh8.data /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.data * ============================== * Created by igangsan on 2016. 9. 4.. * * 코틀린 data class를 이용한 Mail Model입니다. * data class는 data model을 사용할 때 구현해야하는 * Getter Setter와 같은 보일러플레이트 코드를 사용하지 않아도 * 즉, 롬복을 사용하지 않아도 바로 Mail 필드에 접근이 가능합니다. * 주로 바인딩할 경우에 val을 사용하여 final로 고정시켜주고 * instance를 직접 생성하거나 변경 사항이 있을 때에는 var을 사용하여도 됩니다. * * @author 이강산 (river-mountain) */ data class Mail( val recipient: String, val secret_code: String, val sender: String, val subject: String, val contents: String, val recip_date: String, val is_read: Boolean )
apache-2.0
6273132f7ec0421932c3e10a40a60f99
26.555556
51
0.602961
2.553265
false
false
false
false
sonnytron/FitTrainerBasic
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/fragments/WorkoutFragment.kt
1
3091
package com.sonnyrodriguez.fittrainer.fittrainerbasic.fragments import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.sonnyrodriguez.fittrainer.fittrainerbasic.adapters.WorkoutAdapter import com.sonnyrodriguez.fittrainer.fittrainerbasic.database.WorkoutObject import com.sonnyrodriguez.fittrainer.fittrainerbasic.library.addFragment import com.sonnyrodriguez.fittrainer.fittrainerbasic.presenter.WorkoutPresenter import com.sonnyrodriguez.fittrainer.fittrainerbasic.presenter.WorkoutPresenterHelper import com.sonnyrodriguez.fittrainer.fittrainerbasic.ui.WorkoutFragmentUi import com.sonnyrodriguez.fittrainer.fittrainerbasic.values.RequestConstants import dagger.android.support.AndroidSupportInjection import org.jetbrains.anko.AnkoContext import org.jetbrains.anko.support.v4.ctx import javax.inject.Inject class WorkoutFragment: Fragment(), WorkoutPresenter { lateinit var ui: WorkoutFragmentUi internal var workoutAdapter = WorkoutAdapter() @Inject lateinit var workoutHelper: WorkoutPresenterHelper companion object { fun newInstance() = WorkoutFragment() } override fun onCreate(savedInstanceState: Bundle?) { AndroidSupportInjection.inject(this) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { ui = WorkoutFragmentUi(workoutAdapter) return ui.createView(AnkoContext.Companion.create(ctx, this)).apply { workoutHelper.onCreate(this@WorkoutFragment) } } override fun onDestroy() { workoutHelper.onDestroy() super.onDestroy() } internal fun addNewWorkout() { addFragment(EditWorkoutFragment.newInstance(null), RequestConstants.ADD_WORKOUT_CONSTANT) } override fun showWorkouts(workouts: List<WorkoutObject>) { workoutAdapter.changeAll(workouts) } internal fun editWorkout(workoutObject: WorkoutObject) { addFragment(EditWorkoutFragment.newInstance(workoutObject), RequestConstants.ADD_WORKOUT_CONSTANT) } override fun scrollTo(position: Int) { ui.workoutRecyclerView.smoothScrollToPosition(position) } override fun workoutAddedTo(position: Int) { workoutAdapter.notifyItemInserted(position) } override fun workoutUpdatedAt(position: Int) { workoutAdapter.notifyItemChanged(position) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { data?.run { when (requestCode) { RequestConstants.ADD_WORKOUT_CONSTANT -> { workoutHelper.loadWorkouts() } else -> { } } } } } }
apache-2.0
509ded8a9445faaa78acb512a0e99db0
33.730337
117
0.724685
5.05892
false
false
false
false
grote/Transportr
app/src/main/java/de/grobox/transportr/trips/detail/TripDrawer.kt
1
8966
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * 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 de.grobox.transportr.trips.detail import android.content.Context import android.graphics.PorterDuff.Mode.SRC_IN import android.graphics.PorterDuff.Mode.MULTIPLY import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.mapbox.mapboxsdk.annotations.Icon import com.mapbox.mapboxsdk.annotations.PolylineOptions import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.geometry.LatLngBounds import com.mapbox.mapboxsdk.maps.MapboxMap import de.grobox.transportr.R import de.grobox.transportr.map.MapDrawer import de.grobox.transportr.utils.DateUtils.formatTime import de.grobox.transportr.utils.hasLocation import de.schildbach.pte.dto.Location import de.schildbach.pte.dto.Point import de.schildbach.pte.dto.Stop import de.schildbach.pte.dto.Trip import de.schildbach.pte.dto.Trip.* import java.util.* internal class TripDrawer(context: Context) : MapDrawer(context) { private enum class MarkerType { BEGIN, CHANGE, STOP, END, WALK } fun draw(map: MapboxMap, trip: Trip, zoom: Boolean) { // draw leg path first, so it is always at the bottom var i = 1 val builder = LatLngBounds.Builder() for (leg in trip.legs) { // add path if it is missing if (leg.path == null) calculatePath(leg) if (leg.path == null) continue // get colors val backgroundColor = getBackgroundColor(leg) val foregroundColor = getForegroundColor(leg) // draw leg path first, so it is always at the bottom val points = ArrayList<LatLng>(leg.path.size) leg.path.mapTo(points) { LatLng(it.latAsDouble, it.lonAsDouble) } map.addPolyline(PolylineOptions() .color(backgroundColor) .addAll(points) .width(5f) ) // Only draw marker icons for public transport legs if (leg is Public) { // Draw intermediate stops below all others leg.intermediateStops?.let { for (stop in it) { val stopIcon = getMarkerIcon(MarkerType.STOP, backgroundColor, foregroundColor) val text = getStopText(stop) markLocation(map, stop.location, stopIcon, text) } } // Draw first station or change station if (i == 1 || i == 2 && trip.legs[0] is Individual) { val icon = getMarkerIcon(MarkerType.BEGIN, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(leg, MarkerType.BEGIN)) } else { val icon = getMarkerIcon(MarkerType.CHANGE, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(trip.legs[i - 2], leg)) } // Draw final station only at the end or if end is walking if (i == trip.legs.size || i == trip.legs.size - 1 && trip.legs[i] is Individual) { val icon = getMarkerIcon(MarkerType.END, backgroundColor, foregroundColor) markLocation(map, leg.arrival, icon, getStationText(leg, MarkerType.END)) } } else if (leg is Individual) { // only draw an icon if walk is required in the middle of a trip if (i > 1 && i < trip.legs.size) { val icon = getMarkerIcon(MarkerType.WALK, backgroundColor, foregroundColor) markLocation(map, leg.departure, icon, getStationText(trip.legs[i - 2], leg)) } } i += 1 builder.includes(points) } if (zoom) { zoomToBounds(map, builder, false) } } private fun calculatePath(leg: Leg) { if (leg.path == null) leg.path = ArrayList() if (leg.departure != null && leg.departure.hasLocation()) { leg.path.add(Point.fromDouble(leg.departure.latAsDouble, leg.departure.lonAsDouble)) } if (leg is Public) { leg.intermediateStops?.filter { it.location != null && it.location.hasLocation() }?.forEach { leg.path.add(Point.fromDouble(it.location.latAsDouble, it.location.lonAsDouble)) } } if (leg.arrival != null && leg.arrival.hasLocation()) { leg.path.add(Point.fromDouble(leg.arrival.latAsDouble, leg.arrival.lonAsDouble)) } } @ColorInt private fun getBackgroundColor(leg: Leg): Int { if (leg is Public) { val line = leg.line return if (line?.style != null && line.style!!.backgroundColor != 0) { line.style!!.backgroundColor } else { ContextCompat.getColor(context, R.color.accent) } } return ContextCompat.getColor(context, R.color.walking) } @ColorInt private fun getForegroundColor(leg: Leg): Int { if (leg is Public) { val line = leg.line return if (line?.style != null && line.style!!.foregroundColor != 0) { line.style!!.foregroundColor } else { ContextCompat.getColor(context, android.R.color.white) } } return ContextCompat.getColor(context, android.R.color.black) } private fun markLocation(map: MapboxMap, location: Location, icon: Icon, text: String) { markLocation(map, location, icon, location.uniqueShortName(), text) } private fun getMarkerIcon(type: MarkerType, backgroundColor: Int, foregroundColor: Int): Icon { // Get Drawable val drawable: Drawable if (type == MarkerType.STOP) { drawable = ContextCompat.getDrawable(context, R.drawable.ic_marker_trip_stop) ?: throw RuntimeException() drawable.mutate().setColorFilter(backgroundColor, SRC_IN) } else { val res: Int = when (type) { MarkerType.BEGIN -> R.drawable.ic_marker_trip_begin MarkerType.CHANGE -> R.drawable.ic_marker_trip_change MarkerType.END -> R.drawable.ic_marker_trip_end MarkerType.WALK -> R.drawable.ic_marker_trip_walk else -> throw IllegalArgumentException() } drawable = ContextCompat.getDrawable(context, res) as LayerDrawable drawable.getDrawable(0).mutate().setColorFilter(backgroundColor, MULTIPLY) drawable.getDrawable(1).mutate().setColorFilter(foregroundColor, SRC_IN) } return drawable.toIcon() } private fun getStopText(stop: Stop): String { var text = "" stop.getArrivalTime(false)?.let { text += "${context.getString(R.string.trip_arr)}: ${formatTime(context, it)}" } stop.getDepartureTime(false)?.let { if (text.isNotEmpty()) text += "\n" text += "${context.getString(R.string.trip_dep)}: ${formatTime(context, it)}" } return text } private fun getStationText(leg: Public, type: MarkerType): String { return when (type) { MarkerType.BEGIN -> leg.getDepartureTime(false)?.let { "${context.getString(R.string.trip_dep)}: ${formatTime(context, it)}" } MarkerType.END -> leg.getArrivalTime(false)?.let { "${context.getString(R.string.trip_arr)}: ${formatTime(context, it)}" } else -> throw IllegalArgumentException() } ?: "" } private fun getStationText(leg1: Leg, leg2: Leg): String { var text = "" leg1.arrivalTime?.let { text += "${context.getString(R.string.trip_arr)}: ${formatTime(context, it)}" } leg2.departureTime?.let { if (text.isNotEmpty()) text += "\n" text += "${context.getString(R.string.trip_dep)}: ${formatTime(context, it)}" } return text } }
gpl-3.0
63423aea839e035a0309afa59fa0eec0
39.570136
117
0.601383
4.436418
false
false
false
false
hhariri/mark-code
samples-out/sample/_SomeSampleChapter.kt
1
440
package sample._SomeSampleChapter import java.util.ArrayList data class Person(val name: String, val age: Int? = null) fun main(args: Array<String>) { val otherPersons = ArrayList<String>() val persons = listOf(Person("Alice"), Person("Bob", age = 29)) val oldest = persons.maxBy { it.age ?: 0 } println("The oldest is: $oldest") } // The oldest is: Person(name=Bob, age=29)
mit
f742a7459409d29698f94ec3377856a1
23.444444
49
0.606818
3.728814
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/chatroom/adapter/PeopleSuggestionsAdapter.kt
2
3423
package chat.rocket.android.chatroom.adapter import DrawableHelper import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.view.isVisible import chat.rocket.android.R import chat.rocket.android.chatroom.adapter.PeopleSuggestionsAdapter.PeopleSuggestionViewHolder import chat.rocket.android.chatroom.uimodel.suggestion.PeopleSuggestionUiModel import chat.rocket.android.suggestions.model.SuggestionModel import chat.rocket.android.suggestions.ui.BaseSuggestionViewHolder import chat.rocket.android.suggestions.ui.SuggestionsAdapter import com.facebook.drawee.view.SimpleDraweeView class PeopleSuggestionsAdapter(context: Context) : SuggestionsAdapter<PeopleSuggestionViewHolder>("@") { init { val allDescription = context.getString(R.string.suggest_all_description) val hereDescription = context.getString(R.string.suggest_here_description) val pinnedList = listOf( PeopleSuggestionUiModel(imageUri = null, text = "all", username = "all", name = allDescription, status = null, pinned = false, searchList = listOf("all")), PeopleSuggestionUiModel(imageUri = null, text = "here", username = "here", name = hereDescription, status = null, pinned = false, searchList = listOf("here")) ) setPinnedSuggestions(pinnedList) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PeopleSuggestionViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.suggestion_member_item, parent, false) return PeopleSuggestionViewHolder(view) } class PeopleSuggestionViewHolder(view: View) : BaseSuggestionViewHolder(view) { override fun bind(item: SuggestionModel, itemClickListener: SuggestionsAdapter.ItemClickListener?) { item as PeopleSuggestionUiModel with(itemView) { val username = itemView.findViewById<TextView>(R.id.text_username) val name = itemView.findViewById<TextView>(R.id.text_name) val avatar = itemView.findViewById<SimpleDraweeView>(R.id.image_avatar) val statusView = itemView.findViewById<ImageView>(R.id.image_status) username.text = item.username name.text = item.name if (item.imageUri?.isEmpty() != false) { avatar.isVisible = false } else { avatar.isVisible = true avatar.setImageURI(item.imageUri) } val status = item.status if (status != null) { val statusDrawable = DrawableHelper.getUserStatusDrawable(status, itemView.context) statusView.setImageDrawable(statusDrawable) } else { statusView.isVisible = false } setOnClickListener { itemClickListener?.onClick(item) } } } } }
mit
6961f18fdc9ef3501c683ef663934af9
42.341772
108
0.613205
5.356808
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/api/list/MediaListEndpoint.kt
2
2125
package me.proxer.library.api.list import me.proxer.library.ProxerCall import me.proxer.library.api.PagingLimitEndpoint import me.proxer.library.entity.list.MediaListEntry import me.proxer.library.enums.Category import me.proxer.library.enums.MediaListSortCriteria import me.proxer.library.enums.Medium import me.proxer.library.enums.SortType /** * Endpoint for retrieving the entries of a search as type of [MediaListEntry]. * * @author Desnoo */ class MediaListEndpoint internal constructor( private val internalApi: InternalApi ) : PagingLimitEndpoint<List<MediaListEntry>> { private var page: Int? = null private var limit: Int? = null private var category: Category? = null private var medium: Medium? = null private var includeHentai: Boolean? = null private var sort: MediaListSortCriteria? = null private var sortType: SortType? = null private var searchStart: String? = null override fun page(page: Int?) = this.apply { this.page = page } override fun limit(limit: Int?) = this.apply { this.limit = limit } /** * Sets the category to search. */ fun category(category: Category?) = this.apply { this.category = category } /** * Sets the medium. */ fun medium(medium: Medium?) = this.apply { this.medium = medium } /** * Sets if hentai should be included in the result. */ fun includeHentai(includeHentai: Boolean? = true) = this.apply { this.includeHentai = includeHentai } /** * Sets the criteria to search the result by. */ fun sort(sort: MediaListSortCriteria?) = this.apply { this.sort = sort } /** * Sets the type to search the result by. */ fun sortType(sortType: SortType?) = this.apply { this.sortType = sortType } /** * Sets the query to search for only from the start. */ fun searchStart(searchStart: String?) = this.apply { this.searchStart = searchStart } override fun build(): ProxerCall<List<MediaListEntry>> { return internalApi.mediaList(category, medium, includeHentai, searchStart, sort, sortType, page, limit) } }
gpl-3.0
70da3036848be1ba948ad96db7cc076f
31.19697
111
0.689412
4.158513
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/lists/Member.kt
1
11587
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.lists import jp.nephy.penicillin.core.request.action.JsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Lists import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.User /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param listId The numerical id of the list. * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( listId: Long, userId: Long, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(listId, null, null, null, userId, null, includeEntities, skipStatus, *options) /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param listId The numerical id of the list. * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( listId: Long, screenName: String, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(listId, null, null, null, null, screenName, includeEntities, skipStatus, *options) /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerScreenName The screen name of the user who owns the list being requested by a slug. * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( slug: String, ownerScreenName: String, userId: Long, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(null, slug, ownerScreenName, null, userId, null, includeEntities, skipStatus, *options) /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerScreenName The screen name of the user who owns the list being requested by a slug. * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( slug: String, ownerScreenName: String, screenName: String, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(null, slug, ownerScreenName, null, null, screenName, includeEntities, skipStatus, *options) /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerId The user ID of the user who owns the list being requested by a slug. * @param userId The ID of the user for whom to return results. Helpful for disambiguating when a valid user ID is also a valid screen name. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( slug: String, ownerId: Long, userId: Long, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(null, slug, null, ownerId, userId, null, includeEntities, skipStatus, *options) /** * Check if the specified user is a member of the specified list. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/create-manage-lists/api-reference/get-lists-members-show) * * @param slug You can identify a list by its slug instead of its numerical id. If you decide to do so, note that you'll also have to specify the list owner using the owner_id or owner_screen_name parameters. * @param ownerId The user ID of the user who owns the list being requested by a slug. * @param screenName The screen name of the user for whom to return results. Helpful for disambiguating when a valid screen name is also a user ID. * @param includeEntities When set to either true, t or 1, each tweet will include a node called "entities". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See [Tweet Entities](https://developer.twitter.com/overview/api/tweets) for more details. * @param skipStatus When set to either true, t or 1 statuses will not be included in the returned user objects. * @param options Optional. Custom parameters of this request. * @receiver [Lists] endpoint instance. * @return [JsonObjectApiAction] for [User] model. */ fun Lists.member( slug: String, ownerId: Long, screenName: String, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = member(null, slug, null, ownerId, null, screenName, includeEntities, skipStatus, *options) internal fun Lists.member( listId: Long? = null, slug: String? = null, ownerScreenName: String? = null, ownerId: Long? = null, userId: Long? = null, screenName: String? = null, includeEntities: Boolean? = null, skipStatus: Boolean? = null, vararg options: Option ) = client.session.get("/1.1/lists/members/show.json") { parameters( "list_id" to listId, "slug" to slug, "owner_screen_name" to ownerScreenName, "owner_id" to ownerId, "user_id" to userId, "screen_name" to screenName, "include_entities" to includeEntities, "skip_status" to skipStatus, *options ) }.jsonObject<User>()
mit
cacb10392368bae26ef61be726805d34
59.348958
438
0.747648
4.097242
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/scene3d/obj/ObjModelLoader.kt
1
10463
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.scene3d.obj import com.almasb.fxgl.dsl.FXGL import com.almasb.fxgl.scene3d.Model3D import com.almasb.fxgl.scene3d.Model3DLoader import javafx.scene.paint.Color import javafx.scene.paint.PhongMaterial import javafx.scene.shape.CullFace import javafx.scene.shape.MeshView import javafx.scene.shape.TriangleMesh import javafx.scene.shape.VertexFormat import java.net.URL /** * TODO: revisit implementation * * @author Almas Baimagambetov ([email protected]) */ class ObjModelLoader : Model3DLoader { companion object { private val objParsers = linkedMapOf<(String) -> Boolean, (List<String>, ObjData) -> Unit>() private val mtlParsers = linkedMapOf<(String) -> Boolean, (List<String>, MtlData) -> Unit>() init { objParsers[ { it.startsWith("g") } ] = Companion::parseGroup objParsers[ { it.startsWith("s") } ] = Companion::parseSmoothing objParsers[ { it.startsWith("vt") } ] = Companion::parseVertexTextures objParsers[ { it.startsWith("vn") } ] = Companion::parseVertexNormals objParsers[ { it.startsWith("v ") } ] = Companion::parseVertices objParsers[ { it.startsWith("f") } ] = Companion::parseFaces objParsers[ { it.startsWith("mtllib") } ] = Companion::parseMaterialLib objParsers[ { it.startsWith("usemtl") } ] = Companion::parseUseMaterial mtlParsers[ { it.startsWith("newmtl") } ] = Companion::parseNewMaterial mtlParsers[ { it.startsWith("Ka") } ] = Companion::parseColorAmbient mtlParsers[ { it.startsWith("Kd") } ] = Companion::parseColorDiffuse mtlParsers[ { it.startsWith("Ks") } ] = Companion::parseColorSpecular mtlParsers[ { it.startsWith("Ns") } ] = Companion::parseSpecularPower mtlParsers[ { it.startsWith("map_Kd") } ] = Companion::parseDiffuseMap } private fun parseGroup(tokens: List<String>, data: ObjData) { val groupName = if (tokens.isEmpty()) "default" else tokens[0] data.groups += ObjGroup(groupName) } private fun parseSmoothing(tokens: List<String>, data: ObjData) { data.currentGroup.currentSubGroup.smoothingGroup = tokens.toSmoothingGroup() } private fun parseVertexTextures(tokens: List<String>, data: ObjData) { data.vertexTextures += tokens.toFloats2() } private fun parseVertexNormals(tokens: List<String>, data: ObjData) { data.vertexNormals += tokens.toFloats3() } private fun parseVertices(tokens: List<String>, data: ObjData) { // for -Y // .mapIndexed { index, fl -> if (index == 1) -fl else fl } data.vertices += tokens.toFloats3() } private fun parseFaces(tokens: List<String>, data: ObjData) { if (tokens.size > 3) { for (i in 2 until tokens.size) { parseFaceVertex(tokens[0], data) parseFaceVertex(tokens[i-1], data) parseFaceVertex(tokens[i], data) } } else { tokens.forEach { token -> parseFaceVertex(token, data) } } } /** * Each token is of form v1/(vt1)/(vn1). * Case v1 * Case v1/vt1 * Case v1//n1 * Case v1/vt1/vn1 */ private fun parseFaceVertex(token: String, data: ObjData) { val faceVertex = token.split("/") // JavaFX format is vertices, normals and tex when (faceVertex.size) { // f v1 1 -> { data.currentGroup.currentSubGroup.faces += faceVertex[0].toInt() - 1 data.currentGroup.currentSubGroup.faces += 0 data.currentGroup.currentSubGroup.faces += 0 } // f v1/vt1 2 -> { data.currentGroup.currentSubGroup.faces += faceVertex[0].toInt() - 1 data.currentGroup.currentSubGroup.faces += 0 data.currentGroup.currentSubGroup.faces += faceVertex[1].toInt() - 1 } // f v1//vn1 // f v1/vt1/vn1 3 -> { data.currentGroup.currentSubGroup.faces += faceVertex[0].toInt() - 1 data.currentGroup.currentSubGroup.faces += faceVertex[2].toInt() - 1 data.currentGroup.currentSubGroup.faces += (faceVertex[1].toIntOrNull() ?: 1) - 1 } } } private fun parseMaterialLib(tokens: List<String>, data: ObjData) { val fileName = tokens[0] val mtlURL = URL(data.url.toExternalForm().substringBeforeLast('/') + '/' + fileName) val mtlData = loadMtlData(mtlURL) data.materials += mtlData.materials data.ambientColors += mtlData.ambientColors } private fun parseUseMaterial(tokens: List<String>, data: ObjData) { data.currentGroup.subGroups += SubGroup() data.currentGroup.currentSubGroup.material = data.materials[tokens[0]] ?: throw RuntimeException("Material with name ${tokens[0]} not found") data.currentGroup.currentSubGroup.ambientColor = data.ambientColors[data.currentGroup.currentSubGroup.material] } private fun List<String>.toFloats2(): List<Float> { return this.take(2).map { it.toFloat() } } private fun List<String>.toFloats3(): List<Float> { return this.take(3).map { it.toFloat() } } private fun List<String>.toColor(): Color { val rgb = this.toFloats3().map { if (it > 1.0) 1.0 else it.toDouble() } return Color.color(rgb[0], rgb[1], rgb[2]) } private fun List<String>.toSmoothingGroup(): Int { return if (this[0] == "off") 0 else this[0].toInt() } private fun parseNewMaterial(tokens: List<String>, data: MtlData) { data.currentMaterial = PhongMaterial() data.materials[tokens[0]] = data.currentMaterial } private fun parseColorAmbient(tokens: List<String>, data: MtlData) { data.ambientColors[data.currentMaterial] = tokens.toColor() } private fun parseColorDiffuse(tokens: List<String>, data: MtlData) { data.currentMaterial.diffuseColor = tokens.toColor() } private fun parseColorSpecular(tokens: List<String>, data: MtlData) { data.currentMaterial.specularColor = tokens.toColor() } private fun parseSpecularPower(tokens: List<String>, data: MtlData) { data.currentMaterial.specularPower = tokens[0].toDouble() } private fun parseDiffuseMap(tokens: List<String>, data: MtlData) { val ext = data.url.toExternalForm().substringBeforeLast("/") + "/" data.currentMaterial.diffuseMap = FXGL.getAssetLoader().loadImage(URL(ext + tokens[0])) } private fun loadObjData(url: URL): ObjData { val data = ObjData(url) load(url, objParsers, data) return data } private fun loadMtlData(url: URL): MtlData { val data = MtlData(url) load(url, mtlParsers, data) return data } private fun <T> load(url: URL, parsers: Map<(String) -> Boolean, (List<String>, T) -> Unit>, data: T) { url.openStream().bufferedReader().useLines { it.forEach { line -> val lineTrimmed = line.trim() for ((condition, action) in parsers) { if (condition.invoke(lineTrimmed) ) { // drop identifier val tokens = lineTrimmed.split(" +".toRegex()).drop(1) action.invoke(tokens, data) break } } } } } } // TODO: smoothing groups override fun load(url: URL): Model3D { try { val data = loadObjData(url) val modelRoot = Model3D() data.groups.forEach { val groupRoot = Model3D() groupRoot.properties["name"] = it.name it.subGroups.forEach { // TODO: ? if (!it.faces.isEmpty()) { val mesh = TriangleMesh(VertexFormat.POINT_NORMAL_TEXCOORD) mesh.points.addAll(*data.vertices.map { it * 0.05f }.toFloatArray()) // if there are no vertex textures, just add 2 values if (data.vertexTextures.isEmpty()) { mesh.texCoords.addAll(*FloatArray(2) { _ -> 0.0f }) } else { mesh.texCoords.addAll(*data.vertexTextures.toFloatArray()) } // if there are no vertex normals, just add 3 values if (data.vertexNormals.isEmpty()) { mesh.normals.addAll(*FloatArray(3) { _ -> 0.0f }) } else { mesh.normals.addAll(*data.vertexNormals.toFloatArray()) } mesh.faces.addAll(*it.faces.toIntArray()) if (it.smoothingGroups.isNotEmpty()) { mesh.faceSmoothingGroups.addAll(*it.smoothingGroups.toIntArray()) } val view = MeshView(mesh) view.material = it.material view.cullFace = CullFace.NONE groupRoot.addMeshView(view) } } modelRoot.addModel(groupRoot) } return modelRoot } catch (e: Exception) { e.printStackTrace() throw RuntimeException("Load failed for URL: $url Error: $e") } } }
mit
d3bff9b8e78a3552810a48290c9d5309
36.238434
123
0.535506
4.458032
false
false
false
false
Takhion/android-extras-delegates
library/src/main/java/me/eugeniomarletti/extras/bundle/base/ArrayList.kt
1
1856
@file:Suppress("NOTHING_TO_INLINE") package me.eugeniomarletti.extras.bundle.base import android.os.Parcelable import me.eugeniomarletti.extras.bundle.BundleExtra import me.eugeniomarletti.extras.bundle.BundlePropertyDelegate import java.util.ArrayList inline fun BundleExtra.CharSequenceArrayList(name: String? = null, customPrefix: String? = null) = CharSequenceArrayList({ it }, { it }, name, customPrefix) inline fun BundleExtra.CharSequenceArrayList(defaultValue: ArrayList<CharSequence?>, name: String? = null, customPrefix: String? = null) = CharSequenceArrayList({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.StringArrayList(name: String? = null, customPrefix: String? = null) = StringArrayList({ it }, { it }, name, customPrefix) inline fun BundleExtra.StringArrayList(defaultValue: ArrayList<String?>, name: String? = null, customPrefix: String? = null) = StringArrayList({ it ?: defaultValue }, { it }, name, customPrefix) inline fun BundleExtra.IntArrayList(name: String? = null, customPrefix: String? = null) = IntArrayList({ it }, { it }, name, customPrefix) inline fun BundleExtra.IntArrayList(defaultValue: ArrayList<Int?>, name: String? = null, customPrefix: String? = null) = IntArrayList({ it ?: defaultValue }, { it }, name, customPrefix) inline fun <T : Parcelable> BundleExtra.ParcelableArrayList( name: String? = null, customPrefix: String? = null ): BundlePropertyDelegate<ArrayList<T?>?> = ParcelableArrayList<ArrayList<T?>?, T>({ it }, { it }, name, customPrefix) inline fun <T : Parcelable> BundleExtra.ParcelableArrayList( defaultValue: ArrayList<T?>, name: String? = null, customPrefix: String? = null ): BundlePropertyDelegate<ArrayList<T?>?> = ParcelableArrayList<ArrayList<T?>?, T>({ it ?: defaultValue }, { it }, name, customPrefix)
mit
186c08e795e2f283b2782820c5d88285
46.615385
138
0.730603
4.189616
false
false
false
false
kishmakov/Kitchen
server/src/io/magnaura/server/compiler/ErrorAnalyzer.kt
1
2281
package io.magnaura.server.compiler import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.cli.common.messages.* import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM import org.jetbrains.kotlin.config.languageVersionSettings import org.jetbrains.kotlin.psi.KtFile data class LocatedMessage(val message: String, val location: CompilerMessageSourceLocation? = null) { override fun toString() = "$message @ $location" } class AnalyzerMessageCollector : MessageCollector { private val warnings = mutableListOf<LocatedMessage>() private val errors = mutableListOf<LocatedMessage>() override fun clear() { warnings.clear() errors.clear() } override fun hasErrors() = errors.isNotEmpty() override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageSourceLocation?) { val locatedMessage = LocatedMessage(message, location) when { severity.isError -> errors.add(locatedMessage) severity.isWarning -> warnings.add(locatedMessage) } } fun warnings(): List<String> = warnings.map { it.toString() } fun errors(): List<String> = errors.map { it.toString() } } class ErrorAnalyzer(val files: List<KtFile>) { val project = files.first().project val messageCollector = AnalyzerMessageCollector() private val coreEnvironment = KotlinEnvironment.coreEnvironment() private val analyzerWithCompilerReport = AnalyzerWithCompilerReport( messageCollector, coreEnvironment.configuration.languageVersionSettings ) val analysisResult: AnalysisResult get() = analyzerWithCompilerReport.analysisResult init { analyzerWithCompilerReport.analyzeAndReport(files) { TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration( project, files, NoScopeRecordCliBindingTrace(), coreEnvironment.configuration, coreEnvironment::createPackagePartProvider, sourceModuleSearchScope = TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, files) ) } } }
gpl-3.0
32dd819dd6eb82ba66a0548e19ab9176
34.107692
119
0.716352
5.160633
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/base/usecase/GetPointFromGeocacheCodeUseCase.kt
1
1909
package com.arcao.geocaching4locus.base.usecase import com.arcao.geocaching4locus.authentication.util.restrictions import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.data.api.GeocachingApiRepository import com.arcao.geocaching4locus.data.api.exception.GeocachingApiException import com.arcao.geocaching4locus.data.api.model.enums.StatusCode import com.arcao.geocaching4locus.error.exception.CacheNotFoundException import kotlinx.coroutines.withContext import locus.api.mapper.DataMapper class GetPointFromGeocacheCodeUseCase( private val repository: GeocachingApiRepository, private val geocachingApiLogin: GeocachingApiLoginUseCase, private val accountManager: AccountManager, private val mapper: DataMapper, private val dispatcherProvider: CoroutinesDispatcherProvider ) { @Suppress("BlockingMethodInNonBlockingContext") suspend operator fun invoke( referenceCode: String, liteData: Boolean = true, geocacheLogsCount: Int = 0 ) = withContext(dispatcherProvider.io) { geocachingApiLogin() try { val geocache = repository.geocache( referenceCode = referenceCode, lite = liteData, logsCount = geocacheLogsCount ) accountManager.restrictions().updateLimits(repository.userLimits()) mapper.createLocusPoint(geocache) } catch (e: GeocachingApiException) { if (e.statusCode == StatusCode.NOT_FOUND) { throw CacheNotFoundException(referenceCode) } if (e.statusCode == StatusCode.FORBIDDEN && e.errorMessage?.contains("not published") == true) { throw CacheNotFoundException(referenceCode) } throw e } } }
gpl-3.0
b16156257a2aafd40ad8fd24ebc2f949
37.18
108
0.716082
4.920103
false
false
false
false
weisterjie/FamilyLedger
app/src/main/java/ycj/com/familyledger/Consts.kt
1
509
package ycj.com.familyledger /** * @author: ycj * @date: 2017-06-21 09:42 * @version V1.0 <> */ object Consts { const val BASE_URL = "http://111.231.89.14:8099/ledger/" const val SP_APP_NAME = "sp_user" const val SP_PHONE = "phone" const val SP_USER_NAME = "userName" const val SP_PASSWORD = "password" const val SP_USER_ID = "userId" const val DATA_ID = "id" const val DATA_BEAN = "bean" const val LIST_DATA = "listData" const val ACTIVITY_RESULT_REFRESH = 2000 }
apache-2.0
46958166cbf56aced4214b48b3865103
25.842105
60
0.630648
3.066265
false
false
false
false
klose911/klose911.github.io
src/kotlin/src/tutorial/collections/overview/SetInterface.kt
1
422
package tutorial.collections.overview fun main() { val numbers = setOf(1, 2, 3, 4) println("Number of elements: ${numbers.size}") if (numbers.contains(1)) println("1 is in the set") val numbersBackwards = setOf(4, 3, 2, 1) println("The sets are equal: ${numbers == numbersBackwards}") println(numbers.first() == numbersBackwards.first()) println(numbers.first() == numbersBackwards.last()) }
bsd-2-clause
081136a96fc3dade867a85fe379aec9a
31.538462
65
0.668246
3.767857
false
false
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/cargo/project/settings/ui/RustProjectSettingsPanel.kt
1
4866
package org.rust.cargo.project.settings.ui import backcompat.ui.layout.CCFlags import backcompat.ui.layout.LayoutBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.options.ConfigurationException import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.Disposer import com.intellij.ui.DocumentAdapter import com.intellij.ui.JBColor import com.intellij.util.Alarm import org.rust.cargo.project.settings.RustProjectSettingsService import org.rust.cargo.toolchain.RustToolchain import javax.swing.JCheckBox import javax.swing.JLabel import javax.swing.JTextField import javax.swing.event.DocumentEvent class RustProjectSettingsPanel { data class Data( val toolchain: RustToolchain?, val autoUpdateEnabled: Boolean ) { fun applyTo(settings: RustProjectSettingsService) { settings.autoUpdateEnabled = autoUpdateEnabled settings.toolchain = toolchain } } private val disposable: Disposable = Disposer.newDisposable() fun disposeUIResources() = Disposer.dispose(disposable) private val versionUpdateAlarm = Alarm(Alarm.ThreadToUse.POOLED_THREAD, disposable) private val toolchainLocationField = TextFieldWithBrowseButton(null, disposable) private val autoUpdateEnabled = JCheckBox() private val rustVersion = JLabel() private val cargoVersion = JLabel() private val rustupVersion = JLabel() private val versionUpdateDelayMillis = 200 var data: Data get() = Data( RustToolchain(toolchainLocationField.text), autoUpdateEnabled.isSelected ) set(value) { toolchainLocationField.text = value.toolchain?.location autoUpdateEnabled.isSelected = value.autoUpdateEnabled } fun attachTo(layout: LayoutBuilder) = with(layout) { toolchainLocationField.addBrowseFolderListener( "", "Cargo location", null, FileChooserDescriptorFactory.createSingleFolderDescriptor(), TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, false ) listenForUpdates(toolchainLocationField.textField) Disposer.register(disposable, toolchainLocationField) data = Data( RustToolchain.suggest(), autoUpdateEnabled = true ) row("Toolchain location") { toolchainLocationField(CCFlags.pushX) } row("Rustc") { rustVersion() } row("Cargo") { cargoVersion() } row("Rustup") { rustupVersion() } } @Throws(ConfigurationException::class) fun validateSettings() { val toolchain = data.toolchain ?: return if (!toolchain.looksLikeValidToolchain()) { throw ConfigurationException("Invalid toolchain location: can't find Cargo in ${toolchain.location}") } } private fun listenForUpdates(textField: JTextField) { var previousLocation = textField.text textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent?) { val currentLocation = textField.text if (currentLocation != previousLocation) { scheduleVersionUpdate(currentLocation) previousLocation = currentLocation } } }) } private fun scheduleVersionUpdate(toolchainLocation: String) { versionUpdateAlarm.cancelAllRequests() versionUpdateAlarm.addRequest({ val versionInfo = RustToolchain(toolchainLocation).queryVersions() updateVersion(versionInfo) }, versionUpdateDelayMillis) } private fun updateVersion(info: RustToolchain.VersionInfo) { ApplicationManager.getApplication().invokeLater({ if (Disposer.isDisposed(disposable)) return@invokeLater val labelToVersion = listOf( rustVersion to info.rustc?.semver, cargoVersion to info.cargo?.semver, rustupVersion to info.rustup ) for ((label, version) in labelToVersion) { if (version == null) { label.text = "N/A" label.foreground = JBColor.RED } else { label.text = version.parsedVersion label.foreground = JBColor.foreground() } } if (info.cargo?.hasMetadataCommand == false) { cargoVersion.foreground = JBColor.RED } }, ModalityState.any()) } }
mit
3d4ffc6b81525f75732a6ef7903f526f
35.044444
113
0.663584
5.430804
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/DrawnWordCommand.kt
1
6314
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.utils.ImageUtils import net.perfectdreams.loritta.morenitta.utils.enableFontAntiAliasing import net.perfectdreams.loritta.morenitta.utils.substringIfNeeded import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.commands.arguments import net.perfectdreams.loritta.common.utils.image.JVMImage import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils import net.perfectdreams.loritta.morenitta.utils.extensions.readImage import java.awt.Color import java.awt.FontMetrics import java.awt.Graphics import java.awt.image.BufferedImage import java.io.File class DrawnWordCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("drawnword"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { companion object { private const val LOCALE_PREFIX = "commands.command" } override fun command() = create { needsToUploadFiles = true localizedDescription("$LOCALE_PREFIX.drawnword.description") localizedExamples("$LOCALE_PREFIX.drawnword.examples") usage { arguments { argument(ArgumentType.TEXT) {} } } executesDiscord { val context = this if (args.isEmpty()) explainAndExit() OutdatedCommandUtils.sendOutdatedCommandMessage(this, this.locale, "drawnmask word") val text = args.joinToString(" ").substringIfNeeded(0..800) fun getTextWrapSpacesRequiredHeight(text: String, startX: Int, startY: Int, endX: Int, endY: Int, fontMetrics: FontMetrics, graphics: Graphics): Int { val lineHeight = fontMetrics.height var currentX = startX var currentY = startY val split = text.split("((?<= )|(?= ))".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (str in split) { var width = fontMetrics.stringWidth(str) if (currentX + width > endX) { currentX = startX currentY += lineHeight } var idx = 0 for (c in str.toCharArray()) { idx++ if (c == '\n') { currentX = startX currentY += lineHeight continue } width = fontMetrics.charWidth(c) if (!graphics.font.canDisplay(c)) { val emoteImage = ImageUtils.getTwitterEmoji(loritta, str, idx) if (emoteImage != null) { currentX += width } continue } currentX += width } } return currentY } val drawnMaskWordImage = readImage(File(LorittaBot.ASSETS, "drawn_mask_word.png")) val drawnMaskWordBottomImage = readImage(File(LorittaBot.ASSETS, "drawn_mask_word_bottom.png")) val babyMaskChairImage = readImage(File(LorittaBot.ASSETS, "baby_mask_chair.png")) var wordScreenHeight = drawnMaskWordImage.height val width = 468 val graphics = drawnMaskWordImage.graphics.enableFontAntiAliasing() val font2 = graphics.font.deriveFont(24f) graphics.font = font2 val fontMetrics = graphics.fontMetrics val lineHeight = fontMetrics.height val startY = 90 val currentY = getTextWrapSpacesRequiredHeight( text, 54, 90, drawnMaskWordImage.width, 99999, fontMetrics, graphics ) val currentJumps = (currentY - startY) / lineHeight val pixelsNeeded = currentY - startY if (currentJumps > 4) { val overflownPixels = (pixelsNeeded - (lineHeight * 3)) + lineHeight + lineHeight val requiredPastes = (overflownPixels / 53) wordScreenHeight += (53 * requiredPastes) - 27 } val wordScreen = BufferedImage(drawnMaskWordImage.width, wordScreenHeight, BufferedImage.TYPE_INT_ARGB) val wordScreenGraphics = wordScreen.graphics.enableFontAntiAliasing() wordScreenGraphics.drawImage(drawnMaskWordImage, 0, 0, null) wordScreenGraphics.color = Color.BLACK val font = wordScreenGraphics.font.deriveFont(24f) wordScreenGraphics.font = font2 val fontMetrics2 = wordScreenGraphics.fontMetrics if (currentJumps > 4) { val overflownPixels = (pixelsNeeded - (lineHeight * 3)) + lineHeight + lineHeight val requiredPastes = (overflownPixels / 53) var currentY = (drawnMaskWordImage.height - 40) repeat(requiredPastes) { wordScreenGraphics.drawImage(drawnMaskWordBottomImage, 0, currentY, null) currentY += 53 } } ImageUtils.drawTextWrapSpaces( loritta, text, 54, 90, wordScreen.width, 99999, fontMetrics2, wordScreenGraphics ) val image = BufferedImage(width, wordScreen.height + 202, BufferedImage.TYPE_INT_ARGB) val imageGraphics = image.graphics imageGraphics.fillRect(0, 0, 468, wordScreen.height + 202) imageGraphics.drawImage(wordScreen, 218, 0, null) imageGraphics.drawImage(babyMaskChairImage, 0, image.height - babyMaskChairImage.height, null) context.sendImage(JVMImage(image), "drawn_word.png", context.getUserMention(true)) } } }
agpl-3.0
1bd90eed7271a8cd6e8057fe8ef54801
36.814371
170
0.581565
5.231152
false
false
false
false
googlecodelabs/odml-pathways
product-search/codelab1/android/starter/app/src/main/java/com/google/codelabs/productimagesearch/ObjectDetectorActivity.kt
2
7752
/** * Copyright 2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.codelabs.productimagesearch import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.MediaStore import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.content.FileProvider import com.google.codelabs.productimagesearch.databinding.ActivityObjectDetectorBinding import com.google.mlkit.vision.objects.DetectedObject import java.io.File import java.io.IOException class ObjectDetectorActivity : AppCompatActivity() { companion object { private const val REQUEST_IMAGE_CAPTURE = 1000 private const val REQUEST_IMAGE_GALLERY = 1001 private const val TAKEN_BY_CAMERA_FILE_NAME = "MLKitDemo_" private const val IMAGE_PRESET_1 = "Preset1.jpg" private const val IMAGE_PRESET_2 = "Preset2.jpg" private const val IMAGE_PRESET_3 = "Preset3.jpg" private const val TAG = "MLKit-ODT" } private lateinit var viewBinding: ActivityObjectDetectorBinding private var cameraPhotoUri: Uri? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivityObjectDetectorBinding.inflate(layoutInflater) setContentView(viewBinding.root) initViews() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // After taking camera, display to Preview if (resultCode == RESULT_OK) { when (requestCode) { REQUEST_IMAGE_CAPTURE -> cameraPhotoUri?.let { this.setViewAndDetect( getBitmapFromUri(it) ) } REQUEST_IMAGE_GALLERY -> data?.data?.let { this.setViewAndDetect(getBitmapFromUri(it)) } } } } private fun initViews() { with(viewBinding) { ivPreset1.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_1)) ivPreset2.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_2)) ivPreset3.setImageBitmap(getBitmapFromAsset(IMAGE_PRESET_3)) ivCapture.setOnClickListener { dispatchTakePictureIntent() } ivGalleryApp.setOnClickListener { choosePhotoFromGalleryApp() } ivPreset1.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_1)) } ivPreset2.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) } ivPreset3.setOnClickListener { setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_3)) } // Default display setViewAndDetect(getBitmapFromAsset(IMAGE_PRESET_2)) } } /** * Update the UI with the input image and start object detection */ private fun setViewAndDetect(bitmap: Bitmap?) { bitmap?.let { // Clear the dots indicating the previous detection result viewBinding.ivPreview.drawDetectionResults(emptyList()) // Display the input image on the screen. viewBinding.ivPreview.setImageBitmap(bitmap) // Run object detection and show the detection results. runObjectDetection(bitmap) } } /** * Detect Objects in a given Bitmap */ private fun runObjectDetection(bitmap: Bitmap) { } /** * Show Camera App to take a picture based Intent */ private fun dispatchTakePictureIntent() { Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent -> // Ensure that there's a camera activity to handle the intent takePictureIntent.resolveActivity(packageManager)?.also { // Create the File where the photo should go val photoFile: File? = try { createImageFile(TAKEN_BY_CAMERA_FILE_NAME) } catch (ex: IOException) { // Error occurred while creating the File null } // Continue only if the File was successfully created photoFile?.also { cameraPhotoUri = FileProvider.getUriForFile( this, "com.google.codelabs.productimagesearch.fileprovider", it ) // Setting output file to take a photo takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPhotoUri) // Open camera based Intent. startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE) } } ?: run { Toast.makeText(this, getString(R.string.camera_app_not_found), Toast.LENGTH_LONG) .show() } } } /** * Show gallery app to pick photo from intent. */ private fun choosePhotoFromGalleryApp() { startActivityForResult(Intent(Intent.ACTION_OPEN_DOCUMENT).apply { type = "image/*" addCategory(Intent.CATEGORY_OPENABLE) }, REQUEST_IMAGE_GALLERY) } /** * The output file will be stored on private storage of this app * By calling function getExternalFilesDir * This photo will be deleted when uninstall app. */ @Throws(IOException::class) private fun createImageFile(fileName: String): File { // Create an image file name val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile( fileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ) } /** * Method to copy asset files sample to private app folder. * Return the Uri of an output file. */ private fun getBitmapFromAsset(fileName: String): Bitmap? { return try { BitmapFactory.decodeStream(assets.open(fileName)) } catch (ex: IOException) { null } } /** * Function to get the Bitmap From Uri. * Uri is received by using Intent called to Camera or Gallery app * SuppressWarnings => we have covered this warning. */ private fun getBitmapFromUri(imageUri: Uri): Bitmap? { val bitmap = try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ImageDecoder.decodeBitmap(ImageDecoder.createSource(contentResolver, imageUri)) } else { // Add Suppress annotation to skip warning by Android Studio. // This warning resolved by ImageDecoder function. @Suppress("DEPRECATION") MediaStore.Images.Media.getBitmap(contentResolver, imageUri) } } catch (ex: IOException) { null } // Make a copy of the bitmap in a desirable format return bitmap?.copy(Bitmap.Config.ARGB_8888, false) } }
apache-2.0
d2fdcf6fbb58b5f524e6fa7213625587
36.449275
104
0.634675
5.130377
false
false
false
false
NoodleMage/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsSourcesController.kt
1
4387
package eu.kanade.tachiyomi.ui.setting import android.graphics.drawable.Drawable import android.support.v7.preference.PreferenceGroup import android.support.v7.preference.PreferenceScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.source.online.LoginSource import eu.kanade.tachiyomi.widget.preference.LoginCheckBoxPreference import eu.kanade.tachiyomi.widget.preference.SourceLoginDialog import eu.kanade.tachiyomi.widget.preference.SwitchPreferenceCategory import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.util.* class SettingsSourcesController : SettingsController(), SourceLoginDialog.Listener { private val onlineSources by lazy { Injekt.get<SourceManager>().getOnlineSources() } override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) { titleRes = R.string.pref_category_sources // Get the list of active language codes. val activeLangsCodes = preferences.enabledLanguages().getOrDefault() // Get a map of sources grouped by language. val sourcesByLang = onlineSources.groupByTo(TreeMap(), { it.lang }) // Order first by active languages, then inactive ones val orderedLangs = sourcesByLang.keys.filter { it in activeLangsCodes } + sourcesByLang.keys.filterNot { it in activeLangsCodes } orderedLangs.forEach { lang -> val sources = sourcesByLang[lang].orEmpty().sortedBy { it.name } // Create a preference group and set initial state and change listener SwitchPreferenceCategory(context).apply { preferenceScreen.addPreference(this) title = Locale(lang).let { it.getDisplayLanguage(it).capitalize() } isPersistent = false if (lang in activeLangsCodes) { setChecked(true) addLanguageSources(this, sources) } onChange { newValue -> val checked = newValue as Boolean val current = preferences.enabledLanguages().getOrDefault() if (!checked) { preferences.enabledLanguages().set(current - lang) removeAll() } else { preferences.enabledLanguages().set(current + lang) addLanguageSources(this, sources) } true } } } } override fun setDivider(divider: Drawable?) { super.setDivider(null) } /** * Adds the source list for the given group (language). * * @param group the language category. */ private fun addLanguageSources(group: PreferenceGroup, sources: List<HttpSource>) { val hiddenCatalogues = preferences.hiddenCatalogues().getOrDefault() sources.forEach { source -> val sourcePreference = LoginCheckBoxPreference(group.context, source).apply { val id = source.id.toString() title = source.name key = getSourceKey(source.id) isPersistent = false isChecked = id !in hiddenCatalogues onChange { newValue -> val checked = newValue as Boolean val current = preferences.hiddenCatalogues().getOrDefault() preferences.hiddenCatalogues().set(if (checked) current - id else current + id) true } setOnLoginClickListener { val dialog = SourceLoginDialog(source) dialog.targetController = this@SettingsSourcesController dialog.showDialog(router) } } group.addPreference(sourcePreference) } } override fun loginDialogClosed(source: LoginSource) { val pref = findPreference(getSourceKey(source.id)) as? LoginCheckBoxPreference pref?.notifyChanged() } private fun getSourceKey(sourceId: Long): String { return "source_$sourceId" } }
apache-2.0
4b5bd60eced2ed2080cbe9ed99789930
36.504274
89
0.612947
5.476904
false
false
false
false
christophpickl/kpotpourri
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/random/RandomList.kt
1
1114
package com.github.christophpickl.kpotpourri.common.random import java.util.* import kotlin.random.Random fun <E> randomListOf(first: Pair<E, Int>, vararg elements: Pair<E, Int>): RandomList<E> = RandomListImpl(mutableListOf(first).apply { addAll(elements.toList()) }) interface RandomList<E> : List<E> { fun randomElement(): E } private class RandomListImpl<E>( private val elements: List<Pair<E, Int>> ) : ArrayList<E>(elements.map { it.first }), RandomList<E> { init { require(elements.sumBy { it.second } == 100) { "Percentage must sum up to 100%, but was: ${elements.sumBy { it.second }}%" } } override fun randomElement(): E { val rand = Random.nextInt(0, 100) var skipWindow = 0 elements.forEach { element -> val window = skipWindow..(skipWindow + element.second - 1) if (window.contains(rand)) { return element.first } skipWindow += element.second } throw IllegalStateException("Internal error. No random element could be calculated!") } }
apache-2.0
496bb4bb26340ab723f226f2e873c598
30.828571
93
0.622083
4.007194
false
false
false
false
mastizada/focus-android
app/src/main/java/org/mozilla/focus/fragment/UrlInputFragment.kt
1
19848
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.fragment import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.graphics.Typeface import android.os.Bundle import android.text.SpannableString import android.text.TextUtils import android.text.style.StyleSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver import android.widget.FrameLayout import kotlinx.android.synthetic.main.fragment_urlinput.* import org.mozilla.focus.R import org.mozilla.focus.activity.InfoActivity import org.mozilla.focus.autocomplete.UrlAutoCompleteFilter import org.mozilla.focus.locale.LocaleAwareAppCompatActivity import org.mozilla.focus.locale.LocaleAwareFragment import org.mozilla.focus.menu.home.HomeMenu import org.mozilla.focus.session.Session import org.mozilla.focus.session.SessionManager import org.mozilla.focus.session.Source import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.Settings import org.mozilla.focus.utils.SupportUtils import org.mozilla.focus.utils.ThreadUtils import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.utils.ViewUtils import org.mozilla.focus.whatsnew.WhatsNew import org.mozilla.focus.widget.InlineAutocompleteEditText /** * Fragment for displaying the URL input controls. */ // Refactoring the size and function count of this fragment is non-trivial at this point. // Therefore we ignore those violations for now. @Suppress("LargeClass", "TooManyFunctions") class UrlInputFragment : LocaleAwareFragment(), View.OnClickListener, InlineAutocompleteEditText.OnCommitListener, InlineAutocompleteEditText.OnFilterListener { companion object { @JvmField val FRAGMENT_TAG = "url_input" private val ARGUMENT_ANIMATION = "animation" private val ARGUMENT_X = "x" private val ARGUMENT_Y = "y" private val ARGUMENT_WIDTH = "width" private val ARGUMENT_HEIGHT = "height" private val ARGUMENT_SESSION_UUID = "sesssion_uuid" private val ANIMATION_BROWSER_SCREEN = "browser_screen" private val PLACEHOLDER = "5981086f-9d45-4f64-be99-7d2ffa03befb" private val ANIMATION_DURATION = 200 @JvmStatic fun createWithoutSession(): UrlInputFragment { val arguments = Bundle() val fragment = UrlInputFragment() fragment.arguments = arguments return fragment } @JvmStatic fun createWithSession(session: Session, urlView: View): UrlInputFragment { val arguments = Bundle() arguments.putString(ARGUMENT_SESSION_UUID, session.uuid) arguments.putString(ARGUMENT_ANIMATION, ANIMATION_BROWSER_SCREEN) val screenLocation = IntArray(2) urlView.getLocationOnScreen(screenLocation) arguments.putInt(ARGUMENT_X, screenLocation[0]) arguments.putInt(ARGUMENT_Y, screenLocation[1]) arguments.putInt(ARGUMENT_WIDTH, urlView.width) arguments.putInt(ARGUMENT_HEIGHT, urlView.height) val fragment = UrlInputFragment() fragment.arguments = arguments return fragment } /** * Create a new UrlInputFragment with a gradient background (and the Focus logo). This configuration * is usually shown if there's no content to be shown below (e.g. the current website). */ @JvmStatic fun createWithBackground(): UrlInputFragment { val arguments = Bundle() val fragment = UrlInputFragment() fragment.arguments = arguments return fragment } } private val urlAutoCompleteFilter: UrlAutoCompleteFilter = UrlAutoCompleteFilter() private var displayedPopupMenu: HomeMenu? = null @Volatile private var isAnimating: Boolean = false private var session: Session? = null private val isOverlay: Boolean get() = session != null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Get session from session manager if there's a session UUID in the fragment's arguments arguments?.getString(ARGUMENT_SESSION_UUID)?.let { session = SessionManager.getInstance().getSessionByUUID(it) } } override fun onResume() { super.onResume() urlAutoCompleteFilter.load(activity.applicationContext) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_urlinput, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { listOf(dismissView, clearView, searchView).forEach { it.setOnClickListener(this) } urlView.setOnFilterListener(this) urlView.imeOptions = urlView.imeOptions or ViewUtils.IME_FLAG_NO_PERSONALIZED_LEARNING urlInputContainerView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { urlInputContainerView.viewTreeObserver.removeOnPreDrawListener(this) animateFirstDraw() return true } }) if (isOverlay) { keyboardLinearLayout.visibility = View.GONE } else { backgroundView.setBackgroundResource(R.drawable.background_gradient) dismissView.visibility = View.GONE toolbarBackgroundView.visibility = View.GONE menuView.visibility = View.VISIBLE menuView.setOnClickListener(this) } urlView.setOnCommitListener(this) session?.let { urlView.setText(if (it.isSearch) it.searchTerms else it.url.value) clearView.visibility = View.VISIBLE searchViewContainer.visibility = View.GONE } } override fun applyLocale() { if (isOverlay) { activity?.supportFragmentManager ?.beginTransaction() ?.replace( R.id.container, UrlInputFragment.createWithSession(session!!, urlView), UrlInputFragment.FRAGMENT_TAG) ?.commit() } else { activity?.supportFragmentManager ?.beginTransaction() ?.replace( R.id.container, UrlInputFragment.createWithBackground(), UrlInputFragment.FRAGMENT_TAG) ?.commit() } } fun onBackPressed(): Boolean { if (isOverlay) { animateAndDismiss() return true } return false } override fun onStart() { super.onStart() if (!Settings.getInstance(context).shouldShowFirstrun()) { // Only show keyboard if we are not displaying the first run tour on top. showKeyboard() } } override fun onStop() { super.onStop() // Reset the keyboard layout to avoid a jarring animation when the view is started again. (#1135) keyboardLinearLayout.reset() } fun showKeyboard() { ViewUtils.showKeyboard(urlView) } // This method triggers the complexity warning. However it's actually not that hard to understand. @Suppress("ComplexMethod") override fun onClick(view: View) { when (view.id) { R.id.clearView -> clear() R.id.searchView -> onSearch() R.id.dismissView -> if (isOverlay) { animateAndDismiss() } else { clear() } R.id.menuView -> context?.let { val menu = HomeMenu(it, this) menu.show(view) displayedPopupMenu = menu } R.id.whats_new -> context?.let { TelemetryWrapper.openWhatsNewEvent(WhatsNew.shouldHighlightWhatsNew(it)) WhatsNew.userViewedWhatsNew(it) SessionManager.getInstance() .createSession(Source.MENU, SupportUtils.getWhatsNewUrl(context)) } R.id.settings -> (activity as LocaleAwareAppCompatActivity).openPreferences() R.id.help -> { val helpIntent = InfoActivity.getHelpIntent(activity) startActivity(helpIntent) } else -> throw IllegalStateException("Unhandled view in onClick()") } } private fun clear() { urlView.setText("") urlView.requestFocus() } override fun onDetach() { super.onDetach() // On detach, the PopupMenu is no longer relevant to other content (e.g. BrowserFragment) so dismiss it. // Note: if we don't dismiss the PopupMenu, its onMenuItemClick method references the old Fragment, which now // has a null Context and will cause crashes. displayedPopupMenu?.dismiss() } private fun animateFirstDraw() { if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) { playVisibilityAnimation(false) } } private fun animateAndDismiss() { ThreadUtils.assertOnUiThread() if (isAnimating) { // We are already animating some state change. Ignore all other requests. return } // Don't allow any more clicks: dismissView is still visible until the animation ends, // but we don't want to restart animations and/or trigger hiding again (which could potentially // cause crashes since we don't know what state we're in). Ignoring further clicks is the simplest // solution, since dismissView is about to disappear anyway. dismissView.isClickable = false if (ANIMATION_BROWSER_SCREEN == arguments?.getString(ARGUMENT_ANIMATION)) { playVisibilityAnimation(true) } else { dismiss() } } /** * This animation is quite complex. The 'reverse' flag controls whether we want to show the UI * (false) or whether we are going to hide it (true). Additionally the animation is slightly * different depending on whether this fragment is shown as an overlay on top of other fragments * or if it draws its own background. */ // This method correctly triggers a complexity warning. This method is indeed very and too complex. // However refactoring it is not trivial at this point so we ignore the warning for now. @Suppress("ComplexMethod") private fun playVisibilityAnimation(reverse: Boolean) { if (isAnimating) { // We are already animating, let's ignore another request. return } isAnimating = true val xyOffset = (if (isOverlay) (urlInputContainerView.layoutParams as FrameLayout.LayoutParams).bottomMargin else 0).toFloat() val width = urlInputBackgroundView.width.toFloat() val height = urlInputBackgroundView.height.toFloat() val widthScale = if (isOverlay) (width + 2 * xyOffset) / width else 1f val heightScale = if (isOverlay) (height + 2 * xyOffset) / height else 1f if (!reverse) { urlInputBackgroundView.pivotX = 0f urlInputBackgroundView.pivotY = 0f urlInputBackgroundView.scaleX = widthScale urlInputBackgroundView.scaleY = heightScale urlInputBackgroundView.translationX = -xyOffset urlInputBackgroundView.translationY = -xyOffset clearView.alpha = 0f } // Let the URL input use the full width/height and then shrink to the actual size urlInputBackgroundView.animate() .setDuration(ANIMATION_DURATION.toLong()) .scaleX(if (reverse) widthScale else 1f) .scaleY(if (reverse) heightScale else 1f) .alpha((if (reverse && isOverlay) 0 else 1).toFloat()) .translationX(if (reverse) -xyOffset else 0f) .translationY(if (reverse) -xyOffset else 0f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { if (reverse) { clearView.alpha = 0f } } override fun onAnimationEnd(animation: Animator) { if (reverse) { if (isOverlay) { dismiss() } } else { clearView?.alpha = 1f } isAnimating = false } }) // We only need to animate the toolbar if we are an overlay. if (isOverlay) { val screenLocation = IntArray(2) urlView.getLocationOnScreen(screenLocation) val leftDelta = arguments!!.getInt(ARGUMENT_X) - screenLocation[0] - urlView.paddingLeft if (!reverse) { urlView.pivotX = 0f urlView.pivotY = 0f urlView.translationX = leftDelta.toFloat() } // The URL moves from the right (at least if the lock is visible) to it's actual position urlView.animate() .setDuration(ANIMATION_DURATION.toLong()) .translationX((if (reverse) leftDelta else 0).toFloat()) } if (!reverse) { toolbarBackgroundView.alpha = 0f clearView.alpha = 0f } // The darker background appears with an alpha animation toolbarBackgroundView.animate() .setDuration(ANIMATION_DURATION.toLong()) .alpha((if (reverse) 0 else 1).toFloat()) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { toolbarBackgroundView.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator) { if (reverse) { toolbarBackgroundView.visibility = View.GONE if (!isOverlay) { dismissView.visibility = View.GONE menuView.visibility = View.VISIBLE } } } }) } private fun dismiss() { // This method is called from animation callbacks. In the short time frame between the animation // starting and ending the activity can be paused. In this case this code can throw an // IllegalStateException because we already saved the state (of the activity / fragment) before // this transaction is committed. To avoid this we commit while allowing a state loss here. // We do not save any state in this fragment (It's getting destroyed) so this should not be a problem. activity?.supportFragmentManager ?.beginTransaction() ?.remove(this) ?.commitAllowingStateLoss() } override fun onCommit() { val input = urlView.text.toString() if (!input.trim { it <= ' ' }.isEmpty()) { ViewUtils.hideKeyboard(urlView) val isUrl = UrlUtils.isUrl(input) val url = if (isUrl) UrlUtils.normalize(input) else UrlUtils.createSearchUrl(context, input) val searchTerms = if (isUrl) null else input.trim { it <= ' ' } openUrl(url, searchTerms) TelemetryWrapper.urlBarEvent(isUrl, urlView.lastAutocompleteResult) } } private fun onSearch() { val searchTerms = urlView.originalText val searchUrl = UrlUtils.createSearchUrl(context, searchTerms) openUrl(searchUrl, searchTerms) TelemetryWrapper.searchSelectEvent() } private fun openUrl(url: String, searchTerms: String?) { session?.searchTerms = searchTerms val fragmentManager = activity!!.supportFragmentManager // Replace all fragments with a fresh browser fragment. This means we either remove the // HomeFragment with an UrlInputFragment on top or an old BrowserFragment with an // UrlInputFragment. val browserFragment = fragmentManager.findFragmentByTag(BrowserFragment.FRAGMENT_TAG) if (browserFragment != null && browserFragment is BrowserFragment && browserFragment.isVisible) { // Reuse existing visible fragment - in this case we know the user is already browsing. // The fragment might exist if we "erased" a browsing session, hence we need to check // for visibility in addition to existence. browserFragment.loadUrl(url) // And this fragment can be removed again. fragmentManager.beginTransaction() .remove(this) .commit() } else { if (!TextUtils.isEmpty(searchTerms)) { SessionManager.getInstance().createSearchSession(Source.USER_ENTERED, url, searchTerms) } else { SessionManager.getInstance().createSession(Source.USER_ENTERED, url) } } } override fun onFilter(searchText: String, view: InlineAutocompleteEditText?) { // If the UrlInputFragment has already been hidden, don't bother with filtering. Because of the text // input architecture on Android it's possible for onFilter() to be called after we've already // hidden the Fragment, see the relevant bug for more background: // https://github.com/mozilla-mobile/focus-android/issues/441#issuecomment-293691141 if (!isVisible) { return } urlAutoCompleteFilter.onFilter(searchText, view) if (searchText.trim { it <= ' ' }.isEmpty()) { clearView.visibility = View.GONE searchViewContainer.visibility = View.GONE if (!isOverlay) { playVisibilityAnimation(true) } } else { clearView.visibility = View.VISIBLE menuView.visibility = View.GONE if (!isOverlay && dismissView.visibility != View.VISIBLE) { playVisibilityAnimation(false) dismissView.visibility = View.VISIBLE } // LTR languages sometimes have grammar where the search terms are displayed to the left // of the hint string. To take care of LTR, RTL, and special LTR cases, we use a // placeholder to know the start and end indices of where we should bold the search text val hint = getString(R.string.search_hint, PLACEHOLDER) val start = hint.indexOf(PLACEHOLDER) val content = SpannableString(hint.replace(PLACEHOLDER, searchText)) content.setSpan(StyleSpan(Typeface.BOLD), start, start + searchText.length, 0) searchView.text = content searchViewContainer.visibility = View.VISIBLE } } }
mpl-2.0
1a9e54c7cccf9ebd08460ace525608f8
35.552486
117
0.611145
5.239704
false
false
false
false
maskaravivek/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/ui/selector/FolderFragment.kt
3
4631
package fr.free.nrw.commons.customselector.ui.selector import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import fr.free.nrw.commons.R import fr.free.nrw.commons.customselector.helper.ImageHelper import fr.free.nrw.commons.customselector.model.Result import fr.free.nrw.commons.customselector.listeners.FolderClickListener import fr.free.nrw.commons.customselector.model.CallbackStatus import fr.free.nrw.commons.customselector.model.Folder import fr.free.nrw.commons.customselector.ui.adapter.FolderAdapter import fr.free.nrw.commons.di.CommonsDaggerSupportFragment import fr.free.nrw.commons.media.MediaClient import fr.free.nrw.commons.upload.FileProcessor import kotlinx.android.synthetic.main.fragment_custom_selector.* import kotlinx.android.synthetic.main.fragment_custom_selector.view.* import javax.inject.Inject /** * Custom selector folder fragment. */ class FolderFragment : CommonsDaggerSupportFragment() { /** * View Model for images. */ private var viewModel: CustomSelectorViewModel? = null /** * View Elements */ private var selectorRV: RecyclerView? = null private var loader: ProgressBar? = null /** * View Model Factory. */ var customSelectorViewModelFactory: CustomSelectorViewModelFactory? = null @Inject set var fileProcessor: FileProcessor? = null @Inject set var mediaClient: MediaClient? = null @Inject set /** * Folder Adapter. */ private lateinit var folderAdapter: FolderAdapter /** * Grid Layout Manager for recycler view. */ private lateinit var gridLayoutManager: GridLayoutManager /** * Folder List. */ private lateinit var folders : ArrayList<Folder> /** * Companion newInstance. */ companion object{ fun newInstance(): FolderFragment { return FolderFragment() } } /** * OnCreate Fragment, get the view model. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider(requireActivity(),customSelectorViewModelFactory!!).get(CustomSelectorViewModel::class.java) } /** * OnCreateView. * Inflate Layout, init adapter, init gridLayoutManager, setUp recycler view, observe the view model for result. */ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = inflater.inflate(R.layout.fragment_custom_selector, container, false) folderAdapter = FolderAdapter(activity!!, activity as FolderClickListener) gridLayoutManager = GridLayoutManager(context, columnCount()) selectorRV = root.selector_rv loader = root.loader with(root.selector_rv){ this.layoutManager = gridLayoutManager setHasFixedSize(true) this.adapter = folderAdapter } viewModel?.result?.observe(viewLifecycleOwner, Observer { handleResult(it) }) return root } /** * Handle view model result. * Get folders from images. * Load adapter. */ private fun handleResult(result: Result) { if(result.status is CallbackStatus.SUCCESS){ val images = result.images if(images.isNullOrEmpty()) { empty_text?.let { it.visibility = View.VISIBLE } } folders = ImageHelper.folderListFromImages(result.images) folderAdapter.init(folders) folderAdapter.notifyDataSetChanged() selectorRV?.let { it.visibility = View.VISIBLE } } loader?.let { it.visibility = if (result.status is CallbackStatus.FETCHING) View.VISIBLE else View.GONE } } /** * onResume * notifyDataSetChanged, rebuild the holder views to account for deleted images, folders. */ override fun onResume() { folderAdapter.notifyDataSetChanged() super.onResume() } /** * Return Column count ie span count for grid view adapter. */ private fun columnCount(): Int { return 2 // todo change column count depending on the orientation of the device. } }
apache-2.0
6386ba914f08ca02dff156f2e23b836d
29.88
130
0.672641
4.910923
false
false
false
false
andrei-heidelbacher/algostorm
algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/graphics2d/AnimationSystem.kt
1
3156
/* * Copyright 2017 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andreihh.algostorm.systems.graphics2d import com.andreihh.algostorm.core.ecs.EntityGroup import com.andreihh.algostorm.core.ecs.EntityRef import com.andreihh.algostorm.core.ecs.EntityRef.Id import com.andreihh.algostorm.core.event.Event import com.andreihh.algostorm.core.event.Subscribe import com.andreihh.algostorm.systems.Update import com.andreihh.algostorm.systems.graphics2d.TileSet.Frame import com.andreihh.algostorm.systems.graphics2d.TileSet.Companion.flags import com.andreihh.algostorm.systems.graphics2d.TileSet.Companion.applyFlags class AnimationSystem : GraphicsSystem() { private val entities: EntityGroup by context(ENTITY_POOL) private val animated get() = entities.filter { Animation::class in it } class Animate( val entityId: Id, val animation: String, val loop: Boolean ) : Event @Subscribe fun onAnimate(request: Animate) { val entity = animated[request.entityId] ?: return val animation = entity[Animation::class]?.copy( name = request.animation, elapsedMillis = 0, loop = request.loop ) ?: return val frames = tileSetCollection.getAnimation(animation.animation) if (frames != null) { val flags = entity.sprite.gid.flags val newGid = frames.first().tileId.applyFlags(flags) val sprite = entity.sprite.copy(gid = newGid) entity.set(animation) entity.set(sprite) } } private fun EntityRef.update(deltaMillis: Int) { val animation = get(Animation::class) ?: return val frames = tileSetCollection.getAnimation(animation.animation) ?: return val totalDuration = frames.sumBy(Frame::duration) val elapsedMillis = animation.elapsedMillis + deltaMillis if (elapsedMillis >= totalDuration && animation.loop) { set(animation.copy(elapsedMillis = elapsedMillis % totalDuration)) } else { set(animation.copy(elapsedMillis = minOf(elapsedMillis, totalDuration))) } var t = elapsedMillis var i = 0 do { t -= frames[i].duration i++ } while (t >= 0 && i < frames.size) val flags = sprite.gid.flags val newGid = frames[i - 1].tileId.applyFlags(flags) set(sprite.copy(gid = newGid)) } @Subscribe fun onUpdate(event: Update) { animated.forEach { it.update(event.elapsedMillis) } } }
apache-2.0
77f0c552e040b71bf65d64e554ba15b6
37.024096
84
0.672053
4.276423
false
false
false
false
lanhuaguizha/Christian
app/src/main/java/com/christian/nav/gospel/DiscipleItemView.kt
1
14412
package com.christian.nav.gospel import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.view.View import android.view.animation.AnimationUtils import androidx.appcompat.widget.AppCompatImageButton import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.christian.HistoryAndMyArticlesActivity import com.christian.R import com.christian.common.* import com.christian.common.data.Gospel import com.christian.data.Setting import com.christian.databinding.ItemDiscipleBinding import com.christian.nav.disciple.DiscipleDetailActivity import com.christian.nav.me.AboutActivity import com.christian.nav.toolbarTitle import com.christian.swipe.SwipeBackActivity import com.christian.util.* import com.christian.view.showPopupMenu /** * NavItemView/NavItemHolder is view logic of nav items. */ open class DiscipleItemView( private val binding: ItemDiscipleBinding, swipeBackActivity: SwipeBackActivity, navId: Int, ) : RecyclerView.ViewHolder(binding.root) { private lateinit var gospel: Gospel private lateinit var sharedPreferences: SharedPreferences init { // containerView.login_nav_item.setOnClickListener { // } // when (adapterPosition) { // 1 -> { // itemView.setOnClickListener { // if (isOn) { // itemView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = false // isOn = false // } else { // itemView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = true // isOn = true // } // } // } // else -> { // itemView.setOnClickListener { // val i = Intent(itemView.context, NavDetailActivity::class.java) // i.putExtra(toolbarTitle, presenter.getTitle(adapterPosition)) // itemView.context.startActivity(i) // } // } // } val displayWidth = getDisplayWidth(swipeBackActivity) val displayHeight = getDisplayHeight(swipeBackActivity) if (itemView.findViewById<AppCompatImageButton>(R.id.ib_nav_item) != null) { itemView.findViewById<AppCompatImageButton>(R.id.ib_nav_item).setOnClickListener { v: View -> // val list: ArrayList<CharSequence> = ArrayList() // list.add(Html.fromHtml(containerView.context.getString(R.string.share))) // list.add(Html.fromHtml(containerView.context.getString(R.string.favorite))) // list.add(Html.fromHtml(containerView.context.getString(R.string.translate))) // ChristianUtil.showListDialog(v.context as NavActivity, list) // showPopupMenu(v) if (auth.currentUser?.uid == gospel.userId) { actionArray = if (gospel.like.contains(auth.currentUser?.uid)) { arrayOf( swipeBackActivity.getString(R.string.action_mute), swipeBackActivity.getString(R.string.action_unfollow), swipeBackActivity.getString(R.string.action_delete), swipeBackActivity.getString(R.string.action_block) ) } else { arrayOf( swipeBackActivity.getString(R.string.action_mute), swipeBackActivity.getString(R.string.action_follow), swipeBackActivity.getString(R.string.action_delete), swipeBackActivity.getString(R.string.action_block) ) } } else { actionArray = if (gospel.like.contains(auth.currentUser?.uid)) { arrayOf( swipeBackActivity.getString(R.string.action_share), swipeBackActivity.getString(R.string.action_unfollow), ) } else { arrayOf( swipeBackActivity.getString(R.string.action_share), swipeBackActivity.getString(R.string.action_follow), ) } } showPopupMenu( v, swipeBackActivity, actionArray ) { _, text -> when (text) { actionArray[0] -> { actionShareText(swipeBackActivity, gospel.content) } actionArray[1] -> { actionFollow(gospel, navId, swipeBackActivity) } actionArray[2] -> { toEditorActivity(swipeBackActivity, navId, gospel.gospelId) } actionArray[3] -> { DeleteDialogFragment( swipeBackActivity, navId, gospel.gospelId ).show(swipeBackActivity.supportFragmentManager, "ExitDialogFragment") } } } } } // activity = navActivity } /*private fun showPopupMenu(v: View) { val popupMenu = PopupMenu(v.context, v) popupMenu.gravity = Gravity.END or Gravity.BOTTOM popupMenu.menuInflater.inflate(R.menu.menu_nav_item, popupMenu.menu) popupMenu.setOnMenuItemClickListener { false } popupMenu.show() }*/ fun initView() { // cv_nav_item.radius = 0f // cv_nav_item.foreground = null // tv_subtitle_nav_item.visibility = View.GONE // tv_title_nav_item.visibility = View.GONE // tv_detail_nav_item.textColor = ResourcesCompat.getColor(itemView.resources, R.color.text_color_primary, itemView.context.theme) // tv_detail_nav_item.textSize = 18f // tv_detail_nav_item.maxLines = Integer.MAX_VALUE } fun animateItemView(itemView: View) { val animation = AnimationUtils.loadAnimation(itemView.context, R.anim.up_from_bottom) itemView.startAnimation(animation) } fun clearItemAnimation(itemView: View) { itemView.clearAnimation() } fun bind(navId: Int, gospel: Gospel) { this.gospel = gospel val gospelImg = filterImageUrlThroughDetailPageContent(gospel.content) /*if (gospelImg.isNotBlank()) { binding.ivNavItem.visibility = View.VISIBLE Glide.with(binding.root.context).load(gospelImg).into(binding.ivNavItem) } else { binding.ivNavItem.visibility = View.GONE }*/ Glide.with(binding.root.context).load(gospel.defaultImageUrl).into(binding.ivNavItem) binding.tvTitleNavItem.text = gospel.classify binding.tvSubtitleNavItem.text = gospel.title.replace(Regex("\\d+"), "") // makeViewBlur(tv_title_nav_item, cl_nav_item, activity.window, true) if ("en" == getPropLan()) { setMarkdownToTextView(binding.root.context, binding.tvDetailNavItem, gospel.content .replace(Regex("!\\[.+\\)"), "") //跳过图片 .replace(Regex("\\#.+\\s"), "") //跳过标题 // .replace(Regex("\\s+"), "") //在跳过图片和标题的基础上,移除空白行 ) } else { setMarkdownToTextView(binding.root.context, binding.tvDetailNavItem, gospel.content .replace(Regex("!\\[.+\\)"), "") //跳过图片 .replace(Regex("\\#.+\\s"), "") //跳过标题 .replace(Regex("\\n+"), "") //在跳过图片和标题的基础上,移除空白行 ) } /*binding.tvDetailNavItem.text = gospel.content .replace(Regex("!\\[.+\\)"), "") .replace(Regex("\\#.+\\s"), "") .replace(Regex("\\s+"), "")*/ binding.textView.text = gospel.classifySubtitle /*+ "·" + gospel.author*/ + " " + gospel.createTime // textView2.text = gospel.church // textView3.text = gospel.time binding.root.setOnClickListener { startGospelDetailActivity(navId, gospel) } binding.tvTitleNavItem.setOnClickListener { // gospelId = gospel.id startGospelDetailActivity(navId, gospel) } binding.tvSubtitleNavItem.setOnClickListener { startGospelDetailActivity(navId, gospel) } binding.tvDetailNavItem.setOnClickListener { startGospelDetailActivity(navId, gospel) } binding.textView.setOnClickListener { startGospelDetailActivity(navId, gospel) } } private fun startGospelDetailActivity(navId: Int, gospel: Gospel) { val intent = Intent(binding.root.context, DiscipleDetailActivity::class.java) intent.putExtra(SUB_TITLE, gospel.classify) intent.putExtra(ACTION_BAR_TITLE, gospel.title) intent.putExtra(binding.root.context.getString(R.string.content_lower_case), gospel.content) intent.putExtra(binding.root.context.getString(R.string.author), gospel.author) // intent.putExtra(binding.root.context.getString(R.string.church_lower_case), gospel.church) intent.putExtra(binding.root.context.getString(R.string.time), gospel.createTime) intent.putExtra(GOSPEL_ID, gospel.gospelId) intent.putExtra(TAB_ID, navId) intent.putExtra(USER_ID, gospel.userId) intent.putExtra(toolbarTitle, gospel.title) binding.root.context.startActivity(intent) } private var isOn = false fun bind(setting: Setting) { when (adapterPosition) { /* 0 -> { containerView.setOnClickListener { if (isOn) { containerView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = false // 恢复应用默认皮肤 // Aesthetic.config { // activityTheme(R.style.Christian) // isDark(false) // textColorPrimary(res = R.color.text_color_primary) // textColorSecondary(res = R.color.text_color_secondary) // attribute(R.attr.my_custom_attr, res = R.color.default_background_nav) // attribute(R.attr.my_custom_attr2, res = R.color.white) // } isOn = false } else { containerView.findViewById<Switch>(R.id.switch_nav_item_small).isChecked = true // 夜间模式 // Aesthetic.config { // activityTheme(R.style.ChristianDark) // isDark(true) // textColorPrimary(res = android.R.color.primary_text_dark) // textColorSecondary(res = android.R.color.secondary_text_dark) // attribute(R.attr.my_custom_attr, res = R.color.text_color_primary) // attribute(R.attr.my_custom_attr2, res = R.color.background_material_dark) // } isOn = true } } }*/ 4 -> { binding.root.setOnClickListener { // 老的跳转设置移到了NavActivity页的options menu val i = Intent(binding.root.context, AboutActivity::class.java) i.putExtra(toolbarTitle, getTitle(setting, adapterPosition)) binding.root.context.startActivity(i) } } else -> { binding.root.setOnClickListener { val i = Intent(binding.root.context, HistoryAndMyArticlesActivity::class.java) i.putExtra(toolbarTitle, getTitle(setting, adapterPosition)) binding.root.context.startActivity(i) } } } if (adapterPosition == 0) { val sharedPreferences = binding.root.context.getSharedPreferences("christian", Activity.MODE_PRIVATE) val string = sharedPreferences.getString("sunrise", "") ?: "" val string1 = sharedPreferences.getString("sunset", "") ?: "" // switch_nav_item_small.visibility = View.VISIBLE if (string.isNotEmpty() && string.isNotEmpty()) { val sunriseString = string.substring(11, 19) val sunsetString = string1.substring(11, 19) // switch_nav_item_small.text = String.format(binding.root.context.getString(R.string.sunrise_sunset), sunriseString, sunsetString) // switch_nav_item_small.visibility = View.VISIBLE } else { // switch_nav_item_small.text = binding.root.context.getString(R.string.no_location_service) // switch_nav_item_small.visibility = View.GONE } } // tv_nav_item_small.text = setting.name // tv2_nav_item_small.text = setting.desc val url = setting.url // Glide.with(binding.root.context).load(if (CommonApp.getNightModeSP(binding.root.context)) generateUrlIdNightMode(url) else generateUrlId(url)).into(iv_nav_item_small) } private fun getTitle(setting: Setting, pos: Int): String { // return when (navId) { // VIEW_HOME, VIEW_GOSPEL, VIEW_DISCIPLE -> { // snapshots[pos].data?.get("subtitle").toString() // } // VIEW_ME -> { return when (pos) { // 0 -> { // containerView.context.getString(R.string.me) // } in 0..1 -> { setting.name } else -> "" } // } // else -> { // return "" // } } }
gpl-3.0
9361fefb25bd53250e2cf65d90379c30
43.304348
176
0.547003
4.637516
false
false
false
false
andrei-heidelbacher/algostorm
algostorm-systems/src/main/kotlin/com/andreihh/algostorm/systems/physics2d/PathFindingSystem.kt
1
4683
/* * Copyright 2017 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andreihh.algostorm.systems.physics2d import com.andreihh.algostorm.core.ecs.EntityGroup import com.andreihh.algostorm.core.ecs.EntityRef import com.andreihh.algostorm.core.ecs.EntityRef.Id import com.andreihh.algostorm.core.event.Request import com.andreihh.algostorm.core.event.Subscribe import com.andreihh.algostorm.systems.EventSystem import com.andreihh.algostorm.systems.physics2d.geometry2d.Direction import java.util.PriorityQueue class PathFindingSystem : EventSystem() { companion object { /** * Returns the path going from `source` to `destination` using the given * `directions` and avoiding the given colliders. * * @param source the source location * @param destination the destination location * @param directions the directions used for movement * @param isCollider the map which contains all colliders * @return the directions in which the `source` should move in order to * reach the `destination`, or `null` if the `destination` can't be * reached */ fun findPath( source: Position, destination: Position, directions: List<Direction>, isCollider: (Position) -> Boolean ): List<Direction>? { data class HeapNode( val p: Position, val f: Int ) : Comparable<HeapNode> { override fun compareTo(other: HeapNode): Int = f - other.f } fun hScore(p : Position): Int = Math.max( Math.abs(p.x - destination.x), Math.abs(p.y - destination.y) ) val INF = 0x0fffffff val visited = hashSetOf<Position>() val father = hashMapOf<Position, Direction>() val gScore = hashMapOf(source to 0) val fScore = hashMapOf(source to hScore(source)) val heap = PriorityQueue<HeapNode>() heap.add(HeapNode(source, fScore[source] ?: INF)) while (heap.isNotEmpty()) { val v = heap.poll().p if (v == destination) { val path = arrayListOf<Direction>() var head = destination while (head in father) { father[head]?.let { d -> path.add(d) head = head.transformed(-d.dx, -d.dy) } } path.reverse() return path } val vCost = gScore[v] ?: INF visited.add(v) for (d in directions) { val w = v.transformed(d.dx, d.dy) val wCost = gScore[w] ?: INF if (!isCollider(w) && w !in visited && vCost + 1 < wCost) { gScore[w] = vCost + 1 father[w] = d heap.add(HeapNode(w, vCost + 1 + hScore(w))) } } } return null } } private val entities: EntityGroup by context(ENTITY_POOL) class FindPath( val sourceId: Id, val destinationX: Int, val destinationY: Int, val directions: List<Direction> = Direction.ORDINAL, val ignoreColliderDestination: Boolean = true ) : Request<List<Direction>?>() @Subscribe fun onFindPath(request: FindPath) { val colliders = entities.filter { it.isCollider } .mapNotNullTo(hashSetOf(), EntityRef::position) val source = checkNotNull(entities[request.sourceId]?.position) val destination = Position(request.destinationX, request.destinationY) request.complete(findPath(source, destination, request.directions) { it in colliders && (it != destination || request.ignoreColliderDestination) }) } }
apache-2.0
7e2f658c27d0162d4bfe0ab17e6fc025
38.352941
80
0.566517
4.622902
false
false
false
false
7hens/KDroid
core/src/main/java/cn/thens/kdroid/core/app/res/States.kt
1
589
package cn.thens.kdroid.core.app.res import android.R.attr.* @Suppress("unused") object States { const val ENABLED = state_enabled const val SELECTED = state_selected const val CHECKED = state_checked const val CHECKABLE = state_checkable const val FOCUSED = state_focused const val HOVERED = state_hovered const val PRESSED = state_pressed const val ACTIVATED = state_activated const val ACTIVE = state_active const val FIRST = state_first const val MIDDLE = state_middle const val LAST = state_last const val SINGLE = state_single }
apache-2.0
15ef592747c9c61210c6c4e02b6d618b
28.45
41
0.711375
4.006803
false
false
false
false
facebook/litho
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/VerticalScroll.kt
1
2717
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.kotlin.widget import android.view.MotionEvent import androidx.core.widget.NestedScrollView import com.facebook.litho.Component import com.facebook.litho.Dimen import com.facebook.litho.ResourcesScope import com.facebook.litho.Style import com.facebook.litho.dp import com.facebook.litho.kotlinStyle import com.facebook.litho.px import com.facebook.litho.widget.VerticalScroll import com.facebook.litho.widget.VerticalScrollEventsController /** Builder function for creating [VerticalScrollSpec] components. */ @Suppress("FunctionName") inline fun ResourcesScope.VerticalScroll( initialScrollPosition: Dimen = 0.px, scrollbarEnabled: Boolean = false, scrollbarFadingEnabled: Boolean = true, verticalFadingEdgeEnabled: Boolean = false, nestedScrollingEnabled: Boolean = false, fadingEdgeLength: Dimen = 0.dp, fillViewport: Boolean = false, incrementalMountEnabled: Boolean = false, eventsController: VerticalScrollEventsController? = null, noinline onScrollChange: ((NestedScrollView, scrollY: Int, oldScrollY: Int) -> Unit)? = null, noinline onInterceptTouch: ((NestedScrollView, event: MotionEvent) -> Boolean)? = null, style: Style? = null, child: ResourcesScope.() -> Component ): VerticalScroll = VerticalScroll.create(context) .childComponent(child()) .initialScrollOffsetPixels(initialScrollPosition.toPixels()) .scrollbarEnabled(scrollbarEnabled) .scrollbarFadingEnabled(scrollbarFadingEnabled) .verticalFadingEdgeEnabled(verticalFadingEdgeEnabled) .nestedScrollingEnabled(nestedScrollingEnabled) .fadingEdgeLengthPx(fadingEdgeLength.toPixels()) .fillViewport(fillViewport) .incrementalMountEnabled(incrementalMountEnabled) .eventsController(eventsController) .apply { onScrollChange?.let { onScrollChangeListener { v, _, scrollY, _, oldScrollY -> it(v, scrollY, oldScrollY) } } } .onInterceptTouchListener(onInterceptTouch) .kotlinStyle(style) .build()
apache-2.0
fc19e6cb9dc4d048bc370fbcdeb86017
40.166667
97
0.741259
4.476112
false
false
false
false
Sevran/DnDice
app/src/main/java/io/deuxsept/dndice/Adapter/FavoriteAdapter.kt
1
4940
package io.deuxsept.dndice.Adapter import android.os.Build import android.os.Handler import android.support.v4.view.MotionEventCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import io.deuxsept.dndice.Database.DatabaseHelper import io.deuxsept.dndice.MainView.FavoriteFragment import io.deuxsept.dndice.Model.RollModel import io.deuxsept.dndice.R import io.deuxsept.dndice.Utils.ItemTouchHelperAdapter import io.deuxsept.dndice.Utils.Utils import java.util.* /** * Created by Luo * on 15/08/2016. */ class FavoriteAdapter : RecyclerView.Adapter<FavoriteAdapter.ViewHolder>, ItemTouchHelperAdapter { private lateinit var mFragment: FavoriteFragment private val mList = ArrayList<RollModel>() private var lastPosition = -1 private lateinit var mDragStartListener: OnDragStartListener private lateinit var mLocale: Locale private lateinit var mDb: DatabaseHelper @Suppress("DEPRECATION") constructor(fragment: FavoriteFragment, dragStartListener: OnDragStartListener) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) mLocale = fragment.context.resources.configuration.locales.get(0) else mLocale = fragment.context.resources.configuration.locale mFragment = fragment mDragStartListener = dragStartListener mDb = DatabaseHelper(fragment.context) } interface OnDragStartListener { fun onDragStarted(viewHolder: RecyclerView.ViewHolder) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var mLayout: View var mBackground: View var mForeground: View internal var mFormula: TextView internal var mReorderButton: ImageView internal var mName: TextView init { mLayout = itemView.findViewById(R.id.row_layout) mBackground = itemView.findViewById(R.id.background) mForeground = itemView.findViewById(R.id.foreground) mFormula = itemView.findViewById(R.id.recent_formula) as TextView mReorderButton = itemView.findViewById(R.id.fav_reorder_button) as ImageView mName = itemView.findViewById(R.id.favorite_name) as TextView } internal fun clearAnimation() { mLayout.clearAnimation() } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteAdapter.ViewHolder { val itemView = LayoutInflater.from(mFragment.context).inflate(R.layout.row_favorite, parent, false) return ViewHolder(itemView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val model: RollModel = mList[position] holder.mFormula.text = model.formula holder.mName.text = if (model.name.trim() != "") model.name else "Unnamed" holder.mReorderButton.setOnTouchListener { v, event -> if (MotionEventCompat.getActionMasked(event) === MotionEvent.ACTION_DOWN) mDragStartListener.onDragStarted(holder) false } val animation = AnimationUtils.loadAnimation(mFragment.context, R.anim.item_slide_in_from_left) setAnimation(holder.mLayout, position, animation) } private fun setAnimation(viewToAnimate: View, position: Int, animation: Animation) { if (position > lastPosition) { viewToAnimate.startAnimation(animation) lastPosition = position } } override fun onViewDetachedFromWindow(holder: ViewHolder) { holder.clearAnimation() } override fun onItemMove(fromPosition: Int, toPosition: Int) { val prev = mList.removeAt(fromPosition) mList.add(if (toPosition > fromPosition) toPosition - 1 else toPosition, prev) notifyItemMoved(fromPosition, toPosition) } override fun onItemMoved(fromPosition: Int, toPosition: Int) { Handler().postDelayed({ var i: Int = 0 for ((formula, result, detail, name, id) in mList) { Utils.log_d("onItemMove", "Reordering $formula to position $i") mDb.reorderFavoriteRoll(id, i) i++ } }, 500) } fun addAll(models: List<RollModel>) { mList.addAll(models) notifyDataSetChanged() } override fun getItemCount(): Int { return mList.count() } fun getItem(position: Int) : RollModel { return mList[position] } fun removeItem(position: Int) { mList.removeAt(position) notifyItemRemoved(position) } fun addItem(pos: Int, model: RollModel) { mList.add(pos, model) notifyItemInserted(pos) } }
mit
88ddf880c53db617534b6460aafb9425
33.795775
107
0.686032
4.490909
false
false
false
false
google/kiosk-app-reference-implementation
app/src/main/java/com/ape/apps/sample/baypilot/data/FieldNames.kt
1
1057
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ape.apps.sample.baypilot.data object FieldNames { const val imei = "Imei" const val firebaseToken = "FirebaseToken" object CreditPlanInfo { const val plan = "Plan" object Plan { const val totalAmount = "Total Amount" const val dueDate = "Due Date" const val nextInstallmentAmount = "Next Installment Amount" const val planType = "Plan Type" const val totalPaidAmount = "Total Paid Amount" } } }
apache-2.0
42dbabb7e34821f8eb7d07506c35d479
28.388889
75
0.708609
4.065385
false
false
false
false
vilnius/tvarkau-vilniu
app/src/test/java/lt/vilnius/tvarkau/auth/OauthTokenRefresherTest.kt
1
5843
package lt.vilnius.tvarkau.auth import com.nhaarman.mockito_kotlin.* import com.vinted.preferx.ObjectPreference import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import lt.vilnius.tvarkau.api.ApiHeadersInterceptor import lt.vilnius.tvarkau.api.ApiHeadersInterceptor.Companion.HTTP_HEADER_OAUTH import lt.vilnius.tvarkau.entity.City import lt.vilnius.tvarkau.prefs.AppPreferences import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.mockwebserver.Dispatcher import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import org.junit.Test import java.util.concurrent.TimeUnit class OauthTokenRefresherTest { val oldToken = ApiToken(accessToken = "old") val newToken = ApiToken(accessToken = "new") private val dispatcher = object : Dispatcher() { override fun dispatch(request: RecordedRequest): MockResponse { return if (request.getHeader(HTTP_HEADER_OAUTH) == formatTokenForHeader(oldToken.accessToken)) { MockResponse().setResponseCode(401) } else if (request.getHeader(HTTP_HEADER_OAUTH) == formatTokenForHeader(newToken.accessToken)) { MockResponse().setResponseCode(200) } else { throw RuntimeException("Token is not supported") } } } private val webServer: MockWebServer = MockWebServer().apply { setDispatcher(dispatcher) } private val cityPreference = mock<ObjectPreference<City>> { onGeneric { get() } doReturn City.NOT_SELECTED } private val apiTokenPref = ApiTokenPref(oldToken) private val appPreferences: AppPreferences = mock { on { apiToken } doReturn apiTokenPref on { selectedCity } doReturn cityPreference } private val sessionToken: SessionToken = mock { on { refreshCurrentToken(any()) } doAnswer { Completable.complete().delay(100, TimeUnit.MILLISECONDS).doOnComplete { apiTokenPref.set(newToken) } } } private val apiHeadersInterceptor = ApiHeadersInterceptor(appPreferences) val fixture = OauthTokenRefresher(appPreferences, sessionToken, apiHeadersInterceptor) private val client = OkHttpClient.Builder() .addInterceptor(apiHeadersInterceptor) .addInterceptor(fixture) .build() private val ioScheduler = Schedulers.io() @Test fun multipleRequests_onlyOneTokenRefresh() { Flowable.range(1, 50).flatMap({ Flowable.fromCallable { val request = Request.Builder().url(webServer.url("/")).build() client.newCall(request).execute() }.subscribeOn(ioScheduler) }, true, 50, 50).blockingLast() verify(sessionToken, only()).refreshCurrentToken(oldToken) } @Test fun multipleRequests_allSuccess() { Flowable.range(1, 50).flatMap({ Flowable.fromCallable { val request = Request.Builder().url(webServer.url("/")).build() client.newCall(request).execute() }.subscribeOn(ioScheduler) }, true, 50, 50).filter { it.code() == 200 }.test().await().assertValueCount(50) } @Test fun multipleRequests_failedRefreshToken() { val error = RuntimeException("failed") whenever(sessionToken.refreshCurrentToken(any())).thenReturn(Completable.error(error)) Flowable.range(1, 50).flatMap({ Flowable.fromCallable { val request = Request.Builder().url(webServer.url("/")).build() client.newCall(request).execute() }.subscribeOn(ioScheduler) }, true, 50, 50) .timeout(10000, TimeUnit.MILLISECONDS) .filter { it.code() == 500 } .test().await().assertValueCount(50) } @Test fun multipleRequests_refreshServerIsRestoredEventually() { val error = RuntimeException("failed") whenever(sessionToken.refreshCurrentToken(any())).thenReturn(Completable.error(error)) //add noise before and in the middle. Flowable.range(1, 50) .delay { Flowable.just(0).delay(it / 30L, TimeUnit.SECONDS) } .flatMap({ Flowable.fromCallable { val request = Request.Builder().url(webServer.url("/")).build() client.newCall(request).execute() }.subscribeOn(ioScheduler) }, true, 50, 50) .test() //server is revived whenever(sessionToken.refreshCurrentToken(any())).doAnswer { Completable.complete().delay(100, TimeUnit.MILLISECONDS).doOnComplete { apiTokenPref.set(newToken) } } //check is all next request succeed Flowable.range(1, 50).flatMap({ Flowable.fromCallable { val request = Request.Builder().url(webServer.url("/")).build() client.newCall(request).execute() }.subscribeOn(ioScheduler) }, true, 50, 50).filter { it.code() == 200 }.test().await().assertValueCount(50) } fun formatTokenForHeader(token: String) = "Bearer $token" class ApiTokenPref(private var current: ApiToken) : ObjectPreference<ApiToken> { override fun set(value: ApiToken, commit: Boolean) { current = value } override fun get(): ApiToken = current override fun delete() { throw UnsupportedOperationException("not implemented") } override fun isSet() = true override val onChangeObservable: Observable<ApiToken> get() = throw RuntimeException("Not implemented") } }
mit
c109781aa5b7dbe25bf7b17835f72080
35.067901
108
0.641622
4.901846
false
true
false
false
rock3r/detekt
detekt-formatting/src/test/kotlin/io/gitlab/arturbosch/detekt/formatting/AutoCorrectLevelSpec.kt
1
4270
package io.gitlab.arturbosch.detekt.formatting import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.FileProcessListener import io.gitlab.arturbosch.detekt.api.Finding import io.gitlab.arturbosch.detekt.core.DetektFacade import io.gitlab.arturbosch.detekt.core.rules.visitFile import io.gitlab.arturbosch.detekt.test.createProcessingSettings import io.gitlab.arturbosch.detekt.test.loadRuleSet import io.gitlab.arturbosch.detekt.test.resource import io.gitlab.arturbosch.detekt.test.yamlConfig import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.psi.KtFile import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.nio.file.Paths class AutoCorrectLevelSpec : Spek({ describe("test different autoCorrect levels in configuration") { describe("autoCorrect: true on all levels") { val config = yamlConfig("/autocorrect/autocorrect-all-true.yml") it("should reformat the test file") { val (file, findings) = runAnalysis(config) assertThat(wasLinted(findings)).isTrue() assertThat(wasFormatted(file)).isTrue() } } describe("autoCorrect: false on top level") { val config = yamlConfig("/autocorrect/autocorrect-toplevel-false.yml") it("should format the test file but not print to disc") { val project = Paths.get(resource("configTests/fixed.kt")) var expectedContentBeforeRun: String? = null val contentChanged = object : FileProcessListener { override fun onStart(files: List<KtFile>) { assertThat(files).hasSize(1) expectedContentBeforeRun = files[0].text } override fun onFinish(files: List<KtFile>, result: Detektion) { assertThat(files).hasSize(1) assertThat(wasFormatted(files[0])).isTrue() } } val result = createProcessingSettings(project, config).use { DetektFacade.create(it, listOf(FormattingProvider()), listOf(contentChanged)).run() } val findings = result.findings.flatMap { it.value } val actualContentAfterRun = loadFileContent("configTests/fixed.kt") assertThat(wasLinted(findings)).isTrue() assertThat(actualContentAfterRun).isEqualTo(expectedContentBeforeRun) } } describe("autoCorrect: false on ruleSet level") { val config = yamlConfig("/autocorrect/autocorrect-ruleset-false.yml") it("should not reformat the test file") { val (file, findings) = runAnalysis(config) assertThat(wasLinted(findings)).isTrue() assertThat(wasFormatted(file)).isFalse() } } describe("autoCorrect: false on rule level") { val config = yamlConfig("/autocorrect/autocorrect-rule-false.yml") it("should not reformat the test file") { val (file, findings) = runAnalysis(config) assertThat(wasLinted(findings)).isTrue() assertThat(wasFormatted(file)).isFalse() } } describe("autoCorrect: true but rule active false") { val config = yamlConfig("/autocorrect/autocorrect-true-rule-active-false.yml") it("should not reformat the test file") { val (file, findings) = runAnalysis(config) assertThat(wasLinted(findings)).isFalse() assertThat(wasFormatted(file)).isFalse() } } } }) private fun runAnalysis(config: Config): Pair<KtFile, List<Finding>> { val testFile = loadFile("configTests/fixed.kt") val ruleSet = loadRuleSet<FormattingProvider>(config) val findings = ruleSet.visitFile(testFile) return testFile to findings } private fun wasLinted(findings: List<Finding>) = findings.isNotEmpty() private fun wasFormatted(file: KtFile) = file.text == contentAfterChainWrapping
apache-2.0
1a0fa363755483501937a408ed72bfc6
39.283019
103
0.636534
4.723451
false
true
false
false
rock3r/detekt
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/AnnotationExcluder.kt
1
1397
package io.gitlab.arturbosch.detekt.api import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtFile /** * Primary use case for an AnnotationExcluder is to decide if a KtElement should be * excluded from further analysis. This is done by checking if a special annotation * is present over the element. */ class AnnotationExcluder( root: KtFile, private val excludes: List<String> ) { constructor(root: KtFile, excludes: SplitPattern) : this(root, excludes.mapAll { it }) private val resolvedAnnotations = root.importList ?.imports ?.asSequence() ?.filterNot { it.isAllUnder } ?.mapNotNull { it.importedFqName?.asString() } ?.map { it.substringAfterLast('.') to it } ?.toMap() ?: emptyMap() /** * Is true if any given annotation name is declared in the SplitPattern * which basically describes entries to exclude. */ fun shouldExclude(annotations: List<KtAnnotationEntry>): Boolean = annotations.firstOrNull(::isExcluded) != null private fun isExcluded(annotation: KtAnnotationEntry): Boolean { val annotationText = annotation.typeReference?.text val value = resolvedAnnotations[annotationText] ?: annotationText return if (value == null) false else excludes.any { value.contains(it, ignoreCase = true) } } }
apache-2.0
81558ceb752832c7ebaab18f62e4e7e9
35.763158
99
0.683608
4.817241
false
false
false
false
ldebello/hackerrank
src/main/scala/com/hacerkrank/algorithms/search/hackerland_radio_transmitters/Solution.kt
1
764
package com.hacerkrank.algorithms.search.hackerland_radio_transmitters import java.util.TreeSet fun main(args : Array<String>) { val values = readLine()!!.split(" ") val houses = readLine()!!.split(" ") val numberOfHouses = values[0].toInt() val range = values[1].toInt() val data = TreeSet<Int>() for (index in 0..numberOfHouses - 1) { val currentHouse = houses[index].toInt() data.add(currentHouse) } var counter = 0 var nextTarget = data.first() data.forEach { if (it >= nextTarget) { val optimalTarget = it + range val realTarget = data.floor(optimalTarget) nextTarget = realTarget + range + 1 counter++ } } print(counter) }
mit
8044e8055fdcd7e7a737c7c1ff27b464
22.90625
70
0.592932
3.958549
false
false
false
false
sabi0/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/ImageCollector.kt
1
11535
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.intellij.build.images import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleSourceRoot import java.io.File import java.util.* import java.util.regex.Matcher import java.util.regex.Pattern import kotlin.collections.ArrayList internal class ImagePaths(val id: String, val sourceRoot: JpsModuleSourceRoot, val phantom: Boolean) { private var flags: ImageFlags = ImageFlags() private var images: MutableList<File> = ArrayList() fun addImage(file: File, fileFlags: ImageFlags) { images.add(file) flags = mergeImageFlags(flags, fileFlags, file.path) } val files: List<File> get() = images fun getFiles(vararg types: ImageType): List<File> = files.filter { ImageType.fromFile(it) in types } val file: File? get() = getFiles(ImageType.BASIC) .sortedBy { ImageExtension.fromFile(it) } .firstOrNull() val presentablePath: File get() = file ?: files.first() ?: File("<unknown>") val used: Boolean get() = flags.used val deprecated: Boolean get() = flags.deprecation != null val deprecation: DeprecationData? get() = flags.deprecation } class ImageFlags(val skipped: Boolean, val used: Boolean, val deprecation: DeprecationData?) { constructor() : this(false, false, null) } data class DeprecationData(val comment: String?, val replacement: String?, val replacementContextClazz: String?) internal class ImageCollector(val projectHome: File, val iconsOnly: Boolean = true, val ignoreSkipTag: Boolean = false) { private val icons = HashMap<String, ImagePaths>() private val phantomIcons = HashMap<String, ImagePaths>() private val usedIconsRobots: MutableSet<File> = HashSet() fun collect(module: JpsModule, includePhantom: Boolean = false): List<ImagePaths> { module.sourceRoots.forEach { processRoot(it) } val result = ArrayList(icons.values.toList()) if (includePhantom) { result += phantomIcons.values.toList() } return result } fun printUsedIconRobots() { usedIconsRobots.forEach { println("Found icon-robots: $it") } } private fun processRoot(sourceRoot: JpsModuleSourceRoot) { val root = sourceRoot.file if (!root.exists()) return if (!JavaModuleSourceRootTypes.PRODUCTION.contains(sourceRoot.rootType)) return val iconsRoot = downToRoot(root) if (iconsRoot == null) return val rootRobotData = upToProjectHome(root) if (rootRobotData.isSkipped(root)) return val robotData = rootRobotData.fork(iconsRoot, root) processDirectory(iconsRoot, sourceRoot, robotData, emptyList()) processPhantomIcons(iconsRoot, sourceRoot, robotData, emptyList()) } private fun processDirectory(dir: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) { dir.children.forEach { file -> if (robotData.isSkipped(file)) return@forEach if (file.isDirectory) { val root = sourceRoot.file val childRobotData = robotData.fork(file, root) val childPrefix = prefix + file.name processDirectory(file, sourceRoot, childRobotData, childPrefix) if (childRobotData != robotData) { processPhantomIcons(file, sourceRoot, childRobotData, childPrefix) } } else if (isImage(file, iconsOnly)) { processImageFile(file, sourceRoot, robotData, prefix) } } } private fun processImageFile(file: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) { val id = ImageType.getBasicName(file, prefix) val flags = robotData.getImageFlags(file) if (flags.skipped) return val iconPaths = icons.computeIfAbsent(id, { ImagePaths(id, sourceRoot, false) }) iconPaths.addImage(file, flags) } private fun processPhantomIcons(root: File, sourceRoot: JpsModuleSourceRoot, robotData: IconRobotsData, prefix: List<String>) { for (icon in robotData.getOwnDeprecatedIcons()) { val iconFile = File(root, icon.first) val id = ImageType.getBasicName(icon.first, prefix) if (icons.containsKey(id)) continue val paths = ImagePaths(id, sourceRoot, true) paths.addImage(iconFile, icon.second) if (phantomIcons.containsKey(id)) { val otherPaths = phantomIcons[id]!! throw Exception("Duplicated phantom icon found: $id\n${root.path}/${ROBOTS_FILE_NAME}") } phantomIcons.put(id, paths) } } private fun upToProjectHome(dir: File): IconRobotsData { if (FileUtil.filesEqual(dir, projectHome)) return IconRobotsData() val parent = dir.parentFile ?: return IconRobotsData() return upToProjectHome(parent).fork(parent, projectHome) } private fun downToRoot(dir: File): File? { val answer = downToRoot(dir, dir, null, IconRobotsData()) return if (answer == null || answer.isDirectory) answer else answer.parentFile } private fun downToRoot(root: File, file: File, common: File?, robotData: IconRobotsData): File? { if (robotData.isSkipped(file)) return common if (file.isDirectory) { val childRobotData = robotData.fork(file, root) var childCommon = common file.children.forEach { childCommon = downToRoot(root, it, childCommon, childRobotData) } return childCommon } else if (isImage(file, iconsOnly)) { if (common == null) return file return FileUtil.findAncestor(common, file) } else { return common } } private inner class IconRobotsData(private val parent: IconRobotsData? = null) { private val skip: MutableList<Matcher> = ArrayList() private val used: MutableList<Matcher> = ArrayList() private val deprecated: MutableList<Pair<Matcher, DeprecationData>> = ArrayList() private val ownDeprecatedIcons: MutableList<Pair<String, DeprecationData>> = ArrayList() fun getImageFlags(file: File): ImageFlags { val isSkipped = !ignoreSkipTag && matches(file, skip) val isUsed = matches(file, used) val deprecationData = findDeprecatedData(file) val ourFlags = ImageFlags(isSkipped, isUsed, deprecationData) val parentFlags = parent?.getImageFlags(file) ?: ImageFlags() return mergeImageFlags(ourFlags, parentFlags, file.path) } fun getOwnDeprecatedIcons(): List<Pair<String, ImageFlags>> { return ownDeprecatedIcons.map { Pair(it.first, ImageFlags(false, false, it.second)) } } fun isSkipped(file: File): Boolean = getImageFlags(file).skipped fun fork(dir: File, root: File): IconRobotsData { val robots = File(dir, ROBOTS_FILE_NAME) if (!robots.exists()) return this usedIconsRobots.add(robots) val answer = IconRobotsData(this) parse(robots, Pair("skip:", { value -> answer.skip += compilePattern(dir, root, value) }), Pair("used:", { value -> answer.used += compilePattern(dir, root, value) }), Pair("deprecated:", { value -> val comment = StringUtil.nullize(value.substringAfter(";", "").trim()) val valueWithoutComment = value.substringBefore(";") val pattern = valueWithoutComment.substringBefore("->").trim() val replacementString = StringUtil.nullize(valueWithoutComment.substringAfter("->", "").trim()) val replacement = replacementString?.substringAfter('@')?.trim() val replacementContextClazz = StringUtil.nullize(replacementString?.substringBefore('@', "")?.trim()) val deprecatedData = DeprecationData(comment, replacement, replacementContextClazz) answer.deprecated += Pair(compilePattern(dir, root, pattern), deprecatedData) if (!pattern.contains('*') && !pattern.startsWith('/')) { answer.ownDeprecatedIcons.add(Pair(pattern, deprecatedData)) } }), Pair("name:", { value -> }), // ignore directive for IconsClassGenerator Pair("#", { value -> }) // comment ) return answer } private fun parse(robots: File, vararg handlers: Pair<String, (String) -> Unit>) { robots.forEachLine { line -> if (line.isBlank()) return@forEachLine for (h in handlers) { if (line.startsWith(h.first)) { h.second(StringUtil.trimStart(line, h.first)) return@forEachLine } } throw Exception("Can't parse $robots. Line: $line") } } private fun compilePattern(dir: File, root: File, value: String): Matcher { var pattern = value.trim() if (pattern.startsWith("/")) { pattern = root.absolutePath + pattern } else { pattern = dir.absolutePath + '/' + pattern } val regExp = FileUtil.convertAntToRegexp(pattern, false) try { return Pattern.compile(regExp).matcher("") } catch (e: Exception) { throw Exception("Cannot compile pattern: $pattern. Built on based in $dir/$ROBOTS_FILE_NAME") } } private fun findDeprecatedData(file: File): DeprecationData? { val basicPath = getBasicPath(file) return deprecated.find { it.first.reset(basicPath).matches() }?.second } private fun matches(file: File, matcher: List<Matcher>): Boolean { val basicPath = getBasicPath(file) return matcher.any { it.reset(basicPath).matches() } } private fun getBasicPath(file: File): String { val path = file.absolutePath.replace('\\', '/') val pathWithoutExtension = FileUtilRt.getNameWithoutExtension(path) val extension = FileUtilRt.getExtension(path) val basicPathWithoutExtension = ImageType.stripSuffix(pathWithoutExtension) val basicPath = basicPathWithoutExtension + if (extension.isNotEmpty()) "." + extension else "" return basicPath } } companion object { const val ROBOTS_FILE_NAME: String = "icon-robots.txt" } } private fun mergeImageFlags(flags1: ImageFlags, flags2: ImageFlags, comment: String): ImageFlags { return ImageFlags(flags1.skipped || flags2.skipped, flags1.used || flags2.used, mergeDeprecations(flags1.deprecation, flags2.deprecation, comment)) } private fun mergeDeprecations(data1: DeprecationData?, data2: DeprecationData?, comment: String): DeprecationData? { if (data1 == null) return data2 if (data2 == null) return data1 if (data1 == data2) return data1 throw AssertionError("Different deprecation statements found for icon: $comment\n$data1\n$data2") }
apache-2.0
c1abaa782518782857ef49a26149d3a7
35.046875
129
0.671175
4.532417
false
false
false
false
chandilsachin/DietTracker
app/src/main/java/com/chandilsachin/diettracker/ui/FoodDiaryFragment.kt
1
4777
package com.chandilsachin.diettracker.ui import android.arch.lifecycle.Observer import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.chandilsachin.diettracker.R import com.chandilsachin.diettracker.adapters.DietListAdapter import com.chandilsachin.diettracker.database.DietFood import com.chandilsachin.diettracker.database.PersonalizedFood import com.chandilsachin.diettracker.model.Date import com.chandilsachin.diettracker.other.InitPreferences import com.chandilsachin.diettracker.util.* import com.chandilsachin.diettracker.util.annotation.RequiresTagName import com.chandilsachin.diettracker.view_model.MainActivityModel import kotlinx.android.synthetic.main.fragment_food_diary.* import kotlinx.android.synthetic.main.layout_meal_listing.* import kotlinx.android.synthetic.main.toolbar_layout.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import kotlin.properties.Delegates @RequiresTagName("FoodDiaryFragment") class FoodDiaryFragment : BaseFragment() { var date: Date by Delegates.notNull() val model: MainActivityModel by lazy { initViewModel(MainActivityModel::class.java) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_food_diary, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { init() setEvents() setUpDatabase() prepareDietList() super.onViewCreated(view, savedInstanceState) } fun init() { recyclerViewDietList.layoutManager = LinearLayoutManager(context) date = arguments.getSerializable(DATE) as Date textViewDate.text = date.getPrettyDate() if(!date.equals(Date())) relativeLayoutAddFood.visibility = View.GONE } private fun setUpDatabase() { doAsync { if (!InitPreferences(context).hasDataLoaded()) { model.prepareInitDatabase() InitPreferences(context).setDataHasLoaded(true) } } } private fun prepareDietList() { val adapter = DietListAdapter(context, date.equals(Date())) recyclerViewDietList.adapter = adapter model.personalisedFoodList.observe(this, Observer { list -> list?.let { adapter.foodList = list setFact(list) adapter.notifyDataSetChanged() } }) fetchFoodList() adapter.onItemDeleteClick = { food -> val foodObj = PersonalizedFood() foodObj.foodId = food.id foodObj.date = date doAsync { model.deleteDietFood(foodObj) uiThread { fetchFoodList() } } } adapter.onItemEditClick = { food -> loadFragment(R.id.frameLayoutFragment, FoodDetailsFragment.getInstance(food.id, true, getAppCompactActivity())) } } private fun fetchFoodList() { doAsync { val uiTask = model.fetchFoodListOn(date) uiThread { uiTask() } } } private fun setFact(list: List<DietFood>) { var calorie: Double = 0.0 var protein: Double = 0.0 var carbs: Double = 0.0 var fat: Double = 0.0 for (item in list) { calorie += item.calories * item.quantity protein += item.protein * item.quantity carbs += item.carbs * item.quantity fat += item.fat * item.quantity } textViewTotalCalories.text = calorie.toDecimal(2) textViewTotalProtein.text = protein.toDecimal(2) + "g" textViewTotalCarbs.text = carbs.toDecimal(2) + "g" textViewTotalFat.text = fat.toDecimal(2) + "g" } fun setEvents() { relativeLayoutAddFood.setOnClickListener { loadFragment(R.id.frameLayoutFragment, FoodListFragment.getInstance(activity)) } } companion object { private val DATE = "foodDiaryFragment.date" fun getInstance(date: Date = Date(), activity: FragmentActivity? = null): Fragment { var fragment = findInstance(activity) if (fragment == null) { fragment = FoodDiaryFragment() } val bundle = Bundle() bundle.putSerializable(DATE, date) fragment.arguments = bundle return fragment } } }
gpl-3.0
21bea23c08560b484dde1e371b7afebc
31.503401
117
0.645175
4.692534
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/setup/SetupActivity.kt
1
2960
package com.andreapivetta.blu.ui.setup import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.support.v4.content.LocalBroadcastManager import android.support.v7.app.AppCompatActivity import com.andreapivetta.blu.R import com.andreapivetta.blu.common.settings.AppSettingsFactory import com.andreapivetta.blu.common.utils.visible import com.andreapivetta.blu.data.jobs.PopulateDatabaseIntentService import kotlinx.android.synthetic.main.activity_setup.* import timber.log.Timber class SetupActivity : AppCompatActivity() { companion object { private val ARG_DOWNLOAD = "download" fun launch(context: Context) { context.startActivity(Intent(context, SetupActivity::class.java)) } } private var downloadStarted = false private val responseReceiver = ResponseReceiver() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_setup) setSupportActionBar(setupToolbar) if (savedInstanceState != null && savedInstanceState.getBoolean(ARG_DOWNLOAD, false)) updateViewForDownload() LocalBroadcastManager.getInstance(this).registerReceiver(responseReceiver, IntentFilter(PopulateDatabaseIntentService.BROADCAST_ACTION)) val settings = AppSettingsFactory.getAppSettings(this) startDownloadButton.setOnClickListener { settings.setNotifyDirectMessages(directMessagesCheckBox.isChecked) settings.setNotifyFavRet(favRetCheckBox.isChecked) settings.setNotifyFollowers(followersCheckBox.isChecked) settings.setNotifyMentions(mentionsCheckBox.isChecked) PopulateDatabaseIntentService.startService(this) updateViewForDownload() } } override fun onBackPressed() { moveTaskToBack(true) } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) outState?.putBoolean(ARG_DOWNLOAD, downloadStarted) } override fun onDestroy() { super.onDestroy() LocalBroadcastManager.getInstance(this).unregisterReceiver(responseReceiver) } private fun updateViewForDownload() { downloadStarted = true setupViewGroup.visible(false) loadingViewGroup.visible() } private inner class ResponseReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Timber.i("Broadcast received") if (intent != null && intent.getBooleanExtra(PopulateDatabaseIntentService.DATA_STATUS, false)) { [email protected]() } else { PopulateDatabaseIntentService.startService(this@SetupActivity) } } } }
apache-2.0
70409eed126840e149013beccb0091f4
34.238095
95
0.713176
5.352622
false
false
false
false
Finnerale/FileBase
src/main/kotlin/de/leopoldluley/filebase/view/CreatorView.kt
1
11109
package de.leopoldluley.filebase.view import de.leopoldluley.filebase.controller.TypeCtrl import de.leopoldluley.filebase.Utils import de.leopoldluley.filebase.components.TagField.Companion.tagField import de.leopoldluley.filebase.controller.DataCtrl import de.leopoldluley.filebase.controller.SettingsCtrl import de.leopoldluley.filebase.models.Entry import de.leopoldluley.filebase.models.EntryModel import de.leopoldluley.filebase.Extensions.internalAlert import de.leopoldluley.filebase.models.FileType import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleObjectProperty import javafx.event.ActionEvent import javafx.geometry.Insets import javafx.geometry.Pos import javafx.scene.image.Image import javafx.scene.layout.Priority import javafx.scene.paint.Color import javafx.stage.FileChooser import tornadofx.* import java.io.File import java.io.FileInputStream import java.nio.file.Path import java.nio.file.Paths class CreatorView : View() { private val dataCtrl: DataCtrl by inject() private val settingsCtrl: SettingsCtrl by inject() private val typeCtrl: TypeCtrl by inject() private val model = EntryModel(Entry()) private var source: Path? = null private var isForeignFileType = false private val moveFile = SimpleBooleanProperty(settingsCtrl.moveFilesByDefaultProperty.value) private val previewProperty = SimpleObjectProperty<Image>() private val bigPreviewProperty = SimpleBooleanProperty(false) private val finishing = SimpleBooleanProperty(false) override fun onDock() { super.onDock() if (dataCtrl.addQueue.isNotEmpty()) { openFile(dataCtrl.addQueue.first()) } else { model.rebind { Entry() } } } override val root = stackpane { title = "FileBase - " + messages["creatorTitle"] hbox { vbox { minWidth = 200.0 prefWidth = 400.0 padding = Insets(10.0) spacing = 10.0 listview(dataCtrl.addQueue) { vgrow = Priority.ALWAYS disableWhen(finishing) cellCache { label(it.fileName.toString()) { tooltip(it.toString()) } } onUserSelect(clickCount = 1) { openFile(it) } } imageview { alignment = Pos.CENTER isPreserveRatio = true fitWidth = 200.0 fitHeight = 200.0 imageProperty().bind(previewProperty) removeWhen(previewProperty.isNull) setOnMouseEntered { bigPreviewProperty.value = true } } hbox { spacing = 10.0 button(messages["clear"]) { prefWidth = [email protected] / 2 disableWhen(finishing) action { dataCtrl.addQueue.clear() goBack() } } button(messages["back"]) { prefWidth = [email protected] / 2 isCancelButton = true disableWhen(finishing) action { goBack() } } } } form { minWidth = 400.0 hgrow = Priority.ALWAYS fieldset { padding = Insets(0.0) field(messages["path"]) { textfield(model.file) { hgrow = Priority.ALWAYS validator { if (it.isNullOrBlank()) error(messages["errorMustChooseFile"]) else if (!File(it).exists()) error(messages["errorFileNotExists"]) else null } } button(messages["select"]) { setOnAction { openFile() } } } field(messages["name"]) { textfield(model.name) { validator { if (it.isNullOrBlank()) error(messages["errorNameRequired"]) else if (!dataCtrl.checkFileName(it!!)) error(messages["errorIllegalName"]) else null } } } field(messages["tags"]) { tagField(model.tags, dataCtrl.tags) { validator { if (it!!.trim().split(" ").size < 2) return@validator warning(messages["warnFewTags"]) Utils.splitTags(it).forEach { if (!dataCtrl.checkTagName(it)) return@validator error(messages["errorIllegalTag"].replace("#name", it)) } return@validator null } } } field(messages["note"]) { textarea(model.note) { prefHeight = 150.0 } } field("Type") { choicebox(model.type, FileType.Values) } field(messages["moveFile"]) { checkbox(property = moveFile) { isDisable = modalStage != null } } field(forceLabelIndent = true) { button(messages["cancel"]) { disableWhen(finishing) action { cancelCreation() } } button(messages["finishCreation"]) { disableWhen(finishing) setOnAction { finish() } } } } } } stackpane { visibleWhen(bigPreviewProperty) alignment = Pos.CENTER padding = Insets(20.0) style { backgroundColor += Color.color(0.3, 0.3, 0.3, 0.5) } imageview { alignment = Pos.CENTER isPreserveRatio = true imageProperty().bind(previewProperty) [email protected]().onChange { this.fitWidth = it - 40.0 } [email protected]().onChange { this.fitHeight = it - 40.0 } setOnMouseExited { bigPreviewProperty.value = false } setOnMouseClicked { bigPreviewProperty.value = false } setOnTouchReleased { bigPreviewProperty.value = false } } setOnMouseClicked { bigPreviewProperty.value = false } setOnTouchReleased { bigPreviewProperty.value = false } } stackpane { visibleWhen(finishing) style { backgroundColor += Color.color(0.3, 0.3, 0.3, 0.5) } progressindicator { maxWidth = 200.0 maxHeight = 200.0 } } } private fun cancelCreation() { dataCtrl.addQueue.remove(source) if (dataCtrl.addQueue.isEmpty()) { goBack() } else { openFile(dataCtrl.addQueue.first()) } } fun finish() { model.commit { finishing.value = true runAsync<Boolean> { dataCtrl.createEntry(model.entry, moveFile.value) } ui { finishing.value = false if (it) { if (isForeignFileType && source != null) { isForeignFileType = false typeCtrl.setType(source!!, model.entry.type) } dataCtrl.addQueue.remove(source) if (dataCtrl.addQueue.isEmpty()) { goBack() } else { openFile(dataCtrl.addQueue.first()) } } else { openInternalBuilderWindow(messages["finishCreationErrorTitle"]) { internalAlert(messages["finishCreationErrorTitle"], messages["finishCreationErrorText"]) { [email protected]() } } } } } } private fun openFile(path: Path? = null) { var file = path if (file == null) { val fileChooser = FileChooser() fileChooser.title = messages["selectTitle"] fileChooser.initialDirectory = File(System.getProperty("user.home")) val userFile = fileChooser.showOpenDialog(FX.primaryStage) if (userFile != null) { file = userFile.toPath() } } if (file != null) { model.file.value = file.toAbsolutePath().toString() model.name.value = if (settingsCtrl.includeExtension) file.fileName.toString() else Utils.getFileName(file).trim() val type = typeCtrl.getType(file) model.type.value = if (type != null) { isForeignFileType = false type } else { isForeignFileType = true FileType.Other } source = file val extension = Utils.getFileExtension(file) if (extension == "png" || extension == "jpg" || extension == "gif") { previewProperty.value = Image(FileInputStream(file.toFile())) } else { previewProperty.value = null } moveFile.value = file.toAbsolutePath().startsWith(Paths.get(settingsCtrl.depotPath).toAbsolutePath()) } else { model.rebind { Entry() } } } private fun goBack() { replaceWith(MainView::class, ViewTransition.Slide(300.millis, ViewTransition.Direction.RIGHT)) } }
mit
f2f601a04cabd6c0c170d8d0b37b6d2d
35.071429
140
0.456747
5.75
false
false
false
false
FHannes/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/values/PrimitiveValue.kt
7
926
package org.jetbrains.debugger.values open class PrimitiveValue(type: ValueType, override val valueString: String) : ValueBase(type) { constructor(type: ValueType, value: Int) : this(type, Integer.toString(value)) { } constructor(type: ValueType, value: Long) : this(type, java.lang.Long.toString(value)) { } companion object { val NA_N_VALUE = "NaN" val INFINITY_VALUE = "Infinity" @JvmField val NULL = PrimitiveValue(ValueType.NULL, "null") @JvmField val UNDEFINED = PrimitiveValue(ValueType.UNDEFINED, "undefined") val NAN = PrimitiveValue(ValueType.NUMBER, NA_N_VALUE) val INFINITY = PrimitiveValue(ValueType.NUMBER, INFINITY_VALUE) private val TRUE = PrimitiveValue(ValueType.BOOLEAN, "true") private val FALSE = PrimitiveValue(ValueType.BOOLEAN, "false") fun bool(value: String): PrimitiveValue { return if (value == "true") TRUE else FALSE } } }
apache-2.0
8f1cce86ce298ff776b9f9a3732d5641
29.9
96
0.704104
3.957265
false
false
false
false
AcapellaSoft/Aconite
aconite-client/src/io/aconite/client/AconiteClient.kt
1
857
package io.aconite.client import io.aconite.BodySerializer import io.aconite.StringSerializer import io.aconite.parser.ModuleParser import io.aconite.serializers.BuildInStringSerializers import io.aconite.serializers.SimpleBodySerializer import kotlin.reflect.KClass class AconiteClient( val acceptor: ClientRequestAcceptor, val bodySerializer: BodySerializer.Factory = SimpleBodySerializer.Factory, val stringSerializer: StringSerializer.Factory = BuildInStringSerializers ) { private val parser = ModuleParser() internal val moduleFactory = ModuleProxy.Factory(this) fun <T: Any> create(iface: KClass<T>): Service<T> { val desc = parser.parse(iface) val module = moduleFactory.create(desc) return ServiceImpl(module, iface) } inline fun <reified T: Any> create() = create(T::class) }
mit
de443cdd1960b3ddc454aa4a77893f6e
33.32
82
0.752625
4.463542
false
false
false
false
jraska/github-client
plugins/src/main/java/com/jraska/gradle/buildtime/BuildReporter.kt
1
2223
package com.jraska.gradle.buildtime import com.jraska.analytics.AnalyticsEvent import com.jraska.analytics.AnalyticsReporter import java.util.concurrent.TimeUnit class BuildReporter( private val analyticsReporter: AnalyticsReporter ) { fun report(buildData: BuildData) { try { reportMeasured(buildData) } catch (ex: Exception) { println("Build time reporting failed: $ex") } } private fun reportMeasured(buildData: BuildData) { val start = nowMillis() reportInternal(buildData) val reportingOverhead = nowMillis() - start println("$STOPWATCH_ICON Build time '${buildData.buildTime} ms' reported to ${analyticsReporter.name} in $reportingOverhead ms.$STOPWATCH_ICON") } private fun reportInternal(buildData: BuildData) { val properties = convertBuildData(buildData) val event = AnalyticsEvent("Android Build", properties) analyticsReporter.report(event) } private fun nowMillis() = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) private fun convertBuildData(buildData: BuildData): Map<String, Any?> { return mutableMapOf<String, Any?>( "action" to buildData.action, "buildTime" to buildData.buildTime, "tasks" to buildData.tasks.joinToString(), "failed" to buildData.failed, "failure" to buildData.failure.toString(), "daemonsRunning" to buildData.daemonsRunning, "thisDaemonBuilds" to buildData.thisDaemonBuilds, "hostname" to buildData.hostname, "gradleVersion" to buildData.gradleVersion, "OS" to buildData.operatingSystem, "environment" to buildData.environment, "tasksTotal" to buildData.taskStatistics.total, "tasksUpToDate" to buildData.taskStatistics.upToDate, "tasksFromCache" to buildData.taskStatistics.fromCache, "tasksExecuted" to buildData.taskStatistics.executed, "buildDataCollectionOverhead" to buildData.buildDataCollectionOverhead ).apply { putAll(buildData.parameters) putAll(buildData.gitInfo.asAnalyticsProperties()) if (buildData.ciInfo != null) { putAll(buildData.ciInfo.asAnalyticsProperties()) } } } companion object { private const val STOPWATCH_ICON = "\u23F1" } }
apache-2.0
f22c3c6929c6aed5d3b75f36b2b27d24
33.2
148
0.723347
4.101476
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/nnet/NnetDocumentManager.kt
1
27780
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.designer.editor.nnet import com.intellij.AppTopics import com.intellij.CommonBundle import com.intellij.codeStyle.CodeStyleFacade import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffManager import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.util.DiffUserDataKeys import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.TransactionGuardImpl import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentAdapter import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.ex.DocumentEx import com.intellij.openapi.editor.impl.EditorFactoryImpl import com.intellij.openapi.editor.impl.TrailingSpacesStripper import com.intellij.openapi.extensions.Extensions import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileDocumentManagerListener import com.intellij.openapi.fileEditor.FileDocumentSynchronizationVetoer import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.UnknownFileType import com.intellij.openapi.project.* import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.Key import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem import com.intellij.pom.core.impl.PomModelImpl import com.intellij.psi.ExternalChangeAction import com.intellij.psi.PsiDocumentManager import com.intellij.psi.SingleRootFileViewProvider import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.UIBundle import com.intellij.ui.components.JBScrollPane import com.intellij.util.containers.ContainerUtil import com.intellij.util.messages.MessageBus import com.thomas.needham.neurophidea.Constants import com.thomas.needham.neurophidea.Constants.DOCUMENT_HARD_REF_KEY import com.thomas.needham.neurophidea.Constants.LINE_KEY import com.thomas.needham.neurophidea.Predicates import com.thomas.needham.neurophidea.exceptions.SaveVetoException import org.jetbrains.annotations.NotNull import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ActionEvent import java.io.IOException import java.lang.reflect.InvocationHandler import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Proxy import java.util.* import javax.swing.* /** * Created by thoma on 18/06/2016. */ class NnetDocumentManager : FileDocumentManager, VirtualFileListener, ProjectManagerListener, SafeWriteRequestor { val unsavedDocuments: MutableSet<Document?> = ContainerUtil.newConcurrentSet<Document?>() val messageBus: MessageBus? val documentManagerListener: FileDocumentManagerListener? val virtualFileManager: VirtualFileManager? val projectManager: ProjectManager? val trailingSpaceStripper = TrailingSpacesStripper() val documentCache: MutableMap<VirtualFile, Document>? var onClose = false; companion object Data { @JvmStatic val LOG = Logger.getInstance("#com.thomas.needham.neurophidea.designer.editor") @JvmStatic val HARD_REF_TO_DOCUMENT_KEY: Key<Document> = Key.create<Document>(DOCUMENT_HARD_REF_KEY) @JvmStatic val LINE_SEPARATOR_KEY: Key<String> = Key.create<String>(LINE_KEY) @JvmStatic val FILE_KEY: Key<VirtualFile> = Key.create<VirtualFile>(Constants.FILE_KEY); @JvmStatic val RECOMPUTE_FILE_TYPE = Key.create<Boolean>(Constants.RECOMPUTE_FILE_TYPE) @JvmStatic val LOCK: Any? = Any() @JvmName("getInstanceKt") @JvmStatic fun getInstance(): FileDocumentManager { return ApplicationManager.getApplication().getComponent(NnetDocumentManager::class.java) } @JvmStatic fun unwrapAndRethrow(e: Exception) { var unpacked: Throwable = e if (e is InvocationTargetException) { if (e.cause == null) unpacked = e else unpacked = unpacked.cause!! } when (unpacked) { is Error -> throw unpacked is RuntimeException -> throw unpacked else -> { System.err.println(unpacked.message); unpacked.printStackTrace(System.err) } } LOG.error(unpacked) } @JvmStatic fun areTooManyDocumentsInTheQueue(documents: MutableSet<Document?>): Boolean { if (Predicates.MoreThan(documents.size, 200)) return true var totalSize: Int = 0 for (doc: Document? in documents) { totalSize += doc?.textLength!!.toInt() if (Predicates.MoreThan(totalSize, FileUtilRt.LARGE_FOR_CONTENT_LOADING)) return true } return false } @JvmStatic fun createDocument(text: CharSequence, file: VirtualFile): Document { val acceptSlash = file is LightVirtualFile && StringUtil.indexOf(text, '\r') >= 0 val freeThreaded = file.getUserData(SingleRootFileViewProvider.FREE_THREADED) == true return (EditorFactory.getInstance() as EditorFactoryImpl).createDocument(text, acceptSlash, freeThreaded) } @JvmStatic fun isSaveNeeded(doc: Document, file: VirtualFile): Boolean { if (file.fileType.isBinary || Predicates.MoreThan(doc.textLength, (1000 * 1000))) { return true } val bytes = byteArrayOf(*file.contentsToByteArray()) val loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, file, false, false) return !(Comparing.equal(doc.charsSequence, loaded)) } @JvmStatic fun needsRefresh(file: VirtualFile): Boolean { val vfs = file.fileSystem return vfs is NewVirtualFileSystem && file.timeStamp != vfs.getTimeStamp(file) } @JvmStatic fun updateModifiedProperty(file: VirtualFile) { for (project: Project? in ProjectManager.getInstance().openProjects) { val fileEditorManager: FileEditorManager? = FileEditorManager.getInstance(project!!) for (i in 0..fileEditorManager?.getAllEditors(file)?.size!! step 1) { if (fileEditorManager?.allEditors!![i] is NnetEditorImpl) { (fileEditorManager?.allEditors!![i] as NnetEditorImpl).updateModifiedProperty() } } } } @JvmStatic fun recomputeFileTypeIfNeccessary(@NotNull file: VirtualFile): Boolean { if (file.getUserData(RECOMPUTE_FILE_TYPE) != null) { file.fileType file.putUserData(RECOMPUTE_FILE_TYPE, null) return true } return false } } @Deprecated("DO NOT USE!!", ReplaceWith("constructor(@NotNull virtualFileManager : VirtualFileManager?, @NotNull projectManager : ProjectManager?)", *arrayOf("")), DeprecationLevel.ERROR) private constructor() : super() { this.virtualFileManager = null this.documentManagerListener = null this.projectManager = null this.documentCache = null this.messageBus = null } constructor(@NotNull virtualFileManager: VirtualFileManager?, @NotNull projectManager: ProjectManager?) : super() { this.virtualFileManager = virtualFileManager this.virtualFileManager?.addVirtualFileListener(this) this.projectManager = projectManager this.projectManager?.addProjectManagerListener(this) this.documentCache = ContainerUtil.createConcurrentWeakValueMap() this.messageBus = ApplicationManager.getApplication().messageBus val handler = NnetInvocationHandler(this) val classLoader: ClassLoader = FileDocumentManagerListener::class.java.classLoader this.documentManagerListener = (Proxy.newProxyInstance(classLoader, arrayOf<Class<*>>(FileDocumentManagerListener::class.java as Class<*>) as Array<out Class<*>>, handler as InvocationHandler?)) as FileDocumentManagerListener? } override fun getFile(@NotNull p0: Document): VirtualFile? { return p0.getUserData(FILE_KEY) } override fun isPartialPreviewOfALargeFile(p0: Document): Boolean { return false } override fun saveAllDocuments() { saveAllDocuments(true) } fun saveAllDocuments(b: Boolean) { ApplicationManager.getApplication().assertIsDispatchThread() (TransactionGuard.getInstance() as TransactionGuardImpl).assertWriteActionAllowed() documentManagerListener?.beforeAllDocumentsSaving() if (unsavedDocuments.isEmpty()) return val failedToSaveMap: MutableMap<Document, IOException> = HashMap<Document, IOException>() val vector: MutableSet<Document> = HashSet<Document>() while (true) { var count = 0 for (doc: Document? in unsavedDocuments) { if (failedToSaveMap.containsKey(doc)) continue if (vector.contains(doc)) continue try { doSaveDocument(doc, b) } catch (ioe: IOException) { ioe.printStackTrace(System.err) failedToSaveMap.put(doc!!, ioe) } catch (sve: SaveVetoException) { vector.add(doc!!) } count++ } if (count == 0) break } if (!failedToSaveMap.isEmpty()) { handleErrorsOnSave(failedToSaveMap) } } private fun handleErrorsOnSave(failedToSaveMap: MutableMap<Document, IOException>) { if (ApplicationManager.getApplication().isUnitTestMode) { val ioe: IOException? = ContainerUtil.getFirstItem(ArrayList<IOException>(failedToSaveMap.values)) if (ioe != null) { throw RuntimeException(ioe) } return } for (e: IOException? in failedToSaveMap.values) { LOG.warn(e as Throwable) } val text: String = StringUtil.join(failedToSaveMap.values, { ex: IOException -> ex.message }, "\n") val dialog = object : DialogWrapper(null) { override fun createDefaultActions() { super.createDefaultActions() myOKAction.putValue(Action.NAME, UIBundle.message( if (onClose) "cannot.save.files.dialog.ignore.changes" else "cannot.save.files.dialog.revert.changes")) myOKAction.putValue(DEFAULT_ACTION, null) if (!onClose) { myCancelAction.putValue(Action.NAME, CommonBundle.getCloseButtonText()) } } override fun createCenterPanel(): JComponent? { val panel: JPanel = JPanel(BorderLayout(0, 5)) panel.add(JLabel(UIBundle.message("cannot.save.files.dialog.message")), BorderLayout.NORTH) val area: JTextPane? = JTextPane() area?.text = text area?.isEditable = false area?.minimumSize = Dimension(area?.minimumSize?.width!!, 50) panel.add(JBScrollPane(area, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) , BorderLayout.CENTER) return panel } }; if (dialog.showAndGet()) { for (doc: Document? in failedToSaveMap.keys) { reloadFromDisk(doc!!) } } } private fun doSaveDocument(doc: Document?, b: Boolean) { val file = getFile(doc!!) if (file == null || file is LightVirtualFile || (file.isValid && !isFileModified(file))) { removeFromUnsaved(doc) return } if (file.isValid && needsRefresh(file)) { file.refresh(false, false) if (!unsavedDocuments.contains(doc)) return } for (vector: FileDocumentSynchronizationVetoer? in Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { if (!vector?.maySaveDocument(doc, b)!!) throw SaveVetoException() } val token: AccessToken? = ApplicationManager.getApplication().acquireWriteActionLock(NnetDocumentManager::class.java) try { doSaveDocumentInWriteAction(doc, file) } finally { token?.finish() } } private fun doSaveDocumentInWriteAction(doc: Document, file: VirtualFile) { if (!file.isValid) { removeFromUnsaved(doc) return } if (!file.equals(getFile(doc))) { registerDocument(doc as DocumentEx, file as LightVirtualFile) } if (!isSaveNeeded(doc, file)) { if (doc is DocumentEx) { doc.modificationStamp = file.modificationStamp } removeFromUnsaved(doc) updateModifiedProperty(file) return } PomModelImpl.guardPsiModificationsIn<Exception> { documentManagerListener?.beforeDocumentSaving(doc) LOG.assertTrue(file.isValid) var text = doc.text val lineSeperator = "\n" if (lineSeperator.equals("\n")) { text = StringUtil.convertLineSeparators(text, lineSeperator) } val project: Project? = ProjectLocator.getInstance().guessProjectForFile(file) LoadTextUtil.write(project, file, this, text, doc.modificationStamp) unsavedDocuments.remove(doc) LOG.assertTrue(!unsavedDocuments.contains(doc)) trailingSpaceStripper.clearLineModificationFlags(doc) } } private fun removeFromUnsaved(doc: Document) { unsavedDocuments.remove(doc) fireUnsavedDocumentsDropped() LOG.assertTrue(!unsavedDocuments.contains(doc)) } private fun fireUnsavedDocumentsDropped() { documentManagerListener?.unsavedDocumentsDropped() } override fun getUnsavedDocuments(): Array<out Document> { if (unsavedDocuments.isEmpty()) { return Document.EMPTY_ARRAY } val list: MutableList<Document> = ArrayList<Document>(unsavedDocuments) return list.toTypedArray() } override fun isDocumentUnsaved(p0: Document): Boolean { return unsavedDocuments.contains(p0) } override fun reloadFiles(vararg p0: VirtualFile?) { for (file: VirtualFile? in p0) { if (file?.exists()!!) { val doc: Document? = getCachedDocument(file!!) if (doc != null) { reloadFromDisk(doc) } } } } override fun saveDocument(p0: Document) { saveDocument(p0, true) } fun saveDocument(document: Document, explicit: Boolean) { ApplicationManager.getApplication().assertIsDispatchThread() (TransactionGuard.getInstance() as TransactionGuardImpl).assertWriteActionAllowed() if (!unsavedDocuments.contains(document)) return try { doSaveDocument(document, explicit) } catch (ioe: IOException) { ioe.printStackTrace(System.err) handleErrorsOnSave(Collections.singletonMap(document, ioe)) } catch (sve: SaveVetoException) { sve.printStackTrace(System.err) } } override fun requestWriting(p0: Document, p1: Project?): Boolean { val file: VirtualFile? = getInstance().getFile(p0) if (p1 != null && file != null && file.isValid) { return !(file.fileType.isBinary && ReadonlyStatusHandler.ensureFilesWritable(p1, file)) } if (p0.isWritable) { return true } p0.fireReadOnlyModificationAttempt() return false } override fun isFileModified(p0: VirtualFile): Boolean { val doc: Document? = getCachedDocument(p0) return doc != null && isDocumentUnsaved(doc) && doc.modificationStamp != p0.modificationStamp } override fun getCachedDocument(@NotNull p0: VirtualFile): Document? { val hard: Document? = p0.getUserData(HARD_REF_TO_DOCUMENT_KEY) return hard ?: getDocumentFromCache(p0) } private fun getDocumentFromCache(p0: VirtualFile): Document? { return documentCache?.get(p0) } override fun reloadFromDisk(p0: Document) { ApplicationManager.getApplication().assertIsDispatchThread() val file: VirtualFile = getFile(p0)!! if (!fireBeforeFileContentReload(file, p0)) return if (file.length > FileUtilRt.LARGE_FOR_CONTENT_LOADING) { unbindFileFromDocument(file, p0) unsavedDocuments.remove(p0) documentManagerListener?.fileWithNoDocumentChanged(file) return } val project = ProjectLocator.getInstance().guessProjectForFile(file) CommandProcessor.getInstance().executeCommand(project, (object : Runnable { override fun run() { val wasWritable = p0.isWritable val docEx = p0 as DocumentEx docEx.setReadOnly(false) docEx.replaceText(LoadTextUtil.loadText(file), file.modificationStamp) docEx.setReadOnly(!wasWritable) } }), UIBundle.message("file.cache.conflict.action"), null, UndoConfirmationPolicy.REQUEST_CONFIRMATION) unsavedDocuments.remove(p0) documentManagerListener?.fileContentReloaded(file, p0) } private fun unbindFileFromDocument(file: VirtualFile?, p0: Document) { removeDocumentFromCache(file!!) file.putUserData(HARD_REF_TO_DOCUMENT_KEY, null) p0.putUserData(FILE_KEY, null) } private fun fireBeforeFileContentReload(file: VirtualFile, p0: Document): Boolean { for (vector: FileDocumentSynchronizationVetoer in Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { try { if (!vector.mayReloadFileContent(file, p0)) return false } catch (e: Exception) { e.printStackTrace(System.err) LOG.error(e) } } documentManagerListener?.beforeFileContentReload(file, p0) return true } override fun saveDocumentAsIs(p0: Document) { val file: VirtualFile? = getFile(p0) var spaceStrippingEnabled = true if (file != null) { spaceStrippingEnabled = TrailingSpacesStripper.isEnabled(file) TrailingSpacesStripper.setEnabled(file, false) } try { saveDocument(p0) } finally { if (file != null) { TrailingSpacesStripper.setEnabled(file, spaceStrippingEnabled) } } } override fun getLineSeparator(p0: VirtualFile?, p1: Project?): String { return "\n" } override fun getDocument(p0: VirtualFile): Document? { ApplicationManager.getApplication().assertReadAccessAllowed(); var document = getCachedDocument(p0) as DocumentEx?; if (!p0.isValid || p0.isDirectory || SingleRootFileViewProvider.isTooLargeForContentLoading(p0)) { return null; } else { val text: String = LoadTextUtil.loadText(p0) as String synchronized(LOCK!!) { document = getCachedDocument(p0) as DocumentEx? if (document != null) return document document = createDocument(text, p0) as DocumentEx document?.modificationStamp = p0.modificationStamp val type: FileType = p0.fileType document?.setReadOnly(!p0.isWritable) if (p0 is LightVirtualFile) { registerDocument(document!!, p0) } else { cacheDocument(p0, document!!) document?.putUserData(FILE_KEY, p0) } if (!(p0 is LightVirtualFile || p0.fileSystem is NonPhysicalFileSystem)) { document?.addDocumentListener(object : DocumentAdapter() { override fun documentChanged(e: DocumentEvent) { val doc: Document? = e.document unsavedDocuments.add(doc) val command: Runnable? = CommandProcessor.getInstance().currentCommand val project: Project? = if (command == null) null else CommandProcessor.getInstance().currentCommandProject val lineSeperator = CodeStyleFacade.getInstance(project).lineSeparator if (areTooManyDocumentsInTheQueue(unsavedDocuments)) { saveAllDocumentsLater() } } }) } } documentManagerListener?.fileContentLoaded(p0, document!!) } return document } fun saveAllDocumentsLater() { ApplicationManager.getApplication().invokeLater(object : Runnable { override fun run() { if (ApplicationManager.getApplication().isDisposed) exit@ Unit val unsavedDocuments: Array<out Document?> = getUnsavedDocuments() for (doc: Document? in unsavedDocuments) { val file: VirtualFile? = getFile(doc!!) if (file == null) continue val project: Project? = guessProjectForFile(file) if (project == null) continue if (PsiDocumentManager.getInstance(project).isDocumentBlockedByPsi(doc)) { saveDocument(doc) } } } }) } fun cacheDocument(file: VirtualFile, document: DocumentEx) { documentCache?.put(file, document) } fun registerDocument(document: DocumentEx, file: LightVirtualFile) { synchronized(LOCK!!, { file.putUserData(HARD_REF_TO_DOCUMENT_KEY, document) document.putUserData(FILE_KEY, file) }) } override fun beforePropertyChange(p0: VirtualFilePropertyEvent) { } override fun beforeContentsChange(p0: VirtualFileEvent) { val file: VirtualFile? = p0.file if (file?.length == 0L && file?.fileType == UnknownFileType.INSTANCE) { file?.putUserData(RECOMPUTE_FILE_TYPE, true) } } override fun fileDeleted(p0: VirtualFileEvent) { val doc: Document? = getCachedDocument(p0.file) if (doc != null) { trailingSpaceStripper.documentDeleted(doc) } } override fun beforeFileMovement(p0: VirtualFileMoveEvent) { } override fun fileMoved(p0: VirtualFileMoveEvent) { } override fun propertyChanged(p0: VirtualFilePropertyEvent) { val file: VirtualFile? = p0.file if (VirtualFile.PROP_WRITABLE.equals(p0.propertyName)) { val doc: Document? = getCachedDocument(file!!) if (doc != null) { ApplicationManager.getApplication().runWriteAction(object : ExternalChangeAction { override fun run() { doc.setReadOnly(!file.isWritable) } }) } else if (VirtualFile.PROP_NAME.equals(p0.propertyName)) { val doc: Document? = getCachedDocument(file) if (doc != null) { println("Found Unknown File Type: ${file.fileType.name}") } } } } override fun contentsChanged(p0: VirtualFileEvent) { if (p0.isFromSave) return val file: VirtualFile? = p0.file val doc: Document? = getCachedDocument(file!!) if (doc == null) { documentManagerListener?.fileWithNoDocumentChanged(file) return } val documentStamp = doc.modificationStamp val oldDocumentStamp = p0.oldModificationStamp if (documentStamp != oldDocumentStamp) { LOG.info("reload " + file.getName() + " from disk?"); LOG.info(" documentStamp:" + documentStamp); LOG.info(" oldFileStamp:" + oldDocumentStamp); if (file.isValid && askReloadFromDisk(file, doc)) { reloadFromDisk(doc) } } else { reloadFromDisk(doc) } } private fun askReloadFromDisk(file: VirtualFile, doc: Document): Boolean { ApplicationManager.getApplication().assertIsDispatchThread() if (!isDocumentUnsaved(doc)) return true return askReloadFromDisk.invoke(file, doc) } override fun beforeFileDeletion(p0: VirtualFileEvent) { } override fun fileCreated(p0: VirtualFileEvent) { } override fun fileCopied(p0: VirtualFileCopyEvent) { fileCreated(p0 as VirtualFileEvent) } override fun canCloseProject(p0: Project): Boolean { if (!unsavedDocuments.isEmpty()) { onClose = true try { saveAllDocuments() } finally { onClose = false } } return unsavedDocuments.isEmpty() } override fun projectClosing(p0: Project) { } override fun projectClosed(p0: Project) { } override fun projectOpened(p0: Project) { } @SuppressWarnings("OverlyBroadCatchBlock") fun multiCast(method: Method?, args: Array<out Any>?) { val arguments = ParseArguments(args) try { if (method?.parameterCount == 1) method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), arguments[0] as VirtualFile?) else if (method?.parameterCount == 2) method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), arguments[0] as VirtualFile?, arguments[1] as Document?) else method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), *arguments) } catch (cce: ClassCastException) { LOG.error("Arguments ${Arrays.toString(args)}", cce) } catch (e: Exception) { unwrapAndRethrow(e) //uncomment when debugging e.printStackTrace(System.err) } for (listener: FileDocumentManagerListener? in getListeners()) { try { method?.invoke(listener, arguments) } catch (e: Exception) { unwrapAndRethrow(e) //uncomment when debugging e.printStackTrace(System.err) } } try { if (method?.parameterCount == 1) method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), arguments[0] as VirtualFile?) else if (method?.parameterCount == 2) method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), arguments[0] as VirtualFile?, arguments[1] as Document?) else method?.invoke(messageBus?.syncPublisher(AppTopics.FILE_DOCUMENT_SYNC), *arguments) } catch (e: Exception) { unwrapAndRethrow(e) //uncomment when debugging e.printStackTrace(System.err) } } private fun ParseArguments(args: Array<out Any>?): Array<Any?> { val init: (Int) -> Any? = { Any() } val arguments = Array<Any?>(args?.size!!, init) for (i in 0..args?.size!! - 1) { if (i == 0) { arguments[i] = args!![i] as VirtualFile? } else { arguments[i] = args!![i] } } return arguments } private fun getListeners(): Array<out FileDocumentManagerListener?> { return FileDocumentManagerListener.EP_NAME.extensions } @Volatile private var askReloadFromDisk = { file: VirtualFile, document: Document -> val message = UIBundle.message("file.cache.conflict.message.text", file.getPresentableUrl()) val builder = DialogBuilder() builder.setCenterPanel(JLabel(message, Messages.getQuestionIcon(), SwingConstants.CENTER)) builder.addOkAction().setText(UIBundle.message("file.cache.conflict.load.fs.changes.button")) builder.addCancelAction().setText(UIBundle.message("file.cache.conflict.keep.memory.changes.button")) builder.addAction(object : AbstractAction() { override fun actionPerformed(p0: ActionEvent?) { val project = ProjectLocator.getInstance().guessProjectForFile(file) as ProjectEx val fileType = file.getFileType() val fsContent = LoadTextUtil.loadText(file).toString() val content1 = DiffContentFactory.getInstance().create(fsContent, fileType) val content2 = DiffContentFactory.getInstance().create(project, document, file) val title = UIBundle.message("file.cache.conflict.for.file.dialog.title", file.getPresentableUrl()) val title1 = UIBundle.message("file.cache.conflict.diff.content.file.system.content") val title2 = UIBundle.message("file.cache.conflict.diff.content.memory.content") val request = SimpleDiffRequest(title, content1, content2, title1, title2) request.putUserData(DiffUserDataKeys.GO_TO_SOURCE_DISABLE, true) val diffBuilder = DialogBuilder(project) val diffPanel = DiffManager.getInstance().createRequestPanel(project, diffBuilder, diffBuilder.getWindow()) diffPanel.setRequest(request) diffBuilder.setCenterPanel(diffPanel.getComponent()) diffBuilder.setDimensionServiceKey("FileDocumentManager.FileCacheConflict") diffBuilder.addOkAction().setText(UIBundle.message("file.cache.conflict.save.changes.button")) diffBuilder.addCancelAction() diffBuilder.setTitle(title) if (diffBuilder.show() === DialogWrapper.OK_EXIT_CODE) { builder.getDialogWrapper().close(DialogWrapper.CANCEL_EXIT_CODE) } } }); builder.setTitle(UIBundle.message("file.cache.conflict.dialog.title")) builder.setButtonsAlignment(SwingConstants.CENTER) builder.setHelpId("reference.dialogs.fileCacheConflict") builder.show() == 0 } fun removeDocumentFromCache(file: VirtualFile) { documentCache?.remove(file) } }
mit
90a89edfe0b4a7e75ffec1adb530c9ca
34.433673
188
0.7455
3.865312
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/programs/ProgramRecyclerViewAdapter.kt
1
6703
package org.tvheadend.tvhclient.ui.features.programs import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import org.tvheadend.data.entity.ProgramInterface import org.tvheadend.data.entity.Recording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.ProgramListAdapterBinding import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.util.extensions.isEqualTo import java.util.* import java.util.concurrent.CopyOnWriteArrayList class ProgramRecyclerViewAdapter internal constructor(private val viewModel: ProgramViewModel, private val clickCallback: RecyclerViewClickInterface, private val onLastProgramVisibleListener: LastProgramVisibleListener, private val lifecycleOwner: LifecycleOwner) : RecyclerView.Adapter<ProgramRecyclerViewAdapter.ProgramViewHolder>(), Filterable { private val programList = ArrayList<ProgramInterface>() private var programListFiltered: MutableList<ProgramInterface> = ArrayList() private val recordingList = ArrayList<Recording>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProgramViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = ProgramListAdapterBinding.inflate(layoutInflater, parent, false) val viewHolder = ProgramViewHolder(itemBinding, viewModel) itemBinding.lifecycleOwner = lifecycleOwner return viewHolder } override fun onBindViewHolder(holder: ProgramViewHolder, position: Int) { if (programListFiltered.size > position) { val program = programListFiltered[position] holder.bind(program, position, clickCallback) if (position == programList.size - 1) { onLastProgramVisibleListener.onLastProgramVisible(position) } } } override fun onBindViewHolder(holder: ProgramViewHolder, position: Int, payloads: List<Any>) { onBindViewHolder(holder, position) } internal fun addItems(newItems: MutableList<ProgramInterface>) { updateRecordingState(newItems, recordingList) val oldItems = ArrayList(programListFiltered) val diffResult = DiffUtil.calculateDiff(ProgramListDiffCallback(oldItems, newItems)) programList.clear() programListFiltered.clear() programList.addAll(newItems) programListFiltered.addAll(newItems) diffResult.dispatchUpdatesTo(this) } override fun getItemCount(): Int { return programListFiltered.size } override fun getItemViewType(position: Int): Int { return R.layout.program_list_adapter } fun getItem(position: Int): ProgramInterface? { return if (programListFiltered.size > position && position >= 0) { programListFiltered[position] } else { null } } override fun getFilter(): Filter { return object : Filter() { override fun performFiltering(charSequence: CharSequence): FilterResults { val charString = charSequence.toString() val filteredList: MutableList<ProgramInterface> = ArrayList() if (charString.isNotEmpty()) { for (program in CopyOnWriteArrayList(programList)) { val title = program.title ?: "" when { title.lowercase().contains(charString.lowercase()) -> filteredList.add(program) } } } else { filteredList.addAll(programList) } val filterResults = FilterResults() filterResults.values = filteredList return filterResults } override fun publishResults(charSequence: CharSequence, filterResults: FilterResults) { programListFiltered.clear() @Suppress("UNCHECKED_CAST") programListFiltered.addAll(filterResults.values as ArrayList<ProgramInterface>) notifyDataSetChanged() } } } /** * Whenever a recording changes in the database the list of available recordings are * saved in this recycler view. The previous list is cleared to avoid showing outdated * recording states. Each recording is checked if it belongs to the * currently shown program. If yes then its state is updated. * * @param list List of recordings */ internal fun addRecordings(list: List<Recording>) { recordingList.clear() recordingList.addAll(list) updateRecordingState(programListFiltered, recordingList) } private fun updateRecordingState(programs: MutableList<ProgramInterface>, recordings: List<Recording>) { for (i in programs.indices) { val program = programs[i] var recordingExists = false for (recording in recordings) { if (program.eventId > 0 && program.eventId == recording.eventId) { val oldRecording = program.recording program.recording = recording // Do a full update only when a new recording was added or the recording // state has changed which results in a different recording state icon // Otherwise do not update the UI if (oldRecording == null || !oldRecording.error.isEqualTo(recording.error) || !oldRecording.state.isEqualTo(recording.state)) { notifyItemChanged(i) } recordingExists = true break } } if (!recordingExists && program.recording != null) { program.recording = null notifyItemChanged(i) } programs[i] = program } } class ProgramViewHolder(private val binding: ProgramListAdapterBinding, private val viewModel: ProgramViewModel) : RecyclerView.ViewHolder(binding.root) { fun bind(program: ProgramInterface, position: Int, clickCallback: RecyclerViewClickInterface) { binding.program = program binding.position = position binding.viewModel = viewModel binding.callback = clickCallback binding.executePendingBindings() } } }
gpl-3.0
bf2ed0bd232e9e44a30866e54f9303dd
40.89375
348
0.652394
5.576539
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/settings/SettingsListConnectionsFragment.kt
1
8439
package org.tvheadend.tvhclient.ui.features.settings import android.content.Context import android.content.Intent import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.afollestad.materialdialogs.MaterialDialog import org.tvheadend.data.entity.Connection import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.RecyclerviewFragmentBinding import org.tvheadend.tvhclient.service.ConnectionService import org.tvheadend.tvhclient.ui.common.WakeOnLanTask import org.tvheadend.tvhclient.ui.common.interfaces.BackPressedInterface import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.ui.common.interfaces.ToolbarInterface import org.tvheadend.tvhclient.ui.features.MainActivity class SettingsListConnectionsFragment : Fragment(), BackPressedInterface, ActionMode.Callback, RecyclerViewClickInterface { private lateinit var binding: RecyclerviewFragmentBinding private var activeConnectionId: Int = -1 private var connectionHasChanged: Boolean = false private lateinit var toolbarInterface: ToolbarInterface private lateinit var recyclerViewAdapter: ConnectionRecyclerViewAdapter private lateinit var settingsViewModel: SettingsViewModel private var actionMode: ActionMode? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = RecyclerviewFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) settingsViewModel = ViewModelProvider(activity as SettingsActivity)[SettingsViewModel::class.java] if (activity is ToolbarInterface) { toolbarInterface = activity as ToolbarInterface toolbarInterface.setTitle(getString(R.string.pref_connections)) } recyclerViewAdapter = ConnectionRecyclerViewAdapter(this, viewLifecycleOwner) binding.recyclerView.layoutManager = LinearLayoutManager(activity) binding.recyclerView.adapter = recyclerViewAdapter settingsViewModel.connectionListLiveData.observe(viewLifecycleOwner, { connections -> if (connections != null) { recyclerViewAdapter.addItems(connections) context?.let { toolbarInterface.setSubtitle(it.resources.getQuantityString( R.plurals.number_of_connections, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount)) } } }) settingsViewModel.activeConnectionLiveData.observe(viewLifecycleOwner, { connection -> connectionHasChanged = connection != null && connection.id != settingsViewModel.connectionToEdit.id activeConnectionId = connection?.id ?: -1 }) setHasOptionsMenu(true) } private fun startActionMode() { actionMode = activity?.startActionMode(this) actionMode?.invalidate() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.connection_add_options_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_add_connection -> addConnection() else -> super.onOptionsItemSelected(item) } } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val ctx = context ?: return false val position = recyclerViewAdapter.selectedPosition if (recyclerViewAdapter.itemCount <= position) return false val connection = recyclerViewAdapter.getItem(position) ?: return false return when (item.itemId) { R.id.menu_set_connection_active -> setConnectionActiveOrInactive(connection, mode, true) R.id.menu_set_connection_not_active -> setConnectionActiveOrInactive(connection, mode, false) R.id.menu_edit_connection -> editConnection(connection, mode) R.id.menu_send_wol -> { WakeOnLanTask(lifecycleScope, ctx, connection) mode.finish() true } R.id.menu_delete_connection -> deleteConnection(ctx, connection, mode) else -> false } } private fun addConnection(): Boolean { settingsViewModel.setNavigationMenuId("add_connection") return true } private fun editConnection(connection: Connection, mode: ActionMode): Boolean { settingsViewModel.connectionIdToBeEdited = connection.id settingsViewModel.setNavigationMenuId("edit_connection") mode.finish() return true } private fun setConnectionActiveOrInactive(connection: Connection, mode: ActionMode, active: Boolean): Boolean { connection.isActive = active settingsViewModel.updateConnection(connection) mode.finish() return true } private fun deleteConnection(context: Context, connection: Connection, mode: ActionMode): Boolean { MaterialDialog(context).show { message(text = getString(R.string.delete_connection, connection.name)) positiveButton(R.string.delete) { settingsViewModel.removeConnection(connection) } negativeButton(R.string.cancel) { cancel() } } mode.finish() return true } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.menuInflater.inflate(R.menu.connection_list_options_menu, menu) return true } override fun onDestroyActionMode(mode: ActionMode) { actionMode = null } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { // Get the currently selected program from the list val position = recyclerViewAdapter.selectedPosition val connection = recyclerViewAdapter.getItem(position) if (connection != null) { // Show or hide the wake on LAN menu item menu.getItem(0).isVisible = connection.isWolEnabled && !connection.wolMacAddress.isNullOrEmpty() // Show or hide the activate / deactivate menu items menu.getItem(1).isVisible = !connection.isActive menu.getItem(2).isVisible = connection.isActive mode.title = connection.name } return true } override fun onBackPressed() { when { activeConnectionId < 0 -> context?.let { MaterialDialog(it).show { title(R.string.disconnect_from_server) message(R.string.no_active_connection) positiveButton(R.string.disconnect) { updateConnectionAndRestartApplication() } } } connectionHasChanged -> context?.let { MaterialDialog(it).show { title(R.string.connect_to_new_server) message(R.string.connection_changed) positiveButton(R.string.connect) { updateConnectionAndRestartApplication() } } } else -> { (activity as RemoveFragmentFromBackstackInterface).removeFragmentFromBackstack() } } } private fun updateConnectionAndRestartApplication() { context?.stopService(Intent(context, ConnectionService::class.java)) val intent = Intent(context, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK context?.startActivity(intent) } override fun onClick(view: View, position: Int) { actionMode?.finish() if (actionMode == null) { recyclerViewAdapter.setPosition(position) startActionMode() } } override fun onLongClick(view: View, position: Int): Boolean { return true } }
gpl-3.0
6d5c6d9d3aac2629b692d6cb77e9f118
39.185714
123
0.66643
5.399232
false
false
false
false
DankBots/Mega-Gnar
src/main/kotlin/gg/octave/bot/utils/IntentHelper.kt
1
1025
package gg.octave.bot.utils import net.dv8tion.jda.api.requests.GatewayIntent object IntentHelper { private val disabledIntents = listOf( GatewayIntent.GUILD_INVITES, GatewayIntent.GUILD_BANS, GatewayIntent.DIRECT_MESSAGE_REACTIONS, GatewayIntent.DIRECT_MESSAGES, GatewayIntent.DIRECT_MESSAGE_TYPING, GatewayIntent.GUILD_EMOJIS, GatewayIntent.GUILD_MEMBERS, //GatewayIntent.GUILD_MESSAGE_REACTIONS, GatewayIntent.GUILD_MESSAGE_TYPING, GatewayIntent.GUILD_PRESENCES ) // Basically everything except GUILD_MESSAGES, GUILD_VOICE_STATES, and GUILD_MESSAGE_REACTIONS. // Not actually sure if we need GUILD_MESSAGE_REACTIONS but I've left it in for the sake of vote-* commands. val allIntents = GatewayIntent.ALL_INTENTS val disabledIntentsInt = GatewayIntent.getRaw(disabledIntents) val enabledIntentsInt = allIntents and disabledIntentsInt.inv() val enabledIntents = GatewayIntent.getIntents(enabledIntentsInt) }
mit
d8b558b0f68a2bae78d5e30e445fba6a
38.423077
112
0.740488
4.20082
false
false
false
false
genobis/tornadofx
src/main/java/tornadofx/Workspace.kt
1
16208
package tornadofx import javafx.beans.property.ObjectProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.geometry.Pos import javafx.geometry.Side import javafx.scene.Node import javafx.scene.Parent import javafx.scene.control.Button import javafx.scene.control.TabPane import javafx.scene.control.ToolBar import javafx.scene.input.KeyCombination import javafx.scene.layout.BorderPane import javafx.scene.layout.HBox import javafx.scene.layout.StackPane import tornadofx.Workspace.NavigationMode.Stack import kotlin.reflect.KClass class HeadingContainer : HBox() { init { addClass("heading-container") } } class WorkspaceArea : BorderPane() { internal var dynamicComponentMode: Boolean = false internal val dynamicComponents = FXCollections.observableArrayList<Node>() var header: ToolBar by singleAssign() init { addClass("workspace") } } open class Workspace(title: String = "Workspace", navigationMode: NavigationMode = Stack) : View(title) { var refreshButton: Button by singleAssign() var saveButton: Button by singleAssign() var createButton: Button by singleAssign() var deleteButton: Button by singleAssign() var backButton: Button by singleAssign() var forwardButton: Button by singleAssign() enum class NavigationMode { Stack, Tabs } val navigationModeProperty: ObjectProperty<NavigationMode> = SimpleObjectProperty(navigationMode) var navigationMode by navigationModeProperty val viewStack = FXCollections.observableArrayList<UIComponent>() val maxViewStackDepthProperty = SimpleIntegerProperty(DefaultViewStackDepth) var maxViewStackDepth by maxViewStackDepthProperty val headingContainer = HeadingContainer() val tabContainer = TabPane().addClass("editor-container") val stackContainer = StackPane().addClass("editor-container") val contentContainerProperty = SimpleObjectProperty<Parent>(stackContainer) var contentContainer by contentContainerProperty val showHeadingLabelProperty = SimpleBooleanProperty(true) var showHeadingLabel by showHeadingLabelProperty val dockedComponentProperty: ObjectProperty<UIComponent> = SimpleObjectProperty() val dockedComponent: UIComponent? get() = dockedComponentProperty.value private val viewPos = integerBinding(viewStack, dockedComponentProperty) { viewStack.indexOf(dockedComponent) } val leftDrawer: Drawer get() = (root.left as? Drawer) ?: Drawer(Side.LEFT, false, false).also { root.left = it it.toFront() } val rightDrawer: Drawer get() = (root.right as? Drawer) ?: Drawer(Side.RIGHT, false, false).also { root.right = it it.toFront() } val bottomDrawer: Drawer get() = (root.bottom as? Drawer) ?: Drawer(Side.BOTTOM, false, false).also { root.bottom = it it.toFront() } companion object { val activeWorkspaces = FXCollections.observableArrayList<Workspace>() val DefaultViewStackDepth = 10 fun closeAll() { activeWorkspaces.forEach(Workspace::close) } var defaultSavable = true var defaultDeletable = true var defaultRefreshable = true var defaultCloseable = true var defaultComplete = true var defaultCreatable = true init { importStylesheet("/tornadofx/workspace.css") } } fun disableNavigation() { viewStack.clear() maxViewStackDepth = 0 } private fun registerWorkspaceAccelerators() { accelerators[KeyCombination.valueOf("Ctrl+S")] = { if (!saveButton.isDisable) onSave() } accelerators[KeyCombination.valueOf("Ctrl+N")] = { if (!createButton.isDisable) onSave() } accelerators[KeyCombination.valueOf("Ctrl+R")] = { if (!refreshButton.isDisable) onRefresh() } accelerators[KeyCombination.valueOf("F5")] = { if (!refreshButton.isDisable) onRefresh() } } override fun onDock() { activeWorkspaces += this } override fun onUndock() { activeWorkspaces -= this } override val root = WorkspaceArea().apply { top { vbox { header = toolbar { addClass("header") // Force the container to retain pos center even when it's resized (hack to make ToolBar behave) skinProperty().onChange { (lookup(".container") as? HBox)?.apply { alignment = Pos.CENTER_LEFT alignmentProperty().onChange { if (it != Pos.CENTER_LEFT) alignment = Pos.CENTER_LEFT } } } button { addClass("icon-only") backButton = this graphic = label { addClass("icon", "back") } action { if (dockedComponent?.onNavigateBack() ?: true) { navigateBack() } } disableProperty().bind(booleanBinding(viewPos, viewStack) { value < 1 }) } button { addClass("icon-only") forwardButton = this graphic = label { addClass("icon", "forward") } action { if (dockedComponent?.onNavigateForward() ?: true) { navigateForward() } } disableProperty().bind(booleanBinding(viewPos, viewStack) { value == viewStack.size - 1 }) } button { addClass("icon-only") refreshButton = this isDisable = true graphic = label { addClass("icon", "refresh") } action { onRefresh() } } button { addClass("icon-only") saveButton = this isDisable = true graphic = label { addClass("icon", "save") } action { onSave() } } button { addClass("icon-only") createButton = this isDisable = true graphic = label { addClass("icon", "create") } action { onCreate() } } button { addClass("icon-only") deleteButton = this isDisable = true graphic = label { addClass("icon", "delete") } action { onDelete() } } add(headingContainer) spacer() } } } } private fun navigateForward(): Boolean { if (!forwardButton.isDisabled) { dock(viewStack[viewPos.get() + 1], false) return true } return false } fun navigateBack(): Boolean { if (!backButton.isDisabled) { dock(viewStack[viewPos.get() - 1], false) return true } return false } init { // @Suppress("LeakingThis") // if (!scope.hasActiveWorkspace) scope.workspaceInstance = this navigationModeProperty.addListener { _, ov, nv -> navigationModeChanged(ov, nv) } tabContainer.tabs.onChange { change -> while (change.next()) { if (change.wasRemoved()) { change.removed.forEach { if (it == dockedComponent) { titleProperty.unbind() refreshButton.disableProperty().unbind() saveButton.disableProperty().unbind() createButton.disableProperty().unbind() deleteButton.disableProperty().unbind() } } } if (change.wasAdded()) { change.addedSubList.forEach { it.content.properties["tornadofx.tab"] = it } } } } tabContainer.selectionModel.selectedItemProperty().addListener { observableValue, ov, nv -> val newCmp = nv?.content?.uiComponent<UIComponent>() val oldCmp = ov?.content?.uiComponent<UIComponent>() if (newCmp != null && newCmp != dockedComponent) { setAsCurrentlyDocked(newCmp) } if (oldCmp != newCmp) oldCmp?.callOnUndock() } dockedComponentProperty.onChange { child -> if (child != null) { inDynamicComponentMode { if (contentContainer == stackContainer) { tabContainer.tabs.clear() stackContainer.clear() stackContainer += child } else { stackContainer.clear() var tab = tabContainer.tabs.find { it.content == child.root } if (tab == null) { tabContainer += child tab = tabContainer.tabs.last() } else { child.callOnDock() } tabContainer.selectionModel.select(tab) } } } } navigationModeChanged(null, navigationMode) registerWorkspaceAccelerators() } private fun navigationModeChanged(oldMode: NavigationMode?, newMode: NavigationMode?) { if (oldMode == null || oldMode != newMode) { contentContainer = if (navigationMode == Stack) stackContainer else tabContainer root.center = contentContainer if (contentContainer == stackContainer && tabContainer.tabs.isNotEmpty()) { tabContainer.tabs.clear() } dockedComponent?.also { dockedComponentProperty.value = null dock(it, true) } } if (newMode == Stack) { if (backButton !in root.header.items) { root.header.items.add(0, backButton) root.header.items.add(1, forwardButton) } } else { root.header.items -= backButton root.header.items -= forwardButton } } override fun onSave() { dockedComponentProperty.value ?.takeIf { it.savable.value } ?.onSave() } override fun onDelete() { dockedComponentProperty.value ?.takeIf { it.deletable.value } ?.onDelete() } override fun onCreate() { dockedComponentProperty.value ?.takeIf { it.creatable.value } ?.onCreate() } override fun onRefresh() { dockedComponentProperty.value ?.takeIf { it.refreshable.value } ?.onRefresh() } inline fun <reified T : UIComponent> dock(scope: Scope = [email protected], params: Map<*, Any?>? = null) = dock(find<T>(scope, params)) fun dock(child: UIComponent, forward: Boolean = true) { // Remove everything after viewpos if moving forward if (forward) while (viewPos.get() < viewStack.size -1) viewStack.removeAt(viewPos.get() + 1) val addToStack = contentContainer == stackContainer && maxViewStackDepth > 0 && child !in viewStack if (addToStack) viewStack += child setAsCurrentlyDocked(child) // Ensure max stack size while (viewStack.size >= maxViewStackDepth) viewStack.removeAt(0) } private fun setAsCurrentlyDocked(child: UIComponent) { titleProperty.bind(child.titleProperty) refreshButton.disableProperty().cleanBind(!child.refreshable) saveButton.disableProperty().cleanBind(!child.savable) createButton.disableProperty().cleanBind(!child.creatable) deleteButton.disableProperty().cleanBind(!child.deletable) headingContainer.children.clear() headingContainer.label(child.headingProperty) { graphicProperty().bind(child.iconProperty) removeWhen(!showHeadingLabelProperty) } clearDynamicComponents() dockedComponentProperty.value = child } private fun clearDynamicComponents() { root.dynamicComponents.forEach(Node::removeFromParent) root.dynamicComponents.clear() } fun inDynamicComponentMode(function: () -> Unit) { root.dynamicComponentMode = true try { function() } finally { root.dynamicComponentMode = false } } /** * Create a new scope and associate it with this Workspace and optionally add one * or more ScopedInstance instances into the scope. The op block operates on the workspace and is passed the new scope. The following example * creates a new scope, injects a Customer Model into it and docks the CustomerEditor * into the Workspace: * * <pre> * workspace.withNewScope(CustomerModel(customer)) { newScope -> * dock<CustomerEditor>(newScope) * } * </pre> */ fun withNewScope(vararg setInScope: ScopedInstance, op: Workspace.(Scope) -> Unit) { this.op(Scope().also { it.workspaceInstance = this it.set(*setInScope) }) } /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope, passing the given parameters on to the UIComponent and optionally injecting the given Injectables into the new scope. */ inline fun <reified T : UIComponent> dockInNewScope(params: Map<*, Any?>, vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { newScope -> dock<T>(newScope, params) } } /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope, optionally injecting the given Injectables into the new scope. */ inline fun <reified T : UIComponent> dockInNewScope(vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { newScope -> dock<T>(newScope) } } /** * Create a new scope and associate it with this Workspace and dock the given UIComponent type into * the scope and optionally injecting the given Injectables into the new scope. */ fun <T : UIComponent> dockInNewScope(uiComponent: T, vararg setInScope: ScopedInstance) { withNewScope(*setInScope) { dock(uiComponent) } } /** * Will automatically dock the given [UIComponent] if the [ListMenuItem] is selected. */ inline fun <reified T : UIComponent> ListMenuItem.dockOnSelect() { whenSelected { dock<T>() } } } open class WorkspaceApp(val initiallyDockedView: KClass<out UIComponent>, vararg stylesheet: KClass<out Stylesheet>) : App(Workspace::class, *stylesheet) { override fun onBeforeShow(view: UIComponent) { workspace.dock(find(initiallyDockedView)) } }
apache-2.0
e4f6fd259fde37a2f71427db219a3c24
34.940133
155
0.553924
5.345646
false
false
false
false
johnguant/RedditThing
app/src/main/java/com/johnguant/redditthing/redditapi/ServiceGenerator.kt
1
1598
package com.johnguant.redditthing.redditapi import android.content.Context import com.google.gson.FieldNamingPolicy import com.google.gson.GsonBuilder import com.johnguant.redditthing.BuildConfig import com.johnguant.redditthing.redditapi.model.Thing import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object ServiceGenerator { private val BASE_URL = "https://oauth.reddit.com/" private val gson = GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(Thing::class.java, ThingDeserializer()) private val builder = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson.create())) private val httpClient = OkHttpClient.Builder() .addInterceptor(HeaderInterceptor()) init { if (BuildConfig.DEBUG) { val logging = HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY) httpClient.addInterceptor(logging) } } private var addedAuth = false fun <S> createService(serviceClass: Class<S>, context: Context): S { if (!addedAuth) { httpClient.addInterceptor(AuthInterceptor(context)) addedAuth = true } httpClient.authenticator(OAuthAuthenticator(context)) builder.client(httpClient.build()) val retrofit = builder.build() return retrofit.create(serviceClass) } }
mit
661001f92e72546d23023e7f0b924964
30.333333
80
0.702128
4.827795
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/lang/format/NbttFormattingModelBuilder.kt
1
2744
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.NbttLanguage import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.formatting.FormattingContext import com.intellij.formatting.FormattingModel import com.intellij.formatting.FormattingModelBuilder import com.intellij.formatting.FormattingModelProvider import com.intellij.formatting.Indent import com.intellij.formatting.SpacingBuilder import com.intellij.psi.codeStyle.CodeStyleSettings class NbttFormattingModelBuilder : FormattingModelBuilder { override fun createModel(formattingContext: FormattingContext): FormattingModel { val block = NbttBlock(formattingContext.node, formattingContext.codeStyleSettings, Indent.getNoneIndent(), null) return FormattingModelProvider.createFormattingModelForPsiFile( formattingContext.containingFile, block, formattingContext.codeStyleSettings ) } companion object { fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder { val nbttSettings = settings.getCustomSettings(NbttCodeStyleSettings::class.java) val commonSettings = settings.getCommonSettings(NbttLanguage) val spacesBeforeComma = if (commonSettings.SPACE_BEFORE_COMMA) 1 else 0 val spacesBeforeColon = if (nbttSettings.SPACE_BEFORE_COLON) 1 else 0 val spacesAfterColon = if (nbttSettings.SPACE_AFTER_COLON) 1 else 0 return SpacingBuilder(settings, NbttLanguage) .before(NbttTypes.COLON).spacing(spacesBeforeColon, spacesBeforeColon, 0, false, 0) .after(NbttTypes.COLON).spacing(spacesAfterColon, spacesAfterColon, 0, false, 0) // Empty blocks .between(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spacing(0, 0, 0, false, 0) .between(NbttTypes.LPAREN, NbttTypes.RPAREN).spacing(0, 0, 0, false, 0) .between(NbttTypes.LBRACE, NbttTypes.RBRACE).spacing(0, 0, 0, false, 0) // Non-empty blocks .withinPair(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spaceIf(commonSettings.SPACE_WITHIN_BRACKETS, true) .withinPair(NbttTypes.LPAREN, NbttTypes.RPAREN).spaceIf(commonSettings.SPACE_WITHIN_PARENTHESES, true) .withinPair(NbttTypes.LBRACE, NbttTypes.RBRACE).spaceIf(commonSettings.SPACE_WITHIN_BRACES, true) .before(NbttTypes.COMMA).spacing(spacesBeforeComma, spacesBeforeComma, 0, false, 0) .after(NbttTypes.COMMA).spaceIf(commonSettings.SPACE_AFTER_COMMA) } } }
mit
57875bc0069619ed57fc72e17ad7b2ed
47.140351
120
0.715743
4.611765
false
false
false
false