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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lbbento/pitchup | tuner/src/main/kotlin/com/lbbento/pitchuptuner/GuitarTuner.kt | 1 | 1617 | package com.lbbento.pitchuptuner
import com.lbbento.pitchupcore.InstrumentType.GUITAR
import com.lbbento.pitchuptuner.audio.PitchAudioRecorder
import com.lbbento.pitchuptuner.service.TunerService
import rx.Subscription
class GuitarTuner(pitchAudioRecord: PitchAudioRecorder, private val guitarTunerListener: GuitarTunerListener) {
private var appSchedulers: AppSchedulers
private var tunerService: TunerService
private var subscription: Subscription? = null
init {
tunerService = initializeTunerService(pitchAudioRecord)
appSchedulers = initializeAppSchedulers()
}
internal constructor(pitchAudioRecord: PitchAudioRecorder,
guitarTunerListener: GuitarTunerListener,
tunerService: TunerService,
appSchedulers: AppSchedulers) : this(pitchAudioRecord, guitarTunerListener) {
this.tunerService = tunerService
this.appSchedulers = appSchedulers
}
fun start() {
subscription = tunerService.getNotes()
.subscribeOn(appSchedulers.computation())
.observeOn(appSchedulers.ui())
.subscribe(
{ tunerResult -> guitarTunerListener.onNoteReceived(tunerResult) },
{ throwable -> guitarTunerListener.onError(throwable) })
}
fun stop() {
subscription!!.unsubscribe()
}
private fun initializeTunerService(pitchAudioRecord: PitchAudioRecorder) = TunerService(pitchAudioRecord, GUITAR)
private fun initializeAppSchedulers(): AppSchedulers = AppSchedulers()
} | apache-2.0 | d9c82365b8404e39e7d9a88f7b9343b0 | 36.627907 | 117 | 0.695114 | 4.975385 | false | false | false | false |
googlecodelabs/android-paging | advanced/end/app/src/main/java/com/example/android/codelabs/paging/db/RepoDatabase.kt | 1 | 1622 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelabs.paging.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.android.codelabs.paging.model.Repo
@Database(
entities = [Repo::class, RemoteKeys::class],
version = 1,
exportSchema = false
)
abstract class RepoDatabase : RoomDatabase() {
abstract fun reposDao(): RepoDao
abstract fun remoteKeysDao(): RemoteKeysDao
companion object {
@Volatile
private var INSTANCE: RepoDatabase? = null
fun getInstance(context: Context): RepoDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE
?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
RepoDatabase::class.java, "Github.db"
)
.build()
}
}
| apache-2.0 | 89c85c41103b3da5c8a5b9eda21e017d | 29.603774 | 75 | 0.672626 | 4.55618 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/homescreenwidget/VoiceWidget.kt | 1 | 2098 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui.homescreenwidget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.util.Log
import android.widget.RemoteViews
import androidx.annotation.LayoutRes
import org.openhab.habdroid.R
import org.openhab.habdroid.background.BackgroundTasksManager
import org.openhab.habdroid.util.PendingIntent_Immutable
/**
* Implementation of App Widget functionality.
*/
open class VoiceWidget : AppWidgetProvider() {
internal open val layoutRes: Int @LayoutRes get() = R.layout.widget_voice
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
appWidgetIds.forEach { appWidgetId ->
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, layoutRes)
Log.d(TAG, "Build voice recognition intent")
val intent = BackgroundTasksManager.buildVoiceRecognitionIntent(context, true)
val pendingIntent = PendingIntent.getActivity(context, 6, intent, PendingIntent_Immutable)
views.setOnClickPendingIntent(R.id.outer_layout, pendingIntent)
setupOpenhabIcon(context, views)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
internal open fun setupOpenhabIcon(context: Context, views: RemoteViews) {
// This widget has no openHAB icon displayed.
}
companion object {
private val TAG = VoiceWidget::class.java.simpleName
}
}
| epl-1.0 | b32209923f5bc7bb0a57e854cb5b8064 | 35.172414 | 105 | 0.734986 | 4.704036 | false | false | false | false |
FarbodSalamat-Zadeh/TimetableApp | app/src/main/java/co/timetableapp/data/schema/ClassTimesSchema.kt | 1 | 2136 | /*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.data.schema
import android.provider.BaseColumns
/**
* The schema for the 'class_times' table, containing constants for the column names and an SQLite
* create statement.
*
* @see co.timetableapp.model.ClassTime
*/
object ClassTimesSchema : BaseColumns {
const val TABLE_NAME = "class_times"
const val _ID = BaseColumns._ID
const val COL_TIMETABLE_ID = "timetable_id"
const val COL_CLASS_DETAIL_ID = "class_detail_id"
const val COL_DAY = "day"
const val COL_WEEK_NUMBER = "week_number"
const val COL_START_TIME_HRS = "start_time_hrs"
const val COL_START_TIME_MINS = "start_time_mins"
const val COL_END_TIME_HRS = "end_time_hrs"
const val COL_END_TIME_MINS = "end_time_mins"
/**
* An SQLite statement which creates the 'class_times' table upon execution.
*
* @see co.timetableapp.data.TimetableDbHelper
*/
internal const val SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
BaseColumns._ID + INTEGER_TYPE + PRIMARY_KEY_AUTOINCREMENT + COMMA_SEP +
COL_TIMETABLE_ID + INTEGER_TYPE + COMMA_SEP +
COL_CLASS_DETAIL_ID + INTEGER_TYPE + COMMA_SEP +
COL_DAY + INTEGER_TYPE + COMMA_SEP +
COL_WEEK_NUMBER + INTEGER_TYPE + COMMA_SEP +
COL_START_TIME_HRS + INTEGER_TYPE + COMMA_SEP +
COL_START_TIME_MINS + INTEGER_TYPE + COMMA_SEP +
COL_END_TIME_HRS + INTEGER_TYPE + COMMA_SEP +
COL_END_TIME_MINS + INTEGER_TYPE +
" )"
}
| apache-2.0 | 6fa99c15876b49ed0eaf2051b66200d8 | 36.473684 | 98 | 0.664326 | 3.695502 | false | false | false | false |
OdysseusLevy/kale | src/main/kotlin/org/kale/mail/MailUtils.kt | 1 | 1483 | package org.kale.mail
import com.sun.mail.imap.IMAPFolder
import javax.mail.Message
/**
* @author Odysseus Levy ([email protected])
*/
object MailUtils {
public fun getOrElse(value: Any?, other: Any) = if (value != null) value else other
public fun getOrElse(value: String?, other: String) = if (value != null) value else other
public fun getUID(m: Message): Long {
val folder = m.folder
return when(folder) {
is IMAPFolder -> folder.getUID(m)
else -> -1
}
}
//
// Folder names
//
private val Trash = "Trash"
private val GmailTrash = "[Gmail]/Trash"
private val Spam = "Spam"
private val GmailSpam = "[Gmail]/Spam"
fun trashFolder(account: EmailAccountConfig): String {
return if (isGmail(account))
GmailTrash
else
Trash
}
val gmailTopLevelFolders = setOf("inbox", "deleted messages", "drafts", "sent", "sent messages")
fun isGmail(account: EmailAccountConfig) = account.user.toLowerCase().endsWith("gmail.com")
fun getFolderName(account: EmailAccountConfig, name: String): String {
if (!isGmail(account))
return name
// Handle Gmail specific folders
val lname = name.toLowerCase()
return when(lname) {
"trash" -> "[Gmail]/Trash"
"spam" -> "[Gmail]/Spam"
"drafts" -> "[Gmail]/Drafts"
else -> lname
}
}
} | apache-2.0 | 2987330f21a0b053292ec2728b8a70dc | 24.152542 | 100 | 0.589346 | 3.912929 | false | true | false | false |
pdvrieze/ProcessManager | multiplatform/src/jsMain/kotlin/nl/adaptivity/util/multiplatform/jsStrings.kt | 1 | 1206 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.multiplatform
actual class Locale
actual object Locales {
actual val DEFAULT: Locale = Locale()
actual val ENGLISH: Locale = Locale()
}
@Suppress("NOTHING_TO_INLINE")
actual inline fun String.toLowercase(locale: Locale):String = lowercase()
@Suppress("NOTHING_TO_INLINE", "UnsafeCastFromDynamic")
actual inline fun Int.toHex(): String = asDynamic().toString(16)
@Suppress("NOTHING_TO_INLINE")
actual inline fun String.toCharArray(): CharArray = (this as CharSequence).toCharArray()
| lgpl-3.0 | 29fc150d94d87255f950e3b437316952 | 33.457143 | 112 | 0.752073 | 4.276596 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/repository/DesignerRepository.kt | 1 | 4612 | package com.boardgamegeek.repository
import android.content.SharedPreferences
import androidx.core.content.contentValuesOf
import androidx.lifecycle.MutableLiveData
import com.boardgamegeek.BggApplication
import com.boardgamegeek.db.CollectionDao
import com.boardgamegeek.db.DesignerDao
import com.boardgamegeek.entities.PersonEntity
import com.boardgamegeek.entities.PersonStatsEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.io.Adapter
import com.boardgamegeek.io.BggService
import com.boardgamegeek.mappers.mapToEntity
import com.boardgamegeek.provider.BggContract.Designers
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class DesignerRepository(val application: BggApplication) {
private val dao = DesignerDao(application)
private val prefs: SharedPreferences by lazy { application.preferences() }
suspend fun loadDesigners(sortBy: DesignerDao.SortType) = dao.loadDesigners(sortBy)
suspend fun loadDesigner(designerId: Int) = dao.loadDesigner(designerId)
suspend fun loadCollection(id: Int, sortBy: CollectionDao.SortType) = dao.loadCollection(id, sortBy)
suspend fun delete() = dao.delete()
suspend fun refreshDesigner(designerId: Int): PersonEntity = withContext(Dispatchers.IO) {
val response = Adapter.createForXml().person(BggService.PERSON_TYPE_DESIGNER, designerId)
val missingDesignerMessage = "This page does not exist. You can edit this page to create it."
dao.upsert(
designerId, contentValuesOf(
Designers.Columns.DESIGNER_NAME to response.name,
Designers.Columns.DESIGNER_DESCRIPTION to (if (response.description == missingDesignerMessage) "" else response.description),
Designers.Columns.UPDATED to System.currentTimeMillis()
)
)
response.mapToEntity(designerId)
}
suspend fun refreshImages(designer: PersonEntity): PersonEntity = withContext(Dispatchers.IO) {
val response = Adapter.createForXml().person(designer.id)
response.items.firstOrNull()?.let {
dao.upsert(
designer.id, contentValuesOf(
Designers.Columns.DESIGNER_THUMBNAIL_URL to it.thumbnail,
Designers.Columns.DESIGNER_IMAGE_URL to it.image,
Designers.Columns.DESIGNER_IMAGES_UPDATED_TIMESTAMP to System.currentTimeMillis(),
)
)
designer.copy(thumbnailUrl = it.thumbnail.orEmpty(), imageUrl = it.image.orEmpty())
} ?: designer
}
suspend fun refreshHeroImage(designer: PersonEntity): PersonEntity = withContext(Dispatchers.IO) {
val response = Adapter.createGeekdoApi().image(designer.thumbnailUrl.getImageId())
val url = response.images.medium.url
dao.upsert(designer.id, contentValuesOf(Designers.Columns.DESIGNER_HERO_IMAGE_URL to url))
designer.copy(heroImageUrl = url)
}
suspend fun calculateWhitmoreScores(designers: List<PersonEntity>, progress: MutableLiveData<Pair<Int, Int>>) = withContext(Dispatchers.Default) {
val sortedList = designers.sortedBy { it.statsUpdatedTimestamp }
val maxProgress = sortedList.size
sortedList.forEachIndexed { i, data ->
progress.postValue(i to maxProgress)
val collection = dao.loadCollection(data.id)
val statsEntity = PersonStatsEntity.fromLinkedCollection(collection, application)
updateWhitmoreScore(data.id, statsEntity.whitmoreScore, data.whitmoreScore)
}
prefs[PREFERENCES_KEY_STATS_CALCULATED_TIMESTAMP_DESIGNERS] = System.currentTimeMillis()
progress.postValue(0 to 0)
}
suspend fun calculateStats(designerId: Int): PersonStatsEntity = withContext(Dispatchers.Default) {
val collection = dao.loadCollection(designerId)
val linkedCollection = PersonStatsEntity.fromLinkedCollection(collection, application)
updateWhitmoreScore(designerId, linkedCollection.whitmoreScore)
linkedCollection
}
private suspend fun updateWhitmoreScore(id: Int, newScore: Int, oldScore: Int = -1) = withContext(Dispatchers.IO) {
val realOldScore = if (oldScore == -1) dao.loadDesigner(id)?.whitmoreScore ?: 0 else oldScore
if (newScore != realOldScore) {
dao.upsert(
id, contentValuesOf(
Designers.Columns.WHITMORE_SCORE to newScore,
Designers.Columns.DESIGNER_STATS_UPDATED_TIMESTAMP to System.currentTimeMillis(),
)
)
}
}
}
| gpl-3.0 | f29d25dd587fe61b6942d17a1e08d6c1 | 47.041667 | 150 | 0.710755 | 4.658586 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/extensions/NotificationContext.kt | 1 | 8475 | @file:JvmName("NotificationUtils")
package com.boardgamegeek.extensions
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Build
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import com.boardgamegeek.R
import com.boardgamegeek.ui.HomeActivity
import com.boardgamegeek.ui.PlayActivity
import com.boardgamegeek.util.LargeIconLoader
private const val TAG_PREFIX = "com.boardgamegeek."
const val TAG_PLAY_TIMER = TAG_PREFIX + "PLAY_TIMER"
/**
* Creates a [androidx.core.app.NotificationCompat.Builder] with the correct icons, specified title, and pending intent that goes to the [com.boardgamegeek.ui.HomeActivity].
*/
fun Context.createNotificationBuilder(
@StringRes titleResId: Int,
channelId: String,
cls: Class<*>? = HomeActivity::class.java
): NotificationCompat.Builder {
return createNotificationBuilder(getString(titleResId), channelId, cls)
}
/**
* Creates a [androidx.core.app.NotificationCompat.Builder] with the correct icons, specified title, and pending intent that goes to the [com.boardgamegeek.ui.HomeActivity].
*/
fun Context.createNotificationBuilder(title: String?, channelId: String, cls: Class<*>? = HomeActivity::class.java): NotificationCompat.Builder {
return createNotificationBuilder(title, channelId, Intent(this, cls))
}
/**
* Creates a [NotificationCompat.Builder] with the correct icons, specified title, and pending intent.
*/
fun Context.createNotificationBuilder(@StringRes titleResId: Int, channelId: String, intent: Intent?): NotificationCompat.Builder {
return createNotificationBuilder(getString(titleResId), channelId, intent)
}
/**
* Creates a [NotificationCompat.Builder] with the correct icons, specified title, and pending intent.
*/
fun Context.createNotificationBuilder(
title: String?,
channelId: String,
intent: Intent?
): NotificationCompat.Builder {
val builder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_bgg)
.setColor(ContextCompat.getColor(this, R.color.primary))
.setContentTitle(title)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
val flags = PendingIntent.FLAG_UPDATE_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
val resultPendingIntent = PendingIntent.getActivity(this, 0, intent, flags)
builder.setContentIntent(resultPendingIntent)
return builder
}
fun Context.launchPlayingNotification(
internalId: Long,
gameName: String,
location: String,
playerCount: Int,
startTime: Long,
vararg imageUrl: String,
) {
val loader = LargeIconLoader(this, *imageUrl, callback = object : LargeIconLoader.Callback {
override fun onSuccessfulIconLoad(bitmap: Bitmap) {
buildAndNotifyPlaying(internalId, gameName, location, playerCount, startTime, largeIcon = bitmap)
}
override fun onFailedIconLoad() {
buildAndNotifyPlaying(internalId, gameName, location, playerCount, startTime)
}
})
loader.executeOnMainThread()
}
private fun Context.buildAndNotifyPlaying(
internalId: Long,
gameName: String,
location: String,
playerCount: Int,
startTime: Long,
largeIcon: Bitmap? = null
) {
val builder = createNotificationBuilder(gameName, NotificationChannels.PLAYING)
val intent = PlayActivity.createIntent(this, internalId).clearTop().newTask()
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT or if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
)
var info = ""
if (location.isNotBlank()) info += "${getString(R.string.at)} $location "
if (playerCount > 0) info += resources.getQuantityString(R.plurals.player_description, playerCount, playerCount)
builder
.setContentText(info.trim())
.setLargeIcon(largeIcon)
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
if (startTime > 0) builder.setWhen(startTime).setUsesChronometer(true)
@Suppress("DEPRECATION")
largeIcon?.let { builder.extend(NotificationCompat.WearableExtender().setBackground(it)) }
notify(builder, TAG_PLAY_TIMER, internalId.toInt())
}
/**
* Cancel the notification by a unique ID.
*/
fun Context.cancelNotification(tag: String?, id: Long = 0L) {
NotificationManagerCompat.from(this).cancel(tag, id.toInt())
}
/**
* Display the notification with a unique ID.
*/
fun Context.notify(builder: NotificationCompat.Builder, tag: String?, id: Int = 0) {
NotificationManagerCompat.from(this).notify(tag, id, builder.build())
}
object NotificationChannels {
const val SYNC_PROGRESS = "sync"
const val ERROR = "sync_error"
const val SYNC_UPLOAD = "sync_upload"
const val PLAYING = "playing"
const val STATS = "stats"
const val FIREBASE_MESSAGES = "firebase_messages"
@TargetApi(Build.VERSION_CODES.O)
fun create(context: Context?) {
val notificationManager = context?.getSystemService<NotificationManager>() ?: return
notificationManager.createNotificationChannel(
NotificationChannel(
SYNC_PROGRESS,
context.getString(R.string.channel_name_sync_progress),
NotificationManager.IMPORTANCE_LOW
).apply {
description = context.getString(R.string.channel_description_sync_progress)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
SYNC_UPLOAD,
context.getString(R.string.channel_name_sync_upload),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = context.getString(R.string.channel_description_sync_upload)
})
notificationManager.createNotificationChannel(
NotificationChannel(
ERROR,
context.getString(R.string.channel_name_sync_error),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = context.getString(R.string.channel_description_sync_error)
lightColor = Color.RED
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
PLAYING,
context.getString(R.string.channel_name_playing),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = context.getString(R.string.channel_description_playing)
lightColor = Color.BLUE
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
STATS,
context.getString(R.string.channel_name_stats),
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = context.getString(R.string.channel_description_stats)
}
)
notificationManager.createNotificationChannel(
NotificationChannel(
FIREBASE_MESSAGES,
context.getString(R.string.channel_name_firebase_messages),
NotificationManager.IMPORTANCE_HIGH
).apply {
description = context.getString(R.string.channel_description_firebase_messages)
}
)
}
}
object NotificationTags {
private const val TAG_PREFIX = "com.boardgamegeek."
const val PLAY_STATS = TAG_PREFIX + "PLAY_STATS"
const val PROVIDER_ERROR = TAG_PREFIX + "PROVIDER_ERROR"
const val SYNC_PROGRESS = TAG_PREFIX + "SYNC_PROGRESS"
const val SYNC_ERROR = TAG_PREFIX + "SYNC_ERROR"
const val UPLOAD_PLAY = TAG_PREFIX + "UPLOAD_PLAY"
const val UPLOAD_PLAY_ERROR = TAG_PREFIX + "UPLOAD_PLAY_ERROR"
const val UPLOAD_COLLECTION = TAG_PREFIX + "UPLOAD_COLLECTION"
const val UPLOAD_COLLECTION_ERROR = TAG_PREFIX + "UPLOAD_COLLECTION_ERROR"
const val FIREBASE_MESSAGE = TAG_PREFIX + "FIREBASE_MESSAGE"
}
| gpl-3.0 | 8945c073feffebef7f128d0631d2d8f0 | 36.834821 | 173 | 0.694867 | 4.758563 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientDiggingDecoder.kt | 1 | 1761 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import io.netty.handler.codec.DecoderException
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientDropHeldItemPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.FinishUsingItemPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientDiggingPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSwapHandItemsPacket
object ClientDiggingDecoder : PacketDecoder<Packet> {
private val diggingActions = ClientDiggingPacket.Action.values()
override fun decode(ctx: CodecContext, buf: ByteBuffer): Packet {
val action = buf.readByte().toInt()
val position = buf.readBlockPosition()
val face = buf.readByte().toInt()
return when (action) {
0, 1, 2 -> ClientDiggingPacket(this.diggingActions[action], position, CodecUtils.decodeDirection(face))
3, 4 -> ClientDropHeldItemPacket(action == 3)
5 -> FinishUsingItemPacket
6 -> ClientSwapHandItemsPacket
else -> throw DecoderException("Unknown player digging message action: $action")
}
}
}
| mit | de753c4d5553a22ce064dcac3330f796 | 44.153846 | 115 | 0.752981 | 4.223022 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/ext/String.kt | 5 | 2071 | /* 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.ext
import android.net.Uri
import org.mozilla.focus.utils.UrlUtils
// Extension functions for the String class
/**
* Beautify a URL by truncating it in a way that highlights important parts of the URL.
*
* Spec: https://github.com/mozilla-mobile/focus-android/issues/1231#issuecomment-326237077
*/
fun String.beautifyUrl(): String {
if (isNullOrEmpty() || !UrlUtils.isHttpOrHttps(this)) {
return this
}
val beautifulUrl = StringBuilder()
val uri = Uri.parse(this)
// Use only the truncated host name
val truncatedHost = uri.truncatedHost()
if (truncatedHost.isNullOrEmpty()) {
return this
}
beautifulUrl.append(truncatedHost)
// Append the truncated path
val truncatedPath = uri.truncatedPath()
if (!truncatedPath.isNullOrEmpty()) {
beautifulUrl.append(truncatedPath)
}
// And then append (only) the first query parameter
val query = uri.query
if (!query.isNullOrEmpty()) {
beautifulUrl.append("?")
beautifulUrl.append(query.split("&").first())
}
// We always append a fragment if there's one
val fragment = uri.fragment
if (!fragment.isNullOrEmpty()) {
beautifulUrl.append("#")
beautifulUrl.append(fragment)
}
return beautifulUrl.toString()
}
/**
* If this string starts with the one or more of the given [prefixes] (in order and ignoring case),
* returns a copy of this string with the prefixes removed. Otherwise, returns this string.
*/
fun String.removePrefixesIgnoreCase(vararg prefixes: String): String {
var value = this
var lower = this.toLowerCase()
prefixes.forEach {
if (lower.startsWith(it.toLowerCase())) {
value = value.substring(it.length)
lower = lower.substring(it.length)
}
}
return value
}
| mpl-2.0 | d8ecb369aa1f261a929c442a8b168f4c | 25.896104 | 99 | 0.670208 | 3.929791 | false | false | false | false |
LISTEN-moe/android-app | app/src/main/kotlin/me/echeung/moemoekyun/util/SongSortUtil.kt | 1 | 3659 | package me.echeung.moemoekyun.util
import android.content.Context
import android.view.Menu
import android.view.MenuItem
import androidx.preference.PreferenceManager
import me.echeung.moemoekyun.R
import me.echeung.moemoekyun.adapter.SongsListAdapter
import me.echeung.moemoekyun.client.model.Song
import java.util.Comparator
class SongSortUtil(
private val context: Context,
) {
fun setListSortType(listId: String, sortType: String) {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
sharedPrefs.edit()
.putString(PREF_LIST_PREFIX_TYPE + listId, sortType)
.apply()
}
fun setListSortDescending(listId: String, descending: Boolean) {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
sharedPrefs.edit()
.putBoolean(PREF_LIST_PREFIX_DESC + listId, descending)
.apply()
}
fun getComparator(listId: String): Comparator<Song> {
val sortType = getSortTypeByListId(listId)
val sortDescending = getSortDescendingByListId(listId)
return when (sortType) {
SORT_ARTIST ->
if (sortDescending) {
compareByDescending(String.CASE_INSENSITIVE_ORDER) { it.artistsString ?: "" }
} else {
compareBy(String.CASE_INSENSITIVE_ORDER) { it.artistsString ?: "" }
}
// Default is SORT_TITLE
else ->
if (sortDescending) {
compareByDescending(String.CASE_INSENSITIVE_ORDER) { it.titleString ?: "" }
} else {
compareBy(String.CASE_INSENSITIVE_ORDER) { it.titleString ?: "" }
}
}
}
fun initSortMenu(listId: String, menu: Menu) {
val sortTypeId = when (getSortTypeByListId(listId)) {
SORT_ARTIST -> R.id.action_sort_type_artist
// Default is SORT_TITLE
else -> R.id.action_sort_type_title
}
menu.findItem(sortTypeId).isChecked = true
val sortDescending = getSortDescendingByListId(listId)
menu.findItem(R.id.action_sort_desc).isChecked = sortDescending
}
fun handleSortMenuItem(item: MenuItem, adapter: SongsListAdapter): Boolean {
when (item.itemId) {
R.id.action_sort_desc -> {
item.isChecked = !item.isChecked
adapter.sortDescending(item.isChecked)
return true
}
R.id.action_sort_type_title -> {
item.isChecked = true
adapter.sortType(SORT_TITLE)
return true
}
R.id.action_sort_type_artist -> {
item.isChecked = true
adapter.sortType(SORT_ARTIST)
return true
}
}
return false
}
private fun getSortTypeByListId(listKey: String): String {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
return sharedPrefs.getString(PREF_LIST_PREFIX_TYPE + listKey, SORT_TITLE)!!
}
private fun getSortDescendingByListId(listKey: String): Boolean {
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
return sharedPrefs.getBoolean(PREF_LIST_PREFIX_DESC + listKey, false)
}
companion object {
private const val PREF_LIST_PREFIX_TYPE = "song_sort_list_type_"
private const val PREF_LIST_PREFIX_DESC = "song_sort_list_desc_"
private const val SORT_TITLE = "song_sort_title"
private const val SORT_ARTIST = "song_sort_artist"
}
}
| mit | 592d6fbace2602ca3b37cac0ef301ea4 | 33.847619 | 97 | 0.617108 | 4.661146 | false | false | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/init/BootReason.kt | 1 | 1151 | package init
class BootReason {
/*
Canonical boot reason format
<reason>,<subreason>,<detail>…
*/
class Reason private constructor(private val reason: String, subReason: String?, detail: String?) {
companion object {
val kernelSet = listOf("watchdog", "kernel_panic")
val strongSet = listOf("recovery", "bootloader")
val bluntSet = listOf("cold", "hard", "warm", "shutdown", "reboot")
fun create(
firstSpanReason: String,
secondSpanReason: String? = null,
detailReason: String? = null
): Reason {
if (firstSpanReason !in mutableListOf<String>().apply {
addAll(kernelSet)
addAll(strongSet)
addAll(bluntSet)
}) {
throw IllegalArgumentException("$firstSpanReason is not allowd first span boot reason in Android")
}
return Reason(firstSpanReason, secondSpanReason, detailReason)
}
}//end-of-companion
} //end-of-Reason
} //EOF
| apache-2.0 | 188afd055a40dae400dbc308c1161efd | 38.62069 | 118 | 0.537859 | 5.017467 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | test/nl/hannahsten/texifyidea/inspections/latex/probablebugs/LatexUnicodeInspectionTest.kt | 1 | 3801 | package nl.hannahsten.texifyidea.inspections.latex.probablebugs
import io.mockk.every
import io.mockk.mockkStatic
import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase
import nl.hannahsten.texifyidea.util.runCommandWithExitCode
class OutsideMathLatexUnicodeInspectionTest : LatexUnicodeInspectionTest() {
fun `test illegal unicode character`() {
setUnicodeSupport(false)
myFixture.configureByText(LatexFileType, "<error descr=\"Unsupported non-ASCII character\">î</error>")
myFixture.checkHighlighting()
}
fun `test support by loaded packages`() {
setUnicodeSupport(false)
myFixture.configureByText(LatexFileType, """
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
î
""".trimIndent())
myFixture.checkHighlighting()
}
fun `test legal unicode character with compiler compatibility`() {
setUnicodeSupport()
myFixture.configureByText(LatexFileType, "î")
myFixture.checkHighlighting()
}
}
class InsideMathLatexUnicodeInspectionTest : LatexUnicodeInspectionTest() {
override fun setUp() {
super.setUp()
mockkStatic(::runCommandWithExitCode)
every { runCommandWithExitCode(*anyVararg(), workingDirectory = any(), timeout = any(), returnExceptionMessage = any()) } returns Pair(null, 0)
}
fun `test without support`() {
setUnicodeSupport(false)
myFixture.configureByText(LatexFileType, "\$<error descr=\"Unsupported non-ASCII character\">î</error>\$")
myFixture.checkHighlighting()
}
fun `test with loaded packages`() {
setUnicodeSupport()
myFixture.configureByText(LatexFileType, "\\usepackage[utf8]{inputenc}\n" +
" \\usepackage[T1]{fontenc}\n" +
"\$<error descr=\"Unsupported non-ASCII character\">î</error>\$")
myFixture.checkHighlighting()
}
fun `test with compiler compatibility`() {
setUnicodeSupport()
myFixture.configureByText(LatexFileType, "\$<error descr=\"Unsupported non-ASCII character\">î</error>\$")
myFixture.checkHighlighting()
}
}
class LatexUnicodeInspectionQuickFix : LatexUnicodeInspectionTest() {
fun `test include packages quick fix`() {
setUnicodeSupport(false)
testNamedQuickFix("\nî", """
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
î""".trimIndent(),
"Include Unicode support packages", 2)
}
@Suppress("NonAsciiCharacters")
fun `test escape unicode quick fix é`() {
setUnicodeSupport(false)
testNamedQuickFix("é", "\\'e", "Escape Unicode character", 2)
}
@Suppress("NonAsciiCharacters")
fun `test escape unicode quick fix î`() {
setUnicodeSupport(false)
testNamedQuickFix("î", "\\^{\\i}", "Escape Unicode character", 2)
}
fun `test escape unicode quick fix regular command`() {
setUnicodeSupport(false)
testNamedQuickFix("å", "\\aa", "Escape Unicode character", 2)
}
fun `test escape unicode quick fix known math command`() {
setUnicodeSupport(false)
testNamedQuickFix("\$α\$", "\$\\alpha\$", "Escape Unicode character", 1)
}
fun `test escape unicode quick fix math command`() {
setUnicodeSupport(false)
// ℂ cannot be converted.
testNamedQuickFix("\$ℂ\$", "\$ℂ\$", "Escape Unicode character", 1)
}
}
abstract class LatexUnicodeInspectionTest : TexifyInspectionTestBase(LatexUnicodeInspection()) {
fun setUnicodeSupport(enabled: Boolean = true) = nl.hannahsten.texifyidea.testutils.setUnicodeSupport(myFixture.project, enabled)
} | mit | 05bbb9ce62d6784c0c14f525d88b3f66 | 31.050847 | 151 | 0.662523 | 4.685254 | false | true | false | false |
debop/debop4k | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/MonthRange.kt | 1 | 1739 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.timeperiod.timeranges
import debop4k.core.kodatimes.asDate
import debop4k.core.kodatimes.today
import debop4k.timeperiod.DefaultTimeCalendar
import debop4k.timeperiod.ITimeCalendar
import debop4k.timeperiod.models.YearMonth
import debop4k.timeperiod.utils.startTimeOfMonth
import org.joda.time.DateTime
/**
* Created by debop
*/
open class MonthRange @JvmOverloads constructor(startTime: DateTime = today(),
calendar: ITimeCalendar = DefaultTimeCalendar) :
MonthTimeRange(startTime, 1, calendar) {
@JvmOverloads
constructor(year: Int, monthOfYear: Int, calendar: ITimeCalendar = DefaultTimeCalendar)
: this(startTimeOfMonth(year, monthOfYear), calendar)
constructor(startYm: YearMonth) : this(asDate(startYm.year, startYm.monthOfYear))
val year: Int get() = startYear
val monthOfYear: Int get() = startMonthOfYear
fun addMonths(months: Int): MonthRange {
return MonthRange(start.plusMonths(months), calendar)
}
val nextMonth: MonthRange get() = addMonths(1)
val prevMonth: MonthRange get() = addMonths(-1)
} | apache-2.0 | 0a3ebd70dd05999d9470a9e6314c9d13 | 34.510204 | 96 | 0.742381 | 4.150358 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/widget/RawJsonConverterFactory.kt | 1 | 1240 | package me.ykrank.s1next.widget
import com.github.ykrank.androidtools.util.StringUtil
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.io.IOException
import java.lang.reflect.Type
/**
* decode like `\ u` unicode response string.
* and fix illegal json error
*/
class RawJsonConverterFactory private constructor() : Converter.Factory() {
override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, *>? {
if (type === String::class.java) {
return RawJsonResponseBodyConverter
}
return null
}
private object RawJsonResponseBodyConverter : Converter<ResponseBody, String> {
@Throws(IOException::class)
override fun convert(value: ResponseBody): String {
var str = value.string()
//decode like `\ u` unicode response string
str = StringUtil.uniDecode(str)
//replace like `A:,` with `A:null,`
str = str.replace(":,", ":null,")
return str
}
}
companion object {
fun create(): RawJsonConverterFactory {
return RawJsonConverterFactory()
}
}
}
| apache-2.0 | 75c2f4838522a3caac54c45b99266961 | 27.837209 | 136 | 0.65 | 4.644195 | false | false | false | false |
jamieadkins95/Roach | app/src/main/java/com/jamieadkins/gwent/deck/list/DeckListFragment.kt | 1 | 2969 | package com.jamieadkins.gwent.deck.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.jamieadkins.gwent.R
import com.jamieadkins.gwent.base.FeatureNavigator
import com.jamieadkins.gwent.bus.GwentDeckClickEvent
import com.jamieadkins.gwent.bus.RxBus
import com.jamieadkins.gwent.base.VerticalSpaceItemDecoration
import com.jamieadkins.gwent.deck.create.CreateDeckDialog
import com.jamieadkins.gwent.domain.deck.model.GwentDeck
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.appbar_layout.*
import kotlinx.android.synthetic.main.fragment_deck_list.*
import javax.inject.Inject
class DeckListFragment : DaggerFragment(), DeckListContract.View {
@Inject lateinit var presenter: DeckListContract.Presenter
private val adapter = GroupAdapter<ViewHolder>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_deck_list, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as? AppCompatActivity)?.apply {
setSupportActionBar(toolbar)
title = getString(R.string.deck_builder)
}
toolbar.setTitleTextAppearance(requireContext(), R.style.GwentTextAppearance)
loadingIndicator.setColorSchemeResources(R.color.gwentAccent)
loadingIndicator.isEnabled = false
val layoutManager = LinearLayoutManager(recyclerView.context)
recyclerView.layoutManager = layoutManager
val dividerItemDecoration = VerticalSpaceItemDecoration(resources.getDimensionPixelSize(R.dimen.divider_spacing))
recyclerView.addItemDecoration(dividerItemDecoration)
recyclerView.adapter = adapter
adapter.setOnItemClickListener { item, _ ->
when (item) {
is DeckListItem -> RxBus.post(GwentDeckClickEvent(item.deck.id))
}
}
btnCreate.setOnClickListener {
val dialog = CreateDeckDialog()
dialog.show(activity?.supportFragmentManager, dialog.tag)
}
presenter.onAttach()
}
override fun onDestroyView() {
presenter.onDetach()
super.onDestroyView()
}
override fun showDecks(decks: List<GwentDeck>) {
adapter.update(decks.map { DeckListItem(it) })
}
override fun showDeckDetails(deckId: String) {
activity?.let(::FeatureNavigator)?.openDeckBuilder(deckId)
}
override fun showLoadingIndicator(loading: Boolean) { loadingIndicator.isRefreshing = loading }
}
| apache-2.0 | e73cd077e3b076f2abcb68f905910743 | 36.1125 | 121 | 0.737622 | 5.040747 | false | false | false | false |
yotkaz/thimman | thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/Skill.kt | 1 | 844 | package yotkaz.thimman.backend.model
import com.fasterxml.jackson.annotation.JsonIgnore
import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR
import java.util.*
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.persistence.ManyToMany
@Entity
data class Skill(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long? = null,
var name: String,
var description: String,
@JsonIgnore
@ManyToMany(fetch = FetchType.EAGER)
var persons: Set<Person> = HashSet(),
@JsonIgnore
@ManyToMany(fetch = FetchType.EAGER)
var jobOffers: Set<JobOffer> = HashSet()
) {
@Deprecated(JPA_EMPTY_CONSTRUCTOR)
constructor() : this(
name = "",
description = ""
)
} | apache-2.0 | b388dbc09afea0d886a9c50f7bb08473 | 21.837838 | 55 | 0.663507 | 4.262626 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/main/MainActivity.kt | 1 | 12886 | package com.quickblox.sample.conference.kotlin.presentation.screens.main
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.sample.conference.kotlin.R
import com.quickblox.sample.conference.kotlin.databinding.ActivityMainBinding
import com.quickblox.sample.conference.kotlin.databinding.PopupMainLayoutBinding
import com.quickblox.sample.conference.kotlin.presentation.screens.appinfo.AppInfoActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.chat.ChatActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.createchat.CreateChatActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.login.LoginActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.main.DialogsAdapter.DialogsAdapterStates.Companion.DEFAULT
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.DIALOG_UPDATED
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.ERROR
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.LIST_DIALOGS_UPDATED
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.MOVE_TO_FIRST_DIALOG
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.PROGRESS
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_CHAT_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_DIALOGS
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_LOGIN_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.USER_ERROR
import com.quickblox.sample.conference.kotlin.presentation.screens.settings.audio.AudioSettingsActivity
import com.quickblox.sample.conference.kotlin.presentation.screens.settings.video.VideoSettingsActivity
import com.quickblox.sample.conference.kotlin.presentation.utils.AvatarUtils
import com.quickblox.sample.conference.kotlin.presentation.utils.convertToPx
import com.quickblox.users.model.QBUser
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
const val POPUP_MAIN_WIDTH = 200
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@AndroidEntryPoint
class MainActivity : BaseActivity<MainViewModel>(MainViewModel::class.java) {
private lateinit var binding: ActivityMainBinding
private var dialogsAdapter: DialogsAdapter? = null
private val onScrollListenerImpl = OnScrollListenerImpl()
companion object {
fun start(context: Context) {
val intent = Intent(context, MainActivity::class.java)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initView()
initAdapter()
showUser(viewModel.user)
setAvatarClickListener()
initScrollListeners()
viewModel.liveData.observe(this, { result ->
result?.let { (state, data) ->
when (state) {
PROGRESS -> {
showProgress()
}
SHOW_LOGIN_SCREEN -> {
LoginActivity.start(this)
finish()
}
ERROR -> {
hideProgress()
Toast.makeText(baseContext, "$data", Toast.LENGTH_SHORT).show()
}
MOVE_TO_FIRST_DIALOG -> {
dialogsAdapter?.moveToFirst(data as QBChatDialog)
}
LIST_DIALOGS_UPDATED -> {
hideProgress()
dialogsAdapter?.notifyDataSetChanged()
}
DIALOG_UPDATED -> {
dialogsAdapter?.notifyItemChanged(data as Int)
}
USER_ERROR -> {
Toast.makeText(baseContext, getString(R.string.user_error), Toast.LENGTH_SHORT).show()
viewModel.singOut()
}
SHOW_DIALOGS -> {
hideProgress()
dialogsAdapter?.notifyDataSetChanged()
if (viewModel.getDialogs().isEmpty()) {
binding.rvDialogs.visibility = View.GONE
binding.tvPlaceHolder.visibility = View.VISIBLE
} else {
binding.rvDialogs.visibility = View.VISIBLE
binding.tvPlaceHolder.visibility = View.GONE
}
}
SHOW_CHAT_SCREEN -> {
val dialog = data as QBChatDialog
ChatActivity.start(this@MainActivity, dialog.dialogId)
}
ViewState.SHOW_CREATE_SCREEN -> {
CreateChatActivity.start(this@MainActivity)
}
}
}
})
}
private fun initScrollListeners() {
val mLayoutManager = LinearLayoutManager(this)
binding.rvDialogs.layoutManager = mLayoutManager
// TODO: 6/10/21 Commented the scroll for pagination
//binding.rvDialogs.addOnScrollListener(onScrollListenerImpl)
}
private fun initAdapter() {
dialogsAdapter = DialogsAdapter(viewModel.getDialogs(), object : DialogsAdapter.DialogAdapterListener {
override fun onChanged(state: Int) {
when (state) {
DialogsAdapter.DialogsAdapterStates.SELECT -> {
binding.toolbarMain.menu.clear()
binding.toolbarMain.inflateMenu(R.menu.menu_delete_dialogs)
binding.flBack.visibility = View.VISIBLE
binding.rlAvatar.visibility = View.GONE
binding.tvSubTitle.visibility = View.VISIBLE
binding.toolbarTitle.text = getString(R.string.delete_chats)
binding.flBack.setOnClickListener {
binding.toolbarMain.inflateMenu(R.menu.menu_main)
binding.toolbarMain.menu.clear()
binding.toolbarMain.inflateMenu(R.menu.menu_main)
dialogsAdapter?.setState(DEFAULT)
}
}
DEFAULT -> {
binding.toolbarMain.menu.clear()
binding.toolbarMain.inflateMenu(R.menu.menu_main)
binding.toolbarTitle.text = getString(R.string.main_toolbar_title)
binding.flBack.visibility = View.GONE
binding.rlAvatar.visibility = View.VISIBLE
binding.tvSubTitle.visibility = View.GONE
}
}
}
override fun onSelected(selectedCounter: Int) {
if (selectedCounter != 0) {
binding.toolbarMain.menu.clear()
binding.toolbarMain.inflateMenu(R.menu.menu_delete_dialogs)
} else {
binding.toolbarMain.menu.removeItem(R.id.deleteDialogs)
}
binding.tvSubTitle.text = if (selectedCounter > 1) {
getString(R.string.subtitle_main_chats, selectedCounter.toString())
} else {
getString(R.string.subtitle_main_chat, selectedCounter.toString())
}
}
override fun onDialogClicked(dialog: QBChatDialog) {
viewModel.onDialogClicked(dialog)
}
})
binding.rvDialogs.layoutManager = LinearLayoutManager(this)
binding.rvDialogs.itemAnimator = null
binding.rvDialogs.setHasFixedSize(true)
binding.rvDialogs.adapter = dialogsAdapter
}
private fun initView() {
binding.toolbarMain.inflateMenu(R.menu.menu_main)
binding.toolbarMain.setOnMenuItemClickListener {
when (it.itemId) {
R.id.deleteDialogs -> {
openAlertDialog()
}
R.id.menuNewChat -> {
viewModel.showCreateScreen()
}
}
return@setOnMenuItemClickListener true
}
binding.flBack.visibility = View.GONE
binding.rlAvatar.visibility = View.VISIBLE
binding.tvSubTitle.visibility = View.GONE
binding.swipeRefresh.setOnRefreshListener {
showProgress()
viewModel.loadDialogs(refresh = true, reJoin = false)
}
binding.swipeRefresh.setColorSchemeColors(ContextCompat.getColor(baseContext, R.color.colorPrimary))
}
private fun setAvatarClickListener() {
binding.rlAvatar.setOnClickListener {
val layoutInflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
val bindingPopUp = PopupMainLayoutBinding.inflate(layoutInflater)
val popupWindow = PopupWindow(bindingPopUp.root, POPUP_MAIN_WIDTH.convertToPx(), ViewGroup.LayoutParams.WRAP_CONTENT)
popupWindow.isOutsideTouchable = true
popupWindow.showAsDropDown(it)
bindingPopUp.tvName.text = viewModel.user?.fullName
bindingPopUp.tvVideoConf.setOnClickListener {
VideoSettingsActivity.start(this@MainActivity)
popupWindow.dismiss()
}
bindingPopUp.tvAudioConf.setOnClickListener {
AudioSettingsActivity.start(this@MainActivity)
popupWindow.dismiss()
}
bindingPopUp.tvInfo.setOnClickListener {
AppInfoActivity.start(this@MainActivity)
popupWindow.dismiss()
}
bindingPopUp.tvLogout.setOnClickListener {
viewModel.singOut()
popupWindow.dismiss()
}
}
}
private fun showUser(user: QBUser?) {
binding.tvAvatar.text = user?.fullName?.substring(0, 1)?.toUpperCase(Locale.getDefault())
binding.ivAvatar.setImageDrawable(user?.id?.let {
AvatarUtils.getDrawableAvatar(baseContext, it)
})
}
override fun showProgress() {
binding.swipeRefresh.isRefreshing = false
binding.progressBar.visibility = View.VISIBLE
}
override fun hideProgress() {
onScrollListenerImpl.isLoad = false
binding.progressBar.visibility = View.GONE
}
private fun openAlertDialog() {
val alertDialogBuilder = AlertDialog.Builder(this, R.style.AlertDialogStyle)
alertDialogBuilder.setTitle(getString(R.string.delete_dialogs))
alertDialogBuilder.setMessage(getString(R.string.delete_question))
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton(getString(R.string.delete)) { _, _ ->
val list = arrayListOf<QBChatDialog>()
dialogsAdapter?.getSelectedDialogs()?.let { list.addAll(it) }
dialogsAdapter?.clearSelectedDialogs()
leaveGroupDialogs(list)
dialogsAdapter?.setState(DEFAULT)
}
alertDialogBuilder.setNegativeButton(getString(R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
alertDialogBuilder.create()
alertDialogBuilder.show()
}
private fun leaveGroupDialogs(groupDialogsToDelete: ArrayList<QBChatDialog>) {
viewModel.deleteDialogs(groupDialogsToDelete)
}
inner class OnScrollListenerImpl : RecyclerView.OnScrollListener() {
var isLoad: Boolean = false
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (!recyclerView.canScrollVertically(1) || isLoad) {
isLoad = true
viewModel.loadDialogs(refresh = false, reJoin = false)
}
}
}
} | bsd-3-clause | e61d3e397d9a9c4013e51c46ef246fe4 | 43.898955 | 129 | 0.629647 | 5.362047 | false | false | false | false |
Guardsquare/proguard | base/src/test/kotlin/proguard/obfuscate/SimpleNameFactoryTest.kt | 1 | 1915 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2022 Guardsquare NV
*
* 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 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.obfuscate
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.collections.shouldNotBeIn
class SimpleNameFactoryTest : StringSpec({
val reservedNames = listOf("AUX", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "CON", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "NUL", "PRN")
"Should not generate WINDOWS reserved names with mixed case enabled" {
val factory = SimpleNameFactory(true)
// 115895 is index for generating PRN with mixed case enabled.
repeat(115896) {
val name = factory.nextName()
name.uppercase() shouldNotBeIn reservedNames
}
}
"Should not generate WINDOWS reserved names with mixed case disabled" {
val factory = SimpleNameFactory(false)
// 44213 is index for generating prn with mixed case disabled.
repeat(44214) {
val name = factory.nextName()
name.uppercase() shouldNotBeIn reservedNames
}
}
})
| gpl-2.0 | d3a47108cdcf6288d3f6dd7990e9ec0b | 38.081633 | 202 | 0.684595 | 4.100642 | false | true | false | false |
andela-kogunde/CheckSmarter | app/src/main/kotlin/com/andela/checksmarter/views/CheckSmarterView.kt | 1 | 3655 | package com.andela.checksmarter.views
import android.content.Context
import android.content.Intent
import android.support.v7.widget.GridLayoutManager
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.Toast
import com.andela.checksmarter.Extensions.createCheckSmarter
import com.andela.checksmarter.activities.DetailActivity
import com.andela.checksmarter.activities.MainActivity
import com.andela.checksmarter.adapters.CheckSmarterAdapter
import com.andela.checksmarter.model.CheckSmarterJava
import com.andela.checksmarter.model.CheckSmarterTaskJava
import com.andela.checksmarter.utilities.Exchange
import com.andela.checksmarter.utilities.MsgBox
import com.andela.checksmarter.utilities.databaseCollection.DBCollection
import io.realm.Realm
import io.realm.RealmList
import io.realm.RealmResults
import kotlinx.android.synthetic.main.fragment_main.view.*
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Func1
import rx.subjects.PublishSubject
import rx.subscriptions.CompositeSubscription
import kotlin.properties.Delegates
/**
* Created by CodeKenn on 18/04/16.
*/
class CheckSmarterView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs), CheckSmarterAdapter.CheckSmarterClickListener {
val CHECK_SMARTER = "checksmarter"
private val checkSmarterAdapter = CheckSmarterAdapter(this)
private val subscriptions = CompositeSubscription()
private val dbCollection = DBCollection()
override fun onCheckSmarterClick(checkSmarter: CheckSmarterJava) {
var newCheckSmarter = Exchange().getParcelableCheckSmarter(checkSmarter)
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(CHECK_SMARTER, newCheckSmarter)
context.startActivity(intent)
MsgBox.show(context, "ID: ${checkSmarter.id}")
}
fun createNewCheckSmarter() {
val intent = Intent(context, DetailActivity::class.java)
context.startActivity(intent)
}
override fun onCheckSmarterLongClick(checkSmarter: CheckSmarterJava) {
MsgBox.show(context, "LONG CLICK ID: ${checkSmarter.id}")
}
override fun onFinishInflate() {
super.onFinishInflate()
checkSmarterView.layoutManager = GridLayoutManager(context, 2)
checkSmarterView.adapter = checkSmarterAdapter
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val publishSubject: PublishSubject<CheckSmarterJava>
publishSubject = PublishSubject.create()
val result = publishSubject
.flatMap(checkSmarterSearch)
.observeOn(AndroidSchedulers.mainThread())
.share()
subscriptions.add(result
.subscribe(checkSmarterAdapter))
var result2 = publishSubject
.flatMap(checkSmarterChecked)
.observeOn(AndroidSchedulers.mainThread())
.share()
subscriptions.add(result2
.subscribe(context as MainActivity))
post { publishSubject.onNext(CheckSmarterJava(0)) }
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
subscriptions.unsubscribe()
}
private val checkSmarterSearch = Func1<CheckSmarterJava, Observable<RealmResults<CheckSmarterJava>>> { checkSmarter ->
dbCollection.findAll(CheckSmarterJava::class.java)
}
private val checkSmarterChecked = Func1<CheckSmarterJava, Observable<RealmResults<CheckSmarterJava>>> { checkSmarter ->
dbCollection.findByChecked(CheckSmarterJava::class.java, "check", true)
}
} | mit | aad0f88a8e9b3a42d0ae7703f96c1084 | 34.843137 | 143 | 0.745007 | 5.013717 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/Project.kt | 1 | 2234 | package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonProperty
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.YesNo
/**
* A project in Ontrack. Usually associated with a SCM repository, this is the main entity in the Ontrack
* model.
*/
data class Project(
override val id: ID,
val name: String,
override val description: String?,
@JsonProperty("disabled")
val isDisabled: Boolean,
override val signature: Signature
) : ProjectEntity {
fun withDisabled(isDisabled: Boolean) = Project(id, name, description, isDisabled, signature)
fun withSignature(signature: Signature) = Project(id, name, description, isDisabled, signature)
fun withDescription(description: String) = Project(id, name, description, isDisabled, signature)
fun withId(id: ID) = Project(id, name, description, isDisabled, signature)
companion object {
/**
* Maximum length for the name of a project
*/
const val PROJECT_NAME_MAX_LENGTH = 80
@JvmStatic
fun of(nameDescription: NameDescriptionState) =
Project(ID.NONE, nameDescription.name, nameDescription.description, nameDescription.isDisabled, Signature.anonymous())
@JvmStatic
fun of(nameDescription: NameDescription) =
Project(ID.NONE, nameDescription.name, nameDescription.description, false, Signature.anonymous())
@JvmStatic
fun form(): Form =
Form.nameAndDescription()
.with(
YesNo.of("disabled").label("Disabled").help("Check if the project must be disabled.")
)
}
override val project: Project get() = this
override val entityDisplayName: String get() = "Project $name"
override val parent: ProjectEntity? = null
override val projectEntityType: ProjectEntityType = ProjectEntityType.PROJECT
fun update(form: NameDescriptionState): Project =
of(form).withId(id).withDisabled(form.isDisabled)
fun asForm(): Form =
form().name(name).description(description).fill("disabled", isDisabled)
}
| mit | 122b42db511d81428312394e366ccd56 | 32.848485 | 134 | 0.663832 | 4.888403 | false | false | false | false |
soywiz/korge | korge/src/jvmMain/kotlin/com/soywiz/korge/atlas/AtlasResourceProcessor.kt | 1 | 2299 | package com.soywiz.korge.atlas
import com.soywiz.korge.resources.ResourceProcessor
import com.soywiz.korim.atlas.*
import com.soywiz.korim.bitmap.slice
import com.soywiz.korim.format.ImageEncodingProps
import com.soywiz.korim.format.PNG
import com.soywiz.korim.format.readBitmap
import com.soywiz.korio.dynamic.mapper.*
import com.soywiz.korio.dynamic.serialization.stringifyTyped
import com.soywiz.korio.file.*
import com.soywiz.korio.serialization.json.Json
import com.soywiz.korio.util.*
open class AtlasResourceProcessor : ResourceProcessor("atlas") {
companion object : AtlasResourceProcessor()
override val version: Int = 0
override val outputExtension: String = "atlas.json"
override suspend fun processInternal(inputFile: VfsFile, outputFile: VfsFile) {
val mapper = ObjectMapper().jvmFallback()
// @TODO: Ignored file content. Use atlas to store information like max width/height, scale, etc.
//val atlasPath0 = inputFile.readString().trim()
//val atlasPath0 = ""
//val atlasPath = if (atlasPath0.isNotEmpty()) atlasPath0 else inputFile.baseName
val atlasPath = inputFile.baseNameWithoutExtension
val atlasFolder = inputFile.parent[atlasPath].jail()
//println("inputFile=$inputFile")
//println("outputFile=$outputFile")
//println("atlasPath=$atlasPath, atlasFolder=$atlasFolder")
val files = atlasFolder.listRecursiveSimple { it.extensionLC == "png" || it.extensionLC == "jpg" }
//println("atlasFiles=$files")
if (files.isNotEmpty()) {
val bitmaps = files.map { it.readBitmap().slice(name = it.baseName) }
val outputImageFile = outputFile.withCompoundExtension("atlas.png")
//println("outputImageFile=$outputImageFile")
val atlases = AtlasPacker.pack(bitmaps, fileName = outputImageFile.baseName)
val atlas = atlases.atlases.first()
outputImageFile.write(
PNG.encode(atlas.tex, ImageEncodingProps(filename = "file.png", quality = 1.0))
)
//println(Json.stringify(atlasInfo, pretty = true))
outputFile.withCompoundExtension("atlas.json")
.writeString(Json.stringifyTyped(atlas.atlasInfo, pretty = true, mapper = mapper))
//Atlas.Factory()
//println(files)
}
}
}
| apache-2.0 | 6518dd7e5a1f795fdcc2e37bca622270 | 37.316667 | 100 | 0.707699 | 4.061837 | false | false | false | false |
calvin-li/Quest | app/src/main/java/com/sandbox/calvin_li/quest/QuestOptionsDialogFragment.kt | 1 | 6388 | package com.sandbox.calvin_li.quest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import androidx.fragment.app.DialogFragment
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.*
import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
class QuestOptionsDialogFragment : DialogFragment() {
companion object {
fun setAddButton(
adapter: CustomListAdapter, clickable: View, index: List<Int>, scroll: () -> Unit) {
clickable.setOnClickListener {
val editView = getDialogView(adapter.context)
val dialog = createDialog(adapter.context, editView, "Add subquest") { _, _ ->
val newQuest = editView.text.toString()
addSubQuest(index, newQuest, adapter.context)
adapter.notifyDataSetChanged(false)
scroll()
}
editView.setOnEditorActionListener { _, _, _ ->
dialog.getButton(DialogInterface.BUTTON_POSITIVE).callOnClick()
}
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED)
dialog.show()
editView.requestFocus()
}
}
fun setEditButton(adapter: CustomListAdapter, clickable: View, currentQuest:
CharSequence, index: List<Int>) {
clickable.setOnClickListener {
val editView = getDialogView(adapter.context)
editView.append(currentQuest)
editView.hint = currentQuest
val dialog = createDialog(adapter.context, editView, "Edit quest") { _, _ ->
editQuest(index, editView.text.toString(), adapter.context)
adapter.notifyDataSetChanged(false)
}
editView.setOnEditorActionListener { _, _, _ ->
dialog.getButton(DialogInterface.BUTTON_POSITIVE).callOnClick()
}
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MODE_CHANGED)
dialog.show()
editView.requestFocus()
}
}
fun setDeleteButton(adapter: CustomListAdapter, clickable: View, index:
List<Int>) {
clickable.setOnClickListener {
deleteQuest(index, adapter.context)
adapter.notifyDataSetChanged(false)
}
}
fun addSubQuest(index: List<Int>, text: String, context: Context) {
MainActivity.loadQuestJson(context)
val currentObject = MainActivity.getNestedArray(index)
currentObject[Quest.expandLabel] = true
val newObject = JsonObject()
newObject[Quest.nameLabel] = text
newObject[Quest.expandLabel] = true
newObject[Quest.checkedLabel] = false
@Suppress("UNCHECKED_CAST")
val childObject: JsonArray<JsonObject>? =
currentObject[Quest.childLabel] as JsonArray<JsonObject>?
if (childObject == null) {
currentObject[Quest.childLabel] = JsonArray(newObject)
} else {
childObject.add(newObject)
}
MainActivity.saveJson(context)
NotificationActionReceiver.refreshNotifications(context)
}
fun editQuest(index: List<Int>, text: String, context: Context) {
MainActivity.loadQuestJson(context)
val nestedObject: JsonObject = MainActivity.getNestedArray(index)
nestedObject[Quest.nameLabel] = text
MainActivity.saveJson(context)
NotificationActionReceiver.refreshNotifications(context)
}
fun deleteQuest(indices: List<Int>, context: Context) {
val leafIndex = indices.last()
MainActivity.loadQuestJson(context)
var toDelete: JsonArray<JsonObject> = MainActivity.questJson
@Suppress("UNCHECKED_CAST")
if (indices.size > 1) {
toDelete =
MainActivity.getNestedArray(indices.dropLast(1))[Quest.childLabel]
as JsonArray<JsonObject>
}
toDelete.removeAt(leafIndex)
MainActivity.saveJson(context)
if(indices.size == 1){
NotificationActionReceiver.removeAndShiftNotification(context, indices.first())
} else{
val notificationIndices = NotificationActionReceiver.getIndexList(context)
notificationIndices[indices.first()] =
notificationIndices[indices.first()].take(indices.size-1)
NotificationActionReceiver.saveIndexList(context, notificationIndices)
}
NotificationActionReceiver.refreshNotifications(context)
}
internal fun createDialog(context: Context, editView: EditText, title: String,
positiveAction: (DialogInterface, Int) -> Unit): AlertDialog {
if(MainActivity.inNightMode(context)) {
editView.setTextColor(context.resources.getColor(R.color.light_text, null))
editView.setHintTextColor(context.resources.getColor(R.color.light_hint_text, null))
}
return AlertDialog.Builder(context, R.style.QuestDialogStyle)
.setTitle(title)
.setView(editView)
.setPositiveButton("Confirm", positiveAction)
.setNegativeButton("Cancel") { _, _ -> }
.create()
}
@SuppressLint("InflateParams")
internal fun getDialogView(context: Context): EditText {
val layoutInflater: LayoutInflater = context.getSystemService(Context
.LAYOUT_INFLATER_SERVICE) as LayoutInflater
return layoutInflater.inflate(R.layout.element_dialog, null) as EditText
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
builder.setMessage("")
return builder.create()
}
} | mit | 271ec6dc23f1074b9573c78913701bd4 | 40.487013 | 100 | 0.609424 | 5.33222 | false | false | false | false |
google-developer-training/android-basics-kotlin-affirmations-app-solution | app/src/main/java/com/example/affirmations/adapter/ItemAdapter.kt | 1 | 2574 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.affirmations.adapter
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.recyclerview.widget.RecyclerView
import com.example.affirmations.R
import com.example.affirmations.model.Affirmation
/**
* Adapter for the [RecyclerView] in [MainActivity]. Displays [Affirmation] data object.
*/
class ItemAdapter(
private val context: Context,
private val dataset: List<Affirmation>
): RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder.
// Each data item is just an Affirmation object.
class ItemViewHolder(private val view: View): RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.item_title)
val imageView: ImageView = view.findViewById(R.id.item_image)
}
/**
* Create new views (invoked by the layout manager)
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
// create a new view
val adapterLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
return ItemViewHolder(adapterLayout)
}
/**
* Replace the contents of a view (invoked by the layout manager)
*/
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = dataset[position]
holder.textView.text = context.resources.getString(item.stringResourceId)
holder.imageView.setImageResource(item.imageResourceId)
}
/**
* Return the size of your dataset (invoked by the layout manager)
*/
override fun getItemCount() = dataset.size
}
| apache-2.0 | e356e8f81ab3b228cedc6e15b8a6061b | 35.771429 | 88 | 0.721445 | 4.415094 | false | false | false | false |
mvarnagiris/expensius | app/src/main/kotlin/com/mvcoding/expensius/feature/BaseActivity.kt | 1 | 2598 | /*
* Copyright (C) 2017 Mantas Varnagiris.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package com.mvcoding.expensius.feature
import android.graphics.PorterDuff
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.mvcoding.expensius.extension.forEach
import com.mvcoding.expensius.extension.getColorFromTheme
import kotlinx.android.synthetic.main.toolbar.*
import memoizrlabs.com.shankandroid.ShankAppCompatActivity
import java.io.Closeable
abstract class BaseActivity : ShankAppCompatActivity() {
override val finalAction: (Any) -> Unit = {
when (it) {
is Closeable -> it.close()
}
}
override fun setContentView(layoutResID: Int) {
super.setContentView(layoutResID)
setupToolbar()
}
override fun setContentView(view: View?) {
super.setContentView(view)
setupToolbar()
}
override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) {
super.setContentView(view, params)
setupToolbar()
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
tintToolbarIcons(menu)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
protected fun setupToolbar() {
toolbar?.run {
setSupportActionBar(this)
supportActionBar?.run {
setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(true)
}
}
}
private fun tintToolbarIcons(menu: Menu) {
toolbar?.apply {
val tintColor = getColorFromTheme(context, android.R.attr.textColorPrimary)
menu.forEach {
val icon = it.icon
if (icon != null) {
icon.mutate()
icon.setColorFilter(tintColor, PorterDuff.Mode.SRC_ATOP)
}
}
}
}
} | gpl-3.0 | 66de37ffff4d3df24236d5f3ac3d71d4 | 29.22093 | 87 | 0.65358 | 4.837989 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/plugins/AutoLogin.kt | 1 | 1109 | package com.gh0u1l5.wechatmagician.backend.plugins
import android.app.Activity
import android.widget.Button
import com.gh0u1l5.wechatmagician.Global.SETTINGS_AUTO_LOGIN
import com.gh0u1l5.wechatmagician.backend.WechatHook
import com.gh0u1l5.wechatmagician.spellbook.interfaces.IActivityHook
import com.gh0u1l5.wechatmagician.spellbook.mirror.com.tencent.mm.plugin.webwx.ui.Classes.ExtDeviceWXLoginUI
import de.robv.android.xposed.XposedBridge.log
import de.robv.android.xposed.XposedHelpers.findFirstFieldByExactType
object AutoLogin : IActivityHook {
private val pref = WechatHook.settings
private fun isPluginEnabled() = pref.getBoolean(SETTINGS_AUTO_LOGIN, false)
override fun onActivityStarting(activity: Activity) {
if (!isPluginEnabled()) {
return
}
if (activity::class.java == ExtDeviceWXLoginUI) {
val field = findFirstFieldByExactType(ExtDeviceWXLoginUI, Button::class.java)
val button = field.get(activity) as Button?
log("field = $field, button = $button")
button?.performClick()
}
}
} | gpl-3.0 | 8a7dc1d3679a6ac131eef465bc87b6a8 | 37.275862 | 108 | 0.741208 | 3.797945 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/mosaic/src/main/kotlin/com/teamwizardry/librarianlib/mosaic/WrappedSprite.kt | 1 | 2129 | package com.teamwizardry.librarianlib.mosaic
import com.teamwizardry.librarianlib.core.rendering.DefaultRenderPhases
import com.teamwizardry.librarianlib.math.Matrix4d
import net.minecraft.client.render.RenderPhase
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.VertexFormats
import net.minecraft.util.Identifier
import org.lwjgl.opengl.GL11
import java.awt.Color
public abstract class WrappedSprite: Sprite {
public abstract val wrapped: Sprite?
override fun minU(animFrames: Int): Float = wrapped?.minU(animFrames) ?: 0f
override fun minV(animFrames: Int): Float = wrapped?.minV(animFrames) ?: 0f
override fun maxU(animFrames: Int): Float = wrapped?.maxU(animFrames) ?: 1f
override fun maxV(animFrames: Int): Float = wrapped?.maxV(animFrames) ?: 1f
override val texture: Identifier get() = wrapped?.texture ?: Identifier("missingno")
override val width: Int get() = wrapped?.width ?: 1
override val height: Int get() = wrapped?.height ?: 1
override val uSize: Float get() = wrapped?.uSize ?: 1f
override val vSize: Float get() = wrapped?.vSize ?: 1f
override val frameCount: Int get() = wrapped?.frameCount ?: 1
override val minUCap: Float get() = wrapped?.minUCap ?: 0f
override val minVCap: Float get() = wrapped?.minVCap ?: 0f
override val maxUCap: Float get() = wrapped?.maxUCap ?: 0f
override val maxVCap: Float get() = wrapped?.maxVCap ?: 0f
override val pinTop: Boolean get() = wrapped?.pinTop ?: true
override val pinBottom: Boolean get() = wrapped?.pinBottom ?: true
override val pinLeft: Boolean get() = wrapped?.pinLeft ?: true
override val pinRight: Boolean get() = wrapped?.pinRight ?: true
override val rotation: Int get() = wrapped?.rotation ?: 0
override fun draw(matrix: Matrix4d, x: Float, y: Float, animTicks: Int, tint: Color) {
wrapped?.draw(matrix, x, y, animTicks, tint)
}
override fun draw(matrix: Matrix4d, x: Float, y: Float, width: Float, height: Float, animTicks: Int, tint: Color) {
wrapped?.draw(matrix, x, y, width, height, animTicks, tint)
}
} | lgpl-3.0 | 3fce0aa9f84cdc2f14b086ca91a2f7ee | 49.714286 | 119 | 0.711602 | 3.92081 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | advanced/exercise-solutions/card-game/part-10/user-collections/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/usercollections/DtoConverter.kt | 7 | 852 | package org.tsdes.advanced.exercises.cardgame.usercollections
import org.tsdes.advanced.exercises.cardgame.usercollections.db.CardCopy
import org.tsdes.advanced.exercises.cardgame.usercollections.db.User
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.CardCopyDto
import org.tsdes.advanced.exercises.cardgame.usercollections.dto.UserDto
object DtoConverter {
fun transform(user: User) : UserDto{
return UserDto().apply {
userId = user.userId
coins = user.coins
cardPacks = user.cardPacks
ownedCards = user.ownedCards.map { transform(it) }.toMutableList()
}
}
fun transform(cardCopy: CardCopy) : CardCopyDto{
return CardCopyDto().apply {
cardId = cardCopy.cardId
numberOfCopies = cardCopy.numberOfCopies
}
}
} | lgpl-3.0 | bc52829109391751f7d36866c69457b4 | 29.464286 | 78 | 0.697183 | 4.30303 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems | old/old_news-rest-v2/src/test/kotlin/org/tsdes/advanced/rest/newsrestv2/api/OldNewsRestApiTest.kt | 1 | 10006 | package org.tsdes.advanced.rest.newsrestv2.api
import io.restassured.RestAssured.*
import io.restassured.http.ContentType
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.junit.jupiter.api.Test
import org.tsdes.advanced.rest.newsrestv2.dto.NewsDto
import java.time.ZonedDateTime
/*
NOTE: in "theory", this should just be COPY&PASTE of the tests
of the previous module with version 1.0
As we want to maintain backward compatibility, all of these tests
should still pass without the need to do ANY modification.
Unfortunately, it looks like there is a limitation (ie bug) of RestAssured,
which does automated-redirects only for GET :(
So, what to do when an open-source project that you use does
have a bug? Well, you fill a bug report...
https://github.com/rest-assured/rest-assured/issues/750
It is possible to force RestAssured to always do a redirect, but, then,
the underlying library Apache HTTPClient has the great idea of
transforming DELETE into GET when 301... and it ignores 308...
*/
class OldNewsRestApiTest : NRTestBase() {
@Test
fun testCleanDB() {
given().get().then()
.statusCode(200)
.body("size()", equalTo(0))
}
@Test
fun testCreateAndGet() {
val author = "author"
val text = "someText"
val country = "Norway"
val dto = NewsDto(null, author, text, country, null)
given().get().then().statusCode(200).body("size()", equalTo(0))
val id = given().contentType(ContentType.JSON)
.body(dto)
.post()
.then()
.statusCode(201)
.extract().asString()
given().get().then().statusCode(200).body("size()", equalTo(1))
given().pathParam("id", id)
.get("/id/{id}")
.then()
.statusCode(200)
.body("id", equalTo(id))
.body("authorId", equalTo(author))
.body("text", equalTo(text))
.body("country", equalTo(country))
}
@Test
fun testDelete() {
val id = given().contentType(ContentType.JSON)
.body(NewsDto(null, "author", "text", "Norway", null))
.post()
.then()
.statusCode(201)
.extract().asString()
get().then()
.body("size()", equalTo(1))
.body("id[0]", containsString(id))
delete("/id/$id").then().statusCode(308) //instead of 204
// get().then().body("id", not(containsString(id)))
}
@Test
fun testUpdate() {
val text = "someText"
//first create with a POST
val id = given().contentType(ContentType.JSON)
.body(NewsDto(null, "author", text, "Norway", null))
.post()
.then()
.statusCode(201)
.extract().asString()
//check if POST was fine
get("/id/$id").then().body("text", equalTo(text))
val updatedText = "new updated text"
//now change text with PUT
given().contentType(ContentType.JSON)
.pathParam("id", id)
.body(NewsDto(id, "foo", updatedText, "Norway", ZonedDateTime.now()))
.put("/id/{id}")
.then()
.statusCode(308) // instead of 204
// //was the PUT fine?
// get("/id/" + id).then().body("text", equalTo(updatedText))
//
//
// //now rechange, but just the text
// val anotherText = "yet another text"
//
// given().contentType(ContentType.TEXT)
// .body(anotherText)
// .pathParam("id", id)
// .put("/id/{id}/text")
// .then()
// .statusCode(204)
//
// get("/id/" + id).then().body("text", equalTo(anotherText))
}
@Test
fun testMissingForUpdate() {
given().contentType(ContentType.JSON)
.body("{\"id\":\"-333\"}")
.pathParam("id", "-333")
.put("/id/{id}")
.then()
.statusCode(308) // instead of 404
}
@Test
fun testUpdateNonMatchingId() {
given().contentType(ContentType.JSON)
.body(NewsDto("222", "foo", "some text", "Norway", ZonedDateTime.now()))
.pathParam("id", "-333")
.put("/id/{id}")
.then()
.statusCode(308) //instead of 409
}
@Test
fun testInvalidUpdate() {
val id = given().contentType(ContentType.JSON)
.body(NewsDto(null, "author", "someText", "Norway", null))
.post()
.then()
.extract().asString()
val updatedText = ""
given().contentType(ContentType.JSON)
.pathParam("id", id)
.body(NewsDto(id, null, updatedText, null, null))
.put("/id/{id}")
.then()
.statusCode(308) // instead of 400
}
private fun createSomeNews() {
createNews("a", "text", "Norway")
createNews("a", "other text", "Norway")
createNews("a", "more text", "Sweden")
createNews("b", "text", "Norway")
createNews("b", "yet another text", "Iceland")
createNews("c", "text", "Iceland")
}
private fun createNews(authorId: String, text: String, country: String) {
given().contentType(ContentType.JSON)
.body(NewsDto(null, authorId, text, country, null))
.post()
.then()
.statusCode(201)
}
@Test
fun testGetAll() {
get().then().body("size()", equalTo(0))
createSomeNews()
get().then().body("size()", equalTo(6))
}
@Test
fun testGetAllByCountry() {
get().then().body("size()", equalTo(0))
createSomeNews()
get("/countries/Norway").then().body("size()", equalTo(3))
get("/countries/Sweden").then().body("size()", equalTo(1))
get("/countries/Iceland").then().body("size()", equalTo(2))
}
@Test
fun testGetAllByAuthor() {
get().then().body("size()", equalTo(0))
createSomeNews()
get("/authors/a").then().body("size()", equalTo(3))
get("/authors/b").then().body("size()", equalTo(2))
get("/authors/c").then().body("size()", equalTo(1))
}
@Test
fun testGetAllByCountryAndAuthor() {
get().then().body("size()", equalTo(0))
createSomeNews()
get("/countries/Norway/authors/a").then().body("size()", equalTo(2))
get("/countries/Sweden/authors/a").then().body("size()", equalTo(1))
get("/countries/Iceland/authors/a").then().body("size()", equalTo(0))
get("/countries/Norway/authors/b").then().body("size()", equalTo(1))
get("/countries/Sweden/authors/b").then().body("size()", equalTo(0))
get("/countries/Iceland/authors/b").then().body("size()", equalTo(1))
get("/countries/Norway/authors/c").then().body("size()", equalTo(0))
get("/countries/Sweden/authors/c").then().body("size()", equalTo(0))
get("/countries/Iceland/authors/c").then().body("size()", equalTo(1))
}
@Test
fun testInvalidGetByCountry() {
/*
Although the fields are marked with constraint @Country,
by default Spring does not validate them.
We will see later of to handle constraint validations
*/
get("/countries/foo").then()
.statusCode(200)
.body("size()", equalTo(0))
}
@Test
fun testInvalidGetByCountryAndAuthor() {
get("/countries/foo/authors/foo").then()
.statusCode(200)
.body("size()", equalTo(0))
}
@Test
fun testInvalidAuthor() {
given().contentType(ContentType.JSON)
.body(NewsDto(null, "", "text", "Norway", null))
.post()
.then()
.statusCode(400)
}
@Test
fun testInvalidCountry() {
given().contentType(ContentType.JSON)
.body(NewsDto(null, "author", "text", "foo", null))
.post()
.then()
.statusCode(400)
}
@Test
fun testPostWithId() {
given().contentType(ContentType.JSON)
.body(NewsDto("1", "author", "text", "Norway", null))
.post()
.then()
.statusCode(400)
}
@Test
fun testPostWithWrongType() {
/*
HTTP Error 415: "Unsupported media type"
The REST API is set to return data in JSON, ie
@Produces(MediaType.APPLICATION_JSON)
so, if ask for XML, we should get a 415 error.
Note: a server might provide the same resource (on same URL)
with different formats!
Although nowadays most just deal with JSON.
*/
given().contentType(ContentType.XML)
.body("<foo></foo>")
.post()
.then()
.statusCode(415)
}
@Test
fun testGetByInvalidId() {
/*
In this particular case, "foo" might be a valid id.
however, as it is not in the database, and there is no mapping
for a String id, the server will say "Not Found", ie 404.
*/
get("/id/foo")
.then()
.statusCode(404)
}
/*
Test if Swagger is properly configured
*/
@Test
fun testSwaggerSchema() {
get("../v2/api-docs")
.then()
.statusCode(200)
.body("swagger", equalTo("2.0"))
}
@Test
fun testSwaggerUI() {
get("../swagger-ui.html").then().statusCode(200)
}
} | lgpl-3.0 | 38206d3e3bb9bd6c3fbc49a0f45cf1ea | 27.838617 | 88 | 0.519788 | 4.290738 | false | true | false | false |
androidx/androidx | navigation/navigation-compose-lint/src/main/java/androidx/navigation/compose/lint/ComposableDestinationInComposeScopeDetector.kt | 3 | 3984 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnstableApiUsage")
package androidx.navigation.compose.lint
import androidx.compose.lint.Name
import androidx.compose.lint.Package
import androidx.compose.lint.isInPackageName
import androidx.compose.lint.isInvokedWithinComposable
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
import java.util.EnumSet
/**
* [Detector] that checks `composable` calls to make sure that they are not called inside a
* Composable body.
*/
class ComposableDestinationInComposeScopeDetector : Detector(), SourceCodeScanner {
override fun getApplicableMethodNames(): List<String> = listOf(
Composable.shortName,
Navigation.shortName
)
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
if (!method.isInPackageName(PackageName)) return
if (node.isInvokedWithinComposable()) {
if (method.name == Composable.shortName) {
context.report(
ComposableDestinationInComposeScope,
node,
context.getNameLocation(node),
"Using composable inside of a compose scope"
)
} else {
context.report(
ComposableNavGraphInComposeScope,
node,
context.getNameLocation(node),
"Using navigation inside of a compose scope"
)
}
}
}
companion object {
val ComposableDestinationInComposeScope = Issue.create(
"ComposableDestinationInComposeScope",
"Building composable destination in compose scope",
"Composable destinations should only be constructed directly within a " +
"NavGraphBuilder scope. Composable destinations cannot not be nested, and you " +
"should use the `navigation` function to create a nested graph instead.",
Category.CORRECTNESS, 3, Severity.ERROR,
Implementation(
ComposableDestinationInComposeScopeDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
)
)
val ComposableNavGraphInComposeScope = Issue.create(
"ComposableNavGraphInComposeScope",
"Building navigation graph in compose scope",
"Composable destinations should only be constructed directly within a " +
"NavGraphBuilder scope.",
Category.CORRECTNESS, 3, Severity.ERROR,
Implementation(
ComposableDestinationInComposeScopeDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES)
)
)
}
}
private val PackageName = Package("androidx.navigation.compose")
private val Composable = Name(PackageName, "composable")
private val Navigation = Name(PackageName, "navigation")
| apache-2.0 | 053f731c6d520f9d94da254b7ae7e3a7 | 39.653061 | 98 | 0.680974 | 4.906404 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/WGL_ARB_robustness_isolation.kt | 1 | 2711 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val WGL_ARB_robustness_application_isolation = "WGLARBRobustnessApplicationIsolation".nativeClassWGL("WGL_ARB_robustness_application_isolation", ARB) {
documentation =
"""
Native bindings to the ${registryLink("ARB", "wgl_robustness_isolation")} extension.
GL_ARB_robustness and WGL_ARB_create_context_robustness allow creating an OpenGL context supporting graphics reset notification behavior.
WGL_ARB_robustness_application_isolation provides stronger guarantees about the possible side-effects of a graphics reset.
If the graphics driver advertises the WGL_ARB_robustness_application_isolation extension string, then the driver guarantees that if a particular
application causes a graphics reset to occur:
${ol(
"No other application on the system is affected by the graphics reset.",
"No other application on the system receives any notification that the graphics reset occurred."
)}
Requires ${WGL_ARB_extensions_string.link} and ${WGL_ARB_create_context_robustness.link}.
"""
IntConstant(
"""
Accepted as a bit in the attribute value for WGLARBCreateContext#CONTEXT_FLAGS_ARB in the {@code attribList} argument to
WGLARBCreateContext#CreateContextAttribsARB().
""",
"CONTEXT_RESET_ISOLATION_BIT_ARB"..0x00000008
)
}
val WGL_ARB_robustness_share_group_isolation = EXT_FLAG.nativeClassWGL("WGL_ARB_robustness_share_group_isolation", postfix = ARB) {
documentation =
"""
Native bindings to the ${registryLink("ARB", "wgl_robustness_isolation")} extension.
GL_ARB_robustness and WGL_ARB_create_context_robustness allow creating an OpenGL context supporting graphics reset notification behavior.
WGL_ARB_robustness_share_group_isolation provides stronger guarantees about the possible side-effects of a graphics reset.
If the graphics driver advertises the WGL_ARB_robustness_share_group_isolation extension string, then the driver guarantees that if a context in a
particular share group causes a graphics reset to occur:
${ol(
"""
No other share group within the application is affected by the graphics reset. Additionally, no other application on the system is affected by the
graphics reset.
""",
"""
No other share group within the application receives any notification that the graphics reset occurred. Additionally, no other application on the
system receives any notification that the graphics reset occurred.
"""
)}
Requires ${WGL_ARB_extensions_string.link} and ${WGL_ARB_create_context_robustness.link}.
"""
} | bsd-3-clause | 99d82ac855aee158562633e3db24480f | 43.459016 | 151 | 0.769458 | 4.222741 | false | false | false | false |
Grisu118/lss-userscript | src/main/kotlin/ch/grisu118/userscript/leitstellenspiel/MissionWindowHandler.kt | 1 | 3502 | package ch.grisu118.userscript.leitstellenspiel
import JQuery
import ch.grisu118.js.logger.LoggerFactory
import jQuery
import kotlinx.html.classes
import kotlinx.html.dom.create
import kotlinx.html.js.a
import kotlinx.html.js.div
import kotlinx.html.js.style
import kotlinx.html.span
import kotlinx.html.style
import kotlin.browser.document
import kotlin.browser.localStorage
class MissionWindowHandler : Component {
private val logger = LoggerFactory.logger(this)
private var filterVehicles = false
init {
val storageItem = localStorage.getItem("g118FilterVehicles")
if (storageItem != null) {
filterVehicles = storageItem == "true"
}
}
override fun initUI(parent: JQuery) {
if (user_id == LSSData.grisu118) {
logger.info { "Activating Special Features for Grisu118!" }
initRelaABDHandler(parent)
}
initVehicleFilter()
initAAOClickHandler(parent)
}
private fun initVehicleFilter() {
jQuery("#h2_free_vehicles").append(document.create.a {
classes += "g118FilterVehicleList"
style = "color: ${if (filterVehicles) "red" else "black"};"
href = "#"
span {
classes = setOf("glyphicon", "glyphicon-filter")
}
})
jQuery(".g118FilterVehicleList").click { event ->
val elem = jQuery(event.currentTarget)
if (filterVehicles) {
filterVehicles = false
elem.css("color", "black")
} else {
filterVehicles = true
elem.css("color", "red")
}
localStorage.setItem("g118FilterVehicles", filterVehicles.toString())
filterVehiclesList()
return@click true
}
jQuery("#tabs").each { _, e ->
jQuery(e).click { _ -> filterVehiclesList() }
}
filterVehiclesList()
}
private fun filterVehiclesList() {
jQuery(".tab-pane.active table tbody").find("tr").each { _, elem ->
val element = jQuery(elem)
if (filterVehicles) {
if (element.find(".vehicle_checkbox").prop("checked") as Boolean) {
element.show(0)
} else {
element.hide(0)
}
} else {
element.show(0)
}
}
}
private fun initAAOClickHandler(parent: JQuery) {
parent.append(document.create.style {
+".g118-aao-badge { border-radius: 8px; position: relative; top: -20px;z-index: 1000;background: red;color: white;width: 16px;height: 16px;left: -8px; } .aao { height: 22px }"
})
jQuery(".btn.aao").click { eventObject ->
val badge = jQuery(eventObject.currentTarget).find(".g118-aao-badge")
val length = badge.length as Int
if (length > 0) {
val currentValue = badge.html().toInt()
badge.html((currentValue + 1).toString())
} else {
jQuery(eventObject.currentTarget).append(document.create.div {
classes += "g118-aao-badge"
+"1"
})
}
filterVehiclesList()
return@click true
}
}
private fun initRelaABDHandler(parent: JQuery) {
val abdId = 7647412
val tlfId = 25079
jQuery("input[value='$abdId']").change { eventObject ->
val target = jQuery(eventObject.target)
val selector = jQuery("input[value='$tlfId']")
if (target.prop("checked") as Boolean) {
logger.trace { "Add Dekon TLF to selection" }
selector.prop("checked", true)
} else {
logger.trace { "Remove Dekon TLF from selection" }
selector.prop("checked", false)
}
}
}
override fun update() {
// Do nothing
}
} | mit | 5ad93cdf07d5c90be18d6f4714380c9e | 27.713115 | 181 | 0.628784 | 3.798265 | false | false | false | false |
wealthfront/magellan | magellan-sample-advanced/src/main/java/com/wealthfront/magellan/sample/advanced/ordertickets/OrderTicketsBasketStep.kt | 1 | 3036 | package com.wealthfront.magellan.sample.advanced.ordertickets
import android.content.Context
import android.widget.EditText
import androidx.core.widget.doAfterTextChanged
import com.wealthfront.magellan.core.Step
import com.wealthfront.magellan.sample.advanced.R
import com.wealthfront.magellan.sample.advanced.SampleApplication.Companion.app
import com.wealthfront.magellan.sample.advanced.ToolbarHelper
import com.wealthfront.magellan.sample.advanced.databinding.OrderTicketsBasketBinding
import java.math.BigDecimal
import javax.inject.Inject
val adultTicketCost: BigDecimal = BigDecimal("8.50")
val childTicketCost: BigDecimal = BigDecimal("5.00")
interface BasketStepListener {
fun onBasketFilled(adultTicketCount: Int, childTicketCount: Int)
}
class OrderTicketsBasketStep(
private val basketStepListener: BasketStepListener,
private val ticketOrder: TicketOrder
) : Step<OrderTicketsBasketBinding>(OrderTicketsBasketBinding::inflate) {
@Inject lateinit var toolbarHelper: ToolbarHelper
override fun onCreate(context: Context) {
app(context).injector().inject(this)
}
override fun onShow(context: Context, binding: OrderTicketsBasketBinding) {
toolbarHelper.hideToolbar()
binding.adultTicketPriceLabel.text =
context.getString(R.string.order_tickets_price_label, adultTicketCost.toPlainString())
binding.childTicketPriceLabel.text =
context.getString(R.string.order_tickets_price_label, childTicketCost.toPlainString())
binding.adultTicketCount.setText(ticketOrder.adultTickets.toString())
binding.adultTicketCount.doAfterTextChanged { updateTotalCost(context, binding) }
binding.childTicketCount.setText(ticketOrder.childTickets.toString())
binding.childTicketCount.doAfterTextChanged { updateTotalCost(context, binding) }
updateTotalCost(context, binding)
binding.next.setOnClickListener {
basketStepListener.onBasketFilled(
getTicketCount(binding.adultTicketCount),
getTicketCount(binding.childTicketCount)
)
}
}
private fun getTicketCount(entryView: EditText): Int {
val ticketCountText = entryView.text.toString()
return if (ticketCountText.isNotBlank()) {
ticketCountText.toInt()
} else {
0
}
}
private fun updateTotalCost(context: Context, binding: OrderTicketsBasketBinding) {
val adultTicketCount = getTicketCount(binding.adultTicketCount)
val childTicketCount = getTicketCount(binding.childTicketCount)
val totalCost = getTotalCost(adultTicketCount, childTicketCount)
binding.totalTicketCount.text =
context.getString(R.string.order_tickets_total_price, totalCost.toPlainString())
binding.next.isEnabled = totalCost > BigDecimal.ZERO
}
private fun getTotalCost(adultTicketCount: Int, childTicketCount: Int): BigDecimal {
val totalAdultTicketCost = (adultTicketCost * BigDecimal(adultTicketCount))
val totalChildTicketCost = (childTicketCost * BigDecimal(childTicketCount))
return totalAdultTicketCost + totalChildTicketCost
}
}
| apache-2.0 | c24bfa693eb156b6b732177981d92839 | 37.923077 | 92 | 0.790184 | 4.246154 | false | false | false | false |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/util/Views.kt | 1 | 3813 | package com.tomclaw.drawa.util
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewPropertyAnimator
import android.view.animation.AccelerateDecelerateInterpolator
fun View?.toggle() {
if (this?.visibility == VISIBLE) hide() else show()
}
fun View?.isVisible(): Boolean = this?.visibility == VISIBLE
fun View?.show() {
this?.visibility = VISIBLE
}
fun View?.hide() {
this?.visibility = GONE
}
fun View.showWithAlphaAnimation(
duration: Long = ANIMATION_DURATION,
animateFully: Boolean = true,
endCallback: (() -> Unit)? = null
): ViewPropertyAnimator {
if (animateFully) {
alpha = 0.0f
}
show()
return animate()
.setDuration(duration)
.alpha(1.0f)
.setInterpolator(AccelerateDecelerateInterpolator())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
alpha = 1.0f
show()
endCallback?.invoke()
}
})
}
fun View.hideWithAlphaAnimation(
duration: Long = ANIMATION_DURATION,
animateFully: Boolean = true,
endCallback: (() -> Unit)? = null
): ViewPropertyAnimator {
if (animateFully) {
alpha = 1.0f
}
return animate()
.setDuration(duration)
.alpha(0.0f)
.setInterpolator(AccelerateDecelerateInterpolator())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
hide()
alpha = 1.0f
endCallback?.invoke()
}
})
}
fun View.showWithTranslationAnimation(
height: Float
): ViewPropertyAnimator {
translationY = height
alpha = 0.0f
show()
return animate()
.setDuration(ANIMATION_DURATION)
.alpha(1.0f)
.translationY(0f)
.setInterpolator(AccelerateDecelerateInterpolator())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
translationY = 0f
alpha = 1.0f
show()
}
})
}
fun View.moveWithTranslationAnimation(
fromTranslationY: Float,
tillTranslationY: Float,
endCallback: () -> (Unit)
): ViewPropertyAnimator {
translationY = fromTranslationY
return animate()
.setDuration(ANIMATION_DURATION)
.translationY(tillTranslationY)
.setInterpolator(AccelerateDecelerateInterpolator())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
translationY = 0f
endCallback.invoke()
}
})
}
fun View.hideWithTranslationAnimation(
endCallback: () -> (Unit)
): ViewPropertyAnimator {
alpha = 1.0f
translationY = 0f
val endTranslationY = height.toFloat()
return animate()
.setDuration(ANIMATION_DURATION)
.alpha(0.0f)
.translationY(endTranslationY)
.setInterpolator(AccelerateDecelerateInterpolator())
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
translationY = endTranslationY
hide()
alpha = 1.0f
endCallback.invoke()
}
})
}
const val ANIMATION_DURATION: Long = 250
| apache-2.0 | 168306b9bcb053b00110bf06acdf5580 | 28.789063 | 67 | 0.578547 | 5.252066 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/stubs/LuaDocTagClassStub.kt | 2 | 4148 | /*
* Copyright (c) 2017. tangzx([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.tang.intellij.lua.stubs
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.util.io.StringRef
import com.tang.intellij.lua.comment.psi.LuaDocTagClass
import com.tang.intellij.lua.comment.psi.impl.LuaDocTagClassImpl
import com.tang.intellij.lua.psi.LuaElementType
import com.tang.intellij.lua.psi.aliasName
import com.tang.intellij.lua.stubs.index.StubKeys
import com.tang.intellij.lua.ty.TyClass
import com.tang.intellij.lua.ty.createSerializedClass
/**
* Created by tangzx on 2016/11/28.
*/
class LuaDocTagClassType : LuaStubElementType<LuaDocTagClassStub, LuaDocTagClass>("DOC_CLASS") {
override fun createPsi(luaDocClassStub: LuaDocTagClassStub): LuaDocTagClass {
return LuaDocTagClassImpl(luaDocClassStub, this)
}
override fun createStub(luaDocTagClass: LuaDocTagClass, stubElement: StubElement<*>): LuaDocTagClassStub {
val superClassNameRef = luaDocTagClass.superClassNameRef
val superClassName = superClassNameRef?.text
val aliasName: String? = luaDocTagClass.aliasName
return LuaDocTagClassStubImpl(luaDocTagClass.name, aliasName, superClassName, luaDocTagClass.isDeprecated, stubElement)
}
override fun serialize(luaDocClassStub: LuaDocTagClassStub, stubOutputStream: StubOutputStream) {
stubOutputStream.writeName(luaDocClassStub.className)
stubOutputStream.writeName(luaDocClassStub.aliasName)
stubOutputStream.writeName(luaDocClassStub.superClassName)
stubOutputStream.writeBoolean(luaDocClassStub.isDeprecated)
}
override fun deserialize(stubInputStream: StubInputStream, stubElement: StubElement<*>): LuaDocTagClassStub {
val className = stubInputStream.readName()
val aliasName = stubInputStream.readName()
val superClassName = stubInputStream.readName()
val isDeprecated = stubInputStream.readBoolean()
return LuaDocTagClassStubImpl(StringRef.toString(className)!!,
StringRef.toString(aliasName),
StringRef.toString(superClassName),
isDeprecated,
stubElement)
}
override fun indexStub(luaDocClassStub: LuaDocTagClassStub, indexSink: IndexSink) {
val classType = luaDocClassStub.classType
indexSink.occurrence(StubKeys.CLASS, classType.className)
indexSink.occurrence(StubKeys.SHORT_NAME, classType.className)
val superClassName = classType.superClassName
if (superClassName != null) {
indexSink.occurrence(StubKeys.SUPER_CLASS, superClassName)
}
}
}
interface LuaDocTagClassStub : StubElement<LuaDocTagClass> {
val className: String
val aliasName: String?
val superClassName: String?
val classType: TyClass
val isDeprecated: Boolean
}
class LuaDocTagClassStubImpl(override val className: String,
override val aliasName: String?,
override val superClassName: String?,
override val isDeprecated: Boolean,
parent: StubElement<*>)
: LuaDocStubBase<LuaDocTagClass>(parent, LuaElementType.CLASS_DEF), LuaDocTagClassStub {
override val classType: TyClass
get() {
val luaType = createSerializedClass(className, className, superClassName)
luaType.aliasName = aliasName
return luaType
}
} | apache-2.0 | 97410d3b57014b0cc4ca0b21ae1f84e4 | 39.676471 | 127 | 0.726374 | 4.59867 | false | false | false | false |
inorichi/tachiyomi-extensions | src/ru/remanga/src/eu/kanade/tachiyomi/extension/ru/remanga/RemangaActivity.kt | 1 | 1383 | package eu.kanade.tachiyomi.extension.ru.remanga
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.util.Log
import kotlin.system.exitProcess
/**
* Springboard that accepts https://remanga.org/manga/xxx intents and redirects them to
* the main tachiyomi process. The idea is to not install the intent filter unless
* you have this extension installed, but still let the main tachiyomi app control
* things.
*/
class RemangaActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val pathSegments = intent?.data?.pathSegments
if (pathSegments != null && pathSegments.size > 1) {
val titleid = pathSegments[1]
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.SEARCH"
putExtra("query", "${Remanga.PREFIX_SLUG_SEARCH}$titleid")
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: ActivityNotFoundException) {
Log.e("RemangaActivity", e.toString())
}
} else {
Log.e("RemangaActivity", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
| apache-2.0 | ac8e13d293b713efbffd484c8d7a1a0b | 33.575 | 87 | 0.643529 | 4.688136 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/cafeteria/CafeteriaNotificationSettingsAdapter.kt | 1 | 4119 | package de.tum.`in`.tumcampusapp.component.ui.cafeteria
import android.app.TimePickerDialog
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.utils.Utils
import kotlinx.android.synthetic.main.notification_schedule_listitem.view.*
import org.joda.time.LocalTime
import org.joda.time.format.DateTimeFormat
import java.util.*
class CafeteriaNotificationSettingsAdapter(
private val context: Context,
private val dailySchedule: List<CafeteriaNotificationTime>
) : RecyclerView.Adapter<CafeteriaNotificationSettingsAdapter.ViewHolder>(), OnNotificationTimeChangedListener {
private val settings = CafeteriaNotificationSettings.getInstance(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.notification_schedule_listitem, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val notificationTime = dailySchedule[position]
holder.bind(notificationTime, settings, this)
}
override fun onTimeChanged(position: Int, newTime: LocalTime) {
if (newTime.hourOfDay !in MIN_HOUR..MAX_HOUR) {
val text = context.getString(
R.string.invalid_notification_time_format_string, MIN_HOUR, MAX_HOUR)
Utils.showToast(context, text)
return
}
updateNotificationTime(position, newTime)
}
override fun onCheckChanged(position: Int, isChecked: Boolean) {
if (!isChecked) {
updateNotificationTime(position, null)
return
}
// If the user re-enables a notification on a particular day, we retrieve the last known
// time or the default time
val time = dailySchedule[position]
val newTime = settings.retrieveLocalTimeOrDefault(time.weekday)
updateNotificationTime(position, newTime)
}
private fun updateNotificationTime(position: Int, newTime: LocalTime?) {
dailySchedule[position].apply {
time = newTime
}
notifyItemChanged(position)
}
override fun getItemCount() = dailySchedule.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val dayFormatter = DateTimeFormat.forPattern("EEEE").withLocale(Locale.getDefault())
private val timeFormatter = DateTimeFormat.shortTime().withLocale(Locale.getDefault())
fun bind(
time: CafeteriaNotificationTime,
settings: CafeteriaNotificationSettings,
listener: OnNotificationTimeChangedListener
) = with(itemView) {
val dayOfWeekString = dayFormatter.print(time.weekday)
weekdayTextView.text = dayOfWeekString
notificationActiveCheckBox.setOnCheckedChangeListener(null)
notificationActiveCheckBox.isChecked = time.time != null
time.time?.let {
notificationTimeTextView.text = timeFormatter.print(it)
}
notificationTimeTextView.setOnClickListener {
val defaultTime = settings.retrieveLocalTimeOrDefault(time.weekday)
val timePicker = TimePickerDialog(context, { _, hour, minute ->
val newTime = LocalTime.now()
.withHourOfDay(hour)
.withMinuteOfHour(minute)
listener.onTimeChanged(adapterPosition, newTime)
}, defaultTime.hourOfDay, defaultTime.minuteOfHour, true)
timePicker.show()
}
notificationActiveCheckBox.setOnCheckedChangeListener { _, isChecked ->
listener.onCheckChanged(adapterPosition, isChecked)
}
}
}
companion object {
private const val MIN_HOUR = 6
private const val MAX_HOUR = 14
}
}
| gpl-3.0 | 8bb935ee9fac87877ef3025c7d7789ba | 37.495327 | 112 | 0.674193 | 5.253827 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/user_courses/structure/DbStructureUserCourse.kt | 2 | 896 | package org.stepik.android.cache.user_courses.structure
object DbStructureUserCourse {
const val TABLE_NAME = "user_courses"
object Columns {
const val ID = "id"
const val USER = "user"
const val COURSE = "course"
const val IS_FAVORITE = "is_favorite"
const val IS_PINNED = "is_pinned"
const val IS_ARCHIVED = "is_archived"
const val LAST_VIEWED = "last_viewed"
}
const val TABLE_SCHEMA =
"CREATE TABLE IF NOT EXISTS $TABLE_NAME (" +
"${Columns.ID} LONG," +
"${Columns.USER} LONG," +
"${Columns.COURSE} LONG," +
"${Columns.IS_FAVORITE} INTEGER," +
"${Columns.IS_PINNED} INTEGER," +
"${Columns.IS_ARCHIVED} INTEGER," +
"${Columns.LAST_VIEWED} LONG," +
"PRIMARY KEY (${Columns.USER}, ${Columns.COURSE})" +
")"
} | apache-2.0 | 924ad329eff1baaf6753d3b2e17f28c3 | 32.222222 | 64 | 0.549107 | 4.017937 | false | false | false | false |
StepicOrg/stepic-android | app/src/stageDebuggable/java/org/stepik/android/view/debug/ui/fragment/DebugFragment.kt | 2 | 5363 | package org.stepik.android.view.debug.ui.fragment
import android.os.Bundle
import android.view.View
import android.widget.RadioButton
import android.widget.Toast
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.util.copyTextToClipboard
import org.stepik.android.presentation.debug.DebugFeature
import org.stepik.android.presentation.debug.DebugViewModel
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.presentation.redux.container.ReduxView
import ru.nobird.android.view.redux.ui.extension.reduxViewModel
import javax.inject.Inject
import android.content.Intent
import android.content.Context
import androidx.core.view.isVisible
import by.kirich1409.viewbindingdelegate.viewBinding
import org.stepic.droid.databinding.FragmentDebugBinding
import org.stepik.android.view.debug.ui.dialog.SplitTestsDialogFragment
import ru.nobird.android.view.base.ui.extension.showIfNotExists
class DebugFragment : Fragment(R.layout.fragment_debug), ReduxView<DebugFeature.State, DebugFeature.Action.ViewAction> {
companion object {
fun newInstance(): Fragment =
DebugFragment()
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
private val debugViewModel: DebugViewModel by reduxViewModel(this) { viewModelFactory }
private val viewStateDelegate = ViewStateDelegate<DebugFeature.State>()
private val debugBinding: FragmentDebugBinding by viewBinding(FragmentDebugBinding::bind)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
debugBinding.appBarLayoutBinding.viewCenteredToolbarBinding.centeredToolbarTitle.setText(R.string.debug_toolbar_title)
initViewStateDelegate()
debugViewModel.onNewMessage(DebugFeature.Message.InitMessage())
debugBinding.debugFcmTokenValue.setOnLongClickListener {
val textToCopy = (it as AppCompatTextView).text.toString()
requireContext().copyTextToClipboard(
textToCopy = textToCopy,
toastMessage = getString(R.string.copied_to_clipboard_toast)
)
true
}
debugBinding.debugEndpointRadioGroup.setOnCheckedChangeListener { group, checkedId ->
val checkedRadioButton = group.findViewById<RadioButton>(checkedId)
val position = group.indexOfChild(checkedRadioButton)
debugViewModel.onNewMessage(DebugFeature.Message.RadioButtonSelectionMessage(position))
}
debugBinding.debugApplySettingsAction.setOnClickListener {
debugViewModel.onNewMessage(DebugFeature.Message.ApplySettingsMessage)
}
debugBinding.debugLoadingError.tryAgain.setOnClickListener {
debugViewModel.onNewMessage(DebugFeature.Message.InitMessage(forceUpdate = true))
}
debugBinding.debugSplitTests.setOnClickListener {
SplitTestsDialogFragment
.newInstance()
.showIfNotExists(childFragmentManager, SplitTestsDialogFragment.TAG)
}
}
private fun injectComponent() {
App.component()
.debugComponentBuilder()
.build()
.inject(this)
}
private fun initViewStateDelegate() {
viewStateDelegate.addState<DebugFeature.State.Idle>()
viewStateDelegate.addState<DebugFeature.State.Loading>(debugBinding.debugProgressBar.loadProgressbarOnEmptyScreen)
viewStateDelegate.addState<DebugFeature.State.Error>(debugBinding.debugLoadingError.errorNoConnection)
viewStateDelegate.addState<DebugFeature.State.Content>(debugBinding.debugContent)
}
override fun onAction(action: DebugFeature.Action.ViewAction) {
if (action is DebugFeature.Action.ViewAction.RestartApplication) {
Toast.makeText(requireContext(), R.string.debug_restarting_message, Toast.LENGTH_SHORT).show()
view?.postDelayed({ triggerApplicationRestart(requireContext()) }, 1500)
}
}
override fun render(state: DebugFeature.State) {
viewStateDelegate.switchState(state)
if (state is DebugFeature.State.Content) {
debugBinding.debugFcmTokenValue.text = state.fcmToken
setRadioButtonSelection(state.endpointConfigSelection)
debugBinding.debugApplySettingsAction.isVisible = state.currentEndpointConfig.ordinal != state.endpointConfigSelection
}
}
private fun triggerApplicationRestart(context: Context) {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
val componentName = intent?.component
val mainIntent = Intent.makeRestartActivityTask(componentName)
context.startActivity(mainIntent)
Runtime.getRuntime().exit(0)
}
private fun setRadioButtonSelection(itemPosition: Int) {
val targetRadioButton = debugBinding.debugEndpointRadioGroup[itemPosition] as RadioButton
targetRadioButton.isChecked = true
}
} | apache-2.0 | 6ce9e9aa41c0a25c67b3bb38a559a442 | 41.571429 | 130 | 0.74697 | 5.102759 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/components/Menus.kt | 1 | 2704 | /* Copyright 2021 Braden Farmer
*
* 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.farmerbb.notepad.ui.components
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Box
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.farmerbb.notepad.R
@Composable
fun NoteListMenu(
showMenu: Boolean,
onDismiss: () -> Unit,
onMoreClick: () -> Unit,
onSettingsClick: () -> Unit,
onImportClick: () -> Unit,
onAboutClick: () -> Unit
) {
Box {
MoreButton(onMoreClick)
DropdownMenu(
expanded = showMenu,
onDismissRequest = onDismiss
) {
MenuItem(R.string.action_settings, onSettingsClick)
MenuItem(R.string.import_notes, onImportClick)
MenuItem(R.string.dialog_about_title, onAboutClick)
}
}
}
@Composable
fun NoteViewEditMenu(
showMenu: Boolean = false,
onDismiss: () -> Unit = {},
onMoreClick: () -> Unit = {},
onShareClick: () -> Unit = {},
onExportClick: () -> Unit = {},
onPrintClick: () -> Unit = {}
) {
Box {
MoreButton(onMoreClick)
DropdownMenu(
expanded = showMenu,
onDismissRequest = onDismiss
) {
MenuItem(R.string.action_share, onShareClick)
MenuItem(R.string.action_export, onExportClick)
MenuItem(R.string.action_print, onPrintClick)
}
}
}
@Composable
fun StandaloneEditorMenu(
showMenu: Boolean = false,
onDismiss: () -> Unit,
onMoreClick: () -> Unit = {},
onShareClick: () -> Unit = {}
) {
Box {
MoreButton(onMoreClick)
DropdownMenu(
expanded = showMenu,
onDismissRequest = onDismiss
) {
MenuItem(R.string.action_share, onShareClick)
}
}
}
@Composable
fun MenuItem(
@StringRes stringRes: Int,
onClick: () -> Unit
) {
DropdownMenuItem(onClick = onClick) {
Text(text = stringResource(id = stringRes))
}
} | apache-2.0 | 48d078aeca951dbd219e9d5ad450a2ff | 26.886598 | 75 | 0.644601 | 4.244898 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt | 1 | 2253 | package info.nightscout.androidaps.diaconn.pumplog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 일시정지 중지 (기저정지 해제)
*/
class LOG_SUSPEND_RELEASE_V2 private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte,
batteryRemain: Byte,
patternType: Byte
) {
val type: Byte
val kind: Byte
val batteryRemain: Byte
val patternType // 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2
: Byte
override fun toString(): String {
val sb = StringBuilder("LOG_SUSPEND_RELEASE_V2{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append(", patternType=").append(patternType.toInt())
sb.append('}')
return sb.toString()
}
fun getBasalPattern():String {
//1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown
return when(patternType) {
1.toByte() -> "Base"
2.toByte() -> "Life1"
3.toByte() -> "Life2"
4.toByte() -> "Life3"
5.toByte() -> "Dr1"
6.toByte() -> "Dr2"
else -> "No Pattern"
}
}
companion object {
const val LOG_KIND: Byte = 0x04
fun parse(data: String): LOG_SUSPEND_RELEASE_V2 {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_SUSPEND_RELEASE_V2(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer)
)
}
}
init {
type = PumplogUtil.getType(typeAndKind)
kind = PumplogUtil.getKind(typeAndKind)
this.batteryRemain = batteryRemain
this.patternType = patternType
}
} | agpl-3.0 | 358e25b1743b6dc3c51ee149b3a07dfc | 30.070423 | 131 | 0.573696 | 3.775685 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt | 1 | 2366 | package info.nightscout.androidaps.plugins.pump.common.bolusInfo
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.utils.T
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.abs
@OpenForTesting
@Singleton
class DetailedBolusInfoStorage @Inject constructor(
val aapsLogger: AAPSLogger
) {
val store = ArrayList<DetailedBolusInfo>()
@Synchronized
fun add(detailedBolusInfo: DetailedBolusInfo) {
aapsLogger.debug("Stored bolus info: $detailedBolusInfo")
store.add(detailedBolusInfo)
}
@Synchronized
fun findDetailedBolusInfo(bolusTime: Long, bolus: Double): DetailedBolusInfo? {
// Look for info with bolus
for (i in store.indices) {
val d = store[i]
//aapsLogger.debug(LTag.PUMP, "Existing bolus info: " + store[i])
if (bolusTime > d.timestamp - T.mins(1).msecs() && bolusTime < d.timestamp + T.mins(1).msecs() && abs(store[i].insulin - bolus) < 0.01) {
aapsLogger.debug(LTag.PUMP, "Using & removing bolus info for time $bolusTime: ${store[i]}")
store.removeAt(i)
return d
}
}
// If not found use time only
for (i in store.indices) {
val d = store[i]
if (bolusTime > d.timestamp - T.mins(1).msecs() && bolusTime < d.timestamp + T.mins(1).msecs() && bolus <= store[i].insulin + 0.01) {
aapsLogger.debug(LTag.PUMP, "Using TIME-ONLY & removing bolus info for time $bolusTime: ${store[i]}")
store.removeAt(i)
return d
}
}
// If not found, use last record if amount is the same
// if (store.size > 0) {
// val d = store[store.size - 1]
// if (abs(d.insulin - bolus) < 0.01) {
// aapsLogger.debug(LTag.PUMP, "Using LAST & removing bolus info for time $bolusTime: $d")
// store.removeAt(store.size - 1)
// return d
// }
// }
//Not found
aapsLogger.debug(LTag.PUMP, "Bolus info not found for time $bolusTime")
return null
}
} | agpl-3.0 | 826f600ea41fb7b3683347055a001845 | 37.803279 | 149 | 0.611158 | 4.114783 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/dashboard/CardsAdapter.kt | 1 | 5941 | package org.wordpress.android.ui.mysite.cards.dashboard
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.DiffUtil.Callback
import androidx.recyclerview.widget.RecyclerView.Adapter
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.BloggingPromptCard.BloggingPromptCardWithData
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.ErrorCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.ErrorWithinCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.PostCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.PostCard.PostCardWithPostItems
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.PostCard.PostCardWithoutPostItems
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.DashboardCards.DashboardCard.TodaysStatsCard.TodaysStatsCardWithData
import org.wordpress.android.ui.mysite.MySiteCardAndItem.DashboardCardType
import org.wordpress.android.ui.mysite.cards.dashboard.bloggingprompts.BloggingPromptCardViewHolder
import org.wordpress.android.ui.mysite.cards.dashboard.bloggingprompts.BloggingPromptsCardAnalyticsTracker
import org.wordpress.android.ui.mysite.cards.dashboard.error.ErrorCardViewHolder
import org.wordpress.android.ui.mysite.cards.dashboard.error.ErrorWithinCardViewHolder
import org.wordpress.android.ui.mysite.cards.dashboard.posts.PostCardViewHolder
import org.wordpress.android.ui.mysite.cards.dashboard.todaysstats.TodaysStatsCardViewHolder
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.HtmlCompatWrapper
import org.wordpress.android.util.image.ImageManager
class CardsAdapter(
private val imageManager: ImageManager,
private val uiHelpers: UiHelpers,
private val bloggingPromptsCardAnalyticsTracker: BloggingPromptsCardAnalyticsTracker,
private val htmlCompatWrapper: HtmlCompatWrapper,
private val learnMoreClicked: () -> Unit
) : Adapter<CardViewHolder<*>>() {
private val items = mutableListOf<DashboardCard>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder<*> {
return when (viewType) {
DashboardCardType.ERROR_CARD.ordinal -> ErrorCardViewHolder(parent)
DashboardCardType.TODAYS_STATS_CARD_ERROR.ordinal,
DashboardCardType.POST_CARD_ERROR.ordinal -> ErrorWithinCardViewHolder(parent, uiHelpers)
DashboardCardType.TODAYS_STATS_CARD.ordinal -> TodaysStatsCardViewHolder(parent, uiHelpers)
DashboardCardType.POST_CARD_WITHOUT_POST_ITEMS.ordinal ->
PostCardViewHolder.PostCardWithoutPostItemsViewHolder(parent, imageManager, uiHelpers)
DashboardCardType.POST_CARD_WITH_POST_ITEMS.ordinal ->
PostCardViewHolder.PostCardWithPostItemsViewHolder(parent, imageManager, uiHelpers)
DashboardCardType.BLOGGING_PROMPT_CARD.ordinal -> BloggingPromptCardViewHolder(
parent,
uiHelpers,
imageManager,
bloggingPromptsCardAnalyticsTracker,
htmlCompatWrapper,
learnMoreClicked
)
else -> throw IllegalArgumentException("Unexpected view type")
}
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: CardViewHolder<*>, position: Int) {
when (holder) {
is ErrorCardViewHolder -> holder.bind(items[position] as ErrorCard)
is ErrorWithinCardViewHolder -> holder.bind(items[position] as ErrorWithinCard)
is TodaysStatsCardViewHolder -> holder.bind(items[position] as TodaysStatsCardWithData)
is PostCardViewHolder<*> -> holder.bind(items[position] as PostCard)
is BloggingPromptCardViewHolder -> holder.bind(items[position] as BloggingPromptCardWithData)
}
}
override fun getItemViewType(position: Int) = items[position].dashboardCardType.ordinal
fun update(newItems: List<DashboardCard>) {
val diffResult = DiffUtil.calculateDiff(DashboardCardsDiffUtil(items, newItems))
items.clear()
items.addAll(newItems)
diffResult.dispatchUpdatesTo(this)
}
@Suppress("ComplexMethod")
class DashboardCardsDiffUtil(
private val oldList: List<DashboardCard>,
private val newList: List<DashboardCard>
) : Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val newItem = newList[newItemPosition]
val oldItem = oldList[oldItemPosition]
return oldItem.dashboardCardType == newItem.dashboardCardType && when {
oldItem is ErrorCard && newItem is ErrorCard -> true
oldItem is ErrorWithinCard && newItem is ErrorWithinCard -> true
oldItem is TodaysStatsCardWithData && newItem is TodaysStatsCardWithData -> true
oldItem is PostCardWithPostItems && newItem is PostCardWithPostItems -> true
oldItem is PostCardWithoutPostItems && newItem is PostCardWithoutPostItems -> true
oldItem is BloggingPromptCardWithData && newItem is BloggingPromptCardWithData -> true
else -> throw UnsupportedOperationException("Diff not implemented yet")
}
}
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean = oldList[oldItemPosition] == newList[newItemPosition]
}
}
| gpl-2.0 | fbb636f7b492dc6ea15ac127fff80973 | 55.04717 | 136 | 0.746507 | 5.082121 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/utilities/SettingsManagerImpl.kt | 1 | 3521 | package com.kelsos.mbrc.utilities
import android.app.Application
import android.content.SharedPreferences
import androidx.annotation.StringDef
import com.kelsos.mbrc.R
import com.kelsos.mbrc.logging.FileLoggingTree
import com.kelsos.mbrc.utilities.RemoteUtils.getVersionCode
import com.kelsos.mbrc.utilities.SettingsManager.Companion.NONE
import org.threeten.bp.Instant
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SettingsManagerImpl
@Inject
constructor(
private val context: Application,
private val preferences: SharedPreferences
) : SettingsManager {
init {
setupManager()
}
private fun setupManager() {
val loggingEnabled = loggingEnabled()
if (loggingEnabled) {
Timber.plant(FileLoggingTree(this.context.applicationContext))
} else {
val fileLoggingTree = Timber.forest().find { it is FileLoggingTree }
fileLoggingTree?.let { Timber.uproot(it) }
}
}
private fun loggingEnabled(): Boolean {
return preferences.getBoolean(getKey(R.string.settings_key_debug_logging), false)
}
@SettingsManager.CallAction
override fun getCallAction(): String = preferences.getString(
getKey(R.string.settings_key_incoming_call_action), NONE) ?: NONE
override fun isPluginUpdateCheckEnabled(): Boolean {
return preferences.getBoolean(getKey(R.string.settings_key_plugin_check), false)
}
override fun getLastUpdated(required: Boolean):Instant {
val key = if(required) REQUIRED_CHECK else getKey(R.string.settings_key_last_update_check)
return Instant.ofEpochMilli(preferences.getLong(key, 0))
}
override fun setLastUpdated(lastChecked: Instant, required: Boolean) {
val key = if (required) REQUIRED_CHECK else getKey(R.string.settings_key_last_update_check)
preferences.edit()
.putLong(key, lastChecked.toEpochMilli())
.apply()
}
override suspend fun shouldDisplayOnlyAlbumArtists(): Boolean {
return preferences.getBoolean(getKey(R.string.settings_key_album_artists_only), false)
}
override fun setShouldDisplayOnlyAlbumArtist(onlyAlbumArtist: Boolean) {
preferences.edit().putBoolean(getKey(R.string.settings_key_album_artists_only), onlyAlbumArtist)
.apply()
}
override fun shouldShowChangeLog(): Boolean {
val lastVersionCode = preferences.getLong(getKey(R.string.settings_key_last_version_run), 0)
val currentVersion = context.getVersionCode()
if (lastVersionCode < currentVersion) {
preferences.edit()
.putLong(getKey(R.string.settings_key_last_version_run), currentVersion)
.apply()
Timber.d("Update or fresh install")
return true
}
return false
}
private fun getKey(settingsKey: Int) = context.getString(settingsKey)
companion object {
const val REQUIRED_CHECK = "update_required_check"
}
}
interface SettingsManager {
@CallAction fun getCallAction(): String
@StringDef(NONE,
PAUSE,
STOP,
REDUCE)
@Retention(AnnotationRetention.SOURCE)
annotation class CallAction
companion object {
const val NONE = "none"
const val PAUSE = "pause"
const val STOP = "stop"
const val REDUCE = "reduce"
}
suspend fun shouldDisplayOnlyAlbumArtists(): Boolean
fun setShouldDisplayOnlyAlbumArtist(onlyAlbumArtist: Boolean)
fun shouldShowChangeLog(): Boolean
fun isPluginUpdateCheckEnabled(): Boolean
fun getLastUpdated(required: Boolean = false): Instant
fun setLastUpdated(lastChecked: Instant, required: Boolean = false)
}
| gpl-3.0 | 392c3963722ceb8e2e0cd032535e5ffd | 29.885965 | 100 | 0.745527 | 4.242169 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/SourceRootEntityImpl.kt | 1 | 19260 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SourceRootEntityImpl : SourceRootEntity, WorkspaceEntityBase() {
companion object {
internal val CONTENTROOT_CONNECTION_ID: ConnectionId = ConnectionId.create(ContentRootEntity::class.java, SourceRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java,
CustomSourceRootPropertiesEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_ONE, false)
internal val JAVASOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java,
JavaSourceRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val JAVARESOURCEROOTS_CONNECTION_ID: ConnectionId = ConnectionId.create(SourceRootEntity::class.java,
JavaResourceRootEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, false)
val connections = listOf<ConnectionId>(
CONTENTROOT_CONNECTION_ID,
CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID,
JAVASOURCEROOTS_CONNECTION_ID,
JAVARESOURCEROOTS_CONNECTION_ID,
)
}
override val contentRoot: ContentRootEntity
get() = snapshot.extractOneToManyParent(CONTENTROOT_CONNECTION_ID, this)!!
@JvmField
var _url: VirtualFileUrl? = null
override val url: VirtualFileUrl
get() = _url!!
@JvmField
var _rootType: String? = null
override val rootType: String
get() = _rootType!!
override val customSourceRootProperties: CustomSourceRootPropertiesEntity?
get() = snapshot.extractOneToOneChild(CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID, this)
override val javaSourceRoots: List<JavaSourceRootEntity>
get() = snapshot.extractOneToManyChildren<JavaSourceRootEntity>(JAVASOURCEROOTS_CONNECTION_ID, this)!!.toList()
override val javaResourceRoots: List<JavaResourceRootEntity>
get() = snapshot.extractOneToManyChildren<JavaResourceRootEntity>(JAVARESOURCEROOTS_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SourceRootEntityData?) : ModifiableWorkspaceEntityBase<SourceRootEntity>(), SourceRootEntity.Builder {
constructor() : this(SourceRootEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SourceRootEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "url", this.url)
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(CONTENTROOT_CONNECTION_ID, this) == null) {
error("Field SourceRootEntity#contentRoot should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, CONTENTROOT_CONNECTION_ID)] == null) {
error("Field SourceRootEntity#contentRoot should be initialized")
}
}
if (!getEntityData().isUrlInitialized()) {
error("Field SourceRootEntity#url should be initialized")
}
if (!getEntityData().isRootTypeInitialized()) {
error("Field SourceRootEntity#rootType should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(JAVASOURCEROOTS_CONNECTION_ID, this) == null) {
error("Field SourceRootEntity#javaSourceRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, JAVASOURCEROOTS_CONNECTION_ID)] == null) {
error("Field SourceRootEntity#javaSourceRoots should be initialized")
}
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(JAVARESOURCEROOTS_CONNECTION_ID, this) == null) {
error("Field SourceRootEntity#javaResourceRoots should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, JAVARESOURCEROOTS_CONNECTION_ID)] == null) {
error("Field SourceRootEntity#javaResourceRoots should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as SourceRootEntity
this.entitySource = dataSource.entitySource
this.url = dataSource.url
this.rootType = dataSource.rootType
if (parents != null) {
this.contentRoot = parents.filterIsInstance<ContentRootEntity>().single()
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var contentRoot: ContentRootEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(CONTENTROOT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
CONTENTROOT_CONNECTION_ID)]!! as ContentRootEntity
}
else {
this.entityLinks[EntityLink(false, CONTENTROOT_CONNECTION_ID)]!! as ContentRootEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(CONTENTROOT_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, CONTENTROOT_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, CONTENTROOT_CONNECTION_ID)] = value
}
changedProperty.add("contentRoot")
}
override var url: VirtualFileUrl
get() = getEntityData().url
set(value) {
checkModificationAllowed()
getEntityData().url = value
changedProperty.add("url")
val _diff = diff
if (_diff != null) index(this, "url", value)
}
override var rootType: String
get() = getEntityData().rootType
set(value) {
checkModificationAllowed()
getEntityData().rootType = value
changedProperty.add("rootType")
}
override var customSourceRootProperties: CustomSourceRootPropertiesEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true,
CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID)] as? CustomSourceRootPropertiesEntity
}
else {
this.entityLinks[EntityLink(true, CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID)] as? CustomSourceRootPropertiesEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToOneChildOfParent(CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, CUSTOMSOURCEROOTPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("customSourceRootProperties")
}
// List of non-abstract referenced types
var _javaSourceRoots: List<JavaSourceRootEntity>? = emptyList()
override var javaSourceRoots: List<JavaSourceRootEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<JavaSourceRootEntity>(JAVASOURCEROOTS_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
JAVASOURCEROOTS_CONNECTION_ID)] as? List<JavaSourceRootEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, JAVASOURCEROOTS_CONNECTION_ID)] as? List<JavaSourceRootEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(JAVASOURCEROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, JAVASOURCEROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, JAVASOURCEROOTS_CONNECTION_ID)] = value
}
changedProperty.add("javaSourceRoots")
}
// List of non-abstract referenced types
var _javaResourceRoots: List<JavaResourceRootEntity>? = emptyList()
override var javaResourceRoots: List<JavaResourceRootEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<JavaResourceRootEntity>(JAVARESOURCEROOTS_CONNECTION_ID,
this)!!.toList() + (this.entityLinks[EntityLink(true,
JAVARESOURCEROOTS_CONNECTION_ID)] as? List<JavaResourceRootEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, JAVARESOURCEROOTS_CONNECTION_ID)] as? List<JavaResourceRootEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(JAVARESOURCEROOTS_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, JAVARESOURCEROOTS_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, JAVARESOURCEROOTS_CONNECTION_ID)] = value
}
changedProperty.add("javaResourceRoots")
}
override fun getEntityData(): SourceRootEntityData = result ?: super.getEntityData() as SourceRootEntityData
override fun getEntityClass(): Class<SourceRootEntity> = SourceRootEntity::class.java
}
}
class SourceRootEntityData : WorkspaceEntityData<SourceRootEntity>() {
lateinit var url: VirtualFileUrl
lateinit var rootType: String
fun isUrlInitialized(): Boolean = ::url.isInitialized
fun isRootTypeInitialized(): Boolean = ::rootType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SourceRootEntity> {
val modifiable = SourceRootEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): SourceRootEntity {
val entity = SourceRootEntityImpl()
entity._url = url
entity._rootType = rootType
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SourceRootEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SourceRootEntity(url, rootType, entitySource) {
this.contentRoot = parents.filterIsInstance<ContentRootEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ContentRootEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceRootEntityData
if (this.entitySource != other.entitySource) return false
if (this.url != other.url) return false
if (this.rootType != other.rootType) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SourceRootEntityData
if (this.url != other.url) return false
if (this.rootType != other.rootType) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + rootType.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + url.hashCode()
result = 31 * result + rootType.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.url?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
| apache-2.0 | 5efd77a3ba88630690c24c0a1be572b0 | 41.895323 | 195 | 0.648027 | 5.352974 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/serializers/JsonKotlinFormat.kt | 1 | 4534 | /*
* JsonKotlinFormat.kt
*
* Copyright 2019 Google
*
* 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 au.id.micolous.metrodroid.serializers
import au.id.micolous.metrodroid.card.Card
import au.id.micolous.metrodroid.util.readToString
import kotlinx.io.InputStream
import kotlinx.io.OutputStream
import kotlinx.serialization.*
import kotlinx.serialization.CompositeDecoder.Companion.READ_ALL
import kotlinx.serialization.CompositeDecoder.Companion.READ_DONE
import kotlinx.serialization.internal.SerialClassDescImpl
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import kotlinx.serialization.json.JsonElement
object JsonKotlinFormat : CardExporter, CardImporter {
override fun writeCard(s: OutputStream, card: Card) {
s.write(writeCard(card).toUtf8Bytes())
}
fun writeCard(card: Card) = Json(JsonConfiguration.Stable.copy(prettyPrint = true, encodeDefaults = false)).stringify(Card.serializer(), card)
override fun readCard(stream: InputStream) =
readCard(stream.readToString())
// This intentionally runs in non-strict mode.
//
// This allows us to skip unknown fields:
// 1. This lets us remove old fields, without keeping attributes hanging around. There doesn't
// seem to be a simple way to explicitly ignore single fields in JSON inputs.
// 2. Dumps from a newer version of Metrodroid can still be read (though, without these fields).
val nonstrict = Json(JsonConfiguration.Stable.copy(useArrayPolymorphism = true,
strictMode = false))
override fun readCard(input: String): Card =
nonstrict.parse(Card.serializer(), input)
}
// Standard polymorphic serializer works fine but let's avoid putting
// full class names in stored formats
abstract class MultiTypeSerializer<T : Any> : KSerializer<T> {
abstract val name: String
override val descriptor: SerialDescriptor
get() = object : SerialClassDescImpl(name) {
override val kind: SerialKind = UnionKind.POLYMORPHIC
init {
addElement("type")
addElement("contents")
}
}
@Suppress("UNCHECKED_CAST")
override fun serialize(encoder: Encoder, obj: T) {
@Suppress("NAME_SHADOWING")
val output = encoder.beginStructure(descriptor)
val (str, serializer) = obj2serializer(obj)
output.encodeStringElement(descriptor, 0, str)
output.encodeSerializableElement(descriptor, 1, serializer as KSerializer<T>,
obj)
output.endStructure(descriptor)
}
abstract fun obj2serializer(obj: T): Pair<String, KSerializer<out T>>
abstract fun str2serializer(name: String): KSerializer<out T>
@Suppress("UNCHECKED_CAST")
override fun deserialize(decoder: Decoder): T {
@Suppress("NAME_SHADOWING")
val input = decoder.beginStructure(descriptor)
var klassName: String? = null
var value: T? = null
mainLoop@ while (true) {
when (input.decodeElementIndex(descriptor)) {
READ_ALL -> {
klassName = input.decodeStringElement(descriptor, 0)
val loader = str2serializer(klassName) as KSerializer<T>
value = input.decodeSerializableElement(descriptor, 1, loader)
break@mainLoop
}
READ_DONE -> {
break@mainLoop
}
0 -> {
klassName = input.decodeStringElement(descriptor, 0)
}
1 -> {
val loader = str2serializer(klassName!!) as KSerializer<T>
value = input.decodeSerializableElement(descriptor, 1, loader)
}
else -> throw SerializationException("Invalid index")
}
}
input.endStructure(descriptor)
return value!!
}
}
| gpl-3.0 | 16b17a0c81fa432f1ad67b12dc443197 | 38.77193 | 146 | 0.67071 | 4.635992 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | di/di_singleton/src/main/kotlin/siarhei/luskanau/iot/doorbell/di/AppModules.kt | 1 | 4388 | package siarhei.luskanau.iot.doorbell.di
import android.content.Context
import androidx.startup.AppInitializer
import androidx.work.WorkManager
import siarhei.luskanau.iot.doorbell.common.DefaultDoorbellsDataSource
import siarhei.luskanau.iot.doorbell.common.DeviceInfoProvider
import siarhei.luskanau.iot.doorbell.common.DoorbellsDataSource
import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactory
import siarhei.luskanau.iot.doorbell.common.ImagesDataSourceFactoryImpl
import siarhei.luskanau.iot.doorbell.common.IpAddressProvider
import siarhei.luskanau.iot.doorbell.data.AndroidDeviceInfoProvider
import siarhei.luskanau.iot.doorbell.data.AndroidIpAddressProvider
import siarhei.luskanau.iot.doorbell.data.AndroidThisDeviceRepository
import siarhei.luskanau.iot.doorbell.data.AppBackgroundServices
import siarhei.luskanau.iot.doorbell.data.ScheduleWorkManagerService
import siarhei.luskanau.iot.doorbell.data.repository.CameraRepository
import siarhei.luskanau.iot.doorbell.data.repository.DoorbellRepository
import siarhei.luskanau.iot.doorbell.data.repository.FirebaseDoorbellRepository
import siarhei.luskanau.iot.doorbell.data.repository.ImageRepository
import siarhei.luskanau.iot.doorbell.data.repository.InternalStorageImageRepository
import siarhei.luskanau.iot.doorbell.data.repository.JetpackCameraRepository
import siarhei.luskanau.iot.doorbell.data.repository.PersistenceRepository
import siarhei.luskanau.iot.doorbell.data.repository.StubDoorbellRepository
import siarhei.luskanau.iot.doorbell.data.repository.StubUptimeRepository
import siarhei.luskanau.iot.doorbell.data.repository.ThisDeviceRepository
import siarhei.luskanau.iot.doorbell.data.repository.UptimeFirebaseRepository
import siarhei.luskanau.iot.doorbell.data.repository.UptimeRepository
import siarhei.luskanau.iot.doorbell.persistence.DefaultPersistenceRepository
import siarhei.luskanau.iot.doorbell.workmanager.DefaultScheduleWorkManagerService
import siarhei.luskanau.iot.doorbell.workmanager.WorkManagerInitializer
class AppModules(context: Context) {
val imageRepository: ImageRepository by lazy {
InternalStorageImageRepository(
context = context
)
}
val doorbellRepository: DoorbellRepository by lazy {
if (thisDeviceRepository.isEmulator()) {
StubDoorbellRepository()
} else {
FirebaseDoorbellRepository()
}
}
val uptimeRepository: UptimeRepository by lazy {
if (thisDeviceRepository.isEmulator()) {
StubUptimeRepository()
} else {
UptimeFirebaseRepository()
}
}
val thisDeviceRepository: ThisDeviceRepository by lazy {
AndroidThisDeviceRepository(
context = context,
deviceInfoProvider = deviceInfoProvider,
cameraRepository = cameraRepository,
ipAddressProvider = ipAddressProvider
)
}
val deviceInfoProvider: DeviceInfoProvider by lazy {
AndroidDeviceInfoProvider(
context = context
)
}
val cameraRepository: CameraRepository by lazy {
JetpackCameraRepository(
context = context,
imageRepository = imageRepository
)
}
val persistenceRepository: PersistenceRepository by lazy {
DefaultPersistenceRepository(
context = context
)
}
val imagesDataSourceFactory: ImagesDataSourceFactory by lazy {
ImagesDataSourceFactoryImpl(
doorbellRepository = doorbellRepository
)
}
val ipAddressProvider: IpAddressProvider by lazy { AndroidIpAddressProvider() }
val doorbellsDataSource: DoorbellsDataSource by lazy {
DefaultDoorbellsDataSource(
doorbellRepository = doorbellRepository
)
}
val workManager: WorkManager by lazy {
AppInitializer.getInstance(context).initializeComponent(WorkManagerInitializer::class.java)
}
val scheduleWorkManagerService: ScheduleWorkManagerService by lazy {
DefaultScheduleWorkManagerService(workManager = { workManager })
}
val appBackgroundServices: AppBackgroundServices by lazy {
AppBackgroundServices(
doorbellRepository = doorbellRepository,
thisDeviceRepository = thisDeviceRepository,
scheduleWorkManagerService = scheduleWorkManagerService
)
}
}
| mit | 39645cd81e893b3069d0508474d966ff | 42.019608 | 99 | 0.766636 | 5.192899 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/wizard/GitNewProjectWizardStep.kt | 1 | 2395 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.wizard
import com.intellij.ide.IdeBundle
import com.intellij.ide.projectWizard.NewProjectWizardCollector
import com.intellij.openapi.GitRepositoryInitializer
import com.intellij.openapi.observable.util.bindBooleanStorage
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.ui.UIBundle
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.Panel
import com.intellij.ui.dsl.builder.bindSelected
import java.nio.file.Path
class GitNewProjectWizardStep(
parent: NewProjectWizardBaseStep
) : AbstractNewProjectWizardStep(parent),
NewProjectWizardBaseData by parent,
GitNewProjectWizardData {
private val gitRepositoryInitializer = GitRepositoryInitializer.getInstance()
private val gitProperty = propertyGraph.property(false)
.bindBooleanStorage("NewProjectWizard.gitState")
override val git get() = gitRepositoryInitializer != null && gitProperty.get()
override fun setupUI(builder: Panel) {
if (gitRepositoryInitializer != null) {
with(builder) {
row("") {
checkBox(UIBundle.message("label.project.wizard.new.project.git.checkbox"))
.bindSelected(gitProperty)
}.bottomGap(BottomGap.SMALL)
}
}
}
override fun setupProject(project: Project) {
setupProjectSafe(project, UIBundle.message("error.project.wizard.new.project.git")) {
if (git) {
val projectBaseDirectory = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(Path.of(path, name))
if (projectBaseDirectory != null) {
runBackgroundableTask(IdeBundle.message("progress.title.creating.git.repository"), project) {
setupProjectSafe(project, UIBundle.message("error.project.wizard.new.project.git")) {
gitRepositoryInitializer!!.initRepository(project, projectBaseDirectory, true)
}
}
}
}
NewProjectWizardCollector.logGitFinished(context, git)
}
}
init {
data.putUserData(GitNewProjectWizardData.KEY, this)
gitProperty.afterChange {
NewProjectWizardCollector.logGitChanged(context)
}
}
} | apache-2.0 | 6160acf04ce126dc74224e29d15d25c0 | 37.031746 | 158 | 0.746973 | 4.659533 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowSetInitializer.kt | 1 | 11498 | // 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.toolWindow
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.runActivity
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.ToolWindowManagerListener
import com.intellij.openapi.wm.impl.DesktopLayout
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.ui.ExperimentalUI
import com.intellij.util.containers.addIfNotNull
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.*
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.VisibleForTesting
import java.util.concurrent.CancellationException
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.atomic.AtomicReference
@Suppress("SSBasedInspection")
private val LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.ToolWindowManagerImpl")
private inline fun Logger.debug(project: Project, lazyMessage: (project: String) -> @NonNls String) {
if (isDebugEnabled) {
// project.name must be not used - only projectFilePath is side effect free
debug(lazyMessage(project.presentableUrl ?: ""))
}
}
// open for rider
class ToolWindowSetInitializer(private val project: Project, private val manager: ToolWindowManagerImpl) {
@Volatile
private var isInitialized = false
private val initFuture: Deferred<Ref<List<RegisterToolWindowTask>?>>
private val pendingLayout = AtomicReference<DesktopLayout?>()
private val pendingTasks = ConcurrentLinkedQueue<Runnable>()
init {
val app = ApplicationManager.getApplication()
if (project.isDefault || app.isUnitTestMode || app.isHeadlessEnvironment) {
initFuture = CompletableDeferred(value = Ref())
}
else {
initFuture = project.coroutineScope.async {
Ref(runActivity("toolwindow init command creation") {
computeToolWindowBeans(project)
})
}
}
}
fun addToPendingTasksIfNotInitialized(task: Runnable): Boolean {
if (isInitialized) {
return false
}
else {
pendingTasks.add(task)
return true
}
}
fun scheduleSetLayout(newLayout: DesktopLayout) {
if (!isInitialized) {
// will be executed once project is loaded
pendingLayout.set(newLayout)
return
}
val app = ApplicationManager.getApplication()
if (app.isDispatchThread) {
pendingLayout.set(null)
manager.setLayout(newLayout)
}
else {
pendingLayout.set(newLayout)
project.coroutineScope.launch(Dispatchers.EDT) {
manager.setLayout(pendingLayout.getAndSet(null) ?: return@launch)
}
}
}
suspend fun initUi(reopeningEditorsJob: Job) {
try {
val ref = initFuture.await()
val tasks = ref.get()
LOG.debug(project) { "create and layout tool windows (project=$it, tasks=${tasks?.joinToString(separator = "\n")}" }
ref.set(null)
createAndLayoutToolWindows(manager, tasks ?: return, reopeningEditorsJob)
// separate EDT task - ensure that more important tasks like editor restoring maybe executed
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
while (true) {
(pendingTasks.poll() ?: break).run()
}
}
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
}
finally {
LOG.debug(project) { "initialization completed (project=$it)" }
isInitialized = true
}
}
private suspend fun createAndLayoutToolWindows(manager: ToolWindowManagerImpl,
tasks: List<RegisterToolWindowTask>,
reopeningEditorsJob: Job) {
val ep = (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint<RegisterToolWindowTaskProvider>("com.intellij.registerToolWindowTaskProvider")
val list = addExtraTasks(tasks, project, ep)
val hasSecondaryFrameToolWindows = withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
@Suppress("TestOnlyProblems")
manager.setLayoutOnInit(pendingLayout.getAndSet(null) ?: throw IllegalStateException("Expected some pending layout"))
val hasSecondaryFrameToolWindows = runActivity("toolwindow creating") {
// Register all tool windows for the default tool window pane. If there are any tool windows for other panes, we'll register them
// after the reopening editors job has created the panes
val registeredAll = registerToolWindows(list, manager) { it == WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID }
for (toolWindowPane in manager.getToolWindowPanes()) {
toolWindowPane.buttonManager.initMoreButton()
toolWindowPane.buttonManager.revalidateNotEmptyStripes()
toolWindowPane.putClientProperty(UIUtil.NOT_IN_HIERARCHY_COMPONENTS, manager.createNotInHierarchyIterable(toolWindowPane.paneId))
}
return@runActivity !registeredAll
}
service<ToolWindowManagerImpl.ToolWindowManagerAppLevelHelper>()
hasSecondaryFrameToolWindows
}
registerEpListeners(manager)
if (hasSecondaryFrameToolWindows) {
reopeningEditorsJob.join()
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
runActivity("secondary frames toolwindow creation") {
registerToolWindows(list, manager) { it != WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID }
}
}
}
}
}
private fun registerToolWindows(registerTasks: List<RegisterToolWindowTask>,
manager: ToolWindowManagerImpl,
shouldRegister: (String) -> Boolean): Boolean {
val entries = ArrayList<String>(registerTasks.size)
for (task in registerTasks) {
try {
val paneId = manager.getLayout().getInfo(task.id)?.safeToolWindowPaneId ?: WINDOW_INFO_DEFAULT_TOOL_WINDOW_PANE_ID
if (shouldRegister(paneId)) {
val toolWindowPane = manager.getToolWindowPane(paneId)
entries.add(manager.registerToolWindow(task, toolWindowPane.buttonManager).id)
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error(PluginException("Cannot init toolwindow ${task.contentFactory}", e, task.pluginDescriptor?.pluginId))
}
}
manager.project.messageBus.syncPublisher(ToolWindowManagerListener.TOPIC).toolWindowsRegistered(entries, manager)
return entries.size == registerTasks.size
}
private suspend fun addExtraTasks(tasks: List<RegisterToolWindowTask>,
project: Project,
ep: ExtensionPointImpl<RegisterToolWindowTaskProvider>): List<RegisterToolWindowTask> {
if (ep.size() == 0) {
return tasks
}
val result = tasks.toMutableList()
// FacetDependentToolWindowManager - strictly speaking, computeExtraToolWindowBeans should be executed not in EDT, but for now it is not safe because:
// 1. read action is required to read facet list (might cause a deadlock)
// 2. delay between collection and adding ProjectWideFacetListener (should we introduce a new method in RegisterToolWindowTaskProvider to add listeners?)
for (adapter in ep.sortedAdapters) {
val pluginDescriptor = adapter.pluginDescriptor
if (pluginDescriptor.pluginId != PluginManagerCore.CORE_ID) {
LOG.error("Only bundled plugin can define registerToolWindowTaskProvider: $pluginDescriptor")
continue
}
val provider = try {
adapter.createInstance<RegisterToolWindowTaskProvider>(ApplicationManager.getApplication()) ?: continue
}
catch (e: CancellationException) {
throw e
}
catch (e: Throwable) {
LOG.error(e)
continue
}
for (bean in withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) { provider.getTasks(project) }) {
beanToTask(project, bean)?.let(result::add)
}
}
return result
}
// This method cannot be inlined because of magic Kotlin compilation bug: it 'captured' "list" local value and cause class-loader leak
// See IDEA-CR-61904
private fun registerEpListeners(manager: ToolWindowManagerImpl) {
ToolWindowEP.EP_NAME.addExtensionPointListener(object : ExtensionPointListener<ToolWindowEP> {
override fun extensionAdded(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) {
manager.initToolWindow(extension, pluginDescriptor)
}
override fun extensionRemoved(extension: ToolWindowEP, pluginDescriptor: PluginDescriptor) {
manager.doUnregisterToolWindow(extension.id)
}
}, manager.project)
}
internal fun getToolWindowAnchor(factory: ToolWindowFactory?, bean: ToolWindowEP): ToolWindowAnchor {
return factory?.anchor ?: ToolWindowAnchor.fromText(bean.anchor ?: ToolWindowAnchor.LEFT.toString())
}
private fun beanToTask(project: Project, bean: ToolWindowEP, plugin: PluginDescriptor = bean.pluginDescriptor): RegisterToolWindowTask? {
val factory = bean.getToolWindowFactory(plugin)
return if (factory.isApplicable(project)) beanToTask(project, bean, plugin, factory) else null
}
private fun beanToTask(project: Project,
bean: ToolWindowEP,
plugin: PluginDescriptor,
factory: ToolWindowFactory): RegisterToolWindowTask {
val task = RegisterToolWindowTask(
id = bean.id,
icon = findIconFromBean(bean, factory, plugin),
anchor = getToolWindowAnchor(factory, bean),
sideTool = (bean.secondary || (@Suppress("DEPRECATION") bean.side)) && !ExperimentalUI.isNewUI(),
canCloseContent = bean.canCloseContents,
canWorkInDumbMode = DumbService.isDumbAware(factory),
shouldBeAvailable = factory.shouldBeAvailable(project),
contentFactory = factory,
stripeTitle = getStripeTitleSupplier(bean.id, project, plugin),
)
task.pluginDescriptor = bean.pluginDescriptor
return task
}
@VisibleForTesting
internal fun computeToolWindowBeans(project: Project): List<RegisterToolWindowTask> {
val ep = ToolWindowEP.EP_NAME.point as ExtensionPointImpl<ToolWindowEP>
val list = ArrayList<RegisterToolWindowTask>(ep.size())
ep.processWithPluginDescriptor(true) { bean, pluginDescriptor ->
try {
val condition = bean.getCondition(pluginDescriptor)
if (condition == null || condition.value(project)) {
list.addIfNotNull(beanToTask(project, bean, pluginDescriptor))
}
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
LOG.error("Cannot process toolwindow ${bean.id}", e)
}
}
return list
} | apache-2.0 | 18e9713711997e42ac78921c01238cb2 | 38.927083 | 155 | 0.72517 | 4.872034 | false | false | false | false |
GunoH/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarAdditionActionsHolder.kt | 2 | 1563 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.runToolbar
import com.intellij.execution.executors.ExecutorGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
internal class RunToolbarAdditionActionsHolder(private val executorGroup: ExecutorGroup<*>, val process: RunToolbarProcess) {
companion object {
@JvmStatic
fun getAdditionActionId(process: RunToolbarProcess) = "${process.moreActionSubGroupName}_additionAction"
@JvmStatic
fun getAdditionActionChooserGroupId(process: RunToolbarProcess) = "${process.moreActionSubGroupName}_additionActionChooserGroupId"
}
private var selectedAction: AnAction? = null
val moreActionChooserGroup: RunToolbarChooserAdditionGroup =
RunToolbarChooserAdditionGroup(executorGroup, process) { ex ->
object : RunToolbarProcessAction(process, ex) {
override fun actionPerformed(e: AnActionEvent) {
super.actionPerformed(e)
selectedAction = this
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = e.presentation.isEnabled && e.presentation.isVisible
}
}
}
val additionAction: RunToolbarAdditionAction = RunToolbarAdditionAction(executorGroup, process) { selectedAction }
init {
selectedAction = moreActionChooserGroup.getChildren(null)?.getOrNull(0)
}
} | apache-2.0 | cce140d96d7dcda7f6bcda0706691ac5 | 39.102564 | 158 | 0.760077 | 4.794479 | false | false | false | false |
NiciDieNase/chaosflix | touch/src/main/java/de/nicidienase/chaosflix/touch/browse/streaming/LivestreamAdapter.kt | 1 | 2270 | package de.nicidienase.chaosflix.touch.browse.streaming
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import de.nicidienase.chaosflix.common.mediadata.entities.streaming.LiveConference
import de.nicidienase.chaosflix.touch.databinding.ItemLiveeventCardviewBinding
class LivestreamAdapter(val listener: LivestreamListFragment.InteractionListener, liveConferences: List<LiveConference> = emptyList()) : androidx.recyclerview.widget.RecyclerView.Adapter<LivestreamAdapter.ViewHolder>() {
lateinit var items: MutableList<StreamingItem>
init {
setContent(liveConferences)
}
private fun convertToStreamingItemList(liveConferences: List<LiveConference>) {
liveConferences.map { liveConference ->
liveConference.groups.map { group ->
group.rooms.map { room ->
items.add(StreamingItem(liveConference, group, room))
}
}
}
}
private val TAG = LivestreamAdapter::class.simpleName
fun setContent(liveConferences: List<LiveConference>) {
items = ArrayList()
convertToStreamingItemList(liveConferences)
Log.d(TAG, "Size:" + items.size)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding =
ItemLiveeventCardviewBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
holder.binding.item = item
Glide.with(holder.binding.root)
.load(item.room.thumb)
.apply(RequestOptions().fitCenter())
.into(holder.binding.imageView)
holder.binding.root.setOnClickListener { listener.onStreamSelected(item) }
}
inner class ViewHolder(val binding: ItemLiveeventCardviewBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(binding.root)
}
| mit | 3f7c8874aec7c1406218cae89defff1f | 35.612903 | 220 | 0.70793 | 4.709544 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/stories/viewer/page/StoryViewerPageRepository.kt | 1 | 8092 | package org.thoughtcrime.securesms.stories.viewer.page
import android.content.Context
import android.net.Uri
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.BreakIteratorCompat
import org.signal.core.util.concurrent.SignalExecutors
import org.thoughtcrime.securesms.conversation.ConversationMessage
import org.thoughtcrime.securesms.database.DatabaseObserver
import org.thoughtcrime.securesms.database.NoSuchMessageException
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.MessageId
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.database.model.MmsMessageRecord
import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.jobs.MultiDeviceViewedUpdateJob
import org.thoughtcrime.securesms.jobs.SendViewedReceiptJob
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.recipients.RecipientId
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.util.Base64
/**
* Open for testing.
*/
open class StoryViewerPageRepository(context: Context) {
private val context = context.applicationContext
private fun getStoryRecords(recipientId: RecipientId): Observable<List<MessageRecord>> {
return Observable.create { emitter ->
val recipient = Recipient.resolved(recipientId)
fun refresh() {
val stories = if (recipient.isMyStory) {
SignalDatabase.mms.getAllOutgoingStories(false)
} else {
SignalDatabase.mms.getAllStoriesFor(recipientId)
}
val results = mutableListOf<MessageRecord>()
while (stories.next != null) {
if (!(recipient.isMyStory && stories.current.recipient.isGroup)) {
results.add(stories.current)
}
}
emitter.onNext(results)
}
val storyObserver = DatabaseObserver.Observer {
refresh()
}
ApplicationDependencies.getDatabaseObserver().registerStoryObserver(recipientId, storyObserver)
emitter.setCancellable {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(storyObserver)
}
refresh()
}
}
private fun getStoryPostFromRecord(recipientId: RecipientId, record: MessageRecord): Observable<StoryPost> {
return Observable.create { emitter ->
fun refresh(record: MessageRecord) {
val recipient = Recipient.resolved(recipientId)
val story = StoryPost(
id = record.id,
sender = if (record.isOutgoing) Recipient.self() else record.individualRecipient,
group = if (recipient.isGroup) recipient else null,
distributionList = if (record.recipient.isDistributionList) record.recipient else null,
viewCount = record.viewedReceiptCount,
replyCount = SignalDatabase.mms.getNumberOfStoryReplies(record.id),
dateInMilliseconds = record.dateSent,
content = getContent(record as MmsMessageRecord),
conversationMessage = ConversationMessage.ConversationMessageFactory.createWithUnresolvedData(context, record),
allowsReplies = record.storyType.isStoryWithReplies,
hasSelfViewed = if (record.isOutgoing) true else record.viewedReceiptCount > 0
)
emitter.onNext(story)
}
val recipient = Recipient.resolved(recipientId)
val messageUpdateObserver = DatabaseObserver.MessageObserver {
if (it.mms && it.id == record.id) {
try {
val messageRecord = SignalDatabase.mms.getMessageRecord(record.id)
if (messageRecord.isRemoteDelete) {
emitter.onComplete()
} else {
refresh(messageRecord)
}
} catch (e: NoSuchMessageException) {
emitter.onComplete()
}
}
}
val conversationObserver = DatabaseObserver.Observer {
refresh(SignalDatabase.mms.getMessageRecord(record.id))
}
ApplicationDependencies.getDatabaseObserver().registerConversationObserver(record.threadId, conversationObserver)
ApplicationDependencies.getDatabaseObserver().registerMessageUpdateObserver(messageUpdateObserver)
val messageInsertObserver = DatabaseObserver.MessageObserver {
refresh(SignalDatabase.mms.getMessageRecord(record.id))
}
if (recipient.isGroup) {
ApplicationDependencies.getDatabaseObserver().registerMessageInsertObserver(record.threadId, messageInsertObserver)
}
emitter.setCancellable {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(conversationObserver)
ApplicationDependencies.getDatabaseObserver().unregisterObserver(messageUpdateObserver)
if (recipient.isGroup) {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(messageInsertObserver)
}
}
refresh(record)
}
}
fun forceDownload(post: StoryPost): Completable {
return Stories.enqueueAttachmentsFromStoryForDownload(post.conversationMessage.messageRecord as MmsMessageRecord, true)
}
fun getStoryPostsFor(recipientId: RecipientId): Observable<List<StoryPost>> {
return getStoryRecords(recipientId)
.switchMap { records ->
val posts = records.map { getStoryPostFromRecord(recipientId, it) }
if (posts.isEmpty()) {
Observable.just(emptyList())
} else {
Observable.combineLatest(posts) { it.toList() as List<StoryPost> }
}
}.observeOn(Schedulers.io())
}
fun hideStory(recipientId: RecipientId): Completable {
return Completable.fromAction {
SignalDatabase.recipients.setHideStory(recipientId, true)
}.subscribeOn(Schedulers.io())
}
fun markViewed(storyPost: StoryPost) {
if (!storyPost.conversationMessage.messageRecord.isOutgoing) {
SignalExecutors.BOUNDED.execute {
val markedMessageInfo = SignalDatabase.mms.setIncomingMessageViewed(storyPost.id)
if (markedMessageInfo != null) {
ApplicationDependencies.getDatabaseObserver().notifyConversationListListeners()
ApplicationDependencies.getJobManager().add(
SendViewedReceiptJob(
markedMessageInfo.threadId,
storyPost.sender.id,
markedMessageInfo.syncMessageId.timetamp,
MessageId(storyPost.id, true)
)
)
MultiDeviceViewedUpdateJob.enqueue(listOf(markedMessageInfo.syncMessageId))
val recipientId = storyPost.group?.id ?: storyPost.sender.id
SignalDatabase.recipients.updateLastStoryViewTimestamp(recipientId)
Stories.enqueueNextStoriesForDownload(recipientId, true)
}
}
}
}
private fun getContent(record: MmsMessageRecord): StoryPost.Content {
return if (record.storyType.isTextStory || record.slideDeck.asAttachments().isEmpty()) {
StoryPost.Content.TextContent(
uri = Uri.parse("story_text_post://${record.id}"),
recordId = record.id,
hasBody = canParseToTextStory(record.body),
length = getTextStoryLength(record.body)
)
} else {
StoryPost.Content.AttachmentContent(
attachment = record.slideDeck.asAttachments().first()
)
}
}
private fun getTextStoryLength(body: String): Int {
return if (canParseToTextStory(body)) {
val breakIteratorCompat = BreakIteratorCompat.getInstance()
breakIteratorCompat.setText(StoryTextPost.parseFrom(Base64.decode(body)).body)
breakIteratorCompat.countBreaks()
} else {
0
}
}
private fun canParseToTextStory(body: String): Boolean {
return if (body.isNotEmpty()) {
try {
StoryTextPost.parseFrom(Base64.decode(body))
return true
} catch (e: Exception) {
false
}
} else {
false
}
}
}
| gpl-3.0 | 3e2036edaf59d130f6cdab7b6954dd2e | 36.290323 | 123 | 0.711814 | 4.955297 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/privacy/advanced/AdvancedPrivacySettingsFragment.kt | 1 | 9561 | package org.thoughtcrime.securesms.components.settings.app.privacy.advanced
import android.app.ProgressDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.text.SpannableStringBuilder
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.widget.TextViewCompat
import androidx.lifecycle.ViewModelProvider
import androidx.preference.PreferenceManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter
import org.thoughtcrime.securesms.registration.RegistrationNavigationActivity
import org.thoughtcrime.securesms.util.CommunicationActions
import org.thoughtcrime.securesms.util.SpanUtil
import org.thoughtcrime.securesms.util.ViewUtil
class AdvancedPrivacySettingsFragment : DSLSettingsFragment(R.string.preferences__advanced) {
private lateinit var viewModel: AdvancedPrivacySettingsViewModel
private var networkReceiver: NetworkReceiver? = null
private val sealedSenderSummary: CharSequence by lazy {
SpanUtil.learnMore(
requireContext(),
ContextCompat.getColor(requireContext(), R.color.signal_text_primary)
) {
CommunicationActions.openBrowserLink(
requireContext(),
getString(R.string.AdvancedPrivacySettingsFragment__sealed_sender_link)
)
}
}
var progressDialog: ProgressDialog? = null
val statusIcon: CharSequence by lazy {
val unidentifiedDeliveryIcon = requireNotNull(
ContextCompat.getDrawable(
requireContext(),
R.drawable.ic_unidentified_delivery
)
)
unidentifiedDeliveryIcon.setBounds(0, 0, ViewUtil.dpToPx(20), ViewUtil.dpToPx(20))
val iconTint = ContextCompat.getColor(requireContext(), R.color.signal_text_primary_dialog)
unidentifiedDeliveryIcon.colorFilter = PorterDuffColorFilter(iconTint, PorterDuff.Mode.SRC_IN)
SpanUtil.buildImageSpan(unidentifiedDeliveryIcon)
}
override fun onResume() {
super.onResume()
viewModel.refresh()
registerNetworkReceiver()
}
override fun onPause() {
super.onPause()
unregisterNetworkReceiver()
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
val repository = AdvancedPrivacySettingsRepository(requireContext())
val preferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
val factory = AdvancedPrivacySettingsViewModel.Factory(preferences, repository)
viewModel = ViewModelProvider(this, factory)[AdvancedPrivacySettingsViewModel::class.java]
viewModel.state.observe(viewLifecycleOwner) {
if (it.showProgressSpinner) {
if (progressDialog?.isShowing == false) {
progressDialog = ProgressDialog.show(requireContext(), null, null, true)
}
} else {
progressDialog?.hide()
}
adapter.submitList(getConfiguration(it).toMappingModelList())
}
viewModel.events.observe(viewLifecycleOwner) {
if (it == AdvancedPrivacySettingsViewModel.Event.DISABLE_PUSH_FAILED) {
Toast.makeText(
requireContext(),
R.string.ApplicationPreferencesActivity_error_connecting_to_server,
Toast.LENGTH_LONG
).show()
}
}
}
private fun getConfiguration(state: AdvancedPrivacySettingsState): DSLConfiguration {
return configure {
switchPref(
title = DSLSettingsText.from(R.string.preferences__signal_messages_and_calls),
summary = DSLSettingsText.from(getPushToggleSummary(state.isPushEnabled)),
isChecked = state.isPushEnabled
) {
if (state.isPushEnabled) {
val builder = MaterialAlertDialogBuilder(requireContext()).apply {
setMessage(R.string.ApplicationPreferencesActivity_disable_signal_messages_and_calls_by_unregistering)
setNegativeButton(android.R.string.cancel, null)
setPositiveButton(
android.R.string.ok
) { _, _ -> viewModel.disablePushMessages() }
}
val icon: Drawable = requireNotNull(ContextCompat.getDrawable(builder.context, R.drawable.ic_info_outline))
icon.setBounds(0, 0, ViewUtil.dpToPx(32), ViewUtil.dpToPx(32))
val title = TextView(builder.context)
val padding = ViewUtil.dpToPx(16)
title.setText(R.string.ApplicationPreferencesActivity_disable_signal_messages_and_calls)
title.setPadding(padding, padding, padding, padding)
title.compoundDrawablePadding = padding / 2
TextViewCompat.setTextAppearance(title, R.style.TextAppearance_Signal_Title2_MaterialDialog)
TextViewCompat.setCompoundDrawablesRelative(title, icon, null, null, null)
builder
.setCustomTitle(title)
.show()
} else {
startActivity(RegistrationNavigationActivity.newIntentForReRegistration(requireContext()))
}
}
switchPref(
title = DSLSettingsText.from(R.string.preferences_advanced__always_relay_calls),
summary = DSLSettingsText.from(R.string.preferences_advanced__relay_all_calls_through_the_signal_server_to_avoid_revealing_your_ip_address),
isChecked = state.alwaysRelayCalls
) {
viewModel.setAlwaysRelayCalls(!state.alwaysRelayCalls)
}
dividerPref()
sectionHeaderPref(R.string.preferences_communication__category_censorship_circumvention)
val censorshipSummaryResId: Int = when (state.censorshipCircumventionState) {
CensorshipCircumventionState.AVAILABLE -> R.string.preferences_communication__censorship_circumvention_if_enabled_signal_will_attempt_to_circumvent_censorship
CensorshipCircumventionState.AVAILABLE_MANUALLY_DISABLED -> R.string.preferences_communication__censorship_circumvention_you_have_manually_disabled
CensorshipCircumventionState.AVAILABLE_AUTOMATICALLY_ENABLED -> R.string.preferences_communication__censorship_circumvention_has_been_activated_based_on_your_accounts_phone_number
CensorshipCircumventionState.UNAVAILABLE_CONNECTED -> R.string.preferences_communication__censorship_circumvention_is_not_necessary_you_are_already_connected
CensorshipCircumventionState.UNAVAILABLE_NO_INTERNET -> R.string.preferences_communication__censorship_circumvention_can_only_be_activated_when_connected_to_the_internet
}
switchPref(
title = DSLSettingsText.from(R.string.preferences_communication__censorship_circumvention),
summary = DSLSettingsText.from(censorshipSummaryResId),
isChecked = state.censorshipCircumventionEnabled,
isEnabled = state.censorshipCircumventionState.available,
onClick = {
viewModel.setCensorshipCircumventionEnabled(!state.censorshipCircumventionEnabled)
}
)
dividerPref()
sectionHeaderPref(R.string.preferences_communication__category_sealed_sender)
switchPref(
title = DSLSettingsText.from(
SpannableStringBuilder(getString(R.string.AdvancedPrivacySettingsFragment__show_status_icon))
.append(" ")
.append(statusIcon)
),
summary = DSLSettingsText.from(R.string.AdvancedPrivacySettingsFragment__show_an_icon),
isChecked = state.showSealedSenderStatusIcon
) {
viewModel.setShowStatusIconForSealedSender(!state.showSealedSenderStatusIcon)
}
switchPref(
title = DSLSettingsText.from(R.string.preferences_communication__sealed_sender_allow_from_anyone),
summary = DSLSettingsText.from(R.string.preferences_communication__sealed_sender_allow_from_anyone_description),
isChecked = state.allowSealedSenderFromAnyone
) {
viewModel.setAllowSealedSenderFromAnyone(!state.allowSealedSenderFromAnyone)
}
textPref(
summary = DSLSettingsText.from(sealedSenderSummary)
)
}
}
private fun getPushToggleSummary(isPushEnabled: Boolean): String {
return if (isPushEnabled) {
PhoneNumberFormatter.prettyPrint(SignalStore.account().e164!!)
} else {
getString(R.string.preferences__free_private_messages_and_calls)
}
}
@Suppress("DEPRECATION")
private fun registerNetworkReceiver() {
val context: Context? = context
if (context != null && networkReceiver == null) {
networkReceiver = NetworkReceiver()
context.registerReceiver(networkReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
}
}
private fun unregisterNetworkReceiver() {
val context: Context? = context
if (context != null && networkReceiver != null) {
context.unregisterReceiver(networkReceiver)
networkReceiver = null
}
}
private inner class NetworkReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
viewModel.refresh()
}
}
}
| gpl-3.0 | cda8a0cf22fdec95714fc99aabecb418 | 39.858974 | 187 | 0.744587 | 4.836115 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/globalsearch/GlobalSearchPresenter.kt | 2 | 10427 | package eu.kanade.tachiyomi.ui.browse.source.globalsearch
import android.os.Bundle
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.toMangaInfo
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.source.CatalogueSource
import eu.kanade.tachiyomi.source.Source
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.model.toSManga
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourcePresenter
import eu.kanade.tachiyomi.util.lang.runAsObservable
import eu.kanade.tachiyomi.util.system.logcat
import logcat.LogPriority
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
/**
* Presenter of [GlobalSearchController]
* Function calls should be done from here. UI calls should be done from the controller.
*
* @param sourceManager manages the different sources.
* @param db manages the database calls.
* @param preferences manages the preference calls.
*/
open class GlobalSearchPresenter(
val initialQuery: String? = "",
val initialExtensionFilter: String? = null,
val sourceManager: SourceManager = Injekt.get(),
val db: DatabaseHelper = Injekt.get(),
val preferences: PreferencesHelper = Injekt.get()
) : BasePresenter<GlobalSearchController>() {
/**
* Enabled sources.
*/
val sources by lazy { getSourcesToQuery() }
/**
* Fetches the different sources by user settings.
*/
private var fetchSourcesSubscription: Subscription? = null
/**
* Subject which fetches image of given manga.
*/
private val fetchImageSubject = PublishSubject.create<Pair<List<Manga>, Source>>()
/**
* Subscription for fetching images of manga.
*/
private var fetchImageSubscription: Subscription? = null
private val extensionManager: ExtensionManager by injectLazy()
private var extensionFilter: String? = null
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
extensionFilter = savedState?.getString(GlobalSearchPresenter::extensionFilter.name)
?: initialExtensionFilter
// Perform a search with previous or initial state
search(
savedState?.getString(BrowseSourcePresenter::query.name)
?: initialQuery.orEmpty()
)
}
override fun onDestroy() {
fetchSourcesSubscription?.unsubscribe()
fetchImageSubscription?.unsubscribe()
super.onDestroy()
}
override fun onSave(state: Bundle) {
state.putString(BrowseSourcePresenter::query.name, query)
state.putString(GlobalSearchPresenter::extensionFilter.name, extensionFilter)
super.onSave(state)
}
/**
* Returns a list of enabled sources ordered by language and name, with pinned catalogues
* prioritized.
*
* @return list containing enabled sources.
*/
protected open fun getEnabledSources(): List<CatalogueSource> {
val languages = preferences.enabledLanguages().get()
val disabledSourceIds = preferences.disabledSources().get()
val pinnedSourceIds = preferences.pinnedSources().get()
return sourceManager.getCatalogueSources()
.filter { it.lang in languages }
.filterNot { it.id.toString() in disabledSourceIds }
.sortedWith(compareBy({ it.id.toString() !in pinnedSourceIds }, { "${it.name.lowercase()} (${it.lang})" }))
}
private fun getSourcesToQuery(): List<CatalogueSource> {
val filter = extensionFilter
val enabledSources = getEnabledSources()
var filteredSources: List<CatalogueSource>? = null
if (!filter.isNullOrEmpty()) {
filteredSources = extensionManager.installedExtensions
.filter { it.pkgName == filter }
.flatMap { it.sources }
.filter { it in enabledSources }
.filterIsInstance<CatalogueSource>()
}
if (filteredSources != null && filteredSources.isNotEmpty()) {
return filteredSources
}
val onlyPinnedSources = preferences.searchPinnedSourcesOnly()
val pinnedSourceIds = preferences.pinnedSources().get()
return enabledSources
.filter { if (onlyPinnedSources) it.id.toString() in pinnedSourceIds else true }
}
/**
* Creates a catalogue search item
*/
protected open fun createCatalogueSearchItem(source: CatalogueSource, results: List<GlobalSearchCardItem>?): GlobalSearchItem {
return GlobalSearchItem(source, results)
}
/**
* Initiates a search for manga per catalogue.
*
* @param query query on which to search.
*/
fun search(query: String) {
// Return if there's nothing to do
if (this.query == query) return
// Update query
this.query = query
// Create image fetch subscription
initializeFetchImageSubscription()
// Create items with the initial state
val initialItems = sources.map { createCatalogueSearchItem(it, null) }
var items = initialItems
val pinnedSourceIds = preferences.pinnedSources().get()
fetchSourcesSubscription?.unsubscribe()
fetchSourcesSubscription = Observable.from(sources)
.flatMap(
{ source ->
Observable.defer { source.fetchSearchManga(1, query, source.getFilterList()) }
.subscribeOn(Schedulers.io())
.onErrorReturn { MangasPage(emptyList(), false) } // Ignore timeouts or other exceptions
.map { it.mangas }
.map { list -> list.map { networkToLocalManga(it, source.id) } } // Convert to local manga
.doOnNext { fetchImage(it, source) } // Load manga covers
.map { list -> createCatalogueSearchItem(source, list.map { GlobalSearchCardItem(it) }) }
},
5
)
.observeOn(AndroidSchedulers.mainThread())
// Update matching source with the obtained results
.map { result ->
items
.map { item -> if (item.source == result.source) result else item }
.sortedWith(
compareBy(
// Bubble up sources that actually have results
{ it.results.isNullOrEmpty() },
// Same as initial sort, i.e. pinned first then alphabetically
{ it.source.id.toString() !in pinnedSourceIds },
{ "${it.source.name.lowercase()} (${it.source.lang})" }
)
)
}
// Update current state
.doOnNext { items = it }
// Deliver initial state
.startWith(initialItems)
.subscribeLatestCache(
{ view, manga ->
view.setItems(manga)
},
{ _, error ->
logcat(LogPriority.ERROR, error)
}
)
}
/**
* Initialize a list of manga.
*
* @param manga the list of manga to initialize.
*/
private fun fetchImage(manga: List<Manga>, source: Source) {
fetchImageSubject.onNext(Pair(manga, source))
}
/**
* Subscribes to the initializer of manga details and updates the view if needed.
*/
private fun initializeFetchImageSubscription() {
fetchImageSubscription?.unsubscribe()
fetchImageSubscription = fetchImageSubject.observeOn(Schedulers.io())
.flatMap { (first, source) ->
Observable.from(first)
.filter { it.thumbnail_url == null && !it.initialized }
.map { Pair(it, source) }
.concatMap { runAsObservable { getMangaDetails(it.first, it.second) } }
.map { Pair(source as CatalogueSource, it) }
}
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ (source, manga) ->
@Suppress("DEPRECATION")
view?.onMangaInitialized(source, manga)
},
{ error ->
logcat(LogPriority.ERROR, error)
}
)
}
/**
* Initializes the given manga.
*
* @param manga the manga to initialize.
* @return The initialized manga.
*/
private suspend fun getMangaDetails(manga: Manga, source: Source): Manga {
val networkManga = source.getMangaDetails(manga.toMangaInfo())
manga.copyFrom(networkManga.toSManga())
manga.initialized = true
db.insertManga(manga).executeAsBlocking()
return manga
}
/**
* Returns a manga from the database for the given manga from network. It creates a new entry
* if the manga is not yet in the database.
*
* @param sManga the manga from the source.
* @return a manga from the database.
*/
protected open fun networkToLocalManga(sManga: SManga, sourceId: Long): Manga {
var localManga = db.getManga(sManga.url, sourceId).executeAsBlocking()
if (localManga == null) {
val newManga = Manga.create(sManga.url, sManga.title, sourceId)
newManga.copyFrom(sManga)
val result = db.insertManga(newManga).executeAsBlocking()
newManga.id = result.insertedId()
localManga = newManga
} else if (!localManga.favorite) {
// if the manga isn't a favorite, set its display title from source
// if it later becomes a favorite, updated title will go to db
localManga.title = sManga.title
}
return localManga
}
}
| apache-2.0 | 458aa00f66e2fc4c465f0522224f586e | 36.642599 | 131 | 0.621368 | 4.967604 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/openal/src/templates/kotlin/openal/ALCTypes.kt | 4 | 903 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package openal
import org.lwjgl.generator.*
// void
val ALCvoid = "ALCvoid".void
// numeric
val ALCboolean = IntegerType("ALCboolean", PrimitiveMapping.BOOLEAN)
val ALCint = IntegerType("ALCint", PrimitiveMapping.INT)
val ALCuint = IntegerType("ALCuint", PrimitiveMapping.INT, unsigned = true)
// custom numeric
val ALCsizei = IntegerType("ALCsizei", PrimitiveMapping.INT)
val ALCenum = IntegerType("ALCenum", PrimitiveMapping.INT)
val ALCint64SOFT = IntegerType("ALCint64SOFT", PrimitiveMapping.LONG)
val ALCuint64SOFT = IntegerType("ALCuint64SOFT", PrimitiveMapping.LONG, unsigned = true)
// strings
val ALCcharASCII = CharType("ALCchar", CharMapping.ASCII)
val ALCcharUTF8 = CharType("ALCchar", CharMapping.UTF8)
// misc
val ALCdevice = "ALCdevice".opaque
val ALCcontext = "ALCcontext".opaque | bsd-3-clause | 37c38f2337caf1c0bbeb96d72fa56878 | 24.828571 | 88 | 0.765227 | 3.407547 | false | false | false | false |
dahlstrom-g/intellij-community | platform/core-impl/src/com/intellij/ide/plugins/IdeaPluginDescriptorImpl.kt | 1 | 21570 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.ide.plugins
import com.intellij.AbstractBundle
import com.intellij.DynamicBundle
import com.intellij.core.CoreBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import java.io.File
import java.io.IOException
import java.nio.file.Path
import java.time.ZoneOffset
import java.util.*
private val LOG: Logger
get() = PluginManagerCore.getLogger()
fun Iterable<IdeaPluginDescriptor>.toPluginSet(): Set<PluginId> = mapTo(LinkedHashSet()) { it.pluginId }
fun Iterable<PluginId>.toPluginDescriptors(): List<IdeaPluginDescriptorImpl> = mapNotNull { PluginManagerCore.findPlugin(it) }
@ApiStatus.Internal
class IdeaPluginDescriptorImpl(raw: RawPluginDescriptor,
@JvmField val path: Path,
private val isBundled: Boolean,
id: PluginId?,
@JvmField val moduleName: String?,
@JvmField val useCoreClassLoader: Boolean = false) : IdeaPluginDescriptor {
private val id: PluginId = id ?: PluginId.getId(raw.id ?: raw.name ?: throw RuntimeException("Neither id nor name are specified"))
private val name = raw.name ?: id?.idString ?: raw.id
@Suppress("EnumEntryName")
enum class OS {
mac, linux, windows, unix, freebsd
}
// only for sub descriptors
@JvmField internal var descriptorPath: String? = null
@Volatile private var description: String? = null
private val productCode = raw.productCode
private var releaseDate: Date? = raw.releaseDate?.let { Date.from(it.atStartOfDay(ZoneOffset.UTC).toInstant()) }
private val releaseVersion = raw.releaseVersion
private val isLicenseOptional = raw.isLicenseOptional
@NonNls private var resourceBundleBaseName: String? = null
private val changeNotes = raw.changeNotes
private var version: String? = raw.version
private var vendor = raw.vendor
private val vendorEmail = raw.vendorEmail
private val vendorUrl = raw.vendorUrl
private var category: String? = raw.category
@JvmField internal val url = raw.url
@JvmField val pluginDependencies: List<PluginDependency>
@JvmField val incompatibilities: List<PluginId> = raw.incompatibilities ?: Collections.emptyList()
init {
// https://youtrack.jetbrains.com/issue/IDEA-206274
val list = raw.depends
if (list != null) {
val iterator = list.iterator()
while (iterator.hasNext()) {
val item = iterator.next()
if (!item.isOptional) {
for (a in list) {
if (a.isOptional && a.pluginId == item.pluginId) {
a.isOptional = false
iterator.remove()
break
}
}
}
}
}
pluginDependencies = list ?: Collections.emptyList()
}
companion object {
@ApiStatus.Internal
@JvmField var disableNonBundledPlugins = false
}
@Transient @JvmField var jarFiles: List<Path>? = null
private var _pluginClassLoader: ClassLoader? = null
@JvmField val actions: List<RawPluginDescriptor.ActionDescriptor> = raw.actions ?: Collections.emptyList()
// extension point name -> list of extension descriptors
val epNameToExtensions: Map<String, MutableList<ExtensionDescriptor>>? = raw.epNameToExtensions
@JvmField val appContainerDescriptor = raw.appContainerDescriptor
@JvmField val projectContainerDescriptor = raw.projectContainerDescriptor
@JvmField val moduleContainerDescriptor = raw.moduleContainerDescriptor
@JvmField val content: PluginContentDescriptor = raw.contentModules?.let { PluginContentDescriptor(it) } ?: PluginContentDescriptor.EMPTY
@JvmField val dependencies = raw.dependencies
@JvmField val modules: List<PluginId> = raw.modules ?: Collections.emptyList()
private val descriptionChildText = raw.description
@JvmField val isUseIdeaClassLoader = raw.isUseIdeaClassLoader
@JvmField val isBundledUpdateAllowed = raw.isBundledUpdateAllowed
@JvmField internal val implementationDetail = raw.implementationDetail
@JvmField internal val onDemand = raw.onDemand
@JvmField internal val isRestartRequired = raw.isRestartRequired
@JvmField val packagePrefix = raw.`package`
private val sinceBuild = raw.sinceBuild
private val untilBuild = raw.untilBuild
private var isEnabled = true
var isDeleted = false
@JvmField internal var isIncomplete = false
override fun getDescriptorPath() = descriptorPath
override fun getDependencies(): List<IdeaPluginDependency> {
return if (pluginDependencies.isEmpty()) Collections.emptyList() else Collections.unmodifiableList(pluginDependencies)
}
override fun getPluginPath() = path
private fun createSub(raw: RawPluginDescriptor,
descriptorPath: String,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
dataLoader: DataLoader,
moduleName: String?): IdeaPluginDescriptorImpl {
raw.name = name
val result = IdeaPluginDescriptorImpl(raw, path = path, isBundled = isBundled, id = id, moduleName = moduleName,
useCoreClassLoader = useCoreClassLoader)
result.descriptorPath = descriptorPath
result.vendor = vendor
result.version = version
result.resourceBundleBaseName = resourceBundleBaseName
result.readExternal(raw = raw, pathResolver = pathResolver, context = context, isSub = true, dataLoader = dataLoader)
return result
}
fun readExternal(raw: RawPluginDescriptor,
pathResolver: PathResolver,
context: DescriptorListLoadingContext,
isSub: Boolean,
dataLoader: DataLoader) {
// include module file descriptor if not specified as `depends` (old way - xi:include)
// must be first because merged into raw descriptor
if (!isSub) {
for (module in content.modules) {
val subDescriptorFile = module.configFile ?: "${module.name}.xml"
val subDescriptor = createSub(raw = pathResolver.resolveModuleFile(readContext = context,
dataLoader = dataLoader,
path = subDescriptorFile,
readInto = null),
descriptorPath = subDescriptorFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = module.name)
module.descriptor = subDescriptor
}
}
if (raw.resourceBundleBaseName != null) {
if (id == PluginManagerCore.CORE_ID && !isSub) {
LOG.warn("<resource-bundle>${raw.resourceBundleBaseName}</resource-bundle> tag is found in an xml descriptor" +
" included into the platform part of the IDE but the platform part uses predefined bundles " +
"(e.g. ActionsBundle for actions) anyway; this tag must be replaced by a corresponding attribute in some inner tags " +
"(e.g. by 'resource-bundle' attribute in 'actions' tag)")
}
if (resourceBundleBaseName != null && resourceBundleBaseName != raw.resourceBundleBaseName) {
LOG.warn("Resource bundle redefinition for plugin $id. " +
"Old value: $resourceBundleBaseName, new value: ${raw.resourceBundleBaseName}")
}
resourceBundleBaseName = raw.resourceBundleBaseName
}
if (version == null) {
version = context.defaultVersion
}
if (!isSub) {
if (context.isPluginDisabled(id)) {
markAsIncomplete(context, disabledDependency = null, shortMessage = null)
}
else {
checkCompatibility(context)
if (isIncomplete) {
return
}
for (pluginDependency in dependencies.plugins) {
if (context.isPluginDisabled(pluginDependency.id)) {
markAsIncomplete(context, pluginDependency.id, shortMessage = "plugin.loading.error.short.depends.on.disabled.plugin")
}
else if (context.result.isBroken(pluginDependency.id)) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = pluginDependency.id)
}
}
}
}
if (!isIncomplete && moduleName == null) {
processOldDependencies(descriptor = this,
context = context,
pathResolver = pathResolver,
dependencies = pluginDependencies,
dataLoader = dataLoader)
}
}
private fun processOldDependencies(descriptor: IdeaPluginDescriptorImpl,
context: DescriptorListLoadingContext,
pathResolver: PathResolver,
dependencies: List<PluginDependency>,
dataLoader: DataLoader) {
var visitedFiles: MutableList<String>? = null
for (dependency in dependencies) {
// context.isPluginIncomplete must be not checked here as another version of plugin maybe supplied later from another source
if (context.isPluginDisabled(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context, dependency.pluginId, "plugin.loading.error.short.depends.on.disabled.plugin")
}
}
else if (context.result.isBroken(dependency.pluginId)) {
if (!dependency.isOptional && !isIncomplete) {
markAsIncomplete(context = context,
disabledDependency = null,
shortMessage = "plugin.loading.error.short.depends.on.broken.plugin",
pluginId = dependency.pluginId)
}
}
// because of https://youtrack.jetbrains.com/issue/IDEA-206274, configFile maybe not only for optional dependencies
val configFile = dependency.configFile ?: continue
if (pathResolver.isFlat && context.checkOptionalConfigShortName(configFile, descriptor)) {
continue
}
var resolveError: Exception? = null
val raw: RawPluginDescriptor? = try {
pathResolver.resolvePath(readContext = context, dataLoader = dataLoader, relativePath = configFile, readInto = null)
}
catch (e: IOException) {
resolveError = e
null
}
if (raw == null) {
val message = "Plugin $descriptor misses optional descriptor $configFile"
if (context.isMissingSubDescriptorIgnored) {
LOG.info(message)
if (resolveError != null) {
LOG.debug(resolveError)
}
}
else {
throw RuntimeException(message, resolveError)
}
continue
}
if (visitedFiles == null) {
visitedFiles = context.visitedFiles
}
checkCycle(descriptor, configFile, visitedFiles)
visitedFiles.add(configFile)
val subDescriptor = descriptor.createSub(raw = raw,
descriptorPath = configFile,
pathResolver = pathResolver,
context = context,
dataLoader = dataLoader,
moduleName = null)
dependency.subDescriptor = subDescriptor
visitedFiles.clear()
}
}
private fun checkCompatibility(context: DescriptorListLoadingContext) {
if (isBundled) {
return
}
fun markAsIncompatible(error: PluginLoadingError) {
if (isIncomplete) {
return
}
isIncomplete = true
isEnabled = false
context.result.addIncompletePlugin(plugin = this, error = error)
}
if (disableNonBundledPlugins) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.custom.plugin.loading.disabled", getName()) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.custom.plugin.loading.disabled") },
isNotifyUser = false
))
return
}
PluginManagerCore.checkBuildNumberCompatibility(this, context.result.productBuildNumber.get())?.let {
markAsIncompatible(it)
return
}
// "Show broken plugins in Settings | Plugins so that users can uninstall them and resolve "Plugin Error" (IDEA-232675)"
if (context.result.isBroken(this)) {
markAsIncompatible(PluginLoadingError(
plugin = this,
detailedMessageSupplier = { CoreBundle.message("plugin.loading.error.long.marked.as.broken", name, version) },
shortMessageSupplier = { CoreBundle.message("plugin.loading.error.short.marked.as.broken") }
))
}
}
private fun markAsIncomplete(context: DescriptorListLoadingContext,
disabledDependency: PluginId?,
@PropertyKey(resourceBundle = CoreBundle.BUNDLE) shortMessage: String?,
pluginId: PluginId? = disabledDependency) {
if (isIncomplete) {
return
}
isIncomplete = true
isEnabled = false
val pluginError = if (shortMessage == null) {
null
}
else {
PluginLoadingError(plugin = this,
detailedMessageSupplier = null,
shortMessageSupplier = { CoreBundle.message(shortMessage, pluginId!!) },
isNotifyUser = false,
disabledDependency = disabledDependency)
}
context.result.addIncompletePlugin(this, pluginError)
}
@ApiStatus.Internal
fun registerExtensions(nameToPoint: Map<String, ExtensionPointImpl<*>>,
containerDescriptor: ContainerDescriptor,
listenerCallbacks: MutableList<in Runnable>?) {
containerDescriptor.extensions?.let {
if (!it.isEmpty()) {
@Suppress("JavaMapForEach")
it.forEach { name, list ->
nameToPoint.get(name)?.registerExtensions(list, this, listenerCallbacks)
}
}
return
}
val unsortedMap = epNameToExtensions ?: return
// app container: in most cases will be only app-level extensions - to reduce map copying, assume that all extensions are app-level and then filter out
// project container: rest of extensions wil be mostly project level
// module container: just use rest, area will not register unrelated extension anyway as no registered point
if (containerDescriptor == appContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
projectContainerDescriptor.extensions = Collections.emptyMap()
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else if (containerDescriptor == projectContainerDescriptor) {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
containerDescriptor.distinctExtensionPointCount = registeredCount
if (registeredCount == unsortedMap.size) {
containerDescriptor.extensions = unsortedMap
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
else if (registeredCount == (unsortedMap.size - appContainerDescriptor.distinctExtensionPointCount)) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
else {
val registeredCount = doRegisterExtensions(unsortedMap, nameToPoint, listenerCallbacks)
if (registeredCount == 0) {
moduleContainerDescriptor.extensions = Collections.emptyMap()
}
}
}
private fun doRegisterExtensions(unsortedMap: Map<String, MutableList<ExtensionDescriptor>>,
nameToPoint: Map<String, ExtensionPointImpl<*>>,
listenerCallbacks: MutableList<in Runnable>?): Int {
var registeredCount = 0
for (entry in unsortedMap) {
val point = nameToPoint.get(entry.key) ?: continue
point.registerExtensions(entry.value, this, listenerCallbacks)
registeredCount++
}
return registeredCount
}
@Suppress("HardCodedStringLiteral")
override fun getDescription(): String? {
var result = description
if (result != null) {
return result
}
result = (resourceBundleBaseName?.let { baseName ->
try {
AbstractBundle.messageOrDefault(
DynamicBundle.getResourceBundle(classLoader, baseName),
"plugin.$id.description",
descriptionChildText ?: "",
)
}
catch (_: MissingResourceException) {
LOG.info("Cannot find plugin $id resource-bundle: $baseName")
null
}
}) ?: descriptionChildText
description = result
return result
}
override fun getChangeNotes() = changeNotes
override fun getName(): String = name!!
override fun getProductCode() = productCode
override fun getReleaseDate() = releaseDate
override fun getReleaseVersion() = releaseVersion
override fun isLicenseOptional() = isLicenseOptional
override fun getOptionalDependentPluginIds(): Array<PluginId> {
val pluginDependencies = pluginDependencies
return if (pluginDependencies.isEmpty())
PluginId.EMPTY_ARRAY
else
pluginDependencies.asSequence()
.filter { it.isOptional }
.map { it.pluginId }
.toList()
.toTypedArray()
}
override fun getVendor() = vendor
override fun getVersion() = version
override fun getResourceBundleBaseName() = resourceBundleBaseName
override fun getCategory() = category
/*
This setter was explicitly defined to be able to set a category for a
descriptor outside its loading from the xml file.
Problem was that most commonly plugin authors do not publish the plugin's
category in its .xml file so to be consistent in plugins representation
(e.g. in the Plugins form) we have to set this value outside.
*/
fun setCategory(category: String?) {
this.category = category
}
val unsortedEpNameToExtensionElements: Map<String, List<ExtensionDescriptor>>
get() {
return Collections.unmodifiableMap(epNameToExtensions ?: return Collections.emptyMap())
}
override fun getVendorEmail() = vendorEmail
override fun getVendorUrl() = vendorUrl
override fun getUrl() = url
override fun getPluginId() = id
override fun getPluginClassLoader(): ClassLoader? = _pluginClassLoader
@ApiStatus.Internal
fun setPluginClassLoader(classLoader: ClassLoader?) {
_pluginClassLoader = classLoader
}
override fun isEnabled() = isEnabled
override fun setEnabled(enabled: Boolean) {
isEnabled = enabled
}
override fun getSinceBuild() = sinceBuild
override fun getUntilBuild() = untilBuild
override fun isBundled() = isBundled
override fun allowBundledUpdate() = isBundledUpdateAllowed
override fun isImplementationDetail() = implementationDetail
override fun isOnDemand() = onDemand
override fun isRequireRestart() = isRestartRequired
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is IdeaPluginDescriptorImpl) {
return false
}
return id == other.id && descriptorPath == other.descriptorPath
}
override fun hashCode(): Int {
return 31 * id.hashCode() + (descriptorPath?.hashCode() ?: 0)
}
override fun toString(): String {
return "PluginDescriptor(" +
"name=$name, " +
"id=$id, " +
(if (moduleName == null) "" else "moduleName=$moduleName, ") +
"descriptorPath=${descriptorPath ?: "plugin.xml"}, " +
"path=${pluginPathToUserString(path)}, " +
"version=$version, " +
"package=$packagePrefix, " +
"isBundled=$isBundled" +
")"
}
}
// don't expose user home in error messages
internal fun pluginPathToUserString(file: Path): String {
return file.toString().replace("${System.getProperty("user.home")}${File.separatorChar}", "~${File.separatorChar}")
}
private fun checkCycle(descriptor: IdeaPluginDescriptorImpl, configFile: String, visitedFiles: List<String>) {
var i = 0
val n = visitedFiles.size
while (i < n) {
if (configFile == visitedFiles[i]) {
val cycle = visitedFiles.subList(i, visitedFiles.size)
throw RuntimeException("Plugin $descriptor optional descriptors form a cycle: ${java.lang.String.join(", ", cycle)}")
}
i++
}
} | apache-2.0 | e86b22599ee645f7314edd7c4ac8eb0a | 37.178761 | 155 | 0.649977 | 5.293252 | false | false | false | false |
vicboma1/GameBoyEmulatorEnvironment | src/main/kotlin/utils/system/System.kt | 1 | 503 | package utils.system
/**
* Created by vicboma on 14/01/17.
*/
public fun isWindows() = getProperty().indexOf("win") >= 0
public fun isMac() = getProperty().indexOf("mac") >= 0
public fun isUnix() = getProperty().indexOf("nix") >= 0 ||
getProperty().indexOf("nux") >= 0 ||
getProperty().indexOf("aix") > 0
public fun isSolaris() = getProperty().indexOf("sunos") >= 0
private fun getProperty() = System.getProperty("os.name").toLowerCase() | lgpl-3.0 | dc6c62cefca5b3871d3f11d534039fc0 | 28.647059 | 71 | 0.588469 | 4.056452 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/kms/src/main/kotlin/com/kotlin/kms/EnableCustomerKey.kt | 1 | 1611 | // snippet-sourcedescription:[EnableCustomerKey.kt demonstrates how to enable an AWS Key Management Service (AWS KMS) key.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[AWS Key Management Service]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.kms
// snippet-start:[kms.kotlin_enable_key.import]
import aws.sdk.kotlin.services.kms.KmsClient
import aws.sdk.kotlin.services.kms.model.EnableKeyRequest
import kotlin.system.exitProcess
// snippet-end:[kms.kotlin_enable_key.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<keyId>
Where:
keyId - An AWS KMS key id value to enable (for example, xxxxxbcd-12ab-34cd-56ef-1234567890ab).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val keyId = args[0]
enableKey(keyId)
}
// snippet-start:[kms.kotlin_enable_key.main]
suspend fun enableKey(keyIdVal: String?) {
val request = EnableKeyRequest {
keyId = keyIdVal
}
KmsClient { region = "us-west-2" }.use { kmsClient ->
kmsClient.enableKey(request)
println("$keyIdVal was successfully enabled.")
}
}
// snippet-end:[kms.kotlin_enable_key.main]
| apache-2.0 | 5f51d5798df9fd9be2a27b2709722f86 | 26.767857 | 123 | 0.668529 | 3.694954 | false | false | false | false |
ediTLJ/novelty | app/src/main/java/ro/edi/novelty/data/DataManager.kt | 1 | 40676 | /*
* Copyright 2019 Eduard Scarlat
*
* 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 ro.edi.novelty.data
import android.annotation.SuppressLint
import android.app.Application
import android.text.format.DateUtils
import android.util.SparseArray
import androidx.core.text.HtmlCompat
import androidx.core.text.parseAsHtml
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.ouattararomuald.syndication.DeserializationException
import okhttp3.internal.closeQuietly
import ro.edi.novelty.data.db.AppDatabase
import ro.edi.novelty.data.db.entity.DbFeed
import ro.edi.novelty.data.db.entity.DbNews
import ro.edi.novelty.data.db.entity.DbNewsState
import ro.edi.novelty.data.remote.FeedService
import ro.edi.novelty.data.remote.HttpService
import ro.edi.novelty.model.Feed
import ro.edi.novelty.model.News
import ro.edi.novelty.model.TYPE_ATOM
import ro.edi.novelty.model.TYPE_RSS
import ro.edi.util.AppExecutors
import ro.edi.util.Singleton
import java.io.BufferedReader
import java.lang.reflect.UndeclaredThrowableException
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.chrono.IsoChronology
import java.time.format.*
import java.time.temporal.ChronoField
import timber.log.Timber.Forest.d as logd
import timber.log.Timber.Forest.e as loge
import timber.log.Timber.Forest.i as logi
import timber.log.Timber.Forest.w as logw
/**
* This class manages the underlying data.
*
* Data sources can be local (e.g. db) or remote (e.g. REST APIs).
*
* All methods should return model objects only.
*
* **Warning:**
*
* **This shouldn't expose any of the underlying data to the application layers above.**
*/
class DataManager private constructor(application: Application) {
private val db: AppDatabase by lazy { AppDatabase.getInstance(application) }
val feedsFound = MutableLiveData<List<Feed>?>()
val isFetchingArray = SparseArray<MutableLiveData<Boolean>>()
init {
feedsFound.value = null
val isFetching = MutableLiveData<Boolean>()
isFetching.value = true
isFetchingArray.put(0, isFetching)
}
companion object : Singleton<DataManager, Application>(::DataManager) {
private val REGEX_TAG_IMG =
Regex(
"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>([^<]*</img>)*",
RegexOption.IGNORE_CASE
)
private val REGEX_TAG_SMALL = Regex("<small>.*</small>", RegexOption.IGNORE_CASE)
private val REGEX_TAG_BR = Regex("<\\s*<br\\s*/?>\\s*", RegexOption.IGNORE_CASE)
// private val REGEX_BR_TAGS = Regex("(\\s*<br\\s*[/]*>\\s*){3,}", RegexOption.IGNORE_CASE)
private val REGEX_EMPTY_TAGS = Regex("(<[^>]*>\\s*</[^>]*>)+", RegexOption.IGNORE_CASE)
// manually code maps to ensure correct data always used (locale data can be changed by application code)
@SuppressLint("UseSparseArrays")
private val dow = HashMap<Long, String>().apply {
put(1L, "Mon")
put(2L, "Tue")
put(3L, "Wed")
put(4L, "Thu")
put(5L, "Fri")
put(6L, "Sat")
put(7L, "Sun")
}
@SuppressLint("UseSparseArrays")
private val moy = HashMap<Long, String>().apply {
put(1L, "Jan")
put(2L, "Feb")
put(3L, "Mar")
put(4L, "Apr")
put(5L, "May")
put(6L, "Jun")
put(7L, "Jul")
put(8L, "Aug")
put(9L, "Sep")
put(10L, "Oct")
put(11L, "Nov")
put(12L, "Dec")
}
/**
* [DateTimeFormatter.RFC_1123_DATE_TIME] with support for zone ids (e.g. PST).
*/
private val RFC_1123_DATE_TIME = DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseLenient()
.optionalStart()
.appendText(ChronoField.DAY_OF_WEEK, dow)
.appendLiteral(", ")
.optionalEnd()
.appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE)
.appendLiteral(' ')
.appendText(ChronoField.MONTH_OF_YEAR, moy)
.appendLiteral(' ')
.appendValue(ChronoField.YEAR, 4) // 2 digit year not handled
.appendLiteral(' ')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.optionalEnd()
.appendLiteral(' ')
.optionalStart()
.appendZoneText(TextStyle.SHORT) // optionally handle UT/Z/EST/EDT/CST/CDT/MST/MDT/PST/MDT
.optionalEnd()
.optionalStart()
.appendOffset("+HHMM", "GMT")
.toFormatter().withResolverStyle(ResolverStyle.SMART)
.withChronology(IsoChronology.INSTANCE)
@SuppressLint("UseSparseArrays")
private val dowRo = HashMap<Long, String>().apply {
put(1L, "Lu")
put(2L, "Ma")
put(3L, "Mi")
put(4L, "Jo")
put(5L, "Vi")
put(6L, "Sa")
put(7L, "Du")
}
@SuppressLint("UseSparseArrays")
private val moyRo = HashMap<Long, String>().apply {
put(1L, "ian")
put(2L, "feb")
put(3L, "mar")
put(4L, "apr")
put(5L, "mai")
put(6L, "iun")
put(7L, "iul")
put(8L, "aug")
put(9L, "sep")
put(10L, "oct")
put(11L, "noi")
put(12L, "dec")
}
/**
* [DateTimeFormatter.RFC_1123_DATE_TIME] with zone id set to Europe/Bucharest,
* day of month & month reversed, and day of week & months in Romanian language.
*/
private val RFC_1123_DATE_TIME_RO = DateTimeFormatterBuilder()
.parseCaseInsensitive()
.parseLenient()
.optionalStart()
.appendText(ChronoField.DAY_OF_WEEK, dowRo)
.appendLiteral(", ")
.optionalEnd()
.appendText(ChronoField.MONTH_OF_YEAR, moyRo)
.appendLiteral(' ')
.appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NOT_NEGATIVE)
.appendLiteral(' ')
.appendValue(ChronoField.YEAR, 4) // 2 digit year not handled
.appendLiteral(' ')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(ChronoField.SECOND_OF_MINUTE, 2)
.optionalEnd()
.appendLiteral(' ')
.optionalStart()
.appendLiteral("GMT")
.toFormatter().withResolverStyle(ResolverStyle.SMART)
.withChronology(IsoChronology.INSTANCE)
.withZone(ZoneId.of("Europe/Bucharest"))
}
/**
* Get available feeds at specified URL.
*
* This makes a call to get data from the server.
*/
fun findFeeds(url: String): LiveData<List<Feed>?> {
feedsFound.value = null
AppExecutors.networkIO().execute {
feedsFound.postValue(fetchFeeds(url))
}
return feedsFound
}
fun clearFoundFeeds() {
feedsFound.value = null
}
/**
* Get all feeds.
*/
fun getFeeds(): LiveData<List<Feed>> {
return db.feedDao().getFeeds()
}
/**
* Get my news (bookmarked news) for all feeds.
*/
fun getMyNews(): LiveData<List<News>> {
return db.newsDao().getMyNews()
}
/**
* Get news.
* This also triggers a call to get latest data from the server.
*
* @param feedId
* 0 => all news for my feeds
* else => news for specified feed id
*/
fun getNews(feedId: Int): LiveData<List<News>> {
refreshNews(feedId)
if (feedId == 0) {
return db.newsDao().getNews()
}
return db.newsDao().getNews(feedId)
}
/**
* Refresh news for specified feed.
*
* This makes a call to get latest data from the server.
*/
fun refreshNews(feedId: Int) {
if (feedId == 0) {
refreshNews()
return
}
if (isFetchingArray.indexOfKey(feedId) < 0) {
isFetchingArray.put(feedId, MutableLiveData())
}
AppExecutors.networkIO().execute {
val isFetching = isFetchingArray.get(feedId)
isFetching.postValue(true)
val feed = db.feedDao().getFeed(feedId)
feed?.let {
fetchNews(it.id, it.url, it.type)
}
isFetching.postValue(false)
}
}
/**
* Refresh news for my feeds only.
*
* This makes a call to get latest data from the server.
*/
private fun refreshNews() {
AppExecutors.networkIO().execute {
val isFetching = isFetchingArray.get(0)
isFetching.postValue(true)
val feeds = db.feedDao().getMyFeeds()
feeds?.let {
for (feed in it) {
fetchNews(feed.id, feed.url, feed.type)
}
}
isFetching.postValue(false)
}
}
/**
* Get info for specified news id.
*/
fun getNewsInfo(newsId: Int): LiveData<News> {
return db.newsDao().getInfo(newsId)
}
private fun updateFeedType(feedId: Int, type: Int) {
AppExecutors.diskIO().execute {
db.feedDao().updateType(feedId, type)
}
}
fun swapFeedPages(feed1: Feed, feed2: Feed) {
AppExecutors.diskIO().execute {
db.feedDao().swapPages(feed1.id, feed1.page, feed2.id, feed2.page)
}
}
fun updateFeedStarred(feed: Feed, isStarred: Boolean) {
AppExecutors.diskIO().execute {
val dbFeed =
DbFeed(
feed.id,
feed.title,
feed.url,
feed.type,
feed.page,
isStarred
)
db.feedDao().update(dbFeed)
}
}
fun updateNewsStarred(news: News, isStarred: Boolean) {
AppExecutors.diskIO().execute {
val dbNewsState =
DbNewsState(
news.id,
news.feedId,
news.isRead,
isStarred
)
db.newsStateDao().update(dbNewsState)
}
}
fun updateNewsRead(news: News, isRead: Boolean) {
AppExecutors.diskIO().execute {
val dbNewsState =
DbNewsState(
news.id,
news.feedId,
isRead,
news.isStarred
)
db.newsStateDao().update(dbNewsState)
}
}
fun insertFeed(title: String, url: String, type: Int, page: Int, isStarred: Boolean) {
AppExecutors.diskIO().execute {
val dbFeed =
DbFeed(
url.hashCode(),
title,
url,
type,
page,
isStarred
)
db.feedDao().insert(dbFeed)
}
}
fun updateFeed(feed: Feed, title: String, url: String) {
AppExecutors.diskIO().execute {
if (feed.url == url) {
val dbFeed =
DbFeed(
feed.id,
title,
feed.url,
feed.type,
feed.page,
feed.isStarred
)
db.feedDao().update(dbFeed)
return@execute
}
db.runInTransaction {
val dbFeedNew =
DbFeed(
url.hashCode(),
title,
url,
feed.type,
feed.page,
feed.isStarred
)
db.feedDao().insert(dbFeedNew)
val dbFeedOld =
DbFeed(
feed.id,
feed.title,
feed.url,
feed.type,
feed.page,
feed.isStarred
)
db.feedDao().delete(dbFeedOld)
}
}
}
fun deleteFeed(feed: Feed) {
AppExecutors.diskIO().execute {
db.feedDao().delete(feed.id)
db.runInTransaction {
val feeds = db.feedDao().getFeedsAfter(feed.page)
feeds?.let {
for (f in it) {
val dbFeed =
DbFeed(
f.id,
f.title,
f.url,
f.type,
f.page - 1,
f.isStarred
)
db.feedDao().update(dbFeed)
}
}
}
}
}
/**
* Get all available feeds at the specified URL.
*
* **Don't call this on the main UI thread!**
*/
private fun fetchFeeds(url: String): List<Feed> {
logi("fetching URL: $url")
val call = HttpService.instance.get(url)
val response = runCatching { call.execute() }.getOrElse {
loge(it, "error fetching or parsing URL")
return emptyList()
}
if (response.isSuccessful) {
val body = response.body() ?: return emptyList()
var reader: BufferedReader? = null
val feeds: ArrayList<Feed> = ArrayList()
runCatching {
val contentType = body.contentType()
if (contentType?.type.equals("text", true)
&& contentType?.subtype.equals("html", true)
) {
logi("URL seems to be an HTML page")
reader = BufferedReader(body.charStream())
var line: String? = null
var idxBody = -1
var idxLink = -1
while (true) {
if (idxLink < 0) {
line = reader?.readLine()
// logi("read line: $line")
}
line ?: break
// TODO add check for "<html "/"<html>" too?
if (idxBody < 0) {
idxBody = line.indexOf("<body ", 0, true)
if (idxBody < 0) {
idxBody = line.indexOf("<body>", 0, true)
}
}
// this won't work if link attributes are on different lines, but who does that? :)
idxLink = line.indexOf("<link ", if (idxLink < 0) 0 else idxLink, true)
if (idxLink < 0) { // no link found
if (idxBody < 0) {
// no body yet either, so keep looking for feeds
continue
} else {
// body reached, stop looking for feeds
break
}
}
if (idxBody in 0 until idxLink) {
// link after body, stop looking for feeds
break
}
idxLink += 5
val idxNextLink = line.indexOf("<link ", idxLink, true)
// if current link rel is not alternate, keep looking
var idxRelAlternate = line.indexOf(" rel=\"alternate\"", idxLink, true)
if (idxRelAlternate < 0 || idxNextLink in idxLink until idxRelAlternate) {
idxRelAlternate = line.indexOf(" rel='alternate'", idxLink, true)
if (idxRelAlternate < 0 || idxNextLink in idxLink until idxRelAlternate) {
continue
}
}
// if current link type is not rss or atom, keep looking
var idxTypeRss =
line.indexOf(" type=\"application/rss+xml\"", idxLink, true)
if (idxTypeRss < 0 || idxNextLink in idxLink until idxTypeRss) {
idxTypeRss = line.indexOf(" type='application/rss+xml'", idxLink, true)
if (idxTypeRss < 0 || idxNextLink in idxLink until idxTypeRss) {
var idxTypeAtom =
line.indexOf(" type=\"application/atom+xml\"", idxLink, true)
if (idxTypeAtom < 0 || idxNextLink in idxLink until idxTypeAtom) {
idxTypeAtom =
line.indexOf(" type='application/atom+xml'", idxLink, true)
if (idxTypeAtom < 0 || idxNextLink in idxLink until idxTypeAtom) {
continue
}
}
}
}
var quote = '\"'
var idxHref = line.indexOf(" href=\"", idxLink, true)
if (idxHref < 0 || idxNextLink in idxLink until idxHref) {
quote = '\''
idxHref = line.indexOf(" href='", idxLink, true)
if (idxHref < 0 || idxNextLink in idxLink until idxHref) {
continue
}
}
var href = line.substring(idxHref + 7, line.indexOf(quote, idxHref + 9))
.trim { it <= ' ' }
.parseAsHtml(HtmlCompat.FROM_HTML_MODE_COMPACT, null, null).toString()
if (href.startsWith("/")) {
href = url + href
} else if (!href.startsWith("http://", true)
&& !href.startsWith("https://", true)
) {
href = "$url/$href"
}
var hasTitle = true
quote = '\"'
var idxTitle = line.indexOf(" title=\"", idxLink, true)
if (idxTitle < 0 || idxNextLink in idxLink until idxTitle) {
quote = '\''
idxTitle = line.indexOf(" title='", idxLink, true)
if (idxTitle < 0 || idxNextLink in idxLink until idxTitle) {
hasTitle = false
}
}
val title = if (hasTitle) {
line.substring(idxTitle + 8, line.indexOf(quote, idxTitle + 8))
.trim { it <= ' ' }
.parseAsHtml(HtmlCompat.FROM_HTML_MODE_COMPACT, null, null)
.toString()
} else {
""
}
logi("found feed: $title - $href")
feeds.add(Feed(href.hashCode(), title, href, 0, 0, false))
continue
}
reader?.closeQuietly()
body.closeQuietly()
if (feeds.isEmpty()) {
// apparently some feeds have text/html content type :|
logi("URL seems to be a feed after all: $url")
val feedCall = HttpService.instance.get(url)
val feedResponse = runCatching { feedCall.execute() }.getOrNull()
if (feedResponse?.isSuccessful == true) {
val feedBody = feedResponse.body() ?: return emptyList()
var feedReader: BufferedReader? = null
runCatching {
feedReader = BufferedReader(feedBody.charStream())
var feedType = 0
while (true) {
val feedLine = feedReader?.readLine() ?: break
// logi("read line: $line")
val idxRss = feedLine.indexOf("<rss ", 0, true)
if (idxRss < 0) {
val idxFeed = feedLine.indexOf("<feed ", 0, true)
if (idxFeed < 0) {
continue
} else {
feedType = TYPE_ATOM
break
}
} else {
feedType = TYPE_RSS
break
}
}
if (feedType > 0) {
feeds.add(Feed(url.hashCode(), "", url, feedType, 0, false))
} else {
logi("no feeds found!")
}
}.getOrElse {
loge(it)
feedReader?.closeQuietly()
feedBody.closeQuietly()
}
} else {
loge("error fetching URL: $url")
loge(
"error fetching URL [%d]: %s",
feedResponse?.code(),
feedResponse?.errorBody()
)
}
} else {
logi("found ${feeds.size} feeds...")
for (feed in feeds) {
logi("fetching feed URL: ${feed.url}")
val feedCall = HttpService.instance.get(feed.url)
val feedResponse = runCatching { feedCall.execute() }.getOrNull()
if (feedResponse?.isSuccessful == true) {
val feedBody = feedResponse.body() ?: continue
var feedReader: BufferedReader? = null
// TODO remove feeds with invalid URL or unknown type
runCatching {
feedReader = BufferedReader(feedBody.charStream())
logi("feed URL is valid: ${feed.url}")
while (true) {
val feedLine = feedReader?.readLine() ?: break
// logi("read line: $line")
val idxRss = feedLine.indexOf("<rss ", 0, true)
if (idxRss < 0) {
val idxFeed = feedLine.indexOf("<feed ", 0, true)
if (idxFeed < 0) {
continue
} else {
feed.type = TYPE_ATOM
break
}
} else {
feed.type = TYPE_RSS
break
}
}
feedReader?.closeQuietly()
feedBody.closeQuietly()
}.getOrElse {
loge(it)
feedReader?.closeQuietly()
feedBody.closeQuietly()
}
} else {
loge("error fetching feed URL: ${feed.url}")
loge(
"error fetching feed URL [%d]: %s",
feedResponse?.code(),
feedResponse?.errorBody()
)
}
}
}
} else {
reader = BufferedReader(body.charStream())
logi("URL seems to be a feed: $url")
var type = 0
while (true) {
val line = reader?.readLine() ?: break
// logi("read line: $line")
val idxRss = line.indexOf("<rss ", 0, true)
if (idxRss < 0) {
val idxFeed = line.indexOf("<feed ", 0, true)
if (idxFeed < 0) {
continue
} else {
type = TYPE_ATOM
break
}
} else {
type = TYPE_RSS
break
}
}
feeds.add(Feed(url.hashCode(), "", url, type, 0, false))
}
reader?.closeQuietly()
body.closeQuietly()
return feeds
}.getOrElse {
loge(it)
reader?.closeQuietly()
body.closeQuietly()
return emptyList()
}
} else {
// ignore error
loge("error fetching URL [%d]: %s", response.code(), response.errorBody())
return emptyList()
}
}
/**
* Get all news from the specified feed URL.
*
* **Don't call this on the main UI thread!**
*/
private fun fetchNews(feedId: Int, feedUrl: String, feedType: Int) {
when (feedType) {
TYPE_ATOM -> fetchAtomNews(feedId, feedUrl)
TYPE_RSS -> fetchRssNews(feedId, feedUrl)
else -> when (fetchRssNews(feedId, feedUrl)) {
TYPE_ATOM -> {
if (fetchAtomNews(feedId, feedUrl)) {
updateFeedType(feedId, TYPE_ATOM)
}
}
TYPE_RSS -> updateFeedType(feedId, TYPE_RSS)
}
}
}
/**
* Get all news from the specified Atom feed URL.
*
* **Don't call this on the main UI thread!**
*
* @return true if successful, false if error
*/
private fun fetchAtomNews(feedId: Int, feedUrl: String): Boolean {
logi("fetching Atom feed: $feedUrl")
val atomFeed = runCatching {
FeedService(feedUrl).getReader().readAtom()
}.getOrElse {
if (it.cause == DeserializationException::class) {
logw(it, "error deserializing Atom feed")
} else {
loge(it, "error fetching or parsing feed")
}
// isFetching.postValue(false)
return false
}
val news = atomFeed.items
news ?: return false
val now = Instant.now().toEpochMilli()
val dbNews = ArrayList<DbNews>(news.size)
val dbNewsState = ArrayList<DbNewsState>(news.size)
for (item in news) {
var link: String?
if (item.links.isNullOrEmpty()) {
link = null
} else {
if (item.links.size == 1) {
val l = item.links.first()
link = l.href ?: l.value
} else {
link = null
for (l in item.links) {
if (l.rel == null) {
link = l.href ?: l.value
} else if (l.rel == "alternate") {
link = l.href ?: l.value
break
}
}
}
}
if (item.content == null && link == null) {
// no content and no links... skip this entry
continue
}
// logd("item: $item")
val id = item.id.plus(feedId).hashCode()
val title = item.title.trim { it <= ' ' }
.parseAsHtml(HtmlCompat.FROM_HTML_MODE_COMPACT, null, null).toString()
val updDate = runCatching {
// logi("published: ${item.updatedDate}")
ZonedDateTime.parse(
item.updatedDate,
DateTimeFormatter.ISO_DATE_TIME
).toEpochSecond() * 1000
}.getOrElse {
logi(it, "updated date parsing error... fallback to now()")
now
}
val pubDate = if (item.pubDate == null) {
updDate
} else {
runCatching {
// logi("published: ${item.pubDate}")
ZonedDateTime.parse(
item.pubDate,
DateTimeFormatter.ISO_DATE_TIME
).toEpochSecond() * 1000
}.getOrElse {
logi(it, "published date parsing error... fallback to now()")
now
}
}
val author: StringBuilder?
if (item.authors.isNullOrEmpty()) {
author = null
} else {
author = StringBuilder(16)
for (a in item.authors) {
author.append(a.name)
author.append(',')
author.append(' ')
}
author.deleteCharAt(author.length - 1)
author.deleteCharAt(author.length - 1)
}
dbNews.add(
DbNews(
id,
feedId,
title,
cleanHtml(
item.content ?: link?.let {
"<a href=\"$it\">$it</a>"
} ?: ""
), // we.ll never reach the "" part (the Kotlin compiler seems to be blind)
author?.toString(),
pubDate,
updDate,
link
)
)
dbNewsState.add(
DbNewsState(
id,
feedId
)
)
}
db.runInTransaction {
db.newsDao().replace(dbNews)
db.newsStateDao().insert(dbNewsState)
db.newsDao()
.deleteOlder(feedId, Instant.now().toEpochMilli() - DateUtils.WEEK_IN_MILLIS)
db.newsDao().deleteAllButLatest(feedId, 100)
}
// isFetching.postValue(false)
return true
}
/**
* Get all news from the specified RSS feed URL.
*
* **Don't call this on the main UI thread!**
*
* @return feed type or 0, if error
*/
private fun fetchRssNews(feedId: Int, feedUrl: String): Int {
logi("fetching RSS feed: $feedUrl")
val rssFeed = runCatching {
FeedService(feedUrl).getReader().readRss()
}.getOrElse {
return if (it is UndeclaredThrowableException && it.undeclaredThrowable is DeserializationException) {
loge(it, "error deserializing RSS feed")
// isFetching.postValue(false)
TYPE_ATOM
} else {
loge(it, "error fetching or parsing feed")
// isFetching.postValue(false)
0
}
}
val news = rssFeed.channel.items
news ?: return 0
val channelDate = rssFeed.channel.updatedDate ?: rssFeed.channel.pubDate
val now = Instant.now().toEpochMilli()
// logd("feed channel: ${rssFeed.channel}")
val feedUpdDate = runCatching {
// Tue, 3 Jun 2008 11:05:30 GMT
// logi("feed updated: $channelDate")
ZonedDateTime.parse(channelDate, RFC_1123_DATE_TIME).toEpochSecond() * 1000
}.getOrElse {
runCatching {
// 2022-02-18T14:37:00+02:00
// logw("feed date parsing error... fallback to ISO date-time")
// logi("feed updated: $channelDate")
ZonedDateTime.parse(channelDate, DateTimeFormatter.ISO_DATE_TIME)
.toEpochSecond() * 1000
}.getOrElse {
if (feedUrl.startsWith("https://www.hotnews.ro")
|| feedUrl.startsWith("http://www.hotnews.ro")
) {
// special case for hotnews.ro... because why not :|
runCatching {
// Lu, feb 14 2022 22:32:30 GMT
// logw("feed date parsing error... fallback to 'almost' RFC 1123")
// logi("feed updated: $channelDate")
ZonedDateTime.parse(channelDate, RFC_1123_DATE_TIME_RO)
.toEpochSecond() * 1000
}.getOrElse {
logw(it, "feed date parsing error... fallback to now()")
now
}
} else {
logw(it, "feed date parsing error... fallback to now()")
now
}
}
}
val dbNews = ArrayList<DbNews>(news.size)
val dbNewsState = ArrayList<DbNewsState>(news.size)
for (item in news) {
item.title ?: continue
item.description ?: continue
logd("item: $item")
val id = (item.id ?: (item.link ?: item.title)).plus(feedId).hashCode()
val title = item.title.trim { it <= ' ' }
.parseAsHtml(HtmlCompat.FROM_HTML_MODE_COMPACT, null, null).toString()
val pubDate = if (item.pubDate == null) {
feedUpdDate
} else {
runCatching {
// Tue, 3 Jun 2008 11:05:30 GMT
// logi("published: ${item.pubDate}")
ZonedDateTime.parse(item.pubDate, RFC_1123_DATE_TIME).toEpochSecond() * 1000
}.getOrElse {
runCatching {
// 2022-02-18T14:37:00+02:00
// logw("published date parsing error... fallback to ISO date-time")
// logi("published: ${item.pubDate}")
ZonedDateTime.parse(item.pubDate, DateTimeFormatter.ISO_DATE_TIME)
.toEpochSecond() * 1000
}.getOrElse {
if (feedUrl.startsWith("https://www.hotnews.ro")
|| feedUrl.startsWith("http://www.hotnews.ro")
) {
// special case for hotnews.ro... because why not :|
runCatching {
// Lu, feb 14 2022 20:22:00 GMT
// logw("published date parsing error... fallback to 'almost' RFC 1123")
// logi("published: ${item.pubDate}")
ZonedDateTime.parse(item.pubDate, RFC_1123_DATE_TIME_RO)
.toEpochSecond() * 1000
}.getOrElse {
logw(it, "published date parsing error... fallback to now()")
now
}
} else {
logw(it, "feed date parsing error... fallback to now()")
now
}
}
}
}
dbNews.add(
DbNews(
id,
feedId,
title,
cleanHtml(item.description),
item.author,
pubDate,
feedUpdDate,
item.link
)
)
dbNewsState.add(
DbNewsState(
id,
feedId
)
)
}
logi("db items to add: ${dbNews.size}")
db.runInTransaction {
db.newsDao().replace(dbNews)
db.newsStateDao().insert(dbNewsState)
db.newsDao()
.deleteOlder(feedId, Instant.now().toEpochMilli() - DateUtils.WEEK_IN_MILLIS)
db.newsDao().deleteAllButLatest(feedId, 100)
}
// isFetching.postValue(false)
return TYPE_RSS
}
private fun cleanHtml(html: String): String {
var txt = html.replace(REGEX_TAG_IMG, "")
txt = txt.replace(REGEX_TAG_SMALL, "")
txt = txt.replace(REGEX_EMPTY_TAGS, "")
txt = txt.replace(REGEX_TAG_BR, "\n")
txt = txt.replace("\r\n", "\n", true)
txt = txt.trim { it <= ' ' }
val len = txt.length
val sb = StringBuilder(len)
for (i in 0 until len) {
val c = txt[i]
if (i < 2) {
sb.append(c)
continue
}
if (c != '\n') {
sb.append(c)
continue
} // else: we've reached a \n
if (c != txt[i - 1]) {
if (i < 4
|| txt[i - 1] != '>'
|| txt[i - 2] != 'p'
|| txt[i - 2] != 'P'
|| txt[i - 3] != '/'
|| txt[i - 4] != '<'
) {
if (i > len - 4
|| txt[i + 1] != '<'
|| txt[i + 2] != 'p'
|| txt[i + 2] != 'P'
|| txt[i + 3] != '>'
) {
sb.append('<')
sb.append('b')
sb.append('r')
sb.append('>')
} // else skip \n if it's before <p>
} // else skip \n if it's after </p>
continue
}
// else: we've reached a 2nd consecutive \n
if (c != txt[i - 2]) {
sb.append('<')
sb.append('b')
sb.append('r')
sb.append('>')
} // else: we've reached the 3rd consecutive \n
// skip the 3rd consecutive \n
}
sb.append('<')
sb.append('b')
sb.append('r')
sb.append('>')
return sb.toString()
}
} | apache-2.0 | c01667ed801aa8cabf33e6dae0665286 | 34.807218 | 114 | 0.426886 | 5.124213 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/sts/src/main/kotlin/com/kotlin/sts/GetAccessKeyInfo.kt | 1 | 1903 | // snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
// snippet-sourcedescription:[GetAccessKeyInfo.kt demonstrates how to return the account identifier for the specified access key ID by using AWS Security Token Service (AWS STS).]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[AWS Security Token Service (AWS STS)]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.sts
// snippet-start:[sts.kotlin.get_access_key.import]
import aws.sdk.kotlin.services.sts.StsClient
import aws.sdk.kotlin.services.sts.model.GetAccessKeyInfoRequest
import kotlin.system.exitProcess
// snippet-end:[sts.kotlin.get_access_key.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
accessKeyId>
Where:
accessKeyId - The identifier of an access key (for example, XXXXX3JWY3BXW7POHDLA).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val accessKeyId = args[0]
getKeyInfo(accessKeyId)
}
// snippet-start:[sts.kotlin.get_access_key.main]
suspend fun getKeyInfo(accessKeyIdVal: String?) {
val accessRequest = GetAccessKeyInfoRequest {
accessKeyId = accessKeyIdVal
}
StsClient { region = "us-east-1" }.use { stsClient ->
val accessResponse = stsClient.getAccessKeyInfo(accessRequest)
println("The account associated with the access key is ${accessResponse.account}")
}
}
// snippet-end:[sts.kotlin.get_access_key.main]
| apache-2.0 | 5fe41e2404a1b2cacc0f77676dfa2a21 | 31.385965 | 179 | 0.693642 | 3.798403 | false | false | false | false |
pijpijpij/LottieShow | business/src/main/java/com/pij/lottieshow/detail/LottieViewModel.kt | 1 | 1751 | package com.pij.lottieshow.detail
import com.pij.lottieshow.interactor.LottieSink
import com.pij.lottieshow.interactor.Serializer
import com.pij.lottieshow.model.LottieFile
import rx.Observable
import rx.Observable.empty
import rx.Observable.merge
import rx.subjects.PublishSubject
class LottieViewModel(private val sink: LottieSink, private val serializer: Serializer) {
private val lottieToLoad = PublishSubject.create<LottieFile>()
private val lottieToAdd = PublishSubject.create<LottieFile>()
private val errors = PublishSubject.create<Throwable>()
private val lottieToShow: Observable<LottieFile>
private val animationToShow: Observable<String>
init {
val addedLottie = lottieToAdd.flatMap {
Observable.just(it)
.doOnNext { sink.add(it) }
.doOnError { errors.onNext(it) }
.onErrorResumeNext(empty())
}
val loadedLottie = lottieToLoad
lottieToShow = merge(loadedLottie, addedLottie)
animationToShow = lottieToShow.map { it?.id }
.concatMap {
serializer.open(it)
.toObservable()
.doOnError { errors.onNext(it) }
.onErrorResumeNext(empty())
}
}
fun loadLottie(newFile: LottieFile?) {
lottieToLoad.onNext(newFile)
}
fun showAnimation(): Observable<String> {
return animationToShow
}
fun showLoadingError(): Observable<Throwable> {
return errors
}
fun addLottie(newFile: LottieFile) {
lottieToAdd.onNext(newFile)
}
fun showLottie(): Observable<LottieFile> {
return lottieToShow
}
}
| apache-2.0 | 26a3dd003d5db05e76efec32ba09e2b0 | 28.183333 | 89 | 0.632781 | 4.669333 | false | false | false | false |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/CloseProjectWindowHelper.kt | 1 | 2643 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl
import com.intellij.configurationStore.runInSaveOnFrameDeactivationDisabledMode
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.GeneralSettings
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.util.SystemProperties
open class CloseProjectWindowHelper {
protected open val isMacSystemMenu: Boolean
get() = SystemProperties.getBooleanProperty("idea.test.isMacSystemMenu", SystemInfo.isMacSystemMenu)
private val isShowWelcomeScreen: Boolean
get() = isMacSystemMenu && isShowWelcomeScreenFromSettings
protected open val isShowWelcomeScreenFromSettings
get() = GeneralSettings.getInstance().isShowWelcomeScreen
fun windowClosing(project: Project?) {
val numberOfOpenedProjects = getNumberOfOpenedProjects()
// Exit on Linux and Windows if the only opened project frame is closed.
// On macOS behaviour is different - to exit app, quit action should be used, otherwise welcome frame is shown.
// If welcome screen is disabled, behaviour on all OS is the same.
if (numberOfOpenedProjects > 1 || (numberOfOpenedProjects == 1 && isShowWelcomeScreen)) {
closeProjectAndShowWelcomeFrameIfNoProjectOpened(project)
}
else {
quitApp()
}
}
protected open fun getNumberOfOpenedProjects() = ProjectManager.getInstance().openProjects.size
protected open fun closeProjectAndShowWelcomeFrameIfNoProjectOpened(project: Project?) {
runInSaveOnFrameDeactivationDisabledMode {
if (project != null && project.isOpen) {
ProjectManagerEx.getInstanceEx().closeAndDispose(project)
}
val app = ApplicationManager.getApplication()
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectFrameClosed()
// app must be not saved as part of project closing because app settings maybe modified as result - e.g. RecentProjectsManager state
SaveAndSyncHandler.getInstance().saveSettingsUnderModalProgress(app)
}
WelcomeFrame.showIfNoProjectOpened()
}
protected open fun quitApp() {
ApplicationManagerEx.getApplicationEx().exit()
}
} | apache-2.0 | 20657aa0b70fa0fb5fc8297b834c3505 | 43.066667 | 140 | 0.790011 | 5.275449 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/identification/TranslationIdentifier.kt | 1 | 3764 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.identification
import com.demonwav.mcdev.translations.identification.TranslationInstance.Companion.FormattingError
import com.demonwav.mcdev.translations.index.TranslationIndex
import com.demonwav.mcdev.translations.index.merge
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiCallExpression
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiExpressionList
import java.util.MissingFormatArgumentException
abstract class TranslationIdentifier<T : PsiElement> {
@Suppress("UNCHECKED_CAST")
fun identifyUnsafe(element: PsiElement): TranslationInstance? {
return identify(element as T)
}
abstract fun identify(element: T): TranslationInstance?
abstract fun elementClass(): Class<T>
companion object {
val INSTANCES = listOf(LiteralTranslationIdentifier(), ReferenceTranslationIdentifier())
fun identify(
project: Project,
element: PsiExpression,
container: PsiElement,
referenceElement: PsiElement
): TranslationInstance? {
if (container is PsiExpressionList && container.parent is PsiCallExpression) {
val call = container.parent as PsiCallExpression
val index = container.expressions.indexOf(element)
for (function in TranslationInstance.translationFunctions) {
if (function.matches(call, index)) {
val translationKey = function.getTranslationKey(call, referenceElement) ?: continue
val entries = TranslationIndex.getAllDefaultEntries(project).merge("")
val translation = entries[translationKey.full]?.text
if (translation != null) {
try {
val (formatted, superfluousParams) = function.format(translation, call)
?: (translation to -1)
return TranslationInstance(
if (function.foldParameters) container else call,
function.matchedIndex,
referenceElement,
translationKey,
formatted,
if (superfluousParams >= 0) FormattingError.SUPERFLUOUS else null,
superfluousParams
)
} catch (ignored: MissingFormatArgumentException) {
return TranslationInstance(
if (function.foldParameters) container else call,
function.matchedIndex,
referenceElement,
translationKey,
translation,
FormattingError.MISSING
)
}
} else {
return TranslationInstance(
null,
function.matchedIndex,
referenceElement,
translationKey,
null
)
}
}
}
return null
}
return null
}
}
}
| mit | d8428aa89aeec3dc139de55b595e5e35 | 40.822222 | 107 | 0.514612 | 6.709447 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/diagram/PumlCode.kt | 2 | 2418 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.causeway.client.kroviz.ui.diagram
class PumlCode() {
private val NL = "\n"
var code = ""
fun add(s: String): PumlCode {
code += s
return this
}
fun addLine(s: String): PumlCode {
code += s + NL
return this
}
fun addStereotype(s: String): PumlCode {
var result = "<<$s>>"
result = italic(result)
result = center(result)
code += result + NL
return this
}
fun addLink(url: String, title: String): PumlCode {
var result = "[[$url $title]]"
result = bold(result)
code += result + NL
return this
}
fun addClass(s: String): PumlCode {
val result = underline("(C) $s")
code += result + NL
return this
}
fun toMindmap(): PumlCode {
code += "@startmindmap$NL$code@endmindmap$NL"
return this
}
fun toMindmapNode(level:Int): PumlCode {
val depth = "*".repeat(level)
code = "$depth:$code;$NL"
return this
}
private fun center(s: String): String {
return "..$s.."
}
private fun italic(s: String): String {
return "//$s//"
}
private fun bold(s: String): String {
return "**$s**"
}
private fun underline(s: String): String {
return "__" + s + "__"
}
fun addHorizontalLine(): PumlCode {
code += "----$NL"
return this
}
fun trim(): PumlCode {
if (code.endsWith(NL)) {
code = code.dropLast(1)
}
return this
}
}
| apache-2.0 | cdf0c15bb80851afc55e819770d1f4ba | 23.927835 | 64 | 0.583127 | 3.88746 | false | false | false | false |
luca020400/android_packages_apps_CMChangelog | app/src/main/java/org/cyanogenmod/changelog/ChangelogActivity.kt | 1 | 7135 | /*
* Copyright (c) 2016 The CyanogenMod Project.
*
* 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 org.cyanogenmod.changelog
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.os.AsyncTask
import android.os.Bundle
import android.support.annotation.UiThread
import android.support.annotation.WorkerThread
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.main.*
import java.io.*
import java.util.*
class ChangelogActivity : Activity(), SwipeRefreshLayout.OnRefreshListener {
private val TAG = "ChangelogActivity"
/**
* Adapter for the RecyclerView.
*/
private val mChangelogAdapter by lazy {
ChangelogAdapter()
}
/**
* Dialog showing info about the device.
*/
private var mInfoDialog: Dialog? = null
/**
* Changelog to show
*/
private var changelog = Changelog(Device.LINEAGE_BRANCH)
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main)
/* Setup and create Views */
init()
/* Populate RecyclerView with cached data */
bindCache()
/* Fetch data */
updateChangelog()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.actions, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_device_info -> mInfoDialog!!.show()
R.id.menu_refresh -> if (!swipe_refresh.isRefreshing) updateChangelog()
}
return true
}
override fun onRefresh() {
updateChangelog()
}
/**
* Utility method.
*/
private fun init() {
// Setup refresh listener which triggers new data loading
swipe_refresh.setOnRefreshListener(this)
// Color scheme of the refresh spinner
swipe_refresh.setColorSchemeResources(
R.color.color_primary_dark, R.color.color_accent)
// Setup RecyclerView
recycler_view.setHasFixedSize(true)
val linearLayoutManager = LinearLayoutManager(this)
recycler_view.layoutManager = linearLayoutManager
// Setup divider for RecyclerView items
recycler_view.addItemDecoration(DividerItemDecoration(
recycler_view.context, linearLayoutManager.orientation))
// Setup item animator
recycler_view.itemAnimator = null // Disable to prevent view blinking when refreshing
// Setup and initialize RecyclerView adapter
recycler_view.adapter = mChangelogAdapter
// Setup and initialize info dialog
val message = String.format(Locale.getDefault(), "%s %s\n\n%s %s\n\n%s %s\n\n%s %s",
getString(R.string.dialog_device_name), Device.DEVICE,
getString(R.string.dialog_version), Device.LINEAGE_VERSION,
getString(R.string.dialog_build_date), Device.BUILD_DATE,
getString(R.string.dialog_update_channel), Device.LINEAGE_RELEASE_CHANNEL)
val infoDialog = layoutInflater.inflate(R.layout.info_dialog, recycler_view, false)
val builder = AlertDialog.Builder(this, R.style.Theme_InfoDialog)
.setView(infoDialog)
.setPositiveButton(R.string.dialog_ok, null)
val dialogMessage = infoDialog.findViewById<TextView>(R.id.info_dialog_message)
dialogMessage.text = message
mInfoDialog = builder.create()
}
/**
* Update Changelog
*/
private fun updateChangelog() {
Log.i(TAG, "Updating Changelog")
if (!Device.isConnected(this)) {
Log.w(TAG, "Missing network connection")
Toast.makeText(this, R.string.data_connection_required, Toast.LENGTH_SHORT).show()
swipe_refresh.isRefreshing = false
return
}
ChangelogTask().execute()
}
/**
* Read cached data and bind it to the RecyclerView.
*/
private fun bindCache() {
try {
val fileInputStream = FileInputStream(File(cacheDir, "cache"))
val objectInputStream = ObjectInputStream(fileInputStream)
val cachedData = arrayListOf<Change>()
while (true) {
val temp = objectInputStream.readObject() as Change? ?: break
cachedData.add(temp)
}
objectInputStream.close()
changelog.changes = cachedData
mChangelogAdapter.clear()
mChangelogAdapter.addAll(changelog.changes)
Log.d(TAG, "Restored cache")
} catch (e: FileNotFoundException) {
Log.w(TAG, "Cache not found.")
} catch (e: EOFException) {
Log.e(TAG, "Error while reading cache! (EOF) ")
} catch (e: StreamCorruptedException) {
Log.e(TAG, "Corrupted cache!")
} catch (e: IOException) {
Log.e(TAG, "Error while reading cache!")
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
}
private inner class ChangelogTask : AsyncTask<Void, Void, Boolean>() {
@UiThread
override fun onPreExecute() {
/* Start refreshing circle animation.
* Wrap in runnable to workaround SwipeRefreshLayout bug.
* View: https://code.google.com/p/android/issues/detail?id=77712
*/
swipe_refresh.post { swipe_refresh.isRefreshing = true }
}
@WorkerThread
override fun doInBackground(vararg voids: Void): Boolean {
return changelog.update(100)
}
@UiThread
override fun onPostExecute(isUpdated: Boolean) {
if (isUpdated) {
mChangelogAdapter.clear()
mChangelogAdapter.addAll(changelog.changes)
// Update cache
CacheChangelogTask(cacheDir).execute(changelog.changes)
} else {
Log.d(TAG, "Nothing changed")
}
// Stop refreshing circle animation.
swipe_refresh.post { swipe_refresh.isRefreshing = false }
}
}
}
| gpl-3.0 | bd14f95d8ff92bc1f35cb3b28f6bfa38 | 35.035354 | 96 | 0.639944 | 4.703362 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2021/Day16.kt | 1 | 2673 | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
import com.nibado.projects.advent.collect.StringTokenizer
object Day16 : Day {
private val binary = resourceString(2021, 16).trim().chunked(2)
.map { it.toUByte(16).toString(2).padStart(8, '0') }.joinToString("")
private val tree: Packet by lazy { parse(StringTokenizer(binary)) }
private fun parse(tok: StringTokenizer, packet: Packet? = null) : Packet {
val version = tok.take(3).toInt(2)
val type = tok.take(3).toInt(2).let { PacketType.values()[it] }
var current = packet
if(type == PacketType.LIT) {
var number = ""
do {
val v = tok.take(5)
number += v.substring(1)
} while(v.first() == '1')
val lit = Packet(version, type, number.toLong(2))
if(current == null) {
current = lit
} else {
current.sub += lit
}
} else {
val new = Packet(version, type)
if(current != null) {
current.sub += new
}
current = new
val lenId = tok.take(1).toInt(2)
val length = tok.take(if(lenId == 0) 15 else 11).toInt(2)
if(lenId == 0) {
val readStart = tok.read
while(tok.read - readStart < length) {
parse(tok, current)
}
} else {
repeat(length) {
parse(tok, current)
}
}
}
return current
}
data class Packet(val version: Int, val type: PacketType, val value: Long? = null, val sub: MutableList<Packet> = mutableListOf()) {
val versionSum: Int
get() = version + sub.sumOf { it.versionSum }
fun eval() : Long = when(type) {
PacketType.LIT -> value!!
PacketType.SUM -> sub.sumOf { it.eval() }
PacketType.PROD -> sub.fold(1L) { acc, n -> acc * n.eval() }
PacketType.MIN -> sub.minOf { it.eval() }
PacketType.MAX -> sub.maxOf { it.eval() }
PacketType.GT -> sub.let { (a, b) -> if(a.eval() > b.eval()) 1 else 0 }
PacketType.LT -> sub.let { (a, b) -> if(a.eval() < b.eval()) 1 else 0 }
PacketType.EQ -> sub.let { (a, b) -> if(a.eval() == b.eval()) 1 else 0 }
}
}
enum class PacketType {
SUM,
PROD,
MIN,
MAX,
LIT,
GT,
LT,
EQ
}
override fun part1() : Int = tree.versionSum
override fun part2() : Long = tree.eval()
} | mit | 15b3a6face8b847315f5f9d8c0312092 | 32.425 | 136 | 0.48859 | 3.829513 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/IdeaKotlinDependenciesContainer.kt | 1 | 2932 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling
import org.jetbrains.kotlin.gradle.idea.proto.tcs.IdeaKotlinDependency
import org.jetbrains.kotlin.gradle.idea.serialize.IdeaKotlinSerializationContext
import org.jetbrains.kotlin.gradle.idea.tcs.IdeaKotlinDependency
import java.io.Serializable
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
sealed interface IdeaKotlinDependenciesContainer : Serializable {
operator fun get(sourceSetName: String): Set<IdeaKotlinDependency>
}
private data class IdeaKotlinDeserializedDependenciesContainer(
private val dependencies: Map<String, Set<IdeaKotlinDependency>>
) : IdeaKotlinDependenciesContainer {
override fun get(sourceSetName: String): Set<IdeaKotlinDependency> {
return dependencies[sourceSetName].orEmpty()
}
}
class IdeaKotlinSerializedDependenciesContainer(
dependencies: Map<String, List<ByteArray>>
) : IdeaKotlinDependenciesContainer {
private val readWriteLock = ReentrantReadWriteLock()
private var serializedDependencies: Map<String, List<ByteArray>>? = dependencies
private var deserializedDependencies: IdeaKotlinDependenciesContainer? = null
val isDeserialized: Boolean get() = readWriteLock.read { deserializedDependencies != null }
override fun get(sourceSetName: String): Set<IdeaKotlinDependency> = readWriteLock.read {
val deserializedDependencies = this.deserializedDependencies
if (deserializedDependencies == null) {
throw NotDeserializedException("${IdeaKotlinDependenciesContainer::class.simpleName} not deserialized yet")
}
deserializedDependencies[sourceSetName]
}
fun deserialize(context: IdeaKotlinSerializationContext): Unit = readWriteLock.write {
val serializedDependencies = this.serializedDependencies
if (serializedDependencies == null) {
context.logger.warn("${IdeaKotlinDependenciesContainer::class.java.name} already serialized")
return@write
}
val deserialized = serializedDependencies.mapNotNull { (sourceSetName, dependencies) ->
val deserializedDependencies = dependencies.mapNotNull { dependency ->
context.IdeaKotlinDependency(dependency)
}
sourceSetName to deserializedDependencies.toSet()
}.toMap()
this.deserializedDependencies = IdeaKotlinDeserializedDependenciesContainer(deserialized)
}
fun deserializeIfNecessary(context: IdeaKotlinSerializationContext) {
if (isDeserialized) return
readWriteLock.write {
if (isDeserialized) return
deserialize(context)
}
}
class NotDeserializedException(message: String) : IllegalStateException(message)
}
| apache-2.0 | e10a3431c7d82dc9fe7fb5b83fb3043f | 39.722222 | 120 | 0.754093 | 5.282883 | false | false | false | false |
JetBrains/intellij-community | plugins/settings-sync/src/com/intellij/settingsSync/SettingsSyncBridge.kt | 1 | 15518 | package com.intellij.settingsSync
import com.intellij.codeInsight.template.impl.TemplateSettings
import com.intellij.configurationStore.saveSettings
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.runBlockingMaybeCancellable
import com.intellij.settingsSync.SettingsSyncBridge.PushRequestMode.*
import com.intellij.util.Alarm
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import org.jetbrains.annotations.VisibleForTesting
import java.nio.file.Path
import java.time.Instant
import java.util.concurrent.TimeUnit
/**
* Handles events about settings change both from the current IDE, and from the server, merges the settings, logs them,
* and provides the combined data to clients: both to the IDE and to the server.
*/
@ApiStatus.Internal
class SettingsSyncBridge(parentDisposable: Disposable,
private val appConfigPath: Path,
private val settingsLog: SettingsLog,
private val ideMediator: SettingsSyncIdeMediator,
private val remoteCommunicator: SettingsSyncRemoteCommunicator,
private val updateChecker: SettingsSyncUpdateChecker) {
private val pendingEvents = ContainerUtil.createConcurrentList<SyncSettingsEvent>()
private val queue = MergingUpdateQueue("SettingsSyncBridge", 1000, false, null, parentDisposable, null,
Alarm.ThreadToUse.POOLED_THREAD).apply {
setRestartTimerOnAdd(true)
}
private val updateObject = object : Update(1) { // all requests are always merged
override fun run() {
processPendingEvents()
// todo what if here a new event is added; probably synchronization is needed between pPE and adding to the queue
}
}
private val settingsChangeListener = SettingsChangeListener { event ->
LOG.debug("Adding settings changed event $event to the queue")
pendingEvents.add(event)
queue.queue(updateObject)
}
@RequiresBackgroundThread
internal fun initialize(initMode: InitMode) {
saveIdeSettings()
settingsLog.initialize()
// the queue is not activated initially => events will be collected but not processed until we perform all initialization tasks
SettingsSyncEvents.getInstance().addSettingsChangedListener(settingsChangeListener)
ideMediator.activateStreamProvider()
applyInitialChanges(initMode)
queue.activate()
}
private fun saveIdeSettings() {
runBlockingMaybeCancellable {
saveSettings(ApplicationManager.getApplication(), forceSavingAllSettings = true)
}
}
private fun applyInitialChanges(initMode: InitMode) {
val previousState = collectCurrentState()
settingsLog.logExistingSettings()
try {
when (initMode) {
is InitMode.TakeFromServer -> applySnapshotFromServer(initMode.cloudEvent)
InitMode.PushToServer -> mergeAndPush(previousState.idePosition, previousState.cloudPosition, FORCE_PUSH)
InitMode.JustInit -> mergeAndPush(previousState.idePosition, previousState.cloudPosition, PUSH_IF_NEEDED)
is InitMode.MigrateFromOldStorage -> migrateFromOldStorage(initMode.migration)
}
}
catch (e: Throwable) {
stopSyncingAndRollback(previousState, e)
}
}
private fun applySnapshotFromServer(cloudEvent: SyncSettingsEvent.CloudChange) {
settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings
val masterPosition = settingsLog.forceWriteToMaster(cloudEvent.snapshot, "Remote changes to initialize settings by data from cloud")
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
// normally we set cloud position only after successful push to cloud, but in this case we already take all settings from the cloud,
// so no push is needed, and we know the cloud settings state.
settingsLog.setCloudPosition(masterPosition)
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = cloudEvent.serverVersionId
}
private fun migrateFromOldStorage(migration: SettingsSyncMigration) {
TemplateSettings.getInstance() // Required for live templates to be migrated correctly, see IDEA-303831
val migrationSnapshot = migration.getLocalDataIfAvailable(appConfigPath)
if (migrationSnapshot != null) {
settingsLog.applyIdeState(migrationSnapshot, "Migrate from old settings sync")
LOG.info("Migration from old storage applied.")
var masterPosition = settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings & by migration
// if there is already a version on the server, then it should be preferred over migration
val updateResult = remoteCommunicator.receiveUpdates()
if (updateResult is UpdateResult.Success) {
val snapshot = updateResult.settingsSnapshot
masterPosition = settingsLog.forceWriteToMaster(snapshot, "Remote changes to overwrite migration data by settings from cloud")
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = updateResult.serverVersionId
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
}
else {
// otherwise we place our migrated data to the cloud
forcePushToCloud(masterPosition)
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
migration.migrateCategoriesSyncStatus(appConfigPath, SettingsSyncSettings.getInstance())
saveIdeSettings()
}
settingsLog.setCloudPosition(masterPosition)
}
else {
LOG.warn("Migration from old storage didn't happen, although it was identified as possible: no data to migrate")
settingsLog.advanceMaster() // merge (preserve) 'ide' changes made by logging existing settings
}
}
private fun forcePushToCloud(masterPosition: SettingsLog.Position) {
pushAndHandleResult(true, masterPosition, onRejectedPush = {
LOG.error("Reject shouldn't happen when force push is used")
SettingsSyncStatusTracker.getInstance().updateOnError(SettingsSyncBundle.message("notification.title.push.error"))
})
}
internal sealed class InitMode {
object JustInit : InitMode()
class TakeFromServer(val cloudEvent: SyncSettingsEvent.CloudChange) : InitMode()
class MigrateFromOldStorage(val migration: SettingsSyncMigration) : InitMode()
object PushToServer : InitMode()
}
@RequiresBackgroundThread
private fun processPendingEvents() {
val previousState = collectCurrentState()
try {
var pushRequestMode: PushRequestMode = PUSH_IF_NEEDED
var mergeAndPushAfterProcessingEvents = true
while (pendingEvents.isNotEmpty()) {
val event = pendingEvents.removeAt(0)
LOG.debug("Processing event $event")
when (event) {
is SyncSettingsEvent.IdeChange -> {
settingsLog.applyIdeState(event.snapshot, "Local changes made in the IDE")
}
is SyncSettingsEvent.CloudChange -> {
settingsLog.applyCloudState(event.snapshot, "Remote changes")
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = event.serverVersionId
}
is SyncSettingsEvent.LogCurrentSettings -> {
settingsLog.logExistingSettings()
}
is SyncSettingsEvent.MustPushRequest -> {
pushRequestMode = MUST_PUSH
}
is SyncSettingsEvent.DeleteServerData -> {
mergeAndPushAfterProcessingEvents = false
stopSyncingAndRollback(previousState)
deleteServerData(event.afterDeleting)
}
SyncSettingsEvent.DeletedOnCloud -> {
mergeAndPushAfterProcessingEvents = false
stopSyncingAndRollback(previousState)
}
SyncSettingsEvent.PingRequest -> {}
}
}
if (mergeAndPushAfterProcessingEvents) {
mergeAndPush(previousState.idePosition, previousState.cloudPosition, pushRequestMode)
}
}
catch (exception: Throwable) {
stopSyncingAndRollback(previousState, exception)
}
}
private fun deleteServerData(afterDeleting: (DeleteServerDataResult) -> Unit) {
val deletionSnapshot = SettingsSnapshot(SettingsSnapshot.MetaInfo(Instant.now(), getLocalApplicationInfo(), isDeleted = true),
emptySet(), null)
val pushResult = pushToCloud(deletionSnapshot, force = true)
LOG.info("Deleting server data. Result: $pushResult")
when (pushResult) {
is SettingsSyncPushResult.Success -> {
afterDeleting(DeleteServerDataResult.Success)
}
is SettingsSyncPushResult.Error -> {
afterDeleting(DeleteServerDataResult.Error(pushResult.message))
}
SettingsSyncPushResult.Rejected -> {
afterDeleting(DeleteServerDataResult.Error("Deletion rejected by server"))
}
}
}
private class CurrentState(
val masterPosition: SettingsLog.Position,
val idePosition: SettingsLog.Position,
val cloudPosition: SettingsLog.Position,
val knownServerId: String?
)
private fun collectCurrentState(): CurrentState = CurrentState(settingsLog.getMasterPosition(),
settingsLog.getIdePosition(),
settingsLog.getCloudPosition(),
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId)
private fun stopSyncingAndRollback(previousState: CurrentState, exception: Throwable? = null) {
if (exception != null) {
LOG.error("Couldn't apply settings. Disabling sync and rolling back.", exception)
SettingsSyncEventsStatistics.DISABLED_AUTOMATICALLY.log(SettingsSyncEventsStatistics.AutomaticDisableReason.EXCEPTION)
}
else {
LOG.info("Settings Sync is switched off. Rolling back.")
}
SettingsSyncSettings.getInstance().syncEnabled = false
if (exception != null) {
SettingsSyncStatusTracker.getInstance().updateOnError(exception.localizedMessage)
}
ideMediator.removeStreamProvider()
SettingsSyncEvents.getInstance().removeSettingsChangedListener(settingsChangeListener)
pendingEvents.clear()
rollback(previousState)
queue.deactivate() // for tests it is important to have it the last statement, otherwise waitForAllExecuted can finish before rollback
}
private fun rollback(previousState: CurrentState) {
try {
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = previousState.knownServerId
settingsLog.setIdePosition(previousState.idePosition)
settingsLog.setCloudPosition(previousState.cloudPosition)
settingsLog.setMasterPosition(previousState.masterPosition)
// we don't need to roll back the state of the IDE here, because it is the latest stage of mergeAndPush which can fail
// (pushing can fail also, but it is a normal failure which doesn't need to roll everything back and turn the sync off
}
catch (e: Throwable) {
LOG.error("Couldn't rollback to the previous successful state", e)
}
}
private fun mergeAndPush(previousIdePosition: SettingsLog.Position,
previousCloudPosition: SettingsLog.Position,
pushRequestMode: PushRequestMode) {
val newIdePosition = settingsLog.getIdePosition()
val newCloudPosition = settingsLog.getCloudPosition()
val masterPosition: SettingsLog.Position
if (newIdePosition != previousIdePosition || newCloudPosition != previousCloudPosition) {
// move master to the actual position. It can be a fast-forward to either ide, or cloud changes, or it can be a merge
masterPosition = settingsLog.advanceMaster()
}
else {
// there were only fake events without actual changes to the repository => master doesn't need to be changed either
masterPosition = settingsLog.getMasterPosition()
}
if (newIdePosition != masterPosition) { // master has advanced further that ide => the ide needs to be updated
pushToIde(settingsLog.collectCurrentSnapshot(), masterPosition)
}
if (newCloudPosition != masterPosition || pushRequestMode == MUST_PUSH || pushRequestMode == FORCE_PUSH) {
pushAndHandleResult(pushRequestMode == FORCE_PUSH, masterPosition, onRejectedPush = {
// todo add protection against potential infinite reject-update-reject cycle
// (it would indicate some problem, but still shouldn't cycle forever)
// In the case of reject we'll just "wait" for the next update event:
// it will be processed in the next session anyway
if (pendingEvents.none { it is SyncSettingsEvent.CloudChange }) {
// not to wait for too long, schedule an update right away unless it has already been scheduled
updateChecker.scheduleUpdateFromServer()
}
})
}
else {
LOG.debug("Nothing to push")
}
}
private fun pushAndHandleResult(force: Boolean, positionToSetCloudBranch: SettingsLog.Position, onRejectedPush: () -> Unit) {
val pushResult: SettingsSyncPushResult = pushToCloud(settingsLog.collectCurrentSnapshot(), force)
LOG.info("Result of pushing settings to the cloud: $pushResult")
when (pushResult) {
is SettingsSyncPushResult.Success -> {
settingsLog.setCloudPosition(positionToSetCloudBranch)
SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId = pushResult.serverVersionId
SettingsSyncStatusTracker.getInstance().updateOnSuccess()
}
is SettingsSyncPushResult.Error -> {
SettingsSyncStatusTracker.getInstance().updateOnError(
SettingsSyncBundle.message("notification.title.push.error") + ": " + pushResult.message)
}
SettingsSyncPushResult.Rejected -> {
onRejectedPush()
}
}
}
private enum class PushRequestMode {
PUSH_IF_NEEDED,
MUST_PUSH,
FORCE_PUSH
}
private fun pushToCloud(settingsSnapshot: SettingsSnapshot, force: Boolean): SettingsSyncPushResult {
val versionId = SettingsSyncLocalSettings.getInstance().knownAndAppliedServerId
if (force) {
return remoteCommunicator.push(settingsSnapshot, force = true, versionId)
}
else if (remoteCommunicator.checkServerState() is ServerState.UpdateNeeded) {
return SettingsSyncPushResult.Rejected
}
else {
return remoteCommunicator.push(settingsSnapshot, force = false, versionId)
}
}
private fun pushToIde(settingsSnapshot: SettingsSnapshot, targetPosition: SettingsLog.Position) {
ideMediator.applyToIde(settingsSnapshot)
settingsLog.setIdePosition(targetPosition)
LOG.info("Applied settings to the IDE.")
}
@TestOnly
fun waitForAllExecuted(timeout: Long, timeUnit: TimeUnit) {
queue.waitForAllExecuted(timeout, timeUnit)
}
@VisibleForTesting
internal fun suspendEventProcessing() {
queue.suspend()
}
@VisibleForTesting
internal fun resumeEventProcessing() {
queue.resume()
}
companion object {
private val LOG = logger<SettingsSyncBridge>()
}
} | apache-2.0 | 8e1f9077b5e0005f1a0f1e5c9be97189 | 42.108333 | 138 | 0.720905 | 5.228437 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/catalog/ui/adapter/delegate/AuthorListAdapterDelegate.kt | 1 | 3469 | package org.stepik.android.view.catalog.ui.adapter.delegate
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.header_catalog_block.*
import kotlinx.android.synthetic.main.item_author_list.*
import org.stepic.droid.R
import org.stepik.android.domain.catalog.model.CatalogAuthor
import org.stepik.android.presentation.course_list_redux.model.CatalogBlockStateWrapper
import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager
import org.stepik.android.view.catalog.mapper.AuthorCountMapper
import org.stepik.android.view.catalog.model.CatalogItem
import org.stepik.android.view.catalog.ui.delegate.CatalogBlockHeaderDelegate
import ru.nobird.app.core.model.cast
import ru.nobird.android.ui.adapterdelegates.AdapterDelegate
import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
class AuthorListAdapterDelegate(
private val authorCountMapper: AuthorCountMapper,
private val onAuthorClick: (Long) -> Unit
) : AdapterDelegate<CatalogItem, DelegateViewHolder<CatalogItem>>() {
private val sharedViewPool = RecyclerView.RecycledViewPool()
override fun isForViewType(position: Int, data: CatalogItem): Boolean =
data is CatalogItem.Block && data.catalogBlockStateWrapper is CatalogBlockStateWrapper.AuthorList
override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CatalogItem> =
AuthorListViewHolder(createView(parent, R.layout.item_author_list))
private inner class AuthorListViewHolder(
override val containerView: View
) : DelegateViewHolder<CatalogItem>(containerView), LayoutContainer {
private val catalogBlockTitleDelegate =
CatalogBlockHeaderDelegate(catalogBlockContainer, null)
private val adapter = DefaultDelegateAdapter<CatalogAuthor>()
.also {
it += AuthorAdapterDelegate(onAuthorClick)
}
init {
val rowCount = context.resources.getInteger(R.integer.author_lists_default_rows)
authorListRecycler.layoutManager =
TableLayoutManager(
context,
horizontalSpanCount = context.resources.getInteger(R.integer.author_lists_default_columns),
verticalSpanCount = rowCount,
orientation = RecyclerView.HORIZONTAL,
reverseLayout = false
)
authorListRecycler.setRecycledViewPool(sharedViewPool)
authorListRecycler.setHasFixedSize(true)
authorListRecycler.adapter = adapter
val snapHelper = LinearSnapHelper()
snapHelper.attachToRecyclerView(authorListRecycler)
}
override fun onBind(data: CatalogItem) {
val authorLists = data
.cast<CatalogItem.Block>()
.catalogBlockStateWrapper
.cast<CatalogBlockStateWrapper.AuthorList>()
adapter.items = authorLists.content.authors
catalogBlockTitleDelegate.setInformation(authorLists.catalogBlockItem)
val count = authorLists.content.authors.size
catalogBlockTitleDelegate.setCount(authorCountMapper.mapAuthorCountToString(context, count))
}
}
} | apache-2.0 | 83936212ad0d2597f27b0751036e3bed | 44.064935 | 111 | 0.732776 | 5.162202 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/submission/SubmissionsPresenter.kt | 1 | 4114 | package org.stepik.android.presentation.submission
import ru.nobird.app.core.model.plus
import org.stepik.android.domain.submission.interactor.SubmissionInteractor
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepik.android.domain.filter.model.SubmissionsFilterQuery
import org.stepik.android.domain.review_instruction.model.ReviewInstruction
import org.stepik.android.presentation.base.PresenterBase
import javax.inject.Inject
class SubmissionsPresenter
@Inject
constructor(
private val submissionInteractor: SubmissionInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<SubmissionsView>() {
private var state: SubmissionsView.State.Data = SubmissionsView.State.Data(
submissionsFilterQuery = SubmissionsFilterQuery.DEFAULT_QUERY,
SubmissionsView.ContentState.Idle
)
set(value) {
field = value
view?.setState(value)
}
override fun attachView(view: SubmissionsView) {
super.attachView(view)
view.setState(state)
}
fun fetchSubmissions(
stepId: Long,
isTeacher: Boolean,
submissionsFilterQuery: SubmissionsFilterQuery,
reviewInstruction: ReviewInstruction? = null,
forceUpdate: Boolean = false
) {
if (state.contentState != SubmissionsView.ContentState.Idle &&
!((state.contentState == SubmissionsView.ContentState.NetworkError || state.contentState is SubmissionsView.ContentState.Content || state.contentState is SubmissionsView.ContentState.ContentEmpty) && forceUpdate)) {
return
}
val oldState = state
compositeDisposable.clear()
state = state.copy(
submissionsFilterQuery = submissionsFilterQuery,
contentState = SubmissionsView.ContentState.Loading
)
compositeDisposable += submissionInteractor
.getSubmissionItems(stepId, isTeacher, state.submissionsFilterQuery, reviewInstruction)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = {
val newState = if (it.isEmpty()) {
SubmissionsView.ContentState.ContentEmpty
} else {
SubmissionsView.ContentState.Content(it)
}
state = state.copy(contentState = newState)
},
onError = {
if (oldState.contentState is SubmissionsView.ContentState.Content) {
state = oldState
view?.showNetworkError()
} else {
state = state.copy(contentState = SubmissionsView.ContentState.NetworkError)
}
}
)
}
fun fetchNextPage(stepId: Long, isTeacher: Boolean, reviewInstruction: ReviewInstruction? = null) {
val oldState = (state.contentState as? SubmissionsView.ContentState.Content)
?.takeIf { it.items.hasNext }
?: return
state = state.copy(contentState = SubmissionsView.ContentState.ContentLoading(oldState.items))
compositeDisposable += submissionInteractor
.getSubmissionItems(stepId, isTeacher, state.submissionsFilterQuery, reviewInstruction, oldState.items.page + 1)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = state.copy(contentState = SubmissionsView.ContentState.Content(oldState.items + it)) },
onError = { state = state.copy(contentState = oldState); view?.showNetworkError() }
)
}
fun onFilterMenuItemClicked() {
view?.showSubmissionsFilterDialog(state.submissionsFilterQuery)
}
} | apache-2.0 | bbfdc48d139a696d15996e50751aaa22 | 39.742574 | 227 | 0.659942 | 5.342857 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/protocol/MainPersistenceProvider.kt | 1 | 10081 | /*
* Copyright (C) 2021 Veli Tasalı
*
* 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 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.protocol
import android.content.Context
import android.net.Uri
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.genonbeta.android.framework.io.OpenableContent
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.runBlocking
import org.monora.uprotocol.client.android.config.AppConfig
import org.monora.uprotocol.client.android.data.ClientRepository
import org.monora.uprotocol.client.android.data.TransferRepository
import org.monora.uprotocol.client.android.data.UserDataRepository
import org.monora.uprotocol.client.android.database.model.UClient
import org.monora.uprotocol.client.android.database.model.UClientAddress
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.client.android.io.DocumentFileStreamDescriptor
import org.monora.uprotocol.client.android.io.StreamInfoStreamDescriptor
import org.monora.uprotocol.client.android.util.Graphics
import org.monora.uprotocol.client.android.util.picturePath
import org.monora.uprotocol.core.io.StreamDescriptor
import org.monora.uprotocol.core.persistence.PersistenceException
import org.monora.uprotocol.core.persistence.PersistenceProvider
import org.monora.uprotocol.core.protocol.Client
import org.monora.uprotocol.core.protocol.ClientAddress
import org.monora.uprotocol.core.protocol.ClientType
import org.monora.uprotocol.core.protocol.Direction
import org.monora.uprotocol.core.transfer.TransferItem
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.security.PrivateKey
import java.security.PublicKey
import java.security.SecureRandom
import java.security.cert.X509Certificate
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*
import javax.inject.Inject
class MainPersistenceProvider @Inject constructor(
@ApplicationContext val context: Context,
private val clientRepository: ClientRepository,
private val userDataRepository: UserDataRepository,
private val transferRepository: TransferRepository,
) : PersistenceProvider {
private val invalidationRequests = mutableSetOf<String>()
override fun approveInvalidationOfCredentials(client: Client): Boolean {
check(client is UClient) {
"Unexpected implementation type"
}
if (!invalidationRequests.remove(client.clientUid)) {
return false
}
client.certificate = null
runBlocking {
clientRepository.update(client)
}
return true
}
override fun containsTransfer(groupId: Long): Boolean = runBlocking {
transferRepository.containsTransfer(groupId)
}
override fun createClientAddressFor(address: InetAddress, clientUid: String) = UClientAddress(
address, clientUid, System.currentTimeMillis()
)
override fun createClientFor(
uid: String,
nickname: String,
manufacturer: String,
product: String,
type: ClientType,
versionName: String,
versionCode: Int,
protocolVersion: Int,
protocolVersionMin: Int,
revisionOfPicture: Long
) = UClient(
uid,
nickname,
manufacturer,
product,
type,
versionName,
versionCode,
protocolVersion,
protocolVersionMin,
revisionOfPicture
)
override fun createTransferItemFor(
groupId: Long,
id: Long,
name: String,
mimeType: String,
size: Long,
directory: String?,
direction: Direction,
): TransferItem = UTransferItem(id, groupId, name, mimeType, size, directory, uniqueFileName(), direction)
override fun getCertificate(): X509Certificate = userDataRepository.certificate
override fun getClient(): UClient = userDataRepository.clientStatic
override fun getClientFor(uid: String): UClient? = runBlocking { clientRepository.getDirect(uid) }
override fun getClientNickname(): String = userDataRepository.clientNickname
override fun getClientPicture(client: Client): ByteArray? {
context.runCatching {
return openFileInput(client.picturePath).readBytes()
}
return null
}
override fun getClientUid(): String = userDataRepository.clientUid
override fun getDescriptorFor(transferItem: TransferItem): StreamDescriptor {
check(transferItem is UTransferItem) {
"Unknown item type"
}
// TODO: 7/19/21 Cache the 'Transfer' instance
val transfer = runBlocking {
transferRepository.getTransfer(transferItem.groupId) ?: throw IOException()
}
return if (transferItem.direction == Direction.Incoming) {
DocumentFileStreamDescriptor(transferRepository.getIncomingFile(transferItem, transfer))
} else {
StreamInfoStreamDescriptor(OpenableContent.from(context, Uri.parse(transferItem.location)))
}
}
override fun getFirstReceivableItem(groupId: Long) = runBlocking {
transferRepository.getReceivable(groupId)
}
override fun getNetworkPin(): Int {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
var pin = sharedPreferences.getInt("pin", 0)
if (pin == 0) {
pin = SecureRandom().nextInt()
sharedPreferences.edit()
.putInt("pin", pin)
.apply()
}
return pin
}
override fun getPrivateKey(): PrivateKey = userDataRepository.keyFactory.generatePrivate(
PKCS8EncodedKeySpec(userDataRepository.keyPair.private.encoded)
)
override fun getPublicKey(): PublicKey = userDataRepository.keyFactory.generatePublic(
X509EncodedKeySpec(userDataRepository.keyPair.public.encoded)
)
override fun hasRequestForInvalidationOfCredentials(clientUid: String): Boolean {
return invalidationRequests.contains(clientUid)
}
override fun loadTransferItem(
clientUid: String, groupId: Long, id: Long, direction: Direction,
): TransferItem = runBlocking {
transferRepository.getTransferItem(groupId, id, direction) ?: throw PersistenceException("Item does not exist")
}
override fun openInputStream(descriptor: StreamDescriptor): InputStream {
if (descriptor is StreamInfoStreamDescriptor) {
return descriptor.openableContent.openInputStream(context)
} else if (descriptor is DocumentFileStreamDescriptor) {
return context.contentResolver.openInputStream(descriptor.documentFile.getUri()) ?: throw IOException(
"Supported resource did not open"
)
}
throw RuntimeException("Unsupported descriptor.")
}
override fun openOutputStream(descriptor: StreamDescriptor): OutputStream {
if (descriptor is StreamInfoStreamDescriptor) {
return descriptor.openableContent.openOutputStream(context)
} else if (descriptor is DocumentFileStreamDescriptor) {
return context.contentResolver.openOutputStream(
descriptor.documentFile.getUri(), "wa"
) ?: throw IOException("Supported resource did not open")
}
throw RuntimeException("Unsupported descriptor.")
}
override fun persist(client: Client, updating: Boolean) {
if (client is UClient) runBlocking {
if (updating) {
clientRepository.update(client)
} else {
clientRepository.insert(client)
}
} else {
throw UnsupportedOperationException()
}
}
override fun persist(clientAddress: ClientAddress) {
if (clientAddress is UClientAddress) runBlocking {
clientRepository.insert(clientAddress)
} else {
throw UnsupportedOperationException()
}
}
override fun persist(clientUid: String, item: TransferItem) {
if (item is UTransferItem) runBlocking {
transferRepository.update(item)
} else {
throw UnsupportedOperationException()
}
}
override fun persist(clientUid: String, itemList: MutableList<out TransferItem>) {
if (itemList.isEmpty()) return
runBlocking {
transferRepository.insert(itemList.filterIsInstance(UTransferItem::class.java))
}
}
override fun persistClientPicture(client: Client, data: ByteArray?) = runBlocking {
Graphics.saveRemoteClientPicture(context, client, data)
}
override fun revokeNetworkPin() {
PreferenceManager.getDefaultSharedPreferences(context).edit {
putInt("pin", 0)
}
}
override fun saveRequestForInvalidationOfCredentials(clientUid: String) {
invalidationRequests.add(clientUid)
}
override fun setState(clientUid: String, item: TransferItem, state: TransferItem.State, e: Exception?) {
if (item is UTransferItem) {
item.state = state
} else {
throw UnsupportedOperationException()
}
}
}
fun uniqueFileName() = ".${UUID.randomUUID()}.${AppConfig.EXT_FILE_PART}"
| gpl-2.0 | c0f2cea4ed95da009386ada19e3ec713 | 34.871886 | 119 | 0.705556 | 4.995045 | false | false | false | false |
SmokSmog/smoksmog-android | android/src/main/kotlin/smoksmog/air/AirQuality.kt | 1 | 1960 | package smoksmog.air
import android.content.Context
import android.support.annotation.ColorRes
import android.support.annotation.StringRes
import smoksmog.R
/**
*/
enum class AirQuality constructor(@ColorRes val colorResId: Int, @StringRes val titleResId: Int) : ValueCheck {
VERY_GOOD(R.color.airQualityVeryGood, R.string.airQualityVeryGood) {
override fun isValueInRange(value: Double): Boolean {
return value <= 1
}
},
GOOD(R.color.airQualityGood, R.string.airQualityGood) {
override fun isValueInRange(value: Double): Boolean {
return value > 1 && value <= 3
}
},
MODERATE(R.color.airQualityModerate, R.string.airQualityModerate) {
override fun isValueInRange(value: Double): Boolean {
return value > 3 && value <= 5
}
},
SUFFICIENT(R.color.airQualitySufficient, R.string.airQualitySufficient) {
override fun isValueInRange(value: Double): Boolean {
return value > 5 && value <= 7
}
},
BAD(R.color.airQualityBad, R.string.airQualityBad) {
override fun isValueInRange(value: Double): Boolean {
return value > 7 && value <= 10
}
},
VERY_BAD(R.color.airQualityVeryBad, R.string.airQualityVeryBad) {
override fun isValueInRange(value: Double): Boolean {
return value > 10
}
};
fun getTitle(context: Context): CharSequence {
return context.getString(titleResId)
}
fun getColor(context: Context): Int {
// Deprecated since 23 API, quite fresh
@Suppress("DEPRECATION")
return context.resources.getColor(colorResId)
}
companion object {
fun findByValue(value: Double): AirQuality {
values().filter { it.isValueInRange(value) }.forEach { return it }
throw IllegalStateException("Unable to find AirQuality for given value ($value)")
}
}
}
| gpl-3.0 | d8048dd22361ed07f5bfaa54924c3059 | 28.253731 | 111 | 0.637755 | 4.270153 | false | false | false | false |
romannurik/muzei | example-unsplash/src/main/java/com/example/muzei/unsplash/UnsplashExampleArtProvider.kt | 1 | 3543 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.muzei.unsplash
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.RemoteActionCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.net.toUri
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider
import java.io.IOException
import java.io.InputStream
class UnsplashExampleArtProvider : MuzeiArtProvider() {
companion object {
private const val TAG = "UnsplashExample"
}
override fun onLoadRequested(initial: Boolean) {
val context = context ?: return
UnsplashExampleWorker.enqueueLoad(context)
}
override fun getCommandActions(artwork: Artwork): List<RemoteActionCompat> {
val context = context ?: return super.getCommandActions(artwork)
return listOfNotNull(
createViewProfileAction(context, artwork),
createVisitUnsplashAction(context))
}
@SuppressLint("InlinedApi")
private fun createViewProfileAction(context: Context, artwork: Artwork): RemoteActionCompat? {
val profileUri = artwork.metadata?.toUri() ?: return null
val title = context.getString(R.string.action_view_profile, artwork.byline)
val intent = Intent(Intent.ACTION_VIEW, profileUri)
return RemoteActionCompat(
IconCompat.createWithResource(context, R.drawable.source_ic_profile),
title,
title,
PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE))
}
@SuppressLint("InlinedApi")
private fun createVisitUnsplashAction(context: Context): RemoteActionCompat {
val title = context.getString(R.string.action_visit_unsplash)
val unsplashUri = context.getString(R.string.unsplash_link) +
ATTRIBUTION_QUERY_PARAMETERS
val intent = Intent(Intent.ACTION_VIEW, unsplashUri.toUri())
return RemoteActionCompat(
IconCompat.createWithResource(context,
com.google.android.apps.muzei.api.R.drawable.muzei_launch_command),
title,
title,
PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)).apply {
setShouldShowIcon(false)
}
}
override fun openFile(artwork: Artwork): InputStream {
return super.openFile(artwork).also {
artwork.token?.run {
try {
UnsplashService.trackDownload(this)
} catch (e: IOException) {
Log.w(TAG, "Error reporting download to Unsplash", e)
}
}
}
}
} | apache-2.0 | 17bab3e0afd0f3e3708f2dc3ede5ac74 | 37.945055 | 99 | 0.675134 | 4.813859 | false | false | false | false |
nobuoka/vc-oauth-java | core/src/main/kotlin/info/vividcode/oauth/protocol/Signatures.kt | 1 | 1831 | /*
Copyright 2014, 2017 NOBUOKA Yu
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 info.vividcode.oauth.protocol
import java.nio.charset.StandardCharsets
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
object Signatures {
private val US_ASCII = StandardCharsets.US_ASCII
/**
* See [RFC 5849, section 3.4.2](https://tools.ietf.org/html/rfc5849#section-3.4.2).
*
* @param text The signature base string from RFC 5849, Section 3.4.1.1.
* @param key TODO
* @return TODO
*/
@JvmStatic
fun makeSignatureWithHmacSha1(key: String, text: String): String {
// Every implementation of the Java platform is required to support HmacSHA1.
val algorithmName = "HmacSHA1"
val mac: Mac = try {
Mac.getInstance(algorithmName)
} catch (e: NoSuchAlgorithmException) {
throw RuntimeException(e)
}
val k = SecretKeySpec(key.toByteArray(US_ASCII), algorithmName)
try {
mac.init(k)
} catch (e: InvalidKeyException) {
throw RuntimeException(e)
}
val digest = mac.doFinal(text.toByteArray(US_ASCII))
return Base64.getEncoder().encodeToString(digest)
}
}
| apache-2.0 | 60494736c05b93f4637e71009f5b001e | 30.568966 | 88 | 0.698525 | 4.180365 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Reflect.kt | 1 | 3693 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.apis.Api
import slatekit.apis.Action
import slatekit.common.Field
import slatekit.common.conf.Config
import slatekit.meta.Reflector
//</doc:import_required>
//<doc:import_examples>
import slatekit.results.Try
import slatekit.results.Success
import slatekit.examples.common.User
import slatekit.examples.common.UserApi
import slatekit.integration.common.AppEntContext
//</doc:import_examples>
class Example_Reflect : Command("reflect") {
override fun execute(request: CommandRequest) : Try<Any> {
// JAVA
// 1. getFields NOT working
// 2. getDeclaredFields working
// 3. can NOT use duplicate annotations on a method
// Kotlin
// 1. all parameters explicitly setup without named parameters works:
// @EntityField2("", true, 12)
// var isMale = false
//
// @EntityField3("action:init", true, 12)
// fun init(first:String, last:String): User =
//
// 2. named parameters FAILS ( because they are not considered constants )
// @EntityField2(required = true, length = 12)
// var isMale = false
//<doc:setup>
//</doc:setup>
//<doc:examples>
val ctx = AppEntContext.sample(Config(), "sample", "sample", "", "")
val api = UserApi(ctx)
// CASE 1: Create instance of a class ( will pick a 0 parameter constructor )
val user = Reflector.create<User>(User::class)
println("user: " + user)
// CASE 2: Get a field value
val user2 = user.copy(email = "[email protected]")
val name = Reflector.getFieldValue(user2, "email")
println("email : " + name)
// CASE 3: Set a field value
Reflector.setFieldValue(user, User::email, "[email protected]")
println("email : " + user.email)
// CASE 4: Call a method with parameters
val result = Reflector.callMethod(UserApi::class, api, "create", arrayOf("[email protected]", "super", "man", true, 35))
println((result as User ).toString())
// CASE 5: Get a class level annotation
// NOTE: The annotation must be created with all parameters ( not named parameters )
val annoCls = Reflector.getAnnotationForClass<Api>(UserApi::class, Api::class)
println(annoCls)
// CASE 6: Get a method level annotations
// NOTE: The annotation must be created with all parameters
val annoMems = Reflector.getAnnotatedMembers<Action>(UserApi::class, Action::class)
println(annoMems)
// CASE 7: Get a field level annotations
// NOTE: The annotation must be created with all parameters
val annoFlds = Reflector.getAnnotatedProps<Field>(User::class, Field::class)
println(annoFlds)
// CASE 8: print parameters
val method = Reflector.getMethod(UserApi::class, "activate")
//Reflector.printParams(method)
// CASE 10: Get method
val sym = Reflector.getMethod(UserApi::class, "info")
println(sym?.name)
// CASE 11: Get method parameters
val symArgs = Reflector.getMethodArgs(UserApi::class, "activate")
println(symArgs)
// CASE 12: Is argument a basic type
val argType = symArgs!!.toList()[0]
println(argType.type)
// CASE 13: Create instance from parameter
val argInstance = Reflector.create<Any>(symArgs!!.toList()[0].javaClass.kotlin)
println(argInstance)
//</doc:examples>
return Success("")
}
}
| apache-2.0 | 0990636b0618be1838a4149b06bb2e32 | 26.559701 | 125 | 0.68183 | 3.89557 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/traits/kt2399.kt | 1 | 1163 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// on JS Parser.parse and MultiParser.parse clash in ProjectInfoJsonParser
class JsonObject {
}
class JsonArray {
}
class ProjectInfo {
override fun toString(): String = "OK"
}
public interface Parser<in IN: Any, out OUT: Any> {
public fun parse(source: IN): OUT
}
public interface MultiParser<in IN: Any, out OUT: Any> {
public fun parse(source: IN): Collection<OUT>
}
public interface JsonParser<T: Any>: Parser<JsonObject, T>, MultiParser<JsonArray, T> {
public override fun parse(source: JsonArray): Collection<T> {
return ArrayList<T>()
}
}
public abstract class ProjectInfoJsonParser(): JsonParser<ProjectInfo> {
public override fun parse(source: JsonObject): ProjectInfo {
return ProjectInfo()
}
}
class ProjectApiContext {
public val projectInfoJsonParser: ProjectInfoJsonParser = object : ProjectInfoJsonParser(){
}
}
fun box(): String {
val context = ProjectApiContext()
val array = context.projectInfoJsonParser.parse(JsonArray())
return if (array != null) "OK" else "fail"
}
| apache-2.0 | d683c0b49fd1425a5479847118090567 | 25.431818 | 95 | 0.708512 | 4.066434 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/primitiveTypes/kt935.kt | 2 | 1034 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
package bottles
fun box() : String {
var bottles = 10
while (bottles > 0) {
print(bottlesOfBeer(bottles) + " on the wall, ")
println(bottlesOfBeer(bottles) + ".")
print("Take one down, pass it around, ")
if (--bottles == 0) {
println("no more bottles of beer on the wall.")
}
else {
println(bottlesOfBeer(bottles) + " on the wall.")
}
}
return "OK"
}
fun bottlesOfBeer(count : Int) : String {
val result = StringBuilder()
result += count
result += if (count > 1) " bottles of beer" else " bottle of beer"
return result.toString() ?: ""
}
// An excerpt from the standard library
fun print(message : String) { System.out?.print(message) }
fun println(message : String) { System.out?.println(message) }
operator fun StringBuilder.plusAssign(o : Any) { append(o) }
val <T> Array<T>.isEmpty : Boolean get() = size == 0
| apache-2.0 | f105e4bbe22d2dfb34d2398eb40de6c6 | 30.333333 | 72 | 0.611219 | 3.517007 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/service/VpnPermissionService.kt | 1 | 1357 | /*
* This file is part of Blokada.
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package service
import android.app.Activity
import android.net.VpnService
import utils.Logger
object VpnPermissionService {
private val log = Logger("VpnPerm")
private val context = ContextService
var onPermissionGranted = { granted: Boolean -> }
fun hasPermission(): Boolean {
return VpnService.prepare(context.requireContext()) == null
}
fun askPermission() {
log.w("Asking for VPN permission")
val activity = context.requireContext()
if (activity !is Activity) {
log.e("No activity context available")
return
}
VpnService.prepare(activity)?.let { intent ->
activity.startActivityForResult(intent, 0)
} ?: onPermissionGranted(true)
}
fun resultReturned(resultCode: Int) {
if (resultCode == -1) onPermissionGranted(true)
else {
log.w("VPN permission not granted, returned code $resultCode")
onPermissionGranted(false)
}
}
} | mpl-2.0 | 0ad6adb586a66b80973c94b3c76bbbf5 | 25.607843 | 74 | 0.64528 | 4.360129 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/file.kt | 1 | 4438 | // 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.intellij.build.io
import java.io.IOException
import java.nio.channels.FileChannel
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.DosFileAttributeView
import java.util.*
import java.util.function.Predicate
internal val RW_CREATE_NEW = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.READ,
StandardOpenOption.CREATE_NEW)
internal val W_CREATE_NEW = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)
internal val isWindows = !System.getProperty("os.name").startsWith("windows", ignoreCase = true)
fun copyDir(sourceDir: Path, targetDir: Path, dirFilter: Predicate<Path>? = null, fileFilter: Predicate<Path>? = null) {
Files.createDirectories(targetDir)
Files.walkFileTree(sourceDir, CopyDirectoryVisitor(
sourceDir,
targetDir,
dirFilter = dirFilter ?: Predicate { true },
fileFilter = fileFilter ?: Predicate { true },
))
}
internal inline fun writeNewFile(file: Path, task: (FileChannel) -> Unit) {
Files.createDirectories(file.parent)
FileChannel.open(file, W_CREATE_NEW).use {
task(it)
}
}
private class CopyDirectoryVisitor(private val sourceDir: Path,
private val targetDir: Path,
private val dirFilter: Predicate<Path>,
private val fileFilter: Predicate<Path>) : SimpleFileVisitor<Path>() {
private val useHardlink: Boolean
private val sourceToTargetFile: (Path) -> Path
init {
val isTheSameFileStore = Files.getFileStore(sourceDir) == Files.getFileStore(targetDir)
useHardlink = !isWindows && isTheSameFileStore
// support copying to ZipFS
if (isTheSameFileStore) {
sourceToTargetFile = { targetDir.resolve(sourceDir.relativize(it)) }
}
else {
sourceToTargetFile = { targetDir.resolve(sourceDir.relativize(it).toString()) }
}
}
override fun preVisitDirectory(directory: Path, attributes: BasicFileAttributes): FileVisitResult {
if (!dirFilter.test(directory)) {
return FileVisitResult.SKIP_SUBTREE
}
try {
Files.createDirectory(sourceToTargetFile(directory))
}
catch (ignore: FileAlreadyExistsException) {
}
return FileVisitResult.CONTINUE
}
override fun visitFile(sourceFile: Path, attributes: BasicFileAttributes): FileVisitResult {
if (!fileFilter.test(sourceFile)) {
return FileVisitResult.CONTINUE
}
val targetFile = sourceToTargetFile(sourceFile)
if (useHardlink) {
Files.createLink(targetFile, sourceFile)
}
else {
Files.copy(sourceFile, targetFile, StandardCopyOption.COPY_ATTRIBUTES)
}
return FileVisitResult.CONTINUE
}
}
internal fun deleteDir(startDir: Path) {
Files.walkFileTree(startDir, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
deleteFile(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exception: IOException?): FileVisitResult {
if (exception != null) {
throw exception
}
Files.deleteIfExists(dir)
return FileVisitResult.CONTINUE
}
})
}
private fun deleteFile(file: Path) {
// repeated delete is required for bad OS like Windows
val maxAttemptCount = 10
var attemptCount = 0
while (true) {
try {
Files.deleteIfExists(file)
return
}
catch (e: IOException) {
if (++attemptCount == maxAttemptCount) {
throw e
}
if (e is AccessDeniedException && isWindows) {
val view = Files.getFileAttributeView(file, DosFileAttributeView::class.java)
if (view != null && view.readAttributes().isReadOnly) {
view.setReadOnly(false)
}
}
try {
Thread.sleep(10)
}
catch (ignored: InterruptedException) {
throw e
}
}
}
}
internal inline fun transformFile(file: Path, task: (tempFile: Path) -> Unit) {
val tempFile = file.parent.resolve("${file.fileName}.tmp")
try {
task(tempFile)
Files.move(tempFile, file, StandardCopyOption.REPLACE_EXISTING)
}
finally {
Files.deleteIfExists(tempFile)
}
} | apache-2.0 | 0868db8878cbefdbf8237966dd47fbed | 30.260563 | 158 | 0.684092 | 4.551795 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/DocumentationUI.kt | 1 | 7511 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.lang.documentation.ide.ui
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.documentation.*
import com.intellij.codeInsight.documentation.DocumentationManager.SELECTED_QUICK_DOC_TEXT
import com.intellij.codeInsight.documentation.DocumentationManager.decorate
import com.intellij.ide.DataManager
import com.intellij.lang.documentation.DocumentationData
import com.intellij.lang.documentation.DocumentationImageResolver
import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_BROWSER
import com.intellij.lang.documentation.ide.actions.PRIMARY_GROUP_ID
import com.intellij.lang.documentation.ide.actions.registerBackForwardActions
import com.intellij.lang.documentation.ide.impl.DocumentationBrowser
import com.intellij.lang.documentation.impl.DocumentationRequest
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.PopupHandler
import com.intellij.util.SmartList
import com.intellij.util.ui.EDT
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.accessibility.ScreenReader
import kotlinx.coroutines.*
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Rectangle
import javax.swing.Icon
import javax.swing.JScrollPane
import javax.swing.SwingUtilities
internal class DocumentationUI(
project: Project,
val browser: DocumentationBrowser,
) : DataProvider, Disposable {
val scrollPane: JScrollPane
val editorPane: DocumentationHintEditorPane
private val icons = mutableMapOf<String, Icon>()
private var imageResolver: DocumentationImageResolver? = null
private val linkHandler: DocumentationLinkHandler
private val cs = CoroutineScope(Dispatchers.EDT)
private val contentListeners: MutableList<() -> Unit> = SmartList()
override fun dispose() {
icons.clear()
imageResolver = null
cs.cancel()
}
init {
scrollPane = DocumentationScrollPane()
editorPane = DocumentationHintEditorPane(project, DocumentationScrollPane.keyboardActions(scrollPane), {
imageResolver?.resolveImage(it)
}, { icons[it] })
editorPane.applyFontProps(DocumentationComponent.getQuickDocFontSize())
scrollPane.setViewportView(editorPane)
scrollPane.addMouseWheelListener(FontSizeMouseWheelListener(editorPane::applyFontProps))
linkHandler = DocumentationLinkHandler.createAndRegister(editorPane, this, browser::navigateByLink)
browser.ui = this
Disposer.register(this, browser)
Disposer.register(this, browser.addStateListener { request, result, _ ->
applyStateLater(request, result)
})
for (action in linkHandler.createLinkActions()) {
action.registerCustomShortcutSet(editorPane, this)
}
registerBackForwardActions(editorPane)
val contextMenu = PopupHandler.installPopupMenu(
editorPane,
PRIMARY_GROUP_ID,
"documentation.pane.content.menu"
)
Disposer.register(this) { editorPane.removeMouseListener(contextMenu) }
DataManager.registerDataProvider(editorPane, this)
fetchingProgress()
}
override fun getData(dataId: String): Any? {
return when {
DOCUMENTATION_BROWSER.`is`(dataId) -> browser
SELECTED_QUICK_DOC_TEXT.`is`(dataId) -> editorPane.selectedText?.replace(160.toChar(), ' ') // IDEA-86633
else -> null
}
}
fun setBackground(color: Color): Disposable {
val editorBG = editorPane.background
editorPane.background = color
return Disposable {
editorPane.background = editorBG
}
}
fun addContentListener(listener: () -> Unit): Disposable {
EDT.assertIsEdt()
contentListeners.add(listener)
return Disposable {
EDT.assertIsEdt()
contentListeners.remove(listener)
}
}
private fun fireContentChanged() {
for (listener in contentListeners) {
listener.invoke()
}
}
private fun applyStateLater(request: DocumentationRequest, asyncData: Deferred<DocumentationData?>) {
// to avoid flickering: don't show ""Fetching..." message right away, give a chance for documentation to load
val fetchingMessage = cs.launch {
delay(DEFAULT_UI_RESPONSE_TIMEOUT)
fetchingProgress()
}
asyncData.invokeOnCompletion {
fetchingMessage.cancel()
}
cs.launch {
val data = try {
asyncData.await()
}
catch (e: IndexNotReadyException) {
null // normal situation, nothing to do
}
applyState(request, data)
}
}
private fun applyState(request: DocumentationRequest, data: DocumentationData?) {
icons.clear()
imageResolver = null
if (data == null) {
showMessage(CodeInsightBundle.message("no.documentation.found"))
return
}
imageResolver = data.imageResolver
val presentation = request.presentation
val locationChunk = getDefaultLocationChunk(presentation)
val linkChunk = linkChunk(presentation.presentableText, data)
val decorated = decorate(data.html, locationChunk, linkChunk)
val scrollingPosition = data.anchor?.let(ScrollingPosition::Anchor) ?: ScrollingPosition.Reset
update(decorated, scrollingPosition)
}
private fun getDefaultLocationChunk(presentation: TargetPresentation): HtmlChunk? {
return presentation.locationText?.let { locationText ->
presentation.locationIcon?.let { locationIcon ->
val iconKey = registerIcon(locationIcon)
HtmlChunk.fragment(
HtmlChunk.tag("icon").attr("src", iconKey),
HtmlChunk.nbsp(),
HtmlChunk.text(locationText)
)
} ?: HtmlChunk.text(locationText)
}
}
private fun registerIcon(icon: Icon): String {
val key = icons.size.toString()
icons[key] = icon
return key
}
private fun fetchingProgress() {
showMessage(CodeInsightBundle.message("javadoc.fetching.progress"))
}
private fun showMessage(message: @Nls String) {
val element = HtmlChunk.div()
.setClass("content-only")
.addText(message)
.wrapWith("body")
.wrapWith("html")
update(element.toString(), ScrollingPosition.Reset)
}
fun update(text: @Nls String, scrollingPosition: ScrollingPosition) {
EDT.assertIsEdt()
if (editorPane.text == text) {
return
}
editorPane.text = text
fireContentChanged()
SwingUtilities.invokeLater {
when (scrollingPosition) {
ScrollingPosition.Keep -> {
// do nothing
}
ScrollingPosition.Reset -> {
editorPane.scrollRectToVisible(Rectangle(0, 0))
if (ScreenReader.isActive()) {
editorPane.caretPosition = 0
}
}
is ScrollingPosition.Anchor -> {
UIUtil.scrollToReference(editorPane, scrollingPosition.anchor)
}
}
}
}
fun uiSnapshot(): UISnapshot {
val viewRect = scrollPane.viewport.viewRect
val highlightedLink = linkHandler.highlightedLink
return {
linkHandler.highlightLink(highlightedLink)
editorPane.scrollRectToVisible(viewRect)
if (ScreenReader.isActive()) {
editorPane.caretPosition = 0
}
}
}
}
| apache-2.0 | b971a54d33706402aa1be1dc36a9cadd | 32.382222 | 120 | 0.728531 | 4.58547 | false | false | false | false |
alibaba/p3c | idea-plugin/p3c-common/src/main/kotlin/com/alibaba/p3c/idea/pmd/SourceCodeProcessor.kt | 1 | 11050 | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package com.alibaba.p3c.idea.pmd
import com.alibaba.p3c.idea.component.AliProjectComponent.FileContext
import com.alibaba.p3c.idea.config.P3cConfig
import com.alibaba.p3c.idea.util.withLockNotInline
import com.alibaba.p3c.idea.util.withTryLock
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Document
import net.sourceforge.pmd.PMD
import net.sourceforge.pmd.PMDConfiguration
import net.sourceforge.pmd.PMDException
import net.sourceforge.pmd.RuleContext
import net.sourceforge.pmd.RuleSets
import net.sourceforge.pmd.benchmark.TimeTracker
import net.sourceforge.pmd.benchmark.TimedOperationCategory
import net.sourceforge.pmd.lang.Language
import net.sourceforge.pmd.lang.LanguageVersion
import net.sourceforge.pmd.lang.LanguageVersionHandler
import net.sourceforge.pmd.lang.Parser
import net.sourceforge.pmd.lang.ast.Node
import net.sourceforge.pmd.lang.ast.ParseException
import java.io.Reader
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.MILLISECONDS
class SourceCodeProcessor(
private val configuration: PMDConfiguration,
private val document: Document,
private val fileContext: FileContext,
private val isOnTheFly: Boolean
) {
/**
* Processes the input stream against a rule set using the given input
* encoding. If the LanguageVersion is `null` on the RuleContext,
* it will be automatically determined. Any code which wishes to process
* files for different Languages, will need to be sure to either properly
* set the Language on the RuleContext, or set it to `null`
* first.
*
* @see RuleContext.setLanguageVersion
* @see PMDConfiguration.getLanguageVersionOfFile
* @param sourceCode
* The Reader to analyze.
* @param ruleSets
* The collection of rules to process against the file.
* @param ctx
* The context in which PMD is operating.
* @throws PMDException
* if the input encoding is unsupported, the input stream could
* not be parsed, or other error is encountered.
*/
@Throws(PMDException::class)
fun processSourceCode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) {
determineLanguage(ctx)
try {
ruleSets.start(ctx)
processSource(sourceCode, ruleSets, ctx)
} catch (pe: ParseException) {
configuration.analysisCache.analysisFailed(ctx.sourceCodeFile)
throw PMDException("Error while parsing " + ctx.sourceCodeFilename, pe)
} catch (e: Exception) {
configuration.analysisCache.analysisFailed(ctx.sourceCodeFile)
throw PMDException("Error while processing " + ctx.sourceCodeFilename, e)
} finally {
ruleSets.end(ctx)
}
}
private fun parse(ctx: RuleContext, sourceCode: Reader, parser: Parser): Node {
TimeTracker.startOperation(TimedOperationCategory.PARSER).use {
val rootNode = parser.parse(ctx.sourceCodeFilename, sourceCode)
ctx.report.suppress(parser.suppressMap)
return rootNode
}
}
private fun getRootNode(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext): Node? {
if (!smartFoxConfig.astCacheEnable) {
return parseNode(ctx, ruleSets, sourceCode)
}
val node = getNode(ctx.sourceCodeFilename, isOnTheFly)
if (node != null) {
return node
}
if (document.lineCount > 3000 && isOnTheFly) {
return null
}
val lock = fileContext.lock
val readLock = lock.readLock()
val writeLock = lock.writeLock()
val ruleName = ruleSets.allRules.joinToString(",") { it.name }
val fileName = ctx.sourceCodeFilename
val readAction = {
getNode(ctx.sourceCodeFilename, isOnTheFly)
}
val cacheNode = if (isOnTheFly) {
readLock.withTryLock(50, MILLISECONDS, readAction)
} else {
val start = System.currentTimeMillis()
LOG.info("rule:$ruleName,file:$fileName require read lock")
readLock.withLockNotInline(readAction).also {
LOG.info("rule:$ruleName,file:$fileName get result $it with read lock ,elapsed ${System.currentTimeMillis() - start}")
}
}
if (cacheNode != null) {
return cacheNode
}
val writeAction = {
val finalNode = getNode(ctx.sourceCodeFilename, isOnTheFly)
if (finalNode == null) {
val start = System.currentTimeMillis()
if (!isOnTheFly) {
LOG.info("rule:$ruleName,file:$fileName parse with write lock")
}
parseNode(ctx, ruleSets, sourceCode).also {
if (!isOnTheFly) {
LOG.info("rule:$ruleName,file:$fileName get result $it parse with write lock ,elapsed ${System.currentTimeMillis() - start}")
}
}
} else {
finalNode
}
}
return if (isOnTheFly) {
writeLock.withTryLock(50, MILLISECONDS, writeAction)!!
} else {
writeLock.withLockNotInline(
writeAction
)!!
}
}
private fun parseNode(ctx: RuleContext, ruleSets: RuleSets, sourceCode: Reader): Node {
val languageVersion = ctx.languageVersion
val languageVersionHandler = languageVersion.languageVersionHandler
val parser = PMD.parserFor(languageVersion, configuration)
val rootNode = parse(ctx, sourceCode, parser)
symbolFacade(rootNode, languageVersionHandler)
val language = languageVersion.language
usesDFA(languageVersion, rootNode, ruleSets, language)
usesTypeResolution(languageVersion, rootNode, ruleSets, language)
onlyTheFlyCache.put(ctx.sourceCodeFilename, rootNode)
userTriggerNodeCache.put(ctx.sourceCodeFilename, rootNode)
return rootNode
}
private fun symbolFacade(rootNode: Node, languageVersionHandler: LanguageVersionHandler) {
TimeTracker.startOperation(TimedOperationCategory.SYMBOL_TABLE)
.use { languageVersionHandler.getSymbolFacade(configuration.classLoader).start(rootNode) }
}
private fun resolveQualifiedNames(rootNode: Node, handler: LanguageVersionHandler) {
TimeTracker.startOperation(TimedOperationCategory.QUALIFIED_NAME_RESOLUTION)
.use { handler.getQualifiedNameResolutionFacade(configuration.classLoader).start(rootNode) }
}
// private ParserOptions getParserOptions(final LanguageVersionHandler
// languageVersionHandler) {
// // TODO Handle Rules having different parser options.
// ParserOptions parserOptions =
// languageVersionHandler.getDefaultParserOptions();
// parserOptions.setSuppressMarker(configuration.getSuppressMarker());
// return parserOptions;
// }
private fun usesDFA(languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets, language: Language) {
if (ruleSets.usesDFA(language)) {
TimeTracker.startOperation(TimedOperationCategory.DFA).use { to ->
val dataFlowFacade = languageVersion.languageVersionHandler.dataFlowFacade
dataFlowFacade.start(rootNode)
}
}
}
private fun usesTypeResolution(
languageVersion: LanguageVersion, rootNode: Node, ruleSets: RuleSets,
language: Language
) {
if (ruleSets.usesTypeResolution(language)) {
TimeTracker.startOperation(TimedOperationCategory.TYPE_RESOLUTION).use { to ->
languageVersion.languageVersionHandler.getTypeResolutionFacade(configuration.classLoader)
.start(rootNode)
}
}
}
private fun usesMultifile(
rootNode: Node, languageVersionHandler: LanguageVersionHandler, ruleSets: RuleSets,
language: Language
) {
if (ruleSets.usesMultifile(language)) {
TimeTracker.startOperation(TimedOperationCategory.MULTIFILE_ANALYSIS)
.use { languageVersionHandler.multifileFacade.start(rootNode) }
}
}
private fun processSource(sourceCode: Reader, ruleSets: RuleSets, ctx: RuleContext) {
val languageVersion = ctx.languageVersion
val languageVersionHandler = languageVersion.languageVersionHandler
val rootNode = getRootNode(sourceCode, ruleSets, ctx) ?: return
resolveQualifiedNames(rootNode, languageVersionHandler)
symbolFacade(rootNode, languageVersionHandler)
val language = languageVersion.language
usesDFA(languageVersion, rootNode, ruleSets, language)
usesTypeResolution(languageVersion, rootNode, ruleSets, language)
usesMultifile(rootNode, languageVersionHandler, ruleSets, language)
val acus = listOf(rootNode)
ruleSets.apply(acus, ctx, language)
}
private fun determineLanguage(ctx: RuleContext) {
// If LanguageVersion of the source file is not known, make a
// determination
if (ctx.languageVersion == null) {
val languageVersion = configuration.getLanguageVersionOfFile(ctx.sourceCodeFilename)
ctx.languageVersion = languageVersion
}
}
companion object {
val smartFoxConfig = ServiceManager.getService(P3cConfig::class.java)!!
private lateinit var onlyTheFlyCache: Cache<String, Node>
private lateinit var userTriggerNodeCache: Cache<String, Node>
private val LOG = Logger.getInstance(SourceCodeProcessor::class.java)
init {
reInitNodeCache(smartFoxConfig.astCacheTime)
}
fun reInitNodeCache(expireTime: Long) {
onlyTheFlyCache = CacheBuilder.newBuilder().concurrencyLevel(16)
.expireAfterWrite(expireTime, TimeUnit.MILLISECONDS)
.maximumSize(300)
.build<String, Node>()!!
userTriggerNodeCache = CacheBuilder.newBuilder().concurrencyLevel(16)
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(300)
.build<String, Node>()!!
}
fun invalidateCache(file: String) {
onlyTheFlyCache.invalidate(file)
userTriggerNodeCache.invalidate(file)
}
fun invalidUserTrigger(file: String) {
userTriggerNodeCache.invalidate(file)
}
fun invalidateAll() {
onlyTheFlyCache.invalidateAll()
userTriggerNodeCache.invalidateAll()
}
fun getNode(file: String, isOnTheFly: Boolean): Node? {
return if (isOnTheFly) onlyTheFlyCache.getIfPresent(file) else userTriggerNodeCache.getIfPresent(file)
}
}
}
| apache-2.0 | 444c5ca2e739853026941511dd185abb | 39.625 | 149 | 0.671674 | 4.835886 | false | true | false | false |
ingokegel/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsCacheMapperImpl.kt | 4 | 1170 | // 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.gradleTooling.arguments
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import java.util.*
abstract class AbstractCompilerArgumentsCacheMapper protected constructor() :
AbstractCompilerArgumentsCacheAware(), CompilerArgumentsCacheMapper {
private var nextId = 0
final override var cacheByValueMap: HashMap<Int, String> = hashMapOf()
private var valueByCacheMap: HashMap<String, Int> = hashMapOf()
override fun cacheArgument(arg: String): Int {
if (checkCached(arg)) return valueByCacheMap.getValue(arg)
val retVal = nextId
nextId += 1
return retVal.also {
cacheByValueMap[it] = arg
valueByCacheMap[arg] = it
}
}
override fun checkCached(arg: String): Boolean = valueByCacheMap.containsKey(arg)
}
data class CompilerArgumentsCacheMapperImpl(override val cacheOriginIdentifier: Long = Random().nextLong()) :
AbstractCompilerArgumentsCacheMapper() {
}
| apache-2.0 | 21c906b4034f5ca8369582862642ebc8 | 40.785714 | 158 | 0.741026 | 4.642857 | false | false | false | false |
asarazan/Bismarck | bismarck/src/jvmMain/kotlin/net/sarazan/bismarck/platform/File.kt | 1 | 760 | package net.sarazan.bismarck.platform
import java.io.File as JavaFile
internal actual class File(private val file: JavaFile) {
actual constructor(path: String) : this(JavaFile(path))
actual constructor(parent: String, child: String) :
this(JavaFile(parent, child))
actual constructor(parent: File, child: String) :
this(JavaFile(parent.file, child))
actual val parentFile: File? get() = File(file.parentFile)
actual val exists: Boolean get() = file.exists()
actual fun delete() = file.delete()
actual fun mkdirs() = file.mkdirs()
actual fun createNewFile() = file.createNewFile()
actual fun readBytes() = file.readBytes()
actual fun writeBytes(bytes: ByteArray) = file.writeBytes(bytes)
}
| apache-2.0 | 3a4d6ff8c28aa6d20cafe3063a606493 | 32.043478 | 68 | 0.692105 | 4.198895 | false | false | false | false |
alisle/Penella | src/main/java/org/penella/codecs/JSONCodec.kt | 1 | 1770 | package org.penella.codecs
import io.vertx.core.buffer.Buffer
import io.vertx.core.eventbus.MessageCodec
import io.vertx.core.json.Json
import org.slf4j.LoggerFactory
/**
* 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.
*
* Created by alisle on 1/14/17.
*/
abstract class JSONCodec<T>(val clazz : Class<*> ) : MessageCodec<T, T> {
protected fun extractJSON(pos: Int, buffer: Buffer) : String {
val size = buffer!!.getInt(pos)
val bytesStart = pos + 4
val bytes = buffer.getBytes(bytesStart, bytesStart + size)
return bytes.toString(Charsets.UTF_8)
}
protected fun insertJSON(buffer: Buffer, json : String) {
val bytes = json.toByteArray(Charsets.UTF_8)
val size = bytes.size
buffer!!.appendInt(size)
buffer.appendBytes(bytes)
}
override fun transform(s: T?): T {
return s!!
}
override fun systemCodecID(): Byte {
return -1
}
override fun decodeFromWire(pos: Int, buffer: Buffer?): T {
val json = extractJSON(pos, buffer!!)
return Json.decodeValue(json, clazz) as T
}
override fun encodeToWire(buffer: Buffer?, s: T) {
insertJSON(buffer!!, Json.encode(s))
}
abstract override fun name(): String
}
| apache-2.0 | 148e5db0d9d48bc56ee2faccaa209640 | 28.5 | 75 | 0.672316 | 3.907285 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/joinToStringViaBuilder.kt | 9 | 180 | // WITH_STDLIB
val x = listOf(1, 2, 3).<caret>map {
val sb = StringBuilder()
sb.append(it).append(" + ").append(it)
sb
}.joinToString(prefix = "= ", separator = " + ") | apache-2.0 | b392728aee23af7cec80a8c4007bf14f | 24.857143 | 48 | 0.566667 | 3.157895 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/KotlinElementActionsFactory.kt | 1 | 27775 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInsight.intention.QuickFixFactory
import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo
import com.intellij.lang.java.beans.PropertyKind
import com.intellij.lang.jvm.*
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl
import com.intellij.psi.util.PropertyUtil
import com.intellij.psi.util.PropertyUtilBase
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade
import org.jetbrains.kotlin.asJava.classes.KtLightClassForSourceDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.appendModifier
import org.jetbrains.kotlin.idea.quickfix.AddModifierFixFE10
import org.jetbrains.kotlin.idea.quickfix.MakeFieldPublicFix
import org.jetbrains.kotlin.idea.quickfix.MakeMemberStaticFix
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFixBase
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.resolveToKotlinType
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class KotlinElementActionsFactory : JvmElementActionsFactory() {
companion object {
val javaPsiModifiersMapping = mapOf(
JvmModifier.PRIVATE to KtTokens.PRIVATE_KEYWORD,
JvmModifier.PUBLIC to KtTokens.PUBLIC_KEYWORD,
JvmModifier.PROTECTED to KtTokens.PUBLIC_KEYWORD,
JvmModifier.ABSTRACT to KtTokens.ABSTRACT_KEYWORD
)
internal fun ExpectedTypes.toKotlinTypeInfo(resolutionFacade: ResolutionFacade): TypeInfo {
val candidateTypes = flatMapTo(LinkedHashSet()) {
val ktType = (it.theType as? PsiType)?.resolveToKotlinType(resolutionFacade) ?: return@flatMapTo emptyList()
when (it.theKind) {
ExpectedType.Kind.EXACT, ExpectedType.Kind.SUBTYPE -> listOf(ktType)
ExpectedType.Kind.SUPERTYPE -> listOf(ktType) + ktType.supertypes()
}
}
if (candidateTypes.isEmpty()) {
val nullableAnyType = resolutionFacade.moduleDescriptor.builtIns.nullableAnyType
return TypeInfo(nullableAnyType, Variance.INVARIANT)
}
return TypeInfo.ByExplicitCandidateTypes(candidateTypes.toList())
}
}
private class FakeExpressionFromParameter(private val psiParam: PsiParameter) : PsiReferenceExpressionImpl() {
override fun getText(): String = psiParam.name
override fun getProject(): Project = psiParam.project
override fun getParent(): PsiElement = psiParam.parent
override fun getType(): PsiType = psiParam.type
override fun isValid(): Boolean = true
override fun getContainingFile(): PsiFile = psiParam.containingFile
override fun getReferenceName(): String = psiParam.name
override fun resolve(): PsiElement = psiParam
}
internal class ModifierBuilder(
private val targetContainer: KtElement,
private val allowJvmStatic: Boolean = true
) {
private val psiFactory = KtPsiFactory(targetContainer.project)
val modifierList = psiFactory.createEmptyModifierList()
private fun JvmModifier.transformAndAppend(): Boolean {
javaPsiModifiersMapping[this]?.let {
modifierList.appendModifier(it)
return true
}
when (this) {
JvmModifier.STATIC -> {
if (allowJvmStatic && targetContainer is KtClassOrObject) {
addAnnotation(JVM_STATIC_ANNOTATION_FQ_NAME)
}
}
JvmModifier.ABSTRACT -> modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD)
JvmModifier.FINAL -> modifierList.appendModifier(KtTokens.FINAL_KEYWORD)
else -> return false
}
return true
}
var isValid = true
private set
fun addJvmModifier(modifier: JvmModifier) {
isValid = isValid && modifier.transformAndAppend()
}
fun addJvmModifiers(modifiers: Iterable<JvmModifier>) {
modifiers.forEach { addJvmModifier(it) }
}
fun addAnnotation(fqName: FqName) {
if (!isValid) return
modifierList.add(psiFactory.createAnnotationEntry("@${fqName.asString()}"))
}
}
private fun JvmClass.toKtClassOrFile(): KtElement? = when (val psi = sourceElement) {
is KtClassOrObject -> psi
is KtLightClassForSourceDeclaration -> psi.kotlinOrigin
is KtLightClassForFacade -> psi.files.firstOrNull()
else -> null
}
private inline fun <reified T : KtElement> JvmElement.toKtElement() = sourceElement?.unwrapped as? T
private fun fakeParametersExpressions(parameters: List<ExpectedParameter>, project: Project): Array<PsiExpression>? = when {
parameters.isEmpty() -> emptyArray()
else -> JavaPsiFacade
.getElementFactory(project)
.createParameterList(
parameters.map { it.semanticNames.firstOrNull() }.toTypedArray(),
parameters.map { param ->
param.expectedTypes.firstOrNull()?.theType?.let { type ->
JvmPsiConversionHelper.getInstance(project).convertType(type)
} ?: return null
}.toTypedArray()
)
.parameters
.map(::FakeExpressionFromParameter)
.toTypedArray()
}
override fun createChangeOverrideActions(target: JvmModifiersOwner, shouldBePresent: Boolean): List<IntentionAction> {
val kModifierOwner = target.toKtElement<KtModifierListOwner>() ?: return emptyList()
return createChangeModifierActions(kModifierOwner, KtTokens.OVERRIDE_KEYWORD, shouldBePresent)
}
override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> {
val kModifierOwner = target.toKtElement<KtModifierListOwner>() ?: return emptyList()
val modifier = request.modifier
val shouldPresent = request.shouldBePresent()
if (modifier == JvmModifier.PUBLIC && shouldPresent && kModifierOwner is KtProperty) {
return listOf(MakeFieldPublicFix(kModifierOwner))
}
if (modifier == JvmModifier.STATIC && shouldPresent && kModifierOwner is KtNamedDeclaration) {
return listOf(MakeMemberStaticFix(kModifierOwner))
}
//TODO: make similar to `createAddMethodActions`
val (kToken, shouldPresentMapped) = when {
modifier == JvmModifier.FINAL -> KtTokens.OPEN_KEYWORD to !shouldPresent
modifier == JvmModifier.PUBLIC && shouldPresent ->
kModifierOwner.visibilityModifierType()
?.takeIf { it != KtTokens.DEFAULT_VISIBILITY_KEYWORD }
?.let { it to false } ?: return emptyList()
else -> javaPsiModifiersMapping[modifier] to shouldPresent
}
if (kToken == null) return emptyList()
return createChangeModifierActions(kModifierOwner, kToken, shouldPresentMapped)
}
private fun createChangeModifierActions(
modifierListOwners: KtModifierListOwner,
token: KtModifierKeywordToken,
shouldBePresent: Boolean
): List<IntentionAction> {
val action = if (shouldBePresent) {
AddModifierFixFE10.createIfApplicable(modifierListOwners, token)
} else {
RemoveModifierFixBase(modifierListOwners, token, false)
}
return listOfNotNull(action)
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val targetKtClass =
targetClass.toKtClassOrFile().safeAs<KtClass>() ?: return emptyList()
val modifierBuilder = ModifierBuilder(targetKtClass).apply { addJvmModifiers(request.modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val parameters = request.expectedParameters
val needPrimary = !targetKtClass.hasExplicitPrimaryConstructor()
val targetClassName = targetClass.name
val addConstructorAction = AddConstructorCreateCallableFromUsageFix(
request = request,
modifierList = modifierBuilder.modifierList,
familyName = KotlinBundle.message("add.method"),
providedText = KotlinBundle.message(
"add.0.constructor.to.1",
if (needPrimary) KotlinBundle.message("text.primary") else KotlinBundle.message("text.secondary"),
targetClassName.toString()
),
targetKtClass = targetKtClass
)
val changePrimaryConstructorAction = run {
val primaryConstructor = targetKtClass.primaryConstructor ?: return@run null
val lightMethod = primaryConstructor.toLightMethods().firstOrNull() ?: return@run null
val project = targetKtClass.project
val fakeParametersExpressions = fakeParametersExpressions(parameters, project) ?: return@run null
QuickFixFactory.getInstance().createChangeMethodSignatureFromUsageFix(
lightMethod,
fakeParametersExpressions,
PsiSubstitutor.EMPTY,
targetKtClass,
false,
2
).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) }
}
return listOfNotNull(changePrimaryConstructorAction, addConstructorAction)
}
private fun createAddPropertyActions(
targetContainer: KtElement,
modifiers: Iterable<JvmModifier>,
propertyType: JvmType,
propertyName: String,
setterRequired: Boolean,
classOrFileName: String?
): List<IntentionAction> {
val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val action = AddPropertyActionCreateCallableFromUsageFix(
targetContainer = targetContainer,
modifierList = modifierBuilder.modifierList,
propertyType = propertyType,
propertyName = propertyName,
setterRequired = setterRequired,
isLateinitPreferred = false,
classOrFileName = classOrFileName
)
val actions = if (setterRequired) {
listOf(
action, AddPropertyActionCreateCallableFromUsageFix(
targetContainer = targetContainer,
modifierList = modifierBuilder.modifierList,
propertyType = propertyType,
propertyName = propertyName,
setterRequired = true,
classOrFileName = classOrFileName
)
)
} else {
listOf(action)
}
return actions
}
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList()
val writable = JvmModifier.FINAL !in request.modifiers && !request.isConstant
val action = AddFieldActionCreateCallableFromUsageFix(
targetContainer = targetContainer, classOrFileName = targetClass.name, request = request, lateinit = false
)
val actions = if (writable) {
listOf(
action,
AddFieldActionCreateCallableFromUsageFix(
targetContainer = targetContainer, classOrFileName = targetClass.name, request = request, lateinit = true
)
)
} else {
listOf(action)
}
return actions
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val targetContainer = targetClass.toKtClassOrFile() ?: return emptyList()
val modifierBuilder = ModifierBuilder(targetContainer).apply { addJvmModifiers(request.modifiers) }
if (!modifierBuilder.isValid) return emptyList()
val methodName = request.methodName
val targetClassName = targetClass.name
val nameAndKind = PropertyUtilBase.getPropertyNameAndKind(methodName)
if (nameAndKind != null) {
val setterRequired = nameAndKind.second == PropertyKind.SETTER
val expectedParameters = request.expectedParameters
val returnTypes = request.returnType
fun getCreatedPropertyType(): ExpectedType? {
if (setterRequired) {
val jvmPsiConversionHelper = JvmPsiConversionHelper.getInstance(targetContainer.project)
if (returnTypes.any { jvmPsiConversionHelper.convertType(it.theType) != PsiType.VOID }) return null
val expectedParameter = expectedParameters.singleOrNull() ?: return null
return expectedParameter.expectedTypes.firstOrNull()
} else if (expectedParameters.isEmpty()) {
return returnTypes.firstOrNull()
} else {
return null
}
}
val propertyType = getCreatedPropertyType()
if (propertyType != null) {
return createAddPropertyActions(
targetContainer,
request.modifiers,
propertyType.theType,
nameAndKind.first,
setterRequired,
targetClass.name
)
}
}
val addMethodAction = AddMethodCreateCallableFromUsageFix(
request = request,
modifierList = modifierBuilder.modifierList,
familyName = KotlinBundle.message("add.method"),
providedText = KotlinBundle.message("add.method.0.to.1", methodName, targetClassName.toString()),
targetContainer = targetContainer
)
return listOf(addMethodAction)
}
override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> {
val declaration = target.safeAs<KtLightElement<*, *>>()?.kotlinOrigin.safeAs<KtModifierListOwner>()?.takeIf {
it.language == KotlinLanguage.INSTANCE
} ?: return emptyList()
val annotationUseSiteTarget = when (target) {
is JvmField -> AnnotationUseSiteTarget.FIELD
is JvmMethod -> when {
PropertyUtil.isSimplePropertySetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_SETTER
PropertyUtil.isSimplePropertyGetter(target as? PsiMethod) -> AnnotationUseSiteTarget.PROPERTY_GETTER
else -> null
}
else -> null
}
return listOf(CreateAnnotationAction(declaration, annotationUseSiteTarget, request))
}
private class CreateAnnotationAction(
target: KtModifierListOwner,
val annotationTarget: AnnotationUseSiteTarget?,
val request: AnnotationRequest
) : IntentionAction {
private val pointer = target.createSmartPointer()
override fun startInWriteAction(): Boolean = true
override fun getText(): String = QuickFixBundle.message("create.annotation.text", StringUtilRt.getShortName(request.qualifiedName))
override fun getFamilyName(): String = QuickFixBundle.message("create.annotation.family")
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
PsiTreeUtil.findSameElementInCopy(pointer.element, file)?.addAnnotation()
return IntentionPreviewInfo.DIFF
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
pointer.element?.addAnnotation() ?: return
}
private fun KtModifierListOwner.addAnnotation() {
val entry = addAnnotationEntry(this, request, annotationTarget)
ShortenReferences.DEFAULT.process(entry)
}
}
override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> {
return when (val kotlinOrigin = (target as? KtLightElement<*, *>)?.kotlinOrigin) {
is KtNamedFunction -> listOfNotNull(ChangeMethodParameters.create(kotlinOrigin, request))
is KtConstructor<*> -> kotlinOrigin.containingClass()?.let {
createChangeConstructorParametersAction(kotlinOrigin, it, request)
} ?: emptyList()
is KtClass -> createChangeConstructorParametersAction(kotlinOrigin, kotlinOrigin, request)
else -> emptyList()
}
}
private fun createChangeConstructorParametersAction(kotlinOrigin: PsiElement,
targetKtClass: KtClass,
request: ChangeParametersRequest): List<IntentionAction> {
return listOfNotNull(run {
val lightMethod = kotlinOrigin.toLightMethods().firstOrNull() ?: return@run null
val project = kotlinOrigin.project
val fakeParametersExpressions = fakeParametersExpressions(request.expectedParameters, project) ?: return@run null
QuickFixFactory.getInstance().createChangeMethodSignatureFromUsageFix(
lightMethod,
fakeParametersExpressions,
PsiSubstitutor.EMPTY,
targetKtClass,
false,
2
).takeIf { it.isAvailable(project, null, targetKtClass.containingFile) }
})
}
override fun createChangeTypeActions(target: JvmMethod, request: ChangeTypeRequest): List<IntentionAction> {
val ktCallableDeclaration = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtCallableDeclaration ?: return emptyList()
return listOfNotNull(ChangeType(ktCallableDeclaration, request))
}
override fun createChangeTypeActions(target: JvmParameter, request: ChangeTypeRequest): List<IntentionAction> {
val ktCallableDeclaration = (target as? KtLightElement<*, *>)?.kotlinOrigin as? KtCallableDeclaration ?: return emptyList()
return listOfNotNull(ChangeType(ktCallableDeclaration, request))
}
private class ChangeType(
target: KtCallableDeclaration,
private val request: ChangeTypeRequest
) : IntentionAction {
private val pointer = target.createSmartPointer()
override fun startInWriteAction(): Boolean = true
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = pointer.element != null && request.isValid
override fun getText(): String {
if (pointer.element == null || !request.isValid) return KotlinBundle.message("fix.change.signature.unavailable")
val typeName = request.qualifiedName
if (typeName == null) return familyName
return QuickFixBundle.message("change.type.text", request.qualifiedName)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.type.family")
override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo {
doChangeType(PsiTreeUtil.findSameElementInCopy(pointer.element ?: return IntentionPreviewInfo.EMPTY, file))
return IntentionPreviewInfo.DIFF
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile) {
if (!request.isValid) return
doChangeType(pointer.element ?: return)
}
private fun doChangeType(target: KtCallableDeclaration) {
val oldType = target.typeReference
val typeName = primitiveTypeMapping.getOrDefault(request.qualifiedName, request.qualifiedName ?: target.typeName() ?: return)
val psiFactory = KtPsiFactory(target.project)
val annotations = request.annotations.joinToString(" ") { "@${renderAnnotation(target, it, psiFactory)}" }
val newType = psiFactory.createType("$annotations $typeName".trim())
target.typeReference = newType
if (oldType != null) {
val commentSaver = CommentSaver(oldType)
commentSaver.restore(target.typeReference!!)
}
ShortenReferences.DEFAULT.process(target)
}
private fun KtCallableDeclaration.typeName(): String? {
val typeReference = this.typeReference
if (typeReference != null) return typeReference.typeElement?.text
if (this !is KtNamedFunction) return null
val descriptor = this.resolveToDescriptorIfAny() as? CallableDescriptor ?: return null
val returnType = descriptor.returnType ?: return null
return IdeDescriptorRenderers.SOURCE_CODE.renderType(returnType)
}
companion object {
private val primitiveTypeMapping = mapOf(
PsiType.VOID.name to "kotlin.Unit",
PsiType.BOOLEAN.name to "kotlin.Boolean",
PsiType.BYTE.name to "kotlin.Byte",
PsiType.CHAR.name to "kotlin.Char",
PsiType.SHORT.name to "kotlin.Short",
PsiType.INT.name to "kotlin.Int",
PsiType.FLOAT.name to "kotlin.Float",
PsiType.LONG.name to "kotlin.Long",
PsiType.DOUBLE.name to "kotlin.Double",
"${PsiType.BOOLEAN.name}[]" to "kotlin.BooleanArray",
"${PsiType.BYTE.name}[]" to "kotlin.ByteArray",
"${PsiType.CHAR.name}[]" to "kotlin.CharArray",
"${PsiType.SHORT.name}[]" to "kotlin.ShortArray",
"${PsiType.INT.name}[]" to "kotlin.IntArray",
"${PsiType.FLOAT.name}[]" to "kotlin.FloatArray",
"${PsiType.LONG.name}[]" to "kotlin.LongArray",
"${PsiType.DOUBLE.name}[]" to "kotlin.DoubleArray"
)
}
}
}
internal fun addAnnotationEntry(
target: KtModifierListOwner,
request: AnnotationRequest,
annotationTarget: AnnotationUseSiteTarget?
): KtAnnotationEntry {
val annotationUseSiteTargetPrefix = run prefixEvaluation@{
if (annotationTarget == null) return@prefixEvaluation ""
val moduleDescriptor = (target as? KtDeclaration)?.resolveToDescriptorIfAny()?.module ?: return@prefixEvaluation ""
val annotationClassDescriptor = moduleDescriptor.resolveClassByFqName(
FqName(request.qualifiedName), NoLookupLocation.FROM_IDE
) ?: return@prefixEvaluation ""
val applicableTargetSet = AnnotationChecker.applicableTargetSet(annotationClassDescriptor)
if (KotlinTarget.PROPERTY !in applicableTargetSet) return@prefixEvaluation ""
"${annotationTarget.renderName}:"
}
val psiFactory = KtPsiFactory(target.project)
// could be generated via descriptor when KT-30478 is fixed
val annotationText = '@' + annotationUseSiteTargetPrefix + renderAnnotation(target, request, psiFactory)
return target.addAnnotationEntry(psiFactory.createAnnotationEntry(annotationText))
}
private fun renderAnnotation(target: PsiElement, request: AnnotationRequest, psiFactory: KtPsiFactory): String {
val javaPsiFacade = JavaPsiFacade.getInstance(target.project)
fun isKotlinAnnotation(annotation: AnnotationRequest): Boolean =
javaPsiFacade.findClass(annotation.qualifiedName, target.resolveScope)?.language == KotlinLanguage.INSTANCE
return renderAnnotation(request, psiFactory, ::isKotlinAnnotation)
}
private fun renderAnnotation(
request: AnnotationRequest,
psiFactory: KtPsiFactory,
isKotlinAnnotation: (AnnotationRequest) -> Boolean
): String {
return "${request.qualifiedName}${
request.attributes.takeIf { it.isNotEmpty() }?.mapIndexed { i, p ->
if (!isKotlinAnnotation(request) && i == 0 && p.name == "value")
renderAttributeValue(p.value, psiFactory, isKotlinAnnotation, isVararg = true)
else
"${p.name} = ${renderAttributeValue(p.value, psiFactory, isKotlinAnnotation)}"
}?.joinToString(", ", "(", ")") ?: ""
}"
}
private fun renderAttributeValue(
annotationAttributeRequest: AnnotationAttributeValueRequest,
psiFactory: KtPsiFactory,
isKotlinAnnotation: (AnnotationRequest) -> Boolean,
isVararg: Boolean = false,
): String =
when (annotationAttributeRequest) {
is AnnotationAttributeValueRequest.PrimitiveValue -> annotationAttributeRequest.value.toString()
is AnnotationAttributeValueRequest.StringValue -> "\"" + annotationAttributeRequest.value + "\""
is AnnotationAttributeValueRequest.ClassValue -> annotationAttributeRequest.classFqn + "::class"
is AnnotationAttributeValueRequest.ConstantValue -> annotationAttributeRequest.text
is AnnotationAttributeValueRequest.NestedAnnotation ->
renderAnnotation(annotationAttributeRequest.annotationRequest, psiFactory, isKotlinAnnotation)
is AnnotationAttributeValueRequest.ArrayValue -> {
val (prefix, suffix) = if (isVararg) "" to "" else "[" to "]"
annotationAttributeRequest.members.joinToString(", ", prefix, suffix) { memberRequest ->
renderAttributeValue(memberRequest, psiFactory, isKotlinAnnotation)
}
}
}
| apache-2.0 | cd4ed4e9969844686661072532493662 | 45.524288 | 139 | 0.674491 | 5.670682 | false | false | false | false |
androidx/androidx | paging/integration-tests/testapp/src/main/java/androidx/paging/integration/testapp/custom/PagedListSampleActivity.kt | 3 | 3232 | /*
* Copyright 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 androidx.paging.integration.testapp.custom
import android.os.Bundle
import android.widget.Button
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.paging.LoadState
import androidx.paging.LoadState.Error
import androidx.paging.LoadState.Loading
import androidx.paging.LoadState.NotLoading
import androidx.paging.LoadType
import androidx.paging.integration.testapp.R
import androidx.paging.integration.testapp.v3.StateItemAdapter
import androidx.recyclerview.widget.RecyclerView
/**
* Sample PagedList activity with artificial data source.
*/
class PagedListSampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
val viewModel by viewModels<PagedListItemViewModel>()
val pagingAdapter = PagedListItemAdapter()
val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
recyclerView.adapter = pagingAdapter.withLoadStateHeaderAndFooter(
header = StateItemAdapter { pagingAdapter.currentList?.retry() },
footer = StateItemAdapter { pagingAdapter.currentList?.retry() }
)
@Suppress("DEPRECATION")
viewModel.livePagedList.observe(this) { pagedList ->
pagingAdapter.submitList(pagedList)
}
setupLoadStateButtons(viewModel, pagingAdapter)
findViewById<Button>(R.id.button_error).setOnClickListener {
dataSourceError.set(true)
}
}
private fun setupLoadStateButtons(
viewModel: PagedListItemViewModel,
@Suppress("DEPRECATION")
adapter: androidx.paging.PagedListAdapter<Item, RecyclerView.ViewHolder>
) {
val button = findViewById<Button>(R.id.button_refresh)
button.setOnClickListener {
viewModel.invalidateList()
}
adapter.addLoadStateListener { type: LoadType, state: LoadState ->
if (type != LoadType.REFRESH) return@addLoadStateListener
when (state) {
is NotLoading -> {
button.text = if (state.endOfPaginationReached) "Refresh" else "Done"
button.isEnabled = state.endOfPaginationReached
}
Loading -> {
button.text = "Loading"
button.isEnabled = false
}
is Error -> {
button.text = "Error"
button.isEnabled = true
}
}
}
}
}
| apache-2.0 | 84f65285dd554322ea5a47f943902230 | 34.911111 | 89 | 0.673267 | 4.987654 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/core/src/org/jetbrains/completion/full/line/ProposalTransformer.kt | 2 | 1664 | package org.jetbrains.completion.full.line
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.completion.full.line.language.FullLineLanguageSupporter
// Transforms FL proposals at very first step of pipeline
fun interface ProposalTransformer {
fun transform(proposal: RawFullLineProposal): RawFullLineProposal
companion object {
fun identity(): ProposalTransformer {
return ProposalTransformer { proposal -> proposal }
}
fun firstToken(supporter: FullLineLanguageSupporter): ProposalTransformer {
return ProposalTransformer {
val firstToken = supporter.getFirstToken(it.suggestion)
if (firstToken != null) it.withSuggestion(firstToken) else it
}
}
fun reformatCode(
supporter: FullLineLanguageSupporter,
file: PsiFile,
offset: Int,
prefix: String
): ProposalTransformer = ProposalTransformer { proposal ->
val fileText = file.text
val beforeSuggestion = fileText
.take(offset - prefix.length)
.filterNot { it.isWhitespace() }
.length
val psi = supporter.createCodeFragment(file, fileText.take(offset - prefix.length) + proposal.suggestion, false)
?: return@ProposalTransformer proposal
var currentNotWhitespaces = 0
val formattedSuggestion = CodeStyleManager.getInstance(file.project)
.reformat(psi, true).text
.dropWhile {
if (!it.isWhitespace()) {
currentNotWhitespaces++
}
currentNotWhitespaces <= beforeSuggestion
}
proposal.withSuggestion(formattedSuggestion)
}
}
}
| apache-2.0 | b043a6505bfe9cf0f799202367fdde13 | 32.959184 | 118 | 0.697115 | 5.135802 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/configuration/utils/utils.kt | 1 | 2328 | // 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.core.script.configuration.utils
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper
import kotlin.script.experimental.api.*
import kotlin.script.experimental.jvm.impl.toClassPathOrEmpty
import kotlin.script.experimental.jvm.jdkHome
import kotlin.script.experimental.jvm.jvm
fun Project.getKtFile(virtualFile: VirtualFile?, ktFile: KtFile? = null): KtFile? {
if (virtualFile == null) return null
if (ktFile != null) {
check(ktFile.originalFile.virtualFile == virtualFile)
return ktFile
} else {
return runReadAction { PsiManager.getInstance(this).findFile(virtualFile) as? KtFile }
}
}
/**
* For using in DefaultScriptConfigurationManager and in tests only
*/
fun areSimilar(old: ScriptCompilationConfigurationWrapper, new: ScriptCompilationConfigurationWrapper): Boolean {
if (old.script != new.script) return false
val oldConfig = old.configuration
val newConfig = new.configuration
if (oldConfig == newConfig) return true
if (oldConfig == null || newConfig == null) return false
if (oldConfig[ScriptCompilationConfiguration.jvm.jdkHome] != newConfig[ScriptCompilationConfiguration.jvm.jdkHome]) return false
// there is differences how script definition classpath is added to script classpath in old and new scripting API,
// so it's important to compare the resulting classpath list, not only the value of key
if (oldConfig[ScriptCompilationConfiguration.dependencies].toClassPathOrEmpty() != newConfig[ScriptCompilationConfiguration.dependencies].toClassPathOrEmpty()) return false
if (oldConfig[ScriptCompilationConfiguration.ide.dependenciesSources] != newConfig[ScriptCompilationConfiguration.ide.dependenciesSources]) return false
if (oldConfig[ScriptCompilationConfiguration.defaultImports] != newConfig[ScriptCompilationConfiguration.defaultImports]) return false
return true
} | apache-2.0 | 09f3735863c9cb64b006fa9b354bf9ff | 47.520833 | 176 | 0.791237 | 5.006452 | false | true | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/dataclass/EntryComment.kt | 1 | 803 | package io.github.feelfreelinux.wykopmobilny.models.dataclass
import io.github.feelfreelinux.wykopmobilny.utils.toPrettyDate
class EntryComment(
val id: Int,
var entryId: Int,
val author: Author,
var body: String,
val fullDate: String,
var isVoted: Boolean,
var embed: Embed?,
var voteCount: Int,
val app: String?,
val violationUrl: String,
var isNsfw: Boolean = false,
var isBlocked: Boolean = false
) {
override fun equals(other: Any?): Boolean {
return if (other !is EntryComment) false
else (other.id == id)
}
override fun hashCode(): Int {
return id
}
val url: String
get() = "https://www.wykop.pl/wpis/$entryId/#comment-$id"
val date: String
get() = this.fullDate.toPrettyDate()
} | mit | 18cd49a18154a5009df6bcbe2ae03575 | 23.363636 | 65 | 0.6401 | 3.917073 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/inline/namedFunction/fromKotlinToJava/removeOverrideInChild.kt | 12 | 797 | open class A {
open fun <caret>a() = Unit
fun ds() = a()
}
open class B: A() {
override fun a() = Unit
fun c() = a()
}
open class B2: A() {
override fun a() = Unit
fun c() = a()
}
class B3 : A() {
final override fun a() = Unit
}
class C : B() {
override fun a() = Unit
}
class C2 : B() {
override fun a() = Unit
}
interface KotlinInterface {
fun a()
}
open class B3: A(), KotlinInterface {
override fun a() = Unit
}
interface NextKotlinInterface : KotlinInterface
open class B4: A(), NextKotlinInterface {
override fun a() = Unit
}
abstract class B5 : A() {
abstract override fun a()
}
class C3 : B5() {
override fun a() = Unit
}
class C4 : B5() {
final override fun a() = Unit
}
class B6 : A() {
final fun a() = Unit
}
| apache-2.0 | c6772177647461d9926900843cb2d247 | 13.232143 | 47 | 0.560853 | 2.996241 | false | false | false | false |
smmribeiro/intellij-community | platform/statistics/devkit/src/com/intellij/internal/statistic/devkit/actions/OpenEventsSchemeFileAction.kt | 3 | 2644 | // 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.internal.statistic.devkit.actions
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil
import com.intellij.internal.statistic.devkit.StatisticsDevKitUtil.showNotification
import com.intellij.internal.statistic.eventLog.validator.storage.persistence.BaseEventLogMetadataPersistence
import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventLogMetadataPersistence
import com.intellij.internal.statistic.eventLog.validator.storage.persistence.EventLogMetadataSettingsPersistence
import com.intellij.internal.statistic.utils.StatisticsRecorderUtil
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import java.nio.file.Path
internal class OpenEventsSchemeFileAction(private val recorderId: String = StatisticsDevKitUtil.DEFAULT_RECORDER)
: DumbAwareAction(StatisticsBundle.message("stats.open.0.scheme.file", recorderId),
ActionsBundle.message("group.OpenEventsSchemeFileAction.description"),
AllIcons.FileTypes.Config) {
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = StatisticsRecorderUtil.isTestModeEnabled(recorderId)
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
openFileInEditor(getEventsSchemeFile(recorderId), project)
}
companion object {
fun openFileInEditor(file: Path, project: Project) {
val virtualFile = VfsUtil.findFile(file, true)
if (virtualFile == null) {
showNotification(project, NotificationType.WARNING, StatisticsBundle.message("stats.file.0.does.not.exist", file.toString()))
return
}
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
fun getEventsSchemeFile(recorderId: String): Path {
val settings = EventLogMetadataSettingsPersistence.getInstance().getPathSettings(recorderId)
return if (settings != null && settings.isUseCustomPath) {
Path.of(settings.customPath)
}
else {
BaseEventLogMetadataPersistence.getDefaultMetadataFile(recorderId, EventLogMetadataPersistence.EVENTS_SCHEME_FILE, null)
}
}
}
} | apache-2.0 | ff99bdfc9367ece997244c196141107f | 47.981481 | 133 | 0.793116 | 4.833638 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/arguments/CompilerArgumentsCacheMapperImpl.kt | 1 | 1269 | // 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.gradleTooling.arguments
import org.jetbrains.kotlin.idea.projectModel.CompilerArgumentsCacheMapper
import java.util.*
import kotlin.random.Random
abstract class AbstractCompilerArgumentsCacheMapper protected constructor() :
AbstractCompilerArgumentsCacheAware(), CompilerArgumentsCacheMapper {
protected abstract val offset: Int
private var nextId = 0
final override var cacheByValueMap: HashMap<Int, String> = hashMapOf()
var valueByCacheMap: HashMap<String, Int> = hashMapOf()
override fun cacheArgument(arg: String): Int {
if (checkCached(arg)) return valueByCacheMap.getValue(arg)
val retVal = offset + nextId
nextId += 1
return retVal.also {
cacheByValueMap[it] = arg
valueByCacheMap[arg] = it
}
}
override fun checkCached(arg: String): Boolean = valueByCacheMap.containsKey(arg)
}
data class CompilerArgumentsCacheMapperImpl(override val cacheOriginIdentifier: Long = Random.nextLong()) :
AbstractCompilerArgumentsCacheMapper() {
override val offset: Int = 0
}
| apache-2.0 | e49156d2ae1078a96aded752cc110937 | 39.935484 | 158 | 0.740741 | 4.614545 | false | false | false | false |
kevinmost/koolbelt | core/src/main/java/com/kevinmost/koolbelt/extension/IterableUtil.kt | 2 | 2506 | package com.kevinmost.koolbelt.extension
/**
* Invokes [block] upon each individual sublist that is chunked out from every [n] elements in this
* [Iterable].
*
* @param [useLeftoversAtEnd] whether or not to use any remaining elements at the end of the list
* that do not divide evenly into [n].
*/
@JvmOverloads
inline fun <T> Iterable<T>.every(
n: Int,
useLeftoversAtEnd: Boolean = true,
block: (List<T>) -> Unit) {
var currentList = mutableListOfSize<T>(n)
for (element in this) {
if (currentList.size == n) {
block(currentList)
currentList = mutableListOfSize(n)
}
currentList.add(element)
}
if (useLeftoversAtEnd && currentList.isNotEmpty()) {
block(currentList)
}
}
// Optimized version of the above function that lets you take sublists instead of iterating through
@JvmOverloads
inline fun <T> List<T>.every(
n: Int,
useLeftoversAtEnd: Boolean = true,
block: (List<T>) -> Unit) {
var currentStartingIndex = 0
var currentEndingIndex = n
while (currentEndingIndex < size) {
block(this[currentStartingIndex..currentEndingIndex])
currentStartingIndex += n
currentEndingIndex += n
}
if (useLeftoversAtEnd) {
val leftovers = this[currentStartingIndex..size]
if (leftovers.isNotEmpty()) {
block(leftovers)
}
}
}
/**
* Collects individual sublists of size [n] from the receiver [Iterable].
*
* @param [useLeftoversAtEnd] whether or not to use any remaining elements at the end of the list
* that do not divide evenly into [n].
*/
@JvmOverloads
fun <T> Iterable<T>.splitEvery(n: Int, useLeftoversAtEnd: Boolean = true): List<List<T>> {
val result = mutableListOf<List<T>>()
every(n = n, useLeftoversAtEnd = useLeftoversAtEnd) { result.add(it) }
return result
}
// Optimized version of the above function that lets you take sublists instead of iterating through
@JvmOverloads
fun <T> List<T>.splitEvery(n: Int, useLeftoversAtEnd: Boolean = true): List<List<T>> {
val result = mutableListOf<List<T>>()
every(n = n, useLeftoversAtEnd = useLeftoversAtEnd) { result.add(it) }
return result
}
inline fun <T> Iterable<T>.splitWhen(
splitPredicate: (index: Int, element: T, currentSubList: List<T>) -> Boolean
): List<List<T>> {
val result = mutableListOf<MutableList<T>>()
forEachIndexed { index, element ->
if (index == 0 || splitPredicate(index, element, result.last())) {
result.add(mutableListOf<T>())
}
result.last().add(element)
}
return result
}
| apache-2.0 | 5d09aef8516dacf808340fb46ca3c636 | 29.560976 | 99 | 0.690343 | 3.55461 | false | false | false | false |
dinosaurwithakatana/freight | freight-processor/src/main/kotlin/io/dwak/freight/processor/FreightProcessor.kt | 1 | 10052 | package io.dwak.freight.processor
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.TypeName
import io.dwak.freight.annotation.ControllerBuilder
import io.dwak.freight.annotation.Extra
import io.dwak.freight.processor.binding.BuilderBindingClass
import io.dwak.freight.processor.binding.FreightTrainBindingClass
import io.dwak.freight.processor.binding.NavigatorBindingClass
import io.dwak.freight.processor.binding.NavigatorImplBindingClass
import io.dwak.freight.processor.extension.className
import io.dwak.freight.processor.extension.hasAnnotationWithName
import io.dwak.freight.processor.extension.packageName
import io.dwak.freight.processor.model.ClassBinding
import io.dwak.freight.processor.model.FieldBinding
import java.io.IOException
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.Filer
import javax.annotation.processing.Messager
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.Element
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.tools.Diagnostic
import kotlin.system.exitProcess
open class FreightProcessor: AbstractProcessor() {
private lateinit var filer: Filer
private lateinit var messager: Messager
private lateinit var elementUtils: Elements
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
this.filer = processingEnv.filer
this.messager = processingEnv.messager
this.elementUtils = processingEnv.elementUtils
}
override fun getSupportedAnnotationTypes()
= mutableSetOf(Extra::class.java.canonicalName,
ControllerBuilder::class.java.canonicalName)
override fun getSupportedSourceVersion() = SourceVersion.latestSupported()
override fun process(annotations: MutableSet<out TypeElement>,
roundEnv: RoundEnvironment): Boolean {
if (annotations.isNotEmpty()) {
val freightTrainTargetClassMap = hashMapOf<TypeElement, FreightTrainBindingClass>()
val builderTargetClassMap = hashMapOf<TypeElement, BuilderBindingClass>()
val navigatorTargetClassMap = hashMapOf<String, NavigatorBindingClass>()
val navigatorImplTargetClassMap = hashMapOf<String, NavigatorImplBindingClass>()
val erasedTargetNames = mutableSetOf<String>()
annotations.forEach { typeElement: TypeElement ->
val elements = roundEnv.getElementsAnnotatedWith(typeElement)
elements.filter { it.hasAnnotationWithName(Extra::class.java.simpleName) }
.forEach {
try {
val enclosingTypeElement = it.enclosingElement as TypeElement
val shipperClass = getOrCreateFreightTrain(freightTrainTargetClassMap,
enclosingTypeElement,
erasedTargetNames)
shipperClass.createAndAddBinding(it)
} catch (e: Exception) {
}
}
elements.filter { it.hasAnnotationWithName(ControllerBuilder::class.java.simpleName) }
.forEach {
val enclosedExtrasElements = arrayListOf<FieldBinding>()
it.enclosedElements
.filter { it.hasAnnotationWithName(Extra::class.java.simpleName) }
.map(::FieldBinding)
.forEach { enclosedExtrasElements.add(it) }
val builderClass = getOrCreateBuilder(builderTargetClassMap,
it as TypeElement,
erasedTargetNames)
builderClass.createAndAddBinding(it, enclosedExtrasElements)
val annotationInstance = it.getAnnotation(ControllerBuilder::class.java)
val scopeName = annotationInstance.scope
val screenName = annotationInstance.value
if (screenName.isNotEmpty()) {
val navigatorClass = getOrCreateNavigator(navigatorTargetClassMap,
it,
erasedTargetNames,
scopeName)
navigatorClass.createAndAddBinding(it)
val navigatorImplClass = getOrCreateNavigatorImpl(navigatorImplTargetClassMap,
it,
erasedTargetNames,
scopeName)
navigatorImplClass.createAndAddBinding(it,
ClassName.get(builderClass.classPackage,
builderClass.className))
}
else if (scopeName != "Main"
|| TypeName.get(ClassBinding.getPopChangeHandler(annotationInstance)) != TypeName.VOID.box()
|| TypeName.get(ClassBinding.getPushChangeHandler(annotationInstance)) != TypeName.VOID.box()) {
warning("${it.qualifiedName} needs a screen name value!")
}
}
}
(freightTrainTargetClassMap.values
+ builderTargetClassMap.values
+ navigatorTargetClassMap.values
+ navigatorImplTargetClassMap.values)
.forEach {
try {
it.writeToFiler(filer)
} catch (e: IOException) {
messager.printMessage(Diagnostic.Kind.ERROR, e.message)
}
}
}
return true
}
private fun getOrCreateFreightTrain(targetClassMap: MutableMap<TypeElement, FreightTrainBindingClass>,
enclosingElement: TypeElement,
erasedTargetNames: MutableSet<String>)
: FreightTrainBindingClass {
var freightTrainClass = targetClassMap[enclosingElement]
if (freightTrainClass == null) {
val targetClass = enclosingElement.qualifiedName.toString()
val classPackage = enclosingElement.packageName(elementUtils)
val className = enclosingElement.className(classPackage) + FreightTrainBindingClass.CLASS_SUFFIX
freightTrainClass = FreightTrainBindingClass(classPackage,
className,
targetClass,
processingEnv)
targetClassMap.put(enclosingElement, freightTrainClass)
erasedTargetNames.add(enclosingElement.toString())
}
return freightTrainClass
}
private fun getOrCreateBuilder(targetClassMap: MutableMap<TypeElement, BuilderBindingClass>,
element: TypeElement,
erasedTargetNames: MutableSet<String>)
: BuilderBindingClass {
var builderClass = targetClassMap[element]
if (builderClass == null) {
val targetClass = element.qualifiedName.toString()
val classPackage = element.packageName(elementUtils)
val className = element.className(classPackage) + BuilderBindingClass.CLASS_SUFFIX
builderClass = BuilderBindingClass(classPackage, className, targetClass, processingEnv)
targetClassMap.put(element, builderClass)
erasedTargetNames.add(element.toString())
}
return builderClass
}
private fun getOrCreateNavigator(targetClassMap: MutableMap<String, NavigatorBindingClass>,
element: TypeElement,
erasedTargetNames: MutableSet<String>,
scopeName: String): NavigatorBindingClass {
var navigatorClass = targetClassMap[scopeName]
if (navigatorClass == null) {
val targetClass = element.qualifiedName.toString()
val classPackage = "io.dwak.freight.navigator.${scopeName.toLowerCase()}"
val className = scopeName + NavigatorBindingClass.CLASS_SUFFIX
navigatorClass = NavigatorBindingClass(classPackage, className, targetClass, processingEnv)
targetClassMap.put(scopeName, navigatorClass)
erasedTargetNames.add(element.toString())
}
return navigatorClass
}
private fun getOrCreateNavigatorImpl(targetClassMap: MutableMap<String, NavigatorImplBindingClass>,
element: TypeElement,
erasedTargetNames: MutableSet<String>,
scopeName: String): NavigatorImplBindingClass {
var navigatorImplClass = targetClassMap[scopeName]
if (navigatorImplClass == null) {
val targetClass = element.qualifiedName.toString()
val classPackage = "io.dwak.freight.navigator.${scopeName.toLowerCase()}"
@Suppress("RemoveSingleExpressionStringTemplate")
val className = "${NavigatorImplBindingClass.CLASS_PREFIX}" +
"$scopeName" +
"${NavigatorImplBindingClass.CLASS_SUFFIX}"
navigatorImplClass = NavigatorImplBindingClass(classPackage,
className,
targetClass,
processingEnv)
targetClassMap.put(scopeName, navigatorImplClass)
erasedTargetNames.add(element.toString())
}
return navigatorImplClass
}
@Suppress("unused")
private fun error(element: Element, message: String, vararg args: Any) {
messager.printMessage(Diagnostic.Kind.ERROR, String.format(message, args), element)
}
@Suppress("unused")
private fun note(note: String) {
messager.printMessage(Diagnostic.Kind.NOTE, note)
}
@Suppress("unused")
private fun warning(note: String) {
messager.printMessage(Diagnostic.Kind.WARNING, note)
}
}
| apache-2.0 | e291374ed3548e57992f7d675fa62116 | 44.076233 | 114 | 0.632909 | 5.688738 | false | false | false | false |
softappeal/yass | kotlin/yass/main/ch/softappeal/yass/serialize/fast/BaseTypeSerializers.kt | 1 | 3651 | package ch.softappeal.yass.serialize.fast
import ch.softappeal.yass.serialize.*
import ch.softappeal.yass.serialize.fast.FieldType.*
val BooleanSerializer = object : BaseTypeSerializer<Boolean>(Boolean::class, VarInt) {
override fun read(reader: Reader) = reader.readByte().toInt() != 0
override fun write(writer: Writer, value: Boolean) = writer.writeByte((if (value) 1 else 0).toByte())
}
val ByteSerializer = object : BaseTypeSerializer<Byte>(Byte::class, VarInt) {
override fun read(reader: Reader) = reader.readZigZagInt().toByte()
override fun write(writer: Writer, value: Byte) = writer.writeZigZagInt(value.toInt())
}
val ShortSerializer = object : BaseTypeSerializer<Short>(Short::class, VarInt) {
override fun read(reader: Reader) = reader.readZigZagInt().toShort()
override fun write(writer: Writer, value: Short) = writer.writeZigZagInt(value.toInt())
}
val IntSerializer = object : BaseTypeSerializer<Int>(Int::class, VarInt) {
override fun read(reader: Reader) = reader.readZigZagInt()
override fun write(writer: Writer, value: Int) = writer.writeZigZagInt(value)
}
val LongSerializer = object : BaseTypeSerializer<Long>(Long::class, VarInt) {
override fun read(reader: Reader) = reader.readZigZagLong()
override fun write(writer: Writer, value: Long) = writer.writeZigZagLong(value)
}
val CharSerializer = object : BaseTypeSerializer<Char>(Char::class, VarInt) {
override fun read(reader: Reader): Char = reader.readVarInt().toChar()
override fun write(writer: Writer, value: Char) = writer.writeVarInt(value.toInt())
}
val FloatSerializer = object : BaseTypeSerializer<Float>(Float::class, Binary) {
override fun read(reader: Reader): Float {
reader.readByte()
return reader.readFloat()
}
override fun write(writer: Writer, value: Float) {
writer.writeByte(4)
writer.writeFloat(value)
}
}
val FloatSerializerNoSkipping = object : BaseTypeSerializer<Float>(Float::class, Binary) {
override fun read(reader: Reader) = reader.readFloat()
override fun write(writer: Writer, value: Float) = writer.writeFloat(value)
}
val DoubleSerializer = object : BaseTypeSerializer<Double>(Double::class, Binary) {
override fun read(reader: Reader): Double {
reader.readByte()
return reader.readDouble()
}
override fun write(writer: Writer, value: Double) {
writer.writeByte(8)
writer.writeDouble(value)
}
}
val DoubleSerializerNoSkipping = object : BaseTypeSerializer<Double>(Double::class, Binary) {
override fun read(reader: Reader) = reader.readDouble()
override fun write(writer: Writer, value: Double) = writer.writeDouble(value)
}
val BinarySerializer = object : BaseTypeSerializer<ByteArray>(ByteArray::class, Binary) {
override fun read(reader: Reader): ByteArray {
val length = reader.readVarInt()
var value = ByteArray(Math.min(length, 128))
var i = 0
while (i < length) {
if (i >= value.size) value = value.copyOf(Math.min(length, 2 * value.size))
val l = value.size - i
reader.readBytes(value, i, l)
i += l
}
return value
}
override fun write(writer: Writer, value: ByteArray) {
writer.writeVarInt(value.size)
writer.writeBytes(value)
}
}
val StringSerializer = object : BaseTypeSerializer<String>(String::class, BinarySerializer.fieldType) {
override fun read(reader: Reader) = utf8toString(BinarySerializer.read(reader))
override fun write(writer: Writer, value: String) = BinarySerializer.write(writer, utf8toBytes(value))
}
| bsd-3-clause | d6b243764868af81554322fde14108fe | 38.258065 | 106 | 0.698439 | 3.83106 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/EditText.kt | 1 | 1388 | package com.bixlabs.bkotlin
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
/**
* Accepts 3 text watcher methods with a default empty implementation.
* This allows for a cleaner implementation of a `TextWatcher` with only the needed
* parts of if being implemented.
*
* @return The `TextWatcher` being added to EditText
*/
fun EditText.addTextWatcher(afterTextChanged: (s: Editable?) -> Unit = { _ -> },
beforeTextChanged: (s: CharSequence?, start: Int, count: Int, after: Int) -> Unit = { _, _, _, _ -> },
onTextChanged: (s: CharSequence?, start: Int, before: Int, count: Int) -> Unit = { _, _, _, _ -> }): TextWatcher {
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
afterTextChanged(s)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
beforeTextChanged(s, start, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged(s, start, before, count)
}
}
addTextChangedListener(textWatcher)
return textWatcher
}
/**
* Get this EditText text as a trimmed [String].
*/
fun EditText.textAsTrimmedString(): String = this.text.toString().trim() | apache-2.0 | 54982f1e90054f6e8f96b93e0c99d5e0 | 34.615385 | 142 | 0.637608 | 4.434505 | false | false | false | false |
hazuki0x0/YuzuBrowser | browser/src/main/java/jp/hazuki/yuzubrowser/browser/behavior/BottomBarBehavior.kt | 1 | 2245 | /*
* 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.browser.behavior
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.google.android.material.appbar.AppBarLayout
import jp.hazuki.yuzubrowser.browser.R
class BottomBarBehavior(context: Context, attrs: AttributeSet) : androidx.coordinatorlayout.widget.CoordinatorLayout.Behavior<LinearLayout>(context, attrs) {
private var isInitialized = false
private lateinit var topToolbar: View
private lateinit var bottomToolbar: View
private lateinit var bottomBar: View
override fun layoutDependsOn(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, bottomBar: LinearLayout, dependency: View): Boolean {
if (dependency is AppBarLayout) {
this.bottomBar = bottomBar
topToolbar = dependency.findViewById(R.id.topToolbar)
bottomToolbar = bottomBar.findViewById(R.id.bottomOverlayToolbar)
isInitialized = true
return true
}
return false
}
override fun onDependentViewChanged(parent: androidx.coordinatorlayout.widget.CoordinatorLayout, bottomBar: LinearLayout, dependency: View): Boolean {
val bottomBarHeight = bottomToolbar.height
if (topToolbar.height != 0) {
val height = -dependency.top * bottomBarHeight / topToolbar.height
bottomBar.translationY = Math.min(height, bottomBarHeight).toFloat()
}
return true
}
fun setExpanded(expanded: Boolean) {
if (isInitialized && expanded) {
bottomBar.translationY = 0f
}
}
}
| apache-2.0 | 26c69549d47f47a2083587e64c29a740 | 35.803279 | 157 | 0.720713 | 4.827957 | false | false | false | false |
gradle/gradle-script-kotlin | samples/hello-kapt/src/main/kotlin/samples/Writer.kt | 2 | 1732 | package samples
import com.google.auto.value.AutoValue
/**
* Example of AutoValue class that implements [User] interface and provides builder
*
* Can be easily used from java and with AutoValue plugins
*/
@AutoValue
abstract class Writer : User {
/**
* Define only additional property [books]
* other properties will be implicitly generated from properties of [User]
*/
abstract val books: List<String>
/**
* Create prefilled builder from current object
*/
abstract fun toBuilder(): Builder
/**
* Define builder fields.
* We must provide all fields and build() method otherwise will get compile error
*/
@AutoValue.Builder
abstract class Builder {
abstract fun name(name: String): Builder
abstract fun age(age: Int?): Builder
abstract fun books(books: List<String>): Builder
fun build(): Writer {
// Example of builder value normalization
if (name == "") name("Anonymous")
// Example of builder value validation
val age = age
require(age == null || age >= 0) { "Age can not be negative" }
return internalBuild()
}
// getters to get builder value
protected abstract val name: String
protected abstract val age: Int?
// Real build method hidden from user to allow us validate and normalize values
protected abstract fun internalBuild(): Writer
}
companion object {
/**
* Creates empty [Builder]
*/
@JvmStatic
fun builder(): Builder = AutoValue_Writer.Builder()
// Default value for builder
.books(emptyList())
}
}
| apache-2.0 | 61dd40459216d799c6f81a7eed699df1 | 27.393443 | 87 | 0.610855 | 5.094118 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-unconsciousness-bukkit/src/main/kotlin/com/rpkit/unconsciousness/bukkit/unconsciousness/RPKUnconsciousnessProviderImpl.kt | 1 | 2920 | /*
* Copyright 2018 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.unconsciousness.bukkit.unconsciousness
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.unconsciousness.bukkit.RPKUnconsciousnessBukkit
import com.rpkit.unconsciousness.bukkit.database.table.RPKUnconsciousStateTable
import com.rpkit.unconsciousness.bukkit.event.unconsciousness.RPKBukkitUnconsciousnessStateChangeEvent
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
class RPKUnconsciousnessProviderImpl(private val plugin: RPKUnconsciousnessBukkit): RPKUnconsciousnessProvider {
override fun isUnconscious(character: RPKCharacter): Boolean {
val unconsciousStateTable = plugin.core.database.getTable(RPKUnconsciousStateTable::class)
val unconsciousState = unconsciousStateTable.get(character)
return if (unconsciousState == null) {
false
} else {
unconsciousState.deathTime + plugin.config.getLong("unconscious-time") > System.currentTimeMillis()
}
}
override fun setUnconscious(character: RPKCharacter, unconscious: Boolean) {
val event = RPKBukkitUnconsciousnessStateChangeEvent(character, unconscious)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return
val unconsciousStateTable = plugin.core.database.getTable(RPKUnconsciousStateTable::class)
var unconsciousState = unconsciousStateTable.get(event.character)
if (unconsciousState != null) {
if (event.isUnconscious) {
unconsciousState.deathTime = System.currentTimeMillis()
unconsciousStateTable.update(unconsciousState)
val minecraftUUID = event.character.minecraftProfile?.minecraftUUID ?: return
plugin.server.getPlayer(minecraftUUID)?.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, Integer.MAX_VALUE, 0), true)
} else {
unconsciousStateTable.delete(unconsciousState)
}
} else {
if (event.isUnconscious) {
unconsciousState = RPKUnconsciousState(
character = event.character,
deathTime = System.currentTimeMillis()
)
unconsciousStateTable.insert(unconsciousState)
}
}
}
} | apache-2.0 | 944d7b1c3021c56ca15673d7d4d107e1 | 43.938462 | 141 | 0.711986 | 4.201439 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.