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
kazhida/surroundcalc
src/com/abplus/surroundcalc/utls/Purchases.kt
1
2065
package com.abplus.surroundcalc.utls import android.content.Context import com.abplus.surroundcalc.billing.BillingHelper import android.util.Log import android.preference.PreferenceManager import android.app.Activity import com.abplus.surroundcalc.billing.BillingHelper.OnPurchaseFinishedListener import com.abplus.surroundcalc.billing.BillingHelper.Result import com.abplus.surroundcalc.billing.BillingHelper.Inventory import java.util.List import java.util.ArrayList /** * Created by kazhida on 2014/01/07. */ class Purchases (val context: Context) { public val billingHelper: BillingHelper = BillingHelper(context) public fun checkState(sku: String, listener: BillingHelper.QueryInventoryFinishedListener): Unit { val more = ArrayList<String>() more.add(sku) billingHelper.startSetup { if (it!!.isSuccess()) { val inventory = billingHelper.queryInventory(true, more) if (inventory!!.hasPurchase(sku)) { billingHelper.savePurchase(sku, 1) } else { billingHelper.savePurchase(sku, -1) } listener.onQueryInventoryFinished(it, inventory) } } } public fun isPurchased(sku: String): Boolean { val preferences = PreferenceManager.getDefaultSharedPreferences(context)!! val purchased = preferences.getInt(sku, 0) Log.d("surroudcalc", "SKU:" + sku + "(" + purchased.toString() + ")") return purchased > 0 } public fun purchase(activity: Activity, sku: String, runnable: Runnable): Unit { val requestCode = 12016 //適当な値 billingHelper.launchPurchaseFlow(activity, sku, requestCode) { (result : BillingHelper.Result?, info : BillingHelper.Purchase?) : Unit -> if (result!!.isSuccess()) { if (info!!.getSku().equals(sku)) { billingHelper.savePurchase(sku, 1) runnable.run() } } } } }
bsd-2-clause
1d95dc9e64f34cfb5a1477c05556d6aa
33.864407
102
0.637336
4.685649
false
false
false
false
debop/debop4k
debop4k-core/src/test/kotlin/debop4k/core/collections/permutations/NoneMatchTest.kt
1
2752
/* * Copyright (c) 2016. KESTI co, ltd * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package debop4k.core.collections.permutations import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.times import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyZeroInteractions import debop4k.core.collections.permutations.samples.primes import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.mockito.BDDMockito /** * NoneMatchTest * @author [email protected] */ class NoneMatchTest : AbstractPermutationTest() { private val supplierMock = mock<() -> Permutation<String>>() @Test fun testAlwaysTruePredicateWithEmptySeq() { assertThat(emptyPermutation.noneMatch { true }).isTrue() } @Test fun testSingleElementSeq() { val single = permutationOf(1) assertThat(single.noneMatch { false }).isTrue() assertThat(single.noneMatch { it < 0 }).isTrue() assertThat(single.noneMatch { it % 2 != 0 }).isFalse() } @Test fun testMultiElementsSeq() { val fixed = permutationOf(5, 10, 15) assertThat(fixed.noneMatch { it % 5 != 0 }).isTrue() assertThat(fixed.noneMatch { it > 10 }).isFalse() } @Test fun testMultiElementsSeqWithString() { val fixed = permutationOf("a", "bc", "def") assertThat(fixed.noneMatch { !it.isEmpty() }).isFalse() } @Test fun testLazySeq() { val lazy = cons(3) { cons(2) { permutationOf(8) } } assertThat(lazy.noneMatch { it < 0 }).isTrue() assertThat(lazy.noneMatch { it % 2 == 0 }).isFalse() } @Test fun testInfiniteSeq() { val primes = primes() assertThat(primes.noneMatch { it % 2 == 0 }).isFalse() assertThat(primes.noneMatch { it > 1000 }).isFalse() } @Test fun testNotEvaluateTailIfHeadMatchesPredicate() { val lazy = cons("a", supplierMock) lazy.noneMatch { !it.isEmpty() } verifyZeroInteractions(supplierMock) } @Test fun testEvaluateTailOnlyOnceWhenHeadMatchesButSecondNotMatches() { val lazy = cons("a", supplierMock) BDDMockito.given(supplierMock.invoke()).willReturn(permutationOf("")) lazy.noneMatch(String::isEmpty) verify(supplierMock, times(1)).invoke() } }
apache-2.0
cbc5deb066e8dbda9ff3d617fbdb7061
27.091837
75
0.699491
3.994194
false
true
false
false
asamm/locus-api
locus-api-core/src/main/java/locus/api/objects/geocaching/GeocachingLog.kt
1
4912
/* * Copyright 2011, Asamm Software, s.r.o. * * This file is part of LocusAddonPublicLib. * * LocusAddonPublicLib 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. * * LocusAddonPublicLib 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 LocusAddonPublicLib. If not, see <http://www.gnu.org/licenses/>. */ package locus.api.objects.geocaching import locus.api.objects.Storable import locus.api.utils.DataReaderBigEndian import locus.api.utils.DataWriterBigEndian import java.io.IOException /** * This Object is container for cache Logs. * <br></br><br></br> * Useful pages with list:<br></br> * * * [German list](http://www.gc-reviewer.de/hilfe-tipps-und-tricks/logtypen/) * * * @author menion */ class GeocachingLog : Storable() { /** * Unique ID of a log. */ var id: Long = 0L /** * Type of log defined by CACHE_LOG_TYPE_X parameter. */ var type: Int = CACHE_LOG_TYPE_UNKNOWN /** * Time when log was created (in ms). */ var date: Long = 0L /** * Name of 'finder'. */ var finder: String = "" /** * ID of the 'finder'. */ var findersId: Long = FINDERS_ID_UNDEFINED /** * Amount of already found caches by current 'finder'. */ var findersFound: Int = 0 /** * Text of log itself. */ var logText: String = "" /** * List of attached images. */ private var _images: MutableList<GeocachingImage> = arrayListOf() /** * Longitude coordinate to this log. Value is in WGS84 format. */ var cooLon: Double = 0.0 /** * Latitude coordinate to this log. Value is in WGS84 format. */ var cooLat: Double = 0.0 // IMAGES /** * Iterator over already attached images. */ val images: Iterator<GeocachingImage> get() = _images.iterator() /** * Add image to current list of images attached to this log. * * @param image image to add */ fun addImage(image: GeocachingImage) { this._images.add(image) } //************************************************* // STORABLE PART //************************************************* override fun getVersion(): Int { return 2 } @Throws(IOException::class) override fun readObject(version: Int, dr: DataReaderBigEndian) { id = dr.readLong() type = dr.readInt() date = dr.readLong() finder = dr.readString() findersFound = dr.readInt() logText = dr.readString() // V1 if (version >= 1) { _images = dr.readListStorable(GeocachingImage::class.java) } // V2 if (version >= 2) { findersId = dr.readLong() cooLon = dr.readDouble() cooLat = dr.readDouble() } } @Throws(IOException::class) override fun writeObject(dw: DataWriterBigEndian) { dw.writeLong(id) dw.writeInt(type) dw.writeLong(date) dw.writeString(finder) dw.writeInt(findersFound) dw.writeString(logText) // V1 dw.writeListStorable(_images) // V2 dw.writeLong(findersId) dw.writeDouble(cooLon) dw.writeDouble(cooLat) } companion object { // LOG TYPES const val CACHE_LOG_TYPE_UNKNOWN = -1 const val CACHE_LOG_TYPE_FOUND = 0 const val CACHE_LOG_TYPE_NOT_FOUND = 1 const val CACHE_LOG_TYPE_WRITE_NOTE = 2 const val CACHE_LOG_TYPE_NEEDS_MAINTENANCE = 3 const val CACHE_LOG_TYPE_OWNER_MAINTENANCE = 4 const val CACHE_LOG_TYPE_PUBLISH_LISTING = 5 const val CACHE_LOG_TYPE_ENABLE_LISTING = 6 const val CACHE_LOG_TYPE_TEMPORARILY_DISABLE_LISTING = 7 const val CACHE_LOG_TYPE_UPDATE_COORDINATES = 8 const val CACHE_LOG_TYPE_ANNOUNCEMENT = 9 const val CACHE_LOG_TYPE_WILL_ATTEND = 10 const val CACHE_LOG_TYPE_ATTENDED = 11 const val CACHE_LOG_TYPE_POST_REVIEWER_NOTE = 12 const val CACHE_LOG_TYPE_NEEDS_ARCHIVED = 13 const val CACHE_LOG_TYPE_WEBCAM_PHOTO_TAKEN = 14 const val CACHE_LOG_TYPE_RETRACT_LISTING = 15 const val CACHE_LOG_TYPE_ARCHIVE = 16 const val CACHE_LOG_TYPE_UNARCHIVE = 17 const val CACHE_LOG_TYPE_PERMANENTLY_ARCHIVED = 18 // flag that ID of finder is not defined const val FINDERS_ID_UNDEFINED: Long = 0L } }
mit
4b3ae46f2cefb8dcc27e354ad6641063
27.398844
79
0.602199
3.892235
false
false
false
false
thm-projects/arsnova-backend
websocket/src/test/kotlin/de/thm/arsnova/service/wsgateway/management/MetricsServiceTest.kt
1
4274
package de.thm.arsnova.service.wsgateway.management import com.ninjasquad.springmockk.MockkBean import com.ninjasquad.springmockk.SpykBean import de.thm.arsnova.service.wsgateway.event.RoomUserCountChangedEvent import de.thm.arsnova.service.wsgateway.service.RoomSubscriptionService import io.mockk.verify import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.ApplicationEventPublisher import java.time.LocalDateTime import kotlin.math.floor import kotlin.math.max import kotlin.math.roundToInt @SpringBootTest class MetricsServiceTest { @MockkBean private lateinit var roomSubscriptionService: RoomSubscriptionService @SpykBean private lateinit var metricsService: MetricsService @Autowired private lateinit var applicationEventPublisher: ApplicationEventPublisher @Test fun testSessionWithUserCountBelowThresholdShouldNotBeTracked() { testHandleRoomUserCountChangedEvent(MetricsService.ACTIVE_ROOM_MIN_USERS - 1) } @Test fun testSessionWithUserCountAtThresholdShouldBeTracked() { testHandleRoomUserCountChangedEvent(MetricsService.ACTIVE_ROOM_MIN_USERS) } @Test fun testSessionWithUserCountOverThresholdShouldBeTracked() { testHandleRoomUserCountChangedEvent(MetricsService.ACTIVE_ROOM_MIN_USERS + 1) } private fun testHandleRoomUserCountChangedEvent(maxUserCount: Int) { val roomId = "Room-With-$maxUserCount-Users" for (i in MetricsService.ACTIVE_ROOM_MIN_USERS..maxUserCount) { val after = LocalDateTime.now().minusSeconds(1) applicationEventPublisher.publishEvent( RoomUserCountChangedEvent( roomId = roomId, count = i ) ) val before = LocalDateTime.now().plusSeconds(1) if (i < MetricsService.ACTIVE_ROOM_MIN_USERS) { assertNull( metricsService.activeRooms[roomId], "Room should not have metrics." ) continue } assertEquals( i, metricsService.activeRooms[roomId]?.maxUserCount, "'maxUserCount' does not have the expected value." ) assertNotNull( metricsService.activeRooms[roomId]?.sessionStart, "'sessionStart' is expected to be not null." ) assertTrue( metricsService.activeRooms[roomId]?.sessionStart?.isAfter(after)!!, "'sessionStart' is not in expected time range." ) assertTrue( metricsService.activeRooms[roomId]?.sessionStart?.isBefore(before)!!, "'sessionStart' is not in expected time range." ) assertEquals( -1, metricsService.activeRooms[roomId]?.decliningMinUserCount, "'decliningMinUserCount' does not have the expected value." ) } verify(exactly = 0) { metricsService["trackSessionEnd"](any<MetricsService.ActiveRoomMetrics>()) } if (maxUserCount < MetricsService.ACTIVE_ROOM_MIN_USERS) { return } for ( i in maxUserCount downTo max( floor(maxUserCount * MetricsService.SESSION_END_USER_FACTOR), floor(MetricsService.ACTIVE_ROOM_MIN_USERS * MetricsService.ACTIVE_ROOM_MIN_USERS_TOLERANCE_FACTOR) ).roundToInt() ) { applicationEventPublisher.publishEvent( RoomUserCountChangedEvent( roomId = roomId, count = i ) ) if (i < maxUserCount * MetricsService.SESSION_END_USER_FACTOR || i < MetricsService.ACTIVE_ROOM_MIN_USERS * MetricsService.ACTIVE_ROOM_MIN_USERS_TOLERANCE_FACTOR ) { verify(exactly = 1) { metricsService["trackSessionEnd"](any<MetricsService.ActiveRoomMetrics>()) } } else { assertEquals( maxUserCount, metricsService.activeRooms[roomId]?.maxUserCount, "'maxUserCount' does not have the expected value." ) assertEquals( -1, metricsService.activeRooms[roomId]?.decliningMinUserCount, "'decliningMinUserCount' does not have the expected value." ) } } } }
gpl-3.0
864887f08278ac0459ee78f4a6c08cf3
34.915966
107
0.719467
4.410733
false
true
false
false
gotev/android-upload-service
uploadservice/src/main/java/net/gotev/uploadservice/schemehandlers/FileSchemeHandler.kt
2
1056
package net.gotev.uploadservice.schemehandlers import android.content.Context import net.gotev.uploadservice.extensions.autoDetectMimeType import net.gotev.uploadservice.logger.UploadServiceLogger import net.gotev.uploadservice.logger.UploadServiceLogger.NA import java.io.File import java.io.FileInputStream import java.io.IOException internal class FileSchemeHandler : SchemeHandler { private lateinit var file: File override fun init(path: String) { file = File(path) } override fun size(context: Context) = file.length() override fun stream(context: Context) = FileInputStream(file) override fun contentType(context: Context) = file.absolutePath.autoDetectMimeType() override fun name(context: Context) = file.name ?: throw IOException("Can't get file name for ${file.absolutePath}") override fun delete(context: Context) = try { file.delete() } catch (exc: Throwable) { UploadServiceLogger.error(javaClass.simpleName, NA, exc) { "File deletion error" } false } }
apache-2.0
853a64b614a1676f2c0ed4a0e4790bdd
31
90
0.737689
4.381743
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/DokitAbility.kt
1
815
package com.didichuxing.doraemonkit.kit.core import com.didichuxing.doraemonkit.constant.DoKitModule /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2021/6/7-19:42 * 描 述:具体的某块具有哪些能力 * 修订历史: * ================================================ */ interface DokitAbility { fun init() /** * 模块名 */ fun moduleName(): DoKitModule /** *注册模块能力处理器 */ fun getModuleProcessor(): DokitModuleProcessor interface DokitModuleProcessor { val TAG: String get() = this.javaClass.simpleName fun values(): Map<String, Any?> fun proceed(actions: Map<String, Any?>? = null): Map<String, Any> } }
apache-2.0
d28ac5cf93e22be9fb1c3f9c85811b0e
18.026316
73
0.511757
3.86631
false
false
false
false
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/ui/lecturecancel/detail/LectureCancelDetailViewModel.kt
1
3429
package jp.kentan.studentportalplus.ui.lecturecancel.detail import android.app.Application import android.content.Intent import androidx.lifecycle.* import jp.kentan.studentportalplus.R import jp.kentan.studentportalplus.data.PortalRepository import jp.kentan.studentportalplus.data.component.LectureAttend import jp.kentan.studentportalplus.data.model.LectureCancellation import jp.kentan.studentportalplus.ui.SingleLiveData import jp.kentan.studentportalplus.util.formatYearMonthDay import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.jsoup.Jsoup class LectureCancelDetailViewModel( private val context: Application, private val portalRepository: PortalRepository ) : AndroidViewModel(context) { private val idLiveData = MutableLiveData<Long>() val lectureCancel: LiveData<LectureCancellation> = Transformations.switchMap(idLiveData) { id -> portalRepository.getLectureCancel(id) } val showAttendNotDialog = SingleLiveData<String>() val snackbar = SingleLiveData<Int>() val indefiniteSnackbar = SingleLiveData<Int>() val share = SingleLiveData<Intent>() val errorNotFound = SingleLiveData<Unit>() private val lectureCancelObserver = Observer<LectureCancellation> { data -> if (data == null) { errorNotFound.value = Unit } else if (!data.isRead) { portalRepository.updateLectureCancel(data.copy(isRead = true)) } } init { lectureCancel.observeForever(lectureCancelObserver) } fun onActivityCreated(id: Long) { idLiveData.value = id } fun onAttendClick(data: LectureCancellation?) { data ?: return if (data.attend.canAttend()) { GlobalScope.launch { val isSuccess = portalRepository.addToMyClass(data.copy(attend = LectureAttend.USER)).await() if (isSuccess) { snackbar.postValue(R.string.msg_register_class) } else { indefiniteSnackbar.postValue(R.string.error_update) } } } else if (data.attend != LectureAttend.PORTAL) { showAttendNotDialog.value = data.subject } } fun onAttendNotClick(subject: String) { GlobalScope.launch { val isSuccess = portalRepository.deleteFromMyClass(subject).await() if (isSuccess) { snackbar.postValue(R.string.msg_unregister_class) } else { indefiniteSnackbar.postValue(R.string.error_update) } } } fun onShareClick() { val data = lectureCancel.value ?: return val text = context.getString(R.string.share_lecture_cancel, data.subject, data.instructor, data.week, data.period, data.cancelDate.formatYearMonthDay(), Jsoup.parse(data.detailHtml).text(), data.createdDate.formatYearMonthDay()) val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_SUBJECT, data.subject) putExtra(Intent.EXTRA_TEXT, text.toString()) } share.value = Intent.createChooser(intent, null) } override fun onCleared() { lectureCancel.removeObserver(lectureCancelObserver) super.onCleared() } }
gpl-3.0
9429993ce8a7a9612bd4d679cbc9a01b
32.300971
109
0.650044
4.782427
false
false
false
false
CharlieZheng/NestedGridViewByListView
app/src/main/java/com/cdc/androidsamples/provider/BookProvider.kt
1
3943
package com.cdc.androidsamples.provider import android.content.ContentProvider import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.util.Log import com.cdc.androidsamples.model.db.DbOpenHelper /** * @author zhenghanrong on 2017/11/13. */ class BookProvider : ContentProvider() { companion object { private val TAG = BookProvider::class.java.simpleName private val AUTHORITY = "com.cdc.androidsamples.provider.BookProvider" private val book_path = "book" private val user_path = "user" private val BOOK_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + book_path) private val USER_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + user_path) private val BOOK_URI_CODE = 0 private val USER_URI_CODE = 1 private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH) } private var db: SQLiteDatabase? = null init { uriMatcher.addURI(AUTHORITY, book_path, BOOK_URI_CODE) uriMatcher.addURI(AUTHORITY, user_path, USER_URI_CODE) } private fun getTableName(uri: Uri?): String? { var tableName: String? = null when (uriMatcher.match(uri)) { BOOK_URI_CODE -> { tableName = DbOpenHelper.Companion.BOOK_TABLE_NAME } USER_URI_CODE -> { tableName = DbOpenHelper.Companion.USER_TABLE_NAME } } return tableName } override fun insert(uri: Uri?, values: ContentValues?): Uri? { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) db?.insert(getTableName(uri), null, values) context.contentResolver.notifyChange(uri, null) return uri } override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) return db?.query(getTableName(uri), projection, selection, selectionArgs, null, null, sortOrder, null) } private fun initProviderData() { db = DbOpenHelper(context).writableDatabase db?.execSQL("delete from " + DbOpenHelper.Companion.BOOK_TABLE_NAME) db?.execSQL("delete from " + DbOpenHelper.Companion.USER_TABLE_NAME) db?.execSQL("insert into book values(3, 'Android');") db?.execSQL("insert into book values(4, 'IOS');") db?.execSQL("insert into book values(5, 'Html5');") db?.execSQL("insert into user values(1, 'Charlie', 0);") db?.execSQL("insert into user values(2, 'Charles', 1);") } override fun onCreate(): Boolean { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) initProviderData() return true } override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) val row = db?.update(getTableName(uri), values, selection, selectionArgs)?:0 if (row > 0) { context?.contentResolver?.notifyChange(uri, null) } return row } override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) val cnt = db?.delete(getTableName(uri), selection, selectionArgs)?:0 if (cnt > 0) { context.contentResolver.notifyChange(uri, null) } return cnt } override fun getType(uri: Uri?): String? { Log.v(Thread.currentThread().stackTrace[2].methodName, Thread.currentThread().name) return null } }
apache-2.0
0e68a5f349c188aeb8d9d1c8b5374479
39.244898
151
0.652295
4.28587
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/preferences/fragments/MainSettingsFragment.kt
1
12982
package org.tasks.preferences.fragments import android.content.Intent import android.os.Bundle import androidx.core.content.ContextCompat import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.preference.Preference import androidx.preference.PreferenceScreen import com.todoroo.astrid.gtasks.auth.GtasksLoginActivity import com.todoroo.astrid.service.TaskDeleter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.BuildConfig import org.tasks.R import org.tasks.auth.SignInActivity import org.tasks.billing.BillingClient import org.tasks.billing.Inventory import org.tasks.billing.Purchase import org.tasks.billing.PurchaseActivity import org.tasks.caldav.BaseCaldavAccountSettingsActivity import org.tasks.caldav.CaldavAccountSettingsActivity import org.tasks.data.CaldavAccount import org.tasks.data.GoogleTaskAccount import org.tasks.etebase.EtebaseAccountSettingsActivity import org.tasks.extensions.Context.openUri import org.tasks.extensions.Context.toast import org.tasks.injection.InjectingPreferenceFragment import org.tasks.preferences.IconPreference import org.tasks.preferences.MainPreferences import org.tasks.preferences.Preferences import org.tasks.preferences.PreferencesViewModel import org.tasks.preferences.fragments.GoogleTasksAccount.Companion.newGoogleTasksAccountPreference import org.tasks.preferences.fragments.MicrosoftAccount.Companion.newMicrosoftAccountPreference import org.tasks.preferences.fragments.TasksAccount.Companion.newTasksAccountPreference import org.tasks.sync.AddAccountDialog import org.tasks.sync.AddAccountDialog.Companion.EXTRA_SELECTED import org.tasks.sync.AddAccountDialog.Companion.newAccountDialog import org.tasks.sync.AddAccountDialog.Platform import org.tasks.sync.microsoft.MicrosoftSignInViewModel import org.tasks.widget.AppWidgetManager import javax.inject.Inject @AndroidEntryPoint class MainSettingsFragment : InjectingPreferenceFragment() { @Inject lateinit var appWidgetManager: AppWidgetManager @Inject lateinit var preferences: Preferences @Inject lateinit var taskDeleter: TaskDeleter @Inject lateinit var inventory: Inventory @Inject lateinit var billingClient: BillingClient private val viewModel: PreferencesViewModel by activityViewModels() private val microsoftVM: MicrosoftSignInViewModel by viewModels() override fun getPreferenceXml() = R.xml.preferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) findPreference(R.string.add_account).setOnPreferenceClickListener { addAccount() } findPreference(R.string.name_your_price).setOnPreferenceClickListener { startActivity(Intent(context, PurchaseActivity::class.java)) false } findPreference(R.string.button_unsubscribe).setOnPreferenceClickListener { inventory.unsubscribe(requireActivity()) } findPreference(R.string.refresh_purchases).setOnPreferenceClickListener { lifecycleScope.launch { try { billingClient.queryPurchases(throwError = true) if (inventory.subscription.value == null) { activity?.toast(R.string.no_google_play_subscription) } } catch (e: Exception) { activity?.toast(e.message) } } false } viewModel.lastBackup.observe(this) { updateBackupWarning() } viewModel.lastAndroidBackup.observe(this) { updateBackupWarning() } viewModel.lastDriveBackup.observe(this) { updateBackupWarning() } viewModel.googleTaskAccounts.observe(this) { refreshAccounts() } viewModel.caldavAccounts.observe(this) { refreshAccounts() } if (BuildConfig.FLAVOR == "generic") { remove(R.string.upgrade_to_pro) } else { inventory.subscription.observe(this) { refreshSubscription(it) } } parentFragmentManager.setFragmentResultListener( AddAccountDialog.ADD_ACCOUNT, this ) { _, result -> val platform = result.getSerializable(EXTRA_SELECTED) as? Platform ?: return@setFragmentResultListener when (platform) { Platform.TASKS_ORG -> startActivityForResult( Intent(requireContext(), SignInActivity::class.java), REQUEST_TASKS_ORG ) Platform.GOOGLE_TASKS -> startActivityForResult( Intent(requireContext(), GtasksLoginActivity::class.java), REQUEST_GOOGLE_TASKS ) Platform.MICROSOFT -> microsoftVM.signIn(requireActivity()) Platform.DAVX5 -> context?.openUri(R.string.url_davx5) Platform.CALDAV -> startActivityForResult( Intent(requireContext(), CaldavAccountSettingsActivity::class.java), REQUEST_CALDAV_SETTINGS ) Platform.ETESYNC -> startActivityForResult( Intent(requireContext(), EtebaseAccountSettingsActivity::class.java), REQUEST_CALDAV_SETTINGS ) Platform.DECSYNC_CC -> context?.openUri(R.string.url_decsync) } } } override fun onResume() { super.onResume() updateBackupWarning() updateWidgetVisibility() } private fun refreshAccounts() { val caldavAccounts = viewModel.caldavAccounts.value ?: emptyList() val googleTaskAccounts = viewModel.googleTaskAccounts.value ?: emptyList() val addAccount = findPreference(R.string.add_account) val index = preferenceScreen.indexOf(addAccount) var current = 0 caldavAccounts.forEach { setup(it, if (current < index) { preferenceScreen.getPreference(current++) as IconPreference } else { preferenceScreen.insertAt(current++) }) } googleTaskAccounts.forEach { setup(it, if (current < index) { preferenceScreen.getPreference(current++) as IconPreference } else { preferenceScreen.insertAt(current++) }) } preferenceScreen.removeAt(current, index - current) if (caldavAccounts.isEmpty() && googleTaskAccounts.isEmpty()) { addAccount.setTitle(R.string.not_signed_in) addAccount.setIcon(R.drawable.ic_outline_cloud_off_24px) } else { addAccount.setTitle(R.string.add_account) addAccount.setIcon(R.drawable.ic_outline_add_24px) } tintIcons(addAccount, requireContext().getColor(R.color.icon_tint_with_alpha)) } private fun addAccount(): Boolean { newAccountDialog(hasTasksAccount = viewModel.tasksAccount() != null) .show(parentFragmentManager, FRAG_TAG_ADD_ACCOUNT) return false } private fun updateWidgetVisibility() { findPreference(R.string.widget_settings).isVisible = appWidgetManager.widgetIds.isNotEmpty() } override suspend fun setupPreferences(savedInstanceState: Bundle?) { requires(BuildConfig.DEBUG, R.string.debug) updateWidgetVisibility() } private fun updateBackupWarning() { val backupWarning = preferences.showBackupWarnings() && (viewModel.usingPrivateStorage || viewModel.staleLocalBackup || viewModel.staleRemoteBackup) (findPreference(R.string.backup_BPr_header) as IconPreference).iconVisible = backupWarning } private fun setup(account: CaldavAccount, pref: IconPreference) { pref.setTitle(account.prefTitle) pref.summary = account.name pref.setIcon(account.prefIcon) if (account.isCaldavAccount) { tintIcons(pref, requireContext().getColor(R.color.icon_tint_with_alpha)) } pref.setOnPreferenceClickListener { if (account.isTasksOrg) { (activity as MainPreferences).startPreference( this, newTasksAccountPreference(account), getString(R.string.tasks_org) ) } else if (account.isMicrosoft) { (activity as MainPreferences).startPreference( this, newMicrosoftAccountPreference(account), getString(R.string.microsoft) ) } else { val intent = Intent(context, account.accountSettingsClass).apply { putExtra(BaseCaldavAccountSettingsActivity.EXTRA_CALDAV_DATA, account) } startActivityForResult(intent, REQUEST_CALDAV_SETTINGS) } false } when { account.isTasksOrg -> { pref.setOnPreferenceClickListener { (activity as MainPreferences).startPreference( this, newTasksAccountPreference(account), getString(R.string.tasks_org) ) false } } } setupErrorIcon(pref, account.hasError, account.isEteSyncAccount) } private fun setup(account: GoogleTaskAccount, pref: IconPreference) { pref.setTitle(R.string.gtasks_GPr_header) pref.setIcon(R.drawable.ic_google) pref.summary = account.account setupErrorIcon(pref, account.hasError) pref.setOnPreferenceClickListener { (activity as MainPreferences).startPreference( this, newGoogleTasksAccountPreference(account), account.account!! ) false } } private fun setupErrorIcon( pref: IconPreference, hasError: Boolean, hasWarning: Boolean = false ) { pref.drawable = ContextCompat .getDrawable(requireContext(), when { hasError -> R.drawable.ic_outline_error_outline_24px hasWarning -> R.drawable.ic_outline_error_outline_24px else -> R.drawable.ic_keyboard_arrow_right_24px }) ?.mutate() pref.tint = context?.getColor(when { hasError -> R.color.overdue hasWarning -> R.color.orange_500 else -> R.color.icon_tint_with_alpha }) } private fun refreshSubscription(subscription: Purchase?) { findPreference(R.string.upgrade_to_pro).setTitle(if (subscription == null) { R.string.upgrade_to_pro } else { R.string.subscription }) findPreference(R.string.name_your_price).apply { if (subscription == null) { title = getString(R.string.name_your_price) summary = null } else { val interval = if (subscription.isMonthly) { R.string.price_per_month } else { R.string.price_per_year } val price = (subscription.subscriptionPrice!! - .01).toString() title = getString(R.string.manage_subscription) summary = getString(R.string.current_subscription, getString(interval, price)) } } findPreference(R.string.button_unsubscribe).isVisible = subscription != null } companion object { private const val FRAG_TAG_ADD_ACCOUNT = "frag_tag_add_account" const val REQUEST_CALDAV_SETTINGS = 10013 const val REQUEST_GOOGLE_TASKS = 10014 const val REQUEST_TASKS_ORG = 10016 fun PreferenceScreen.removeAt(index: Int, count: Int = 1) { repeat(count) { removePreference(getPreference(index)) } } fun PreferenceScreen.indexOf(pref: Preference): Int = 0.until(preferenceCount).first { pref == getPreference(it) } fun PreferenceScreen.insertAt(index: Int): IconPreference { index.until(preferenceCount).forEach { getPreference(it).apply { order += 1 } } return IconPreference(context).apply { layoutResource = R.layout.preference_icon order = index iconVisible = true addPreference(this) } } } }
gpl-3.0
4eda86c6ea1fd22debcc1c02145d6881
38.700306
100
0.618472
5.170052
false
false
false
false
Light-Team/ModPE-IDE-Source
app/src/main/kotlin/com/brackeys/ui/feature/explorer/adapters/DirectoryAdapter.kt
1
2260
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.feature.explorer.adapters import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.view.isVisible import androidx.recyclerview.widget.RecyclerView import com.brackeys.ui.databinding.ItemTabDirectoryBinding import com.brackeys.ui.feature.main.adapters.TabAdapter import com.brackeys.ui.filesystem.base.model.FileModel class DirectoryAdapter : TabAdapter<FileModel, DirectoryAdapter.DirectoryViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DirectoryViewHolder { return DirectoryViewHolder.create(parent) { select(it) } } override fun onBindViewHolder(holder: DirectoryViewHolder, position: Int) { holder.bind(currentList[position], position == selectedPosition) } class DirectoryViewHolder( private val binding: ItemTabDirectoryBinding, private val tabCallback: (Int) -> Unit ) : RecyclerView.ViewHolder(binding.root) { companion object { fun create(parent: ViewGroup, tabCallback: (Int) -> Unit): DirectoryViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ItemTabDirectoryBinding.inflate(inflater, parent, false) return DirectoryViewHolder(binding, tabCallback) } } init { itemView.setOnClickListener { tabCallback.invoke(adapterPosition) } } fun bind(item: FileModel, isSelected: Boolean) { binding.selectionIndicator.isVisible = isSelected binding.itemTitle.text = item.name } } }
apache-2.0
6d81abe576a29518dc07456115523054
36.065574
92
0.708407
4.737945
false
false
false
false
nemerosa/ontrack
ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/LabelJdbcRepository.kt
1
7207
package net.nemerosa.ontrack.repository import net.nemerosa.ontrack.model.Ack import net.nemerosa.ontrack.model.labels.LabelCategoryNameAlreadyExistException import net.nemerosa.ontrack.model.labels.LabelForm import net.nemerosa.ontrack.model.labels.LabelIdNotFoundException import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository import org.springframework.dao.DuplicateKeyException import org.springframework.dao.EmptyResultDataAccessException import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.stereotype.Repository import java.sql.ResultSet import javax.sql.DataSource @Repository class LabelJdbcRepository( dataSource: DataSource ) : AbstractJdbcRepository(dataSource), LabelRepository { override fun findLabelsByProvider(providerId: String): List<LabelRecord> { return namedParameterJdbcTemplate!!.query( "SELECT * FROM LABEL WHERE COMPUTED_BY = :computedBy", params("computedBy", providerId) ) { rs, _ -> rsConversion(rs) } } override fun findLabels(category: String?, name: String?): List<LabelRecord> { val sql: String val params: MapSqlParameterSource if (category == null) { if (name == null) { sql = "SELECT * FROM LABEL ORDER BY CATEGORY, NAME" params = MapSqlParameterSource() } else { sql = "SELECT * FROM LABEL WHERE NAME = :name ORDER BY CATEGORY, NAME" params = params("name", name) } } else if (name == null) { sql = "SELECT * FROM LABEL WHERE CATEGORY = :category ORDER BY CATEGORY, NAME" params = params("category", category) } else { sql = "SELECT * FROM LABEL WHERE CATEGORY = :category AND NAME = :name ORDER BY CATEGORY, NAME" params = params("category", category).addValue("name", name) } return namedParameterJdbcTemplate!!.query( sql, params ) { rs, _ -> rsConversion(rs) } } override fun findLabelByCategoryAndNameAndProvider(category: String?, name: String, providerId: String): LabelRecord? { return getFirstItem( """SELECT * FROM LABEL WHERE COMPUTED_BY = :computedBy AND CATEGORY = :category AND NAME = :name """, params("computedBy", providerId) .addValue("category", category) .addValue("name", name) ) { rs, _ -> rsConversion(rs) } } private fun findLabelByCategoryAndName(category: String?, name: String): LabelRecord? { return getFirstItem( """SELECT * FROM LABEL WHERE CATEGORY = :category AND NAME = :name """, params("category", category) .addValue("name", name) ) { rs, _ -> rsConversion(rs) } } override fun newLabel(form: LabelForm): LabelRecord = newLabel(form, null) override fun overrideLabel(form: LabelForm, providerId: String): LabelRecord { val record = findLabelByCategoryAndName( form.category, form.name ) return if (record != null) { updateAndOverrideLabel(record.id, form, providerId) } else { newLabel(form, providerId) } } private fun newLabel(form: LabelForm, computedBy: String?): LabelRecord { try { val id = dbCreate(""" INSERT INTO LABEL(category, name, description, color, computed_by) VALUES (:category, :name, :description, :color, :computedBy) """, params("computedBy", computedBy) .addValue("category", form.category) .addValue("name", form.name) .addValue("description", form.description) .addValue("color", form.color) ) return LabelRecord( id = id, category = form.category, name = form.name, description = form.description, color = form.color, computedBy = computedBy ) } catch (_: DuplicateKeyException) { throw LabelCategoryNameAlreadyExistException(form.category, form.name) } } override fun updateAndOverrideLabel(labelId: Int, form: LabelForm, providerId: String): LabelRecord = updateLabel(labelId, form, providerId) override fun updateLabel(labelId: Int, form: LabelForm): LabelRecord = updateLabel(labelId, form, null) private fun updateLabel(labelId: Int, form: LabelForm, providerId: String?): LabelRecord { try { namedParameterJdbcTemplate!!.update(""" UPDATE LABEL SET category = :category, name = :name, description = :description, color = :color, computed_by = :providerId WHERE id = :id """, params("category", form.category) .addValue("name", form.name) .addValue("description", form.description) .addValue("color", form.color) .addValue("id", labelId) .addValue("providerId", providerId) ) return getLabel(labelId) } catch (_: DuplicateKeyException) { throw LabelCategoryNameAlreadyExistException(form.category, form.name) } } override fun deleteLabel(labelId: Int): Ack { return Ack.one( namedParameterJdbcTemplate!!.update( "DELETE FROM LABEL WHERE ID = :id", params("id", labelId) ) ) } override fun findLabelById(labelId: Int): LabelRecord? { return getFirstItem( "SELECT * FROM LABEL WHERE ID = :id", params("id", labelId) ) { rs, _ -> rsConversion(rs) } } override fun getLabel(labelId: Int): LabelRecord { return findLabelById(labelId) ?: throw LabelIdNotFoundException(labelId) } override val labels: List<LabelRecord> get() = jdbcTemplate!!.query( "SELECT * FROM LABEL ORDER BY CATEGORY, NAME" ) { rs, _ -> rsConversion(rs) } private val rsConversion: (ResultSet) -> LabelRecord = { rs: ResultSet -> LabelRecord( id = rs.getInt("ID"), category = rs.getString("CATEGORY"), name = rs.getString("NAME"), description = rs.getString("DESCRIPTION"), color = rs.getString("COLOR"), computedBy = rs.getString("COMPUTED_BY") ) } }
mit
0a8e12ed0fee3e6f911d00df7965c0ae
38.604396
123
0.544332
5.214906
false
false
false
false
RedstonerServer/Parcels
src/main/kotlin/io/dico/parcels2/command/CommandsAdminPrivilegesGlobal.kt
1
6062
@file:Suppress("NON_EXHAUSTIVE_WHEN") package io.dico.parcels2.command import io.dico.dicore.command.ExecutionContext import io.dico.dicore.command.Validate import io.dico.dicore.command.annotation.Cmd import io.dico.dicore.command.annotation.Desc import io.dico.parcels2.* import io.dico.parcels2.Privilege.BANNED import io.dico.parcels2.Privilege.CAN_BUILD import io.dico.parcels2.PrivilegeChangeResult.* import io.dico.parcels2.defaultimpl.InfoBuilder import io.dico.parcels2.util.ext.PERM_ADMIN_MANAGE import org.bukkit.OfflinePlayer class CommandsAdminPrivilegesGlobal(plugin: ParcelsPlugin) : AbstractParcelCommands(plugin) { private val data inline get() = plugin.globalPrivileges private fun checkContext(context: ExecutionContext, owner: OfflinePlayer, changing: Boolean = true): OfflinePlayer { if (changing) { checkConnected("have privileges changed") } val sender = context.sender if (sender !== owner) { Validate.isAuthorized(sender, PERM_ADMIN_MANAGE) } return owner } @Cmd("list", aliases = ["l"]) @Desc( "List globally declared privileges, players you", "allowed to build on or banned from all your parcels", shortVersion = "lists globally declared privileges" ) fun cmdList(context: ExecutionContext, owner: OfflinePlayer): Any? { checkContext(context, owner, changing = false) val map = plugin.globalPrivileges[owner] Validate.isTrue(map.hasAnyDeclaredPrivileges(), "This user has not declared any global privileges") return StringBuilder().apply { with(InfoBuilder) { appendProfilesWithPrivilege("Globally Allowed", map, null, CAN_BUILD) appendProfilesWithPrivilege("Globally Banned", map, null, BANNED) } }.toString() } @Cmd("entrust") @Desc( "Allows a player to manage globally", shortVersion = "allows a player to manage globally" ) suspend fun cmdEntrust(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].allowManage(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is already allowed to manage globally") SUCCESS -> "${player.name} is now allowed to manage globally" } @Cmd("distrust") @Desc( "Disallows a player to manage globally,", "they will still be able to build", shortVersion = "disallows a player to manage globally" ) suspend fun cmdDistrust(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].disallowManage(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is not currently allowed to manage globally") SUCCESS -> "${player.name} is not allowed to manage globally anymore" } @Cmd("allow", aliases = ["add", "permit"]) @Desc( "Globally allows a player to build on all", "the parcels that you own.", shortVersion = "globally allows a player to build on your parcels" ) suspend fun cmdAllow(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].allowBuild(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is already allowed globally") SUCCESS -> "${player.name} is now allowed to build globally" } @Cmd("disallow", aliases = ["remove", "forbid"]) @Desc( "Globally disallows a player to build on", "the parcels that you own.", "If the player is allowed to build on specific", "parcels, they can still build there.", shortVersion = "globally disallows a player to build on your parcels" ) suspend fun cmdDisallow(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].disallowBuild(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is not currently allowed globally") SUCCESS -> "${player.name} is not allowed to build globally anymore" } @Cmd("ban", aliases = ["deny"]) @Desc( "Globally bans a player from all the parcels", "that you own, making them unable to enter.", shortVersion = "globally bans a player from your parcels" ) suspend fun cmdBan(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].disallowEnter(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is already banned globally") SUCCESS -> "${player.name} is now banned globally" } @Cmd("unban", aliases = ["undeny"]) @Desc( "Globally unbans a player from all the parcels", "that you own, they can enter again.", "If the player is banned from specific parcels,", "they will still be banned there.", shortVersion = "globally unbans a player from your parcels" ) suspend fun cmdUnban(context: ExecutionContext, owner: OfflinePlayer, player: PlayerProfile): Any? = when (data[checkContext(context, owner)].allowEnter(toPrivilegeKey(player))) { FAIL_OWNER -> err("The target cannot be the owner themselves") FAIL -> err("${player.name} is not currently banned globally") SUCCESS -> "${player.name} is not banned globally anymore" } }
gpl-2.0
61923d85ddcc22fda3ddafafe3e0cfec
43.939394
120
0.643187
4.463918
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/controllers/base/ViewModelCreationInterface.kt
1
1158
package de.xikolo.controllers.base import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import de.xikolo.viewmodels.base.BaseViewModel interface ViewModelCreationInterface<T : BaseViewModel> { var viewModel: T fun createViewModel(): T private fun createViewModelFactory(vm: ViewModel): ViewModelProvider.NewInstanceFactory = object : ViewModelProvider.NewInstanceFactory() { override fun <S : ViewModel?> create(modelClass: Class<S>): S { @Suppress("unchecked_cast") return vm as S } } fun initViewModel(fragment: Fragment) { val vm = createViewModel() val factory = createViewModelFactory(vm) viewModel = ViewModelProviders.of(fragment, factory).get(vm.javaClass) } fun initViewModel(fragmentActivity: FragmentActivity) { val vm = createViewModel() val factory = createViewModelFactory(vm) viewModel = ViewModelProviders.of(fragmentActivity, factory).get(vm.javaClass) } }
bsd-3-clause
635637507a38faf0a12fac49f02e0a61
32.085714
143
0.73057
5.101322
false
false
false
false
apixandru/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/cs/GrReplaceMultiAssignmentFix.kt
9
3228
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.codeInspection.cs import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.GrInspectionUtil import org.jetbrains.plugins.groovy.codeInspection.GroovyFix import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner import org.jetbrains.plugins.groovy.refactoring.DefaultGroovyVariableNameValidator import org.jetbrains.plugins.groovy.refactoring.GroovyNameSuggestionUtil internal val defaultFixVariableName = "storedList" class GrReplaceMultiAssignmentFix(val size: Int) : GroovyFix() { override fun doFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? GrExpression ?: return val grStatement = element.parent as? GrStatement ?: return val grStatementOwner = grStatement.parent as? GrStatementOwner ?: return var initializer = element.text if (element !is GrReferenceExpression || element.resolve() !is GrVariable) { val factory = GroovyPsiElementFactory.getInstance(element.project) val fixVariableName = generateVariableName(element) val varDefinition = factory.createStatementFromText("def ${fixVariableName} = ${initializer}") grStatementOwner.addStatementBefore(varDefinition, grStatement) initializer = fixVariableName } GrInspectionUtil.replaceExpression(element, generateListLiteral(initializer)) } private fun generateVariableName(expression: GrExpression): String { val validator = DefaultGroovyVariableNameValidator(expression) val suggestedNames = GroovyNameSuggestionUtil.suggestVariableNameByType(expression.type, validator) return if (suggestedNames.isNotEmpty()) suggestedNames[0] else defaultFixVariableName } private fun generateListLiteral(varName: String): String { return (0..(size - 1)).joinToString(", ", "[", "]") { "$varName[$it]" } } override fun getName(): String { return GroovyBundle.message("replace.with.list.literal") } @Nls override fun getFamilyName(): String { return GroovyBundle.message("replace.with.list.literal") } }
apache-2.0
7b2ca9534da10991316731954c2cf881
44.464789
103
0.787794
4.546479
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/api/OAuth2NetworkManager.kt
1
3138
package com.pennapps.labs.pennmobile.api import android.preference.PreferenceManager import android.provider.Settings import android.util.Log import com.pennapps.labs.pennmobile.BuildConfig import com.pennapps.labs.pennmobile.MainActivity import com.pennapps.labs.pennmobile.R import com.pennapps.labs.pennmobile.classes.AccessTokenResponse import retrofit.Callback import retrofit.RetrofitError import retrofit.client.Response import java.util.* class OAuth2NetworkManager(private var mActivity: MainActivity) { private var mPlatform = MainActivity.platformInstance private val sp = PreferenceManager.getDefaultSharedPreferences(mActivity) val editor = sp?.edit() fun getDeviceId() : String { val deviceID = Settings.Secure.getString(mActivity.contentResolver, Settings.Secure.ANDROID_ID) ?: "test" return deviceID } fun getAccessToken() { val expiresIn = sp.getString(mActivity.getString(R.string.expires_in), "") if (expiresIn != "") { val seconds = expiresIn?.toInt() val calendar = Calendar.getInstance() val expiresAt = Date(sp.getLong(mActivity.getString(R.string.token_generated), 0)) calendar.time = Date() if (seconds != null) { calendar.add(Calendar.SECOND, -seconds) } if (calendar.time.after(expiresAt)) { // if it has expired, refresh access token refreshAccessToken() } } } private fun refreshAccessToken() { val refreshToken = sp.getString(mActivity.getString(R.string.refresh_token), "") val clientID = BuildConfig.PLATFORM_CLIENT_ID mPlatform.refreshAccessToken(refreshToken, "refresh_token", clientID, object : Callback<AccessTokenResponse> { override fun success(t: AccessTokenResponse?, response: Response?) { if (response?.status == 200) { val editor = sp.edit() editor.putString(mActivity.getString(R.string.access_token), t?.accessToken) editor.putString(mActivity.getString(R.string.refresh_token), t?.refreshToken) editor.putString(mActivity.getString(R.string.expires_in), t?.expiresIn) val calendar = Calendar.getInstance() calendar.time = Date() val expiresIn = t?.expiresIn val expiresInInt = expiresIn!!.toInt() val date = Date(System.currentTimeMillis().plus(expiresInInt)) //or simply new Date(); editor.putLong(mActivity.getString(R.string.token_generated), date.time) editor.apply() } } override fun failure(error: RetrofitError) { Log.e("Accounts", "Error refreshing access token $error") // mActivity.startLoginFragment() } }) } }
mit
25684d5742aded0dff02e4e611bea917
41.418919
114
0.595602
5.20398
false
false
false
false
digammas/damas
solutions.digamma.damas.jcr/src/main/kotlin/solutions/digamma/damas/jcr/content/JcrComment.kt
1
2592
package solutions.digamma.damas.jcr.content import solutions.digamma.damas.common.CompatibilityException import solutions.digamma.damas.common.InternalStateException import solutions.digamma.damas.common.WorkspaceException import solutions.digamma.damas.content.Comment import solutions.digamma.damas.jcr.common.Exceptions import solutions.digamma.damas.jcr.model.JcrBaseEntity import solutions.digamma.damas.jcr.model.JcrCreated import solutions.digamma.damas.jcr.model.JcrModifiable import solutions.digamma.damas.jcr.names.ItemNamespace import solutions.digamma.damas.jcr.names.TypeNamespace import java.util.UUID import javax.jcr.Node import javax.jcr.Property import javax.jcr.Session /** * @author Ahmad Shahwan * * @param node comment's JCR node * * @throws WorkspaceException */ internal class JcrComment @Throws(WorkspaceException::class) private constructor(node: Node) : JcrBaseEntity(node), Comment, JcrCommentReceiver, JcrCreated, JcrModifiable { override fun getText(): String { return this.getString(Property.JCR_CONTENT) ?: "" } override fun setText(value: String) { this.setString(Property.JCR_CONTENT, value) } override fun getReceiverId(): String = Exceptions.uncheck { this.node.parent.identifier } override fun getReceiver() = { this.node } as JcrCommentReceiver override fun getRank(): Long? = this.getLong(ItemNamespace.RANK) override fun setRank(value: Long?) = this.setLong(ItemNamespace.RANK, value) @Throws(InternalStateException::class) override fun checkCompatibility() = this.checkTypeCompatibility(TypeNamespace.COMMENT) @Throws(WorkspaceException::class) fun update(other: Comment) { other.rank?.let { this.rank = it } other.text?.let { this.text = it } } companion object { /** * Factory method to create comment out of JCR node. */ @Throws(WorkspaceException::class) fun of(node: Node) = JcrComment(node) @Throws(WorkspaceException::class) fun from(session: Session, receiverId: String) = Exceptions.check { val name = UUID.randomUUID().toString() val parent = session.getNodeByIdentifier(receiverId) if (!parent.isNodeType(TypeNamespace.COMMENT_RECEIVER)) { throw CompatibilityException("Parent cannot receive comments.") } val node = parent.addNode(name, TypeNamespace.COMMENT) JcrComment.of(node).also { it.rank = 0 } } } }
mit
5bf27c4e3a2b56d1256dde0e330eae5b
30.609756
80
0.697145
4.270181
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/twitter/card/TwitterCardViewFactory.kt
1
3117
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.util.twitter.card import de.vanita5.twittnuker.extension.model.getString import de.vanita5.twittnuker.model.ParcelableCardEntity import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.util.TwitterCardUtils import de.vanita5.twittnuker.view.ContainerView import de.vanita5.twittnuker.view.controller.twitter.card.CardBrowserViewController import de.vanita5.twittnuker.view.controller.twitter.card.CardPollViewController import java.util.* abstract class TwitterCardViewFactory { abstract fun from(status: ParcelableStatus): ContainerView.ViewController? companion object { fun from(status: ParcelableStatus): ContainerView.ViewController? { val vc = fromImplementations(status) if (vc != null) return vc return createCardFragment(status) } private fun fromImplementations(status: ParcelableStatus): ContainerView.ViewController? { ServiceLoader.load(TwitterCardViewFactory::class.java).forEach { factory -> val vc = factory.from(status) if (vc != null) return vc } return null } private fun createCardFragment(status: ParcelableStatus): ContainerView.ViewController? { val card = status.card if (card == null || card.name == null) return null if (TwitterCardUtils.CARD_NAME_PLAYER == card.name) { return createGenericPlayerFragment(card) } else if (TwitterCardUtils.CARD_NAME_AUDIO == card.name) { return createGenericPlayerFragment(card) } else if (TwitterCardUtils.isPoll(card)) { return createCardPollFragment(status) } return null } private fun createCardPollFragment(status: ParcelableStatus): ContainerView.ViewController { return CardPollViewController.show(status) } private fun createGenericPlayerFragment(card: ParcelableCardEntity): ContainerView.ViewController? { val playerUrl = card.getString("player_url") ?: return null return CardBrowserViewController.show(playerUrl) } } }
gpl-3.0
471dcee9beb83ac5c7f66d2db7a63bd1
40.026316
108
0.697466
4.517391
false
false
false
false
stripe/stripe-android
stripe-core/src/main/java/com/stripe/android/core/model/CountryCode.kt
1
849
package com.stripe.android.core.model import android.os.Parcelable import androidx.annotation.RestrictTo import kotlinx.parcelize.Parcelize import java.util.Locale @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun Locale.getCountryCode(): CountryCode = CountryCode.create(this.country) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @Parcelize data class CountryCode( val value: String ) : Parcelable { @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) companion object { val US = CountryCode("US") val CA = CountryCode("CA") val GB = CountryCode("GB") fun isUS(countryCode: CountryCode?) = countryCode == US fun isCA(countryCode: CountryCode?) = countryCode == CA fun isGB(countryCode: CountryCode?) = countryCode == GB fun create(value: String) = CountryCode(value.uppercase()) } }
mit
9eab33b04f332f0a6b43a8950210c7c9
30.444444
75
0.716137
4.266332
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/GestureHandler.kt
2
23005
package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler import android.view.MotionEvent import android.view.MotionEvent.PointerCoords import android.view.MotionEvent.PointerProperties import android.view.View import abi44_0_0.com.facebook.react.bridge.Arguments import abi44_0_0.com.facebook.react.bridge.UiThreadUtil import abi44_0_0.com.facebook.react.bridge.WritableArray import abi44_0_0.com.facebook.react.uimanager.PixelUtil import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerTouchEvent import java.lang.IllegalStateException import java.util.* open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestureHandlerT>> { private val trackedPointerIDs = IntArray(MAX_POINTERS_COUNT) private var trackedPointersIDsCount = 0 var tag = 0 var view: View? = null private set var state = STATE_UNDETERMINED private set var x = 0f private set var y = 0f private set var isWithinBounds = false private set var isEnabled = true private set var usesDeviceEvents = false var changedTouchesPayload: WritableArray? = null private set var allTouchesPayload: WritableArray? = null private set var touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED private set var trackedPointersCount = 0 private set private val trackedPointers: Array<PointerData?> = Array(MAX_POINTERS_COUNT) { null } var needsPointerData = false private var hitSlop: FloatArray? = null var eventCoalescingKey: Short = 0 private set var lastAbsolutePositionX = 0f private set var lastAbsolutePositionY = 0f private set private var manualActivation = false private var lastEventOffsetX = 0f private var lastEventOffsetY = 0f private var shouldCancelWhenOutside = false var numberOfPointers = 0 private set private var orchestrator: GestureHandlerOrchestrator? = null private var onTouchEventListener: OnTouchEventListener? = null private var interactionController: GestureHandlerInteractionController? = null @Suppress("UNCHECKED_CAST") protected fun self(): ConcreteGestureHandlerT = this as ConcreteGestureHandlerT protected inline fun applySelf(block: ConcreteGestureHandlerT.() -> Unit): ConcreteGestureHandlerT = self().apply { block() } // set and accessed only by the orchestrator var activationIndex = 0 // set and accessed only by the orchestrator var isActive = false // set and accessed only by the orchestrator var isAwaiting = false open fun dispatchStateChange(newState: Int, prevState: Int) { onTouchEventListener?.onStateChange(self(), newState, prevState) } open fun dispatchHandlerUpdate(event: MotionEvent) { onTouchEventListener?.onHandlerUpdate(self(), event) } open fun dispatchTouchEvent() { if (changedTouchesPayload != null) { onTouchEventListener?.onTouchEvent(self()) } } open fun resetConfig() { needsPointerData = false manualActivation = false shouldCancelWhenOutside = false isEnabled = true hitSlop = null } fun hasCommonPointers(other: GestureHandler<*>): Boolean { for (i in trackedPointerIDs.indices) { if (trackedPointerIDs[i] != -1 && other.trackedPointerIDs[i] != -1) { return true } } return false } fun setShouldCancelWhenOutside(shouldCancelWhenOutside: Boolean): ConcreteGestureHandlerT = applySelf { this.shouldCancelWhenOutside = shouldCancelWhenOutside } fun setEnabled(enabled: Boolean): ConcreteGestureHandlerT = applySelf { // Don't cancel handler when not changing the value of the isEnabled, executing it always caused // handlers to be cancelled on re-render because that's the moment when the config is updated. // If the enabled prop "changed" from true to true the handler would get cancelled. if (view != null && isEnabled != enabled) { // If view is set then handler is in "active" state. In that case we want to "cancel" handler // when it changes enabled state so that it gets cleared from the orchestrator UiThreadUtil.runOnUiThread { cancel() } } isEnabled = enabled } fun setManualActivation(manualActivation: Boolean): ConcreteGestureHandlerT = applySelf { this.manualActivation = manualActivation } fun setHitSlop( leftPad: Float, topPad: Float, rightPad: Float, bottomPad: Float, width: Float, height: Float, ): ConcreteGestureHandlerT = applySelf { if (hitSlop == null) { hitSlop = FloatArray(6) } hitSlop!![HIT_SLOP_LEFT_IDX] = leftPad hitSlop!![HIT_SLOP_TOP_IDX] = topPad hitSlop!![HIT_SLOP_RIGHT_IDX] = rightPad hitSlop!![HIT_SLOP_BOTTOM_IDX] = bottomPad hitSlop!![HIT_SLOP_WIDTH_IDX] = width hitSlop!![HIT_SLOP_HEIGHT_IDX] = height require(!(hitSlopSet(width) && hitSlopSet(leftPad) && hitSlopSet(rightPad))) { "Cannot have all of left, right and width defined" } require(!(hitSlopSet(width) && !hitSlopSet(leftPad) && !hitSlopSet(rightPad))) { "When width is set one of left or right pads need to be defined" } require(!(hitSlopSet(height) && hitSlopSet(bottomPad) && hitSlopSet(topPad))) { "Cannot have all of top, bottom and height defined" } require(!(hitSlopSet(height) && !hitSlopSet(bottomPad) && !hitSlopSet(topPad))) { "When height is set one of top or bottom pads need to be defined" } } fun setHitSlop(padding: Float): ConcreteGestureHandlerT { return setHitSlop(padding, padding, padding, padding, HIT_SLOP_NONE, HIT_SLOP_NONE) } fun setInteractionController(controller: GestureHandlerInteractionController?): ConcreteGestureHandlerT = applySelf { interactionController = controller } fun prepare(view: View?, orchestrator: GestureHandlerOrchestrator?) { check(!(this.view != null || this.orchestrator != null)) { "Already prepared or hasn't been reset" } Arrays.fill(trackedPointerIDs, -1) trackedPointersIDsCount = 0 state = STATE_UNDETERMINED this.view = view this.orchestrator = orchestrator } private fun findNextLocalPointerId(): Int { var localPointerId = 0 while (localPointerId < trackedPointersIDsCount) { var i = 0 while (i < trackedPointerIDs.size) { if (trackedPointerIDs[i] == localPointerId) { break } i++ } if (i == trackedPointerIDs.size) { return localPointerId } localPointerId++ } return localPointerId } fun startTrackingPointer(pointerId: Int) { if (trackedPointerIDs[pointerId] == -1) { trackedPointerIDs[pointerId] = findNextLocalPointerId() trackedPointersIDsCount++ } } fun stopTrackingPointer(pointerId: Int) { if (trackedPointerIDs[pointerId] != -1) { trackedPointerIDs[pointerId] = -1 trackedPointersIDsCount-- } } private fun needAdapt(event: MotionEvent): Boolean { if (event.pointerCount != trackedPointersIDsCount) { return true } for (i in trackedPointerIDs.indices) { val trackedPointer = trackedPointerIDs[i] if (trackedPointer != -1 && trackedPointer != i) { return true } } return false } private fun adaptEvent(event: MotionEvent): MotionEvent { if (!needAdapt(event)) { return event } var action = event.actionMasked var actionIndex = -1 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) { actionIndex = event.actionIndex val actionPointer = event.getPointerId(actionIndex) action = if (trackedPointerIDs[actionPointer] != -1) { if (trackedPointersIDsCount == 1) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_POINTER_DOWN } else { MotionEvent.ACTION_MOVE } } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { actionIndex = event.actionIndex val actionPointer = event.getPointerId(actionIndex) action = if (trackedPointerIDs[actionPointer] != -1) { if (trackedPointersIDsCount == 1) MotionEvent.ACTION_UP else MotionEvent.ACTION_POINTER_UP } else { MotionEvent.ACTION_MOVE } } initPointerProps(trackedPointersIDsCount) var count = 0 val oldX = event.x val oldY = event.y event.setLocation(event.rawX, event.rawY) var index = 0 val size = event.pointerCount while (index < size) { val origPointerId = event.getPointerId(index) if (trackedPointerIDs[origPointerId] != -1) { event.getPointerProperties(index, pointerProps[count]) pointerProps[count]!!.id = trackedPointerIDs[origPointerId] event.getPointerCoords(index, pointerCoords[count]) if (index == actionIndex) { action = action or (count shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) } count++ } index++ } // introduced in 1.11.0, remove if crashes are not reported if (pointerProps.isEmpty() || pointerCoords.isEmpty()) { throw IllegalStateException("pointerCoords.size=${pointerCoords.size}, pointerProps.size=${pointerProps.size}") } val result: MotionEvent try { result = MotionEvent.obtain( event.downTime, event.eventTime, action, count, pointerProps, /* props are copied and hence it is safe to use static array here */ pointerCoords, /* same applies to coords */ event.metaState, event.buttonState, event.xPrecision, event.yPrecision, event.deviceId, event.edgeFlags, event.source, event.flags ) } catch (e: IllegalArgumentException) { throw AdaptEventException(this, event, e) } event.setLocation(oldX, oldY) result.setLocation(oldX, oldY) return result } // exception to help debug https://github.com/software-mansion/react-native-gesture-handler/issues/1188 class AdaptEventException( handler: GestureHandler<*>, event: MotionEvent, e: IllegalArgumentException ) : Exception( """ handler: ${handler::class.simpleName} state: ${handler.state} view: ${handler.view} orchestrator: ${handler.orchestrator} isEnabled: ${handler.isEnabled} isActive: ${handler.isActive} isAwaiting: ${handler.isAwaiting} trackedPointersCount: ${handler.trackedPointersCount} trackedPointers: ${handler.trackedPointerIDs.joinToString(separator = ", ")} while handling event: $event """.trimIndent(), e ) fun handle(origEvent: MotionEvent) { if (!isEnabled || state == STATE_CANCELLED || state == STATE_FAILED || state == STATE_END || trackedPointersIDsCount < 1 ) { return } val event = adaptEvent(origEvent) x = event.x y = event.y numberOfPointers = event.pointerCount isWithinBounds = isWithinBounds(view, x, y) if (shouldCancelWhenOutside && !isWithinBounds) { if (state == STATE_ACTIVE) { cancel() } else if (state == STATE_BEGAN) { fail() } return } lastAbsolutePositionX = GestureUtils.getLastPointerX(event, true) lastAbsolutePositionY = GestureUtils.getLastPointerY(event, true) lastEventOffsetX = event.rawX - event.x lastEventOffsetY = event.rawY - event.y onHandle(event) if (event != origEvent) { event.recycle() } } private fun dispatchTouchDownEvent(event: MotionEvent) { changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_DOWN val pointerId = event.getPointerId(event.actionIndex) val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y trackedPointers[pointerId] = PointerData( pointerId, event.getX(event.actionIndex), event.getY(event.actionIndex), event.getX(event.actionIndex) + offsetX, event.getY(event.actionIndex) + offsetY, ) trackedPointersCount++ addChangedPointer(trackedPointers[pointerId]!!) extractAllPointersData() dispatchTouchEvent() } private fun dispatchTouchUpEvent(event: MotionEvent) { extractAllPointersData() changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_UP val pointerId = event.getPointerId(event.actionIndex) val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y trackedPointers[pointerId] = PointerData( pointerId, event.getX(event.actionIndex), event.getY(event.actionIndex), event.getX(event.actionIndex) + offsetX, event.getY(event.actionIndex) + offsetY, ) addChangedPointer(trackedPointers[pointerId]!!) trackedPointers[pointerId] = null trackedPointersCount-- dispatchTouchEvent() } private fun dispatchTouchMoveEvent(event: MotionEvent) { changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_MOVE val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y var pointersAdded = 0 for (i in 0 until event.pointerCount) { val pointerId = event.getPointerId(i) val pointer = trackedPointers[pointerId] ?: continue if (pointer.x != event.getX(i) || pointer.y != event.getY(i)) { pointer.x = event.getX(i) pointer.y = event.getY(i) pointer.absoluteX = event.getX(i) + offsetX pointer.absoluteY = event.getY(i) + offsetY addChangedPointer(pointer) pointersAdded++ } } // only data about pointers that have changed their position is sent, it makes no sense to send // an empty move event (especially when this method is called during down/up event and there is // only info about one pointer) if (pointersAdded > 0) { extractAllPointersData() dispatchTouchEvent() } } fun updatePointerData(event: MotionEvent) { if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) { dispatchTouchDownEvent(event) dispatchTouchMoveEvent(event) } else if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_POINTER_UP) { dispatchTouchMoveEvent(event) dispatchTouchUpEvent(event) } else if (event.actionMasked == MotionEvent.ACTION_MOVE) { dispatchTouchMoveEvent(event) } } private fun extractAllPointersData() { allTouchesPayload = null for (pointerData in trackedPointers) { if (pointerData != null) { addPointerToAll(pointerData) } } } private fun cancelPointers() { touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_CANCELLED changedTouchesPayload = null extractAllPointersData() for (pointer in trackedPointers) { pointer?.let { addChangedPointer(it) } } trackedPointersCount = 0 trackedPointers.fill(null) dispatchTouchEvent() } private fun addChangedPointer(pointerData: PointerData) { if (changedTouchesPayload == null) { changedTouchesPayload = Arguments.createArray() } changedTouchesPayload!!.pushMap(createPointerData(pointerData)) } private fun addPointerToAll(pointerData: PointerData) { if (allTouchesPayload == null) { allTouchesPayload = Arguments.createArray() } allTouchesPayload!!.pushMap(createPointerData(pointerData)) } private fun createPointerData(pointerData: PointerData) = Arguments.createMap().apply { putInt("id", pointerData.pointerId) putDouble("x", PixelUtil.toDIPFromPixel(pointerData.x).toDouble()) putDouble("y", PixelUtil.toDIPFromPixel(pointerData.y).toDouble()) putDouble("absoluteX", PixelUtil.toDIPFromPixel(pointerData.absoluteX).toDouble()) putDouble("absoluteY", PixelUtil.toDIPFromPixel(pointerData.absoluteY).toDouble()) } fun consumeChangedTouchesPayload(): WritableArray? { val result = changedTouchesPayload changedTouchesPayload = null return result } fun consumeAllTouchesPayload(): WritableArray? { val result = allTouchesPayload allTouchesPayload = null return result } private fun moveToState(newState: Int) { UiThreadUtil.assertOnUiThread() if (state == newState) { return } // if there are tracked pointers and the gesture is about to end, send event cancelling all pointers if (trackedPointersCount > 0 && (newState == STATE_END || newState == STATE_CANCELLED || newState == STATE_FAILED)) { cancelPointers() } val oldState = state state = newState if (state == STATE_ACTIVE) { // Generate a unique coalescing-key each time the gesture-handler becomes active. All events will have // the same coalescing-key allowing EventDispatcher to coalesce RNGestureHandlerEvents when events are // generated faster than they can be treated by JS thread eventCoalescingKey = nextEventCoalescingKey++ } orchestrator!!.onHandlerStateChange(this, newState, oldState) onStateChange(newState, oldState) } fun wantEvents(): Boolean { return isEnabled && state != STATE_FAILED && state != STATE_CANCELLED && state != STATE_END && trackedPointersIDsCount > 0 } open fun shouldRequireToWaitForFailure(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldRequireHandlerToWaitForFailure(this, handler) ?: false } fun shouldWaitForHandlerFailure(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldWaitForHandlerFailure(this, handler) ?: false } open fun shouldRecognizeSimultaneously(handler: GestureHandler<*>): Boolean { if (handler === this) { return true } return interactionController?.shouldRecognizeSimultaneously(this, handler) ?: false } open fun shouldBeCancelledBy(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldHandlerBeCancelledBy(this, handler) ?: false } fun isWithinBounds(view: View?, posX: Float, posY: Float): Boolean { var left = 0f var top = 0f var right = view!!.width.toFloat() var bottom = view.height.toFloat() if (hitSlop != null) { val padLeft = hitSlop!![HIT_SLOP_LEFT_IDX] val padTop = hitSlop!![HIT_SLOP_TOP_IDX] val padRight = hitSlop!![HIT_SLOP_RIGHT_IDX] val padBottom = hitSlop!![HIT_SLOP_BOTTOM_IDX] if (hitSlopSet(padLeft)) { left -= padLeft } if (hitSlopSet(padTop)) { top -= padTop } if (hitSlopSet(padRight)) { right += padRight } if (hitSlopSet(padBottom)) { bottom += padBottom } val width = hitSlop!![HIT_SLOP_WIDTH_IDX] val height = hitSlop!![HIT_SLOP_HEIGHT_IDX] if (hitSlopSet(width)) { if (!hitSlopSet(padLeft)) { left = right - width } else if (!hitSlopSet(padRight)) { right = left + width } } if (hitSlopSet(height)) { if (!hitSlopSet(padTop)) { top = bottom - height } else if (!hitSlopSet(padBottom)) { bottom = top + height } } } return posX in left..right && posY in top..bottom } fun cancel() { if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) { onCancel() moveToState(STATE_CANCELLED) } } fun fail() { if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) { moveToState(STATE_FAILED) } } fun activate() = activate(force = false) open fun activate(force: Boolean) { if ((!manualActivation || force) && (state == STATE_UNDETERMINED || state == STATE_BEGAN)) { moveToState(STATE_ACTIVE) } } fun begin() { if (state == STATE_UNDETERMINED) { moveToState(STATE_BEGAN) } } fun end() { if (state == STATE_BEGAN || state == STATE_ACTIVE) { moveToState(STATE_END) } } protected open fun onHandle(event: MotionEvent) { moveToState(STATE_FAILED) } protected open fun onStateChange(newState: Int, previousState: Int) {} protected open fun onReset() {} protected open fun onCancel() {} fun reset() { view = null orchestrator = null Arrays.fill(trackedPointerIDs, -1) trackedPointersIDsCount = 0 trackedPointersCount = 0 trackedPointers.fill(null) touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED onReset() } fun setOnTouchEventListener(listener: OnTouchEventListener?): GestureHandler<*> { onTouchEventListener = listener return this } override fun toString(): String { val viewString = if (view == null) null else view!!.javaClass.simpleName return this.javaClass.simpleName + "@[" + tag + "]:" + viewString } val lastRelativePositionX: Float get() = lastAbsolutePositionX - lastEventOffsetX val lastRelativePositionY: Float get() = lastAbsolutePositionY - lastEventOffsetY companion object { const val STATE_UNDETERMINED = 0 const val STATE_FAILED = 1 const val STATE_BEGAN = 2 const val STATE_CANCELLED = 3 const val STATE_ACTIVE = 4 const val STATE_END = 5 const val HIT_SLOP_NONE = Float.NaN private const val HIT_SLOP_LEFT_IDX = 0 private const val HIT_SLOP_TOP_IDX = 1 private const val HIT_SLOP_RIGHT_IDX = 2 private const val HIT_SLOP_BOTTOM_IDX = 3 private const val HIT_SLOP_WIDTH_IDX = 4 private const val HIT_SLOP_HEIGHT_IDX = 5 const val DIRECTION_RIGHT = 1 const val DIRECTION_LEFT = 2 const val DIRECTION_UP = 4 const val DIRECTION_DOWN = 8 private const val MAX_POINTERS_COUNT = 12 private lateinit var pointerProps: Array<PointerProperties?> private lateinit var pointerCoords: Array<PointerCoords?> private fun initPointerProps(size: Int) { var size = size if (!::pointerProps.isInitialized) { pointerProps = arrayOfNulls(MAX_POINTERS_COUNT) pointerCoords = arrayOfNulls(MAX_POINTERS_COUNT) } while (size > 0 && pointerProps[size - 1] == null) { pointerProps[size - 1] = PointerProperties() pointerCoords[size - 1] = PointerCoords() size-- } } private var nextEventCoalescingKey: Short = 0 private fun hitSlopSet(value: Float): Boolean { return !java.lang.Float.isNaN(value) } fun stateToString(state: Int): String? { when (state) { STATE_UNDETERMINED -> return "UNDETERMINED" STATE_ACTIVE -> return "ACTIVE" STATE_FAILED -> return "FAILED" STATE_BEGAN -> return "BEGIN" STATE_CANCELLED -> return "CANCELLED" STATE_END -> return "END" } return null } } private data class PointerData( val pointerId: Int, var x: Float, var y: Float, var absoluteX: Float, var absoluteY: Float ) }
bsd-3-clause
ac0df016f836fb4bdf3a55e18cbe0b5f
30.951389
153
0.679331
4.264133
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/folding/RsFoldingBuilder.kt
2
12542
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.folding import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.folding.CodeFoldingSettings import com.intellij.lang.ASTNode import com.intellij.lang.folding.CustomFoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.FoldingGroup import com.intellij.openapi.project.DumbAware import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.tree.TokenSet import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.nextLeaf import org.rust.ide.injected.RsDoctestLanguageInjector.Companion.INJECTED_MAIN_NAME import org.rust.lang.RsLanguage import org.rust.lang.core.parser.RustParserDefinition.Companion.BLOCK_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_BLOCK_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_EOL_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.ext.* import org.rust.openapiext.document import java.lang.Integer.max class RsFoldingBuilder : CustomFoldingBuilder(), DumbAware { override fun getLanguagePlaceholderText(node: ASTNode, range: TextRange): String { when (node.elementType) { LBRACE -> return " { " RBRACE -> return " }" USE_ITEM -> return "..." } return when (node.psi) { is RsModDeclItem, is RsExternCrateItem, is RsWhereClause -> "..." is PsiComment -> "/* ... */" is RsValueParameterList -> "(...)" else -> "{...}" } } override fun buildLanguageFoldRegions(descriptors: MutableList<FoldingDescriptor>, root: PsiElement, document: Document, quick: Boolean) { if (root !is RsFile) return val usingRanges: MutableList<TextRange> = ArrayList() val modsRanges: MutableList<TextRange> = ArrayList() val cratesRanges: MutableList<TextRange> = ArrayList() val rightMargin = CodeStyle.getSettings(root).getRightMargin(RsLanguage) val visitor = FoldingVisitor(descriptors, usingRanges, modsRanges, cratesRanges, rightMargin) PsiTreeUtil.processElements(root) { it.accept(visitor); true } } private class FoldingVisitor( private val descriptors: MutableList<FoldingDescriptor>, private val usesRanges: MutableList<TextRange>, private val modsRanges: MutableList<TextRange>, private val cratesRanges: MutableList<TextRange>, val rightMargin: Int ) : RsVisitor() { override fun visitMacroBody(o: RsMacroBody) = fold(o) override fun visitMacroExpansion(o: RsMacroExpansion) = fold(o) override fun visitMacro2(o: RsMacro2) { foldBetween(o, o.lparen, o.rparen) foldBetween(o, o.lbrace, o.rbrace) } override fun visitStructLiteralBody(o: RsStructLiteralBody) = fold(o) override fun visitEnumBody(o: RsEnumBody) = fold(o) override fun visitBlockFields(o: RsBlockFields) = fold(o) override fun visitBlock(o: RsBlock) { if (tryFoldBlockWhitespaces(o)) return val parentFn = o.parent as? RsFunction if (parentFn?.name != INJECTED_MAIN_NAME) fold(o) } override fun visitMatchBody(o: RsMatchBody) = fold(o) override fun visitUseGroup(o: RsUseGroup) = fold(o) override fun visitWhereClause(clause: RsWhereClause) { val start = clause.where.foldRegionStart() // RsWhereClause always has at least one child - the `where` keyword val end = clause.lastChild.endOffset if (end > start) { descriptors += FoldingDescriptor(clause.node, TextRange(start, end)) } } override fun visitMembers(o: RsMembers) = foldBetween(o, o.lbrace, o.rbrace) override fun visitModItem(o: RsModItem) = foldBetween(o, o.lbrace, o.rbrace) override fun visitForeignModItem(o: RsForeignModItem) = foldBetween(o, o.lbrace, o.rbrace) override fun visitMacroArgument(o: RsMacroArgument) { val macroCall = o.parent as? RsMacroCall if (macroCall?.bracesKind == MacroBraces.BRACES) { foldBetween(o, o.lbrace, o.rbrace) } } override fun visitValueParameterList(o: RsValueParameterList) { if (o.valueParameterList.isEmpty()) return foldBetween(o, o.firstChild, o.lastChild) } override fun visitComment(comment: PsiComment) { when (comment.tokenType) { BLOCK_COMMENT, INNER_BLOCK_DOC_COMMENT, OUTER_BLOCK_DOC_COMMENT, INNER_EOL_DOC_COMMENT, OUTER_EOL_DOC_COMMENT -> fold(comment) } } override fun visitStructItem(o: RsStructItem) { val blockFields = o.blockFields if (blockFields != null) { fold(blockFields) } } private fun fold(element: PsiElement) { descriptors += FoldingDescriptor(element.node, element.textRange) } private fun foldBetween(element: PsiElement, left: PsiElement?, right: PsiElement?) { if (left != null && right != null && right.textLength > 0) { val range = TextRange(left.textOffset, right.textOffset + 1) descriptors += FoldingDescriptor(element.node, range) } } private fun tryFoldBlockWhitespaces(block: RsBlock): Boolean { if (block.parent !is RsFunction) return false val doc = block.containingFile.document ?: return false val maxLength = rightMargin - block.getOffsetInLine(doc) - ONE_LINER_PLACEHOLDERS_EXTRA_LENGTH if (!block.isSingleLine(doc, maxLength)) return false val lbrace = block.lbrace val rbrace = block.rbrace ?: return false val blockElement = lbrace.getNextNonCommentSibling() if (blockElement == null || blockElement != rbrace.getPrevNonCommentSibling()) return false if (blockElement.textContains('\n')) return false if (!(doc.areOnAdjacentLines(lbrace, blockElement) && doc.areOnAdjacentLines(blockElement, rbrace))) return false val leadingSpace = lbrace.nextSibling as? PsiWhiteSpace ?: return false val trailingSpace = rbrace.prevSibling as? PsiWhiteSpace ?: return false val leftEl = block.prevSibling as? PsiWhiteSpace ?: lbrace val range1 = TextRange(leftEl.textOffset, leadingSpace.endOffset) val range2 = TextRange(trailingSpace.textOffset, rbrace.endOffset) val group = FoldingGroup.newGroup("one-liner") descriptors += FoldingDescriptor(lbrace.node, range1, group) descriptors += FoldingDescriptor(rbrace.node, range2, group) return true } override fun visitUseItem(o: RsUseItem) { foldRepeatingItems(o, o.use, o.use, usesRanges) } override fun visitModDeclItem(o: RsModDeclItem) { foldRepeatingItems(o, o.mod, o.mod, modsRanges) } override fun visitExternCrateItem(o: RsExternCrateItem) { foldRepeatingItems(o, o.extern, o.crate, cratesRanges) } private inline fun <reified T : RsDocAndAttributeOwner> foldRepeatingItems( startNode: T, startKeyword: PsiElement, endKeyword: PsiElement, ranges: MutableList<TextRange> ) { if (isInRangesAlready(ranges, startNode as PsiElement)) return val lastNode = startNode.rightSiblings .filterNot { it is PsiComment || it is PsiWhiteSpace } .takeWhile { it is T } .lastOrNull() ?: return val trailingSemicolon = when (lastNode) { is RsModDeclItem -> lastNode.semicolon is RsExternCrateItem -> lastNode.semicolon is RsUseItem -> lastNode.semicolon else -> null } val foldStartOffset = endKeyword.foldRegionStart() val foldEndOffset = trailingSemicolon?.startOffset ?: lastNode.endOffset // This condition may be false when only the leading keyword is present, but the node is malformed. // We don't collapse such nodes (even though they may have attributes). if (foldStartOffset < foldEndOffset) { val totalRange = TextRange(startNode.startOffset, lastNode.endOffset) ranges.add(totalRange) val group = FoldingGroup.newGroup("${T::javaClass}") val primaryFoldRange = TextRange(foldStartOffset, foldEndOffset) // TODO: the leading keyword is excluded from folding. This makes it pretty on display, but // disables the fold action on it (and also on the last semicolon, if present). I don't // know whether it is possible to display those tokens unfolded, but still provide fold // action. Kotlin, which implements similar import folding logic, doesn't solve that // problem. descriptors += FoldingDescriptor(startNode.node, primaryFoldRange, group) if (startNode.startOffset < startKeyword.startOffset) { // Hide leading attributes and doc comments val attrRange = TextRange(startNode.startOffset, startKeyword.startOffset) descriptors += FoldingDescriptor(startNode.node, attrRange, group, "") } } } private fun isInRangesAlready(ranges: MutableList<TextRange>, element: PsiElement?): Boolean { if (element == null) return false return ranges.any { x -> element.textOffset in x } } } override fun isCustomFoldingRoot(node: ASTNode) = node.elementType == BLOCK override fun isRegionCollapsedByDefault(node: ASTNode): Boolean = (RsCodeFoldingSettings.getInstance().collapsibleOneLineMethods && node.elementType in COLLAPSED_BY_DEFAULT) || CodeFoldingSettings.getInstance().isDefaultCollapsedNode(node) private companion object { val COLLAPSED_BY_DEFAULT = TokenSet.create(LBRACE, RBRACE) const val ONE_LINER_PLACEHOLDERS_EXTRA_LENGTH = 4 } } private fun CodeFoldingSettings.isDefaultCollapsedNode(node: ASTNode) = (this.COLLAPSE_DOC_COMMENTS && node.elementType in RS_DOC_COMMENTS) || (this.COLLAPSE_IMPORTS && node.elementType == USE_ITEM) || (this.COLLAPSE_METHODS && node.elementType == BLOCK && node.psi.parent is RsFunction) private fun Document.areOnAdjacentLines(first: PsiElement, second: PsiElement): Boolean = getLineNumber(first.endOffset) + 1 == getLineNumber(second.startOffset) private fun RsBlock.isSingleLine(doc: Document, maxLength: Int): Boolean { // remove all leading and trailing spaces before counting lines val startContents = lbrace.rightSiblings.dropWhile { it is PsiWhiteSpace }.firstOrNull() ?: return false if (startContents.node.elementType == RBRACE) return false val endContents = rbrace?.leftSiblings?.dropWhile { it is PsiWhiteSpace }?.firstOrNull() ?: return false if (endContents.endOffset - startContents.textOffset > maxLength) return false return doc.getLineNumber(startContents.textOffset) == doc.getLineNumber(endContents.endOffset) } private fun PsiElement.getOffsetInLine(doc: Document): Int { val blockLine = doc.getLineNumber(startOffset) return leftLeaves .takeWhile { doc.getLineNumber(it.endOffset) == blockLine } .sumOf { el -> el.text.lastIndexOf('\n').let { el.text.length - max(it + 1, 0) } } } private fun PsiElement.foldRegionStart(): Int { val nextLeaf = nextLeaf(skipEmptyElements = true) ?: return endOffset return if (nextLeaf.text.startsWith(' ')) { endOffset + 1 } else { endOffset } }
mit
42eacadf2b8dedc344431696e49c8178
42.700348
142
0.659225
4.7009
false
false
false
false
recruit-mp/LightCalendarView
library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/LightCalendarView.kt
1
9845
/* * Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.recruit_mp.android.lightcalendarview import android.content.Context import android.content.res.ColorStateList import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.util.AttributeSet import android.util.TypedValue import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import java.util.* /** * 月カレンダーのカルーセルを表示する {@link FrameLayout} * Created by masayuki-recruit on 8/18/16. */ class LightCalendarView(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : ViewPager(context, attrs) { private var settings: CalendarSettings = CalendarSettings(context) private var selectedPage: Int = 0 var onMonthSelected: ((date: Date, view: MonthView) -> Unit)? = null var onDateSelected: ((date: Date) -> Unit)? = null private val onPageChangeListener: OnPageChangeListener = object : SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { selectedPage = position getMonthViewForPosition(position)?.let { view -> onMonthSelected?.invoke(getDateForPosition(position), view) } } } var monthCurrent: Date get() = getDateForPosition(currentItem) set(value) { currentItem = getPositionForDate(value) } var monthFrom: Date = CalendarKt.getInstance(settings).apply { set(Date().getFiscalYear(settings), Calendar.APRIL, 1) }.time set(value) { field = value adapter.notifyDataSetChanged() } var monthTo: Date = CalendarKt.getInstance(settings).apply { set(monthFrom.getFiscalYear(settings) + 1, Calendar.MARCH, 1) }.time set(value) { field = value adapter.notifyDataSetChanged() } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : this(context, attrs, defStyleAttr, 0) init { val a = context.obtainStyledAttributes(attrs, R.styleable.LightCalendarView, defStyleAttr, defStyleRes) (0..a.indexCount - 1).forEach { i -> val attr = a.getIndex(i) when (attr) { R.styleable.LightCalendarView_lcv_weekDayTextSize -> setWeekDayRawTextSize(a.getDimension(attr, 0f)) R.styleable.LightCalendarView_lcv_dayTextSize -> setDayRawTextSize(a.getDimension(attr, 0f)) R.styleable.LightCalendarView_lcv_textColor -> setTextColor(a.getColorStateList(attr)) R.styleable.LightCalendarView_lcv_selectionColor -> setSelectionColor(a.getColorStateList(attr)) R.styleable.LightCalendarView_lcv_accentColor -> setAccentColor(a.getColorStateList(attr)) R.styleable.LightCalendarView_lcv_firstDayOfWeek -> setFirstDayOfWeek(a.getInt(attr, 0)) } } a.recycle() adapter = Adapter() addOnPageChangeListener(onPageChangeListener) currentItem = getPositionForDate(Date()) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var heightMeasureSpec = heightMeasureSpec // 高さの WRAP_CONTENT を有効にする val (specHeightSize, specHeightMode) = Measure.createFromSpec(heightMeasureSpec) if (specHeightMode == MeasureSpec.AT_MOST || specHeightMode == MeasureSpec.UNSPECIFIED) { val height = childList.map { it.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(specHeightSize, specHeightMode)) it.measuredHeight }.fold(0, { h1, h2 -> Math.max(h1, h2) }) heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY) } super.onMeasure(widthMeasureSpec, heightMeasureSpec) } /** * {@link ViewPager} のページに対応する月を返す */ fun getDateForPosition(position: Int): Date = monthFrom.add(settings, Calendar.MONTH, position) /** * 月に対応する {@link ViewPager} のページを返す */ fun getPositionForDate(date: Date): Int = date.monthsAfter(settings, monthFrom).toInt() /** * {@link ViewPager} の特定のページにある {@link MonthView} を返す */ fun getMonthViewForPosition(position: Int): MonthView? = findViewWithTag(context.getString(R.string.month_view_tag_name, position)) as? MonthView /** * 特定の日付を選択する */ fun setSelectedDate(date: Date) { getMonthViewForPosition(getPositionForDate(date))?.setSelectedDate(date) } /** * 曜日ビューの文字サイズを設定する */ fun setWeekDayTextSize(unit: Int, size: Float) { setWeekDayRawTextSize(TypedValue.applyDimension(unit, size, context.resources.displayMetrics)) } private fun setWeekDayRawTextSize(size: Float) { settings.weekDayView.apply { textSize = size }.notifySettingsChanged() } /** * 日付ビューの文字サイズを指定する */ fun setDayTextSize(unit: Int, size: Float) { setDayRawTextSize(TypedValue.applyDimension(unit, size, context.resources.displayMetrics)) } private fun setDayRawTextSize(size: Float) { settings.dayView.apply { textSize = size }.notifySettingsChanged() } /** * 文字色を設定する */ fun setTextColor(color: Int) { settings.weekDayView.apply { textColor = color }.notifySettingsChanged() settings.dayView.apply { textColor = color }.notifySettingsChanged() } /** * 文字色を設定する */ fun setTextColor(colorStateList: ColorStateList) { settings.weekDayView.apply { setTextColorStateList(colorStateList) }.notifySettingsChanged() settings.dayView.apply { setTextColorStateList(colorStateList) }.notifySettingsChanged() } /** * 日付ビューの選択時の背景色を設定する */ fun setSelectionColor(colorStateList: ColorStateList) { settings.dayView.apply { setCircleColorStateList(colorStateList) }.notifySettingsChanged() } /** * 日付ビューのアクセントの色を設定する */ fun setAccentColor(colorStateList: ColorStateList) { settings.dayView.apply { setAccentColorStateList(colorStateList) }.notifySettingsChanged() } /** * Sets color of a weekday of the week */ fun setWeekDayFilterColor(weekDay: WeekDay, color: Int?) { settings.weekDayView.apply { setTextFilterColor(weekDay, color) }.notifySettingsChanged() } /** * Sets color of a day of the week */ fun setDayFilterColor(weekDay: WeekDay, color: Int?) { settings.dayView.apply { setTextFilterColor(weekDay, color) }.notifySettingsChanged() } /** * First day of the week (e.g. Sunday, Monday, ...) */ var firstDayOfWeek: WeekDay get() = settings.firstDayOfWeek set(value) { settings.firstDayOfWeek = value settings.notifySettingsChanged() } private fun setFirstDayOfWeek(n: Int) { firstDayOfWeek = WeekDay.fromOrdinal(n) } /** * Sets the timezone to use in LightCalendarView. * Set null to use TimeZone.getDefault() */ var timeZone: TimeZone get() = settings.timeZone set(value) { settings.apply { timeZone = value }.notifySettingsChanged() } /** * Sets the locale to use in LightCalendarView. * Set null to use Locale.getDefault() */ var locale: Locale get() = settings.locale set(value) { settings.apply { locale = value }.notifySettingsChanged() } private inner class Adapter : PagerAdapter() { override fun instantiateItem(container: ViewGroup?, position: Int): View { val view = MonthView(context, settings, getDateForPosition(position)).apply { tag = context.getString(R.string.month_view_tag_name, position) onDateSelected = { date -> [email protected]?.invoke(date) } } container?.addView(view, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) if (position == selectedPage) { onMonthSelected?.invoke(getDateForPosition(position), view) } return view } override fun destroyItem(container: ViewGroup?, position: Int, view: Any?) { (view as? View)?.let { container?.removeView(it) } } override fun isViewFromObject(view: View?, obj: Any?): Boolean = view === obj override fun getCount(): Int = Math.max(0, monthTo.monthsAfter(settings, monthFrom).toInt() + 1) } }
apache-2.0
7852ae44b2b2cfb93d2634131198bb5a
33.393502
149
0.645324
4.378217
false
false
false
false
chaseberry/KGeoJson
src/main/kotlin/edu/csh/chase/kgeojson/GeoJsonPoint.kt
1
590
package edu.csh.chase.kgeojson import edu.csh.chase.kgeojson.boundingbox.BoundingBox import edu.csh.chase.kgeojson.coordinatereferencesystem.CoordinateReferenceSystem import edu.csh.chase.kgeojson.models.Position import edu.csh.chase.kjson.JsonObject class GeoJsonPoint(val position: Position, properties: JsonObject, crs: CoordinateReferenceSystem? = null, boundingBox: BoundingBox? = null) : GeoJsonBase(GeoJsonType.Point, crs, boundingBox, properties) { val x = position.x val y = position.y val z = position.z }
apache-2.0
6fe398e96c505d78e07df360a45bd8f3
30.105263
117
0.716949
4.068966
false
false
false
false
yakov116/FastHub
app/src/main/java/com/fastaccess/ui/modules/theme/code/ThemeCodeActivity.kt
2
2227
package com.fastaccess.ui.modules.theme.code import android.app.Activity import android.os.Bundle import android.view.View import android.widget.ProgressBar import android.widget.Spinner import butterknife.BindView import butterknife.OnClick import butterknife.OnItemSelected import com.fastaccess.R import com.fastaccess.helper.PrefGetter import com.fastaccess.ui.adapter.SpinnerAdapter import com.fastaccess.ui.base.BaseActivity import com.prettifier.pretty.PrettifyWebView import com.prettifier.pretty.helper.CodeThemesHelper /** * Created by Kosh on 21 Jun 2017, 2:01 PM */ class ThemeCodeActivity : BaseActivity<ThemeCodeMvp.View, ThemeCodePresenter>(), ThemeCodeMvp.View { @BindView(R.id.themesList) lateinit var spinner: Spinner @BindView(R.id.webView) lateinit var webView: PrettifyWebView @BindView(R.id.readmeLoader) lateinit var progress: ProgressBar override fun layout(): Int = R.layout.theme_code_layout override fun isTransparent(): Boolean = false override fun canBack(): Boolean = true override fun isSecured(): Boolean = false override fun providePresenter(): ThemeCodePresenter = ThemeCodePresenter() @OnClick(R.id.done) fun onSaveTheme() { val theme = spinner.selectedItem as String PrefGetter.setCodeTheme(theme) setResult(Activity.RESULT_OK) finish() } override fun onInitAdapter(list: List<String>) { val adapter = SpinnerAdapter<String>(this, list) spinner.adapter = adapter } @OnItemSelected(R.id.themesList) fun onItemSelect() { val theme = spinner.selectedItem as String progress.visibility = View.VISIBLE webView.setThemeSource(CodeThemesHelper.CODE_EXAMPLE, theme) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) progress.visibility = View.VISIBLE webView.setOnContentChangedListener(this) title = "" presenter.onLoadThemes() } override fun onContentChanged(p: Int) { progress.let { it.progress = p if (p == 100) it.visibility = View.GONE } } override fun onScrollChanged(reachedTop: Boolean, scroll: Int) {} }
gpl-3.0
400c313c1daba97623eb66095eacc1df
29.930556
100
0.718904
4.358121
false
false
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/PagingConfig.kt
3
7298
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging import androidx.annotation.IntRange import androidx.paging.PagingConfig.Companion.MAX_SIZE_UNBOUNDED import androidx.paging.PagingSource.LoadResult.Page.Companion.COUNT_UNDEFINED /** * An object used to configure loading behavior within a [Pager], as it loads content from a * [PagingSource]. */ public class PagingConfig @JvmOverloads public constructor( /** * Defines the number of items loaded at once from the [PagingSource]. * * Should be several times the number of visible items onscreen. * * Configuring your page size depends on how your data is being loaded and used. Smaller * page sizes improve memory usage, latency, and avoid GC churn. Larger pages generally * improve loading throughput, to a point (avoid loading more than 2MB from SQLite at * once, since it incurs extra cost). * * If you're loading data for very large, social-media style cards that take up most of * a screen, and your database isn't a bottleneck, 10-20 may make sense. If you're * displaying dozens of items in a tiled grid, which can present items during a scroll * much more quickly, consider closer to 100. * * Note: [pageSize] is used to inform [PagingSource.LoadParams.loadSize], but is not enforced. * A [PagingSource] may completely ignore this value and still return a valid * [Page][PagingSource.LoadResult.Page]. */ @JvmField public val pageSize: Int, /** * Prefetch distance which defines how far from the edge of loaded content an access must be to * trigger further loading. Typically should be set several times the number of visible items * onscreen. * * E.g., If this value is set to 50, a [PagingData] will attempt to load 50 items in advance of * data that's already been accessed. * * A value of 0 indicates that no list items will be loaded until they are specifically * requested. This is generally not recommended, so that users don't observe a * placeholder item (with placeholders) or end of list (without) while scrolling. */ @JvmField @IntRange(from = 0) public val prefetchDistance: Int = pageSize, /** * Defines whether [PagingData] may display `null` placeholders, if the [PagingSource] * provides them. * * [PagingData] will present `null` placeholders for not-yet-loaded content if two * conditions are met: * * 1) Its [PagingSource] can count all unloaded items (so that the number of nulls to * present is known). * * 2) [enablePlaceholders] is set to `true` */ @JvmField public val enablePlaceholders: Boolean = true, /** * Defines requested load size for initial load from [PagingSource], typically larger than * [pageSize], so on first load data there's a large enough range of content loaded to cover * small scrolls. * * Note: [initialLoadSize] is used to inform [PagingSource.LoadParams.loadSize], but is not * enforced. A [PagingSource] may completely ignore this value and still return a valid initial * [Page][PagingSource.LoadResult.Page]. */ @JvmField @IntRange(from = 1) public val initialLoadSize: Int = pageSize * DEFAULT_INITIAL_PAGE_MULTIPLIER, /** * Defines the maximum number of items that may be loaded into [PagingData] before pages should * be dropped. * * If set to [MAX_SIZE_UNBOUNDED], pages will never be dropped. * * This can be used to cap the number of items kept in memory by dropping pages. This value is * typically many pages so old pages are cached in case the user scrolls back. * * This value must be at least two times the [prefetchDistance] plus the [pageSize]). This * constraint prevent loads from being continuously fetched and discarded due to prefetching. * * [maxSize] is best effort, not a guarantee. In practice, if [maxSize] is many times * [pageSize], the number of items held by [PagingData] will not grow above this number. * Exceptions are made as necessary to guarantee: * * Pages are never dropped until there are more than two pages loaded. Note that * a [PagingSource] may not be held strictly to [requested pageSize][PagingConfig.pageSize], so * two pages may be larger than expected. * * Pages are never dropped if they are within a prefetch window (defined to be * `pageSize + (2 * prefetchDistance)`) of the most recent load. * * @see PagingConfig.MAX_SIZE_UNBOUNDED */ @JvmField @IntRange(from = 2) public val maxSize: Int = MAX_SIZE_UNBOUNDED, /** * Defines a threshold for the number of items scrolled outside the bounds of loaded items * before Paging should give up on loading pages incrementally, and instead jump to the * user's position by triggering REFRESH via invalidate. * * Defaults to [COUNT_UNDEFINED], which disables invalidation due to scrolling large distances. * * Note: In order to allow [PagingSource] to resume from the user's current scroll position * after invalidation, [PagingSource.getRefreshKey] must be implemented. * * @see PagingSource.getRefreshKey * @see PagingSource.jumpingSupported */ @JvmField public val jumpThreshold: Int = COUNT_UNDEFINED ) { init { if (!enablePlaceholders && prefetchDistance == 0) { throw IllegalArgumentException( "Placeholders and prefetch are the only ways" + " to trigger loading of more data in PagingData, so either placeholders" + " must be enabled, or prefetch distance must be > 0." ) } if (maxSize != MAX_SIZE_UNBOUNDED && maxSize < pageSize + prefetchDistance * 2) { throw IllegalArgumentException( "Maximum size must be at least pageSize + 2*prefetchDist" + ", pageSize=$pageSize, prefetchDist=$prefetchDistance" + ", maxSize=$maxSize" ) } require(jumpThreshold == COUNT_UNDEFINED || jumpThreshold > 0) { "jumpThreshold must be positive to enable jumps or COUNT_UNDEFINED to disable jumping." } } public companion object { /** * When [maxSize] is set to [MAX_SIZE_UNBOUNDED], the maximum number of items loaded is * unbounded, and pages will never be dropped. */ @Suppress("MinMaxConstant") public const val MAX_SIZE_UNBOUNDED: Int = Int.MAX_VALUE internal const val DEFAULT_INITIAL_PAGE_MULTIPLIER = 3 } }
apache-2.0
a5d6287a5626bb074519163608b62148
42.96988
99
0.677446
4.633651
false
false
false
false
SimpleMobileTools/Simple-Commons
commons/src/main/kotlin/com/simplemobiletools/commons/models/FileDirItem.kt
1
6081
package com.simplemobiletools.commons.models import android.content.Context import android.net.Uri import android.provider.MediaStore import com.bumptech.glide.signature.ObjectKey import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import java.io.File open class FileDirItem( val path: String, val name: String = "", var isDirectory: Boolean = false, var children: Int = 0, var size: Long = 0L, var modified: Long = 0L, var mediaStoreId: Long = 0L ) : Comparable<FileDirItem> { companion object { var sorting = 0 } override fun toString() = "FileDirItem(path=$path, name=$name, isDirectory=$isDirectory, children=$children, size=$size, modified=$modified, mediaStoreId=$mediaStoreId)" override fun compareTo(other: FileDirItem): Int { return if (isDirectory && !other.isDirectory) { -1 } else if (!isDirectory && other.isDirectory) { 1 } else { var result: Int when { sorting and SORT_BY_NAME != 0 -> { result = if (sorting and SORT_USE_NUMERIC_VALUE != 0) { AlphanumericComparator().compare(name.normalizeString().toLowerCase(), other.name.normalizeString().toLowerCase()) } else { name.normalizeString().toLowerCase().compareTo(other.name.normalizeString().toLowerCase()) } } sorting and SORT_BY_SIZE != 0 -> result = when { size == other.size -> 0 size > other.size -> 1 else -> -1 } sorting and SORT_BY_DATE_MODIFIED != 0 -> { result = when { modified == other.modified -> 0 modified > other.modified -> 1 else -> -1 } } else -> { result = getExtension().toLowerCase().compareTo(other.getExtension().toLowerCase()) } } if (sorting and SORT_DESCENDING != 0) { result *= -1 } result } } fun getExtension() = if (isDirectory) name else path.substringAfterLast('.', "") fun getBubbleText(context: Context, dateFormat: String? = null, timeFormat: String? = null) = when { sorting and SORT_BY_SIZE != 0 -> size.formatSize() sorting and SORT_BY_DATE_MODIFIED != 0 -> modified.formatDate(context, dateFormat, timeFormat) sorting and SORT_BY_EXTENSION != 0 -> getExtension().toLowerCase() else -> name } fun getProperSize(context: Context, countHidden: Boolean): Long { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileSize(path) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getItemSize(countHidden) ?: 0 isNougatPlus() && path.startsWith("content://") -> { try { context.contentResolver.openInputStream(Uri.parse(path))?.available()?.toLong() ?: 0L } catch (e: Exception) { context.getSizeFromContentUri(Uri.parse(path)) } } else -> File(path).getProperSize(countHidden) } } fun getProperFileCount(context: Context, countHidden: Boolean): Int { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFFileCount(path, countHidden) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.getFileCount(countHidden) ?: 0 else -> File(path).getFileCount(countHidden) } } fun getDirectChildrenCount(context: Context, countHiddenItems: Boolean): Int { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFDirectChildrenCount(path, countHiddenItems) context.isPathOnOTG(path) -> context.getDocumentFile(path)?.listFiles()?.filter { if (countHiddenItems) true else !it.name!!.startsWith(".") }?.size ?: 0 else -> File(path).getDirectChildrenCount(context, countHiddenItems) } } fun getLastModified(context: Context): Long { return when { context.isRestrictedSAFOnlyRoot(path) -> context.getAndroidSAFLastModified(path) context.isPathOnOTG(path) -> context.getFastDocumentFile(path)?.lastModified() ?: 0L isNougatPlus() && path.startsWith("content://") -> context.getMediaStoreLastModified(path) else -> File(path).lastModified() } } fun getParentPath() = path.getParentPath() fun getDuration(context: Context) = context.getDuration(path)?.getFormattedDuration() fun getFileDurationSeconds(context: Context) = context.getDuration(path) fun getArtist(context: Context) = context.getArtist(path) fun getAlbum(context: Context) = context.getAlbum(path) fun getTitle(context: Context) = context.getTitle(path) fun getResolution(context: Context) = context.getResolution(path) fun getVideoResolution(context: Context) = context.getVideoResolution(path) fun getImageResolution(context: Context) = context.getImageResolution(path) fun getPublicUri(context: Context) = context.getDocumentFile(path)?.uri ?: "" fun getSignature(): String { val lastModified = if (modified > 1) { modified } else { File(path).lastModified() } return "$path-$lastModified-$size" } fun getKey() = ObjectKey(getSignature()) fun assembleContentUri(): Uri { val uri = when { path.isImageFast() -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI path.isVideoFast() -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI else -> MediaStore.Files.getContentUri("external") } return Uri.withAppendedPath(uri, mediaStoreId.toString()) } }
gpl-3.0
143df402c569c0c7b78c74b04027a3ce
37.487342
160
0.599901
4.761942
false
false
false
false
dropbox/Store
filesystem/src/main/java/com/dropbox/android/external/fs3/FileSystemPersister.kt
1
1168
package com.dropbox.android.external.fs3 import com.dropbox.android.external.fs3.filesystem.FileSystem import okio.BufferedSource /** * FileSystemPersister is used when persisting to/from file system * PathResolver will be used in creating file system paths based on cache keys. * Make sure to have keys containing same data resolve to same "path" * @param <T> key type </T> */ class FileSystemPersister<Key> private constructor( fileSystem: FileSystem, pathResolver: PathResolver<Key> ) : Persister<BufferedSource, Key> { private val fileReader: FSReader<Key> = FSReader(fileSystem, pathResolver) private val fileWriter: FSWriter<Key> = FSWriter(fileSystem, pathResolver) override suspend fun read(key: Key): BufferedSource? = fileReader.read(key) override suspend fun write(key: Key, raw: BufferedSource): Boolean = fileWriter.write(key, raw) companion object { fun <Key> create( fileSystem: FileSystem, pathResolver: PathResolver<Key> ): Persister<BufferedSource, Key> = FileSystemPersister( fileSystem = fileSystem, pathResolver = pathResolver ) } }
apache-2.0
1cf33bb9fd7b9d7221f04fe364a3c8bc
34.393939
99
0.714041
4.544747
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/util/expression-utils.kt
1
2093
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.util import com.demonwav.mcdev.translations.identification.TranslationInstance import com.demonwav.mcdev.translations.identification.TranslationInstance.Companion.FormattingError import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiCall import com.intellij.psi.PsiLiteral import com.intellij.psi.PsiReferenceExpression import com.intellij.psi.PsiTypeCastExpression import com.intellij.psi.PsiVariable fun PsiAnnotationMemberValue.evaluate(allowReferences: Boolean, allowTranslations: Boolean): String? { val visited = mutableSetOf<PsiAnnotationMemberValue?>() fun eval(expr: PsiAnnotationMemberValue?, defaultValue: String? = null): String? { if (!visited.add(expr)) { return defaultValue } when { expr is PsiTypeCastExpression && expr.operand != null -> return eval(expr.operand, defaultValue) expr is PsiReferenceExpression -> { val reference = expr.advancedResolve(false).element if (reference is PsiVariable && reference.initializer != null) { return eval(reference.initializer, "\${${expr.text}}") } } expr is PsiLiteral -> return expr.value.toString() expr is PsiCall && allowTranslations -> for (argument in expr.argumentList?.expressions ?: emptyArray()) { val translation = TranslationInstance.find(argument) ?: continue if (translation.formattingError == FormattingError.MISSING) { return "{ERROR: Missing formatting arguments for '${translation.text}'}" } return translation.text } } return if (allowReferences && expr != null) { "\${${expr.text}}" } else { defaultValue } } return eval(this) }
mit
f4c25c24f1fe128340f47dfbc18d3d37
33.883333
102
0.626851
5.312183
false
false
false
false
mvosske/comlink
app/src/main/java/org/tnsfit/dragon/comlink/matrix/RetrieveAgent.kt
1
1655
package org.tnsfit.dragon.comlink.matrix import android.net.Uri import org.greenrobot.eventbus.EventBus import java.io.* import java.net.Socket /** * Created by dragon on 31.10.16. * Downloaded eine Datei im Hintergrund * */ class RetrieveAgent(val socketPool: SocketPool, val downloadEvent: DownloadEvent, val workingDirectory: File): Thread() { override fun run() { var success = true val outFile = File(workingDirectory, downloadEvent.destination) try { val clientSocket: Socket = Socket(downloadEvent.address, 24321) socketPool.registerSocket(clientSocket) val inStream: BufferedInputStream = clientSocket.inputStream.buffered() val outStream = BufferedOutputStream(FileOutputStream(outFile, false)) val buffer = ByteArray(8192) var len: Int try {while (true) { len = inStream.read(buffer) if (len < 0) break outStream.write(buffer,0,len) }} catch (ioe: IOException) { success = false } outStream.flush() inStream.close() outStream.close() clientSocket.close() socketPool.unregisterSocket(clientSocket) } catch (e: IOException) { success = false } val eventBus = EventBus.getDefault() if (success) { eventBus.post(ImageEvent(Uri.fromFile(outFile), MessagePacket.MATRIX)) } else { eventBus.post(MessagePacket(MatrixConnection.TEXT_MESSAGE,"Loading Image failed",MessagePacket.MATRIX)) } } }
gpl-3.0
93e0535e39535ad265cbbeaf9a7dc652
30.226415
121
0.612085
4.661972
false
false
false
false
initrc/android-bootstrap
app/src/main/java/io/github/initrc/bootstrap/presenter/ColumnPresenter.kt
1
1646
package io.github.initrc.bootstrap.presenter import android.app.Activity import io.github.initrc.bootstrap.R import util.DeviceUtils import util.GridUtils /** * Presenter for the grid column. */ class ColumnPresenter(private val activity: Activity) { var columnCountType = ColumnCountType.STANDARD val resources = activity.resources!! val gridPadding = resources.getDimension(R.dimen.margin).toInt() private var onColumnUpdate: (Int) -> Unit = {} fun getDynamicGridColumnCount(): Int { return when(columnCountType) { ColumnCountType.ONE -> 1 ColumnCountType.STANDARD -> GridUtils.getGridColumnCount(resources) ColumnCountType.DOUBLE -> GridUtils.getGridColumnCount(resources) * 2 } } fun getGridColumnWidthPx(): Int { val gridColumnCount = getDynamicGridColumnCount() val paddingCount = gridColumnCount + 1 val screenWidth = DeviceUtils.getScreenWidthPx(activity) return (screenWidth - gridPadding * paddingCount) / gridColumnCount } /** * @return True if the count is adjusted. */ fun adjustCount(delta: Int): Boolean { if (delta == 0) return false if (columnCountType.ordinal + delta in 0 until ColumnCountType.values().size) { columnCountType = ColumnCountType.values()[columnCountType.ordinal + delta] onColumnUpdate(getDynamicGridColumnCount()) return true } return false } fun setOnColumnUpdateCallback(func: (Int) -> Unit) { onColumnUpdate = func } } enum class ColumnCountType { ONE, STANDARD, DOUBLE }
mit
b5413e6a1e7249e13670c822505ea0df
30.653846
87
0.676792
4.37766
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/translations/identification/TranslationIdentifier.kt
1
4061
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 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) { val foldingElement = when (function.foldParameters) { TranslationFunction.FoldingScope.CALL -> call TranslationFunction.FoldingScope.PARAMETER -> element TranslationFunction.FoldingScope.PARAMETERS -> container } try { val (formatted, superfluousParams) = function.format(translation, call) ?: (translation to -1) return TranslationInstance( foldingElement, function.matchedIndex, referenceElement, translationKey, formatted, if (superfluousParams >= 0) FormattingError.SUPERFLUOUS else null, superfluousParams ) } catch (ignored: MissingFormatArgumentException) { return TranslationInstance( foldingElement, function.matchedIndex, referenceElement, translationKey, translation, FormattingError.MISSING ) } } else { return TranslationInstance( null, function.matchedIndex, referenceElement, translationKey, null ) } } } return null } return null } } }
mit
646e08c7973fc762623c682eeeb9ab02
41.747368
107
0.507757
6.918228
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/external/GhcMod.kt
1
3620
package org.jetbrains.haskell.external import org.jetbrains.haskell.util.ProcessRunner import java.io.IOException import com.intellij.util.messages.MessageBus import com.intellij.util.MessageBusUtil import com.intellij.notification.Notifications import com.intellij.notification.Notification import com.intellij.notification.NotificationType import java.io.File import org.jetbrains.haskell.util.OSUtil import org.jetbrains.haskell.config.HaskellSettings import java.util.Collections import java.util.HashMap /** * Created by atsky on 3/29/14. */ object GhcMod { var errorReported : Boolean = false fun getPath() : String { return HaskellSettings.getInstance().getState().ghcModPath!! } fun getModuleContent(module : String) : List<Pair<String, String?>> { try { val path = getPath() val text = ProcessRunner(null).executeOrFail(path, "browse", "-d", module) if (!text.contains(":Error:")) { val f: (String) -> Pair<String, String?> = { if (it.contains("::")) { val t = it.split("::".toRegex()).toTypedArray() Pair(t[0].trim(), t[1].trim()) } else { Pair(it, null) } } return text.split('\n').map(f).toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } fun debug(basePath : String, file: String) : Map<String, String> { try { val path = getPath() val text = ProcessRunner(basePath).executeOrFail(path, "debug", file) if (!text.contains(":Error:")) { val map = HashMap<String, String>() for (line in text.split('\n')) { val index = line.indexOf(":") map.put(line.substring(0, index), line.substring(index).trim()) } return map } else { return Collections.emptyMap() } } catch(e : Exception) { reportError() return Collections.emptyMap() } } fun check(basePath : String, file: String) : List<String> { try { val path = getPath() val text = ProcessRunner(basePath).executeOrFail(path, "check", file) if (!text.contains(":Error:")) { return text.split('\n').toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } fun reportError() { if (!errorReported) { Notifications.Bus.notify(Notification("ghc-mod error", "ghc-mod", "Can't find ghc-mod executable. "+ "Please correct ghc-mod path in settings.", NotificationType.ERROR)) errorReported = true } } fun сheck() : Boolean { try { ProcessRunner(null).executeOrFail(getPath()) return true; } catch(e : IOException) { return false; } } fun getModulesList() : List<String> { try { val text = ProcessRunner(null).executeOrFail(getPath(), "list") if (!text.contains(":Error:")) { return text.split('\n').toList() } else { return listOf() } } catch(e : Exception) { reportError() return listOf() } } }
apache-2.0
e8d8fdb0a2497d0216d994632721d1aa
29.166667
112
0.518099
4.598475
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/wall/dto/WallWallpostAttachment.kt
1
3689
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.wall.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.audio.dto.AudioAudio import com.vk.sdk.api.base.dto.BaseLink import com.vk.sdk.api.docs.dto.DocsDoc import com.vk.sdk.api.events.dto.EventsEventAttach import com.vk.sdk.api.groups.dto.GroupsGroupAttach import com.vk.sdk.api.market.dto.MarketMarketAlbum import com.vk.sdk.api.market.dto.MarketMarketItem import com.vk.sdk.api.notes.dto.NotesNote import com.vk.sdk.api.pages.dto.PagesWikipageFull import com.vk.sdk.api.photos.dto.PhotosPhoto import com.vk.sdk.api.photos.dto.PhotosPhotoAlbum import com.vk.sdk.api.polls.dto.PollsPoll import com.vk.sdk.api.video.dto.VideoVideoFull import kotlin.String /** * @param type * @param accessKey - Access key for the audio * @param album * @param app * @param audio * @param doc * @param event * @param group * @param graffiti * @param link * @param market * @param marketAlbum * @param note * @param page * @param photo * @param poll * @param postedPhoto * @param video */ data class WallWallpostAttachment( @SerializedName("type") val type: WallWallpostAttachmentType, @SerializedName("access_key") val accessKey: String? = null, @SerializedName("album") val album: PhotosPhotoAlbum? = null, @SerializedName("app") val app: WallAppPost? = null, @SerializedName("audio") val audio: AudioAudio? = null, @SerializedName("doc") val doc: DocsDoc? = null, @SerializedName("event") val event: EventsEventAttach? = null, @SerializedName("group") val group: GroupsGroupAttach? = null, @SerializedName("graffiti") val graffiti: WallGraffiti? = null, @SerializedName("link") val link: BaseLink? = null, @SerializedName("market") val market: MarketMarketItem? = null, @SerializedName("market_album") val marketAlbum: MarketMarketAlbum? = null, @SerializedName("note") val note: NotesNote? = null, @SerializedName("page") val page: PagesWikipageFull? = null, @SerializedName("photo") val photo: PhotosPhoto? = null, @SerializedName("poll") val poll: PollsPoll? = null, @SerializedName("posted_photo") val postedPhoto: WallPostedPhoto? = null, @SerializedName("video") val video: VideoVideoFull? = null )
mit
4045459677ec635371e9e3f003b21614
34.815534
81
0.698021
3.879075
false
false
false
false
EmpowerOperations/getoptk
src/main/kotlin/com/empowerops/getoptk/Lexer.kt
1
4980
package com.empowerops.getoptk object Lexer { fun lex(args: Iterable<String>): List<Token>{ var tokens: List<Token> = emptyList() var currentOffset = 0; // args is a pre-lexed command line. Unfortunately we dont have access to the regular command line // (consider that we might have been invoked from a C-style "exec(char** args)") // so I'm calling these blocks "super tokens", and inserting a "SuperTokenSeparator" between them. // see the LexerFixture for samples on how they are parsed, for(superToken in args){ var startIndex = 0 val openingToken = when { superToken.startsWith("--") -> LongPreamble(currentOffset) superToken.startsWith("-") -> ShortPreamble(currentOffset) superToken.startsWith("/") -> WindowsPreamble(currentOffset) else -> null } if(openingToken != null) { tokens += openingToken startIndex += openingToken.length currentOffset += openingToken.length } val resultingTokenText = superToken.substring(startIndex) tokens += when { tokens.lastOrNull() is OptionPreambleToken && "=" in resultingTokenText -> { splitAssignmentTokens(resultingTokenText, currentOffset) } tokens.lastOrNull() is OptionPreambleToken && resultingTokenText.length == 1 -> { ShortOptionName(resultingTokenText, currentOffset).asSingleList() } tokens.lastOrNull() is OptionPreambleToken && resultingTokenText.length > 1 -> { LongOptionName(resultingTokenText, currentOffset).asSingleList() } else -> { Argument(resultingTokenText, currentOffset).asSingleList() } } currentOffset += resultingTokenText.length val separator = SuperTokenSeparator(currentOffset) tokens += separator currentOffset += separator.length } return tokens } private fun splitAssignmentTokens(resultingTokenText: String, currentOffset: Int): List<Token> = with(resultingTokenText){ val indexOfAssignment = indexOf("=") val optionText = substring(0, indexOfAssignment) val option = if(optionText.length == 1) ShortOptionName(optionText, currentOffset) else LongOptionName(optionText, currentOffset) val assignment = AssignmentSeparator(currentOffset + indexOfAssignment) val argument = Argument(substring(indexOfAssignment + 1), currentOffset + indexOfAssignment + 1) return listOf(option, assignment, argument) } } //TODO add location info for debug messages interface Token { val text: String; val location: IntRange; val length: Int get() = text.length } //token to represent EOF or other tokenization failure object Epsilon: Token { override val text = "" override val location = 0..0 override fun toString() = "[ε]" } //a keyword interface Lemma: Token { val Lemma: String val index: Int override val text: String get() = Lemma override val location: IntRange get() = index .. index + Lemma.length - 1 } //a dynamic word interface Word: Token { val index: Int override val location: IntRange get() = index .. index + text.length - 1 } interface SeparatorToken : Token interface OptionPreambleToken: Token data class SuperTokenSeparator(val index: Int): SeparatorToken { override val text = " " override val location = index .. index + text.length -1 } data class AssignmentSeparator(override val index: Int): Lemma, SeparatorToken { override val Lemma = "=" } data class MinorSeparator(override val index: Int): Lemma, SeparatorToken { override val Lemma = "," } data class ShortPreamble(override val index: Int): Lemma, OptionPreambleToken { override val Lemma = "-"; } data class LongPreamble(override val index: Int): Lemma, OptionPreambleToken { override val Lemma = "--"; } data class WindowsPreamble(override val index: Int): Lemma, OptionPreambleToken { override val Lemma = "/"; } sealed class OptionName: Token {} data class ShortOptionName(override val text: String, override val index: Int): OptionName(), Word, Token { init { require(text.length == 1) } } data class LongOptionName(override val text: String, override val index: Int): OptionName(), Word, Token data class Argument(override val text: String, override val index: Int): Word, Token data class ListItemText(val parent: Token, val rangeInParent: IntRange): Token { override val text: String get() = parent.text.substring(rangeInParent) override val location: IntRange get() = parent.location.start.offset(rangeInParent) } fun <T> T.asSingleList() = listOf(this) fun Int.offset(range: IntRange) = this + range.start .. this + range.endInclusive
apache-2.0
5108935ad28e4f2c60a5119e3f2102f3
39.479675
144
0.661177
4.618738
false
false
false
false
mitallast/netty-queue
src/main/java/org/mitallast/queue/crdt/routing/RoutingReplica.kt
1
930
package org.mitallast.queue.crdt.routing import org.mitallast.queue.common.codec.Codec import org.mitallast.queue.common.codec.Message import org.mitallast.queue.transport.DiscoveryNode class RoutingReplica @JvmOverloads constructor( val id: Long, val member: DiscoveryNode, val state: State = State.OPENED) : Message { enum class State { OPENED, CLOSED } val isOpened: Boolean get() = state == State.OPENED val isClosed: Boolean get() = state == State.CLOSED fun close(): RoutingReplica { return RoutingReplica(id, member, State.CLOSED) } companion object { val codec = Codec.of( ::RoutingReplica, RoutingReplica::id, RoutingReplica::member, RoutingReplica::state, Codec.longCodec(), DiscoveryNode.codec, Codec.enumCodec(State::class.java) ) } }
mit
c71d07ea6ea3a135e7c25bb2aab3d9ae
24.135135
55
0.627957
4.386792
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/NPCBannerView.kt
1
2422
package com.habitrpg.android.habitica.ui.views import android.content.Context import android.graphics.Bitmap import android.graphics.Shader import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet import android.widget.FrameLayout import android.widget.ImageView import androidx.core.graphics.drawable.toBitmap import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.NpcBannerBinding import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.common.habitica.extensions.DataBindingUtils import com.habitrpg.common.habitica.extensions.layoutInflater import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import kotlin.math.roundToInt class NPCBannerView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) { private val binding = NpcBannerBinding.inflate(context.layoutInflater, this) var shopSpriteSuffix: String = "" set(value) { field = if (value.isEmpty() || value.startsWith("_")) { value } else { "_$value" } if (identifier.isNotEmpty()) { setImage() } } var identifier: String = "" set(value) { field = value setImage() } private fun setImage() { DataBindingUtils.loadImage(context, identifier + "_scene" + shopSpriteSuffix) { binding.sceneView.setImageDrawable(it) } binding.backgroundView.scaleType = ImageView.ScaleType.FIT_START DataBindingUtils.loadImage(context, identifier + "_background" + shopSpriteSuffix) { val aspectRatio = it.intrinsicWidth / it.intrinsicHeight.toFloat() val height = context.resources.getDimension(R.dimen.shop_height).toInt() val width = (height * aspectRatio).roundToInt() val drawable = BitmapDrawable(context.resources, Bitmap.createScaledBitmap(it.toBitmap(), width, height, false)) drawable.tileModeX = Shader.TileMode.REPEAT Observable.just(drawable) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { binding.backgroundView.background = it }, ExceptionHandler.rx() ) } } }
gpl-3.0
a85d24a237b943297a900b3acd26ca93
37.444444
124
0.660198
5.014493
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xslt/test/uk/co/reecedunn/intellij/plugin/xslt/tests/lang/highlighter/EQNamesOrHashedKeywordsTest.kt
1
54632
/* * Copyright (C) 2020-2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xslt.tests.lang.highlighter import com.intellij.openapi.extensions.PluginId import org.hamcrest.CoreMatchers.`is` import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.core.tests.parser.prettyPrint import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition import uk.co.reecedunn.intellij.plugin.xslt.ast.schema.XsltSchemaType import uk.co.reecedunn.intellij.plugin.xslt.lang.EQNamesOrHashedKeywords import uk.co.reecedunn.intellij.plugin.xslt.lang.highlighter.SchemaTypeAnnotator import uk.co.reecedunn.intellij.plugin.xslt.schema.XsltSchemaTypes @Suppress("Reformat") @DisplayName("IntelliJ - Custom Language Support - Syntax Highlighting - EQNames-or-hashed-keywords Schema Type Annotator") class EQNamesOrHashedKeywordsTest : AnnotatorTestCase(EQNamesOrHashedKeywords.ParserDefinition(), XPathParserDefinition()) { override val pluginId: PluginId = PluginId.getId("EQNamesOrHashedKeywordsTest") @Nested @DisplayName("xsl:accumulator-names") inner class AccumulatorNamesTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslAccumulatorNames) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:accumulator-names schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:accumulator-names schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:accumulator-names schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:accumulator-names schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:default-mode-type") inner class DefaultModeTypeTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslDefaultModeType) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (31:61) "The xsl:default-mode-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:default-mode-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:default-mode-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:default-mode-type schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:default-mode-type schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:default-mode-type schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:default-mode-type schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:EQName") inner class EQNameTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslEQName) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (31:61) "The xsl:EQName schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:EQName schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:EQName schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:EQName schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:EQName schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:EQName schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:EQName schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:EQName schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:EQName-in-namespace") inner class EQNameInNamespaceTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslEQNameInNamespace) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (31:61) "The xsl:EQName-in-namespace schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:EQName-in-namespace schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:EQName-in-namespace schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:EQName-in-namespace schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:EQName-in-namespace schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:EQName-in-namespace schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:EQName-in-namespace schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:EQName-in-namespace schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:EQNames") inner class EQNamesTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslEQNames) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:EQNames schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:EQNames schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:EQNames schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:EQNames schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:EQNames schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:method") inner class MethodTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslMethod) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:method schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:method schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:method schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:method schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:method schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:method schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:method schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:method schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:method schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:mode") inner class ModeTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslMode) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (31:61) "The xsl:mode schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:mode schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:mode schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:mode schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "The xsl:mode schema type only supports a single item." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "The xsl:mode schema type only supports a single item." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:mode schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:modes") inner class ModesTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslModes) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:modes schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE INFORMATION (23:31) XML_ATTRIBUTE_VALUE INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:modes schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:prefix") inner class PrefixTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslPrefix) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:prefix schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:prefix schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:prefix schema type." ERROR (10:19) "QName is not supported for the xsl:prefix schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:prefix schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:prefix schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:prefix schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:prefix schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:prefix schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:prefixes") inner class PrefixesTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslPrefixes) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:prefixes schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:prefixes schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:prefixes schema type." ERROR (10:19) "QName is not supported for the xsl:prefixes schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:prefixes schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:prefixes schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:prefixes schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:prefixes schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:prefixes schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:prefix-list") inner class PrefixListTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslPrefixList) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:prefix-list schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:prefix-list schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:prefix-list schema type." ERROR (10:19) "QName is not supported for the xsl:prefix-list schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:prefix-list schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:prefix-list schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:prefix-list schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:prefix-list schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:prefix-list-or-all") inner class PrefixListOrAllTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslPrefixListOrAll) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:prefix-list-or-all schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:prefix-list-or-all schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:prefix-list-or-all schema type." ERROR (10:19) "QName is not supported for the xsl:prefix-list-or-all schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:prefix-list-or-all schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:prefix-list-or-all schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:prefix-list-or-all schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:prefix-or-default") inner class PrefixOrDefaultTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslPrefixOrDefault) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:prefix-or-default schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:prefix-or-default schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:prefix-or-default schema type." ERROR (10:19) "QName is not supported for the xsl:prefix-or-default schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:prefix-or-default schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:prefix-or-default schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:prefix-or-default schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:prefix-or-default schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:prefix-or-default schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:QName") inner class QNameTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslQName) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:QName schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:QName schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:QName schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:QName schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:QName schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:QName schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:QName schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:QName schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:QName schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:QNames") inner class QNamesTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslQNames) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:QNames schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:QNames schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:QNames schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:QNames schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:QNames schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:QNames schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:QNames schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:streamability-type") inner class StreamabilityTypeTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslStreamabilityType) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (31:61) "The xsl:streamability-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (10:19) "The xsl:streamability-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (6:11) "The xsl:streamability-type schema type only supports a single item." """.trimIndent() ) ) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:streamability-type schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:streamability-type schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:streamability-type schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:streamability-type schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:streamability-type schema type." """.trimIndent() ) ) } } @Nested @DisplayName("xsl:tokens") inner class TokensTest { val annotator = SchemaTypeAnnotator(XsltSchemaTypes.XslTokens) @Test @DisplayName("XPath 2.0 EBNF (77) Comment ; XPath 2.0 EBNF (82) CommentContents") fun comment() { val file = parse<XsltSchemaType>("lorem (: ipsum :)")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("XPath 3.1 EBNF (122) URIQualifiedName") fun uriQualifiedName() { val file = parse<XsltSchemaType>("Q{http://www.example.co.uk}one Q{http://www.example.co.uk}two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:30) "URIQualifiedName is not supported for the xsl:tokens schema type." ERROR (31:61) "URIQualifiedName is not supported for the xsl:tokens schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (122) QName") fun qname() { val file = parse<XsltSchemaType>("lorem:one lorem:two")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ ERROR (0:9) "QName is not supported for the xsl:tokens schema type." ERROR (10:19) "QName is not supported for the xsl:tokens schema type." """.trimIndent() ) ) } @Test @DisplayName("XPath 3.1 EBNF (123) NCName") fun ncname() { val file = parse<XsltSchemaType>("lorem ipsum")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat(annotations, `is`("")) } @Test @DisplayName("hashed keywords") fun hashedKeywords() { val file = parse<XsltSchemaType>("#all #current #default #unnamed #unknown")[0] val annotations = annotateTree(file, annotator).prettyPrint() assertThat( annotations, `is`( """ INFORMATION (0:4) XML_ATTRIBUTE_VALUE ERROR (0:4) "Keyword '#all' is not supported for the xsl:tokens schema type." INFORMATION (5:13) XML_ATTRIBUTE_VALUE ERROR (5:13) "Keyword '#current' is not supported for the xsl:tokens schema type." INFORMATION (14:22) XML_ATTRIBUTE_VALUE ERROR (14:22) "Keyword '#default' is not supported for the xsl:tokens schema type." INFORMATION (23:31) XML_ATTRIBUTE_VALUE ERROR (23:31) "Keyword '#unnamed' is not supported for the xsl:tokens schema type." INFORMATION (32:40) XML_ATTRIBUTE_VALUE ERROR (32:40) "Keyword '#unknown' is not supported for the xsl:tokens schema type." """.trimIndent() ) ) } } }
apache-2.0
710915f7a21b540527e4abe0c8af932f
41.219474
123
0.535895
4.697103
false
true
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/reader/ReaderPresenter.kt
1
24913
package eu.kanade.tachiyomi.ui.reader import android.app.Application import android.os.Bundle import android.os.Environment import com.jakewharton.rxrelay.BehaviorRelay import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.cache.CoverCache import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.source.LocalSource import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.ui.reader.loader.ChapterLoader import eu.kanade.tachiyomi.ui.reader.loader.DownloadPageLoader import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.model.ReaderPage import eu.kanade.tachiyomi.ui.reader.model.ViewerChapters import eu.kanade.tachiyomi.util.DiskUtil import eu.kanade.tachiyomi.util.ImageUtil import rx.Completable import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.File import java.util.* import java.util.concurrent.TimeUnit /** * Presenter used by the activity to perform background operations. */ class ReaderPresenter( private val db: DatabaseHelper = Injekt.get(), private val sourceManager: SourceManager = Injekt.get(), private val downloadManager: DownloadManager = Injekt.get(), private val coverCache: CoverCache = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) : BasePresenter<ReaderActivity>() { /** * The manga loaded in the reader. It can be null when instantiated for a short time. */ var manga: Manga? = null private set /** * The chapter id of the currently loaded chapter. Used to restore from process kill. */ private var chapterId = -1L /** * The chapter loader for the loaded manga. It'll be null until [manga] is set. */ private var loader: ChapterLoader? = null /** * Subscription to prevent setting chapters as active from multiple threads. */ private var activeChapterSubscription: Subscription? = null /** * Relay for currently active viewer chapters. */ /* [EXH] private */ val viewerChaptersRelay = BehaviorRelay.create<ViewerChapters>() /** * Relay used when loading prev/next chapter needed to lock the UI (with a dialog). */ private val isLoadingAdjacentChapterRelay = BehaviorRelay.create<Boolean>() // EXH --> private var loadKey: String? = null // EXH <-- /** * Chapter list for the active manga. It's retrieved lazily and should be accessed for the first * time in a background thread to avoid blocking the UI. */ private val chapterList by lazy { val manga = manga!! val dbChapters = db.getChapters(manga).executeAsBlocking() val selectedChapter = dbChapters.find { it.id == chapterId } ?: error("Requested chapter of id $chapterId not found in chapter list") val chaptersForReader = if (preferences.skipRead()) { var list = dbChapters.filter { it -> !it.read }.toMutableList() val find = list.find { it.id == chapterId } if (find == null) { list.add(selectedChapter) } list } else { dbChapters } when (manga.sorting) { Manga.SORTING_SOURCE -> ChapterLoadBySource().get(chaptersForReader) Manga.SORTING_NUMBER -> ChapterLoadByNumber().get(chaptersForReader, selectedChapter) else -> error("Unknown sorting method") }.map(::ReaderChapter) } /** * Called when the presenter is created. It retrieves the saved active chapter if the process * was restored. */ override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) if (savedState != null) { chapterId = savedState.getLong(::chapterId.name, -1) } } /** * Called when the presenter is destroyed. It saves the current progress and cleans up * references on the currently active chapters. */ override fun onDestroy() { super.onDestroy() val currentChapters = viewerChaptersRelay.value if (currentChapters != null) { currentChapters.unref() saveChapterProgress(currentChapters.currChapter) saveChapterHistory(currentChapters.currChapter) } } /** * Called when the presenter instance is being saved. It saves the currently active chapter * id and the last page read. */ override fun onSave(state: Bundle) { super.onSave(state) val currentChapter = getCurrentChapter() if (currentChapter != null) { currentChapter.requestedPage = currentChapter.chapter.last_page_read state.putLong(::chapterId.name, currentChapter.chapter.id!!) } } /** * Called when the user pressed the back button and is going to leave the reader. Used to * trigger deletion of the downloaded chapters. */ fun onBackPressed() { deletePendingChapters() } /** * Called when the activity is saved and not changing configurations. It updates the database * to persist the current progress of the active chapter. */ fun onSaveInstanceStateNonConfigurationChange() { val currentChapter = getCurrentChapter() ?: return saveChapterProgress(currentChapter) } /** * Whether this presenter is initialized yet. */ fun needsInit(): Boolean { return manga == null } /** * Initializes this presenter with the given [mangaId] and [initialChapterId]. This method will * fetch the manga from the database and initialize the initial chapter. */ fun init(mangaId: Long, initialChapterId: Long) { if (!needsInit()) return db.getManga(mangaId).asRxObservable() .first() .observeOn(AndroidSchedulers.mainThread()) .doOnNext { init(it, initialChapterId) } .subscribeFirst({ _, _ -> // Ignore onNext event }, ReaderActivity::setInitialChapterError) } /** * Initializes this presenter with the given [manga] and [initialChapterId]. This method will * set the chapter loader, view subscriptions and trigger an initial load. */ private fun init(manga: Manga, initialChapterId: Long) { if (!needsInit()) return this.manga = manga if (chapterId == -1L) chapterId = initialChapterId val source = sourceManager.getOrStub(manga.source) loader = ChapterLoader(downloadManager, manga, source) Observable.just(manga).subscribeLatestCache(ReaderActivity::setManga) viewerChaptersRelay.subscribeLatestCache(ReaderActivity::setChapters) isLoadingAdjacentChapterRelay.subscribeLatestCache(ReaderActivity::setProgressDialog) // Read chapterList from an io thread because it's retrieved lazily and would block main. activeChapterSubscription?.unsubscribe() activeChapterSubscription = Observable .fromCallable { chapterList.first { chapterId == it.chapter.id } } .flatMap { getLoadObservable(loader!!, it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeFirst({ _, _ -> // Ignore onNext event }, ReaderActivity::setInitialChapterError) } /** * Returns an observable that loads the given [chapter] with this [loader]. This observable * handles main thread synchronization and updating the currently active chapters on * [viewerChaptersRelay], however callers must ensure there won't be more than one * subscription active by unsubscribing any existing [activeChapterSubscription] before. * Callers must also handle the onError event. */ private fun getLoadObservable( loader: ChapterLoader, chapter: ReaderChapter, requiredLoadKey: String? = null ): Observable<ViewerChapters> { return loader.loadChapter(chapter) .andThen(Observable.fromCallable { val chapterPos = chapterList.indexOf(chapter) ViewerChapters(chapter, chapterList.getOrNull(chapterPos - 1), chapterList.getOrNull(chapterPos + 1)) }) .observeOn(AndroidSchedulers.mainThread()) .doOnNext { newChapters -> // Add new references first to avoid unnecessary recycling newChapters.ref() // Ensure that we haven't made another load request in the meantime if(requiredLoadKey == null || requiredLoadKey == loadKey) { val oldChapters = viewerChaptersRelay.value oldChapters?.unref() viewerChaptersRelay.call(newChapters) } else { // Another load request has been made, our new chapters are useless :( newChapters.unref() } } } /** * Called when the user changed to the given [chapter] when changing pages from the viewer. * It's used only to set this chapter as active. */ private fun loadNewChapter(chapter: ReaderChapter) { val loader = loader ?: return Timber.d("Loading ${chapter.chapter.url}") val newLoadKey = UUID.randomUUID().toString() loadKey = newLoadKey activeChapterSubscription?.unsubscribe() activeChapterSubscription = getLoadObservable(loader, chapter, newLoadKey) .toCompletable() .onErrorComplete() .subscribe() .also(::add) } /** * Called when the user is going to load the prev/next chapter through the menu button. It * sets the [isLoadingAdjacentChapterRelay] that the view uses to prevent any further * interaction until the chapter is loaded. */ private fun loadAdjacent(chapter: ReaderChapter) { val loader = loader ?: return Timber.d("Loading adjacent ${chapter.chapter.url}") activeChapterSubscription?.unsubscribe() activeChapterSubscription = getLoadObservable(loader, chapter) .doOnSubscribe { isLoadingAdjacentChapterRelay.call(true) } .doOnUnsubscribe { isLoadingAdjacentChapterRelay.call(false) } .subscribeFirst({ view, _ -> view.moveToPageIndex(0) }, { _, _ -> // Ignore onError event, viewers handle that state }) } /** * Called when the viewers decide it's a good time to preload a [chapter] and improve the UX so * that the user doesn't have to wait too long to continue reading. */ private fun preload(chapter: ReaderChapter) { if (chapter.state != ReaderChapter.State.Wait && chapter.state !is ReaderChapter.State.Error) { return } Timber.d("Preloading ${chapter.chapter.url}") val loader = loader ?: return loader.loadChapter(chapter) .observeOn(AndroidSchedulers.mainThread()) // Update current chapters whenever a chapter is preloaded .doOnCompleted { viewerChaptersRelay.value?.let(viewerChaptersRelay::call) } .onErrorComplete() .subscribe() .also(::add) } /** * Called every time a page changes on the reader. Used to mark the flag of chapters being * read, update tracking services, enqueue downloaded chapter deletion, and updating the active chapter if this * [page]'s chapter is different from the currently active. */ fun onPageSelected(page: ReaderPage) { val currentChapters = viewerChaptersRelay.value ?: return val selectedChapter = page.chapter // Save last page read and mark as read if needed selectedChapter.chapter.last_page_read = page.index if (selectedChapter.pages?.lastIndex == page.index) { selectedChapter.chapter.read = true updateTrackLastChapterRead() enqueueDeleteReadChapters(selectedChapter) } if (selectedChapter != currentChapters.currChapter) { Timber.d("Setting ${selectedChapter.chapter.url} as active") onChapterChanged(currentChapters.currChapter, selectedChapter) loadNewChapter(selectedChapter) } } /** * Called when a chapter changed from [fromChapter] to [toChapter]. It updates [fromChapter] * on the database. */ private fun onChapterChanged(fromChapter: ReaderChapter, toChapter: ReaderChapter) { saveChapterProgress(fromChapter) saveChapterHistory(fromChapter) } /** * Saves this [chapter] progress (last read page and whether it's read). */ private fun saveChapterProgress(chapter: ReaderChapter) { db.updateChapterProgress(chapter.chapter).asRxCompletable() .onErrorComplete() .subscribeOn(Schedulers.io()) .subscribe() } /** * Saves this [chapter] last read history. */ private fun saveChapterHistory(chapter: ReaderChapter) { val history = History.create(chapter.chapter).apply { last_read = Date().time } db.updateHistoryLastRead(history).asRxCompletable() .onErrorComplete() .subscribeOn(Schedulers.io()) .subscribe() } /** * Called from the activity to preload the given [chapter]. */ fun preloadChapter(chapter: ReaderChapter) { preload(chapter) } /** * Called from the activity to load and set the next chapter as active. */ fun loadNextChapter() { val nextChapter = viewerChaptersRelay.value?.nextChapter ?: return loadAdjacent(nextChapter) } /** * Called from the activity to load and set the previous chapter as active. */ fun loadPreviousChapter() { val prevChapter = viewerChaptersRelay.value?.prevChapter ?: return loadAdjacent(prevChapter) } /** * Returns the currently active chapter. */ fun getCurrentChapter(): ReaderChapter? { return viewerChaptersRelay.value?.currChapter } /** * Returns the viewer position used by this manga or the default one. */ fun getMangaViewer(): Int { val manga = manga ?: return preferences.defaultViewer() return if (manga.viewer == 0) preferences.defaultViewer() else manga.viewer } /** * Updates the viewer position for the open manga. */ fun setMangaViewer(viewer: Int) { val manga = manga ?: return manga.viewer = viewer db.updateMangaViewer(manga).executeAsBlocking() Observable.timer(250, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()) .subscribeFirst({ view, _ -> val currChapters = viewerChaptersRelay.value if (currChapters != null) { // Save current page val currChapter = currChapters.currChapter currChapter.requestedPage = currChapter.chapter.last_page_read // Emit manga and chapters to the new viewer view.setManga(manga) view.setChapters(currChapters) } }) } /** * Saves the image of this [page] in the given [directory] and returns the file location. */ private fun saveImage(page: ReaderPage, directory: File, manga: Manga): File { val stream = page.stream!! val type = ImageUtil.findImageType(stream) ?: throw Exception("Not an image") directory.mkdirs() val chapter = page.chapter.chapter // Build destination file. val filename = DiskUtil.buildValidFilename( "${manga.title} - ${chapter.name}".take(225) ) + " - ${page.number}.${type.extension}" val destFile = File(directory, filename) stream().use { input -> destFile.outputStream().use { output -> input.copyTo(output) } } return destFile } /** * Saves the image of this [page] on the pictures directory and notifies the UI of the result. * There's also a notification to allow sharing the image somewhere else or deleting it. */ fun saveImage(page: ReaderPage) { if (page.status != Page.READY) return val manga = manga ?: return val context = Injekt.get<Application>() val notifier = SaveImageNotifier(context) notifier.onClear() // Pictures directory. val destDir = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_PICTURES + File.separator + context.getString(R.string.app_name)) // Copy file in background. Observable.fromCallable { saveImage(page, destDir, manga) } .doOnNext { file -> DiskUtil.scanMedia(context, file) notifier.onComplete(file) } .doOnError { notifier.onError(it.message) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeFirst( { view, file -> view.onSaveImageResult(SaveImageResult.Success(file)) }, { view, error -> view.onSaveImageResult(SaveImageResult.Error(error)) } ) } /** * Shares the image of this [page] and notifies the UI with the path of the file to share. * The image must be first copied to the internal partition because there are many possible * formats it can come from, like a zipped chapter, in which case it's not possible to directly * get a path to the file and it has to be decompresssed somewhere first. Only the last shared * image will be kept so it won't be taking lots of internal disk space. */ fun shareImage(page: ReaderPage) { if (page.status != Page.READY) return val manga = manga ?: return val context = Injekt.get<Application>() val destDir = File(context.cacheDir, "shared_image") Observable.fromCallable { destDir.deleteRecursively() } // Keep only the last shared file .map { saveImage(page, destDir, manga) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeFirst( { view, file -> view.onShareImageResult(file) }, { view, error -> /* Empty */ } ) } /** * Sets the image of this [page] as cover and notifies the UI of the result. */ fun setAsCover(page: ReaderPage) { if (page.status != Page.READY) return val manga = manga ?: return val stream = page.stream ?: return Observable .fromCallable { if (manga.source == LocalSource.ID) { val context = Injekt.get<Application>() LocalSource.updateCover(context, manga, stream()) R.string.cover_updated SetAsCoverResult.Success } else { val thumbUrl = manga.thumbnail_url ?: throw Exception("Image url not found") if (manga.favorite) { coverCache.copyToCache(thumbUrl, stream()) SetAsCoverResult.Success } else { SetAsCoverResult.AddToLibraryFirst } } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeFirst( { view, result -> view.onSetAsCoverResult(result) }, { view, _ -> view.onSetAsCoverResult(SetAsCoverResult.Error) } ) } /** * Results of the set as cover feature. */ enum class SetAsCoverResult { Success, AddToLibraryFirst, Error } /** * Results of the save image feature. */ sealed class SaveImageResult { class Success(val file: File) : SaveImageResult() class Error(val error: Throwable) : SaveImageResult() } /** * Starts the service that updates the last chapter read in sync services. This operation * will run in a background thread and errors are ignored. */ private fun updateTrackLastChapterRead() { if (!preferences.autoUpdateTrack()) return val viewerChapters = viewerChaptersRelay.value ?: return val manga = manga ?: return val currChapter = viewerChapters.currChapter.chapter val prevChapter = viewerChapters.prevChapter?.chapter // Get the last chapter read from the reader. val lastChapterRead = if (currChapter.read) currChapter.chapter_number.toInt() else if (prevChapter != null && prevChapter.read) prevChapter.chapter_number.toInt() else return val trackManager = Injekt.get<TrackManager>() db.getTracks(manga).asRxSingle() .flatMapCompletable { trackList -> Completable.concat(trackList.map { track -> val service = trackManager.getService(track.sync_id) if (service != null && service.isLogged && lastChapterRead > track.last_chapter_read) { track.last_chapter_read = lastChapterRead // We wan't these to execute even if the presenter is destroyed and leaks // for a while. The view can still be garbage collected. Observable.defer { service.update(track) } .map { db.insertTrack(track).executeAsBlocking() } .toCompletable() .onErrorComplete() } else { Completable.complete() } }) } .onErrorComplete() .subscribeOn(Schedulers.io()) .subscribe() } /** * Enqueues this [chapter] to be deleted when [deletePendingChapters] is called. The download * manager handles persisting it across process deaths. */ private fun enqueueDeleteReadChapters(chapter: ReaderChapter) { if (!chapter.chapter.read || chapter.pageLoader !is DownloadPageLoader) return val manga = manga ?: return // Return if the setting is disabled val removeAfterReadSlots = preferences.removeAfterReadSlots() if (removeAfterReadSlots == -1) return Completable .fromCallable { // Position of the read chapter val position = chapterList.indexOf(chapter) // Retrieve chapter to delete according to preference val chapterToDelete = chapterList.getOrNull(position - removeAfterReadSlots) if (chapterToDelete != null) { downloadManager.enqueueDeleteChapters(listOf(chapterToDelete.chapter), manga) } } .onErrorComplete() .subscribeOn(Schedulers.io()) .subscribe() } /** * Deletes all the pending chapters. This operation will run in a background thread and errors * are ignored. */ private fun deletePendingChapters() { Completable.fromCallable { downloadManager.deletePendingChapters() } .onErrorComplete() .subscribeOn(Schedulers.io()) .subscribe() } }
apache-2.0
262c8710024739292e966387ab28e98c
37.210123
115
0.607354
5.143064
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/exh/metadata/metadata/HBrowseSearchMetadata.kt
1
1519
package exh.metadata.metadata import eu.kanade.tachiyomi.source.model.SManga import exh.metadata.metadata.EightMusesSearchMetadata.Companion.ARTIST_NAMESPACE import exh.metadata.metadata.base.RaisedSearchMetadata import exh.plusAssign class HBrowseSearchMetadata : RaisedSearchMetadata() { var hbId: Long? = null var title: String? by titleDelegate(TITLE_TYPE_MAIN) // Length in pages var length: Int? = null override fun copyTo(manga: SManga) { manga.url = "/$hbId" title?.let { manga.title = it } // Guess thumbnail URL if manga does not have thumbnail URL if(manga.thumbnail_url.isNullOrBlank()) { manga.thumbnail_url = guessThumbnailUrl(hbId.toString()) } manga.artist = tags.ofNamespace(ARTIST_NAMESPACE).joinToString { it.name } val titleDesc = StringBuilder() title?.let { titleDesc += "Title: $it\n" } length?.let { titleDesc += "Length: $it page(s)\n" } val tagsDesc = tagsToDescription() manga.description = listOf(titleDesc.toString(), tagsDesc.toString()) .filter(String::isNotBlank) .joinToString(separator = "\n") } companion object { const val BASE_URL = "https://www.hbrowse.com" private const val TITLE_TYPE_MAIN = 0 const val TAG_TYPE_DEFAULT = 0 fun guessThumbnailUrl(hbid: String): String { return "$BASE_URL/thumbnails/${hbid}_1.jpg#guessed" } } }
apache-2.0
2f7b191b5aa9d5ac86eb1acdbf266dcc
28.230769
82
0.635945
4.127717
false
false
false
false
walleth/walleth
app/src/online/java/org/walleth/dataprovider/DataProvidingService.kt
1
9726
package org.walleth.dataprovider import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import androidx.lifecycle.* import androidx.lifecycle.Observer import androidx.work.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch import okhttp3.OkHttpClient import org.kethereum.extensions.toHexString import org.kethereum.model.Address import org.kethereum.rpc.EthereumRPCException import org.koin.android.ext.android.inject import org.komputing.kethereum.erc20.ERC20RPCConnector import org.ligi.kaxt.getNotificationManager import org.ligi.kaxt.livedata.nonNull import org.ligi.kaxt.livedata.observe import org.walleth.App import org.walleth.chains.ChainInfoProvider import org.walleth.data.AppDatabase import org.walleth.data.KEY_TX_HASH import org.walleth.data.addresses.CurrentAddressProvider import org.walleth.data.balances.Balance import org.walleth.data.balances.upsertIfNewerBlock import org.walleth.data.chaininfo.ChainInfo import org.walleth.data.config.Settings import org.walleth.data.rpc.RPCProvider import org.walleth.data.tokens.CurrentTokenProvider import org.walleth.data.tokens.isRootToken import org.walleth.data.transactions.TransactionEntity import org.walleth.kethereum.etherscan.ALL_ETHERSCAN_SUPPORTED_NETWORKS import org.walleth.notifications.NOTIFICATION_CHANNEL_ID_DATA_SERVICE import org.walleth.notifications.NOTIFICATION_ID_DATA_SERVICE import org.walleth.workers.RelayTransactionWorker import timber.log.Timber import java.io.IOException import java.util.* import java.util.concurrent.TimeUnit private const val ACTION_STOP_SERVICE = "STOP" class DataProvidingService : LifecycleService() { private val okHttpClient: OkHttpClient by inject() private val currentAddressProvider: CurrentAddressProvider by inject() private val tokenProvider: CurrentTokenProvider by inject() private val appDatabase: AppDatabase by inject() private val chainInfoProvider: ChainInfoProvider by inject() private val rpcProvider: RPCProvider by inject() private val settings: Settings by inject() private val blockScoutApi = EtherScanAPI(appDatabase, rpcProvider, okHttpClient) companion object { private var timing = 7_000 // in MilliSeconds private var last_run = 0L private var shortcut = false } class TimingModifyingLifecycleObserver : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun connectListener() { timing = 7_000 shortcut = true } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun disconnectListener() { timing = 70_000 } } class ResettingObserver<T> : Observer<T> { override fun onChanged(p0: T?) { shortcut = true } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) if (ACTION_STOP_SERVICE == intent?.action) { Timber.d("DataProvider stopped via intent from notificaion"); stopSelf(); } else { if (Build.VERSION.SDK_INT > 25) { val channel = NotificationChannel(NOTIFICATION_CHANNEL_ID_DATA_SERVICE, "Ethereum Data Provider", NotificationManager.IMPORTANCE_LOW) channel.description = "WalletConnectNotifications" getNotificationManager().createNotificationChannel(channel) } val stopSelf = Intent(this, DataProvidingService::class.java) stopSelf.action = ACTION_STOP_SERVICE val stopSelfPendingIntent = PendingIntent.getService(this, 0, stopSelf, PendingIntent.FLAG_CANCEL_CURRENT) val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_DATA_SERVICE).apply { if (Build.VERSION.SDK_INT > 19) { setSmallIcon(org.walleth.R.drawable.ic_ethereum_logo) } setContentTitle(null) setOngoing(true) setLocalOnly(true) setOnlyAlertOnce(true) addAction(org.walleth.R.drawable.ic_baseline_cancel_24, "stop", stopSelfPendingIntent) priority = NotificationCompat.PRIORITY_MIN } startForeground(NOTIFICATION_ID_DATA_SERVICE, notification.build()) lifecycle.addObserver(TimingModifyingLifecycleObserver()) val dateFormat = java.text.DateFormat.getTimeInstance() lifecycleScope.launch(Dispatchers.IO) { lifecycleScope.launch { currentAddressProvider.flow.combine(chainInfoProvider.getFlow()) { _, _ -> }.collect { shortcut = true } } while (settings.isKeepETHSyncEnabledWanted() || last_run == 0L || App.visibleActivities.isNotEmpty()) { last_run = System.currentTimeMillis() chainInfoProvider.getCurrent().let { currentChain -> val currentChainId = currentChain.chainId currentAddressProvider.getCurrent()?.let { address -> notification.setContentTitle("Last Ethereum data sync: " + dateFormat.format(Date())) notification.setContentText("via " + rpcProvider.get()?.description) getNotificationManager().notify(NOTIFICATION_ID_DATA_SERVICE, notification.build()) try { if (ALL_ETHERSCAN_SUPPORTED_NETWORKS.contains(currentChainId)) { tryFetchFromBlockscout(address, currentChain) } queryRPCForBalance(address) queryRPCForTransactions() } catch (ioe: IOException) { Timber.i(ioe, "problem fetching data - are we online? ") } } while ((last_run + timing) > System.currentTimeMillis() && !shortcut) { delay(100) } shortcut = false } } stopSelf() } relayTransactionsIfNeeded() } return START_STICKY } private suspend fun queryRPCForTransactions() { appDatabase.transactions.getAllPending().forEach { localTx -> val rpc = rpcProvider.get() val tx = rpc?.getTransactionByHash(localTx.hash) if (tx?.transaction?.blockNumber != null) { localTx.transactionState.isPending = false localTx.transaction = tx.transaction appDatabase.transactions.upsert(localTx) } localTx.hash } } private fun relayTransactionsIfNeeded() { appDatabase.transactions.getAllToRelayLive().nonNull().observe(this) { transactionList -> val alltorelay = transactionList.filter { it.transactionState.error == null } alltorelay.forEach { sendTransaction(it) } } } private fun sendTransaction(transaction: TransactionEntity) { val uploadWorkRequest = OneTimeWorkRequestBuilder<RelayTransactionWorker>() .setBackoffCriteria( BackoffPolicy.LINEAR, OneTimeWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS ) .addTag("relay") .setInputData(workDataOf(KEY_TX_HASH to transaction.hash)) .build() WorkManager.getInstance(this).enqueueUniqueWork(transaction.hash, ExistingWorkPolicy.REPLACE, uploadWorkRequest) } private suspend fun tryFetchFromBlockscout(address: Address, chain: ChainInfo) { blockScoutApi.queryTransactions(address.hex, chain) } private suspend fun queryRPCForBalance(address: Address) { val currentToken = tokenProvider.getCurrent() val currentChainId = chainInfoProvider.getCurrent()?.chainId val rpc = rpcProvider.get() if (rpc == null) { Timber.e("no RPC found") } else { try { val blockNumber = rpc.blockNumber() if (blockNumber != null) { val blockNumberAsHex = blockNumber.toHexString() val balance = if (currentToken.isRootToken()) { rpc.getBalance(address, blockNumberAsHex) } else { ERC20RPCConnector(currentToken.address, rpc).balanceOf(address) } if (balance != null) { appDatabase.balances.upsertIfNewerBlock( Balance( address = address, block = blockNumber.toLong(), balance = balance, tokenAddress = currentToken.address, chain = currentChainId ) ) } } } catch (rpcException: EthereumRPCException) { Timber.e(rpcException, "error when getting balance") } catch (e: Exception) { Timber.e(e, "error when getting balance") } } } }
gpl-3.0
6e4f54f403a1f59c8ba174a0725326a7
38.064257
149
0.618034
5.189968
false
false
false
false
segmentio/analytics-android
analytics-samples/kotlin-sample/src/main/java/com/example/kotlin_sample/ScreenActivity.kt
1
3379
/** * The MIT License (MIT) * * Copyright (c) 2014 Segment.io, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.example.kotlin_sample import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.kotlin_sample.databinding.ActivityScreenBinding import com.segment.analytics.Analytics class ScreenActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityScreenBinding.inflate(layoutInflater) val view = binding.root setContentView(view) initialSetup() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater: MenuInflater = menuInflater inflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle item selection return when (item.itemId) { R.id.docs -> { val openDocs = Intent(Intent.ACTION_VIEW) openDocs.data = Uri.parse("https://segment.com/docs/tutorials/quickstart-android/") startActivity(openDocs) try { startActivity(openDocs) } catch (e: ActivityNotFoundException) { Toast.makeText(this, "No browser to open link", Toast.LENGTH_SHORT).show() } true } else -> super.onOptionsItemSelected(item) } } private fun onFlushClicked() { Analytics.with(this).flush() Toast.makeText(this, "Events flushed", Toast.LENGTH_SHORT).show() } private lateinit var binding: ActivityScreenBinding private fun initialSetup() { Analytics.with(this).screen("Screen activity viewed") val returnMessage = """ Screen event has been recorded! Press 'Flush' to send events to Segment. """.trimIndent() binding.screenResult.text = returnMessage binding.screenFlush.setOnClickListener { onFlushClicked() } } }
mit
a403b8169d988725f0df49ee879f5d38
35.333333
99
0.683634
4.799716
false
false
false
false
thatadamedwards/kotlin-koans
src/iii_conventions/MyDate.kt
1
1524
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate> { override fun compareTo(other: MyDate) = when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int) operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number) operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval): MyDate { return addTimeIntervals(timeInterval, 1) } operator fun MyDate.plus(timeIntervals: RepeatedTimeInterval): MyDate { return addTimeIntervals(timeIntervals.timeInterval, timeIntervals.number) } enum class TimeInterval { DAY, WEEK, YEAR } class DateRange( override val start: MyDate, override val endInclusive: MyDate ) : ClosedRange<MyDate>, Iterable<MyDate> { override fun contains(value: MyDate): Boolean = start <= value && value <= endInclusive override fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.addTimeIntervals(TimeInterval.DAY, 1) return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive }
mit
9b443fcf5f0ee14761e21a143356cdc3
30.122449
92
0.711942
4.535714
false
false
false
false
grpc/grpc-kotlin
stub/src/test/java/io/grpc/kotlin/AbstractCallsTest.kt
1
6803
/* * Copyright 2020 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.kotlin import com.google.common.util.concurrent.MoreExecutors import io.grpc.BindableService import io.grpc.Context import io.grpc.ManagedChannel import io.grpc.MethodDescriptor import io.grpc.ServerBuilder import io.grpc.ServerCallHandler import io.grpc.ServerInterceptor import io.grpc.ServerInterceptors import io.grpc.ServerMethodDefinition import io.grpc.ServerServiceDefinition import io.grpc.ServiceDescriptor import io.grpc.examples.helloworld.GreeterGrpc import io.grpc.examples.helloworld.HelloReply import io.grpc.examples.helloworld.HelloRequest import io.grpc.examples.helloworld.MultiHelloRequest import io.grpc.inprocess.InProcessChannelBuilder import io.grpc.inprocess.InProcessServerBuilder import io.grpc.testing.GrpcCleanupRule import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.debug.junit4.CoroutinesTimeout import kotlinx.coroutines.launch import org.junit.After import org.junit.Before import org.junit.Rule abstract class AbstractCallsTest { companion object { fun helloRequest(name: String): HelloRequest = HelloRequest.newBuilder().setName(name).build() fun helloReply(message: String): HelloReply = HelloReply.newBuilder().setMessage(message).build() fun multiHelloRequest(vararg name: String): MultiHelloRequest = MultiHelloRequest.newBuilder().addAllName(name.asList()).build() val sayHelloMethod: MethodDescriptor<HelloRequest, HelloReply> = GreeterGrpc.getSayHelloMethod() val clientStreamingSayHelloMethod: MethodDescriptor<HelloRequest, HelloReply> = GreeterGrpc.getClientStreamSayHelloMethod() val serverStreamingSayHelloMethod: MethodDescriptor<MultiHelloRequest, HelloReply> = GreeterGrpc.getServerStreamSayHelloMethod() val bidiStreamingSayHelloMethod: MethodDescriptor<HelloRequest, HelloReply> = GreeterGrpc.getBidiStreamSayHelloMethod() val greeterService: ServiceDescriptor = GreeterGrpc.getServiceDescriptor() fun <E> CoroutineScope.produce( block: suspend SendChannel<E>.() -> Unit ): ReceiveChannel<E> { val channel = Channel<E>() launch { channel.block() channel.close() } return channel } suspend fun suspendForever(): Nothing { suspendUntilCancelled { // do nothing } } suspend fun suspendUntilCancelled(onCancelled: (CancellationException) -> Unit): Nothing { val deferred = Job() try { deferred.join() } catch (c: CancellationException) { onCancelled(c) throw c } throw AssertionError("Unreachable") } fun whenContextIsCancelled(onCancelled: () -> Unit) { Context.current().withCancellation().addListener( Context.CancellationListener { onCancelled() }, MoreExecutors.directExecutor() ) } } @get:Rule val timeout = CoroutinesTimeout.seconds(10) // We want the coroutines timeout to come first, because it comes with useful debug logs. @get:Rule val grpcCleanup = GrpcCleanupRule().setTimeout(11, TimeUnit.SECONDS) lateinit var channel: ManagedChannel private lateinit var executor: ExecutorService private val context: CoroutineContext get() = executor.asCoroutineDispatcher() @Before fun setUp() { executor = Executors.newFixedThreadPool(10) } @After fun tearDown() { executor.shutdown() if (this::channel.isInitialized) { channel.shutdownNow() channel.awaitTermination(1, TimeUnit.SECONDS) } } inline fun <reified E : Exception> assertThrows( callback: () -> Unit ): E { var ex: Exception? = null try { callback() } catch (e: Exception) { ex = e } if (ex is E) { return ex } else { throw Error("Expected an ${E::class.qualifiedName}", ex) } } /** Generates a channel to a Greeter server with the specified implementation. */ fun makeChannel(impl: BindableService, vararg interceptors: ServerInterceptor): ManagedChannel = makeChannel(ServerInterceptors.intercept(impl, *interceptors)) fun makeChannel( serverServiceDefinition: ServerServiceDefinition, serviceConfig: Map<String, Any> = emptyMap() ): ManagedChannel { val serverName = InProcessServerBuilder.generateName() grpcCleanup.register( InProcessServerBuilder.forName(serverName) .run { this as ServerBuilder<*> } // workaround b/123879662 .executor(executor) .addService(serverServiceDefinition) .build() .start() ) return grpcCleanup.register( InProcessChannelBuilder .forName(serverName) .enableRetry() .defaultServiceConfig(serviceConfig) .run { this as io.grpc.ManagedChannelBuilder<*> } // workaround b/123879662 .executor(executor) .build() ) } fun makeChannel( impl: ServerMethodDefinition<*, *>, vararg interceptors: ServerInterceptor ): ManagedChannel { val builder = ServerServiceDefinition.builder(greeterService) for (method in greeterService.methods) { if (method == impl.methodDescriptor) { builder.addMethod(impl) } else { builder.addMethod(method, ServerCallHandler { _, _ -> TODO() }) } } return makeChannel(ServerInterceptors.intercept(builder.build(), *interceptors)) } fun makeChannel( serverServiceDefinition: ServerServiceDefinition, config: Map<String, Any> = emptyMap(), vararg interceptors: ServerInterceptor ): ManagedChannel { return makeChannel( ServerInterceptors.intercept(serverServiceDefinition, *interceptors), config ) } fun <R> runBlocking(block: suspend CoroutineScope.() -> R): Unit = kotlinx.coroutines.runBlocking(context) { block() Unit } }
apache-2.0
26c9a1bb0c6593639a2861b7ad11b755
30.938967
101
0.726738
4.612203
false
false
false
false
JStege1206/AdventOfCode
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day24.kt
1
1670
package nl.jstege.adventofcode.aoc2015.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.* /** * * @author Jelle Stege */ class Day24 : Day(title = "It Hangs in the Balance") { private companion object Configuration { const val FIRST_SHARES = 3 const val SECOND_SHARES = 4 } override fun first(input: Sequence<String>): Any = input .map { it.toInt() } .sorted() .toList() .findQuantumEntanglement(FIRST_SHARES) override fun second(input: Sequence<String>): Any = input .map { it.toInt() } .sorted() .toList() .findQuantumEntanglement(SECOND_SHARES) private fun List<Int>.findQuantumEntanglement(groups: Int): Long = (this.sum() / groups) .let { groupSize -> this .asSequence() .sortedDescending() .scan(0, Int::plus) .takeWhile { it < groupSize } .count() .let { start -> (start until this.size) .asSequence() .map { this.combinations(it).filter { combination -> combination.sum() == groupSize } } .filter { it.any() } .filter(Sequence<Set<Int>>::any) .first() .map { it.map(Int::toLong) } .map { it.reduce(Long::times) } .min()!! } } }
mit
98fbd46133c86e939d12a6708ee73254
31.115385
92
0.467066
4.651811
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/widget/LoadMoreView.kt
1
2784
package com.johnny.gank.widget /* * Copyright (C) 2016 Johnny Shieh 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. */ import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.annotation.LongDef import com.johnny.gank.R import kotlinx.android.synthetic.main.load_more_content.view.* /** * description * @author Johnny Shieh ([email protected]) * * * @version 1.0 */ class LoadMoreView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) { @Retention(AnnotationRetention.SOURCE) @LongDef(STATUS_INIT, STATUS_LOADING, STATUS_FAIL, STATUS_NO_MORE) annotation class LoadStatus var status = STATUS_INIT set(@LoadStatus status) { field = status when (status) { STATUS_INIT -> visibility = View.INVISIBLE STATUS_LOADING -> { loading_indicator.visibility = View.VISIBLE load_tip.visibility = View.INVISIBLE visibility = View.VISIBLE } STATUS_FAIL -> { loading_indicator.visibility = View.INVISIBLE load_tip.setText(R.string.load_fail) load_tip.visibility = View.VISIBLE visibility = View.VISIBLE } STATUS_NO_MORE -> { loading_indicator.visibility = View.INVISIBLE load_tip.setText(R.string.load_no_more) load_tip.visibility = View.VISIBLE visibility = View.VISIBLE } } } init { LayoutInflater.from(context).inflate(R.layout.load_more_content, this) layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } companion object { const val STATUS_INIT = 0L const val STATUS_LOADING = 1L const val STATUS_FAIL = 2L const val STATUS_NO_MORE = 3L } }
apache-2.0
368b261c645f937a80d2f544d06f4fa6
32.95122
119
0.630747
4.534202
false
false
false
false
JetBrains/ideavim
src/main/java/com/maddyhome/idea/vim/vimscript/model/functions/handlers/ExistsFunctionHandler.kt
1
1936
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.functions.handlers import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimInt import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.expressions.Expression import com.maddyhome.idea.vim.vimscript.model.expressions.OptionExpression import com.maddyhome.idea.vim.vimscript.model.expressions.SimpleExpression import com.maddyhome.idea.vim.vimscript.model.functions.FunctionHandler import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser object ExistsFunctionHandler : FunctionHandler() { override val name = "exists" override val minimumNumberOfArguments = 1 override val maximumNumberOfArguments = 1 override fun doFunction( argumentValues: List<Expression>, editor: VimEditor, context: ExecutionContext, vimContext: VimLContext, ): VimDataType { val expression = argumentValues[0] return if (expression is SimpleExpression && expression.data is VimString) { val parsedValue = VimscriptParser.parseExpression((expression.data as VimString).value) if (parsedValue is OptionExpression) { if (injector.optionService.getOptions().any { it == parsedValue.optionName } || injector.optionService.getAbbrevs().any { it == parsedValue.optionName }) { VimInt.ONE } else { VimInt.ZERO } } else { TODO() } } else { VimInt.ZERO } } }
mit
c51fdf25663a7aa665c268fb8d4dfcfd
36.230769
163
0.754649
4.217865
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/base/BaseCharacterTile.kt
1
3346
package org.hexworks.zircon.api.data.base import org.hexworks.zircon.api.color.TileColor import org.hexworks.zircon.api.data.CharacterTile import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.graphics.StyleSet import org.hexworks.zircon.api.modifier.Modifier import org.hexworks.zircon.internal.resource.TileType /** * Base class for [CharacterTile]s. */ abstract class BaseCharacterTile : BaseTile(), CharacterTile { override val tileType: TileType get() = TileType.CHARACTER_TILE override val foregroundColor: TileColor get() = styleSet.foregroundColor override val backgroundColor: TileColor get() = styleSet.backgroundColor override val modifiers: Set<Modifier> get() = styleSet.modifiers override fun withForegroundColor(foregroundColor: TileColor): CharacterTile { return if (this.foregroundColor == foregroundColor) { this } else { Tile.createCharacterTile(character, styleSet.withForegroundColor(foregroundColor)) } } override fun withBackgroundColor(backgroundColor: TileColor): CharacterTile { return if (this.backgroundColor == backgroundColor) { this } else { Tile.createCharacterTile(character, styleSet.withBackgroundColor(backgroundColor)) } } override fun withStyle(style: StyleSet): CharacterTile { return if (this.styleSet == style) { this } else { Tile.createCharacterTile(character, style) } } override fun withModifiers(vararg modifiers: Modifier): CharacterTile = withModifiers(modifiers.toSet()) override fun withModifiers(modifiers: Set<Modifier>): CharacterTile { return if (this.modifiers == modifiers) { this } else { return Tile.createCharacterTile(character, styleSet.withModifiers(modifiers)) } } override fun withAddedModifiers(vararg modifiers: Modifier): CharacterTile = withAddedModifiers(modifiers.toSet()) override fun withAddedModifiers(modifiers: Set<Modifier>): CharacterTile { return if (this.modifiers.containsAll(modifiers)) { this } else { return Tile.createCharacterTile(character, styleSet.withAddedModifiers(modifiers)) } } override fun withRemovedModifiers(vararg modifiers: Modifier): CharacterTile = withRemovedModifiers(modifiers.toSet()) override fun withRemovedModifiers(modifiers: Set<Modifier>): CharacterTile { return if (this.modifiers.intersect(modifiers).isEmpty()) { this } else { Tile.createCharacterTile(character, styleSet.withRemovedModifiers(modifiers)) } } override fun withNoModifiers(): CharacterTile { return if (this.modifiers.isEmpty()) { this } else { Tile.createCharacterTile(character, styleSet.withNoModifiers()) } } override fun withCharacter(character: Char): CharacterTile { return if (this.character == character) { this } else { Tile.createCharacterTile(character, styleSet) } } override fun toBuilder() = Tile.newBuilder() .withCharacter(character) .withStyleSet(styleSet) }
apache-2.0
c0a856f3649b48d5e6ac627fb5bafb62
31.485437
94
0.667962
5.054381
false
false
false
false
nearbydelta/KoreanAnalyzer
hannanum/src/main/kotlin/kr/bydelta/koala/hnn/dict.kt
1
7505
@file:JvmName("Util") @file:JvmMultifileClass package kr.bydelta.koala.hnn import kaist.cilab.jhannanum.common.Code import kaist.cilab.jhannanum.morphanalyzer.chartmorphanalyzer.datastructure.TagSet import kaist.cilab.jhannanum.morphanalyzer.chartmorphanalyzer.datastructure.Trie import kaist.cilab.jhannanum.morphanalyzer.chartmorphanalyzer.resource.AnalyzedDic import kaist.cilab.jhannanum.morphanalyzer.chartmorphanalyzer.resource.Connection import kaist.cilab.jhannanum.morphanalyzer.chartmorphanalyzer.resource.NumberAutomata import kr.bydelta.koala.POS import kr.bydelta.koala.proc.CanCompileDict import kr.bydelta.koala.proc.CanExtractResource import kr.bydelta.koala.proc.DicEntry import java.io.File import java.io.FileOutputStream import java.util.* /** * 한나눔 사용자사전 인터페이스입니다. * * @since 1.x */ object Dictionary : CanCompileDict, CanExtractResource() { /** 품사표기 집합 */ @JvmStatic internal val tagSet: TagSet by lazy { val tagSet = TagSet() val fileTagSet: String = extractResource() + File.separator + "data/kE/tag_set.txt" tagSet.init(fileTagSet, TagSet.TAG_SET_KAIST) tagSet } /** 연결가능 */ @JvmStatic internal val connection: Connection by lazy { val connection = Connection() val fileConnections: String = extractResource() + File.separator + "data/kE/connections.txt" connection.init(fileConnections, tagSet.tagCount, tagSet) connection } /** 기 분석 사전 */ @JvmStatic internal val analyzedDic: AnalyzedDic by lazy { val fileDicAnalyzed: String = extractResource() + File.separator + "data/kE/dic_analyzed.txt" val analyzedDic = AnalyzedDic() analyzedDic.readDic(fileDicAnalyzed) analyzedDic } /** 시스템 사전 */ @JvmStatic internal val systemDic: Trie by lazy { val fileDicSystem: String = extractResource() + File.separator + "data/kE/dic_system.txt" val systemDic = Trie(Trie.DEFAULT_TRIE_BUF_SIZE_SYS) systemDic.read_dic(fileDicSystem, tagSet) systemDic } /** 사용자 사전 파일 */ @JvmStatic private val usrDicPath: File by lazy { val f = File(extractResource() + File.separator + "data/kE/dic_user.txt") f.createNewFile() f.deleteOnExit() f } /** 사용자 사전 (한나눔) **/ @JvmStatic internal val userDic: Trie by lazy { Trie(Trie.DEFAULT_TRIE_BUF_SIZE_USER) } /** 숫자 처리 */ @JvmStatic internal val numAutomata: NumberAutomata by lazy { NumberAutomata() } /** 시스템 사전 (Koala) */ @JvmStatic private val baseEntries = mutableListOf<Pair<String, List<POS>>>() /** 사용자 사전 (Koala) */ @JvmStatic private val usrBuffer = mutableSetOf<Pair<String, POS>>() /** 마지막 사용자사전 업데이트 시각 */ @JvmStatic private var dicLastUpdate = 0L /** * 사용자 사전에, (표면형,품사)의 여러 순서쌍을 추가합니다. * * @since 1.x * @param dict 추가할 (표면형, 품사)의 순서쌍들 (가변인자). 즉, [Pair]<[String], [POS]>들 */ override fun addUserDictionary(vararg dict: DicEntry) { synchronized(usrDicPath) { val writer = FileOutputStream(usrDicPath, true).bufferedWriter() dict.forEach { val (morph, tag) = it writer.write("$morph\t${tag.fromSejongPOS().toLowerCase()}\n") } writer.close() } } /** * 사전에 등재되어 있는지 확인하고, 사전에 없는단어만 반환합니다. * * @since 1.x * @param onlySystemDic 시스템 사전에서만 검색할지 결정합니다. * @param word 확인할 (형태소, 품사)들. * @return 사전에 없는 단어들, 즉, [Pair]<[String], [POS]>들. */ override fun getNotExists(onlySystemDic: Boolean, vararg word: DicEntry): Array<DicEntry> { val (_, system) = if (onlySystemDic) Pair(emptyList(), word.toList()) else word.partition { getItems().contains(it) } // filter out existing morphemes! return system.groupBy { it.first }.flatMap { entry -> val (w, tags) = entry val morph = systemDic.fetch(Code.toTripleArray(w)) // filter out existing morphemes! if (morph == null) tags // The case of not found. else { val found = morph.info_list.map { m -> tagSet.getTagName(m.tag).toSejongPOS() }.toSet() tags.filterNot { m -> m.second in found } } }.toTypedArray() } /** * 사용자 사전에 등재된 모든 Item을 불러옵니다. * * @since 1.x * @return (형태소, 통합품사)의 Sequence. */ override fun getItems(): Set<DicEntry> { usrBuffer += synchronized(usrDicPath){ usrDicPath.readLines().asSequence().map { val segments = it.split('\t') segments[0] to segments[1].toSejongPOS() } } return usrBuffer } /** * 사전을 다시 불러옵니다. */ @JvmStatic internal fun loadDictionary(): Unit = synchronized(userDic) { if (dicLastUpdate < usrDicPath.lastModified()) { dicLastUpdate = usrDicPath.lastModified() userDic.search_end = 0 userDic.read_dic(usrDicPath.absolutePath, tagSet) } } /** * 원본 사전에 등재된 항목 중에서, 지정된 형태소의 항목만을 가져옵니다. (복합 품사 결합 형태는 제외) * * @since 1.x * @param filter 가져올 품사인지 판단하는 함수. * @return (형태소, 품사)의 Iterator. */ override fun getBaseEntries(filter: (POS) -> Boolean): Iterator<DicEntry> { return extractBaseEntries().flatMap { pair -> val (word, tags) = pair tags.filter(filter).map { word to it } }.listIterator() } /** * 시스템 사전의 내용을 불러옵니다. */ @JvmStatic private fun extractBaseEntries(): List<Pair<String, List<POS>>> = if (baseEntries.isNotEmpty()) baseEntries else synchronized(this) { val stack = Stack<Pair<List<Char>, Trie.TNODE>>() stack.push(emptyList<Char>() to systemDic.node_head) while (stack.isNotEmpty()) { val (prefix, top) = stack.pop() val word = if (top.key.toInt() != 0) prefix + top.key else prefix val value = top.info_list if (value != null) { val wordString = Code.toString(word.toCharArray()) baseEntries.add(wordString to value.map { tagSet.getTagName(it.tag).toSejongPOS() }) } if (top.child_size > 0) { for (id in top.child_idx until (top.child_idx + top.child_size)) { stack.push(word to systemDic.get_node(id)) } } } baseEntries } /** * 모델의 명칭입니다. */ override val modelName: String get() = "hannanum" }
gpl-3.0
cbf24a794760c58b2f1f3942e371e965
32.043062
108
0.576539
3.414936
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/asset/assetCacheUtils.kt
1
1779
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.asset import com.acornui.di.Context import com.acornui.io.UrlRequestData import com.acornui.io.toUrlRequestData import com.acornui.serialization.jsonParse import kotlinx.coroutines.Deferred import kotlinx.serialization.DeserializationStrategy suspend fun <R : Any> Context.loadAndCacheJson(deserializer: DeserializationStrategy<R>, path: String, cacheSet: CacheSet = cacheSet()): R = loadAndCacheJsonAsync(deserializer, path.toUrlRequestData(), cacheSet).await() suspend fun <R : Any> Context.loadAndCacheJson(deserializer: DeserializationStrategy<R>, request: UrlRequestData, cacheSet: CacheSet = cacheSet()): R = loadAndCacheJsonAsync(deserializer, request, cacheSet).await() fun <R : Any> Context.loadAndCacheJsonAsync(deserializer: DeserializationStrategy<R>, path: String, cacheSet: CacheSet = cacheSet()): Deferred<R> = loadAndCacheJsonAsync(deserializer, path.toUrlRequestData(), cacheSet) fun <R : Any> Context.loadAndCacheJsonAsync(deserializer: DeserializationStrategy<R>, request: UrlRequestData, cacheSet: CacheSet = cacheSet()): Deferred<R> { return cacheSet.getOrPutAsync(request) { jsonParse(deserializer, loadText(request)) } }
apache-2.0
dbcf1d89c4aa7fc63831f3237ced9379
44.641026
158
0.780776
4.070938
false
false
false
false
Hexworks/zircon
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/fragments/SelectorExample.kt
1
4424
package org.hexworks.zircon.examples.fragments import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.zircon.api.* import org.hexworks.zircon.api.application.AppConfig import org.hexworks.zircon.api.component.ColorTheme import org.hexworks.zircon.api.component.ComponentAlignment import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.graphics.BoxType import org.hexworks.zircon.api.screen.Screen import org.hexworks.zircon.internal.resource.ColorThemeResource object SelectorExample { private val theme = ColorThemes.letThemEatCake() private val themes = ColorThemeResource.values().map { it.getTheme() }.toProperty() @JvmStatic fun main(args: Array<String>) { val tileGrid = SwingApplications.startTileGrid( AppConfig.newBuilder() .withSize(Size.create(60, 40)) .withDefaultTileset(CP437TilesetResources.wanderlust16x16()) .build() ) val screen = Screen.create(tileGrid) screen.theme = theme val leftPanel = Components.panel().withPreferredSize(20, 40).withAlignmentWithin(screen, ComponentAlignment.LEFT_CENTER) .withDecorations(ComponentDecorations.box(BoxType.SINGLE, "Try them!")).build().also { screen.addComponent(it) } val fragmentsList = Components.vbox() .withPreferredSize(leftPanel.contentSize.width, 20) .withAlignmentWithin(leftPanel, ComponentAlignment.CENTER) .withSpacing(2) .build().also { leftPanel.addComponent(it) } val logArea = Components.logArea().withPreferredSize(40, 40).withAlignmentWithin(screen, ComponentAlignment.RIGHT_CENTER) .withDecorations(ComponentDecorations.box(BoxType.TOP_BOTTOM_DOUBLE, "Logs")).build().also { screen.addComponent(it) } val width = fragmentsList.contentSize.width fragmentsList.addFragment( Fragments.selector<String>() .withWidth(width) .withValues(listOf("Centered", "strings", "as", "values").toProperty()).build() ) fragmentsList.addFragment( Fragments.selector<String>() .withWidth(width) .withValues(listOf("Strings", "left", "aligned").toProperty()) .withCenteredText(false) .build() ) fragmentsList.addFragment( Fragments.selector<String>() .withWidth(width) .withValues(listOf("Long", "values", "get", "truncated and that's it").toProperty()) .build() ) // This is a special form of MultiSelect fragmentsList.addFragment( Fragments.selector<ColorTheme>() .withWidth(width) .withValues(themes) .build().apply { screen.themeProperty.updateFrom(selectedValue) selectedValue.onChange { (oldValue, newValue) -> logArea.addParagraph("Changed value from $oldValue to $newValue", true) } } ) fragmentsList.addFragment( Fragments.selector<Int>() .withWidth(width) .withValues(listOf(2, 4, 8, 16, 32).toProperty()) .build().apply { selectedValue.onChange { (oldValue, newValue) -> logArea.addParagraph("Changed value from $oldValue to $newValue", true) } } ) fragmentsList.addFragment( Fragments.selector<String>() .withWidth(width) .withValues(listOf("Click", "me!").toProperty()) .withClickableLabel(true) .build().apply { selectedValue.onChange { (oldValue, newValue) -> val text = if (oldValue == newValue) { "You clicked the label!" } else { "You changed from '$oldValue' to '$newValue'. Try clicking the label!" } logArea.addParagraph(text, true) } } ) screen.display() } }
apache-2.0
be7ab2f2d8c17134fe7088d961364437
37.137931
119
0.563291
5.144186
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/impl/jps/serialization/JpsProjectSaveAfterChangesTest.kt
1
8862
package com.intellij.workspaceModel.ide.impl.jps.serialization import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.util.io.FileUtil import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.JpsProjectConfigLocation import com.intellij.workspaceModel.ide.impl.IdeVirtualFileUrlManagerImpl import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.storage.EntityChange import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.bridgeEntities.api.* import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.jps.util.JpsPathUtil import com.intellij.workspaceModel.storage.bridgeEntities.api.modifyEntity import org.junit.Assert import org.junit.Before import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File class JpsProjectSaveAfterChangesTest { @Rule @JvmField val projectModel = ProjectModelRule(true) private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = IdeVirtualFileUrlManagerImpl() } @Test fun `modify module`() { checkSaveProjectAfterChange("common/modifyIml", "common/modifyIml") { builder, configLocation -> val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" } val sourceRoot = utilModule.sourceRoots.first() builder.modifyEntity(sourceRoot) { url = configLocation.baseDirectoryUrl.append("util/src2") } builder.modifyEntity(utilModule.customImlData!!) { rootManagerTagCustomData = """<component> <annotation-paths> <root url="${configLocation.baseDirectoryUrlString}/lib/anno2" /> </annotation-paths> <javadoc-paths> <root url="${configLocation.baseDirectoryUrlString}/lib/javadoc2" /> </javadoc-paths> </component>""" } builder.modifyEntity(utilModule) { dependencies.removeLast() dependencies.removeLast() } builder.modifyEntity(utilModule.contentRoots.first()) { excludedPatterns = mutableListOf() excludedUrls = mutableListOf() } builder.modifyEntity(sourceRoot.asJavaSourceRoot()!!) { packagePrefix = "" } } } @Test fun `rename module`() { checkSaveProjectAfterChange("directoryBased/renameModule", "fileBased/renameModule") { builder, _ -> val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" } builder.modifyEntity(utilModule) { name = "util2" } } } @Test fun `add library and check vfu index not empty`() { checkSaveProjectAfterChange("directoryBased/addLibrary", "fileBased/addLibrary") { builder, configLocation -> val root = LibraryRoot(virtualFileManager.fromUrl("jar://${JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString)}/lib/junit2.jar!/"), LibraryRootTypeId.COMPILED) val source = JpsEntitySourceFactory.createJpsEntitySourceForProjectLibrary(configLocation) builder.addLibraryEntity("junit2", LibraryTableId.ProjectLibraryTableId, listOf(root), emptyList(), source) builder.entities(LibraryEntity::class.java).forEach { libraryEntity -> val virtualFileUrl = libraryEntity.roots.first().url val entitiesByUrl = builder.getMutableVirtualFileUrlIndex().findEntitiesByUrl(virtualFileUrl) Assert.assertTrue(entitiesByUrl.toList().isNotEmpty()) } } } @Test fun `add module`() { checkSaveProjectAfterChange("directoryBased/addModule", "fileBased/addModule") { builder, configLocation -> val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation) val dependencies = listOf(ModuleDependencyItem.InheritedSdkDependency, ModuleDependencyItem.ModuleSourceDependency) val module = builder.addModuleEntity("newModule", dependencies, source) builder.modifyEntity(module) { type = "JAVA_MODULE" } val contentRootEntity = builder.addContentRootEntity(configLocation.baseDirectoryUrl.append("new"), emptyList(), emptyList(), module) val sourceRootEntity = builder.addSourceRootEntity(contentRootEntity, configLocation.baseDirectoryUrl.append("new"), "java-source", source) builder.addJavaSourceRootEntity(sourceRootEntity, false, "") builder.addJavaModuleSettingsEntity(true, true, null, null, null, module, source) } } @Test fun `remove module`() { checkSaveProjectAfterChange("directoryBased/removeModule", "fileBased/removeModule") { builder, _ -> val utilModule = builder.entities(ModuleEntity::class.java).first { it.name == "util" } //todo now we need to remove module libraries by hand, maybe we should somehow modify the model instead val moduleLibraries = utilModule.getModuleLibraries(builder).toList() builder.removeEntity(utilModule) moduleLibraries.forEach { builder.removeEntity(it) } } } @Test fun `modify library`() { checkSaveProjectAfterChange("directoryBased/modifyLibrary", "fileBased/modifyLibrary") { builder, configLocation -> val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" } val root = LibraryRoot(virtualFileManager.fromUrl("jar://${JpsPathUtil.urlToPath(configLocation.baseDirectoryUrlString)}/lib/junit2.jar!/"), LibraryRootTypeId.COMPILED) builder.modifyEntity(junitLibrary) { roots = mutableListOf(root) } } } @Test fun `rename library`() { checkSaveProjectAfterChange("directoryBased/renameLibrary", "fileBased/renameLibrary") { builder, _ -> val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" } builder.modifyEntity(junitLibrary) { name = "junit2" } } } @Test fun `remove library`() { checkSaveProjectAfterChange("directoryBased/removeLibrary", "fileBased/removeLibrary") { builder, _ -> val junitLibrary = builder.entities(LibraryEntity::class.java).first { it.name == "junit" } builder.removeEntity(junitLibrary) } } private fun checkSaveProjectAfterChange(directoryNameForDirectoryBased: String, directoryNameForFileBased: String, change: (MutableEntityStorage, JpsProjectConfigLocation) -> Unit) { checkSaveProjectAfterChange(sampleDirBasedProjectFile, directoryNameForDirectoryBased, change) checkSaveProjectAfterChange(sampleFileBasedProjectFile, directoryNameForFileBased, change) } private fun checkSaveProjectAfterChange(originalProjectFile: File, changedFilesDirectoryName: String?, change: (MutableEntityStorage, JpsProjectConfigLocation) -> Unit) { val projectData = copyAndLoadProject(originalProjectFile, virtualFileManager) val builder = MutableEntityStorage.from(projectData.storage) change(builder, projectData.configLocation) val changesMap = builder.collectChanges(projectData.storage) val changedSources = changesMap.values.flatMapTo(HashSet()) { changes -> changes.flatMap { change -> when (change) { is EntityChange.Added -> listOf(change.entity) is EntityChange.Removed -> listOf(change.entity) is EntityChange.Replaced -> listOf(change.oldEntity, change.newEntity) } }.map { it.entitySource }} val writer = JpsFileContentWriterImpl(projectData.configLocation) projectData.serializers.saveEntities(builder.toSnapshot(), changedSources, writer) writer.writeFiles() projectData.serializers.checkConsistency(projectData.configLocation, builder.toSnapshot(), virtualFileManager) val expectedDir = FileUtil.createTempDirectory("jpsProjectTest", "expected") FileUtil.copyDir(projectData.originalProjectDir, expectedDir) if (changedFilesDirectoryName != null) { val changedDir = PathManagerEx.findFileUnderCommunityHome("platform/workspaceModel/jps/tests/testData/serialization/reload/$changedFilesDirectoryName") FileUtil.copyDir(changedDir, expectedDir) } expectedDir.walk().filter { it.isFile && it.readText().trim() == "<delete/>" }.forEach { FileUtil.delete(it) } assertDirectoryMatches(projectData.projectDir, expectedDir, emptySet(), emptyList()) } companion object { @JvmField @ClassRule val appRule = ApplicationRule() } }
apache-2.0
f388edee936dfd643eba0d3290af9922
43.537688
174
0.720492
5.290746
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/MoveFilesWithDeclarationsViewDescriptor.kt
1
2320
// 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.refactoring.move.moveDeclarations import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.refactoring.RefactoringBundle import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import com.intellij.usageView.UsageViewUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle internal class MoveFilesWithDeclarationsViewDescriptor( private val myElementsToMove: Array<PsiElement>, newParent: PsiDirectory ) : UsageViewDescriptor { @Nls private val myProcessedElementsHeader: String @Nls private val myCodeReferencesText: String init { if (myElementsToMove.size == 1) { myProcessedElementsHeader = RefactoringBundle.message( "move.single.element.elements.header", UsageViewUtil.getType(myElementsToMove[0]), newParent.virtualFile.presentableUrl ).capitalize() myCodeReferencesText = KotlinBundle.message( "text.references.in.code.to.0.1.and.its.declarations", UsageViewUtil.getType(myElementsToMove[0]), UsageViewUtil.getLongName(myElementsToMove[0]) ) } else { myProcessedElementsHeader = StringUtil.capitalize(RefactoringBundle.message("move.files.elements.header", newParent.virtualFile.presentableUrl)) myCodeReferencesText = RefactoringBundle.message("references.found.in.code") } } override fun getElements() = myElementsToMove override fun getProcessedElementsHeader() = myProcessedElementsHeader override fun getCodeReferencesText(usagesCount: Int, filesCount: Int): String { return myCodeReferencesText + UsageViewBundle.getReferencesString(usagesCount, filesCount) } override fun getCommentReferencesText(usagesCount: Int, filesCount: Int): String = RefactoringBundle.message("comments.elements.header", UsageViewBundle.getOccurencesString(usagesCount, filesCount)) }
apache-2.0
0d6c7d4a6c1830563e6016b58744249f
42.792453
158
0.739224
4.87395
false
false
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/headers/HeaderLevelInferenceTypedHandler.kt
6
7083
package org.intellij.plugins.markdown.editor.headers import com.intellij.application.options.CodeStyle import com.intellij.codeInsight.editorActions.TypedHandlerDelegate import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiUtilCore import com.intellij.psi.util.parents import com.intellij.psi.util.siblings import com.intellij.refactoring.suggested.endOffset import com.intellij.refactoring.suggested.startOffset import com.intellij.util.DocumentUtil import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentSpaces import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAt import org.intellij.plugins.markdown.lang.MarkdownFileType import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile import org.intellij.plugins.markdown.lang.psi.impl.MarkdownHeader import org.intellij.plugins.markdown.lang.psi.impl.MarkdownListItem internal class HeaderLevelInferenceTypedHandler: TypedHandlerDelegate() { override fun beforeCharTyped(char: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result { if (!Registry.`is`("markdown.experimental.header.level.inference.enable")) { return super.beforeCharTyped(char, project, editor, file, fileType) } if (file.fileType != MarkdownFileType.INSTANCE || file !is MarkdownFile || char != '#') { return super.beforeCharTyped(char, project, editor, file, fileType) } val document = editor.document PsiDocumentManager.getInstance(project).commitDocument(document) if (shouldIgnore(file, editor)) { return super.beforeCharTyped(char, project, editor, file, fileType) } val caretOffset = editor.caretModel.offset val level = findPreviousHeader(file, document, caretOffset)?.level ?: 1 val header = buildString { repeat(level) { append('#') } append(' ') } executeCommand(project) { EditorModificationUtil.insertStringAtCaret(editor, header) } return Result.STOP } companion object { /** * Since there are a lot of places there valid headers can not be created, * check current context and decide if header completion shouldn't be performed. * * The main rule for valid header - it should start be at the beginning of the line. * This rule basically covers all cases, except headers inside list items and block quotes. * For that case, we consider item or quote marker end as the beginning of the current line. * * This rule can be checked by looking at the current line prefix (see [isValidLinePrefix]). */ // TODO: Handle headers inside block quotes private fun shouldIgnore(file: MarkdownFile, editor: Editor): Boolean { val offset = editor.caretModel.offset val document = editor.document val listItem = findListItemForOffset(file, offset, document) if (listItem != null) { val currentLine = document.getLineNumber(offset) val itemContentStartOffset = listItem.obtainContentStartOffset(document, currentLine) if (itemContentStartOffset != null && itemContentStartOffset <= offset) { val prefix = document.charsSequence.subSequence(itemContentStartOffset, offset) return !isValidLinePrefix(file, prefix) } } val prefix = obtainLinePrefix(document, offset) return !isValidLinePrefix(file, prefix) } /** * @param line Document plain line number. * @return Actual item content start offset for [line]. */ private fun MarkdownListItem.obtainContentStartOffset(document: Document, line: Int): Int? { val marker = markerElement ?: return null val markerEndOffset = marker.endOffset val markerLineStartOffset = DocumentUtil.getLineStartOffset(markerEndOffset, document) val contentOffsetInsideLine = markerEndOffset - markerLineStartOffset val lineStartOffset = document.getLineStartOffset(line) return lineStartOffset + contentOffsetInsideLine } /** * Line prefix for valid header should be: * * A blank string - every character should be tab or space * * Shorter than 4 symbols (since 4+ spaces will create code block) */ private fun isValidLinePrefix(file: MarkdownFile, prefix: CharSequence): Boolean { if (prefix.isNotBlank()) { return false } val tabSize = CodeStyle.getFacade(file).tabSize val tabReplacement = " ".repeat(tabSize) val actualPrefix = prefix.toString().replace("\t", tabReplacement) return actualPrefix.length < 4 } private fun obtainLinePrefix(document: Document, offset: Int): CharSequence { val lineStart = DocumentUtil.getLineStartOffset(offset, document) return document.charsSequence.subSequence(lineStart, offset) } private fun PsiElement.walkTreeUp(withSelf: Boolean): Sequence<PsiElement> { return parents(withSelf = true).flatMap { it.siblings(forward = false, withSelf = withSelf) } } private fun findPreviousHeader(file: MarkdownFile, document: Document, offset: Int): MarkdownHeader? { val startElement = findStartElement(file, document, offset) val elements = startElement.walkTreeUp(withSelf = true) return elements.filterIsInstance<MarkdownHeader>().firstOrNull() } private fun findStartElement(file: MarkdownFile, document: Document, offset: Int): PsiElement { val listItemBefore = findListItemForOffset(file, offset, document)?.lastChild return listItemBefore ?: PsiUtilCore.getElementAtOffset(file, offset) } private fun findListItemForOffset(file: MarkdownFile, offset: Int, document: Document): MarkdownListItem? { val item = findPossibleListItemForOffset(file, offset, document) ?: return null val itemLine = document.getLineNumber(item.startOffset) val itemIndent = document.getLineIndentSpaces(itemLine, file) ?: return null val line = document.getLineNumber(offset) val currentIndent = document.getLineIndentSpaces(line, file) ?: return null if (currentIndent.startsWith(itemIndent)) { return item } return null } private fun findPossibleListItemForOffset(file: MarkdownFile, offset: Int, document: Document): MarkdownListItem? { val currentLine = document.getLineNumber(offset) val minPossibleStartLine = (currentLine - 2).coerceAtLeast(0) for (line in (minPossibleStartLine..currentLine).reversed()) { val searchOffset = document.getLineEndOffset(line) val listItem = file.getListItemAt(searchOffset, document) if (listItem != null) { return listItem } } return null } } }
apache-2.0
9be2d31016a59b3e08b23ae152670c12
44.403846
121
0.733305
4.740964
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/main/CredentialAdapter.kt
1
10069
package com.yubico.yubioath.ui.main import android.content.Context import android.graphics.Bitmap import android.graphics.drawable.Drawable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.LinearInterpolator import android.view.animation.Transformation import android.widget.BaseAdapter import com.yubico.yubikitold.application.oath.OathType import com.yubico.yubioath.R import com.yubico.yubioath.client.Code import com.yubico.yubioath.client.Credential import kotlinx.android.synthetic.main.view_credential.view.* import kotlinx.coroutines.* import org.jetbrains.anko.imageBitmap import org.jetbrains.anko.imageResource import kotlin.math.min class CredentialAdapter(private val context: Context, private val actionHandler: ActionHandler, initialCreds: Map<Credential, Code?> = mapOf()) : BaseAdapter() { companion object { private const val CREDENTIAL_STORAGE = "CREDENTIAL_STORAGE" private const val IS_PINNED = "IS_PINNED" private val NUMERIC = Regex("^[0-9]+$") } private val credentialStorage = context.getSharedPreferences(CREDENTIAL_STORAGE, Context.MODE_PRIVATE) private val iconManager = IconManager(context) private val inflater = LayoutInflater.from(context) var creds: Map<Credential, Code?> = initialCreds set(value) { field = value.toSortedMap( compareBy<Credential> { !isPinned(it) } .thenBy { it.key != OathViewModel.NDEF_KEY } .thenBy { it.issuer?.toLowerCase() ?: it.name.toLowerCase() } .thenBy { it.name.toLowerCase() } ) notifyDataSetChanged() GlobalScope.launch(Dispatchers.Main) { notifyNextTimeout(value) } } private var notifyTimeout: Job? = null private fun Code?.valid(): Boolean = this != null && validUntil > System.currentTimeMillis() private fun Code?.canRefresh(): Boolean = this == null || validFrom + 5000 < System.currentTimeMillis() private fun Credential.hasTimer(): Boolean = type == OathType.TOTP && period != 30 private fun Credential.canMask(code: Code?): Boolean = key == OathViewModel.NDEF_KEY && code?.value?.matches(OathViewModel.CODE_PATTERN) == false fun isPinned(credential: Credential): Boolean = credentialStorage.getBoolean("$IS_PINNED/${credential.deviceId}/${credential.key}", false) fun setPinned(credential: Credential, value: Boolean) { credentialStorage.edit().putBoolean("$IS_PINNED/${credential.deviceId}/${credential.key}", value).apply() creds = creds //Force re-sort notifyDataSetChanged() } fun hasIcon(credential: Credential): Boolean = iconManager.hasIcon(credential) fun setIcon(credential: Credential, icon: Bitmap) = iconManager.setIcon(credential, icon) fun setIcon(credential: Credential, icon: Drawable) = iconManager.setIcon(credential, icon) fun removeIcon(credential: Credential) = iconManager.removeIcon(credential) private fun Code?.formatValue(): String = this?.value?.let { if (it.matches(NUMERIC)) { when (it.length) { 8 -> it.slice(0..3) + " " + it.slice(4..7) //1234 5678 7 -> it.slice(0..3) + " " + it.slice(4..6) //1234 567 6 -> it.slice(0..2) + " " + it.slice(3..5) //123 456 else -> it } } else it } ?: context.getString(R.string.press_for_code) private suspend fun notifyNextTimeout(credentials: Map<Credential, Code?>) { val now = System.currentTimeMillis() val nextTimeout = credentials.map { (cred, code) -> if (code != null) when (cred.type) { OathType.TOTP -> code.validUntil OathType.HOTP -> code.validFrom + 5000 // Redraw HOTP codes after 5 seconds as they can be re-calculated. null -> Long.MAX_VALUE } else -1 }.filter { it > now }.min() nextTimeout?.let { notifyTimeout?.cancel() notifyTimeout = GlobalScope.launch(Dispatchers.Main) { delay(it - now) notifyDataSetChanged() notifyNextTimeout(creds) } } } fun getPosition(credential: Credential): Int = creds.keys.indexOf(credential) override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { return (convertView ?: inflater.inflate(R.layout.view_credential, parent, false).apply { (this as ViewGroup).descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS tag = CodeAdapterViewHolder(this) }).apply { val (credential, code) = try { getItem(position) } catch (e: IndexOutOfBoundsException) { return null } with(tag as CodeAdapterViewHolder) { icon.imageBitmap = iconManager.getIcon(credential) issuerView.run { visibility = if (credential.issuer != null) { text = credential.name View.VISIBLE } else View.GONE } pinIcon.visibility = if (isPinned(credential)) View.VISIBLE else View.GONE if (credential.issuer != null) { issuerView.text = credential.issuer issuerView.visibility = View.VISIBLE } else { issuerView.visibility = View.GONE } labelView.text = credential.name icon.setOnClickListener { actionHandler.select(position) } readButton.setOnClickListener { actionHandler.calculate(credential) } copyButton.setOnClickListener { code?.let { actionHandler.copy(it) } } readButton.visibility = if (credential.type == OathType.HOTP && code.canRefresh() || credential.touch && !code.valid()) View.VISIBLE else View.GONE copyButton.visibility = if (code != null) View.VISIBLE else View.GONE fun updateMask(visible: Boolean) { if (visible) { showButton.imageResource = R.drawable.ic_visibility_off_24dp codeView.text = code.formatValue() } else { showButton.imageResource = R.drawable.ic_visibility_24dp codeView.text = "".padEnd(min(code?.value?.length ?: 0, 20), '•') } } if (credential.canMask(code)) { showButton.visibility = View.VISIBLE showButton.setOnClickListener { it.tag = it.tag != true updateMask(it.tag == true) } updateMask(showButton.tag == true) } else { showButton.visibility = View.GONE updateMask(true) } codeView.isEnabled = code.valid() timeoutBar.apply { if (credential.hasTimer()) { visibility = View.VISIBLE if (code != null && code.valid()) { if (animation == null || animation.hasEnded() || timeoutAt != code.validUntil) { val now = System.currentTimeMillis() timeoutAt = code.validUntil startAnimation(timeoutAnimation.apply { duration = code.validUntil - Math.min(now, code.validFrom) startOffset = Math.min(0, code.validFrom - now) setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation?) = Unit override fun onAnimationRepeat(animation: Animation?) = Unit override fun onAnimationEnd(animation: Animation?) { notifyDataSetChanged() } }) }) } } else { clearAnimation() progress = 0 timeoutAt = 0 } } else { clearAnimation() visibility = View.GONE timeoutAt = 0 } } } } } override fun getItem(position: Int): Map.Entry<Credential, Code?> = creds.entries.toList()[position] override fun getItemId(position: Int): Long = position.toLong() override fun getCount(): Int = creds.size private class CodeAdapterViewHolder(view: View) { val icon = view.credential_icon!! val pinIcon = view.pin_icon!! val issuerView = view.issuer!! val labelView = view.label!! val codeView = view.code!! val readButton = view.readButton!! val copyButton = view.copyButton!! val showButton = view.showButton!! val timeoutBar = view.timeoutBar!! val timeoutAnimation = object : Animation() { init { interpolator = LinearInterpolator() } override fun applyTransformation(interpolatedTime: Float, t: Transformation?) { timeoutBar.progress = ((1.0 - interpolatedTime) * 1000).toInt() } } var timeoutAt: Long = 0 } interface ActionHandler { fun select(position: Int) fun calculate(credential: Credential) fun copy(code: Code) } }
bsd-2-clause
222a4b8a008d666331c18427d4196320
42.584416
163
0.557564
5.038539
false
false
false
false
hzsweers/CatchUp
services/github/src/main/kotlin/io/sweers/catchup/service/github/GitHubTrendingParser.kt
1
3441
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.github import io.sweers.catchup.service.github.GitHubApi.Companion.ENDPOINT import io.sweers.catchup.service.github.model.TrendingItem import io.sweers.catchup.util.d import okhttp3.ResponseBody import org.jsoup.Jsoup import org.jsoup.nodes.Element /** * GitHub API does not have /trending endpoints so we have to do gross things :( */ internal object GitHubTrendingParser { private val NUMBER_PATTERN = "\\d+".toRegex() private fun String.removeCommas() = replace(",", "") internal fun parse(body: ResponseBody): List<TrendingItem> { val fullBody = body.string() return Jsoup.parse(fullBody, ENDPOINT) .getElementsByClass("Box-row") .mapNotNull(::parseTrendingItem) .ifEmpty { error("List was empty! Usually this is a sign that parsing failed.") } } private fun parseTrendingItem(element: Element): TrendingItem? { // /creativetimofficial/material-dashboard val authorAndName = element.select("h1 > a") .attr("href") .toString() .removePrefix("/") .trimEnd() .split("/") .let { Pair(it[0], it[1]) } val (author, repoName) = authorAndName val url = "$ENDPOINT/${authorAndName.first}/${authorAndName.second}" val description = element.select("p").text() val language = element.select("[itemprop=\"programmingLanguage\"]").text() // "background-color:#563d7c;" val languageColor = element.select(".repo-language-color") .firstOrNull() ?.attr("style") ?.removePrefix("background-color:") ?.trimStart() // Thanks for the leading space, GitHub ?.let { val colorSubstring = it.removePrefix("#") if (colorSubstring.length == 3) { // Three digit hex, convert to 6 digits for Color.parseColor() "#${colorSubstring.replace(".".toRegex(), "$0$0")}" } else { it } } // "3,441" stars, forks val counts = element.select(".Link--muted.d-inline-block.mr-3") .asSequence() .map(Element::text) .map { it.removeCommas() } .map(String::toInt) .toList() val stars = counts.getOrNull(0) ?: 0 val forks = counts.getOrNull(1) // "691 stars today" val starsToday = element.select(".f6.color-text-secondary.mt-2 > span:last-child") .firstOrNull() ?.text() ?.removeCommas() ?.let { NUMBER_PATTERN.find(it)?.groups?.firstOrNull()?.value?.toInt() ?: run { d { "$authorAndName didn't have today" } null } } ?: 0 return TrendingItem( author = author, url = url, repoName = repoName, description = description, stars = stars, forks = forks, starsToday = starsToday, language = language, languageColor = languageColor ) } }
apache-2.0
1bb02e46c727ca268c50f43afa834c88
30.861111
86
0.639349
4.053004
false
false
false
false
Turbo87/intellij-emberjs
src/main/kotlin/com/emberjs/resolver/EmberModuleReferenceContributor.kt
1
6407
package com.emberjs.resolver import com.emberjs.cli.EmberCliProjectConfigurator import com.emberjs.utils.emberRoot import com.emberjs.utils.isInRepoAddon import com.emberjs.utils.parents import com.intellij.lang.javascript.DialectDetector import com.intellij.lang.javascript.frameworks.amd.JSModuleReference import com.intellij.lang.javascript.frameworks.modules.JSExactFileReference import com.intellij.lang.javascript.psi.resolve.JSModuleReferenceContributor import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet import java.util.regex.Pattern /** * Resolves absolute imports from the ember application root, e.g. * ``` * import FooController from 'my-app/controllers/foo' * ``` * * Navigating to `FooController` will browse to `/app/controllers/foo.js` */ class EmberModuleReferenceContributor : JSModuleReferenceContributor { override fun getCommonJSModuleReferences(unquotedRefText: String, host: PsiElement, offset: Int, provider: PsiReferenceProvider?): Array<out PsiReference> { return emptyArray() } override fun getAllReferences(unquotedRefText: String, host: PsiElement, offset: Int, provider: PsiReferenceProvider?): Array<out PsiReference> { // return early for relative imports if (unquotedRefText.startsWith('.')) { return emptyArray() } // e.g. `my-app/controllers/foo` -> `my-app` val packageName = unquotedRefText.substringBefore('/') // e.g. `my-app/controllers/foo` -> `controllers/foo` val importPath = unquotedRefText.removePrefix("$packageName/") // find root package folder of current file (ignoring package.json in in-repo-addons) val hostPackageRoot = host.containingFile.virtualFile?.parents ?.find { it.findChild("package.json") != null && !it.isInRepoAddon } ?: return emptyArray() val modules = if (getAppName(hostPackageRoot) == packageName) { // local import from this app/addon listOf(hostPackageRoot) + EmberCliProjectConfigurator.inRepoAddons(hostPackageRoot) } else { // check node_modules listOfNotNull(host.emberRoot?.findChild("node_modules")?.findChild(packageName)) } /** Search the `/app` and `/addon` directories of the root and each in-repo-addon */ val roots = modules .flatMap { listOfNotNull(it.findChild("app"), it.findChild("addon"), it.findChild("addon-test-support")) } .map { JSExactFileReference(host, TextRange.create(offset, offset + packageName.length), listOf(it.path), null) } val refs : FileReferenceSet val startInElement = offset + packageName.length + 1 try { refs = object : FileReferenceSet(importPath, host, startInElement, provider, false, true, DialectDetector.JAVASCRIPT_FILE_TYPES_ARRAY) { override fun createFileReference(range: TextRange, index: Int, text: String?): FileReference { return object : JSModuleReference(text, index, range, this, null, true) { override fun innerResolveInContext(referenceText: String, psiFileSystemItem: PsiFileSystemItem, resolveResults: MutableCollection<ResolveResult>, caseSensitive: Boolean) { super.innerResolveInContext(referenceText, psiFileSystemItem, resolveResults, caseSensitive) // don't suggest the current file, e.g. when navigating from /app to /addon resolveResults.removeAll { it.element?.containingFile == host.containingFile } } override fun isAllowFolders() = false } } override fun computeDefaultContexts(): MutableCollection<PsiFileSystemItem> { return roots .flatMap { it.multiResolve(false).asIterable() } .map { it.element } .filterIsInstance(PsiFileSystemItem::class.java) .toMutableList() } } } catch (e: StringIndexOutOfBoundsException) { // TODO: this sometimes happens if startInElement is >= importPath.length but we don't exactly know why. println("Error in EmberModuleReferenceContributor for importPath: \"$importPath\" (starting at $startInElement). " + "This is a known issue and can be ignored. See https://github.com/Turbo87/intellij-emberjs/issues/176") return arrayOf() } return (roots + refs.allReferences).toTypedArray() } override fun isApplicable(host: PsiElement): Boolean = DialectDetector.isES6(host) /** Detect the name of the ember application */ private fun getAppName(appRoot: VirtualFile): String? = getModulePrefix(appRoot) ?: getAddonName(appRoot) private fun getModulePrefix(appRoot: VirtualFile): String? { val env = appRoot.findFileByRelativePath("config/environment.js") ?: return null return env.inputStream.use { stream -> stream.reader().useLines { lines -> lines.mapNotNull { line -> val matcher = ModulePrefixPattern.matcher(line) if (matcher.find()) matcher.group(1) else null }.firstOrNull() } } } /** Captures `my-app` from the string `modulePrefix: 'my-app'` */ private val ModulePrefixPattern = Pattern.compile("modulePrefix:\\s*['\"](.+?)['\"]") private fun getAddonName(appRoot: VirtualFile): String? { val index = appRoot.findFileByRelativePath("index.js") ?: return null return index.inputStream.use { stream -> stream.reader().useLines { lines -> lines.mapNotNull { line -> val matcher = NamePattern.matcher(line) if (matcher.find()) matcher.group(1) else null }.firstOrNull() } } } /** Captures `my-app` from the string `name: 'my-app'` */ private val NamePattern = Pattern.compile("name:\\s*['\"](.+?)['\"]") }
apache-2.0
3d0078d11c1e70de521c0e7cf2ef98b6
47.908397
195
0.645076
4.831825
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/ViewHolders/DateOptionItem.kt
1
948
package io.github.sdsstudios.ScoreKeeper.ViewHolders import android.content.Context import io.github.sdsstudios.ScoreKeeper.R import ir.coderz.ghostadapter.BindItem import ir.coderz.ghostadapter.Binder import java.text.SimpleDateFormat import java.util.* /** * Created by sethsch1 on 24/12/17. */ @BindItem(layout = R.layout.view_holder_text_view_card, holder = TextViewHolder::class) class DateOptionItem( val ctx: Context, private val mHintId: Int ) : BaseViewItem<Date>() { companion object { val DATE_FORMAT = SimpleDateFormat("EE dd MMM y k:mm", Locale.getDefault()) } @Binder fun bind(viewHolder: TextViewHolder) { viewHolder.apply { textViewLabel.text = ctx.getString(mHintId) if (option != null) { val date = option?.get() textView.text = DATE_FORMAT.format(date) } } } override var error = false }
gpl-3.0
901e39f621b7f5fea923a38583528bf3
23.973684
87
0.655063
3.966527
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-auth/jvmAndNix/src/io/ktor/server/auth/AuthenticationContext.kt
1
3975
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.auth import io.ktor.server.application.* import io.ktor.util.* import kotlin.properties.* import kotlin.reflect.* /** * An authentication context for a call. * @param call instance of [ApplicationCall] this context is for. */ public class AuthenticationContext(call: ApplicationCall) { public var call: ApplicationCall = call private set private val _errors = HashMap<Any, AuthenticationFailedCause>() internal val _principal: CombinedPrincipal = CombinedPrincipal() /** * Retrieves an authenticated principal, or returns `null` if a user isn't authenticated. */ @Deprecated("Use accessor methods instead", level = DeprecationLevel.WARNING) public var principal: Principal? get() = _principal.principals.firstOrNull()?.second set(value) { check(value != null) _principal.add(null, value) } /** * Stores authentication failures for keys provided by authentication mechanisms. */ @Suppress("unused") @Deprecated("Use allErrors, allFailures or error() function instead", level = DeprecationLevel.ERROR) public val errors: HashMap<Any, AuthenticationFailedCause> get() = _errors /** * All registered errors during auth procedure (only [AuthenticationFailedCause.Error]). */ public val allErrors: List<AuthenticationFailedCause.Error> get() = _errors.values.filterIsInstance<AuthenticationFailedCause.Error>() /** * All authentication failures during auth procedure including missing or invalid credentials. */ public val allFailures: List<AuthenticationFailedCause> get() = _errors.values.toList() /** * Appends an error to the errors list. Overwrites if already registered for the same [key]. */ public fun error(key: Any, cause: AuthenticationFailedCause) { _errors[key] = cause } /** * Gets an [AuthenticationProcedureChallenge] for this context. */ public val challenge: AuthenticationProcedureChallenge = AuthenticationProcedureChallenge() /** * Sets an authenticated principal for this context. */ public fun principal(principal: Principal) { _principal.add(null, principal) } /** * Sets an authenticated principal for this context from provider with name [provider]. */ public fun principal(provider: String? = null, principal: Principal) { _principal.add(provider, principal) } /** * Retrieves a principal of the type [T] from provider with name [provider], if any. */ public inline fun <reified T : Principal> principal(provider: String? = null): T? { return principal(provider, T::class) } /** * Retrieves a principal of the type [T], if any. */ public fun <T : Principal> principal(provider: String?, klass: KClass<T>): T? { return _principal.get(provider, klass) } /** * Requests a challenge to be sent to the client if none of mechanisms can authenticate a user. */ public fun challenge( key: Any, cause: AuthenticationFailedCause, function: ChallengeFunction ) { error(key, cause) challenge.register.add(cause to function) } public companion object { private val AttributeKey = AttributeKey<AuthenticationContext>("AuthContext") internal fun from(call: ApplicationCall): AuthenticationContext { val existingContext = call.attributes.getOrNull(AttributeKey) if (existingContext != null) { existingContext.call = call return existingContext } val context = AuthenticationContext(call) call.attributes.put(AttributeKey, context) return context } } }
apache-2.0
fc04cfb02c8351119233b632acd9489c
31.581967
119
0.659874
4.771909
false
false
false
false
ktorio/ktor
ktor-server/ktor-server-plugins/ktor-server-request-validation/jvmAndNix/test/io/ktor/server/plugins/requestvalidation/RequestValidationTest.kt
1
4408
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.server.plugins.requestvalidation import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.testing.* import io.ktor.utils.io.* import io.ktor.utils.io.core.* import kotlin.test.* class RequestValidationTest { @Test fun testSimpleValidationByClass() = testApplication { install(RequestValidation) { validate<CharSequence> { if (!it.startsWith("+")) ValidationResult.Invalid(listOf("$it should start with \"+\"")) else ValidationResult.Valid } validate<String> { if (!it.endsWith("!")) ValidationResult.Invalid(listOf("$it should end with \"!\"")) else ValidationResult.Valid } } install(StatusPages) { exception<RequestValidationException> { call, cause -> call.respond(HttpStatusCode.BadRequest, "${cause.value}\n${cause.reasons.joinToString()}") } } routing { get("/text") { val body = call.receive<String>() call.respond(body) } get("/channel") { call.receive<ByteReadChannel>().discard() call.respond("OK") } } client.get("/text") { setBody("1") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.BadRequest, it.status) assertEquals("1\n1 should start with \"+\", 1 should end with \"!\"", body) } client.get("/text") { setBody("+1") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.BadRequest, it.status) assertEquals("+1\n+1 should end with \"!\"", body) } client.get("/text") { setBody("1!") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.BadRequest, it.status) assertEquals("1!\n1! should start with \"+\"", body) } client.get("/text") { setBody("+1!") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.OK, it.status) assertEquals("+1!", body) } client.get("/channel") { setBody("1") }.let { assertEquals(HttpStatusCode.OK, it.status) } } @Test fun testValidatorDsl() = testApplication { install(RequestValidation) { validate { filter { it is ByteArray } validation { check(it is ByteArray) val intValue = String(it).toInt() if (intValue < 0) ValidationResult.Invalid("Value is negative") else ValidationResult.Valid } } } install(StatusPages) { exception<RequestValidationException> { call, cause -> call.respond(HttpStatusCode.BadRequest, "${cause.value}\n${cause.reasons.joinToString()}") } } routing { get("/text") { val body = call.receive<String>() call.respond(body) } get("/array") { val body = call.receive<ByteArray>() call.respond(String(body)) } } client.get("/text") { setBody("1") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.OK, it.status) assertEquals("1", body) } client.get("/array") { setBody("1") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.OK, it.status) assertEquals("1", body) } client.get("/array") { setBody("-1") }.let { val body = it.bodyAsText() assertEquals(HttpStatusCode.BadRequest, it.status) assertTrue(body.endsWith("Value is negative"), body) } } }
apache-2.0
f0d98314741a9fedb8d11b7630a45a99
30.042254
119
0.517241
4.765405
false
true
false
false
ledboot/Toffee
app/src/main/java/com/ledboot/toffee/widget/BottomNavigationViewEx.kt
1
6839
package com.ledboot.toffee.widget import android.content.Context import android.util.AttributeSet import android.util.SparseArray import android.view.MenuItem import android.view.View import androidx.viewpager.widget.ViewPager import com.google.android.material.bottomnavigation.BottomNavigationItemView import com.google.android.material.bottomnavigation.BottomNavigationMenuView import com.google.android.material.bottomnavigation.BottomNavigationView import java.lang.reflect.Field /** * Created by Gwynn on 17/9/21. */ open class BottomNavigationViewEx : BottomNavigationView { var mViewPager: ViewPager? = null var mMenuView: BottomNavigationMenuView? = null var mButtons: Array<BottomNavigationItemView>? = null var mOnNavigationItemSelectedListener: ExOnNavigationItemSelectedListener? = null var mOtherOnNavigationItemSelectedListener: OnNavigationItemSelectedListener? = null var mSmoothScroll: Boolean = false var mItemArray: SparseArray<Int>? = null val mOnPageChangeListener: ExOnPageChangeListener = ExOnPageChangeListener(this) constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { getBottomNavigationMenuView() getBottomNavigationItemViews() } fun setupWithViewPager(viewPage: ViewPager) { setupWithViewPager(viewPage, false) } fun setupWithViewPager(viewPager: ViewPager, smoothScroll: Boolean) { mViewPager = viewPager this.mSmoothScroll = smoothScroll mItemArray = SparseArray() val size: Int = menu.size() for (i in 0 until size) { mItemArray!!.put(menu.getItem(i).itemId, i) } mViewPager!!.addOnPageChangeListener(mOnPageChangeListener) mOnNavigationItemSelectedListener = ExOnNavigationItemSelectedListener(viewPager, this, mOtherOnNavigationItemSelectedListener, smoothScroll) super.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) } fun getOnNavigationItemSelectedListener(): Any? { val field: Field = BottomNavigationViewEx::class.java.superclass.getDeclaredField("selectedListener") field.isAccessible = true val listener = field.get(this) return listener } fun enableShiftMode(enable: Boolean) { val menuView = getBottomNavigationMenuView() val field: Field = menuView::class.java.getDeclaredField("mShiftingMode") field.isAccessible = true field.setBoolean(menuView, enable) menuView.updateMenuView() } fun enableItemShiftMode(enable: Boolean) { val menuView = getBottomNavigationMenuView() var mButtons = getBottomNavigationItemViews() val field: Field = BottomNavigationItemView::class.java.getDeclaredField("mShiftingMode") field.isAccessible = true for (item in mButtons) { field.setBoolean(item, enable) } menuView.updateMenuView() } fun getBottomNavigationMenuView(): BottomNavigationMenuView { if (mMenuView == null) { val field: Field = BottomNavigationViewEx::class.java.superclass.getDeclaredField("menuView") field.isAccessible = true mMenuView = field.get(this) as BottomNavigationMenuView } return mMenuView as BottomNavigationMenuView } fun getBottomNavigationItemViews(): Array<BottomNavigationItemView> { if (mButtons == null) { val menuView = getBottomNavigationMenuView() val field: Field = menuView::class.java.getDeclaredField("buttons") field.isAccessible = true mButtons = field.get(menuView) as Array<BottomNavigationItemView> } return mButtons as Array<BottomNavigationItemView> } fun setCurrentItem(item: Int) { if (item < 0 || item >= maxItemCount) { throw ArrayIndexOutOfBoundsException("item is out of bounds, we expected 0 - " + (maxItemCount - 1) + ". Actually " + item) } val menuView = getBottomNavigationMenuView() val buttons = getBottomNavigationItemViews() val field: Field = menuView::class.java.getDeclaredField("onClickListener") field.isAccessible = true val onClickListener: View.OnClickListener = field.get(menuView) as View.OnClickListener onClickListener.onClick(buttons[item]) } fun getMenuItemPosition(item: MenuItem): Int { /*val itemId: Int = item.itemId val size: Int = menu.size() for (i in 0 until size) { if (menu.getItem(i).itemId == itemId) return i } return -1*/ return mItemArray!!.get(item.itemId) } override fun setOnNavigationItemSelectedListener(listener: OnNavigationItemSelectedListener?) { mOtherOnNavigationItemSelectedListener = listener } class ExOnPageChangeListener : ViewPager.OnPageChangeListener { private var bottomNavigation: BottomNavigationViewEx? = null constructor(bottomNavigation: BottomNavigationViewEx) { this.bottomNavigation = bottomNavigation } override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { bottomNavigation!!.setCurrentItem(position) } } class ExOnNavigationItemSelectedListener(viewPage: ViewPager, navigationView: BottomNavigationViewEx, listener: Any?, smoothScroll: Boolean) : BottomNavigationView.OnNavigationItemSelectedListener { var mViewPage: ViewPager = viewPage var mListener: Any? = listener var mSmoothScroll: Boolean = smoothScroll var mPrevioutsPosition: Int = -1 var mNavigationView: BottomNavigationViewEx = navigationView override fun onNavigationItemSelected(item: MenuItem): Boolean { val position: Int = mNavigationView.getMenuItemPosition(item) if (mPrevioutsPosition == position) { return true } if (null != mListener) { val selected: Boolean = (mListener as OnNavigationItemSelectedListener).onNavigationItemSelected(item) if (!selected) return false } mViewPage.setCurrentItem(position, mSmoothScroll) mPrevioutsPosition = position return true } fun setOnNavigationItemSelectedListener(listener: OnNavigationItemSelectedListener) { this.mListener = listener } } }
apache-2.0
f48068e3f423c8294c1c14a23b507c15
35.190476
149
0.690306
5.372349
false
false
false
false
ktorio/ktor
ktor-http/common/src/io/ktor/http/FileContentType.kt
1
2585
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http import io.ktor.util.* import io.ktor.utils.io.charsets.* /** * Default [ContentType] for [extension] */ public fun ContentType.Companion.defaultForFileExtension(extension: String): ContentType = ContentType.fromFileExtension(extension).selectDefault() /** * Default [ContentType] for file [path] */ public fun ContentType.Companion.defaultForFilePath(path: String): ContentType = ContentType.fromFilePath(path).selectDefault() /** * Recommended content types by file [path] */ public fun ContentType.Companion.fromFilePath(path: String): List<ContentType> { val slashIndex = path.lastIndexOfAny("/\\".toCharArray()) val index = path.indexOf('.', startIndex = slashIndex + 1) if (index == -1) { return emptyList() } return fromFileExtension(path.substring(index + 1)) } /** * Recommended content type by file name extension */ public fun ContentType.Companion.fromFileExtension(ext: String): List<ContentType> { var current = ext.removePrefix(".").toLowerCasePreservingASCIIRules() while (current.isNotEmpty()) { val type = contentTypesByExtensions[current] if (type != null) { return type } current = current.substringAfter(".", "") } return emptyList() } /** * Recommended file name extensions for this content type */ public fun ContentType.fileExtensions(): List<String> = extensionsByContentType[this] ?: extensionsByContentType[this.withoutParameters()] ?: emptyList() private val contentTypesByExtensions: Map<String, List<ContentType>> by lazy { caseInsensitiveMap<List<ContentType>>().apply { putAll(mimes.asSequence().groupByPairs()) } } private val extensionsByContentType: Map<ContentType, List<String>> by lazy { mimes.asSequence().map { (first, second) -> second to first }.groupByPairs() } internal fun List<ContentType>.selectDefault(): ContentType { val contentType = firstOrNull() ?: ContentType.Application.OctetStream return when { contentType.contentType == "text" && contentType.charset() == null -> contentType.withCharset(Charsets.UTF_8) else -> contentType } } internal fun <A, B> Sequence<Pair<A, B>>.groupByPairs() = groupBy { it.first } .mapValues { e -> e.value.map { it.second } } internal fun String.toContentType() = try { ContentType.parse(this) } catch (e: Throwable) { throw IllegalArgumentException("Failed to parse $this", e) }
apache-2.0
5973a7b9fe15281db26a7d22d1f4938d
31.3125
118
0.702901
4.189627
false
false
false
false
jonathanlermitage/tikione-c2e
src/main/kotlin/fr/tikione/c2e/core/service/web/scrap/CPCReaderServiceImpl.kt
1
6052
package fr.tikione.c2e.core.service.web.scrap import com.github.salomonbrys.kodein.instance import fr.tikione.c2e.core.Tools import fr.tikione.c2e.core.coreKodein import fr.tikione.c2e.core.model.web.* import fr.tikione.c2e.core.service.web.AbstractReader import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.* import java.util.concurrent.TimeUnit class CPCReaderServiceImpl : AbstractReader(), CPCReaderService { private val log: Logger = LoggerFactory.getLogger(this.javaClass) private val cpcScraperService: CPCScraperService = coreKodein.instance() override fun listDownloadableMagazines(auth: Auth): ArrayList<String> { val doc = Jsoup.connect(CPC_BASE_URL) .cookies(auth.cookies) .userAgent(AbstractReader.UA) .get() val archives = doc.getElementsByClass("archive") val magNumers = ArrayList<String>() archives.forEach { element -> magNumers.add(element.getElementsByTag("a").attr("href").substring("/numero/".length)) } try { magNumers.add(Integer.toString(Integer.parseInt(magNumers[0]) + 1)) } catch (e: Exception) { log.debug("erreur lors du listing des numeros disponibles ('{}' n'est pas un nombre entier)", magNumers[0]) } magNumers.sortDescending() return magNumers } override fun extractAuthorsPicture(doc: Document): Map<String, AuthorPicture> { val authorsAndPic = HashMap<String, AuthorPicture>() try { doc.getElementsByClass("lequipe")[0].getElementsByTag("td").forEach { elt -> val realName: String = text(elt.getElementsByTag("h3"))!! if (realName.isNotEmpty() && !authorsAndPic.containsKey(realName.toUpperCase())) { val picture = Tools.readRemoteToBase64(CPC_BASE_URL + elt.getElementsByTag("img").attr("src")) authorsAndPic.put(realName.toUpperCase(), AuthorPicture(realName, picture)) // Some authors have different names in About-page and articles: register both if (realName.equals("Louis-Ferdinand Sébum", true)) { authorsAndPic.put("L-F. Sébum".toUpperCase(), AuthorPicture(realName, picture)) } } } } catch (e: Exception) { log.warn("impossible de recuperer les pictos des redacteurs, poursuite du telechargement", e) } return authorsAndPic } override fun downloadMagazine(auth: Auth, number: String): Magazine { log.info("telechargement du numero {}...", number) val doc = queryUrl(auth, CPC_MAG_NUMBER_BASE_URL.replace("_NUM_", number)) val mag = Magazine() mag.number = number mag.title = doc.getElementById("numero-titre").text() mag.login = auth.login mag.edito = extractEdito(doc) mag.toc = extractToc(auth, doc) // Décision de la rédac CanardCPC : ne pas intégrer ed picto du site CanardPC mag.authorsPicture = Collections.emptyMap() //extractAuthorsPicture(queryUrl(auth, CPC_AUTHORS_URL)) return mag } private fun extractEdito(doc: Document): Edito { val edito = Edito() val container = doc.getElementById("block-edito-content") edito.authorAndDate = container.getElementById("numero-auteur-date").text() edito.title = container.getElementById("numero-titre").text() edito.content = container.getElementById("numero-edito").text() edito.coverUrl = doc.getElementById("numero-couverture")?.attr("src") if (edito.coverUrl != null) { edito.coverUrl = CPC_BASE_URL + edito.coverUrl } return edito } private fun extractToc(auth: Auth, doc: Document): ArrayList<TocCategory> { val container = doc.getElementById("block-numerosommaire") val columns = container.getElementsByClass("columns") val tocCategories = columns.mapTo(ArrayList()) { buildTocItem(auth, it) } // Fix https://github.com/jonathanlermitage/tikione-c2e/issues/27 val fixedTocCategories = ArrayList<TocCategory>() for (tocCategory in tocCategories) { if (tocCategory.title.isNullOrEmpty() && !fixedTocCategories.isEmpty()) { fixedTocCategories.get(fixedTocCategories.size - 1).items.addAll(tocCategory.items) } else { fixedTocCategories.add(tocCategory) } } return fixedTocCategories } private fun buildTocItem(auth: Auth, elt: Element): TocCategory { val tocCategory = TocCategory() val titleElt = elt.getElementsByTag("h3") if (titleElt.size == 0) { // Fix https://github.com/jonathanlermitage/tikione-c2e/issues/27 // La ToC du numéro 374 est mal formée : la div "Tests brefs" ne contient pas tous les éléments de la rubrique tocCategory.title = "" } else { val title = clean(elt.getElementsByTag("h3")[0].text()) tocCategory.title = title } elt.getElementsByTag("article").forEach { sheet -> tocCategory.items.add(TocItem( sheet.text(), CPC_BASE_URL + attr(sheet.getElementsByTag("a"), "href"), extractArticles(auth, CPC_BASE_URL + attr(sheet.getElementsByTag("a"), "href")))) } return tocCategory } private fun extractArticles(auth: Auth, url: String): List<Article>? { log.info("recuperation de l'article {}", url) TimeUnit.MILLISECONDS.sleep(500) // be nice with CanardPC website val doc = queryUrl(auth, url) val articles = cpcScraperService.extractBestArticles(doc) if (Tools.debug) { articles.forEach { article -> log.debug(article.toString()) } } return articles } }
mit
7d6e465f0c23a34b6ca5d8b317045b28
42.164286
122
0.633295
3.970434
false
false
false
false
mdanielwork/intellij-community
platform/platform-tests/testSrc/org/jetbrains/concurrency/AsyncPromiseTest.kt
1
5147
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.concurrency import com.intellij.concurrency.JobScheduler import com.intellij.testFramework.assertConcurrent import com.intellij.testFramework.assertConcurrentPromises import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicInteger import kotlin.test.fail class AsyncPromiseTest { @Test fun done() { doHandlerTest(false) } @Test fun cancel() { val promise = AsyncPromise<Boolean>() assertThat(promise.isCancelled).isFalse() assertThat(promise.cancel(true)).isTrue() assertThat(promise.isCancelled).isTrue() assertThat(promise.cancel(true)).isFalse() assertThat(promise.isCancelled).isTrue() assertThat(promise.blockingGet(1)).isNull() } @Test fun rejected() { doHandlerTest(true) } @Test fun state() { val promise = AsyncPromise<String>() val count = AtomicInteger() val log = StringBuffer() class Incrementer(val descr:String) : ()->Promise<String> { override fun toString(): String { return descr } override fun invoke(): Promise<String> { return promise.onSuccess { count.incrementAndGet(); log.append("\n" + this + " " + System.identityHashCode(this)) } } } val setResulter: () -> Promise<String> = { promise.setResult("test") promise } val numThreads = 30 val array = Array(numThreads) { if ((it and 1) == 0) Incrementer("handler $it") else setResulter } assertConcurrentPromises(*array) if (count.get() != (numThreads / 2)) { fail("count: "+count +" "+ log.toString()+"\n---Array:\n"+ Arrays.toString(array)) } assertThat(count.get()).isEqualTo(numThreads / 2) assertThat(promise.get()).isEqualTo("test") Incrementer("extra").invoke() assertThat(count.get()).isEqualTo((numThreads / 2) + 1) } @Test fun blockingGet() { val promise = AsyncPromise<String>() assertConcurrent( { assertThat(promise.blockingGet(1000)).isEqualTo("test") }, { Thread.sleep(100) promise.setResult("test") }) } @Test fun `get from Future`() { val promise = AsyncPromise<String>() assertConcurrent( { assertThat(promise.get(1000, TimeUnit.MILLISECONDS)).isEqualTo("test") }, { Thread.sleep(100) promise.setResult("test") }) } @Test fun `ignore errors`() { val a = resolvedPromise("foo") val b = rejectedPromise<String>() assertThat(listOf(a, b).collectResults(ignoreErrors = true).blockingGet(100, TimeUnit.MILLISECONDS)).containsExactly("foo") } @Test fun blockingGet2() { val promise = AsyncPromise<String>() assertThatThrownBy { promise.blockingGet(10) }.isInstanceOf(TimeoutException::class.java) } private fun doHandlerTest(reject: Boolean) { val promise = AsyncPromise<String>() val count = AtomicInteger() val r = { if (reject) { promise.onError { count.incrementAndGet() } } else { promise.onSuccess { count.incrementAndGet() } } } val numThreads = 30 assertConcurrent(*Array(numThreads) { r }) if (reject) { promise.setError("test") } else { promise.setResult("test") } assertThat(count.get()).isEqualTo(numThreads) if (!reject) { assertThat(promise.get()).isEqualTo("test") } assertThat(promise.isDone).isTrue() assertThat(promise.isCancelled).isFalse() r() assertThat(count.get()).isEqualTo(numThreads + 1) } @Test fun collectResultsMustReturnArrayWithTheSameOrder() { val promise0 = AsyncPromise<String>() val promise1 = AsyncPromise<String>() val f0 = JobScheduler.getScheduler().schedule({ promise0.setResult("0") }, 1, TimeUnit.SECONDS) val f1 = JobScheduler.getScheduler().schedule({ promise1.setResult("1") }, 1, TimeUnit.MILLISECONDS) val list = listOf(promise0, promise1) val results = list.collectResults() val l = results.blockingGet(1, TimeUnit.MINUTES) assertThat(l).containsExactly("0", "1") f0.get() f1.get() } @Test fun `collectResultsMustReturnArrayWithTheSameOrder - ignore errors`() { val promiseList = listOf<AsyncPromise<String>>(AsyncPromise(), AsyncPromise(), AsyncPromise()) val toExecute = listOf( JobScheduler.getScheduler().schedule({ promiseList[0].setResult("0") }, 5, TimeUnit.MILLISECONDS), JobScheduler.getScheduler().schedule({ promiseList[1].setError("boo") }, 1, TimeUnit.MILLISECONDS), JobScheduler.getScheduler().schedule({ promiseList[2].setResult("1") }, 2, TimeUnit.MILLISECONDS) ) val results = promiseList.collectResults(ignoreErrors = true) val l = results.blockingGet(15, TimeUnit.SECONDS) assertThat(l).containsExactly("0", "1") toExecute.forEach { it.get() } } }
apache-2.0
521d0d3e384d9a4de16f76565c477fe2
29.105263
140
0.670682
4.243199
false
true
false
false
dahlstrom-g/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IdeaResolverForProject.kt
2
12255
// 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.caches.resolve import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.ModificationTracker import org.jetbrains.kotlin.analyzer.* import org.jetbrains.kotlin.analyzer.common.CommonAnalysisParameters import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.caches.resolve.* import org.jetbrains.kotlin.context.ProjectContext import org.jetbrains.kotlin.context.withModule import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl import org.jetbrains.kotlin.idea.base.projectStructure.* import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.CompositeAnalyzerServices import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.idea.compiler.IdeSealedClassInheritorsProvider import org.jetbrains.kotlin.idea.project.IdeaEnvironment import org.jetbrains.kotlin.load.java.structure.JavaClass import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.platform.idePlatformKind import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.RESOLUTION_ANCHOR_PROVIDER_CAPABILITY import org.jetbrains.kotlin.resolve.ResolutionAnchorProvider import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters import org.jetbrains.kotlin.types.TypeRefinement import org.jetbrains.kotlin.types.checker.REFINER_CAPABILITY import org.jetbrains.kotlin.types.checker.Ref import org.jetbrains.kotlin.types.checker.TypeRefinementSupport class IdeaResolverForProject( debugName: String, projectContext: ProjectContext, modules: Collection<IdeaModuleInfo>, private val syntheticFilesByModule: Map<IdeaModuleInfo, Collection<KtFile>>, delegateResolver: ResolverForProject<IdeaModuleInfo>, fallbackModificationTracker: ModificationTracker? = null, // Note that 'projectContext.project.useCompositeAnalysis == true' doesn't necessarily imply // that 'settings is CompositeAnalysisSettings'. We create "old" settings for some exceptional // cases sometimes even when CompositeMode is enabled, see KotlinCacheService.getResolutionFacadeWithForcedPlatform private val settings: PlatformAnalysisSettings ) : AbstractResolverForProject<IdeaModuleInfo>( debugName, projectContext, modules, fallbackModificationTracker, delegateResolver, projectContext.project.service<IdePackageOracleFactory>(), ) { companion object { val PLATFORM_ANALYSIS_SETTINGS = ModuleCapability<PlatformAnalysisSettings>("PlatformAnalysisSettings") } private val resolutionAnchorProvider = projectContext.project.service<ResolutionAnchorProvider>() private val invalidModuleNotifier: InvalidModuleNotifier = object: InvalidModuleNotifier { override fun notifyModuleInvalidated(moduleDescriptor: ModuleDescriptor) { throw ProcessCanceledException(InvalidModuleException("Accessing invalid module descriptor $moduleDescriptor")) } } private val constantSdkDependencyIfAny: SdkInfo? = if (settings is PlatformAnalysisSettingsImpl) settings.sdk?.let { SdkInfo(projectContext.project, it) } else null private val builtInsCache: BuiltInsCache = (delegateResolver as? IdeaResolverForProject)?.builtInsCache ?: BuiltInsCache(projectContext, this) @OptIn(TypeRefinement::class) private fun getRefinerCapability(): Pair<ModuleCapability<Ref<TypeRefinementSupport>>, Ref<TypeRefinementSupport>> { val isCompositeAnalysisEnabled = settings is CompositeAnalysisSettings val typeRefinementSupport = if (isCompositeAnalysisEnabled) { /* * Will be properly initialized with a type refiner created by DI container of ResolverForModule. * Placeholder is necessary to distinguish state in cases when resolver for module is not created at all. * For instance, platform targets with no sources in project. */ TypeRefinementSupport.EnabledUninitialized } else { TypeRefinementSupport.Disabled } return REFINER_CAPABILITY to Ref(typeRefinementSupport) } override fun getAdditionalCapabilities(): Map<ModuleCapability<*>, Any?> { return super.getAdditionalCapabilities() + getRefinerCapability() + (PLATFORM_ANALYSIS_SETTINGS to settings) + (RESOLUTION_ANCHOR_PROVIDER_CAPABILITY to resolutionAnchorProvider) + (INVALID_MODULE_NOTIFIER_CAPABILITY to invalidModuleNotifier) } override fun sdkDependency(module: IdeaModuleInfo): SdkInfo? { if (settings is CompositeAnalysisSettings) { require(constantSdkDependencyIfAny == null) { "Shouldn't pass SDK dependency manually for composite analysis mode" } } return constantSdkDependencyIfAny ?: module.findSdkAcrossDependencies() } override fun modulesContent(module: IdeaModuleInfo): ModuleContent<IdeaModuleInfo> = ModuleContent(module, syntheticFilesByModule[module] ?: emptyList(), module.moduleContentScope) override fun builtInsForModule(module: IdeaModuleInfo): KotlinBuiltIns = builtInsCache.getOrCreateIfNeeded(module) override fun createResolverForModule(descriptor: ModuleDescriptor, moduleInfo: IdeaModuleInfo): ResolverForModule { val moduleContent = ModuleContent(moduleInfo, syntheticFilesByModule[moduleInfo] ?: listOf(), moduleInfo.moduleContentScope) val languageVersionSettings = IDELanguageSettingsProvider.getLanguageVersionSettings(moduleInfo, projectContext.project) val resolverForModuleFactory = getResolverForModuleFactory(moduleInfo) return resolverForModuleFactory.createResolverForModule( descriptor as ModuleDescriptorImpl, projectContext.withModule(descriptor), moduleContent, this, languageVersionSettings, sealedInheritorsProvider = IdeSealedClassInheritorsProvider ) } private fun getResolverForModuleFactory(moduleInfo: IdeaModuleInfo): ResolverForModuleFactory { val platform = moduleInfo.platform val jvmPlatformParameters = JvmPlatformParameters( packagePartProviderFactory = { IDEPackagePartProvider(it.moduleContentScope) }, moduleByJavaClass = { javaClass: JavaClass -> val psiClass = (javaClass as JavaClassImpl).psi psiClass.getPlatformModuleInfo(JvmPlatforms.unspecifiedJvmPlatform)?.platformModule ?: psiClass.moduleInfoOrNull }, resolverForReferencedModule = { targetModuleInfo, referencingModuleInfo -> require(targetModuleInfo is IdeaModuleInfo && referencingModuleInfo is IdeaModuleInfo) { "Unexpected modules passed through JvmPlatformParameters to IDE resolver ($targetModuleInfo, $referencingModuleInfo)" } tryGetResolverForModuleWithResolutionAnchorFallback(targetModuleInfo, referencingModuleInfo) }, useBuiltinsProviderForModule = { IdeBuiltInsLoadingState.isFromDependenciesForJvm && it is LibraryInfo && it.isKotlinStdlib(projectContext.project) } ) val commonPlatformParameters = CommonAnalysisParameters( metadataPartProviderFactory = { IDEPackagePartProvider(it.moduleContentScope) } ) return if (settings !is CompositeAnalysisSettings) { val parameters = when { platform.isJvm() -> jvmPlatformParameters platform.isCommon() -> commonPlatformParameters else -> PlatformAnalysisParameters.Empty } platform.idePlatformKind.resolution.createResolverForModuleFactory(parameters, IdeaEnvironment, platform) } else { CompositeResolverForModuleFactory( commonPlatformParameters, jvmPlatformParameters, platform, CompositeAnalyzerServices(platform.componentPlatforms.map { it.findAnalyzerServices() }) ) } } // Important: ProjectContext must be from SDK to be sure that we won't run into deadlocks class BuiltInsCache(private val projectContextFromSdkResolver: ProjectContext, private val resolverForSdk: IdeaResolverForProject) { private val cache = mutableMapOf<BuiltInsCacheKey, KotlinBuiltIns>() fun getOrCreateIfNeeded(module: IdeaModuleInfo): KotlinBuiltIns = projectContextFromSdkResolver.storageManager.compute { ProgressManager.checkCanceled() val sdk = resolverForSdk.sdkDependency(module) val stdlib = findStdlibForModulesBuiltins(module) val key = module.platform.idePlatformKind.resolution.getKeyForBuiltIns(module, sdk, stdlib) val cachedBuiltIns = cache[key] if (cachedBuiltIns != null) return@compute cachedBuiltIns module.platform.idePlatformKind.resolution .createBuiltIns(module, projectContextFromSdkResolver, resolverForSdk, sdk, stdlib) .also { // TODO: MemoizedFunction should be used here instead, but for proper we also need a module (for LV settings) that is not contained in the key cache[key] = it } } private fun findStdlibForModulesBuiltins(module: IdeaModuleInfo): LibraryInfo? { return when (IdeBuiltInsLoadingState.state) { IdeBuiltInsLoadingState.IdeBuiltInsLoading.FROM_CLASSLOADER -> null IdeBuiltInsLoadingState.IdeBuiltInsLoading.FROM_DEPENDENCIES_JVM -> { if (module.platform.isJvm()) { module.findJvmStdlibAcrossDependencies() } else { null } } } } } private fun tryGetResolverForModuleWithResolutionAnchorFallback( targetModuleInfo: IdeaModuleInfo, referencingModuleInfo: IdeaModuleInfo, ): ResolverForModule? { tryGetResolverForModule(targetModuleInfo)?.let { return it } return getResolverForProjectUsingResolutionAnchor(targetModuleInfo, referencingModuleInfo) } private fun getResolverForProjectUsingResolutionAnchor( targetModuleInfo: IdeaModuleInfo, referencingModuleInfo: IdeaModuleInfo ): ResolverForModule? { val moduleDescriptorOfReferencingModule = descriptorByModule[referencingModuleInfo]?.moduleDescriptor ?: error("$referencingModuleInfo is not contained in this resolver, which means incorrect use of anchor-aware search") val anchorModuleInfo = resolutionAnchorProvider.getResolutionAnchor(moduleDescriptorOfReferencingModule)?.moduleInfo ?: return null val resolverForProjectFromAnchorModule = KotlinCacheService.getInstance(projectContext.project) .getResolutionFacadeByModuleInfo(anchorModuleInfo, anchorModuleInfo.platform) ?.getResolverForProject() ?: return null require(resolverForProjectFromAnchorModule is IdeaResolverForProject) { "Resolution via anchor modules is expected to be used only from IDE resolvers" } return resolverForProjectFromAnchorModule.tryGetResolverForModule(targetModuleInfo) } } interface BuiltInsCacheKey { object DefaultBuiltInsKey : BuiltInsCacheKey }
apache-2.0
65978286dd75259ba9aea2b878c5f6aa
49.020408
162
0.738474
5.734675
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/j2k/new/tests/testData/newJ2k/overloads/Annotations.kt
13
562
internal class A { @JvmOverloads fun foo(s: String? = null): Any { println("s = $s") return "" } fun bar(s: String?): Any? { println("s = $s") return if (s == null) "" else null } fun bar(): Any { return bar(null)!! } fun bar1(s: String?): Any? { println("s = $s") return if (s == null) "" else null } fun bar1(): Any { return bar1(null)!! } @Deprecated("") fun f() { f(1) } fun f(p: Int) { println("p = $p") } }
apache-2.0
ecdc9cd6207d42c13b81878fabdbc290
15.558824
42
0.414591
3.406061
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/DestructureIntention.kt
2
19236
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.base.psi.copied import org.jetbrains.kotlin.idea.core.isVisible import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.addRemoveModifier.setModifierList import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns class DestructureInspection : IntentionBasedInspection<KtDeclaration>( DestructureIntention::class, { element, _ -> val usagesToRemove = DestructureIntention.collectUsagesToRemove(element)?.data if (element is KtParameter) { usagesToRemove != null && (usagesToRemove.any { it.declarationToDrop is KtDestructuringDeclaration } || usagesToRemove.filter { it.usagesToReplace.isNotEmpty() }.size > usagesToRemove.size / 2) } else { usagesToRemove?.any { it.declarationToDrop is KtDestructuringDeclaration } ?: false } } ) class DestructureIntention : SelfTargetingRangeIntention<KtDeclaration>( KtDeclaration::class.java, KotlinBundle.lazyMessage("use.destructuring.declaration") ) { override fun applyTo(element: KtDeclaration, editor: Editor?) { val (usagesToRemove, removeSelectorInLoopRange) = collectUsagesToRemove(element) ?: return val factory = KtPsiFactory(element) val parent = element.parent val (container, anchor) = if (parent is KtParameterList) parent.parent to null else parent to element val validator = Fe10KotlinNewDeclarationNameValidator( container = container, anchor = anchor, target = KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE, excludedDeclarations = usagesToRemove.map { (it.declarationToDrop as? KtDestructuringDeclaration)?.entries ?: listOfNotNull(it.declarationToDrop) }.flatten() ) val names = ArrayList<String>() val underscoreSupported = element.languageVersionSettings.supportsFeature(LanguageFeature.SingleUnderscoreForParameterName) // For all unused we generate normal names, not underscores val allUnused = usagesToRemove.all { (_, usagesToReplace, variableToDrop) -> usagesToReplace.isEmpty() && variableToDrop == null } usagesToRemove.forEach { (descriptor, usagesToReplace, variableToDrop, name) -> val suggestedName = if (usagesToReplace.isEmpty() && variableToDrop == null && underscoreSupported && !allUnused) { "_" } else { Fe10KotlinNameSuggester.suggestNameByName(name ?: descriptor.name.asString(), validator) } runWriteActionIfPhysical(element) { variableToDrop?.delete() usagesToReplace.forEach { it.replace(factory.createExpression(suggestedName)) } } names.add(suggestedName) } val joinedNames = names.joinToString() when (element) { is KtParameter -> { val loopRange = (element.parent as? KtForExpression)?.loopRange runWriteActionIfPhysical(element) { val type = element.typeReference?.let { ": ${it.text}" } ?: "" element.replace(factory.createDestructuringParameter("($joinedNames)$type")) if (removeSelectorInLoopRange && loopRange is KtDotQualifiedExpression) { loopRange.replace(loopRange.receiverExpression) } } } is KtFunctionLiteral -> { val lambda = element.parent as KtLambdaExpression SpecifyExplicitLambdaSignatureIntention().applyTo(lambda, editor) runWriteActionIfPhysical(element) { lambda.functionLiteral.valueParameters.singleOrNull()?.replace( factory.createDestructuringParameter("($joinedNames)") ) } } is KtVariableDeclaration -> { val rangeAfterEq = PsiChildRange(element.initializer, element.lastChild) val modifierList = element.modifierList?.copied() runWriteActionIfPhysical(element) { val result = element.replace( factory.createDestructuringDeclarationByPattern( "val ($joinedNames) = $0", rangeAfterEq ) ) as KtModifierListOwner if (modifierList != null) { result.setModifierList(modifierList) } } } } } override fun applicabilityRange(element: KtDeclaration): TextRange? { if (!element.isSuitableDeclaration()) return null val usagesToRemove = collectUsagesToRemove(element)?.data ?: return null if (usagesToRemove.isEmpty()) return null return when (element) { is KtFunctionLiteral -> element.lBrace.textRange is KtNamedDeclaration -> element.nameIdentifier?.textRange else -> null } } companion object { internal fun KtDeclaration.isSuitableDeclaration() = getUsageScopeElement() != null private fun KtDeclaration.getUsageScopeElement(): PsiElement? { val lambdaSupported = languageVersionSettings.supportsFeature(LanguageFeature.DestructuringLambdaParameters) return when (this) { is KtParameter -> { val parent = parent when { parent is KtForExpression -> parent parent.parent is KtFunctionLiteral -> if (lambdaSupported) parent.parent else null else -> null } } is KtProperty -> parent.takeIf { isLocal } is KtFunctionLiteral -> if (!hasParameterSpecification() && lambdaSupported) this else null else -> null } } internal data class UsagesToRemove(val data: List<UsageData>, val removeSelectorInLoopRange: Boolean) internal fun collectUsagesToRemove(declaration: KtDeclaration): UsagesToRemove? { val context = declaration.safeAnalyzeNonSourceRootCode() val variableDescriptor = when (declaration) { is KtParameter -> context.get(BindingContext.VALUE_PARAMETER, declaration) is KtFunctionLiteral -> context.get(BindingContext.FUNCTION, declaration)?.valueParameters?.singleOrNull() is KtVariableDeclaration -> context.get(BindingContext.VARIABLE, declaration) else -> null } ?: return null val variableType = variableDescriptor.type if (variableType.isMarkedNullable) return null val classDescriptor = variableType.constructor.declarationDescriptor as? ClassDescriptor ?: return null val mapEntryClassDescriptor = classDescriptor.builtIns.mapEntry val usageScopeElement = declaration.getUsageScopeElement() ?: return null val nameToSearch = when (declaration) { is KtParameter -> declaration.nameAsName is KtVariableDeclaration -> declaration.nameAsName else -> Name.identifier("it") } ?: return null // Note: list should contains properties in order to create destructuring declaration val usagesToRemove = mutableListOf<UsageData>() var noBadUsages = true var removeSelectorInLoopRange = false when { DescriptorUtils.isSubclass(classDescriptor, mapEntryClassDescriptor) -> { val forLoop = declaration.parent as? KtForExpression if (forLoop != null) { val loopRangeDescriptor = forLoop.loopRange.getResolvedCall(context)?.resultingDescriptor if (loopRangeDescriptor != null) { val loopRangeDescriptorOwner = loopRangeDescriptor.containingDeclaration val mapClassDescriptor = classDescriptor.builtIns.map if (loopRangeDescriptorOwner is ClassDescriptor && DescriptorUtils.isSubclass(loopRangeDescriptorOwner, mapClassDescriptor) ) { removeSelectorInLoopRange = loopRangeDescriptor.name.asString().let { it == "entries" || it == "entrySet" } } } } listOf("key", "value").mapTo(usagesToRemove) { UsageData( descriptor = mapEntryClassDescriptor.unsubstitutedMemberScope.getContributedVariables( Name.identifier(it), NoLookupLocation.FROM_BUILTINS ).single() ) } usageScopeElement.iterateOverMapEntryPropertiesUsages( context, nameToSearch, variableDescriptor, { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, { noBadUsages = false } ) } classDescriptor.isData -> { val valueParameters = classDescriptor.unsubstitutedPrimaryConstructor?.valueParameters ?: return null valueParameters.mapTo(usagesToRemove) { UsageData(descriptor = it) } val constructorParameterNameMap = mutableMapOf<Name, ValueParameterDescriptor>() valueParameters.forEach { constructorParameterNameMap[it.name] = it } usageScopeElement.iterateOverDataClassPropertiesUsagesWithIndex( context, nameToSearch, variableDescriptor, constructorParameterNameMap, { index, usageData -> noBadUsages = usagesToRemove[index].add(usageData, index) && noBadUsages }, { noBadUsages = false } ) } else -> return null } if (!noBadUsages) return null val droppedLastUnused = usagesToRemove.dropLastWhile { it.usagesToReplace.isEmpty() && it.declarationToDrop == null } return if (droppedLastUnused.isEmpty()) { UsagesToRemove(usagesToRemove, removeSelectorInLoopRange) } else { UsagesToRemove(droppedLastUnused, removeSelectorInLoopRange) } } private fun PsiElement.iterateOverMapEntryPropertiesUsages( context: BindingContext, parameterName: Name, variableDescriptor: VariableDescriptor, process: (Int, SingleUsageData) -> Unit, cancel: () -> Unit ) { anyDescendantOfType<KtNameReferenceExpression> { when { it.getReferencedNameAsName() != parameterName -> false it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false else -> { val applicableUsage = getDataIfUsageIsApplicable(it, context) if (applicableUsage != null) { val usageDescriptor = applicableUsage.descriptor if (usageDescriptor == null) { process(0, applicableUsage) process(1, applicableUsage) return@anyDescendantOfType false } when (usageDescriptor.name.asString()) { "key", "getKey" -> { process(0, applicableUsage) return@anyDescendantOfType false } "value", "getValue" -> { process(1, applicableUsage) return@anyDescendantOfType false } } } cancel() true } } } } private fun PsiElement.iterateOverDataClassPropertiesUsagesWithIndex( context: BindingContext, parameterName: Name, variableDescriptor: VariableDescriptor, constructorParameterNameMap: Map<Name, ValueParameterDescriptor>, process: (Int, SingleUsageData) -> Unit, cancel: () -> Unit ) { anyDescendantOfType<KtNameReferenceExpression> { when { it.getReferencedNameAsName() != parameterName -> false it.getResolvedCall(context)?.resultingDescriptor != variableDescriptor -> false else -> { val applicableUsage = getDataIfUsageIsApplicable(it, context) if (applicableUsage != null) { val usageDescriptor = applicableUsage.descriptor if (usageDescriptor == null) { for (parameter in constructorParameterNameMap.values) { process(parameter.index, applicableUsage) } return@anyDescendantOfType false } val parameter = constructorParameterNameMap[usageDescriptor.name] if (parameter != null) { process(parameter.index, applicableUsage) return@anyDescendantOfType false } } cancel() true } } } } private fun getDataIfUsageIsApplicable(dataClassUsage: KtReferenceExpression, context: BindingContext): SingleUsageData? { val destructuringDecl = dataClassUsage.parent as? KtDestructuringDeclaration if (destructuringDecl != null && destructuringDecl.initializer == dataClassUsage) { return SingleUsageData(descriptor = null, usageToReplace = null, declarationToDrop = destructuringDecl) } val qualifiedExpression = dataClassUsage.getQualifiedExpressionForReceiver() ?: return null val parent = qualifiedExpression.parent when (parent) { is KtBinaryExpression -> { if (parent.operationToken in KtTokens.ALL_ASSIGNMENTS && parent.left == qualifiedExpression) return null } is KtUnaryExpression -> { if (parent.operationToken == KtTokens.PLUSPLUS || parent.operationToken == KtTokens.MINUSMINUS) return null } } val property = parent as? KtProperty // val x = d.y if (property != null && property.isVar) return null val descriptor = qualifiedExpression.getResolvedCall(context)?.resultingDescriptor ?: return null if (!descriptor.isVisible( dataClassUsage, qualifiedExpression.receiverExpression, context, dataClassUsage.containingKtFile.getResolutionFacade() ) ) { return null } return SingleUsageData(descriptor = descriptor, usageToReplace = qualifiedExpression, declarationToDrop = property) } internal data class SingleUsageData( val descriptor: CallableDescriptor?, val usageToReplace: KtExpression?, val declarationToDrop: KtDeclaration? ) internal data class UsageData( val descriptor: CallableDescriptor, val usagesToReplace: MutableList<KtExpression> = mutableListOf(), var declarationToDrop: KtDeclaration? = null, var name: String? = null ) { // Returns true if data is successfully added, false otherwise fun add(newData: SingleUsageData, componentIndex: Int): Boolean { if (newData.declarationToDrop is KtDestructuringDeclaration) { val destructuringEntries = newData.declarationToDrop.entries if (componentIndex < destructuringEntries.size) { if (declarationToDrop != null) return false name = destructuringEntries[componentIndex].name ?: return false declarationToDrop = newData.declarationToDrop } } else { name = name ?: newData.declarationToDrop?.name declarationToDrop = declarationToDrop ?: newData.declarationToDrop } newData.usageToReplace?.let { usagesToReplace.add(it) } return true } } } }
apache-2.0
6595bc567633391e99421d6731c1e73f
48.199488
158
0.590403
6.690783
false
false
false
false
ediTLJ/novelty
app/src/main/java/ro/edi/novelty/ui/FeedInfoActivity.kt
1
11554
/* * 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.ui import android.app.Activity import android.graphics.Color import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import com.google.android.material.transition.platform.MaterialContainerTransform import com.google.android.material.transition.platform.MaterialContainerTransformSharedElementCallback import ro.edi.novelty.R import ro.edi.novelty.data.DataManager import ro.edi.novelty.databinding.ActivityFeedInfoBinding import ro.edi.novelty.ui.adapter.FeedsFoundAdapter import ro.edi.novelty.ui.viewmodel.FeedsFoundViewModel import ro.edi.novelty.ui.viewmodel.FeedsViewModel import timber.log.Timber.Forest.i as logi class FeedInfoActivity : AppCompatActivity() { companion object { const val EXTRA_FEED_ID = "ro.edi.novelty.ui.feedinfo.extra_feed_id" } private val feedsModel: FeedsViewModel by lazy(LazyThreadSafetyMode.NONE) { ViewModelProvider( viewModelStore, defaultViewModelProviderFactory )[FeedsViewModel::class.java] } private val feedsFoundModel: FeedsFoundViewModel by lazy(LazyThreadSafetyMode.NONE) { ViewModelProvider( viewModelStore, defaultViewModelProviderFactory )[FeedsFoundViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { findViewById<View>(android.R.id.content).transitionName = "shared_feed_container" // attach a callback used to receive the shared elements from Activity a // to be used by the container transform transition setEnterSharedElementCallback(MaterialContainerTransformSharedElementCallback()) window.sharedElementEnterTransition = MaterialContainerTransform(this, true).apply { addTarget(android.R.id.content) fadeMode = MaterialContainerTransform.FADE_MODE_CROSS containerColor = ContextCompat.getColor( applicationContext, R.color.grey ) // FIXME themed scrimColor = Color.TRANSPARENT } window.sharedElementReturnTransition = MaterialContainerTransform(this, false).apply { addTarget(android.R.id.content) fadeMode = MaterialContainerTransform.FADE_MODE_CROSS containerColor = ContextCompat.getColor( applicationContext, R.color.grey ) // FIXME themed scrimColor = Color.TRANSPARENT } super.onCreate(savedInstanceState) val binding: ActivityFeedInfoBinding = DataBindingUtil.setContentView(this, R.layout.activity_feed_info) binding.lifecycleOwner = this binding.model = feedsModel initView(binding) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { if (intent.hasExtra(EXTRA_FEED_ID)) { menuInflater.inflate(R.menu.menu_feed_info, menu) } // return true even if there's no EXTRA_FEED_ID, because we still have the system home/up action return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_delete -> feedsModel.feeds.value?.let { feeds -> val feed = feeds.find { it.id == intent.getIntExtra(EXTRA_FEED_ID, 0) } feed?.let { feedsModel.deleteFeed(it) finish() } } } return super.onOptionsItemSelected(item) } private fun initView(binding: ActivityFeedInfoBinding) { setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) binding.header.visibility = View.GONE binding.feeds.visibility = View.GONE binding.addFeedContainer.visibility = View.VISIBLE if (intent.hasExtra(EXTRA_FEED_ID)) { binding.toolbar.setTitle(R.string.title_edit_feed) binding.btnAdd.setText(R.string.btn_save) } else { DataManager.getInstance(application).clearFoundFeeds() val feedsFoundAdapter = FeedsFoundAdapter(feedsFoundModel, itemClickListener = { _, position -> val title = binding.editTitle.text.toString().trim { it <= ' ' } val feed = feedsFoundModel.getFeed(position) feed ?: return@FeedsFoundAdapter feedsModel.addFeed( title, feed.url, feed.type, (feedsModel.feeds.value?.size ?: 0) + 2, true ) DataManager.getInstance(application).clearFoundFeeds() finish() }).apply { setHasStableIds(true) } binding.feeds.apply { setHasFixedSize(true) adapter = feedsFoundAdapter } } binding.inputTitle.requestFocus() // FIXME add TextWatcher to clear potential errors on key pressed binding.editUrl.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { binding.btnAdd.performClick() return@setOnEditorActionListener true } false } feedsModel.feeds.observe(this) { feeds -> logi("feeds # in db: %d", feeds.size) val feed = feeds.find { it.id == intent.getIntExtra(EXTRA_FEED_ID, 0) } feed?.let { binding.editTitle.setText(it.title) binding.editUrl.setText(it.url) } binding.btnAdd.setOnClickListener { btn -> btn.isEnabled = false binding.inputTitle.error = "" binding.inputUrl.error = "" val title = binding.editTitle.text.toString().trim { it <= ' ' } var url = binding.editUrl.text.toString().trim { it <= ' ' } if (TextUtils.isEmpty(title)) { binding.inputTitle.error = getText(R.string.feed_title_required) binding.inputTitle.requestFocus() } else if (title.length > binding.inputTitle.counterMaxLength) { binding.inputTitle.error = getText(R.string.feed_title_too_long) binding.inputTitle.requestFocus() } else if (TextUtils.isEmpty(url)) { binding.inputUrl.error = getText(R.string.feed_url_required) binding.inputUrl.requestFocus() } else { url = when { url.startsWith("https://", true) -> url.replaceFirst("https", "https", true) url.startsWith("http://", true) -> url.replaceFirst("http", "http", true) else -> "https://$url" } if (intent.hasExtra(EXTRA_FEED_ID)) { // edit feed feed?.let { feedsModel.updateFeed(it, title, url) } finish() } else { // add feed var isDuplicate = false for (f in feeds) { if (f.url == url) { binding.inputUrl.error = getText(R.string.feed_url_duplicate) binding.inputUrl.requestFocus() isDuplicate = true break } if (f.title.equals(title, true)) { binding.inputTitle.error = getText(R.string.feed_title_duplicate) binding.inputTitle.requestFocus() isDuplicate = true break } } if (isDuplicate) { btn.isEnabled = true return@setOnClickListener } binding.loading.show() DataManager.getInstance(application).findFeeds(url) } } } } if (!intent.hasExtra(EXTRA_FEED_ID)) { feedsFoundModel.feeds.observe(this) { feeds -> feeds ?: return@observe logi("feeds found: %d", feeds.size) // logi("feeds: $feeds") if (feeds.isEmpty()) { // FIXME show "no feeds found" error binding.btnAdd.isEnabled = true binding.loading.hide() } else { val title = binding.editTitle.text.toString().trim { it <= ' ' } if (feeds.size == 1) { // FIXME check if already in db val feed = feeds.first() feedsModel.addFeed( title, feed.url, feed.type, (feedsModel.feeds.value?.size ?: 0) + 2, true ) DataManager.getInstance(application).clearFoundFeeds() finish() } else { binding.addFeedContainer.visibility = View.GONE val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0) binding.header.text = title binding.header.visibility = View.VISIBLE binding.feeds.visibility = View.VISIBLE (binding.feeds.adapter as FeedsFoundAdapter).submitList(feeds) // TODO what about feeds already in db? hide or show them as already added } } } } } }
apache-2.0
f21b648db14a4a1f436065a44cbcf981
37.575342
104
0.539121
5.314627
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/dialog/DlgCreateAccount.kt
1
4799
package jp.juggler.subwaytooter.dialog import android.annotation.SuppressLint import android.app.Dialog import android.view.View import android.view.WindowManager import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.api.entity.Host import jp.juggler.subwaytooter.api.entity.TootInstance import jp.juggler.subwaytooter.util.DecodeOptions import jp.juggler.subwaytooter.util.LinkHelper import jp.juggler.subwaytooter.util.openCustomTab import jp.juggler.util.neatSpaces import jp.juggler.util.notBlank import jp.juggler.util.showToast import jp.juggler.util.vg class DlgCreateAccount( val activity: AppCompatActivity, val apiHost: Host, val onClickOk: ( dialog: Dialog, username: String, email: String, password: String, agreement: Boolean, reason: String? ) -> Unit ) : View.OnClickListener { companion object { // private val log = LogCategory("DlgCreateAccount") } @SuppressLint("InflateParams") private val viewRoot = activity.layoutInflater .inflate(R.layout.dlg_account_create, null, false) private val etUserName: EditText = viewRoot.findViewById(R.id.etUserName) private val etEmail: EditText = viewRoot.findViewById(R.id.etEmail) private val etPassword: EditText = viewRoot.findViewById(R.id.etPassword) private val cbAgreement: CheckBox = viewRoot.findViewById(R.id.cbAgreement) private val tvDescription: TextView = viewRoot.findViewById(R.id.tvDescription) private val etReason: EditText = viewRoot.findViewById(R.id.etReason) private val tvReasonCaption: TextView = viewRoot.findViewById(R.id.tvReasonCaption) private val dialog = Dialog(activity) init { viewRoot.findViewById<TextView>(R.id.tvInstance).text = apiHost.pretty intArrayOf( R.id.btnRules, R.id.btnTerms, R.id.btnCancel, R.id.btnOk ).forEach { viewRoot.findViewById<Button>(it)?.setOnClickListener(this) } val instanceInfo = TootInstance.getCached(apiHost) tvDescription.text = DecodeOptions( activity, linkHelper = LinkHelper.create( apiHost, misskeyVersion = instanceInfo?.misskeyVersion ?: 0 ) ).decodeHTML( instanceInfo?.short_description?.notBlank() ?: instanceInfo?.description?.notBlank() ?: TootInstance.DESCRIPTION_DEFAULT ).neatSpaces() val showReason = instanceInfo?.approval_required ?: false tvReasonCaption.vg(showReason) etReason.vg(showReason) } fun show() { dialog.setContentView(viewRoot) dialog.window?.setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT ) dialog.show() } override fun onClick(v: View?) { when (v?.id) { R.id.btnRules -> activity.openCustomTab("https://$apiHost/about/more") R.id.btnTerms -> activity.openCustomTab("https://$apiHost/terms") R.id.btnCancel -> dialog.cancel() R.id.btnOk -> { val username = etUserName.text.toString().trim() val email = etEmail.text.toString().trim() val password = etPassword.text.toString().trim() when { username.isEmpty() -> activity.showToast(true, R.string.username_empty) email.isEmpty() -> activity.showToast(true, R.string.email_empty) password.isEmpty() -> activity.showToast(true, R.string.password_empty) username.contains("/") || username.contains("@") -> activity.showToast(true, R.string.username_not_need_atmark) else -> onClickOk( dialog, username, email, password, cbAgreement.isChecked, when (etReason.visibility) { View.VISIBLE -> etReason.text.toString().trim() else -> null } ) } } } } }
apache-2.0
f9d43d29fd35b1e6455fb48623ffbf43
32.278571
87
0.574495
4.842583
false
false
false
false
laviua/komock
komock-core/src/main/kotlin/ua/com/lavi/komock/ext/FileChangeWatcher.kt
1
1424
package ua.com.lavi.komock.ext import org.apache.commons.codec.digest.DigestUtils import org.slf4j.LoggerFactory import java.nio.file.Path import java.util.* import kotlin.concurrent.scheduleAtFixedRate /** * Created by Oleksandr Loushkin on 01.04.17. * Instant watch on files and invoke handler when file changes */ class FileChangeWatcher(private val fileChangeHandler: FileChangeHandler, private val files: List<Path>, private val period: Long) { private var threadName = this.javaClass.simpleName + "_" + System.currentTimeMillis() private val log = LoggerFactory.getLogger(this.javaClass) private val timer = Timer(threadName, false) private val fileHashes: MutableMap<Path, String> = HashMap() fun start() { log.info("Start watching on files: $files with period: $period ms") timer.scheduleAtFixedRate(0, period) { for (file in files) { val currentHash = DigestUtils.md5Hex(file.toFile().readText()) val oldHash = fileHashes[file] fileHashes.put(file, currentHash) if (oldHash != null && oldHash != currentHash) { log.info("File: $file has been changed! $currentHash") fileHashes.put(file, currentHash) fileChangeHandler.onFileChange(file) } } } } }
apache-2.0
22165c3cbf3e479607310b2200f17f75
35.538462
89
0.629916
4.535032
false
false
false
false
laviua/komock
komock-core/src/main/kotlin/ua/com/lavi/komock/http/server/handler/AbstractHttpHandler.kt
1
3075
package ua.com.lavi.komock.http.server.handler import org.eclipse.jetty.server.session.SessionHandler import org.slf4j.LoggerFactory import ua.com.lavi.komock.model.HttpMethod import ua.com.lavi.komock.model.Request import ua.com.lavi.komock.model.Response import java.io.OutputStream import java.util.* import java.util.zip.GZIPOutputStream import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by Oleksandr Loushkin * This is an entry point of the request * Serialize route properties content to the http response */ abstract class AbstractHttpHandler(private val routingTable: RoutingTable) : SessionHandler() { private val log = LoggerFactory.getLogger(this.javaClass) abstract override fun doHandle( target: String, jettyRequest: org.eclipse.jetty.server.Request, httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse) open fun handle(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse): Response { val requestUri = httpServletRequest.requestURI val response = Response(httpServletResponse) val httpMethod = HttpMethod.retrieveMethod(httpServletRequest.method) val route = routingTable.find(httpMethod, requestUri) if (route == null) { log.warn("Requested route $httpMethod:$requestUri is not mapped") httpServletResponse.status = HttpServletResponse.SC_NOT_FOUND return response } else { val request = Request(httpServletRequest) route.beforeResponseHandler.handle(request, response) route.responseHandler.handle(request, response) route.afterResponseHandler.handle(request, response) route.callbackHandler.handle(request, response) } return response } open fun serializeResponse(httpServletRequest: HttpServletRequest, httpServletResponse: HttpServletResponse, response: Response) { if (!httpServletResponse.isCommitted) { val responseStream = gzip(httpServletRequest, httpServletResponse) responseStream.write(response.getContent().toByteArray()) responseStream.flush() responseStream.close() } } private fun gzip(httpRequest: HttpServletRequest, httpResponse: HttpServletResponse): OutputStream { var responseStream: OutputStream = httpResponse.outputStream if (isGzipAccepted(httpRequest) && httpResponse.getHeaders("Content-Encoding").contains("gzip")) { responseStream = GZIPOutputStream(responseStream, true) } return responseStream } private fun isGzipAccepted(httpServletRequest: HttpServletRequest): Boolean { val headers: Enumeration<String> = httpServletRequest.getHeaders("Accept-Encoding") while (headers.hasMoreElements()) { if (headers.nextElement().contains("gzip")) { return true } } return false } }
apache-2.0
c8759c9fed73d5c9473683712bf4c858
38.948052
134
0.709268
5.168067
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
app/src/main/java/de/ph1b/audiobook/features/bookOverview/list/LoadBookCover.kt
1
2555
package de.ph1b.audiobook.features.bookOverview.list import androidx.core.view.doOnPreDraw import com.squareup.picasso.Picasso import de.ph1b.audiobook.R import de.ph1b.audiobook.covercolorextractor.CoverColorExtractor import de.ph1b.audiobook.data.Book import de.ph1b.audiobook.injection.appComponent import de.ph1b.audiobook.misc.color import de.ph1b.audiobook.misc.coverFile import de.ph1b.audiobook.uitools.CoverReplacement import de.ph1b.audiobook.uitools.MAX_IMAGE_SIZE import kotlinx.android.synthetic.main.book_overview_row_list.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject class LoadBookCover(holder: BookOverviewHolder) { @Inject lateinit var coverColorExtractor: CoverColorExtractor init { appComponent.inject(this) } private val context = holder.itemView.context private val progress = holder.progress private val cover = holder.cover private val defaultProgressColor = context.color(R.color.progressColor) private var boundFileLength: Long = Long.MIN_VALUE private var boundName: String? = null private var currentCoverBindingJob: Job? = null fun load(book: Book) { currentCoverBindingJob?.cancel() currentCoverBindingJob = GlobalScope.launch(Dispatchers.IO) { val coverFile = book.coverFile() val bookName = book.name val coverFileLength = coverFile.length() if (boundName == book.name && boundFileLength == coverFileLength) { return@launch } withContext(Dispatchers.Main) { progress.color = defaultProgressColor } val extractedColor = coverColorExtractor.extract(coverFile) val shouldLoadImage = coverFileLength in 1..(MAX_IMAGE_SIZE - 1) withContext(Dispatchers.Main) { progress.color = extractedColor ?: defaultProgressColor val coverReplacement = CoverReplacement(bookName, context) if (!isActive) return@withContext if (shouldLoadImage) { Picasso.get() .load(coverFile) .placeholder(coverReplacement) .into(cover) } else { Picasso.get().cancelRequest(cover) // we have to set the replacement in onPreDraw, else the transition will fail. cover.doOnPreDraw { cover.setImageDrawable(coverReplacement) } } boundFileLength = coverFileLength boundName = bookName } } } }
lgpl-3.0
bd69d05ebd39c55954c8c08bce9c6daa
32.181818
88
0.733464
4.202303
false
false
false
false
paplorinc/intellij-community
plugins/settings-repository/src/git/JGitMergeProvider.kt
6
4372
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.settingsRepository.git import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.vcs.merge.MergeData import com.intellij.openapi.vcs.merge.MergeProvider2 import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.ui.ColumnInfo import org.eclipse.jgit.lib.Repository import org.jetbrains.settingsRepository.RepositoryVirtualFile import java.nio.CharBuffer import java.util.* internal fun conflictsToVirtualFiles(map: Map<String, Any>): MutableList<VirtualFile> { val result = ArrayList<VirtualFile>(map.size) for (path in map.keys) { result.add(RepositoryVirtualFile(path)) } return result } /** * If content null: * Ours or Theirs - deleted. * Base - missed (no base). */ class JGitMergeProvider<T>(private val repository: Repository, private val conflicts: Map<String, T>, private val pathToContent: Map<String, T>.(path: String, index: Int) -> ByteArray?) : MergeProvider2 { override fun createMergeSession(files: List<VirtualFile>): MergeSession = JGitMergeSession() override fun conflictResolvedForFile(file: VirtualFile) { // we can postpone dir cache update (on merge dialog close) to reduce number of flush, but it can leads to data loss (if app crashed during merge - nothing will be saved) // update dir cache val bytes = (file as RepositoryVirtualFile).byteContent // not null if user accepts some revision (virtual file will be directly modified), otherwise document will be modified if (bytes == null) { val chars = FileDocumentManager.getInstance().getCachedDocument(file)!!.immutableCharSequence val byteBuffer = Charsets.UTF_8.encode(CharBuffer.wrap(chars)) addFile(byteBuffer.array(), file, byteBuffer.remaining()) } else { addFile(bytes, file) } } private fun addFile(bytes: ByteArray, file: VirtualFile, size: Int = bytes.size) { repository.writePath(file.path, bytes, size) } override fun isBinary(file: VirtualFile): Boolean = file.fileType.isBinary override fun loadRevisions(file: VirtualFile): MergeData { val path = file.path val mergeData = MergeData() mergeData.ORIGINAL = getContentOrEmpty(path, 0) mergeData.CURRENT = getContentOrEmpty(path, 1) mergeData.LAST = getContentOrEmpty(path, 2) return mergeData } private fun getContentOrEmpty(path: String, index: Int) = conflicts.pathToContent(path, index) ?: ArrayUtil.EMPTY_BYTE_ARRAY private inner class JGitMergeSession : MergeSession { override fun getMergeInfoColumns(): Array<ColumnInfo<out Any?, out Any?>> { return arrayOf(StatusColumn(false), StatusColumn(true)) } override fun canMerge(file: VirtualFile) = conflicts.contains(file.path) override fun conflictResolvedForFile(file: VirtualFile, resolution: MergeSession.Resolution) { if (resolution == MergeSession.Resolution.Merged) { conflictResolvedForFile(file) } else { val content = getContent(file, resolution == MergeSession.Resolution.AcceptedTheirs) if (content == null) { repository.deletePath(file.path) } else { addFile(content, file) } } } private fun getContent(file: VirtualFile, isTheirs: Boolean) = conflicts.pathToContent(file.path, if (isTheirs) 2 else 1) inner class StatusColumn(private val isTheirs: Boolean) : ColumnInfo<VirtualFile, String>(if (isTheirs) "Theirs" else "Yours") { override fun valueOf(file: VirtualFile?) = if (getContent(file!!, isTheirs) == null) "Deleted" else "Modified" override fun getMaxStringValue() = "Modified" override fun getAdditionalWidth() = 10 } } }
apache-2.0
0e8fde386ba37669760051ca977e8a8d
38.754545
204
0.729872
4.294695
false
false
false
false
georocket/georocket
src/main/kotlin/io/georocket/index/geojson/GeoJsonIdIndexer.kt
1
1516
package io.georocket.index.geojson import de.undercouch.actson.JsonEvent import io.georocket.index.Indexer import io.georocket.util.JsonStreamEvent import java.util.Stack /** * @author Tobias Dorra */ class GeoJsonIdIndexer: Indexer<JsonStreamEvent> { private data class ObjParseState( var currentKey: String? = null, var type: String? = null, var id: Any? = null, ) private var ids = mutableListOf<Any>() private var state = Stack<ObjParseState>() override fun onEvent(event: JsonStreamEvent) { when (event.event) { JsonEvent.START_OBJECT -> { state.push(ObjParseState()) } JsonEvent.END_OBJECT -> { if (!state.empty()) { val s = state.pop() val id = s.id if (s.type == "Feature" && id != null) { ids.add(id) } } } JsonEvent.FIELD_NAME -> { if (!state.empty()) { val s = state.peek() s.currentKey = event.currentValue.toString() } } JsonEvent.VALUE_STRING, JsonEvent.VALUE_INT -> { if (!state.empty()) { val s = state.peek() if (s.currentKey == "type") { s.type = event.currentValue.toString() } if (s.currentKey == "id") { s.id = event.currentValue } } } } } override fun makeResult(): Map<String, Any> { return if (ids.isNotEmpty()) { mapOf("geoJsonFeatureIds" to ids) } else { emptyMap() } } }
apache-2.0
801eca9fe6467f7fcca679d2c0469ba6
23.063492
54
0.55277
3.867347
false
false
false
false
google/intellij-community
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/moduleConfigurators/ModuleConfigurator.kt
2
14524
// 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.tools.projectWizard.moduleConfigurators import org.jetbrains.kotlin.tools.projectWizard.Identificator import org.jetbrains.kotlin.tools.projectWizard.PropertiesOwner import org.jetbrains.kotlin.tools.projectWizard.SettingsOwner import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.properties.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.* import org.jetbrains.kotlin.tools.projectWizard.enumSettingImpl import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.KotlinBuildSystemPluginIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.StdlibType import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModulesToIrConversionData import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.correspondingStdlib import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version import org.jetbrains.kotlin.tools.projectWizard.templates.FileTemplate import java.nio.file.Path import kotlin.properties.ReadOnlyProperty interface ModuleConfiguratorContext { val <V : Any, T : SettingType<V>> ModuleConfiguratorSetting<V, T>.reference: ModuleConfiguratorSettingReference<V, T> val <T : Any> ModuleConfiguratorProperty<T>.reference: PropertyReference<T> } class ModuleBasedConfiguratorContext( private val configurator: ModuleConfigurator, private val module: Module ) : ModuleConfiguratorContext { override val <V : Any, T : SettingType<V>> ModuleConfiguratorSetting<V, T>.reference: ModuleConfiguratorSettingReference<V, T> get() = ModuleBasedConfiguratorSettingReference(configurator, module, this) override val <T : Any> ModuleConfiguratorProperty<T>.reference: PropertyReference<T> get() = ModuleConfiguratorPropertyReference<T>(configurator, module, this) } class IdBasedConfiguratorContext( private val configurator: ModuleConfigurator, private val moduleId: Identificator ) : ModuleConfiguratorContext { override val <V : Any, T : SettingType<V>> ModuleConfiguratorSetting<V, T>.reference: ModuleConfiguratorSettingReference<V, T> get() = IdBasedConfiguratorSettingReference(configurator, moduleId, this) override val <T : Any> ModuleConfiguratorProperty<T>.reference: PropertyReference<T> get() = error("Should not be called as IdBasedConfiguratorContext used only for parsing settings") } fun <T> inContextOfModuleConfigurator( moduleId: Identificator, configurator: ModuleConfigurator, function: ModuleConfiguratorContext.() -> T ): T = function(IdBasedConfiguratorContext(configurator, moduleId)) fun <T> inContextOfModuleConfigurator( module: Module, configurator: ModuleConfigurator = module.configurator, function: ModuleConfiguratorContext.() -> T ): T = function(ModuleBasedConfiguratorContext(configurator, module)) fun <V : Any, T : SettingType<V>> Reader.settingValue(module: Module, setting: ModuleConfiguratorSetting<V, T>): V? = inContextOfModuleConfigurator(module) { setting.reference.notRequiredSettingValue } abstract class ModuleConfiguratorSettings : SettingsOwner { final override fun <V : Any, T : SettingType<V>> settingDelegate( create: (path: String) -> SettingBuilder<V, T> ): ReadOnlyProperty<Any?, ModuleConfiguratorSetting<V, T>> = cached { name -> ModuleConfiguratorSetting(create(name).buildInternal()) } @Suppress("UNCHECKED_CAST") final override fun <V : DisplayableSettingItem> dropDownSetting( title: String, neededAtPhase: GenerationPhase, parser: Parser<V>, init: DropDownSettingType.Builder<V>.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<V, DropDownSettingType<V>>> = super.dropDownSetting( title, neededAtPhase, parser, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<V, DropDownSettingType<V>>> @Suppress("UNCHECKED_CAST") final override fun stringSetting( title: String, neededAtPhase: GenerationPhase, init: StringSettingType.Builder.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<String, StringSettingType>> = super.stringSetting( title, neededAtPhase, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<String, StringSettingType>> @Suppress("UNCHECKED_CAST") final override fun booleanSetting( title: String, neededAtPhase: GenerationPhase, init: BooleanSettingType.Builder.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<Boolean, BooleanSettingType>> = super.booleanSetting( title, neededAtPhase, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<Boolean, BooleanSettingType>> @Suppress("UNCHECKED_CAST") final override fun <V : Any> valueSetting( title: String, neededAtPhase: GenerationPhase, parser: Parser<V>, init: ValueSettingType.Builder<V>.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<V, ValueSettingType<V>>> = super.valueSetting( title, neededAtPhase, parser, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<V, ValueSettingType<V>>> @Suppress("UNCHECKED_CAST") final override fun versionSetting( title: String, neededAtPhase: GenerationPhase, init: VersionSettingType.Builder.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<Version, VersionSettingType>> = super.versionSetting( title, neededAtPhase, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<Version, VersionSettingType>> @Suppress("UNCHECKED_CAST") final override fun <V : Any> listSetting( title: String, neededAtPhase: GenerationPhase, parser: Parser<V>, init: ListSettingType.Builder<V>.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<List<V>, ListSettingType<V>>> = super.listSetting( title, neededAtPhase, parser, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<List<V>, ListSettingType<V>>> @Suppress("UNCHECKED_CAST") final override fun pathSetting( title: String, neededAtPhase: GenerationPhase, init: PathSettingType.Builder.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<Path, PathSettingType>> = super.pathSetting( title, neededAtPhase, init ) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<Path, PathSettingType>> @Suppress("UNCHECKED_CAST") inline fun <reified E> enumSetting( title: String, neededAtPhase: GenerationPhase, crossinline init: DropDownSettingType.Builder<E>.() -> Unit = {} ): ReadOnlyProperty<Any, ModuleConfiguratorSetting<E, DropDownSettingType<E>>> where E : Enum<E>, E : DisplayableSettingItem = enumSettingImpl(title, neededAtPhase, init) as ReadOnlyProperty<Any, ModuleConfiguratorSetting<E, DropDownSettingType<E>>> } interface ModuleConfiguratorWithProperties : ModuleConfigurator { fun getConfiguratorProperties(): List<ModuleConfiguratorProperty<*>> fun SettingsWriter.initDefaultValuesForProperties(module: Module) { inContextOfModuleConfigurator(module) { getConfiguratorProperties().forEach { property -> property.reference.initDefaultValue(module) } } } } interface ModuleConfiguratorProperties : PropertiesOwner { override fun <T : Any> propertyDelegate( create: (path: String) -> PropertyBuilder<T>, ): ReadOnlyProperty<Any, ModuleConfiguratorProperty<T>> = cached { name -> ModuleConfiguratorProperty(create(name).build()) } @Suppress("UNCHECKED_CAST") override fun <T : Any> property( defaultValue: T, init: PropertyBuilder<T>.() -> Unit, ): ReadOnlyProperty<Any, ModuleConfiguratorProperty<T>> = super.property(defaultValue, init) as ReadOnlyProperty<Any, ModuleConfiguratorProperty<T>> @Suppress("UNCHECKED_CAST") override fun <T : Any> listProperty( vararg defaultValues: T, init: PropertyBuilder<List<T>>.() -> Unit ): ReadOnlyProperty<Any, ModuleConfiguratorProperty<List<T>>> = super.listProperty(defaultValues = defaultValues, init) as ReadOnlyProperty<Any, ModuleConfiguratorProperty<List<T>>> } interface ModuleConfiguratorWithSettings : ModuleConfigurator { fun getConfiguratorSettings(): List<ModuleConfiguratorSetting<*, *>> = emptyList() fun getPluginSettings(): List<PluginSettingReference<Any, SettingType<Any>>> = emptyList() fun SettingsWriter.initDefaultValuesFor(module: Module) { inContextOfModuleConfigurator(module) { getConfiguratorSettings().forEach { setting -> setting.reference.setSettingValueToItsDefaultIfItIsNotSetValue() } } } fun <V : Any, T : SettingType<V>> Reader.settingsValue(module: Module, setting: ModuleConfiguratorSetting<V, T>): V = inContextOfModuleConfigurator(module) { setting.reference.settingValue } } val ModuleConfigurator.settings get() = when (this) { is ModuleConfiguratorWithSettings -> getConfiguratorSettings() else -> emptyList() } fun Reader.allSettingsOfModuleConfigurator(moduleConfigurator: ModuleConfigurator) = when (moduleConfigurator) { is ModuleConfiguratorWithSettings -> buildList<Setting<Any, SettingType<Any>>> { +moduleConfigurator.getConfiguratorSettings() +moduleConfigurator.getPluginSettings().map { it.pluginSetting } } else -> emptyList() } fun Module.getConfiguratorSettings() = buildList<SettingReference<*, *>> { +configurator.settings.map { setting -> ModuleBasedConfiguratorSettingReference(configurator, this@getConfiguratorSettings, setting) } configurator.safeAs<ModuleConfiguratorWithSettings>()?.getPluginSettings()?.let { +it } } interface ModuleConfigurator : DisplayableSettingItem, EntitiesOwnerDescriptor { val moduleKind: ModuleKind val suggestedModuleName: String? get() = null val canContainSubModules: Boolean get() = false val requiresRootBuildFile: Boolean get() = false val kotlinDirectoryName: String get() = Defaults.KOTLIN_DIR.toString() val resourcesDirectoryName: String get() = Defaults.RESOURCES_DIR.toString() fun createBuildFileIRs( reader: Reader, configurationData: ModulesToIrConversionData, module: Module ): List<BuildSystemIR> = emptyList() fun createBuildFileIRsComparator(): Comparator<BuildSystemIR>? = null fun createModuleIRs( reader: Reader, configurationData: ModulesToIrConversionData, module: Module ): List<BuildSystemIR> = emptyList() fun createStdlibType(configurationData: ModulesToIrConversionData, module: Module): StdlibType? = safeAs<ModuleConfiguratorWithModuleType>()?.moduleType?.correspondingStdlib() fun createRootBuildFileIrs(configurationData: ModulesToIrConversionData): List<BuildSystemIR> = emptyList() fun createKotlinPluginIR(configurationData: ModulesToIrConversionData, module: Module): KotlinBuildSystemPluginIR? = null fun Writer.runArbitraryTask( configurationData: ModulesToIrConversionData, module: Module, modulePath: Path ): TaskResult<Unit> = UNIT_SUCCESS fun Reader.createTemplates( configurationData: ModulesToIrConversionData, module: Module, modulePath: Path ): List<FileTemplate> = emptyList() companion object { val ALL = buildList<ModuleConfigurator> { +RealNativeTargetConfigurator.configurators +NativeForCurrentSystemTarget +JsBrowserTargetConfigurator +MppLibJsBrowserTargetConfigurator +JsNodeTargetConfigurator +CommonTargetConfigurator +JvmTargetConfigurator +AndroidTargetConfigurator +MppModuleConfigurator +JvmSinglePlatformModuleConfigurator +AndroidSinglePlatformModuleConfigurator +IOSSinglePlatformModuleConfigurator +BrowserJsSinglePlatformModuleConfigurator +NodeJsSinglePlatformModuleConfigurator } init { ALL.groupBy(ModuleConfigurator::id) .forEach { (id, configurators) -> assert(configurators.size == 1) { id } } } private val BY_ID = ALL.associateBy(ModuleConfigurator::id) fun getParser(moduleIdentificator: Identificator): Parser<ModuleConfigurator> = valueParserM { value, path -> val (id) = value.parseAs<String>(path) BY_ID[id].toResult { ConfiguratorNotFoundError(id) } } or mapParser { map, path -> val (id) = map.parseValue<String>(path, "name") val (configurator) = BY_ID[id].toResult { ConfiguratorNotFoundError(id) } val (settingsWithValues) = parseSettingsMap( path, map, configurator.settings.map { setting -> val reference = inContextOfModuleConfigurator(moduleIdentificator, configurator) { setting.reference } reference to setting } ) updateState { it.withSettings(settingsWithValues) } configurator } } } interface GradleModuleConfigurator : ModuleConfigurator { fun createSettingsGradleIRs( reader: Reader, module: Module, data: ModulesToIrConversionData ): List<BuildSystemIR> = emptyList() }
apache-2.0
de73b54b15b4b1c8302f43941735367d
40.5
158
0.704283
5.22446
false
true
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.kt
1
29186
// 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", "ReplacePutWithAssignment", "OVERRIDE_DEPRECATION") package com.intellij.ide import com.intellij.diagnostic.runActivity import com.intellij.ide.RecentProjectsManager.Companion.fireChangeEvent import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.impl.ProjectUtil.isSameProject import com.intellij.ide.impl.ProjectUtilCore import com.intellij.ide.lightEdit.LightEdit import com.intellij.ide.ui.UISettings import com.intellij.idea.AppMode import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.appSystemDir import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.application.ex.ApplicationManagerEx import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.* import com.intellij.openapi.startup.ProjectPostStartupActivity import com.intellij.openapi.util.ModificationTracker import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.* import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.platform.ProjectSelfieUtil import com.intellij.project.stateStore import com.intellij.util.PathUtilRt import com.intellij.util.SingleAlarm import com.intellij.util.io.isDirectory import com.intellij.util.io.outputStream import com.intellij.util.io.systemIndependentPath import com.intellij.util.io.write import com.intellij.util.ui.ImageUtil import kotlinx.coroutines.* import kotlinx.coroutines.future.asDeferred import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.TestOnly import org.jetbrains.annotations.VisibleForTesting import org.jetbrains.jps.util.JpsPathUtil import java.awt.image.BufferedImage import java.io.File import java.nio.ByteBuffer import java.nio.file.Files import java.nio.file.InvalidPathException import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.* import java.util.concurrent.CompletableFuture import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicLong import javax.imageio.IIOImage import javax.imageio.ImageIO import javax.imageio.ImageTypeSpecifier import javax.imageio.stream.MemoryCacheImageOutputStream import javax.swing.Icon import javax.swing.JFrame import kotlin.collections.Map.Entry import kotlin.collections.component1 import kotlin.collections.component2 private val LOG = logger<RecentProjectsManager>() /** * Used directly by IntelliJ IDEA. */ @State(name = "RecentProjectsManager", storages = [Storage(value = "recentProjects.xml", roamingType = RoamingType.DISABLED)]) open class RecentProjectsManagerBase : RecentProjectsManager, PersistentStateComponent<RecentProjectManagerState>, ModificationTracker { companion object { const val MAX_PROJECTS_IN_MAIN_MENU = 6 @JvmStatic fun getInstanceEx(): RecentProjectsManagerBase = RecentProjectsManager.getInstance() as RecentProjectsManagerBase @JvmStatic fun isFileSystemPath(path: String): Boolean { return path.indexOf('/') != -1 || path.indexOf('\\') != -1 } } private val modCounter = AtomicLong() private val projectIconHelper by lazy(::RecentProjectIconHelper) private val namesToResolve = HashSet<String>(MAX_PROJECTS_IN_MAIN_MENU) private val nameCache: MutableMap<String, String> = Collections.synchronizedMap(HashMap()) private val disableUpdatingRecentInfo = AtomicBoolean() private val nameResolver = SingleAlarm.pooledThreadSingleAlarm(50, ApplicationManager.getApplication()) { var paths: Set<String> synchronized(namesToResolve) { paths = HashSet(namesToResolve) namesToResolve.clear() } for (p in paths) { nameCache.put(p, readProjectName(p)) } } private val stateLock = Any() private var state = RecentProjectManagerState() final override fun getState() = state fun getProjectMetaInfo(file: Path): RecentProjectMetaInfo? { synchronized(stateLock) { return state.additionalInfo.get(file.systemIndependentPath) } } final override fun loadState(state: RecentProjectManagerState) { synchronized(stateLock) { this.state = state state.pid = null // IDEA <= 2019.2 doesn't delete project info from additionalInfo on project delete @Suppress("DEPRECATION") val recentPaths = state.recentPaths if (recentPaths.isNotEmpty()) { convertToSystemIndependentPaths(recentPaths) // replace system-dependent paths to system-independent for (key in state.additionalInfo.keys.toList()) { val normalizedKey = FileUtilRt.toSystemIndependentName(key) if (normalizedKey != key) { state.additionalInfo.remove(key)?.let { state.additionalInfo.put(normalizedKey, it) } } } // ensure that additionalInfo contains entries in a reversed order of recentPaths (IDEA <= 2019.2 order of additionalInfo maybe not correct) val newAdditionalInfo = linkedMapOf<String, RecentProjectMetaInfo>() for (recentPath in recentPaths.asReversed()) { val value = state.additionalInfo.get(recentPath) ?: continue newAdditionalInfo.put(recentPath, value) } if (newAdditionalInfo != state.additionalInfo) { state.additionalInfo.clear() state.additionalInfo.putAll(newAdditionalInfo) } @Suppress("DEPRECATION") state.recentPaths.clear() } } } override fun removePath(path: String) { synchronized(stateLock) { if (state.additionalInfo.remove(path) != null) { modCounter.incrementAndGet() } for (group in state.groups) { if (group.removeProject(path)) { modCounter.incrementAndGet() } } fireChangeEvent() } } override fun hasPath(path: String?): Boolean { synchronized(stateLock) { return state.additionalInfo.containsKey(path) } } override var lastProjectCreationLocation: String? get() { synchronized(stateLock) { return state.lastProjectLocation } } set(value) { val newValue = value?.takeIf { it.isNotBlank() }?.let { FileUtilRt.toSystemIndependentName(it) } synchronized(stateLock) { state.lastProjectLocation = newValue } } override fun updateLastProjectPath() { val openProjects = ProjectManagerEx.getOpenProjects() synchronized(stateLock) { for (info in state.additionalInfo.values) { info.opened = false } for (project in openProjects) { updateProjectOpenedState(project, updateTime = false) } state.validateRecentProjects(modCounter) } } private fun updateProjectOpenedState(project: Project, updateTime: Boolean) { val path = getProjectPath(project) ?: return val info = state.additionalInfo.get(path) ?: return info.opened = true if (updateTime) { info.projectOpenTimestamp = System.currentTimeMillis() } info.displayName = getProjectDisplayName(project) } protected open fun getProjectDisplayName(project: Project): String? = null fun getProjectIcon(path: String): Icon = projectIconHelper.getProjectIcon(path = path, generateFromName = false) fun getProjectIcon(path: String, generateFromName: Boolean): Icon = projectIconHelper.getProjectIcon(path, generateFromName) @Suppress("OVERRIDE_DEPRECATION") override fun getRecentProjectsActions(addClearListItem: Boolean): Array<AnAction> { return RecentProjectListActionProvider.getInstance().getActions(addClearListItem = addClearListItem).toTypedArray() } @Suppress("OVERRIDE_DEPRECATION") override fun getRecentProjectsActions(addClearListItem: Boolean, useGroups: Boolean): Array<AnAction> { return RecentProjectListActionProvider.getInstance().getActions(addClearListItem = addClearListItem, useGroups = useGroups).toTypedArray() } fun markPathRecent(path: String, project: Project) { synchronized(stateLock) { for (group in state.groups) { if (group.markProjectFirst(path)) { modCounter.incrementAndGet() break } } // remove instead of get to re-order val info = state.additionalInfo.remove(path) ?: RecentProjectMetaInfo() state.additionalInfo.put(path, info) modCounter.incrementAndGet() val appInfo = ApplicationInfoEx.getInstanceEx() info.displayName = getProjectDisplayName(project) info.projectWorkspaceId = project.stateStore.projectWorkspaceId ProjectFrameBounds.getInstance(project).frameInfoHelper.info?.let { info.frame = it } info.build = appInfo!!.build.asString() info.productionCode = appInfo.build.productCode info.eap = appInfo.isEAP info.binFolder = FileUtilRt.toSystemIndependentName(PathManager.getBinPath()) info.projectOpenTimestamp = System.currentTimeMillis() info.buildTimestamp = appInfo.buildDate.timeInMillis info.metadata = getRecentProjectMetadata(path, project) } } fun addRecentPath(path: String, info: RecentProjectMetaInfo) { synchronized(stateLock) { state.additionalInfo.put(path, info) modCounter.incrementAndGet() } } // for Rider protected open fun getRecentProjectMetadata(path: String, project: Project): String? = null open fun getProjectPath(project: Project): String? { return FileUtilRt.toSystemIndependentName(project.presentableUrl ?: return null) } @TestOnly fun openProjectSync(projectFile: Path, openProjectOptions: OpenProjectTask): Project? { return runBlocking { openProject(projectFile, openProjectOptions) } } // open for Rider open suspend fun openProject(projectFile: Path, options: OpenProjectTask): Project? { var effectiveOptions = options if (options.implOptions == null) { getProjectMetaInfo(projectFile)?.frame?.let { frameInfo -> effectiveOptions = effectiveOptions.copy(implOptions = OpenProjectImplOptions(frameInfo = frameInfo)) } } if (isValidProjectPath(projectFile)) { val projectManager = ProjectManagerEx.getInstanceEx() projectManager.openProjects.firstOrNull { isSameProject(projectFile, it) }?.let { project -> withContext(Dispatchers.EDT) { ProjectUtil.focusProjectWindow(project = project) } return project } return projectManager.openProjectAsync(projectFile, effectiveOptions) } else { // If .idea is missing in the recent project's dir; this might mean, for instance, that 'git clean' was called. // Reopening such a project should be similar to opening the dir first time (and trying to import known project formats) // IDEA-144453 IDEA rejects opening recent project if there are no .idea subfolder // CPP-12106 Auto-load CMakeLists.txt on opening from Recent projects when .idea and cmake-build-debug were deleted return ProjectUtil.openOrImportAsync(projectFile, effectiveOptions) } } open fun setActivationTimestamp(project: Project, timestamp: Long) { getProjectPath(project)?.let { synchronized(stateLock) { state.additionalInfo.get(it)?.activationTimestamp = timestamp } } } fun getLastOpenedProject() = state.lastOpenedProject @Internal class MyFrameStateListener : FrameStateListener { override fun onFrameActivated(frame: IdeFrame) = frame.notifyProjectActivation() } @VisibleForTesting suspend fun runProjectPostStartupActivity(project: Project) { if (disableUpdatingRecentInfo.get() || LightEdit.owns(project)) { return } val projectPath = getProjectPath(project) ?: return synchronized(stateLock) { findAndRemoveNewlyClonedProject(projectPath) markPathRecent(projectPath, project) state.lastOpenedProject = projectPath updateProjectOpenedState(project, updateTime = true) state.validateRecentProjects(modCounter) } withContext(Dispatchers.EDT) { updateSystemDockMenu() } } internal class MyProjectPostStartupActivity : ProjectPostStartupActivity { init { if (ApplicationManager.getApplication().isUnitTestMode || ApplicationManager.getApplication().isHeadlessEnvironment /* disabling for Fleet */) { throw ExtensionNotApplicableException.create() } } override suspend fun execute(project: Project) { getInstanceEx().runProjectPostStartupActivity(project) } } @Internal @VisibleForTesting class MyProjectListener : ProjectManagerListener { override fun projectClosing(project: Project) { val app = ApplicationManagerEx.getApplicationEx() if (app.isExitInProgress) { // appClosing updates project info (even more - on project closed full screen state maybe not correct) return } val manager = getInstanceEx() val path = manager.getProjectPath(project) ?: return if (!app.isHeadlessEnvironment) { manager.updateProjectInfo(project, WindowManager.getInstance() as WindowManagerImpl, writLastProjectInfo = false, false) } manager.nameCache.put(path, project.name) } override fun projectClosed(project: Project) { if (ApplicationManagerEx.getApplicationEx().isExitInProgress) { // appClosing updates project info (even more - on project closed full screen state maybe not correct) return } updateSystemDockMenu() } } fun getRecentPaths(): List<String> { synchronized(stateLock) { state.validateRecentProjects(modCounter) return state.additionalInfo.keys.reversed() } } fun getDisplayName(path: String): String? { synchronized(stateLock) { return state.additionalInfo.get(path)?.displayName } } fun getProjectName(path: String): String { nameCache.get(path)?.let { return it } nameResolver.cancel() synchronized(namesToResolve) { namesToResolve.add(path) } nameResolver.request() val name = PathUtilRt.getFileName(path) return if (path.endsWith(".ipr")) FileUtilRt.getNameWithoutExtension(name) else name } override fun willReopenProjectOnStart(): Boolean { if (!GeneralSettings.getInstance().isReopenLastProject || AppMode.isDontReopenProjects()) { return false } synchronized(stateLock) { return state.additionalInfo.values.any { it.opened } } } override suspend fun reopenLastProjectsOnStart(): Boolean { val openPaths = lastOpenedProjects if (openPaths.isEmpty()) { return false } disableUpdatingRecentInfo.set(true) try { val isOpened = if (openPaths.size == 1 || ApplicationManager.getApplication().isHeadlessEnvironment || WindowManagerEx.getInstanceEx().getFrameHelper(null) != null) { openOneByOne(java.util.List.copyOf(openPaths), index = 0, someProjectWasOpened = false) } else { openMultiple(openPaths) } return isOpened } finally { WelcomeFrame.showIfNoProjectOpened(null) disableUpdatingRecentInfo.set(false) } } private suspend fun openOneByOne(openPaths: List<Entry<String, RecentProjectMetaInfo>>, index: Int, someProjectWasOpened: Boolean): Boolean { val (key, value) = openPaths.get(index) val options = OpenProjectTask { forceOpenInNewFrame = true showWelcomeScreen = false projectWorkspaceId = value.projectWorkspaceId implOptions = OpenProjectImplOptions(frameInfo = value.frame) } val project = openProject(Path.of(key), options) val nextIndex = index + 1 if (nextIndex == openPaths.size) { return someProjectWasOpened || project != null } else { return openOneByOne(openPaths, index = index + 1, someProjectWasOpened = someProjectWasOpened || project != null) } } override fun suggestNewProjectLocation() = ProjectUtil.getBaseDir() // open for Rider protected open fun isValidProjectPath(file: Path) = ProjectUtilCore.isValidProjectPath(file) // open for Rider @Suppress("MemberVisibilityCanBePrivate") protected suspend fun openMultiple(openPaths: List<Entry<String, RecentProjectMetaInfo>>): Boolean { val toOpen = ArrayList<Pair<Path, RecentProjectMetaInfo>>(openPaths.size) for (entry in openPaths) { val path = Path.of(entry.key) if (entry.value.frame == null || !isValidProjectPath(path)) { return false } toOpen.add(Pair(path, entry.value)) } // ok, no non-existent project paths and every info has a frame val activeInfo = toOpen.maxByOrNull { it.second.activationTimestamp }!!.second val taskList = ArrayList<Pair<Path, OpenProjectTask>>(toOpen.size) withContext(Dispatchers.EDT) { runActivity("project frame initialization") { var activeTask: Pair<Path, OpenProjectTask>? = null var fullScreenPromise: CompletableFuture<*>? = null for ((path, info) in toOpen) { val frameInfo = info.frame!! val isActive = info == activeInfo val ideFrame = createNewProjectFrame(frameInfo) info.frameTitle?.let { ideFrame.title = it } val frameHelper = ProjectFrameHelper(ideFrame, null) val frameManager = MyProjectUiFrameManager(ideFrame, frameHelper) frameHelper.init() if (frameInfo.fullScreen && FrameInfoHelper.isFullScreenSupportedInCurrentOs()) { fullScreenPromise = frameHelper.toggleFullScreen(true) } val task = Pair(path, OpenProjectTask { forceOpenInNewFrame = true showWelcomeScreen = false projectWorkspaceId = info.projectWorkspaceId implOptions = OpenProjectImplOptions(frameManager = frameManager) }) if (isActive) { activeTask = task } else { taskList.add(task) } } // we open project windows in the order projects were opened historically (to preserve taskbar order) // but once the windows are created, we start project loading from the latest active project (and put its window at front) taskList.add(activeTask!!) taskList.reverse() val frameToActivate = (activeTask.second.frameManager as MyProjectUiFrameManager).frame fullScreenPromise?.asDeferred()?.join() frameToActivate.toFront() } } val projectManager = ProjectManagerEx.getInstanceEx() val iterator = taskList.iterator() while (iterator.hasNext()) { val entry = iterator.next() try { projectManager.openProjectAsync(entry.first, entry.second) } catch (e: Exception) { withContext(NonCancellable) { @Suppress("SSBasedInspection") (entry.second.frameManager as MyProjectUiFrameManager?)?.dispose() while (iterator.hasNext()) { @Suppress("SSBasedInspection") (iterator.next().second.frameManager as MyProjectUiFrameManager?)?.dispose() } } throw e } } return true } protected val lastOpenedProjects: List<Entry<String, RecentProjectMetaInfo>> get() = synchronized(stateLock) { return state.additionalInfo.entries.filter { it.value.opened } } override val groups: List<ProjectGroup> get() { synchronized(stateLock) { return Collections.unmodifiableList(state.groups) } } override fun addGroup(group: ProjectGroup) { synchronized(stateLock) { if (!state.groups.contains(group)) { state.groups.add(group) fireChangeEvent() } } } override fun removeGroup(group: ProjectGroup) { synchronized(stateLock) { for (path in group.projects) { state.additionalInfo.remove(path) } state.groups.remove(group) modCounter.incrementAndGet() fireChangeEvent() } } override fun moveProjectToGroup(projectPath: String, to: ProjectGroup) { for (group in groups) { group.removeProject(projectPath) } to.addProject(projectPath) to.isExpanded = true // Save state for UI fireChangeEvent() } override fun removeProjectFromGroup(projectPath: String, from: ProjectGroup) { from.removeProject(projectPath) fireChangeEvent() } fun findGroup(projectPath: String): ProjectGroup? = groups.find { it.projects.contains(projectPath) } override fun getModificationCount(): Long { synchronized(stateLock) { return modCounter.get() + state.modificationCount } } private fun updateProjectInfo(project: Project, windowManager: WindowManagerImpl, writLastProjectInfo: Boolean, appClosing: Boolean) { val frameHelper = windowManager.getFrameHelper(project) if (frameHelper == null) { LOG.warn("Cannot update frame info (project=${project.name}, reason=frame helper is not found)") return } val frame = frameHelper.frameOrNull if (frame == null) { LOG.warn("Cannot update frame info (project=${project.name}, reason=frame is null)") return } if (appClosing) { frameHelper.appClosing() } val workspaceId = project.stateStore.projectWorkspaceId val frameInfo = ProjectFrameBounds.getInstance(project).getActualFrameInfoInDeviceSpace(frameHelper, frame, windowManager) val path = getProjectPath(project) synchronized(stateLock) { val info = state.additionalInfo.get(path) if (info == null) { LOG.warn("Cannot find info for ${project.name} to update frame info") } else { if (info.frame !== frameInfo) { info.frame = frameInfo } info.displayName = getProjectDisplayName(project) info.projectWorkspaceId = workspaceId info.frameTitle = frame.title } } LOG.runAndLogException { if (writLastProjectInfo) { writeInfoFile(frameInfo, frame) } if (workspaceId != null && Registry.`is`("ide.project.loading.show.last.state")) { takeASelfie(frameHelper, workspaceId) } } } /** * Finding a project that has just been cloned. * Skip a project with a similar path for [markPathRecent] to work correctly * * @param projectPath path to file that opens project (may differ with directory specified during cloning) */ private fun findAndRemoveNewlyClonedProject(projectPath: String) { if (state.additionalInfo.containsKey(projectPath)) { return } var file: File? = File(projectPath) while (file != null) { val projectMetaInfo = state.additionalInfo.remove(FileUtil.toSystemIndependentName(file.path)) if (projectMetaInfo != null) break file = FileUtil.getParentFile(file) } } private fun writeInfoFile(frameInfo: FrameInfo?, frame: JFrame) { if (!isUseProjectFrameAsSplash()) { return } val infoFile = getLastProjectFrameInfoFile() val bounds = frameInfo?.bounds if (bounds == null) { Files.deleteIfExists(infoFile) return } /* frame-info.tcl: big_endian int16 "Version" int32 "x" int32 "y" int32 "width" int32 "height" uint32 -hex "backgroundColor" uint8 "isFullscreen" int32 "extendedState" */ val buffer = ByteBuffer.allocate(2 + 6 * 4 + 1) // version buffer.putShort(0) buffer.putInt(bounds.x) buffer.putInt(bounds.y) buffer.putInt(bounds.width) buffer.putInt(bounds.height) buffer.putInt(frame.contentPane.background.rgb) buffer.put((if (frameInfo.fullScreen) 1 else 0).toByte()) buffer.putInt(frameInfo.extendedState) buffer.flip() infoFile.write(buffer) } private fun takeASelfie(frameHelper: ProjectFrameHelper, workspaceId: String) { val frame = frameHelper.frameOrNull!! val width = frame.width val height = frame.height val image = ImageUtil.createImage(frame.graphicsConfiguration, width, height, BufferedImage.TYPE_INT_ARGB) UISettings.setupAntialiasing(image.graphics) frame.paint(image.graphics) val selfieFile = ProjectSelfieUtil.getSelfieLocation(workspaceId) // must be a file, because for Path no optimized impl (output stream must be not used, otherwise cache file will be created by JDK) //long start = System.currentTimeMillis(); selfieFile.outputStream().use { stream -> MemoryCacheImageOutputStream(stream).use { out -> val writer = ImageIO.getImageWriters(ImageTypeSpecifier.createFromRenderedImage(image), "png").next() try { writer.output = out writer.write(null, IIOImage(image, null, null), null) } finally { writer.dispose() } } } //System.out.println("Write image: " + (System.currentTimeMillis() - start) + "ms"); val lastLink = selfieFile.parent.resolve("last.png") if (SystemInfo.isUnix) { Files.deleteIfExists(lastLink) Files.createSymbolicLink(lastLink, selfieFile) } else { Files.copy(selfieFile, lastLink, StandardCopyOption.REPLACE_EXISTING) } } fun patchRecentPaths(patcher: (String) -> String?) { synchronized(stateLock) { for (path in state.additionalInfo.keys.toList()) { patcher(path)?.let { newPath -> state.additionalInfo.remove(path)?.let { info -> state.additionalInfo[newPath] = info } } } modCounter.incrementAndGet() } } @Internal class MyAppLifecycleListener : AppLifecycleListener { override fun projectOpenFailed() { getInstanceEx().updateLastProjectPath() } override fun appClosing() { if (ApplicationManager.getApplication().isHeadlessEnvironment) { return } val openProjects = ProjectManagerEx.getOpenProjects() // do not delete info file if ProjectManager not created - it means that it was simply not loaded, so, unlikely something is changed if (openProjects.isEmpty()) { if (!isUseProjectFrameAsSplash()) { Files.deleteIfExists(getLastProjectFrameInfoFile()) } } else { val manager = getInstanceEx() val windowManager = WindowManager.getInstance() as WindowManagerImpl for ((index, project) in openProjects.withIndex()) { manager.updateProjectInfo(project, windowManager, writLastProjectInfo = index == 0, true) } } } override fun appWillBeClosed(isRestart: Boolean) { } override fun projectFrameClosed() { // ProjectManagerListener.projectClosed cannot be used to call updateLastProjectPath, // because called even if project closed on app exit getInstanceEx().updateLastProjectPath() } } } private fun isUseProjectFrameAsSplash() = Registry.`is`("ide.project.frame.as.splash") private fun readProjectName(path: String): String { if (!RecentProjectsManagerBase.isFileSystemPath(path)) { return path } val file = try { Path.of(path) } catch (e: InvalidPathException) { return path } if (!file.isDirectory()) { val fileName = file.fileName if (fileName != null) { return FileUtilRt.getNameWithoutExtension(fileName.toString()) } } val projectDir = file.resolve(Project.DIRECTORY_STORE_FOLDER) return JpsPathUtil.readProjectName(projectDir) ?: JpsPathUtil.getDefaultProjectName(projectDir) } private fun getLastProjectFrameInfoFile() = appSystemDir.resolve("lastProjectFrameInfo") private fun convertToSystemIndependentPaths(list: MutableList<String>) { list.replaceAll { FileUtilRt.toSystemIndependentName(it) } } private open class MyProjectUiFrameManager(val frame: IdeFrameImpl, private val frameHelper: ProjectFrameHelper) : ProjectUiFrameManager { override fun getWindow() = frame override suspend fun createFrameHelper(allocator: ProjectUiFrameAllocator) = frameHelper fun dispose() { frame.dispose() } } private fun updateSystemDockMenu() { if (!ApplicationManager.getApplication().isHeadlessEnvironment) { runActivity("system dock menu") { SystemDock.updateMenu() } } }
apache-2.0
d0a38f9a820cb169bfa899600ebd6ffc
33.016317
148
0.703145
4.669013
false
false
false
false
google/intellij-community
plugins/kotlin/completion/tests-shared/test/org/jetbrains/kotlin/idea/completion/test/CompletionTestUtil.kt
2
4792
// 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.completion.test import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.completion.CompletionType import com.intellij.codeInsight.lookup.LookupElement import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.idea.base.test.KotlinRoot import org.junit.Assert @JvmField val COMPLETION_TEST_DATA_BASE = KotlinRoot.DIR.resolve("completion/testData") fun testCompletion( fileText: String, platform: TargetPlatform?, complete: (CompletionType, Int) -> Array<LookupElement>?, defaultCompletionType: CompletionType = CompletionType.BASIC, defaultInvocationCount: Int = 0, ignoreProperties: Collection<String> = emptyList(), additionalValidDirectives: Collection<String> = emptyList() ) { testWithAutoCompleteSetting(fileText) { val completionType = ExpectedCompletionUtils.getCompletionType(fileText) ?: defaultCompletionType val invocationCount = ExpectedCompletionUtils.getInvocationCount(fileText) ?: defaultInvocationCount val items = complete(completionType, invocationCount) ?: emptyArray() ExpectedCompletionUtils.assertDirectivesValid(fileText, additionalValidDirectives) val expected = ExpectedCompletionUtils.itemsShouldExist(fileText, platform) val unexpected = ExpectedCompletionUtils.itemsShouldAbsent(fileText, platform) val itemsNumber = ExpectedCompletionUtils.getExpectedNumber(fileText, platform) val nothingElse = ExpectedCompletionUtils.isNothingElseExpected(fileText) Assert.assertTrue( "Should be some assertions about completion", expected.size != 0 || unexpected.size != 0 || itemsNumber != null || nothingElse ) ExpectedCompletionUtils.assertContainsRenderedItems(expected, items, ExpectedCompletionUtils.isWithOrder(fileText), nothingElse, ignoreProperties) ExpectedCompletionUtils.assertNotContainsRenderedItems(unexpected, items, ignoreProperties) if (itemsNumber != null) { val expectedItems = ExpectedCompletionUtils.listToString(ExpectedCompletionUtils.getItemsInformation(items)) Assert.assertEquals("Invalid number of completion items: ${expectedItems}", itemsNumber, items.size) } } } private fun testWithAutoCompleteSetting(fileText: String, doTest: () -> Unit) { val autoComplete = ExpectedCompletionUtils.getAutocompleteSetting(fileText) ?: false val settings = CodeInsightSettings.getInstance() val oldValue1 = settings.AUTOCOMPLETE_ON_CODE_COMPLETION val oldValue2 = settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION try { settings.AUTOCOMPLETE_ON_CODE_COMPLETION = autoComplete settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = autoComplete doTest() } finally { settings.AUTOCOMPLETE_ON_CODE_COMPLETION = oldValue1 settings.AUTOCOMPLETE_ON_SMART_TYPE_COMPLETION = oldValue2 } } fun JavaCodeInsightTestFixture.addCharacterCodingException() { addClass( """ package java.nio.charset; import java.io.IOException; public class CharacterCodingException extends IOException {} """.trimIndent() ) } fun JavaCodeInsightTestFixture.addAppendable() { addClass( """ package java.lang; import java.io.IOException; public interface Appendable { Appendable append(CharSequence csq) throws IOException; Appendable append(CharSequence csq, int start, int end) throws IOException; Appendable append(char c) throws IOException; } """.trimIndent() ) } fun JavaCodeInsightTestFixture.addHashSet() { addClass( """ package java.util; import java.io.Serializable; public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable { @Override public Iterator<E> iterator() { return null; } @Override public int size() { return 0; } } """.trimIndent() ) } fun JavaCodeInsightTestFixture.addLinkedHashSet() { addClass( """ package java.util; import java.io.Serializable; public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable {} """.trimIndent() ) }
apache-2.0
1d2843eaf6047bf6e733da8916d91f77
36.740157
158
0.689274
5.20304
false
true
false
false
jogy/jmoney
src/main/kotlin/name/gyger/jmoney/category/CategoryController.kt
1
1779
package name.gyger.jmoney.category import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/api") class CategoryController(private val categoryService: CategoryService) { @GetMapping("/categories") fun getCategories(): List<Category> { val categories = categoryService.getCategories() categories.forEach { c -> c.parent = null c.children.clear() } return categories } @GetMapping("/split-category") fun getSplitCategory(): Category { return categoryService.getSplitCategory() } @GetMapping("/root-category") fun getRootCategory(): Category { val rootCategory = categoryService.getRootCategory() rootCategory.children.clear() return rootCategory } @PostMapping("/categories") fun createCategory(@RequestBody category: Category): Long { return categoryService.createCategory(category) } @DeleteMapping("/categories/{categoryId}") fun deleteCategory(@PathVariable categoryId: Long) { categoryService.deleteCategory(categoryId) } @GetMapping("/category-tree") fun getCategoryMapping(): Category { val rootCategory = categoryService.getCategoryTree() rootCategory.children.remove(categoryService.getSplitCategory()) rootCategory.children.remove(categoryService.getTransferCategory()) cleanupCategories(rootCategory) return rootCategory } private fun cleanupCategories(cat: Category) { cat.parent = null cat.children.forEach { c -> cleanupCategories(c) } } @PutMapping("/category-tree") fun saveCategoryTree(@RequestBody rootCat: Category) { categoryService.saveCategoryTree(rootCat) } }
mit
bf2df18f0979e391dce83b68303164db
28.65
75
0.68353
5.068376
false
false
false
false
aporter/coursera-android
ExamplesKotlin/FragmentStaticConfigLayout/app/src/main/java/course/examples/fragments/staticconfiglayout/QuotesFragment.kt
1
3491
package course.examples.fragments.staticconfiglayout import android.content.Context import android.content.res.Configuration import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ListView import android.widget.TextView //Several Activity and Fragment lifecycle methods are instrumented to emit LogCat output //so you can follow the class' lifecycle class QuotesFragment : Fragment() { companion object { private const val TAG = "QuotesFragment" } private lateinit var mQuoteView: TextView private var mQuoteArrayLen: Int = 0 private var mCurrIdx = ListView.INVALID_POSITION // Show the Quote string at position newIndex fun showQuoteAtIndex(index: Int) { if (index in 0 until mQuoteArrayLen) { mQuoteView.text = QuoteViewerActivity.mQuoteArray[index] mCurrIdx = index } else { mQuoteView.text = QuoteViewerActivity.mNoQuoteSelectedString } } override fun onCreate(savedInstanceState: Bundle?) { Log.i(TAG, "${javaClass.simpleName}: onCreate()") super.onCreate(savedInstanceState) // Retain this Fragment across Activity reconfigurations retainInstance = true } // Called to create the content view for this Fragment override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { Log.i(TAG, "${javaClass.simpleName}: onCreateView()") // Inflate the layout defined in quote_fragment.xml // The last parameter is false because the returned view // does not need to be attached to the container ViewGroup return inflater.inflate(R.layout.quote_fragment, container, false) } // Set up some information about the mQuoteView TextView override fun onActivityCreated(savedInstanceState: Bundle?) { Log.i(TAG, "${javaClass.simpleName}: onActivityCreated()") super.onActivityCreated(savedInstanceState) mQuoteView = activity!!.findViewById(R.id.quoteView) mQuoteArrayLen = QuoteViewerActivity.mQuoteArray.size showQuoteAtIndex(mCurrIdx) } override fun onAttach(context: Context) { Log.i(TAG, "${javaClass.simpleName}: onAttach()") super.onAttach(context) } override fun onConfigurationChanged(newConfig: Configuration) { Log.i(TAG, "${javaClass.simpleName}: onConfigurationChanged()") super.onConfigurationChanged(newConfig) } override fun onDestroy() { Log.i(TAG, "${javaClass.simpleName}: onDestroy()") super.onDestroy() } override fun onDestroyView() { Log.i(TAG, "${javaClass.simpleName}: onDestroyView()") super.onDestroyView() } override fun onDetach() { Log.i(TAG, "${javaClass.simpleName}: onDetach()") super.onDetach() } override fun onPause() { Log.i(TAG, "${javaClass.simpleName}: onPause()") super.onPause() } override fun onResume() { Log.i(TAG, "${javaClass.simpleName}: onResume()") super.onResume() } override fun onStart() { Log.i(TAG, "${javaClass.simpleName}: onStart()") super.onStart() } override fun onStop() { Log.i(TAG, "${javaClass.simpleName}: onStop()") super.onStop() } }
mit
2ae5c128d00e2135698a47283307aa17
29.356522
88
0.669436
4.723951
false
true
false
false
nallar/TransparentWindows
src/main/java/nallar/transparentwindows/jna/User32Fast.kt
1
3943
package nallar.transparentwindows.jna import com.sun.jna.Native import com.sun.jna.Pointer import com.sun.jna.Structure import com.sun.jna.platform.win32.* import com.sun.jna.ptr.ByteByReference import com.sun.jna.ptr.IntByReference import nallar.transparentwindows.TransparentWindows import java.awt.Color object User32Fast { init { Native.register("User32") } external fun FindWindowA(className: String, windowName: String?): WinDef.HWND? external fun GetWindow(hWnd: WinDef.HWND?, flag: Int): WinDef.HWND? external fun GetTopWindow(hWnd: WinDef.HWND): WinDef.HWND? external fun GetWindowRect(hWnd: WinDef.HWND, r: WinDef.RECT): Boolean external fun IsWindowVisible(hWnd: WinDef.HWND): Boolean external fun GetWindowTextA(hWnd: WinDef.HWND, lpString: ByteArray, nMaxCount: Int): Int external fun EnumWindows(lpEnumFunc: WinUser.WNDENUMPROC, arg: Pointer?): Boolean external fun SetWindowLongPtrA(hWnd: WinDef.HWND, index: Int, newLong: BaseTSD.LONG_PTR): BaseTSD.LONG_PTR external fun GetWindowLongPtrA(hWnd: WinDef.HWND, nIndex: Int): BaseTSD.LONG_PTR external fun GetWindowThreadProcessId(hWnd: WinDef.HWND, pid: IntByReference): Int external fun SetLayeredWindowAttributes(hWnd: WinDef.HWND, crKey: Int, bAlpha: Byte, dwFlags: Int): Boolean external fun GetLayeredWindowAttributes(hWnd: WinDef.HWND, pcrKey: IntByReference, pbAlpha: ByteByReference, pdwFlags: IntByReference): Boolean external fun GetForegroundWindow(): WinDef.HWND? external fun SetWindowCompositionAttribute(hWnd: WinDef.HWND, compositionAttribute: CompositionAttribute): Int open class CompositionAttribute() : Structure() { @JvmField var attribute: Int = 19 @JvmField var data: AccentPolicy.ByReference? = null @JvmField var sizeOfData: Int = 0 // WCA attribute = 19 accent style override fun getFieldOrder(): MutableList<Any?>? { return mutableListOf( "attribute", "data", "sizeOfData" ) } } open class AccentPolicy() : Structure() { @JvmField var accentState: Int = 0 @JvmField var accentFlags: Int = 0 @JvmField var gradientColor: Int = 0 @Suppress("unused") // Required for object layout to match (JNA) @JvmField var animationId: Int = 0 class ByReference : AccentPolicy(), Structure.ByReference /*state: ACCENT_DISABLED = 0, ACCENT_ENABLE_GRADIENT = 1, ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, ACCENT_ENABLE_BLURBEHIND = 3, ACCENT_INVALID_STATE = 4*/ override fun getFieldOrder(): MutableList<Any?>? { return mutableListOf( "accentState", "accentFlags", "gradientColor", "animationId" ) } } fun SetWindowAccent(hWnd: WinDef.HWND) { val policy = AccentPolicy.ByReference() policy.accentState = 3 or 2 policy.accentFlags = 2 policy.gradientColor = Color(12, 12, 12, 154).rgb val attr = CompositionAttribute() attr.attribute = 19 attr.data = policy attr.sizeOfData = policy.size() val e = SetWindowCompositionAttribute(hWnd, attr) TransparentWindows.debugPrint { Win32Exception(Kernel32.INSTANCE.GetLastError()).message!! } TransparentWindows.debugPrint { e.toString() + " " + attr.attribute } } fun GetWindowThreadProcessId(hWnd: WinDef.HWND): Int { val pid = IntByReference() GetWindowThreadProcessId(hWnd, pid) return pid.value } fun GetWindowExe(hWnd: WinDef.HWND): String { val pid = GetWindowThreadProcessId(hWnd) val process = Kernel32.INSTANCE.OpenProcess(0x1000, false, pid) ?: return "unknown.exe" val exePathname = ByteArray(512) val result = Psapi.INSTANCE.GetModuleFileNameExA(process, Pointer(0), exePathname, 512) return Native.toString(exePathname).substring(0, result) } private interface Psapi : com.sun.jna.win32.StdCallLibrary { fun GetModuleFileNameExA(process: WinNT.HANDLE, hModule: Pointer, lpString: ByteArray, nMaxCount: Int): Int companion object { val INSTANCE = Native.loadLibrary("psapi", Psapi::class.java) as Psapi } } }
mit
ee01ebac8e96a85fee4c1c997243c831
30.798387
144
0.743343
3.335871
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-apis/src/main/kotlin/slatekit/apis/Settings.kt
1
1803
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.apis import slatekit.apis.tools.docs.Doc import slatekit.apis.tools.docs.DocConsole import slatekit.apis.tools.docs.DocWeb import slatekit.common.Source import slatekit.common.crypto.Encryptor import slatekit.utils.naming.Namer import slatekit.requests.Request import slatekit.serialization.deserializer.Deserializer /** * Server Settings * @param source: Protocol for server ( CLI, Web, File, Queue ) : requests are validated against this * @param naming : Naming convention applied to actions ( routes ) : uses raw method names if not supplied * @param decoder : Decoder to provide the Deserializer for requests: uses default if not supplied * @param encoder : Encoder to convert an ApiResult to JSON; : uses default if not supplied * @param docKey : Documentation API key ( for help/doc requests ) * @param docGen : Documentation generator */ data class Settings( val source: Source = Source.API, val naming: Namer? = null, val decoder: ((Request, Encryptor?) -> Deserializer)? = null, val encoder: ((String, Any?) -> String)? = null, val record : Boolean = false, val docKey: String? = null, val docGen: () -> Doc = { doc(source) } ) { companion object { fun doc(protocol: Source): Doc { return when (protocol) { is Source.Web -> DocWeb() is Source.API -> DocWeb() else -> DocConsole() } } } }
apache-2.0
7535a9d0df66d1bab1b0cd9b3cde345c
33.673077
106
0.678869
4.01559
false
false
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserService.kt
1
7691
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.* import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.updateSettings.impl.PluginDownloader import com.intellij.openapi.util.NlsContexts.NotificationContent import com.intellij.util.containers.MultiMap open class PluginAdvertiserService { companion object { @JvmStatic val instance get() = service<PluginAdvertiserService>() } fun run( project: Project, customPlugins: List<PluginNode>, unknownFeatures: Set<UnknownFeature>, ) { val features = MultiMap.createSet<PluginId, UnknownFeature>() val disabledPlugins = HashMap<PluginData, IdeaPluginDescriptor>() val ids = mutableMapOf<PluginId, PluginData>() val marketplaceRequests = MarketplaceRequests.Instance unknownFeatures.forEach { feature -> ProgressManager.checkCanceled() val featureType = feature.featureType val implementationName = feature.implementationName val installedPluginData = PluginFeatureService.instance .getPluginForFeature(featureType, implementationName) ?.pluginData fun putFeature(data: PluginData) { val id = data.pluginId ids[id] = data features.putValue(id, feature) } if (installedPluginData != null) { putFeature(installedPluginData) } else { marketplaceRequests .getFeatures(featureType, implementationName) .mapNotNull { it.toPluginData() } .forEach { putFeature(it) } } } //include disabled plugins ids.filter { (pluginId, _) -> PluginManagerCore.isDisabled(pluginId) }.mapNotNull { (pluginId, plugin) -> PluginManagerCore.getPlugin(pluginId)?.let { plugin to it } }.forEach { (plugin, pluginDescriptor) -> disabledPlugins[plugin] = pluginDescriptor } val bundledPlugin = getBundledPluginToInstall(ids.values) val plugins = mutableSetOf<PluginDownloader>() if (ids.isNotEmpty()) { RepositoryHelper.mergePluginsFromRepositories( marketplaceRequests.loadLastCompatiblePluginDescriptors(ids.keys), customPlugins, true, ).filterNot { loadedPlugin -> val pluginId = loadedPlugin.pluginId val compareVersions = PluginManagerCore.getPlugin(pluginId)?.let { PluginDownloader.compareVersionsSkipBrokenAndIncompatible(loadedPlugin.version, it) <= 0 } ?: false compareVersions || !ids.containsKey(pluginId) || PluginManagerCore.isDisabled(pluginId) || PluginManagerCore.isBrokenPlugin(loadedPlugin) }.map { PluginDownloader.createDownloader(it) }.forEach { plugins += it } } invokeLater(ModalityState.NON_MODAL) { if (project.isDisposed) return@invokeLater val (notificationMessage, notificationActions) = if (plugins.isNotEmpty() || disabledPlugins.isNotEmpty()) { val action = if (disabledPlugins.isNotEmpty()) { val disabledDescriptors = disabledPlugins.values val title = if (disabledPlugins.size == 1) IdeBundle.message( "plugins.advertiser.action.enable.plugin", disabledDescriptors.single().name ) else IdeBundle.message("plugins.advertiser.action.enable.plugins") NotificationAction.createSimpleExpiring(title) { FUSEventSource.NOTIFICATION.logEnablePlugins( disabledDescriptors.map { it.pluginId.idString }, project, ) PluginManagerConfigurable.showPluginConfigurableAndEnable( project, disabledDescriptors.toSet(), ) } } else NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.configure.plugins")) { FUSEventSource.NOTIFICATION.logConfigurePlugins(project) PluginsAdvertiserDialog(project, plugins, customPlugins).show() } getAddressedMessagePresentation( plugins, disabledPlugins.values, features, ) to listOf( action, NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.ignore.unknown.features")) { FUSEventSource.NOTIFICATION.logIgnoreUnknownFeatures(project) val collector = UnknownFeaturesCollector.getInstance(project) unknownFeatures.forEach { collector.ignoreFeature(it) } }, ) } else if (bundledPlugin.isNotEmpty() && !isIgnoreUltimate) { IdeBundle.message( "plugins.advertiser.ultimate.features.detected", bundledPlugin.joinToString() ) to listOf( NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.try.ultimate")) { FUSEventSource.NOTIFICATION.openDownloadPageAndLog(project) }, NotificationAction.createSimpleExpiring(IdeBundle.message("plugins.advertiser.action.ignore.ultimate")) { FUSEventSource.NOTIFICATION.doIgnoreUltimateAndLog(project) }, ) } else { return@invokeLater } val notification = notificationGroup.createNotification( "", notificationMessage, NotificationType.INFORMATION, null, ) notification.addActions(notificationActions) notification.notify(project) } } open fun getAddressedMessagePresentation( plugins: Set<PluginDownloader>, disabledPlugins: Collection<IdeaPluginDescriptor>, features: MultiMap<PluginId, UnknownFeature>, ): @NotificationContent String { val ids = plugins.mapTo(LinkedHashSet()) { it.id } + disabledPlugins.map { it.pluginId } val addressedFeatures = collectFeaturesByName(ids, features) val pluginsNumber = ids.size val repoPluginsNumber = plugins.size val entries = addressedFeatures.entrySet() return if (entries.size == 1) { val feature = entries.single() IdeBundle.message( "plugins.advertiser.missing.feature", pluginsNumber, feature.key, feature.value.joinToString(), repoPluginsNumber, ) } else { IdeBundle.message( "plugins.advertiser.missing.features", pluginsNumber, entries.joinToString(separator = "; ") { it.value.joinToString(prefix = it.key + ": ") }, repoPluginsNumber, ) } } protected fun collectFeaturesByName(ids: Set<PluginId>, features: MultiMap<PluginId, UnknownFeature>): MultiMap<String, String> { val result = MultiMap.createSet<String, String>() ids .flatMap { features[it] } .forEach { result.putValue(it.featureDisplayName, it.implementationDisplayName) } return result } }
apache-2.0
4559bbb0cbf2f2f383eef375e8e2b13f
34.118721
140
0.671434
5.311464
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/stdlib/properties/delegation/DelegationTest/ObservablePropertyTest.kt
2
499
import kotlin.test.* import kotlin.properties.* class ObservablePropertyTest { var result = false var b: Int by Delegates.observable(1, { property, old, new -> assertEquals("b", property.name) result = true assertEquals(new, b, "New value has already been set") }) fun doTest() { b = 4 assertTrue(b == 4, "fail: b != 4") assertTrue(result, "fail: result should be true") } } fun box() { ObservablePropertyTest().doTest() }
apache-2.0
fc17477ed41d490b3c6043addb65fa74
20.73913
65
0.599198
3.960317
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/highlighter/HighlightingUtils.kt
1
3526
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.highlighter import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAbstract import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors fun textAttributesKeyForKtElement(element: PsiElement): TextAttributesKey? { return sequence { yield(textAttributesKeyForTypeDeclaration(element)) yield(textAttributesKeyForKtFunction(element)) yield(textAttributesKeyForPropertyDeclaration(element)) } .firstOrNull { it != null } } fun textAttributesKeyForPropertyDeclaration(declaration: PsiElement): TextAttributesKey? = when (declaration) { is KtProperty -> textAttributesForKtPropertyDeclaration(declaration) is KtParameter -> textAttributesForKtParameterDeclaration(declaration) is PsiLocalVariable -> Colors.LOCAL_VARIABLE is PsiParameter -> Colors.PARAMETER is PsiField -> Colors.INSTANCE_PROPERTY else -> null } fun textAttributesForKtParameterDeclaration(parameter: KtParameter): TextAttributesKey = if (parameter.valOrVarKeyword != null) Colors.INSTANCE_PROPERTY else Colors.PARAMETER fun textAttributesForKtPropertyDeclaration(property: KtProperty): TextAttributesKey? = when { property.isExtensionDeclaration() -> Colors.EXTENSION_PROPERTY property.isLocal -> Colors.LOCAL_VARIABLE property.isTopLevel -> { if (property.isCustomPropertyDeclaration()) Colors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION else Colors.PACKAGE_PROPERTY } else -> { if (property.isCustomPropertyDeclaration()) Colors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION else Colors.INSTANCE_PROPERTY } } private fun KtProperty.isCustomPropertyDeclaration() = getter?.bodyExpression != null || setter?.bodyExpression != null fun textAttributesKeyForKtFunction(function: PsiElement): TextAttributesKey? = when (function) { is KtFunction -> Colors.FUNCTION_DECLARATION else -> null } @Suppress("UnstableApiUsage") fun textAttributesKeyForTypeDeclaration(declaration: PsiElement): TextAttributesKey? = when { declaration is KtTypeParameter || declaration is PsiTypeParameter -> Colors.TYPE_PARAMETER declaration is KtTypeAlias -> Colors.TYPE_ALIAS declaration is KtClass -> textAttributesForClass(declaration) declaration is PsiClass && declaration.isInterface && !declaration.isAnnotationType -> Colors.TRAIT declaration.isAnnotationClass() -> Colors.ANNOTATION declaration is KtObjectDeclaration -> Colors.OBJECT declaration is PsiEnumConstant -> Colors.ENUM_ENTRY declaration is PsiClass && declaration.hasModifier(JvmModifier.ABSTRACT) -> Colors.ABSTRACT_CLASS declaration is PsiClass -> Colors.CLASS else -> null } fun textAttributesForClass(klass: KtClass): TextAttributesKey = when { klass.isInterface() -> Colors.TRAIT klass.isAnnotation() -> Colors.ANNOTATION klass.isEnum() -> Colors.ENUM klass is KtEnumEntry -> Colors.ENUM_ENTRY klass.isAbstract() -> Colors.ABSTRACT_CLASS else -> Colors.CLASS } fun PsiElement.isAnnotationClass() = this is KtClass && isAnnotation() || this is PsiClass && isAnnotationType
apache-2.0
886a770f961416e941af2fa799603735
43.0875
158
0.771129
5.147445
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/ConstructorSwapArgumentsBefore.kt
13
286
open class C1 protected <caret>(val x1: Int = 1, var x2: Float, x3: ((Int) -> Int)?) { fun bar() { val y1 = x1; val y2 = x2; } } class C2 : C1(1, 2.5, null) { fun foo() { var c = C1(2, 3.5, null); c = C1(x1 = 2, x2 = 3.5, x3 = null); } }
apache-2.0
ff43d50dfab498ebf8ca791bfb15a487
22.833333
86
0.43007
2.344262
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinValProperty/after/RenameKotlinValProperty.kt
13
448
package testing.rename interface AP { val second: Int // <--- Rename base here } public open class BP: AP { override val second: Int get() = 12 // <-- Rename with Java getter here } class CP: BP() { override val second = 2 // <--- Rename overriden here } class CPOther { val first: Int = 111 } fun usagesProp() { val b = BP() val a: AP = b val c = CP() a.second b.second c.second CPOther().first }
apache-2.0
53b05f4433ce7e7ebd0c4a63af446d50
14.482759
75
0.584821
3.270073
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/extensions/GHProtectedBranchRulesLoader.kt
6
3505
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.extensions import com.intellij.concurrency.SensitiveProgressWrapper import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.util.PatternUtil import git4idea.config.GitSharedSettings import git4idea.fetch.GitFetchHandler import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.plugins.github.api.GHGQLRequests import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.util.GHProjectRepositoriesManager import org.jetbrains.plugins.github.util.GithubProjectSettings private val LOG = logger<GHProtectedBranchRulesLoader>() internal class GHProtectedBranchRulesLoader : GitFetchHandler { override fun doAfterSuccessfulFetch(project: Project, fetches: Map<GitRepository, List<GitRemote>>, indicator: ProgressIndicator) { try { loadProtectionRules(indicator, fetches, project) } catch (e: Exception) { if (e is ProcessCanceledException) { throw e } LOG.info("Error occurred while trying to load branch protection rules", e) } } private fun loadProtectionRules(indicator: ProgressIndicator, fetches: Map<GitRepository, List<GitRemote>>, project: Project) { val githubAuthenticationManager = GithubAuthenticationManager.getInstance() if (!GitSharedSettings.getInstance(project).isSynchronizeBranchProtectionRules || !githubAuthenticationManager.hasAccounts()) { runInEdt { project.service<GithubProjectSettings>().branchProtectionPatterns = arrayListOf() } return } indicator.text = GithubBundle.message("progress.text.loading.protected.branches") val branchProtectionPatterns = mutableSetOf<String>() for ((repository, remotes) in fetches) { indicator.checkCanceled() for (remote in remotes) { indicator.checkCanceled() val account = githubAuthenticationManager.getAccounts().find { it.server.matches(remote.firstUrl.orEmpty()) } ?: continue val requestExecutor = GithubApiRequestExecutorManager.getInstance().getExecutor(account) val githubRepositoryMapping = project.service<GHProjectRepositoriesManager>().findKnownRepositories(repository).find { it.gitRemoteUrlCoordinates.remote == remote } ?: continue val repositoryCoordinates = githubRepositoryMapping.ghRepositoryCoordinates SimpleGHGQLPagesLoader(requestExecutor, { GHGQLRequests.Repo.getProtectionRules(repositoryCoordinates) }) .loadAll(SensitiveProgressWrapper((indicator))) .forEach { rule -> branchProtectionPatterns.add(PatternUtil.convertToRegex(rule.pattern)) } } } runInEdt { project.service<GithubProjectSettings>().branchProtectionPatterns = branchProtectionPatterns.toMutableList() } } }
apache-2.0
90eee0f1f345b2c56412bfa08c682f0d
41.228916
144
0.764337
5.065029
false
false
false
false
mglukhikh/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInferenceIndex.kt
2
3736
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.dataFlow import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.psi.impl.source.JavaLightStubBuilder import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.JavaElementType.* import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor import com.intellij.psi.stub.JavaStubImplUtil import com.intellij.util.gist.GistManager import java.util.* /** * @author peter */ private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 6, MethodDataExternalizer) { file -> indexFile(file.node.lighterAST) } private fun indexFile(tree: LighterAST): Map<Int, MethodData> { val result = HashMap<Int, MethodData>() object : RecursiveLighterASTNodeWalkingVisitor(tree) { var methodIndex = 0 override fun visitNode(element: LighterASTNode) { if (element.tokenType === METHOD) { calcData(tree, element)?.let { data -> result[methodIndex] = data } methodIndex++ } if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return super.visitNode(element) } }.visitNode(tree.root) return result } private fun calcData(tree: LighterAST, method: LighterASTNode): MethodData? { val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null val statements = ContractInferenceInterpreter.getStatements(body, tree) val contracts = ContractInferenceInterpreter(tree, method, body).inferContracts(statements) val nullityVisitor = NullityInference.NullityInferenceVisitor(tree, body) val purityVisitor = PurityInference.PurityInferenceVisitor(tree, body) for (statement in statements) { walkMethodBody(tree, statement) { nullityVisitor.visitNode(it); purityVisitor.visitNode(it) } } val notNullParams = inferNotNullParameters(tree, method, statements) return createData(body, contracts, nullityVisitor.result, purityVisitor.result, notNullParams) } private fun walkMethodBody(tree: LighterAST, root: LighterASTNode, processor: (LighterASTNode) -> Unit) { object : RecursiveLighterASTNodeWalkingVisitor(tree) { override fun visitNode(element: LighterASTNode) { val type = element.tokenType if (type === CLASS || type === FIELD || type === METHOD || type === ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return processor(element) super.visitNode(element) } }.visitNode(root) } private fun createData(body: LighterASTNode, contracts: List<PreContract>, nullity: NullityInferenceResult?, purity: PurityInferenceResult?, notNullParams: BitSet): MethodData? { if (nullity == null && purity == null && contracts.isEmpty() && notNullParams.isEmpty) return null return MethodData(nullity, purity, contracts, notNullParams, body.startOffset, body.endOffset) } fun getIndexedData(method: PsiMethodImpl): MethodData? = gist.getFileData(method.containingFile)?.get(JavaStubImplUtil.getMethodStubIndex(method))
apache-2.0
2cb5a8d1236a467832b2b4818c572b0d
37.927083
146
0.742505
4.484994
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ast/NewClassExpression.kt
6
1018
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.j2k.ast import org.jetbrains.kotlin.j2k.CodeBuilder class NewClassExpression( val name: ReferenceElement?, val argumentList: ArgumentList, val qualifier: Expression = Empty, val anonymousClass: AnonymousClassBody? = null ) : Expression() { override fun generateCode(builder: CodeBuilder) { if (anonymousClass != null) { builder.append("object:") } if (!qualifier.isEmpty) { builder.append(qualifier).append(if (qualifier.isNullable) "!!." else ".") } if (name != null) { builder.append(name) } if (anonymousClass == null || !anonymousClass.extendsInterface) { builder.append(argumentList) } if (anonymousClass != null) { builder.append(anonymousClass) } } }
apache-2.0
32b2cbcdcaacdcb92e631a467d03a651
28.085714
158
0.629666
4.445415
false
false
false
false
kohesive/kohesive-iac
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAmazonEC2.kt
1
20065
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.ec2.AbstractAmazonEC2 import com.amazonaws.services.ec2.AmazonEC2 import com.amazonaws.services.ec2.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAmazonEC2(val context: IacContext) : AbstractAmazonEC2(), AmazonEC2 { override fun attachClassicLinkVpc(request: AttachClassicLinkVpcRequest): AttachClassicLinkVpcResult { return with (context) { request.registerWithAutoName() makeProxy<AttachClassicLinkVpcRequest, AttachClassicLinkVpcResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun attachInternetGateway(request: AttachInternetGatewayRequest): AttachInternetGatewayResult { return with (context) { request.registerWithAutoName() AttachInternetGatewayResult().registerWithSameNameAs(request) } } override fun attachNetworkInterface(request: AttachNetworkInterfaceRequest): AttachNetworkInterfaceResult { return with (context) { request.registerWithAutoName() makeProxy<AttachNetworkInterfaceRequest, AttachNetworkInterfaceResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun attachVolume(request: AttachVolumeRequest): AttachVolumeResult { return with (context) { request.registerWithAutoName() makeProxy<AttachVolumeRequest, AttachVolumeResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun attachVpnGateway(request: AttachVpnGatewayRequest): AttachVpnGatewayResult { return with (context) { request.registerWithAutoName() makeProxy<AttachVpnGatewayRequest, AttachVpnGatewayResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createCustomerGateway(request: CreateCustomerGatewayRequest): CreateCustomerGatewayResult { return with (context) { request.registerWithAutoName() CreateCustomerGatewayResult().withCustomerGateway( makeProxy<CreateCustomerGatewayRequest, CustomerGateway>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateCustomerGatewayRequest::getType to CustomerGateway::getType ) ) ).registerWithSameNameAs(request) } } override fun createDhcpOptions(request: CreateDhcpOptionsRequest): CreateDhcpOptionsResult { return with (context) { request.registerWithAutoName() CreateDhcpOptionsResult().withDhcpOptions( makeProxy<CreateDhcpOptionsRequest, DhcpOptions>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateDhcpOptionsRequest::getDhcpConfigurations to DhcpOptions::getDhcpConfigurations ) ) ).registerWithSameNameAs(request) } } override fun createEgressOnlyInternetGateway(request: CreateEgressOnlyInternetGatewayRequest): CreateEgressOnlyInternetGatewayResult { return with (context) { request.registerWithAutoName() CreateEgressOnlyInternetGatewayResult().withEgressOnlyInternetGateway( makeProxy<CreateEgressOnlyInternetGatewayRequest, EgressOnlyInternetGateway>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) ).registerWithSameNameAs(request) } } override fun createFlowLogs(request: CreateFlowLogsRequest): CreateFlowLogsResult { return with (context) { request.registerWithAutoName() makeProxy<CreateFlowLogsRequest, CreateFlowLogsResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateFlowLogsRequest::getClientToken to CreateFlowLogsResult::getClientToken ) ) } } override fun createImage(request: CreateImageRequest): CreateImageResult { return with (context) { request.registerWithAutoName() makeProxy<CreateImageRequest, CreateImageResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createInstanceExportTask(request: CreateInstanceExportTaskRequest): CreateInstanceExportTaskResult { return with (context) { request.registerWithAutoName() CreateInstanceExportTaskResult().withExportTask( makeProxy<CreateInstanceExportTaskRequest, ExportTask>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateInstanceExportTaskRequest::getDescription to ExportTask::getDescription ) ) ).registerWithSameNameAs(request) } } override fun createInternetGateway(request: CreateInternetGatewayRequest): CreateInternetGatewayResult { return with (context) { request.registerWithAutoName() CreateInternetGatewayResult().withInternetGateway( makeProxy<CreateInternetGatewayRequest, InternetGateway>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) ).registerWithSameNameAs(request) } } override fun createKeyPair(request: CreateKeyPairRequest): CreateKeyPairResult { return with (context) { request.registerWithAutoName() CreateKeyPairResult().withKeyPair( makeProxy<CreateKeyPairRequest, KeyPair>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateKeyPairRequest::getKeyName to KeyPair::getKeyName ) ) ).registerWithSameNameAs(request) } } override fun createNatGateway(request: CreateNatGatewayRequest): CreateNatGatewayResult { return with (context) { request.registerWithAutoName() CreateNatGatewayResult().withNatGateway( makeProxy<CreateNatGatewayRequest, NatGateway>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateNatGatewayRequest::getSubnetId to NatGateway::getSubnetId ) ) ).registerWithSameNameAs(request) } } override fun createNetworkAcl(request: CreateNetworkAclRequest): CreateNetworkAclResult { return with (context) { request.registerWithAutoName() CreateNetworkAclResult().withNetworkAcl( makeProxy<CreateNetworkAclRequest, NetworkAcl>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateNetworkAclRequest::getVpcId to NetworkAcl::getVpcId ) ) ).registerWithSameNameAs(request) } } override fun createNetworkAclEntry(request: CreateNetworkAclEntryRequest): CreateNetworkAclEntryResult { return with (context) { request.registerWithAutoName() CreateNetworkAclEntryResult().registerWithSameNameAs(request) } } override fun createNetworkInterface(request: CreateNetworkInterfaceRequest): CreateNetworkInterfaceResult { return with (context) { request.registerWithAutoName() CreateNetworkInterfaceResult().withNetworkInterface( makeProxy<CreateNetworkInterfaceRequest, NetworkInterface>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateNetworkInterfaceRequest::getSubnetId to NetworkInterface::getSubnetId, CreateNetworkInterfaceRequest::getDescription to NetworkInterface::getDescription, CreateNetworkInterfaceRequest::getPrivateIpAddress to NetworkInterface::getPrivateIpAddress ) ) ).registerWithSameNameAs(request) } } override fun createPlacementGroup(request: CreatePlacementGroupRequest): CreatePlacementGroupResult { return with (context) { request.registerWithAutoName() CreatePlacementGroupResult().registerWithSameNameAs(request) } } override fun createReservedInstancesListing(request: CreateReservedInstancesListingRequest): CreateReservedInstancesListingResult { return with (context) { request.registerWithAutoName() makeProxy<CreateReservedInstancesListingRequest, CreateReservedInstancesListingResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createRoute(request: CreateRouteRequest): CreateRouteResult { return with (context) { request.registerWithAutoName() makeProxy<CreateRouteRequest, CreateRouteResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createRouteTable(request: CreateRouteTableRequest): CreateRouteTableResult { return with (context) { request.registerWithAutoName() CreateRouteTableResult().withRouteTable( makeProxy<CreateRouteTableRequest, RouteTable>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateRouteTableRequest::getVpcId to RouteTable::getVpcId ) ) ).registerWithSameNameAs(request) } } override fun createSecurityGroup(request: CreateSecurityGroupRequest): CreateSecurityGroupResult { return with (context) { request.registerWithAutoName() makeProxy<CreateSecurityGroupRequest, CreateSecurityGroupResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createSnapshot(request: CreateSnapshotRequest): CreateSnapshotResult { return with (context) { request.registerWithAutoName() CreateSnapshotResult().withSnapshot( makeProxy<CreateSnapshotRequest, Snapshot>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateSnapshotRequest::getVolumeId to Snapshot::getVolumeId, CreateSnapshotRequest::getDescription to Snapshot::getDescription ) ) ).registerWithSameNameAs(request) } } override fun createSpotDatafeedSubscription(request: CreateSpotDatafeedSubscriptionRequest): CreateSpotDatafeedSubscriptionResult { return with (context) { request.registerWithAutoName() CreateSpotDatafeedSubscriptionResult().withSpotDatafeedSubscription( makeProxy<CreateSpotDatafeedSubscriptionRequest, SpotDatafeedSubscription>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateSpotDatafeedSubscriptionRequest::getBucket to SpotDatafeedSubscription::getBucket, CreateSpotDatafeedSubscriptionRequest::getPrefix to SpotDatafeedSubscription::getPrefix ) ) ).registerWithSameNameAs(request) } } override fun createSubnet(request: CreateSubnetRequest): CreateSubnetResult { return with (context) { request.registerWithAutoName() CreateSubnetResult().withSubnet( makeProxy<CreateSubnetRequest, Subnet>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateSubnetRequest::getVpcId to Subnet::getVpcId, CreateSubnetRequest::getCidrBlock to Subnet::getCidrBlock, CreateSubnetRequest::getAvailabilityZone to Subnet::getAvailabilityZone ) ) ).registerWithSameNameAs(request) } } override fun createTags(request: CreateTagsRequest): CreateTagsResult { return with (context) { request.registerWithAutoName() CreateTagsResult().registerWithSameNameAs(request) } } override fun createVolume(request: CreateVolumeRequest): CreateVolumeResult { return with (context) { request.registerWithAutoName() CreateVolumeResult().withVolume( makeProxy<CreateVolumeRequest, Volume>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateVolumeRequest::getSize to Volume::getSize, CreateVolumeRequest::getSnapshotId to Volume::getSnapshotId, CreateVolumeRequest::getAvailabilityZone to Volume::getAvailabilityZone, CreateVolumeRequest::getVolumeType to Volume::getVolumeType, CreateVolumeRequest::getIops to Volume::getIops, CreateVolumeRequest::getEncrypted to Volume::getEncrypted, CreateVolumeRequest::getKmsKeyId to Volume::getKmsKeyId ) ) ).registerWithSameNameAs(request) } } override fun createVpc(request: CreateVpcRequest): CreateVpcResult { return with (context) { request.registerWithAutoName() CreateVpcResult().withVpc( makeProxy<CreateVpcRequest, Vpc>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateVpcRequest::getCidrBlock to Vpc::getCidrBlock, CreateVpcRequest::getInstanceTenancy to Vpc::getInstanceTenancy ) ) ).registerWithSameNameAs(request) } } override fun createVpcEndpoint(request: CreateVpcEndpointRequest): CreateVpcEndpointResult { return with (context) { request.registerWithAutoName() CreateVpcEndpointResult().withVpcEndpoint( makeProxy<CreateVpcEndpointRequest, VpcEndpoint>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateVpcEndpointRequest::getVpcId to VpcEndpoint::getVpcId, CreateVpcEndpointRequest::getServiceName to VpcEndpoint::getServiceName, CreateVpcEndpointRequest::getPolicyDocument to VpcEndpoint::getPolicyDocument, CreateVpcEndpointRequest::getRouteTableIds to VpcEndpoint::getRouteTableIds ) ) ).registerWithSameNameAs(request) } } override fun createVpcPeeringConnection(request: CreateVpcPeeringConnectionRequest): CreateVpcPeeringConnectionResult { return with (context) { request.registerWithAutoName() CreateVpcPeeringConnectionResult().withVpcPeeringConnection( makeProxy<CreateVpcPeeringConnectionRequest, VpcPeeringConnection>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) ).registerWithSameNameAs(request) } } override fun createVpnConnection(request: CreateVpnConnectionRequest): CreateVpnConnectionResult { return with (context) { request.registerWithAutoName() CreateVpnConnectionResult().withVpnConnection( makeProxy<CreateVpnConnectionRequest, VpnConnection>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateVpnConnectionRequest::getType to VpnConnection::getType, CreateVpnConnectionRequest::getCustomerGatewayId to VpnConnection::getCustomerGatewayId, CreateVpnConnectionRequest::getVpnGatewayId to VpnConnection::getVpnGatewayId ) ) ).registerWithSameNameAs(request) } } override fun createVpnConnectionRoute(request: CreateVpnConnectionRouteRequest): CreateVpnConnectionRouteResult { return with (context) { request.registerWithAutoName() CreateVpnConnectionRouteResult().registerWithSameNameAs(request) } } override fun createVpnGateway(request: CreateVpnGatewayRequest): CreateVpnGatewayResult { return with (context) { request.registerWithAutoName() CreateVpnGatewayResult().withVpnGateway( makeProxy<CreateVpnGatewayRequest, VpnGateway>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateVpnGatewayRequest::getType to VpnGateway::getType, CreateVpnGatewayRequest::getAvailabilityZone to VpnGateway::getAvailabilityZone ) ) ).registerWithSameNameAs(request) } } }
mit
0b234170e25f6b43ccaf25eaad8ab7de
42.243534
138
0.591229
6.196726
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/project-configuration/src/org/jetbrains/kotlin/idea/configuration/KotlinSetupEnvironmentNotificationProvider.kt
1
6823
// 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.configuration import com.intellij.ide.JavaUiBundle import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.ListPopup import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotificationProvider import com.intellij.ui.EditorNotificationProvider.CONST_NULL import com.intellij.ui.EditorNotifications import org.jetbrains.kotlin.idea.KotlinLanguage import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.toModuleGroup import org.jetbrains.kotlin.idea.base.util.createComponentActionLabel import org.jetbrains.kotlin.idea.configuration.ui.KotlinConfigurationCheckerService import org.jetbrains.kotlin.idea.projectConfiguration.KotlinNotConfiguredSuppressedModulesState import org.jetbrains.kotlin.idea.projectConfiguration.KotlinProjectConfigurationBundle import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.idea.versions.getLibraryRootsWithIncompatibleAbi import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import java.util.function.Function import javax.swing.JComponent // Code is partially copied from com.intellij.codeInsight.daemon.impl.SetupSDKNotificationProvider class KotlinSetupEnvironmentNotificationProvider : EditorNotificationProvider { override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> { if (!file.isKotlinFileType()) { return CONST_NULL } val psiFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return CONST_NULL if (psiFile.language !== KotlinLanguage.INSTANCE) { return CONST_NULL } val module = ModuleUtilCore.findModuleForPsiElement(psiFile) ?: return CONST_NULL if (!ModuleRootManager.getInstance(module).fileIndex.isInSourceContent(file)) { return CONST_NULL } if (ModuleRootManager.getInstance(module).sdk == null && psiFile.platform.isJvm()) { return createSetupSdkPanel(project, psiFile) } val configurationChecker = KotlinConfigurationCheckerService.getInstance(module.project) if (!configurationChecker.isSyncing && isNotConfiguredNotificationRequired(module.toModuleGroup()) && !hasAnyKotlinRuntimeInScope(module) && getLibraryRootsWithIncompatibleAbi(module).isEmpty() ) { return createKotlinNotConfiguredPanel(module, getAbleToRunConfigurators(module).toList()) } return CONST_NULL } companion object { private fun createSetupSdkPanel(project: Project, file: PsiFile): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor).apply { text = JavaUiBundle.message("project.sdk.not.defined") createActionLabel(ProjectBundle.message("project.sdk.setup")) { ProjectSettingsService.getInstance(project).chooseAndSetSdk() ?: return@createActionLabel runWriteAction { val module = ModuleUtilCore.findModuleForPsiElement(file) if (module != null) { ModuleRootModificationUtil.setSdkInherited(module) } } } } } private fun createKotlinNotConfiguredPanel(module: Module, configurators: List<KotlinProjectConfigurator>): Function<in FileEditor, out JComponent?> = Function { fileEditor: FileEditor -> EditorNotificationPanel(fileEditor).apply { text = KotlinProjectConfigurationBundle.message("kotlin.not.configured") if (configurators.isNotEmpty()) { val project = module.project createComponentActionLabel(KotlinProjectConfigurationBundle.message("action.text.configure")) { label -> val singleConfigurator = configurators.singleOrNull() if (singleConfigurator != null) { singleConfigurator.apply(project) } else { val configuratorsPopup = createConfiguratorsPopup(project, configurators) configuratorsPopup.showUnderneathOf(label) } } createComponentActionLabel(KotlinProjectConfigurationBundle.message("action.text.ignore")) { KotlinNotConfiguredSuppressedModulesState.suppressConfiguration(module) EditorNotifications.getInstance(project).updateAllNotifications() } } } } private fun KotlinProjectConfigurator.apply(project: Project) { configure(project, emptyList()) EditorNotifications.getInstance(project).updateAllNotifications() checkHideNonConfiguredNotifications(project) } fun createConfiguratorsPopup(project: Project, configurators: List<KotlinProjectConfigurator>): ListPopup { val step = object : BaseListPopupStep<KotlinProjectConfigurator>( KotlinProjectConfigurationBundle.message("title.choose.configurator"), configurators ) { override fun getTextFor(value: KotlinProjectConfigurator?) = value?.presentableText ?: "<none>" override fun onChosen(selectedValue: KotlinProjectConfigurator?, finalChoice: Boolean): PopupStep<*>? { return doFinalStep { selectedValue?.apply(project) } } } return JBPopupFactory.getInstance().createListPopup(step) } } }
apache-2.0
76c6194594c5a550515ec28969958025
48.442029
158
0.687381
5.816709
false
true
false
false
siosio/intellij-community
plugins/kotlin/common/src/org/jetbrains/kotlin/idea/PlatformVersion.kt
2
1729
// 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 import com.intellij.openapi.application.ApplicationInfo import com.intellij.util.PlatformUtils data class PlatformVersion(val platform: Platform, val version: String /* 3.1 or 2017.3 */) { companion object { fun parse(platformString: String): PlatformVersion? { for (platform in Platform.values()) { for (qualifier in platform.qualifiers) { if (platformString.startsWith(qualifier)) { return PlatformVersion(platform, platformString.drop(qualifier.length)) } } } return null } fun getCurrent(): PlatformVersion? { val platform = when (PlatformUtils.getPlatformPrefix()) { PlatformUtils.IDEA_CE_PREFIX, PlatformUtils.IDEA_PREFIX -> Platform.IDEA "AndroidStudio" -> Platform.ANDROID_STUDIO // from 'com.android.tools.idea.IdeInfo' else -> return null } val version = ApplicationInfo.getInstance().run { majorVersion + "." + minorVersion.substringBefore(".") } return PlatformVersion(platform, version) } fun isAndroidStudio(): Boolean = getCurrent()?.platform == Platform.ANDROID_STUDIO } enum class Platform(val qualifiers: List<String>, val presentableText: String) { IDEA(listOf("IJ"), "IDEA"), ANDROID_STUDIO(listOf("Studio", "AS"), "Android Studio") } override fun toString() = platform.presentableText + " " + version }
apache-2.0
959b2f9a74714f8df841962b7b2fad86
41.170732
158
0.628109
4.982709
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/util/BookmarkUtil.kt
1
5938
/* * Copyright (c) 2017. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hbfavmaterial.presentation.util import java.util.* class BookmarkUtil private constructor() { companion object { private val COUNT_MONTHS_AT_YEAR = 12 private val COUNT_DAYS_AT_MONTH = 30 private val COUNT_WEEKS_AT_MONTH = 5 private val COUNT_DAYS_AT_WEEK = 7 private val COUNT_HOURS_AT_DAY = 24 private val COUNT_SECONDS_AT_MINUTE = 60 private val COUNT_MILLIS_AT_SECOND = 1000 private val MAX_LENGTH_COMMENT_AT_TWITTER = 100 private val MAX_LENGTH_TITLE_WITH_COMMENT_AT_TWITTER = 10 private val MAX_LENGTH_TITLE_AT_TWITTER = MAX_LENGTH_COMMENT_AT_TWITTER + MAX_LENGTH_TITLE_WITH_COMMENT_AT_TWITTER private val HATENA_CDN_DOMAIN = "http://cdn1.www.st-hatena.com" /** * Twitterのシェア用のテキストを作成する. */ fun createShareText(url: String, title: String, comment: String): String { return if (comment.isNotEmpty()) { val postComment: String val postTitle: String if (MAX_LENGTH_COMMENT_AT_TWITTER < comment.length) { postComment = comment.take(MAX_LENGTH_COMMENT_AT_TWITTER - 1) + "..." postTitle = if (MAX_LENGTH_TITLE_WITH_COMMENT_AT_TWITTER < (title.length)) { title.take(MAX_LENGTH_TITLE_WITH_COMMENT_AT_TWITTER - 1) + "..." } else { title } } else { postComment = comment val postTitleLength = MAX_LENGTH_TITLE_AT_TWITTER - comment.length postTitle = if (postTitleLength < title.length) { title.take(postTitleLength - 1) + "..." } else { title } } "$postComment \"$postTitle\" $url" } else { val postTitle = if (MAX_LENGTH_TITLE_AT_TWITTER < title.length) { title.substring(0, MAX_LENGTH_TITLE_AT_TWITTER - 1) + "..." } else { title } "\"$postTitle\" $url" } } /** * ユーザーのアイコン画像のURLを取得する. */ @JvmStatic fun getIconImageUrlFromId(userId: String): String { return "$HATENA_CDN_DOMAIN/users/${userId.take(2)}/$userId/profile.gif" } /** * ユーザーのアイコン画像(大)のURLを取得する. */ @JvmStatic fun getLargeIconImageUrlFromId(userId: String): String { return "$HATENA_CDN_DOMAIN/users/${userId.take(2)}/$userId/user.jpg" } /** * 日付の差分を計算し表示用に整形する. */ @JvmStatic fun getPastTimeString(bookmarkAddedDatetime: Date, nowCalendar: Calendar = Calendar.getInstance(TimeZone.getDefault())): String { // 時差を考慮してブックマーク追加時間と現在時間の差分を計算. val bookmarkCal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Tokyo")) bookmarkCal.time = bookmarkAddedDatetime val nowInMills = nowCalendar.timeInMillis - nowCalendar.timeZone.rawOffset val bookmarkInMills = bookmarkCal.timeInMillis - bookmarkCal.timeZone.rawOffset val diffSec = (nowInMills - bookmarkInMills) / COUNT_MILLIS_AT_SECOND if (diffSec < COUNT_SECONDS_AT_MINUTE) { return "${diffSec.toString()}秒前" } val diffMinute = diffSec / COUNT_SECONDS_AT_MINUTE if (diffMinute < COUNT_SECONDS_AT_MINUTE) { return "${diffMinute.toString()}分前" } val diffHour = diffMinute / COUNT_SECONDS_AT_MINUTE if (diffHour < COUNT_HOURS_AT_DAY) { return "${diffHour.toString()}時間前" } val diffDay = diffHour / COUNT_HOURS_AT_DAY if (diffDay.toInt() == 1) { return "昨日" } else if (diffDay < COUNT_DAYS_AT_WEEK) { return "${diffDay.toString()}日前" } val diffWeek = diffDay / COUNT_DAYS_AT_WEEK if (diffWeek.toInt() == 1) { return "先週" } else if (diffWeek < COUNT_WEEKS_AT_MONTH) { return "${diffWeek.toString()}週間前" } val diffMonth = diffDay / COUNT_DAYS_AT_MONTH if (diffMonth.toInt() == 1) { return "先月" } else if (diffMonth < COUNT_MONTHS_AT_YEAR) { return "${diffMonth.toString()}ヶ月前" } // 昨年 val diffYear = diffMonth / COUNT_MONTHS_AT_YEAR if (diffYear.toInt() == 1) { return "昨年" } else { return "${diffYear.toString()}年前" } } @JvmStatic fun getPastTimeString(bookmarkAddedDatetime: Date): String { return getPastTimeString(bookmarkAddedDatetime, Calendar.getInstance(TimeZone.getDefault())) } } }
apache-2.0
ea9722395462e6488de240699e71e45a
33.695122
122
0.545343
4.214815
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/planner/issues/violations/vm/CoreDedicationExpectationViolationDetector.kt
2
2913
package com.github.kerubistan.kerub.planner.issues.violations.vm import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.VirtualMachine import com.github.kerubistan.kerub.model.collection.VirtualMachineDataCollection import com.github.kerubistan.kerub.model.expectations.CoreDedicationExpectation import com.github.kerubistan.kerub.planner.OperationalState import com.github.kerubistan.kerub.utils.any import io.github.kerubistan.kroki.collections.concat object CoreDedicationExpectationViolationDetector : AbstractVmHostViolationDetector<CoreDedicationExpectation>() { override fun checkWithHost( entity: VirtualMachine, expectation: CoreDedicationExpectation, state: OperationalState, host: Host ): Boolean { val vmsOnHost by lazy { state.vmDataOnHost(host.id) } val hostCoreCnt by lazy { host.capabilities?.cpus?.sumBy { it.coreCount ?: 0 } ?: 0 } val coredDedicated: (VirtualMachineDataCollection) -> Boolean = { it.stat.expectations.any<CoreDedicationExpectation>() } val vmNrOfCpus: (VirtualMachineDataCollection) -> Int = { it.stat.nrOfCpus } // if this vm has CPU affinity to a smaller nr of cores, than the number of vcpus, that // means this expectation is not met... however I would say that may be true even with // non-dedicated vcpus // to be on the safe side, let's check and break this expectation if so return entity.nrOfCpus <= requireNotNull(state.vms[entity.id]).dynamic?.coreAffinity?.size ?: hostCoreCnt && isUnderUtilized(vmsOnHost, vmNrOfCpus, hostCoreCnt) || isSafelyOverUtilized(vmsOnHost, coredDedicated, vmNrOfCpus, hostCoreCnt) } /** * over-allocation * the vm's without core-dedication are stick to a number of cores * so that the ones with core-dedication have enough cores left * @param vmsOnHost list of virtual machines running on the host */ private fun isSafelyOverUtilized( vmsOnHost: List<VirtualMachineDataCollection>, coredDedicated: (VirtualMachineDataCollection) -> Boolean, vmNrOfCpus: (VirtualMachineDataCollection) -> Int, hostCoreCnt: Int ): Boolean { val vmsByDedication = vmsOnHost.groupBy(coredDedicated) val dedicatedCoreVms = vmsByDedication[true] ?: listOf() val notDedicatedCoreVms = vmsByDedication[false] ?: listOf() val allCpus by lazy { (1..hostCoreCnt).toList() } return notDedicatedCoreVms .map { it.dynamic?.coreAffinity ?: allCpus } .concat().toSet().size + dedicatedCoreVms .sumBy(vmNrOfCpus) < hostCoreCnt } /** * under-utilization * the total of vcpus on the server is less (or equal if this is the only vm on host) * to the cores in the host -> no further enforcement needed, it is fine */ private fun isUnderUtilized( vmsOnHost: List<VirtualMachineDataCollection>, vmNrOfCpus: (VirtualMachineDataCollection) -> Int, hostCoreCnt: Int ) = vmsOnHost.sumBy(vmNrOfCpus) <= hostCoreCnt }
apache-2.0
cb82491c6abc9c374628597eca7c334d
40.042254
114
0.760728
3.587438
false
false
false
false
dahlstrom-g/intellij-community
plugins/svn4idea/src/org/jetbrains/idea/svn/RootsToWorkingCopies.kt
9
4670
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.progress.BackgroundTaskQueue import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.util.ZipperUpdater import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.VcsMappingListener import com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import org.jetbrains.idea.svn.SvnBundle.message import org.jetbrains.idea.svn.SvnUtil.isAncestor import org.jetbrains.idea.svn.api.Url import org.jetbrains.idea.svn.auth.SvnAuthenticationNotifier // 1. listen to roots changes // 2. - possibly - to deletion/checkouts??? what if WC roots can be @Service class RootsToWorkingCopies(private val project: Project) : VcsMappingListener, Disposable { private val myLock = Any() private val myRootMapping = mutableMapOf<VirtualFile, WorkingCopy>() private val myUnversioned = mutableSetOf<VirtualFile>() private val myQueue = BackgroundTaskQueue(project, message("progress.title.svn.roots.authorization.checker")) private val myZipperUpdater = ZipperUpdater(200, this) private val myRechecker = Runnable { clear() val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs) for (root in roots) { addRoot(root) } } private val vcs: SvnVcs get() = SvnVcs.getInstance(project) init { project.messageBus.connect().subscribe(VCS_CONFIGURATION_CHANGED, this) } private fun addRoot(root: VirtualFile) { myQueue.run(object : Task.Backgroundable(project, message("progress.title.looking.for.file.working.copy.root", root.path), false) { override fun run(indicator: ProgressIndicator) { calculateRoot(root) } }) } @RequiresBackgroundThread fun getMatchingCopy(url: Url?): WorkingCopy? { assert(!ApplicationManager.getApplication().isDispatchThread || ApplicationManager.getApplication().isUnitTestMode) if (url == null) return null val roots = ProjectLevelVcsManager.getInstance(project).getRootsUnderVcs(vcs) synchronized(myLock) { for (root in roots) { val wcRoot = getWcRoot(root) if (wcRoot != null && (isAncestor(wcRoot.url, url) || isAncestor(url, wcRoot.url))) { return wcRoot } } } return null } @RequiresBackgroundThread fun getWcRoot(root: VirtualFile): WorkingCopy? { assert(!ApplicationManager.getApplication().isDispatchThread || ApplicationManager.getApplication().isUnitTestMode) synchronized(myLock) { if (myUnversioned.contains(root)) return null val existing = myRootMapping[root] if (existing != null) return existing } return calculateRoot(root) } private fun calculateRoot(root: VirtualFile): WorkingCopy? { val workingCopyRoot = SvnUtil.getWorkingCopyRoot(virtualToIoFile(root)) var workingCopy: WorkingCopy? = null if (workingCopyRoot != null) { val svnInfo = vcs.getInfo(workingCopyRoot) if (svnInfo != null && svnInfo.url != null) { workingCopy = WorkingCopy(workingCopyRoot, svnInfo.url) } } return registerWorkingCopy(root, workingCopy) } private fun registerWorkingCopy(root: VirtualFile, resolvedWorkingCopy: WorkingCopy?): WorkingCopy? { synchronized(myLock) { if (resolvedWorkingCopy == null) { myRootMapping.remove(root) myUnversioned.add(root) } else { myUnversioned.remove(root) myRootMapping[root] = resolvedWorkingCopy } } return resolvedWorkingCopy } override fun dispose() = clearData() fun clear() { clearData() myZipperUpdater.stop() } private fun clearData() = synchronized(myLock) { myRootMapping.clear() myUnversioned.clear() } override fun directoryMappingChanged() { // todo +- here... shouldnt be SvnAuthenticationNotifier.getInstance(project).clear() myZipperUpdater.queue(myRechecker) } companion object { @JvmStatic fun getInstance(project: Project): RootsToWorkingCopies = project.service() } }
apache-2.0
201e9eafa8183ca7c7eec2551a5570dd
33.087591
140
0.737045
4.304147
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConvertPairConstructorToToFunctionInspection.kt
3
2362
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class ConvertPairConstructorToToFunctionInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return callExpressionVisitor { expression -> if (expression.isPairConstructorCall()) { holder.registerProblem( expression, KotlinBundle.message("can.be.converted.to.to"), ConvertPairConstructorToToFix() ) } } } } private class ConvertPairConstructorToToFix : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.pair.constructor.to.to.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtCallExpression ?: return val args = expression.valueArguments.mapNotNull { it.getArgumentExpression() }.toTypedArray() expression.replace(KtPsiFactory(expression).createExpressionByPattern("$0 to $1", *args)) } } private fun KtCallExpression.isPairConstructorCall(): Boolean { if (valueArguments.size != 2) return false if (valueArguments.mapNotNull { it.getArgumentExpression() }.size != 2) return false return getCallableDescriptor()?.containingDeclaration?.fqNameSafe == FqName("kotlin.Pair") }
apache-2.0
390d6152c47f7fc4cc01acf3afb4e95c
45.313725
158
0.762489
5.057816
false
false
false
false
SDS-Studios/ScoreKeeper
app/src/main/java/io/github/sdsstudios/ScoreKeeper/Activity/OptionActivity.kt
1
2310
package io.github.sdsstudios.ScoreKeeper.Activity import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import io.github.sdsstudios.ScoreKeeper.Fragment.DeleteTimeLimitsFragment import io.github.sdsstudios.ScoreKeeper.Fragment.OptionFragment import io.github.sdsstudios.ScoreKeeper.Fragment.RecyclerViewFragment import io.github.sdsstudios.ScoreKeeper.R import io.github.sdsstudios.ScoreKeeper.ViewModels.TimeLimitViewModel /** * Created by sethsch1 on 23/12/17. */ abstract class OptionActivity(toolbarTitle: Int) : BaseTabActivity<RecyclerViewFragment<*>>( toolbarTitle = toolbarTitle, isBackButtonEnabled = true, layoutName = R.layout.activity_tabs_with_fab ) { private lateinit var mTimeLimitViewModel: TimeLimitViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mTimeLimitViewModel = ViewModelProviders.of(this).get(TimeLimitViewModel::class.java) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_option, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item!!.itemId) { R.id.action_delete_time_limits -> { if (mTimeLimitViewModel.timeLimitList.value!!.isEmpty()) { Toast.makeText(this, R.string.msg_you_havent_created_any_time_limits, Toast.LENGTH_SHORT) .show() return false } DeleteTimeLimitsFragment.showDialog(this) } } return super.onOptionsItemSelected(item) } override fun onBackPressed() { showAlertDialog( message = getString(R.string.msg_quit_set_up), negativeButtonText = getString(R.string.neg_cancel), positiveButtonText = getString(R.string.pos_quit), onPosClick = { super.onBackPressed() }) } fun anyErrorsInOptions() = optionFragment.anyErrorsInOptions() override fun onDialogShown() {} abstract val optionFragment: OptionFragment<*, *, *> }
gpl-3.0
fa5c1ada99f9e1157bb4fd5b91e2d8e8
32.985294
93
0.67013
4.842767
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/RemapIDsVisitor.kt
2
3913
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.diagnostic.hprof.visitors import com.intellij.diagnostic.hprof.classstore.HProfMetadata import com.intellij.diagnostic.hprof.parser.* import com.intellij.diagnostic.hprof.util.FileBackedHashMap import it.unimi.dsi.fastutil.longs.Long2IntOpenHashMap import java.nio.ByteBuffer import java.nio.channels.FileChannel import java.util.function.LongUnaryOperator abstract class RemapIDsVisitor : HProfVisitor() { private var currentID = 0 override fun preVisit() { disableAll() enable(HeapDumpRecordType.ClassDump) enable(HeapDumpRecordType.InstanceDump) enable(HeapDumpRecordType.PrimitiveArrayDump) enable(HeapDumpRecordType.ObjectArrayDump) currentID = 1 } override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type, primitiveArrayData: ByteBuffer) { addMapping(arrayObjectId, currentID++) } override fun visitClassDump(classId: Long, stackTraceSerialNumber: Long, superClassId: Long, classloaderClassId: Long, instanceSize: Long, constants: Array<ConstantPoolEntry>, staticFields: Array<StaticFieldEntry>, instanceFields: Array<InstanceFieldEntry>) { addMapping(classId, currentID++) } override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) { addMapping(arrayObjectId, currentID++) } override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) { addMapping(objectId, currentID++) } abstract fun addMapping(oldId: Long, newId: Int) abstract fun getRemappingFunction(): LongUnaryOperator companion object { fun createMemoryBased(): RemapIDsVisitor { val map = Long2IntOpenHashMap() map.put(0, 0) return object : RemapIDsVisitor() { override fun addMapping(oldId: Long, newId: Int) { map.put(oldId, newId) } override fun getRemappingFunction(): LongUnaryOperator { return LongUnaryOperator { map.get(it).toLong() } } } } fun createFileBased(channel: FileChannel, maxInstanceCount: Long): RemapIDsVisitor { val remapIDsMap = FileBackedHashMap.createEmpty( channel, maxInstanceCount, KEY_SIZE, VALUE_SIZE) return object : RemapIDsVisitor() { override fun addMapping(oldId: Long, newId: Int) { remapIDsMap.put(oldId).putInt(newId) } override fun getRemappingFunction(): LongUnaryOperator { return LongUnaryOperator { operand -> if (operand == 0L) 0L else { if (remapIDsMap.containsKey(operand)) remapIDsMap[operand]!!.int.toLong() else throw HProfMetadata.RemapException() } } } } } fun isSupported(instanceCount: Long): Boolean { return FileBackedHashMap.isSupported(instanceCount, KEY_SIZE, VALUE_SIZE) } private const val KEY_SIZE = 8 private const val VALUE_SIZE = 4 } }
apache-2.0
b829892beba9e1b1fd105a96b6121275
34.261261
166
0.674419
4.725845
false
false
false
false
alisle/Penella
src/test/java/org/penella/query/QueryProcessorTest.kt
1
1651
package org.penella.query import org.junit.Assert import org.junit.Test import org.penella.database.DatabaseImpl import org.penella.database.IDatabase import org.penella.index.bstree.BSTreeIndexFactory import org.penella.store.BSTreeStore import org.penella.structures.triples.Triple /** * 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/3/17. */ class QueryProcessorTest { @Test fun testSimple() { val store = BSTreeStore(665445839L) val db : IDatabase = DatabaseImpl("Test DB", store, BSTreeIndexFactory(), 10) val processor = QueryProcessor(db, store) val testTriples = ( 0 to 5 ).toList().map { Triple("Test-Subject", "Property", "Object-$it") }; testTriples.forEach { db.add(it) } db.bulkAdd((0L until 10000L).map { x -> Triple("Subject " + x, "Property " + x, "Object " + x) }.toTypedArray()) val query = Query(arrayOf("?Subject"), arrayOf("?Subject", "?Object"), arrayOf(Triple("?Subject", "Property", "?Object"))) val results = processor.process(query) results.forEach { x -> Assert.assertTrue(testTriples.contains(x)) } } }
apache-2.0
95ef6768f4023fa993342f92f1be4ace
39.292683
130
0.700787
3.875587
false
true
false
false
jwren/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/gradle/configuration/kpm/ModuleDataInitializer.kt
1
2246
// 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.gradle.configuration.kpm import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.kotlin.config.ExternalSystemRunTask import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKotlinFragment import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKotlinProjectModel import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext interface ModuleDataInitializer { fun initialize( gradleModule: IdeaModule, mainModuleNode: DataNode<ModuleData>, projectDataNode: DataNode<ProjectData>, resolverCtx: ProjectResolverContext, initializerContext: Context ) interface Context { //TODO replace with Key-Value registry with proper visibility and immutability var model: IdeaKotlinProjectModel? var jdkName: String? var moduleGroup: Array<String>? var mainModuleConfigPath: String? var mainModuleFileDirectoryPath: String? var sourceSetToRunTasks: Map<IdeaKotlinFragment, Collection<ExternalSystemRunTask>> companion object { @JvmStatic val EMPTY: Context get() = object : Context { override var model: IdeaKotlinProjectModel? = null override var jdkName: String? = null override var moduleGroup: Array<String>? = null override var mainModuleConfigPath: String? = null override var mainModuleFileDirectoryPath: String? = null override var sourceSetToRunTasks: Map<IdeaKotlinFragment, Collection<ExternalSystemRunTask>> = emptyMap() } } } companion object { @JvmField val EP_NAME: ExtensionPointName<ModuleDataInitializer> = ExtensionPointName.create("org.jetbrains.kotlin.kpm.moduleInitialize") } }
apache-2.0
d349c1a21e7c12b4fcfcd652d399b01f
43.058824
125
0.710151
5.284706
false
true
false
false
jwren/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/external/ExternalDiffSettings.kt
1
6218
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diff.tools.external import com.intellij.diff.util.DiffUtil import com.intellij.openapi.components.* import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.util.text.StringUtil import com.intellij.util.PathUtilRt import com.intellij.util.xmlb.annotations.OptionTag import org.jetbrains.annotations.NonNls @State(name = "ExternalDiffSettings", storages = [Storage(DiffUtil.DIFF_CONFIG)], category = SettingsCategory.TOOLS) class ExternalDiffSettings : BaseState(), PersistentStateComponent<ExternalDiffSettings> { override fun getState(): ExternalDiffSettings = this override fun loadState(state: ExternalDiffSettings) { migrateOldSettings(state) copyFrom(state) } @get:OptionTag("MIGRATE_OLD_SETTINGS") var isSettingsMigrated by property(false) @get:OptionTag("EXTERNAL_TOOLS_ENABLED") var isExternalToolsEnabled: Boolean by property(false) @get:OptionTag("EXTERNAL_TOOLS_CONFIGURATION") var externalToolsConfiguration: MutableList<ExternalToolConfiguration> by list() @get:OptionTag("EXTERNAL_TOOLS") var externalTools: MutableMap<ExternalToolGroup, List<ExternalTool>> by map() @get:OptionTag("DEFAULT_TOOL_CONFIGURATION") var defaultToolConfiguration: ExternalToolConfiguration by property(ExternalToolConfiguration.builtinInstance) { it == ExternalToolConfiguration.builtinInstance } data class ExternalToolConfiguration( @NonNls var fileTypeName: String = DEFAULT_TOOL_NAME, @NonNls var diffToolName: String = BUILTIN_TOOL, @NonNls var mergeToolName: String = BUILTIN_TOOL ) { companion object { @NonNls const val DEFAULT_TOOL_NAME = "Default" @NonNls const val BUILTIN_TOOL = "Built-in" val builtinInstance = ExternalToolConfiguration() } } enum class ExternalToolGroup(val groupName: String) { DIFF_TOOL("Diff tool"), MERGE_TOOL("Merge tool") } data class ExternalTool( @NonNls var name: String = "", var programPath: String = "", var argumentPattern: String = "", var isMergeTrustExitCode: Boolean = false, var groupName: ExternalToolGroup = ExternalToolGroup.DIFF_TOOL ) // OLD SETTINGS AREA @get:OptionTag("DIFF_ENABLED") var isDiffEnabled: Boolean by property(false) @get:OptionTag("DIFF_EXE_PATH") var diffExePath: String by nonNullString() @get:OptionTag("DIFF_PARAMETERS") var diffParameters: String by nonNullString("%1 %2 %3") @get:OptionTag("MERGE_ENABLED") var isMergeEnabled: Boolean by property(false) @get:OptionTag("MERGE_EXE_PATH") var mergeExePath: String by nonNullString() @get:OptionTag("MERGE_PARAMETERS") var mergeParameters: String by nonNullString("%1 %2 %3 %4") @get:OptionTag("MERGE_TRUST_EXIT_CODE") var isMergeTrustExitCode: Boolean by property(false) // ^^^ OLD SETTINGS AREA private fun nonNullString(initialValue: String = "") = property(initialValue) { it == initialValue } companion object { @JvmStatic val instance: ExternalDiffSettings get() = service() private val fileTypeManager get() = FileTypeManager.getInstance() @JvmStatic fun findDiffTool(fileType: FileType): ExternalTool? { val diffToolName = findToolConfiguration(fileType)?.diffToolName ?: instance.defaultToolConfiguration.diffToolName if (diffToolName == ExternalToolConfiguration.BUILTIN_TOOL) return null val diffTools = instance.externalTools[ExternalToolGroup.DIFF_TOOL] ?: return null return findTool(diffTools, diffToolName) } @JvmStatic fun findMergeTool(fileType: FileType): ExternalTool? { val mergeToolName = findToolConfiguration(fileType)?.mergeToolName ?: instance.defaultToolConfiguration.mergeToolName if (mergeToolName == ExternalToolConfiguration.BUILTIN_TOOL) return null val mergeTools = instance.externalTools[ExternalToolGroup.MERGE_TOOL] ?: return null return findTool(mergeTools, mergeToolName) } @JvmStatic fun isNotBuiltinDiffTool(): Boolean { return instance.defaultToolConfiguration.diffToolName != ExternalToolConfiguration.BUILTIN_TOOL } @JvmStatic fun isNotBuiltinMergeTool(): Boolean { return instance.defaultToolConfiguration.mergeToolName != ExternalToolConfiguration.BUILTIN_TOOL } private fun findTool(tools: List<ExternalTool>, toolName: String): ExternalTool? = tools.find { it.name == toolName } private fun findToolConfiguration(fileType: FileType): ExternalToolConfiguration? = instance.externalToolsConfiguration.find { fileTypeManager.findFileTypeByName(it.fileTypeName) == fileType } private fun migrateOldSettings(state: ExternalDiffSettings) { if (!state.isSettingsMigrated) { // load old settings state.isExternalToolsEnabled = state.isDiffEnabled || state.isMergeEnabled // save old settings state.defaultToolConfiguration = ExternalToolConfiguration().apply { if (state.diffExePath.isNotEmpty()) { val oldDiffTool = ExternalTool(StringUtil.capitalize(PathUtilRt.getFileName(state.diffExePath)), state.diffExePath, state.diffParameters, false, ExternalToolGroup.DIFF_TOOL) state.externalTools[ExternalToolGroup.DIFF_TOOL] = listOf(oldDiffTool) diffToolName = oldDiffTool.name } if (state.mergeExePath.isNotEmpty()) { val oldMergeTool = ExternalTool(StringUtil.capitalize(PathUtilRt.getFileName(state.mergeExePath)), state.mergeExePath, state.mergeParameters, state.isMergeTrustExitCode, ExternalToolGroup.MERGE_TOOL) state.externalTools[ExternalToolGroup.MERGE_TOOL] = listOf(oldMergeTool) mergeToolName = oldMergeTool.name } } state.isSettingsMigrated = true } } } }
apache-2.0
50041849942e18272887d249054166d4
36.457831
140
0.713091
4.857813
false
true
false
false
GunoH/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/test/junit/JUnitAssertEqualsMayBeAssertSameInspection.kt
2
2518
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection.test.junit import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInspection.* import com.intellij.psi.* import com.intellij.psi.util.PsiUtil import com.intellij.uast.UastHintedVisitorAdapter import com.siyeh.ig.testFrameworks.UAssertHint import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UExpression import org.jetbrains.uast.visitor.AbstractUastNonRecursiveVisitor class JUnitAssertEqualsMayBeAssertSameInspection : AbstractBaseUastLocalInspectionTool(), CleanupLocalInspectionTool { private fun shouldInspect(file: PsiFile) = isJUnit3InScope(file) || isJUnit4InScope(file) || isJUnit5InScope(file) override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { if (!shouldInspect(holder.file)) return PsiElementVisitor.EMPTY_VISITOR return UastHintedVisitorAdapter.create( holder.file.language, JUnitAssertEqualsMayBeAssertSameVisitor(holder), arrayOf(UCallExpression::class.java), directOnly = true ) } } private class JUnitAssertEqualsMayBeAssertSameVisitor(private val holder: ProblemsHolder) : AbstractUastNonRecursiveVisitor() { override fun visitCallExpression(node: UCallExpression): Boolean { val assertHint = UAssertHint.createAssertEqualsUHint(node) ?: return true if (!couldBeAssertSameArgument(assertHint.firstArgument)) return true if (!couldBeAssertSameArgument(assertHint.secondArgument)) return true val message = JvmAnalysisBundle.message("jvm.inspections.junit.assertequals.may.be.assertsame.problem.descriptor") holder.registerUProblem(node, message, ReplaceMethodCallFix("assertSame")) return true } private fun couldBeAssertSameArgument(expression: UExpression): Boolean { val argumentClass = PsiUtil.resolveClassInClassTypeOnly(expression.getExpressionType()) ?: return false if (!argumentClass.hasModifierProperty(PsiModifier.FINAL)) return false val methods = argumentClass.findMethodsByName("equals", true) val project = expression.sourcePsi?.project ?: return false val objectClass = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_OBJECT, argumentClass.resolveScope) ?: return false for (method in methods) if (objectClass != method.containingClass) return false return true } }
apache-2.0
c58be6080c056991f62f9deec8783ec3
51.479167
130
0.797855
4.927593
false
false
false
false