repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rahulsom/grooves
grooves-diagrams/src/main/kotlin/com/github/rahulsom/grooves/asciidoctor/EventsBlock.kt
1
1499
package com.github.rahulsom.grooves.asciidoctor import org.asciidoctor.ast.StructuralNode import org.asciidoctor.extension.BlockProcessor import org.asciidoctor.extension.Reader import java.io.File import java.math.BigInteger import java.security.MessageDigest /** * Renders an Events block as SVG. * * @author Rahul Somasunderam */ class EventsBlock(name: String) : BlockProcessor(name, mapOf("contexts" to listOf(":literal"), "content_model" to ":simple")) { override fun process(parent: StructuralNode, reader: Reader, attributes: MutableMap<String, Any>?): Any { val projectDirAttr = parent.document.attributes["gradle-projectdir"] as String val outDir = File(projectDirAttr, "build/docs/asciidoc") val input = reader.readLines().joinToString("\n") var filename = (attributes ?: emptyMap()).get("2") as String? ?: md5(input) filename = if (filename.endsWith(".svg")) filename else "$filename.svg" SvgBuilder(input).write(File(outDir, filename)) val newAttributes = mapOf<String, Any>( "type" to ":image", "target" to filename, "format" to "svg" ) return createBlock(parent, "image", input, newAttributes, attributes?.mapKeys { it }) } private fun md5(input: String) = MessageDigest.getInstance("MD5").let { md5 -> md5.update(input.toByteArray()) val hash = BigInteger(1, md5.digest()) hash.toString(16) } }
apache-2.0
6d6c2b06bdb93d29857d0c2733dbb1e6
33.090909
109
0.66044
3.986702
false
false
false
false
geckour/Egret
app/src/main/java/com/geckour/egret/api/MastodonClient.kt
1
6193
package com.geckour.egret.api import com.geckour.egret.App.Companion.gson import com.geckour.egret.api.model.* import com.geckour.egret.api.service.MastodonService import com.geckour.egret.util.OkHttpProvider import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import okhttp3.MultipartBody import okhttp3.ResponseBody import retrofit2.Retrofit import retrofit2.adapter.rxjava2.Result import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory class MastodonClient(baseUrl: String) { private val service = Retrofit.Builder() .client(OkHttpProvider.client) .baseUrl("https://$baseUrl/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(MastodonService::class.java) private val streamService = Retrofit.Builder() .client(OkHttpProvider.streamClient) .baseUrl("https://$baseUrl/") .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(MastodonService::class.java) fun registerApp(): Single<UserSpecificApp> = service.registerApp() fun authUser( clientId: String, clientSecret: String, username: String, password: String ): Single<InstanceAccess> = service.authUser(clientId, clientSecret, username, password) fun getOwnAccount(): Single<Account> = service.getOwnAccount() fun getAccount(accountId: Long): Single<Account> = service.getAccount(accountId) fun updateOwnAccount(displayName: String? = null, note: String? = null, avatarUrl: String? = null, headerUrl: String? = null): Single<Any> = service.updateOwnAccount(displayName, note, avatarUrl, headerUrl) fun getPublicTimelineAsStream(): Observable<ResponseBody> = streamService.getPublicTimelineAsStream() fun getLocalTimelineAsStream(): Observable<ResponseBody> = streamService.getLocalTimelineAsStream() fun getUserTimelineAsStream(): Observable<ResponseBody> = streamService.getUserTimelineAsStream() fun getNotificationTimelineAsStream(): Observable<ResponseBody> = streamService.getUserTimelineAsStream() fun getHashTagTimelineAsStream(hashTag: String): Observable<ResponseBody> = streamService.getHashTagTimelineAsStream(hashTag) fun getPublicTimeline(isLocal: Boolean = false, maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Status>>> = service.getPublicTimeline(isLocal, maxId, sinceId) fun getHashTagTimeline(hashTag: String, isLocal: Boolean = false, maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Status>>> = service.getHashTagTimeline(hashTag, isLocal, maxId, sinceId) fun getUserTimeline(maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Status>>> = service.getUserTimeline(maxId, sinceId) fun getNotificationTimeline(maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Notification>>> = service.getNotificationTimeline(maxId, sinceId) fun getFavouriteTimeline(maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Status>>> = service.getFavouriteTimeline(maxId, sinceId) fun getAccountAllToots(accountId: Long, maxId: Long? = null, sinceId: Long? = null): Single<Result<List<Status>>> = service.getAccountAllToots(accountId, maxId, sinceId) fun favoriteByStatusId(statusId: Long): Single<Status> = service.favoriteStatusById(statusId) fun unFavoriteByStatusId(statusId: Long): Single<Status> = service.unFavoriteStatusById(statusId) fun reblogByStatusId(statusId: Long): Single<Status> = service.reblogStatusById(statusId) fun unReblogByStatusId(statusId: Long): Single<Status> = service.unReblogStatusById(statusId) fun getStatusByStatusId(statusId: Long): Single<Status> = service.getStatusById(statusId) fun getAccountRelationships(vararg accountId: Long): Single<List<Relationship>> = service.getAccountRelationships(*accountId) fun followAccount(accountId: Long): Single<Relationship> = service.followAccount(accountId) fun unFollowAccount(accountId: Long): Single<Relationship> = service.unFollowAccount(accountId) fun blockAccount(accountId: Long): Single<Relationship> = service.blockAccount(accountId) fun unBlockAccount(accountId: Long): Single<Relationship> = service.unBlockAccount(accountId) fun muteAccount(accountId: Long): Single<Relationship> = service.muteAccount(accountId) fun unMuteAccount(accountId: Long): Single<Relationship> = service.unMuteAccount(accountId) fun postNewToot( body: String, inReplyToId: Long? = null, mediaIds: List<Long>? = null, isSensitive: Boolean? = null, spoilerText: String? = null, visibility: MastodonService.Visibility? = null ): Single<Status> = service.postNewToot(body, inReplyToId, mediaIds, isSensitive, spoilerText, visibility?.name) fun deleteToot(statusId: Long): Completable = service.deleteToot(statusId) fun postNewMedia(body: MultipartBody.Part): Single<Attachment> = service.postNewMedia(body) fun getMutedUsers( maxId: Long? = null, sinceId: Long? = null ): Single<List<Account>> = service.getMutedUsers(maxId, sinceId) fun getMutedUsersWithHeaders( maxId: Long? = null, sinceId: Long? = null ): Single<Result<List<Account>>> = service.getMutedUsersWithHeaders(maxId, sinceId) fun getBlockedUsers( maxId: Long? = null, sinceId: Long? = null ): Single<List<Account>> = service.getBlockedUsers(maxId, sinceId) fun getBlockedUsersWithHeaders( maxId: Long? = null, sinceId: Long? = null ): Single<Result<List<Account>>> = service.getBlockedUsersWithHeaders(maxId, sinceId) fun search(query: String): Single<com.geckour.egret.api.model.Result> = service.search(query) fun getContextOfStatus(statusId: Long): Single<Context> = service.getContextOfStatus(statusId) }
gpl-3.0
5da44f8314a492242b61bcb551138288
45.924242
210
0.730018
4.401564
false
false
false
false
square/duktape-android
zipline-bytecode/src/main/kotlin/app/cash/zipline/bytecode/JsObjectWriter.kt
1
4352
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.bytecode import okio.BufferedSink import okio.Closeable /** * Encodes a [JsObject] as bytes. * * @param atoms the mapping from string to integer used to encode the object. If the object was * decoded with a [JsObjectReader], it should be encoded with the same atoms. */ class JsObjectWriter( private val atoms: AtomSet, private val sink: BufferedSink ) : Closeable by sink { private var used: Boolean = false fun writeJsObject(value: JsObject) { check(!used) used = true writeAtoms() writeObjectRecursive(value) } private fun writeAtoms() { sink.writeByte(BC_VERSION) sink.writeLeb128(atoms.strings.size) for (s in atoms.strings) { writeJsString(s) } } private fun writeJsString(value: JsString) { if (value.isWideChar) { val stringLength = value.bytes.size / 2 sink.writeLeb128((stringLength shl 1) or 0x1) sink.write(value.bytes) } else { val stringLength = value.bytes.size sink.writeLeb128((stringLength shl 1) or 0x0) sink.write(value.bytes) } } private fun writeObjectRecursive(value: JsObject) { when (value) { is JsNull -> sink.writeByte(BC_TAG_NULL) is JsUndefined -> sink.writeByte(BC_TAG_UNDEFINED) is JsBoolean -> { val tag = when { value.value -> BC_TAG_BOOL_TRUE else -> BC_TAG_BOOL_FALSE } sink.writeByte(tag) } is JsInt -> { sink.writeByte(BC_TAG_INT32) sink.writeSleb128(value.value) } is JsDouble -> { sink.writeByte(BC_TAG_FLOAT64) sink.writeLong(value.value.toRawBits()) } is JsString -> { sink.writeByte(BC_TAG_STRING) writeJsString(value) } is JsFunctionBytecode -> { sink.writeByte(BC_TAG_FUNCTION_BYTECODE) writeFunction(value) } } } private fun writeFunction(value: JsFunctionBytecode) { sink.writeShort(value.flags) sink.writeByte(value.jsMode.toInt()) writeAtom(value.name.toJsString()) sink.writeLeb128(value.argCount) sink.writeLeb128(value.varCount) sink.writeLeb128(value.definedArgCount) sink.writeLeb128(value.stackSize) sink.writeLeb128(value.closureVars.size) sink.writeLeb128(value.constantPool.size) sink.writeLeb128(value.bytecode.size) sink.writeLeb128(value.locals.size) for (local in value.locals) { writeVarDef(local) } for (closureVar in value.closureVars) { writeClosureVar(closureVar) } // TODO: fixup atoms within bytecode? sink.write(value.bytecode) if (value.debug != null) { writeDebug(value.debug) } for (constant in value.constantPool) { writeObjectRecursive(constant) } } private fun writeAtom(value: JsString) { val valueAndType = atoms.idOf(value) shl 1 sink.writeLeb128(valueAndType) } private fun writeVarDef(value: JsVarDef) { writeAtom(value.name.toJsString()) sink.writeLeb128(value.scopeLevel) sink.writeLeb128(value.scopeNext + 1) sink.writeByte( value.kind or value.isConst.toBit(4) or value.isLexical.toBit(5) or value.isCaptured.toBit(6) ) } private fun writeClosureVar(value: JsClosureVar) { writeAtom(value.name.toJsString()) sink.writeLeb128(value.varIndex) sink.writeByte( value.isLocal.toBit(0) or value.isArg.toBit(1) or value.isConst.toBit(2) or value.isLexical.toBit(3) or (value.kind shl 4) ) } private fun writeDebug(debug: Debug) { writeAtom(debug.fileName.toJsString()) sink.writeLeb128(debug.lineNumber) sink.writeLeb128(debug.pc2Line.size) sink.write(debug.pc2Line) } }
apache-2.0
a797caf8a42778c40ca3319b5cdbf40a
26.371069
95
0.665901
3.570139
false
false
false
false
vilnius/tvarkau-vilniu
app/src/test/java/lt/vilnius/tvarkau/fragments/interactors/MultipleReportsMapInteractorImplTest.kt
1
2486
package lt.vilnius.tvarkau.fragments.interactors import com.nhaarman.mockito_kotlin.* import com.vinted.preferx.StringPreference import io.reactivex.Single import io.reactivex.schedulers.Schedulers import lt.vilnius.tvarkau.backend.LegacyApiService import lt.vilnius.tvarkau.entity.Problem import lt.vilnius.tvarkau.events_listeners.RefreshReportFilterEvent import lt.vilnius.tvarkau.rx.RxBus import lt.vilnius.tvarkau.wrapInResponse import org.junit.Before import org.junit.Test /** * @author Martynas Jurkus */ class MultipleReportsMapInteractorImplTest { private val api = mock<LegacyApiService>() private val reportType = mock<StringPreference>() private val reportStatus = mock<StringPreference>() private val allReportsTitle = "All" private val fixture: MultipleReportsMapInteractor = MultipleReportsMapInteractorImpl( api, Schedulers.trampoline(), reportType, reportStatus, allReportsTitle ) private val reports = listOf(Problem(id = "1"), Problem(id = "2")) @Before fun setUp() { whenever(reportType.get()).thenReturn("") whenever(reportStatus.get()).thenReturn("") whenever(api.getProblems(any())).thenReturn(reports.wrapInResponse) } @Test fun emptyCache_apiHit() { fixture.getReports() .test() .assertValue(reports) verify(api).getProblems(any()) } @Test fun cacheHit_noApiRequest() { whenever(api.getProblems(any())) .thenReturn(reports.wrapInResponse) .thenReturn(Single.error(IllegalStateException("Unexpected API call"))) fixture.getReports().subscribe() fixture.getReports() .test() .assertNoErrors() .assertValue(reports) } @Test fun emptyCache_apiHit_noResults_error() { whenever(api.getProblems(any())).thenReturn(listOf<Problem>().wrapInResponse) fixture.getReports() .test() .assertError(MultipleReportsMapInteractorImpl.NoMapReportsError::class.java) verify(api).getProblems(any()) } @Test fun mapRefresh_cacheCleared() { fixture.getReports().subscribe() RxBus.publish(RefreshReportFilterEvent()) fixture.getReports().subscribe() verify(api, times(2)).getProblems(any()) } }
mit
6b54867bc2cb3b392a4dcd149647df53
28.258824
92
0.642397
4.63806
false
true
false
false
flutter/flutter
dev/benchmarks/platform_channels_benchmarks/android/app/src/main/kotlin/com/example/platform_channels_benchmarks/MainActivity.kt
3
2191
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.platform_channels_benchmarks import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.BasicMessageChannel import io.flutter.plugin.common.BinaryCodec import io.flutter.plugin.common.StandardMessageCodec import java.nio.ByteBuffer class MainActivity: FlutterActivity() { // We allow for the caching of a response in the binary channel case since // the reply requires a direct buffer, but the input is not a direct buffer. // We can't directly send the input back to the reply currently. private var byteBufferCache : ByteBuffer? = null override fun configureFlutterEngine(flutterEngine: FlutterEngine) { val reset = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.reset", StandardMessageCodec.INSTANCE) reset.setMessageHandler { message, reply -> run { byteBufferCache = null } } val basicStandard = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.basic.standard", StandardMessageCodec.INSTANCE) basicStandard.setMessageHandler { message, reply -> reply.reply(message) } val basicBinary = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.basic.binary", BinaryCodec.INSTANCE_DIRECT) basicBinary.setMessageHandler { message, reply -> run { if (byteBufferCache == null) { byteBufferCache = ByteBuffer.allocateDirect(message!!.capacity()) byteBufferCache!!.put(message) } reply.reply(byteBufferCache) } } val taskQueue = flutterEngine.dartExecutor.getBinaryMessenger().makeBackgroundTaskQueue(); val backgroundStandard = BasicMessageChannel(flutterEngine.dartExecutor, "dev.flutter.echo.background.standard", StandardMessageCodec.INSTANCE, taskQueue) backgroundStandard.setMessageHandler { message, reply -> reply.reply(message) } super.configureFlutterEngine(flutterEngine) } }
bsd-3-clause
e8ea129f6339fb1d61afc45cf10fb232
55.179487
162
0.742127
4.847345
false
true
false
false
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/app/settings/repository/SettingsRepository.kt
1
2074
package de.christinecoenen.code.zapp.app.settings.repository import android.annotation.SuppressLint import android.content.Context import android.os.Build import androidx.appcompat.app.AppCompatDelegate import androidx.preference.PreferenceManager import de.christinecoenen.code.zapp.R import java.util.* class SettingsRepository(context: Context) { private val context = context.applicationContext private val preferences = PreferenceManager.getDefaultSharedPreferences(context) val lockVideosInLandcapeFormat: Boolean get() = preferences.getBoolean(context.getString(R.string.pref_key_detail_landscape), true) val meteredNetworkStreamQuality: StreamQualityBucket @SuppressLint("DefaultLocale") get() = preferences.getString(context.getString(R.string.pref_key_stream_quality_over_metered_network), null).let { quality -> if (quality == null) { StreamQualityBucket.DISABLED } else { StreamQualityBucket.valueOf(quality.uppercase(Locale.ENGLISH)) } } val downloadOverUnmeteredNetworkOnly: Boolean get() = preferences.getBoolean(context.getString(R.string.pref_key_download_over_unmetered_network_only), true) var isPlayerZoomed: Boolean get() = preferences.getBoolean(context.getString(R.string.pref_key_player_zoomed), false) set(enabled) { preferences.edit() .putBoolean(context.getString(R.string.pref_key_player_zoomed), enabled) .apply() } val downloadToSdCard: Boolean get() = preferences.getBoolean(context.getString(R.string.pref_key_download_to_sd_card), true) val uiMode: Int get() { val uiMode = preferences.getString(context.getString(R.string.pref_key_ui_mode), null) return prefValueToUiMode(uiMode) } fun prefValueToUiMode(prefSetting: String?): Int { val defaultMode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM else AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY return when (prefSetting) { "light" -> AppCompatDelegate.MODE_NIGHT_NO "dark" -> AppCompatDelegate.MODE_NIGHT_YES else -> defaultMode } } }
mit
bcbd66caf5df63da38541ef24a016c7b
32.451613
128
0.770492
3.644991
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/view/activity/SignInActivity.kt
1
4738
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.view.activity import android.arch.lifecycle.Observer import android.content.Intent import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v7.app.AppCompatActivity import com.toshi.R import com.toshi.extensions.getViewModel import com.toshi.extensions.isVisible import com.toshi.extensions.startActivity import com.toshi.extensions.toast import com.toshi.util.KeyboardUtil import com.toshi.util.sharedPrefs.AppPrefs import com.toshi.viewModel.SignInViewModel import kotlinx.android.synthetic.main.activity_sign_in.closeButton import kotlinx.android.synthetic.main.activity_sign_in.infoView import kotlinx.android.synthetic.main.activity_sign_in.keyboard import kotlinx.android.synthetic.main.activity_sign_in.loadingSpinner import kotlinx.android.synthetic.main.activity_sign_in.passphraseInputView import kotlinx.android.synthetic.main.activity_sign_in.signIn class SignInActivity : AppCompatActivity() { companion object { private const val PASSPHRASE_LENGTH = 12 } private lateinit var viewModel: SignInViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_in) init() } private fun init() { initViewModel() initClickListeners() initSignInPassphraseView() initObservers() } private fun initViewModel() { viewModel = getViewModel() } private fun initClickListeners() { closeButton.setOnClickListener { finish() } infoView.setOnClickListener { startActivity<SignInInfoActivity>() } signIn.setOnClickListener { handleSignInClicked() } } private fun initSignInPassphraseView() { passphraseInputView.apply { setOnPassphraseFinishListener { handlePassphraseFinished() } setOnPassphraseUpdateListener { updateSignInButton(it) } setOnKeyboardListener { keyboard.showKeyboard() } } } private fun handlePassphraseFinished() { signIn.setText(R.string.sign_in) signIn.setBackgroundResource(R.drawable.background_with_radius_primary_color) signIn.isEnabled = true } private fun updateSignInButton(approvedWords: Int) { val wordsLeft = PASSPHRASE_LENGTH - approvedWords if (wordsLeft > 0) { val wordsLeftString = resources.getQuantityString(R.plurals.words, wordsLeft, wordsLeft) disableSignIn(wordsLeftString) } } private fun disableSignIn(string: String) { signIn.text = string signIn.setBackgroundResource(R.drawable.background_with_radius_disabled) signIn.isEnabled = false } private fun handleSignInClicked() { val approvedWords = passphraseInputView.approvedWordList if (approvedWords.size != PASSPHRASE_LENGTH) { toast(R.string.sign_in_length_error_message) return } val masterSeed = approvedWords.joinToString(" ") viewModel.tryCreateWallet(masterSeed) } private fun initObservers() { viewModel.isLoading.observe(this, Observer { if (it != null) loadingSpinner.isVisible(it) }) viewModel.passphrase.observe(this, Observer { if (it != null) passphraseInputView.setWordList(it as ArrayList<String>) }) viewModel.walletSuccess.observe(this, Observer { if (it != null) goToMainActivity() }) viewModel.error.observe(this, Observer { if (it != null) toast(it) }) } private fun goToMainActivity() { KeyboardUtil.hideKeyboard(passphraseInputView) AppPrefs.setSignedIn() startActivity<MainActivity> { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) } ActivityCompat.finishAffinity(this) } override fun onBackPressed() { if (keyboard.isVisible()) keyboard.hideKeyboard() else super.onBackPressed() } }
gpl-3.0
2db6481837a004f030e908b5dfb58750
33.845588
100
0.697552
4.586641
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CategoryCollectionFragment.kt
1
3069
package com.boardgamegeek.ui import android.os.Bundle import android.view.* import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentLinkedCollectionBinding import com.boardgamegeek.ui.adapter.LinkedCollectionAdapter import com.boardgamegeek.ui.viewmodel.CategoryViewModel import com.boardgamegeek.ui.viewmodel.CategoryViewModel.CollectionSort import java.util.* class CategoryCollectionFragment : Fragment() { private var _binding: FragmentLinkedCollectionBinding? = null private val binding get() = _binding!! private var sortType = CollectionSort.RATING private val viewModel by activityViewModels<CategoryViewModel>() private val adapter: LinkedCollectionAdapter by lazy { LinkedCollectionAdapter() } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentLinkedCollectionBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.adapter = adapter binding.emptyMessage.text = getString(R.string.empty_linked_collection, getString(R.string.title_category).lowercase(Locale.getDefault())) binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() } viewModel.sort.observe(viewLifecycleOwner) { sortType = it activity?.invalidateOptionsMenu() } viewModel.collection.observe(viewLifecycleOwner) { adapter.items = it.orEmpty() binding.emptyMessage.isVisible = adapter.items.isEmpty() binding.recyclerView.isVisible = adapter.items.isNotEmpty() binding.swipeRefresh.isRefreshing = false binding.progressView.hide() } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.linked_collection, menu) } override fun onPrepareOptionsMenu(menu: Menu) { menu.findItem( when (sortType) { CollectionSort.NAME -> R.id.menu_sort_name CollectionSort.RATING -> R.id.menu_sort_rating } )?.isChecked = true super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menu_sort_name -> viewModel.setSort(CollectionSort.NAME) R.id.menu_sort_rating -> viewModel.setSort(CollectionSort.RATING) R.id.menu_refresh -> viewModel.refresh() else -> return super.onOptionsItemSelected(item) } return true } }
gpl-3.0
20fe7c7d305866afe7a6a36207518717
37.848101
146
0.703161
4.957997
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/ArticleActivity.kt
1
5522
package com.boardgamegeek.ui import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.fragment.app.Fragment import com.boardgamegeek.R import com.boardgamegeek.entities.ArticleEntity import com.boardgamegeek.entities.ForumEntity import com.boardgamegeek.extensions.link import com.boardgamegeek.extensions.share import com.boardgamegeek.extensions.startActivity import com.boardgamegeek.provider.BggContract import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.logEvent import timber.log.Timber class ArticleActivity : SimpleSinglePaneActivity() { private var threadId = BggContract.INVALID_ID private var threadSubject = "" private var forumId = BggContract.INVALID_ID private var forumTitle = "" private var objectId = BggContract.INVALID_ID private var objectName = "" private var objectType = ForumEntity.ForumType.REGION private var article = ArticleEntity() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (article.id == BggContract.INVALID_ID) { Timber.w("Invalid article ID") finish() } if (objectName.isBlank()) { supportActionBar?.title = forumTitle supportActionBar?.subtitle = threadSubject } else { supportActionBar?.title = "$threadSubject - $forumTitle" supportActionBar?.subtitle = objectName } if (savedInstanceState == null) { firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) { param(FirebaseAnalytics.Param.CONTENT_TYPE, "Article") param(FirebaseAnalytics.Param.ITEM_ID, article.id.toString()) param(FirebaseAnalytics.Param.ITEM_NAME, threadSubject) } } } override fun readIntent(intent: Intent) { threadId = intent.getIntExtra(KEY_THREAD_ID, BggContract.INVALID_ID) threadSubject = intent.getStringExtra(KEY_THREAD_SUBJECT).orEmpty() forumId = intent.getIntExtra(KEY_FORUM_ID, BggContract.INVALID_ID) forumTitle = intent.getStringExtra(KEY_FORUM_TITLE).orEmpty() objectId = intent.getIntExtra(KEY_OBJECT_ID, BggContract.INVALID_ID) objectName = intent.getStringExtra(KEY_OBJECT_NAME).orEmpty() objectType = intent.getSerializableExtra(KEY_OBJECT_TYPE) as ForumEntity.ForumType article = intent.getParcelableExtra(KEY_ARTICLE) ?: ArticleEntity() } override fun onCreatePane(intent: Intent): Fragment { return ArticleFragment.newInstance(article) } override val optionsMenuId = R.menu.view_share override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { ThreadActivity.startUp(this, threadId, threadSubject, forumId, forumTitle, objectId, objectName, objectType) finish() } R.id.menu_view -> { link(article.link) } R.id.menu_share -> { val description = if (objectName.isEmpty()) String.format(getString(R.string.share_thread_article_text), threadSubject, forumTitle) else String.format(getString(R.string.share_thread_article_object_text), threadSubject, forumTitle, objectName) val message = """ $description ${article.link}""".trimIndent() share(getString(R.string.share_thread_subject), message, R.string.title_share) firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE) { param(FirebaseAnalytics.Param.ITEM_ID, article.id.toString()) param( FirebaseAnalytics.Param.ITEM_NAME, if (objectName.isEmpty()) "$forumTitle | $threadSubject" else "$objectName | $forumTitle | $threadSubject" ) param(FirebaseAnalytics.Param.CONTENT_TYPE, "Article") } } else -> return super.onOptionsItemSelected(item) } return true } companion object { private const val KEY_FORUM_ID = "FORUM_ID" private const val KEY_FORUM_TITLE = "FORUM_TITLE" private const val KEY_OBJECT_ID = "OBJECT_ID" private const val KEY_OBJECT_NAME = "OBJECT_NAME" private const val KEY_OBJECT_TYPE = "OBJECT_TYPE" private const val KEY_THREAD_ID = "THREAD_ID" private const val KEY_THREAD_SUBJECT = "THREAD_SUBJECT" private const val KEY_ARTICLE = "ARTICLE" fun start( context: Context, threadId: Int, threadSubject: String?, forumId: Int, forumTitle: String?, objectId: Int, objectName: String?, objectType: ForumEntity.ForumType?, article: ArticleEntity? ) { context.startActivity<ArticleActivity>( KEY_THREAD_ID to threadId, KEY_THREAD_SUBJECT to threadSubject, KEY_FORUM_ID to forumId, KEY_FORUM_TITLE to forumTitle, KEY_OBJECT_ID to objectId, KEY_OBJECT_NAME to objectName, KEY_OBJECT_TYPE to objectType, KEY_ARTICLE to article, ) } } }
gpl-3.0
4d334d7c6251830e41db57f4fa44820e
39.306569
130
0.627852
4.970297
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/stats/time/FileDownloadsRestClient.kt
2
3213
package org.wordpress.android.fluxc.network.rest.wpcom.stats.time import android.content.Context import com.android.volley.RequestQueue import com.google.gson.Gson import com.google.gson.annotations.SerializedName import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WPCOMREST import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.store.StatsStore.FetchStatsPayload import org.wordpress.android.fluxc.store.toStatsError import java.util.Date import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class FileDownloadsRestClient @Inject constructor( dispatcher: Dispatcher, private val wpComGsonRequestBuilder: WPComGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent, val gson: Gson, private val statsUtils: StatsUtils ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchFileDownloads( site: SiteModel, granularity: StatsGranularity, date: Date, itemsToLoad: Int, forced: Boolean ): FetchStatsPayload<FileDownloadsResponse> { val url = WPCOMREST.sites.site(site.siteId).stats.file_downloads.urlV1_1 val params = mapOf( "period" to granularity.toString(), "num" to itemsToLoad.toString(), "date" to statsUtils.getFormattedDate(date) ) val response = wpComGsonRequestBuilder.syncGetRequest( this, url, params, FileDownloadsResponse::class.java, enableCaching = false, forced = forced ) return when (response) { is Success -> { FetchStatsPayload(response.data) } is Error -> { FetchStatsPayload(response.error.toStatsError()) } } } data class FileDownloadsResponse( @SerializedName("period") val statsGranularity: String?, @SerializedName("date") val date: String?, @SerializedName("days") val groups: Map<String, Group> ) { data class Group( @SerializedName("other_downloads") val otherDownloads: Int?, @SerializedName("total_downloads") val totalDownloads: Int?, @SerializedName("files") val files: List<File> ) data class File( @SerializedName("filename") val filename: String?, @SerializedName("downloads") val downloads: Int? ) } }
gpl-2.0
3226090edeb41542c888a8dcf0523e28
37.710843
94
0.694055
4.731959
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/RoverView.kt
1
8574
package io.rover.sdk.experiences.ui import android.content.Context import android.os.Build import com.google.android.material.appbar.AppBarLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import com.google.android.material.snackbar.Snackbar import androidx.swiperefreshlayout.widget.CircularProgressDrawable import androidx.appcompat.app.ActionBar import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.Toolbar import android.util.AttributeSet import android.view.Gravity import android.view.Menu import android.view.View import android.view.Window import android.view.WindowManager import io.rover.experiences.R import io.rover.sdk.experiences.ui.containers.RoverActivity import io.rover.sdk.experiences.ui.navigation.NavigationView import io.rover.sdk.experiences.ui.toolbar.ViewExperienceToolbar import io.rover.sdk.experiences.logging.log import io.rover.sdk.core.streams.androidLifecycleDispose import io.rover.sdk.core.streams.subscribe import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView import io.rover.sdk.experiences.ui.concerns.ViewModelBinding import io.rover.sdk.experiences.platform.whenNotNull import org.reactivestreams.Publisher /** * Embed this view to include a Rover Experience in a layout. * * Most applications will likely want to use [RoverActivity] to display an Experience, but for * more custom setups (say, tablet-enabled single-activity apps that avoid fragments), you can embed * [RoverView] directly, although you will need to do a few more things manually. * * In order to display an Experience, instantiate RoverViewModel and set it to * [viewModelBinding]. * * Note about Android state restoration: Rover SDK views handle state saving & restoration through * their view models, so you will need store a Parcelable on behalf of RoverView and * [RoverViewModel] (grabbing the state Parcelable from the view model at save time and * restoring it by passing it to the view model factory at restart time). * * See [RoverActivity] for an example of how to integrate. */ internal class RoverView : CoordinatorLayout, MeasuredBindableView<RoverViewModelInterface> { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) override var viewModelBinding: MeasuredBindableView.Binding<RoverViewModelInterface>? by ViewModelBinding(rebindingAllowed = false) { binding, subscriptionCallback -> // sadly have to set rebindingAllowed to be false because of complexity dealing with the // toolbar; the toolbar may not be configured twice. val viewModel = binding?.viewModel val toolbarHost = toolbarHost ?: throw RuntimeException("You must set the ToolbarHost up on RoverView before binding the view to a view model.") navigationView.viewModelBinding = null if (viewModel != null) { viewModel.events.androidLifecycleDispose(this).subscribe({ event -> when (event) { is RoverViewModelInterface.Event.DisplayError -> { Snackbar.make(this, R.string.rover_experiences_fetch_failure, Snackbar.LENGTH_LONG).show() log.w("Unable to retrieve experience: ${event.engineeringReason}") } else -> Unit } }, { error -> throw error }, { subscription -> subscriptionCallback(subscription) }) viewModel.actionBar.androidLifecycleDispose(this).subscribe({ toolbarViewModel -> // regenerate and replace the toolbar val newToolbar = viewExperienceToolbar.setViewModelAndReturnToolbar( toolbarViewModel ) connectToolbar(newToolbar) }, { throw(it) }, { subscriptionCallback(it) }) val window = toolbarHost.provideWindow() viewModel.extraBrightBacklight.androidLifecycleDispose(this).subscribe({ extraBright -> if (extraBright) { window.attributes = (window.attributes ?: WindowManager.LayoutParams()).apply { screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL } }}, { throw(it) }, { subscriptionCallback(it) }) viewModel.navigationViewModel.androidLifecycleDispose(this).subscribe({ experienceNavigationViewModel -> navigationView.viewModelBinding = MeasuredBindableView.Binding( experienceNavigationViewModel ) turnOffProgressIndicator() }, { throw(it) }, { subscriptionCallback(it) }) viewModel.loadingState.androidLifecycleDispose(this).subscribe({ loadingState -> if (loadingState) { turnOnProgressIndicator() } else { turnOffProgressIndicator() } }, { throw(it) }, { subscriptionCallback(it) }) viewModel.fetchOrRefresh() } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() toolbarHost = null } private var progressIndicatorView: View? = null private fun setUpProgressIndicator() { val drawable = CircularProgressDrawable(context) drawable.start() val imageView = AppCompatImageView( context ) progressIndicatorView = imageView imageView.setImageDrawable(drawable) addView(imageView) (imageView.layoutParams as LayoutParams).apply { width = 40.dpAsPx(context.resources.displayMetrics) height = 40.dpAsPx(context.resources.displayMetrics) gravity = Gravity.CENTER_HORIZONTAL or Gravity.CENTER_VERTICAL } } private fun turnOnProgressIndicator() { progressIndicatorView?.visibility = View.VISIBLE } private fun turnOffProgressIndicator() { progressIndicatorView?.visibility = View.GONE } private var toolbar: Toolbar? = null private val navigationView: NavigationView = NavigationView(context) private val appBarLayout = AppBarLayout(context) init { addView( navigationView ) (navigationView.layoutParams as LayoutParams).apply { behavior = AppBarLayout.ScrollingViewBehavior() width = LayoutParams.MATCH_PARENT height = LayoutParams.MATCH_PARENT } val appBarLayout = appBarLayout addView(appBarLayout) (appBarLayout.layoutParams as LayoutParams).apply { width = LayoutParams.MATCH_PARENT height = LayoutParams.WRAP_CONTENT } setUpProgressIndicator() } interface ToolbarHost { /** * The ExperiencesView will generate the toolbar and lay it out within it's own view. * * However, for it to work completely, it needs to be set as the Activity's (Fragment?) * toolbar. * * In response to this, the Activity will provide an ActionBar (and then, after a small * delay, a Menu). */ fun setToolbarAsActionBar(toolbar: Toolbar): Publisher<Pair<ActionBar, Menu>> fun provideWindow(): Window } var toolbarHost: ToolbarHost? = null set(host) { field = host originalStatusBarColor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { host?.provideWindow()?.statusBarColor ?: 0 } else 0 } private var originalStatusBarColor: Int = 0 // this is set as a side-effect of the attached window private fun connectToolbar(newToolbar: Toolbar) { toolbar.whenNotNull { appBarLayout.removeView(it) } appBarLayout.addView(newToolbar) (newToolbar.layoutParams as AppBarLayout.LayoutParams).apply { scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS } toolbar = newToolbar } private val viewExperienceToolbar by lazy { val toolbarHost = toolbarHost ?: throw RuntimeException("You must set the ToolbarHost up on RoverView before binding the view to a view model.") ViewExperienceToolbar( this, toolbarHost.provideWindow(), this.context, toolbarHost ) } }
apache-2.0
2110c8a57514a69787aac2b6de7d9114
38.694444
170
0.671449
5.171291
false
false
false
false
ageery/kwicket
kwicket-wicket-extensions/src/main/kotlin/org/kwicket/wicket/extensions/markup/html/repeater/util/KSortableDataProvider.kt
1
2225
package org.kwicket.wicket.extensions.markup.html.repeater.util import org.apache.wicket.extensions.markup.html.repeater.util.SortParam import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider import org.apache.wicket.model.IModel /** * Extension of [SortableDataProvider] where the implementations are provided by lambdas. * * @param T the type of object in the data provider * @param S the type of the sort for the data provider * @property count lambda that counts the number of items in the data provider * @property items lambda that returns a [Sequence] of items in the data provider; the lambda parameters are: * offset, limit, optional sort and whether the sort is ascending * @property modeler lambda that converts an item in the data provider into a model of an item in the data provider * @param initialSort how tht data provider is initially sorted */ open class KSortableDataProvider<T, S>( val count: () -> Long, val items: (Long, Long, S?, Boolean) -> Sequence<T>, val modeler: (T) -> IModel<T>, initialSort: SortParam<S>? = null ) : SortableDataProvider<T, S>() { init { initialSort?.let { sort = it } } /** * @param count lambda that counts the number of items in the data provider * @param items lambda that returns a [Sequence] of items in the data provider; the lambda parameters are: * offset, limit, optional sort and whether the sort is ascending * @param modeler lambda that converts an item in the data provider into a model of an item in the data provider * @param initialSort property on which to sort the data provider; the sort is ascending */ constructor( count: () -> Long, items: (Long, Long, S?, Boolean) -> Sequence<T>, modeler: (T) -> IModel<T>, initialSort: S ) : this( count = count, items = items, modeler = modeler, initialSort = initialSort?.let { SortParam(it, true) } ) override fun iterator(first: Long, count: Long): Iterator<T> = items(first, count, sort?.property, sort?.isAscending != false).iterator() override fun size(): Long = count() override fun model(value: T): IModel<T> = modeler(value) }
apache-2.0
a827d14a7c9f97f25d6b849f4c0a7c48
42.647059
116
0.697079
4.030797
false
false
false
false
ageery/kwicket
kwicket-sample/src/main/kotlin/org/kwicket/sample/ManageCustomersPage.kt
1
9188
package org.kwicket.sample import de.agilecoders.wicket.core.markup.html.bootstrap.form.FormType import de.agilecoders.wicket.core.markup.html.bootstrap.form.InputBehavior import de.agilecoders.wicket.core.markup.html.bootstrap.image.GlyphIconType import kotlinx.coroutines.experimental.delay import kotlinx.html.span import org.apache.wicket.Component import org.apache.wicket.event.Broadcast import org.apache.wicket.event.IEvent import org.apache.wicket.model.IModel import org.apache.wicket.spring.injection.annot.SpringBean import org.kwicket.agilecoders.wicket.core.ajax.markup.html.KBootstrapAjaxLink import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.button.KBootstrapAjaxButton import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.form.KBootstrapForm import org.kwicket.agilecoders.wicket.core.markup.html.bootstrap.dialog.PanelModal import org.kwicket.agilecoders.wicket.core.markup.html.bootstrap.table.KTableBehavior import org.kwicket.behavior.AsyncModelLoadBehavior import org.kwicket.kotlinx.html.RegionInfoPanel import org.kwicket.kotlinx.html.panel import org.kwicket.kotlinx.html.region import org.kwicket.component.q import org.kwicket.component.refresh import org.kwicket.kotlinx.html.div import org.kwicket.kotlinx.html.span import org.kwicket.model.AsyncLoadableDetachableModel import org.kwicket.model.ldm import org.kwicket.model.model import org.kwicket.model.res import org.kwicket.model.value import org.kwicket.wicket.core.markup.html.KWebMarkupContainer import org.kwicket.wicket.core.markup.html.basic.KLabel import org.kwicket.wicket.core.markup.html.form.KTextField import org.kwicket.wicket.extensions.ajax.markup.html.repeater.data.table.KAjaxFallbackDefaultDataTable import org.kwicket.wicket.extensions.markup.html.repeater.data.table.KLambdaColumn import org.kwicket.wicket.extensions.markup.html.repeater.data.table.LinkColumn import org.kwicket.wicket.extensions.markup.html.repeater.util.KSortableDataProvider import org.wicketstuff.annotation.mount.MountPath import java.time.LocalDateTime import java.util.concurrent.TimeUnit @MountPath("/") class ManageCustomersPage : BasePage() { @SpringBean private lateinit var customerService: CustomerService private val table: Component private val modal: PanelModal = q(PanelModal(id = "modal")) private fun weather(model: IModel<String>) = region().panel { div(builder = { KWebMarkupContainer(id = it) }) { span { +"The weather today at " } span(builder = { KLabel(id = it, model = { LocalDateTime.now().toLocalTime() }.ldm()) }) span { +" is " } span(model = model) } } init { q(NamePanel(id = "name", model = "Lu Xun".model())) q(RegionInfoPanel(id = "weather", model = "Sunny".model(), region = ::weather)) q(TimePanel(id = "time", model = "my house".res())) q( KLabel( id = "t1", model = AsyncLoadableDetachableModel(block = { delay(time = 3, unit = TimeUnit.SECONDS) LocalDateTime.now() }), behaviors = listOf(AsyncModelLoadBehavior()) ) ) q( KLabel( id = "t2", model = AsyncLoadableDetachableModel(block = { delay(time = 3, unit = TimeUnit.SECONDS) LocalDateTime.now() }), behaviors = listOf(AsyncModelLoadBehavior()) ) ) q( KLabel( id = "t3", model = AsyncLoadableDetachableModel(block = { delay(time = 3, unit = TimeUnit.SECONDS) LocalDateTime.now() }) ) ) val searchModel: IModel<String?> = null.model() val form = q( KBootstrapForm( id = "form", model = searchModel, type = FormType.Inline, outputMarkupId = true ) ) table = q( KAjaxFallbackDefaultDataTable<Customer, CustomerSort>( id = "table", outputMarkupId = true, columns = listOf( KLambdaColumn(displayModel = "First Name".model(), sort = CustomerSort.FirstName, function = { it.firstName }), KLambdaColumn(displayModel = "Last Name".model(), sort = CustomerSort.LastName, function = { it.lastName }), LinkColumn(displayModel = "Action".model(), links = { id, model -> listOf( KBootstrapAjaxLink(id = id, model = model, icon = GlyphIconType.remove, onClick = { target, link -> link.send( link, Broadcast.BUBBLE, DeleteEvent(target = target, content = model.value) ) }), KBootstrapAjaxLink(id = id, model = model, icon = GlyphIconType.edit, onClick = { target, _ -> modal.show(target = target, panel = { EditCustomerPanel(it, model.value.toEdit.model()) }) }) ) }) ), dataProvider = KSortableDataProvider(count = { customerService.count(term = searchModel.value).toLong() }, items = { first, count, sort, asc -> customerService.find( term = searchModel.value, sort = sort, asc = asc, first = first.toInt(), count = count.toInt() ) }, modeler = { it.model() }), rowsPerPage = 10, behaviors = listOf(KTableBehavior(hover = true, bordered = true, condensed = true, striped = true)) ) ) q( KTextField( id = "search", model = searchModel, behaviors = listOf(InputBehavior()) ) ) q( KBootstrapAjaxButton(id = "searchButton", icon = GlyphIconType.search, model = "Search".model(), onSubmit = { _, _ -> table.refresh() }) ) q( KBootstrapAjaxButton(id = "addButton", icon = GlyphIconType.plus, model = "Add".model(), onSubmit = { target, _ -> modal.show(target = target, panel = { EditCustomerPanel(it, EditCustomer().model()) }) }) ) q( KBootstrapAjaxButton(id = "resetButton", defaultFormProcessing = false, icon = GlyphIconType.refresh, model = "Reset".model(), onSubmit = { _, _ -> searchModel.value = null form.clearInput() form.refresh() table.refresh() }) ) } override fun onEvent(event: IEvent<*>) { super.onEvent(event) val payload = event.payload when (payload) { is CancelEvent -> { modal.close(payload.target) info(msg = "Edit Canceled".model()) } is SaveEvent<*> -> when (payload.content) { is EditCustomer -> { modal.close(payload.target) val customer = payload.content.fromEdit val fullname = customer.fullName val action = if (payload.content.id == null) "added" else "updated" if (payload.content.id == null) customerService.insert(customer) else customerService.update( customer ) success( msg = { "Customer '${fullname}' successfully ${action}" }.ldm(), refresh = *arrayOf(table) ) } } is DeleteEvent<*> -> when (payload.content) { is Customer -> { val fullname = payload.content.fullName customerService.delete(payload.content) success( msg = { "Customer '${fullname}' successfully deleted" }.ldm(), refresh = *arrayOf(table) ) } } } } }
apache-2.0
a21234fb535ea5c283f31cf0d28de3f1
40.579186
117
0.513605
5.012548
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/MessageView.kt
1
4433
package com.pr0gramm.app.ui import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.OnClickListener import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import androidx.annotation.StringRes import com.pr0gramm.app.Duration import com.pr0gramm.app.Instant import com.pr0gramm.app.R import com.pr0gramm.app.Settings import com.pr0gramm.app.api.pr0gramm.Message import com.pr0gramm.app.api.pr0gramm.MessageType import com.pr0gramm.app.feed.ContentType import com.pr0gramm.app.services.UserService import com.pr0gramm.app.ui.views.SenderInfoView import com.pr0gramm.app.util.* import com.pr0gramm.app.util.di.injector import com.squareup.picasso.Picasso /** */ class MessageView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) { private val userDrawables: UserDrawables = UserDrawables(context) private val admin: Boolean private val text: TextView private val image: ImageView private val sender: SenderInfoView private val messageType: TextView? private val picasso: Picasso? private val scoreVisibleThreshold = Instant.now() - Duration.hours(1) init { val layoutId = context.theme.obtainStyledAttributes(attrs, R.styleable.MessageView, 0, 0).use { it.getResourceId(R.styleable.MessageView_viewLayout, R.layout.message_view) } View.inflate(context, layoutId, this) text = find(R.id.message_text) image = find(R.id.message_image) sender = find(R.id.message_sender_info) messageType = findOptional(R.id.message_type) if (!isInEditMode) { picasso = context.injector.instance() val userService = context.injector.instance<UserService>() admin = userService.userIsAdmin } else { admin = false picasso = null } } fun setAnswerClickedListener(@StringRes text: Int, listener: (View) -> Unit) { sender.setOnAnswerClickedListener(text, OnClickListener { listener(it) }) } fun clearAnswerClickedListener() { sender.clearOnAnswerClickedListener() } fun setOnSenderClickedListener(listener: () -> Unit) { sender.setOnSenderClickedListener(listener) } @JvmOverloads fun update(message: Message, name: String? = null) { // the text of the message Linkify.linkifyClean(text, message.message) // draw the image for this post val thumbnail = message.thumbnail if (thumbnail != null) { val contentTypes = Settings.contentType val blurImage = ContentType.firstOf(message.flags) !in contentTypes val url = "https://thumb.pr0gramm.com/$thumbnail" picasso?.load(url)?.let { req -> if (blurImage) { req.transform(BlurTransformation(12)) } req.placeholder(R.color.grey_800) req.into(image) } } else { picasso?.cancelRequest(image) // set a colored drawable with the first two letters of the user image.setImageDrawable(userDrawables.drawable(message)) } // show the points val visible = name != null && message.name.equals(name, ignoreCase = true) || message.creationTime.isBefore(scoreVisibleThreshold) // sender info sender.setSenderName(message.name, message.mark) sender.setDate(message.creationTime) // message type if available. messageType?.let { messageType -> val type = when (message.type) { MessageType.COMMENT -> R.string.message_type_comment MessageType.MESSAGE -> R.string.message_type_message MessageType.STALK -> R.string.message_type_stalk else -> R.string.message_type_notification } messageType.setText(type) } // set the type. if we have an item, we have a comment if (message.type === MessageType.COMMENT) { if (admin || visible) { sender.setPoints(message.score) } else { sender.setPointsUnknown() } } else { sender.hidePointView() } } }
mit
09a034395188b2e48d615ec61d981fbc
32.330827
159
0.644485
4.406561
false
false
false
false
lfkdsk/JustDB
src/transaction/record/SetStringLogRecord.kt
1
1431
package transaction.record import core.BufferManager import core.JustDB import logger.LogRecord import storage.Block /** * write string to file => generateStringLogRecord * Created by liufengkai on 2017/5/1. */ class SetStringLogRecord(val justDB: JustDB, val transaction: Int, val block: Block, val offset: Int, val value: String) : AbsLogRecord(justDB) { constructor(justDB: JustDB, logRecord: LogRecord) : this(justDB, logRecord.nextInt(), Block(logRecord.nextString(), logRecord.nextInt()), logRecord.nextInt(), logRecord.nextString()) override fun writeToLog(): Int { val rec = listOf(LogType.SETSTRING.value, transaction, block.fileName, block.blockNumber, offset, value) return logManager.append(rec) } override fun op(): LogType { return LogType.SETSTRING } override fun transactionNumber(): Int { return transaction } /** * undo write string to file * @param transaction transaction ID */ override fun undo(transaction: Int) { val bufferManager = justDB.BufferManager() val buffer = bufferManager.pin(block) buffer?.let { block -> buffer.setString(offset, value, transaction, -1) bufferManager.unpin(block) } } override fun toString(): String { return "<SetStringLogRecord(transactionID=$transaction, block=$block, offset=$offset, value='$value')>" } }
apache-2.0
5d7602f75ce957917eb0f73222f127f0
24.571429
106
0.677848
3.975
false
false
false
false
facebook/flipper
android/src/main/java/com/facebook/flipper/plugins/uidebugger/descriptors/FragmentSupportDescriptor.kt
1
2088
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.flipper.plugins.uidebugger.descriptors import androidx.fragment.app.Fragment import com.facebook.flipper.plugins.uidebugger.model.Bounds import com.facebook.flipper.plugins.uidebugger.model.Inspectable import com.facebook.flipper.plugins.uidebugger.model.InspectableObject import com.facebook.flipper.plugins.uidebugger.model.InspectableValue import com.facebook.flipper.plugins.uidebugger.model.MetadataId class FragmentSupportDescriptor(val register: DescriptorRegister) : ChainedDescriptor<androidx.fragment.app.Fragment>() { private val NAMESPACE = "Fragment" private var SectionId = MetadataRegister.register(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, NAMESPACE) override fun onGetName(node: androidx.fragment.app.Fragment): String { return node.javaClass.simpleName } override fun onGetBounds(node: Fragment): Bounds = Bounds(0, 0, 0, 0) override fun onGetChildren(node: androidx.fragment.app.Fragment): List<Any> = node.view?.let { view -> listOf(view) } ?: listOf() override fun onGetData( node: androidx.fragment.app.Fragment, attributeSections: MutableMap<MetadataId, InspectableObject> ) { val args = node.arguments args?.let { bundle -> val props = mutableMapOf<Int, Inspectable>() for (key in bundle.keySet()) { val metadata = MetadataRegister.get(NAMESPACE, key) val identifier = metadata?.id ?: MetadataRegister.registerDynamic(MetadataRegister.TYPE_ATTRIBUTE, NAMESPACE, key) when (val value = bundle[key]) { is Number -> props[identifier] = InspectableValue.Number(value) is Boolean -> props[identifier] = InspectableValue.Boolean(value) is String -> props[identifier] = InspectableValue.Text(value) } } attributeSections[SectionId] = InspectableObject(props.toMap()) } } }
mit
e3e085e0ba3a8a71f0c8077390dc9d59
36.963636
100
0.725096
4.386555
false
false
false
false
d3xter/bo-android
app/src/main/java/org/blitzortung/android/map/overlay/StrikeOverlayItem.kt
1
3590
/* Copyright 2015 Andreas Würl 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.blitzortung.android.map.overlay import android.graphics.Point import android.graphics.drawable.Drawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.Shape import com.google.android.maps.GeoPoint import com.google.android.maps.OverlayItem import com.google.android.maps.Projection import org.blitzortung.android.data.Coordsys import org.blitzortung.android.data.beans.RasterParameters import org.blitzortung.android.data.beans.Strike class StrikeOverlayItem(strike: Strike) : OverlayItem(Coordsys.toMapCoords(strike.longitude, strike.latitude), "", ""), Strike { override val timestamp: Long override val multiplicity: Int init { super.setMarker(ShapeDrawable()) timestamp = strike.timestamp multiplicity = strike.multiplicity } override fun setMarker(drawable: Drawable?) { throw IllegalStateException("cannot overwrite marker of strike overlay item") } private val drawable: ShapeDrawable get() { return getMarker(0) as ShapeDrawable } var shape: Shape? get() { return drawable.shape } set(shape) { drawable.shape = shape } fun updateShape(rasterParameters: RasterParameters?, projection: Projection, color: Int, textColor: Int, zoomLevel: Int) { var shape: Shape? = shape if (rasterParameters != null) { if (shape == null && shape !is RasterShape) { shape = RasterShape() } val lon_delta = rasterParameters.longitudeDelta / 2.0f * 1e6f val lat_delta = rasterParameters.latitudeDelta / 2.0f * 1e6f val geoPoint = point projection.toPixels(geoPoint, center) projection.toPixels(GeoPoint( (geoPoint.latitudeE6 + lat_delta).toInt(), (geoPoint.longitudeE6 - lon_delta).toInt()), topLeft) projection.toPixels(GeoPoint( (geoPoint.latitudeE6 - lat_delta).toInt(), (geoPoint.longitudeE6 + lon_delta).toInt()), bottomRight) topLeft.offset(-center.x, -center.y) bottomRight.offset(-center.x, -center.y) if (shape is RasterShape) { shape.update(topLeft, bottomRight, color, multiplicity, textColor) } } else { if (shape == null) { shape = StrikeShape() } if (shape is StrikeShape) { shape.update((zoomLevel + 1).toFloat(), color) } } this.shape = shape } override val longitude: Float get() { return point.longitudeE6 / 1e6f } override val latitude: Float get() { return point.latitudeE6 / 1e6f } companion object { private val center = Point() private val topLeft = Point() private val bottomRight = Point() } }
apache-2.0
1c6722c281dab4734b40f0e688fe0d6b
32.231481
128
0.631931
4.595391
false
false
false
false
light-and-salt/kotloid
src/main/kotlin/kr/or/lightsalt/kotloid/app/Page.kt
1
1531
package kr.or.lightsalt.kotloid.app import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.navigation.fragment.NavHostFragment import kr.or.lightsalt.kotloid.instantiateFragment import kotlin.reflect.KClass @Suppress("unused") abstract class Page<T> { open var data: T? = null open var title: CharSequence? = null open var visible = true abstract val id: Long abstract fun isPageOf(fragment: Fragment): Boolean abstract fun instantiate(activity: FragmentActivity): Fragment open class FragmentPage<T>(fragment: KClass<out Fragment>, private val args: Bundle? = null) : Page<T>() { private val fragmentName: String = fragment.java.name override val id get() = fragmentName.hashCode().toLong() override fun isPageOf(fragment: Fragment) = fragmentName == fragment.javaClass.name override fun instantiate(activity: FragmentActivity) = activity.instantiateFragment(fragmentName).apply { arguments = args } } open class NavHostPage<T>(private val graphResId: Int, private val startDestinationArgs: Bundle? = null) : Page<T>() { override val id get() = graphResId.toLong() override fun isPageOf(fragment: Fragment) = fragment is NavHostFragment && fragment.id == graphResId override fun instantiate(activity: FragmentActivity) = NavHostFragment.create(graphResId, startDestinationArgs) } }
apache-2.0
ff1e74bb63cf2ed5aa4ac417139a102d
38.25641
122
0.705421
4.739938
false
false
false
false
songzhw/AndroidArchitecture
deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/twentythree_scope_peractivity/DI23.kt
1
1139
package six.ca.dagger101.twentythree_scope_peractivity import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Scope import javax.inject.Singleton class HttpEngine23 // 每个页面都需要HttpEngine, 没必要每个都创建一个. 所以可以是一个全局存在的单例 @Module class Common23Module { @Singleton @Provides fun httpClient() : HttpEngine23 { return HttpEngine23() } } @Singleton @Component(modules = [Common23Module::class]) interface Common23Component { fun http() : HttpEngine23 } @Scope @Retention(AnnotationRetention.RUNTIME) annotation class PerActivity @Module class One23Module { @PerActivity @Provides fun name1() = "name1" } @PerActivity @Component(modules = [One23Module::class], dependencies = [Common23Component::class]) interface One23Component { fun inject(receiver: Page23One) } @Module class Two23Module { @PerActivity @Provides fun name2() = "name2" } @PerActivity @Component(modules = [Two23Module::class], dependencies = [Common23Component::class]) interface Two23Component { fun inject(receiver: Page23Two) }
apache-2.0
b58cb5017bd33ac679bc4a0454c86528
19.339623
85
0.754875
3.566225
false
false
false
false
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/data/CookieManager.kt
1
1872
@file:Suppress("DEPRECATION") // 用到Cookies相关的不少过时方法,兼容低版本需要, package cc.aoeiuv020.panovel.data import android.content.Context import android.os.Build import android.webkit.CookieManager import android.webkit.CookieSyncManager import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug /** * Created by AoEiuV020 on 2018.05.23-20:25:48. */ class CookieManager(@Suppress("UNUSED_PARAMETER") ctx: Context) : AnkoLogger { private val cookieManager = CookieManager.getInstance() fun putCookie(domain: String, cookiePair: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.setCookie(domain, cookiePair) { debug { "cookie has been set $it, <$${DataManager.cookie}>" } } } else { cookieManager.setCookie(domain, cookiePair) debug { "cookie has been set, <$${DataManager.cookie}>" } } } // 莫名,旧版刷新方法需要Context, // 方便起见,传入ctx可空,为空就不刷低版本的了, fun sync(ctx: Context?) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.flush() } else { ctx ?: return val syncManager = CookieSyncManager.createInstance(ctx) syncManager.sync() } } fun getCookies(domain: String): String? { return cookieManager.getCookie(domain) } fun removeCookies() { val cookieManager = CookieManager.getInstance() cookieManager.setAcceptCookie(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { cookieManager.removeAllCookies(null) } else { cookieManager.removeAllCookie() } } }
gpl-3.0
40e7639ad2d53c830c6c44f085b65401
28
78
0.618213
4.150235
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/common/v2/stream/AsyncHttp2Connection.kt
1
38275
package com.fireflysource.net.http.common.v2.stream import com.fireflysource.common.concurrent.AtomicBiInteger import com.fireflysource.common.concurrent.Atomics import com.fireflysource.common.concurrent.exceptionallyAccept import com.fireflysource.common.math.MathUtils import com.fireflysource.common.sys.Result import com.fireflysource.common.sys.Result.* import com.fireflysource.common.sys.SystemLogger import com.fireflysource.net.Connection import com.fireflysource.net.http.common.HttpConfig import com.fireflysource.net.http.common.TcpBasedHttpConnection import com.fireflysource.net.http.common.model.HttpStatus import com.fireflysource.net.http.common.model.HttpVersion import com.fireflysource.net.http.common.model.MetaData import com.fireflysource.net.http.common.v2.decoder.Parser import com.fireflysource.net.http.common.v2.encoder.Generator import com.fireflysource.net.http.common.v2.frame.* import com.fireflysource.net.tcp.TcpConnection import com.fireflysource.net.tcp.TcpCoroutineDispatcher import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.future.await import kotlinx.coroutines.launch import java.io.IOException import java.nio.ByteBuffer import java.nio.charset.StandardCharsets import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import java.util.function.Consumer import kotlin.math.min abstract class AsyncHttp2Connection( private val initStreamId: Int, val config: HttpConfig, private val tcpConnection: TcpConnection, private val flowControl: FlowControl, private val listener: Http2Connection.Listener ) : Connection by tcpConnection, TcpCoroutineDispatcher by tcpConnection, Http2Connection, TcpBasedHttpConnection, Parser.Listener { companion object { private val log = SystemLogger.create(AsyncHttp2Connection::class.java) val defaultHttp2ConnectionListener = object : Http2Connection.Listener.Adapter() { override fun onReset(http2Connection: Http2Connection, frame: ResetFrame) { log.info { "HTTP2 connection received reset frame. $frame" } } override fun onFailure(http2Connection: Http2Connection, e: Throwable) { log.error(e) { "HTTP2 connection exception. ${http2Connection.id}" } } } } private val localStreamId = AtomicInteger(initStreamId) private val http2StreamMap = ConcurrentHashMap<Int, Stream>() private val localStreamCount = AtomicInteger() private val remoteStreamCount = AtomicBiInteger() private val lastRemoteStreamId = AtomicInteger() private val closeState = AtomicReference(CloseState.NOT_CLOSED) private val sendWindow = AtomicInteger(HttpConfig.DEFAULT_WINDOW_SIZE) private val recvWindow = AtomicInteger(HttpConfig.DEFAULT_WINDOW_SIZE) private val generator = Generator(config.maxDynamicTableSize, config.maxHeaderBlockFragment) private var maxLocalStreams: Int = -1 private var maxRemoteStreams: Int = -1 private var streamIdleTimeout: Long = config.streamIdleTimeout private var pushEnabled: Boolean = false private var closeFrame: GoAwayFrame? = null protected val initialSessionRecvWindow: Int = config.initialSessionRecvWindow private val flusher = FrameEntryFlusher() init { tcpConnection.onClose { clearStreams() } } private inner class FrameEntryFlusher { private val frameEntryChannel = Channel<FlushFrameMessage>(Channel.UNLIMITED) init { launchEntryFlushJob() } private fun launchEntryFlushJob() = tcpConnection.coroutineScope.launch { while (true) { when (val frameEntry = frameEntryChannel.receive()) { is ControlFrameEntry -> flushControlFrameEntry(frameEntry) is DataFrameEntry -> flushOrStashDataFrameEntry(frameEntry) is OnWindowUpdateMessage -> onWindowUpdateMessage(frameEntry) } } }.invokeOnCompletion { terminate() } private suspend fun flushOrStashDataFrameEntry(frameEntry: DataFrameEntry) { try { val http2Stream = frameEntry.stream as AsyncHttp2Stream val isEmpty = http2Stream.flushStashedDataFrameEntries() if (isEmpty) { val success = flushDataFrame(frameEntry) if (!success) { http2Stream.stashFrameEntry(frameEntry) val dataRemaining = frameEntry.dataRemaining log.debug { "Send data frame failure. Stash a data frame. remaining: $dataRemaining, stream: $http2Stream" } } } else { http2Stream.stashFrameEntry(frameEntry) log.debug { "Stashed data frame is not empty. Stash a data frame. stream: $http2Stream" } } } catch (e: Exception) { log.error { "flush data frame exception. ${e.javaClass.name} ${e.message}" } frameEntry.result.accept(createFailedResult(-1L, e)) } } private fun AsyncHttp2Stream.stashFrameEntry(frameEntry: DataFrameEntry) { this.stashedDataFrames.offer(frameEntry) } private suspend fun AsyncHttp2Stream.flushStashedDataFrameEntries(): Boolean { val stashedDataFrames = this.stashedDataFrames flush@ while (stashedDataFrames.isNotEmpty()) { val stashedFrameEntry = stashedDataFrames.peek() if (stashedFrameEntry != null) { val success = flushDataFrame(stashedFrameEntry) if (success) { val entry = stashedDataFrames.poll() val dataRemaining = entry.dataRemaining val writtenBytes = entry.writtenBytes log.debug { "Poll a stashed data frame. remaining: ${dataRemaining}, written: $writtenBytes" } } else break@flush } else break@flush } return stashedDataFrames.isEmpty() } private suspend fun flushDataFrame(frameEntry: DataFrameEntry): Boolean { val dataFrame = frameEntry.frame val stream = frameEntry.stream as AsyncHttp2Stream val dataRemaining = frameEntry.dataRemaining val connectionSendWindow = getSendWindow() val streamSendWindow = stream.getSendWindow() val window = min(streamSendWindow, connectionSendWindow) log.debug { "Flush data frame. window: $window, remaining: $dataRemaining" } if (window <= 0 && dataRemaining > 0) { log.debug { "The sending window not enough. stream: $stream" } return false } val length = min(dataRemaining, window) val frameBytes = generator.data(dataFrame, length) val dataLength = frameBytes.dataLength log.debug { "Before flush data frame. window: $window, remaining: $dataRemaining, dataLength: $dataLength" } flowControl.onDataSending(stream, dataLength) stream.updateClose(dataFrame.isEndStream, CloseState.Event.BEFORE_SEND) val writtenBytes = writeAndFlush(frameBytes.byteBuffers, dataFrame) frameEntry.dataRemaining -= dataLength frameEntry.writtenBytes += writtenBytes flowControl.onDataSent(stream, dataLength) val currentRemaining = frameEntry.dataRemaining log.debug { "After flush data frame. window: $window, remaining: $currentRemaining, dataLength: $dataLength" } return if (currentRemaining == 0) { // Only now we can update the close state and eventually remove the stream. if (stream.updateClose(dataFrame.isEndStream, CloseState.Event.AFTER_SEND)) { removeStream(stream) } frameEntry.result.accept(Result(true, frameEntry.writtenBytes, null)) log.debug { "Flush all data success. stream: $stream" } true } else { log.debug { "Flush data success. stream: $stream, remaining: $currentRemaining" } false } } fun onWindowUpdate(stream: Stream?, frame: WindowUpdateFrame) { frameEntryChannel.trySend(OnWindowUpdateMessage(stream, frame)) } private suspend fun onWindowUpdateMessage(onWindowUpdateMessage: OnWindowUpdateMessage) { val (stream, frame) = onWindowUpdateMessage flowControl.onWindowUpdate(this@AsyncHttp2Connection, stream, frame) if (stream != null) { val http2Stream = stream as AsyncHttp2Stream log.debug { "Flush stream stashed data frames. stream: $http2Stream" } http2Stream.flushStashedDataFrameEntries() } else { if (frame.isSessionWindowUpdate) { log.debug { "Flush all streams stashed data frames. id: ${tcpConnection.id}" } streams.map { it as AsyncHttp2Stream }.forEach { it.flushStashedDataFrameEntries() } } } log.debug { "Update send window and flush stashed data frame success. frame: $frame" } } private suspend fun flushControlFrameEntry(frameEntry: ControlFrameEntry) { try { val length = flushControlFrames(frameEntry) frameEntry.result.accept(Result(true, length, null)) } catch (e: Exception) { frameEntry.result.accept(createFailedResult(-1, e)) } } private suspend fun flushControlFrames(frameEntry: ControlFrameEntry): Long { val stream = frameEntry.stream var writtenBytes = 0L frameLoop@ for (frame in frameEntry.frames) { when (frame.type) { FrameType.HEADERS -> { val headersFrame = frame as HeadersFrame if (stream != null && stream is AsyncHttp2Stream) { stream.updateClose(headersFrame.isEndStream, CloseState.Event.BEFORE_SEND) } } FrameType.SETTINGS -> { val settingsFrame = frame as SettingsFrame val initialWindow = settingsFrame.settings[SettingsFrame.INITIAL_WINDOW_SIZE] if (initialWindow != null) { flowControl.updateInitialStreamWindow(this@AsyncHttp2Connection, initialWindow, true) } } FrameType.DISCONNECT -> { terminate() break@frameLoop } else -> { // ignore the other control frame types } } val byteBuffers = generator.control(frame).byteBuffers val bytes = writeAndFlush(byteBuffers, frame) writtenBytes += bytes when (frame.type) { FrameType.HEADERS -> { val headersFrame = frame as HeadersFrame if (stream != null && stream is AsyncHttp2Stream) { onStreamOpened(stream) if (stream.updateClose(headersFrame.isEndStream, CloseState.Event.AFTER_SEND)) { removeStream(stream) } } } FrameType.RST_STREAM -> { if (stream != null && stream is AsyncHttp2Stream) { stream.close() removeStream(stream) } } FrameType.PUSH_PROMISE -> { if (stream != null && stream is AsyncHttp2Stream) { stream.updateClose(true, CloseState.Event.RECEIVED) } } FrameType.GO_AWAY -> { tcpConnection.close { log.info { "Send go away frame and close TCP connection success" } } } FrameType.WINDOW_UPDATE -> { flowControl.windowUpdate(this@AsyncHttp2Connection, stream, frame as WindowUpdateFrame) } else -> { // ignore the other control frame types } } } return writtenBytes } private suspend fun writeAndFlush(byteBuffers: List<ByteBuffer>, frame: Frame): Long { val flush = when (frame) { is HeadersFrame -> { if (frame.isEndStream) true else { val metaData = frame.metaData metaData is MetaData.Response && metaData.status == HttpStatus.CONTINUE_100 } } is DataFrame -> frame.isEndStream else -> true } return if (flush) tcpConnection.writeAndFlush(byteBuffers, 0, byteBuffers.size).await() else tcpConnection.write(byteBuffers, 0, byteBuffers.size).await() } fun sendControlFrame(stream: Stream?, vararg frames: Frame): CompletableFuture<Long> { val future = CompletableFuture<Long>() frameEntryChannel.trySend(ControlFrameEntry(stream, arrayOf(*frames), futureToConsumer(future))) return future } fun sendDataFrame(stream: Stream, frame: DataFrame): CompletableFuture<Long> { val future = CompletableFuture<Long>() frameEntryChannel.trySend(DataFrameEntry(stream, frame, futureToConsumer(future))) return future } } fun sendControlFrame(stream: Stream?, vararg frames: Frame): CompletableFuture<Long> = flusher.sendControlFrame(stream, *frames) fun launchParserJob(parser: Parser) = tcpConnection.coroutineScope.launch { recvLoop@ while (true) { val buffer = try { tcpConnection.read().await() } catch (e: Exception) { break@recvLoop } parsingLoop@ while (buffer.hasRemaining()) { parser.parse(buffer) } } } override fun isSecureConnection(): Boolean = tcpConnection.isSecureConnection override fun getHttpVersion(): HttpVersion = HttpVersion.HTTP_2 override fun getTcpConnection(): TcpConnection = tcpConnection fun notifyPreface(): MutableMap<Int, Int> { return try { val settings = listener.onPreface(this) ?: newDefaultSettings() val initialWindowSize = settings[SettingsFrame.INITIAL_WINDOW_SIZE] ?: config.initialStreamRecvWindow flowControl.updateInitialStreamWindow(this, initialWindowSize, true) settings } catch (e: Exception) { log.error(e) { "failure while notifying listener" } newDefaultSettings() } } private fun newDefaultSettings(): MutableMap<Int, Int> { val settings = HashMap(SettingsFrame.DEFAULT_SETTINGS_FRAME.settings) settings[SettingsFrame.INITIAL_WINDOW_SIZE] = config.initialStreamRecvWindow settings[SettingsFrame.MAX_CONCURRENT_STREAMS] = config.maxConcurrentStreams return settings } // stream management override fun getStreams(): MutableCollection<Stream> = http2StreamMap.values override fun getStream(streamId: Int): Stream? = http2StreamMap[streamId] override fun newStream(headersFrame: HeadersFrame, promise: Consumer<Result<Stream?>>, listener: Stream.Listener) { try { val frameStreamId = headersFrame.streamId if (frameStreamId == 0) { val newHeadersFrame = copyHeadersFrameAndSetCurrentStreamId(headersFrame) val stream = createLocalStream(newHeadersFrame.streamId, listener) sendNewHeadersFrame(stream, newHeadersFrame, promise) } else { val stream = createLocalStream(frameStreamId, listener) sendNewHeadersFrame(stream, headersFrame, promise) } } catch (e: Exception) { promise.accept(Result(false, null, e)) } } private fun copyHeadersFrameAndSetCurrentStreamId(headersFrame: HeadersFrame): HeadersFrame { val nextStreamId = getNextStreamId() val priority = headersFrame.priority val priorityFrame = if (priority != null) { PriorityFrame(nextStreamId, priority.parentStreamId, priority.weight, priority.isExclusive) } else null return HeadersFrame(nextStreamId, headersFrame.metaData, priorityFrame, headersFrame.isEndStream) } private fun sendNewHeadersFrame(stream: Stream, newHeadersFrame: HeadersFrame, promise: Consumer<Result<Stream?>>) { sendControlFrame(stream, newHeadersFrame) .thenAccept { promise.accept(Result(true, stream, null)) } .exceptionallyAccept { promise.accept(createFailedResult(null, it)) } } fun removeStream(stream: Stream) { val removed = http2StreamMap.remove(stream.id) if (removed != null) { onStreamClosed(stream) flowControl.onStreamDestroyed(stream) log.debug { "Removed $stream" } } } protected fun getNextStreamId(): Int = getAndIncreaseStreamId(localStreamId, initStreamId) private fun getCurrentLocalStreamId(): Int = localStreamId.get() protected fun createLocalStream(streamId: Int, listener: Stream.Listener): Stream { checkMaxLocalStreams() val stream = AsyncHttp2Stream(this, streamId, true, listener) if (http2StreamMap.putIfAbsent(streamId, stream) == null) { stream.idleTimeout = streamIdleTimeout flowControl.onStreamCreated(stream) // TODO before preface log.debug { "Created local $stream" } return stream } else { localStreamCount.decrementAndGet() throw IllegalStateException("Duplicate stream $streamId") } } private fun checkMaxLocalStreams() { val maxCount = maxLocalStreams if (maxCount > 0) { while (true) { val localCount = localStreamCount.get() if (localCount >= maxCount) { throw IllegalStateException("Max local stream count $localCount exceeded $maxCount") } if (localStreamCount.compareAndSet(localCount, localCount + 1)) { break } } } else { localStreamCount.incrementAndGet() } } protected fun createRemoteStream(streamId: Int): Stream? { // SPEC: exceeding max concurrent streams treated as stream error. if (!checkMaxRemoteStreams(streamId)) { return null } val stream: Stream = AsyncHttp2Stream(this, streamId, false) // SPEC: duplicate stream treated as connection error. return if (http2StreamMap.putIfAbsent(streamId, stream) == null) { updateLastRemoteStreamId(streamId) stream.idleTimeout = streamIdleTimeout flowControl.onStreamCreated(stream) log.debug { "Created remote $stream" } stream } else { remoteStreamCount.addAndGetHi(-1) onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "duplicate_stream") null } } private fun checkMaxRemoteStreams(streamId: Int): Boolean { while (true) { val encoded = remoteStreamCount.get() val remoteCount = AtomicBiInteger.getHi(encoded) val remoteClosing = AtomicBiInteger.getLo(encoded) val maxCount: Int = maxRemoteStreams if (maxCount >= 0 && remoteCount - remoteClosing >= maxCount) { reset(ResetFrame(streamId, ErrorCode.REFUSED_STREAM_ERROR.code), discard()) return false } if (remoteStreamCount.compareAndSet(encoded, remoteCount + 1, remoteClosing)) { break } } return true } protected open fun onStreamOpened(stream: Stream) {} protected open fun onStreamClosed(stream: Stream) {} protected open fun notifyNewStream(stream: Stream, frame: HeadersFrame): Stream.Listener { return try { listener.onNewStream(stream, frame) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } AsyncHttp2Stream.defaultStreamListener } } private fun updateLastRemoteStreamId(streamId: Int) { Atomics.updateMax(lastRemoteStreamId, streamId) } fun updateStreamCount(local: Boolean, deltaStreams: Int, deltaClosing: Int) { if (local) { localStreamCount.addAndGet(deltaStreams) } else { remoteStreamCount.add(deltaStreams, deltaClosing) } } fun isClientStream(streamId: Int) = (streamId and 1 == 1) private fun getLastRemoteStreamId(): Int { return lastRemoteStreamId.get() } protected fun isLocalStreamClosed(streamId: Int): Boolean { return streamId <= getCurrentLocalStreamId() } protected fun isRemoteStreamClosed(streamId: Int): Boolean { return streamId <= getLastRemoteStreamId() } override fun onStreamFailure(streamId: Int, error: Int, reason: String) { val stream = getStream(streamId) if (stream != null && stream is AsyncHttp2Stream) { stream.process(FailureFrame(error, reason), discard()) } else { reset(ResetFrame(streamId, error), discard()) } } // reset frame override fun onReset(frame: ResetFrame) { log.debug { "Received $frame" } val stream = getStream(frame.streamId) if (stream != null && stream is AsyncHttp2Stream) { stream.process(frame, discard()) } else { onResetForUnknownStream(frame) } } protected fun notifyReset(http2Connection: Http2Connection, frame: ResetFrame) { try { listener.onReset(http2Connection, frame) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } protected abstract fun onResetForUnknownStream(frame: ResetFrame) protected fun reset(frame: ResetFrame, result: Consumer<Result<Void>>) { sendControlFrame(getStream(frame.streamId), frame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } } // headers frame abstract override fun onHeaders(frame: HeadersFrame) protected fun notifyHeaders(stream: AsyncHttp2Stream, frame: HeadersFrame) { try { stream.listener.onHeaders(stream, frame) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } fun push(frame: PushPromiseFrame, promise: Consumer<Result<Stream?>>, listener: Stream.Listener) { val promiseStreamId = getNextStreamId() val pushStream = createLocalStream(promiseStreamId, listener) val pushPromiseFrame = PushPromiseFrame(frame.streamId, promiseStreamId, frame.metaData) sendControlFrame(pushStream, pushPromiseFrame) .thenAccept { promise.accept(Result(true, pushStream, null)) } .exceptionallyAccept { promise.accept(Result(false, null, it)) } } // data frame override fun onData(frame: DataFrame) { onData(frame, discard()) } private fun onData(frame: DataFrame, result: Consumer<Result<Void>>) { log.debug { "Received $frame" } val streamId = frame.streamId val stream = getStream(streamId) // SPEC: the session window must be updated even if the stream is null. // The flow control length includes the padding bytes. val flowControlLength = frame.remaining() + frame.padding() flowControl.onDataReceived(this, stream, flowControlLength) if (stream != null) { if (getRecvWindow() < 0) { onConnectionFailure(ErrorCode.FLOW_CONTROL_ERROR.code, "session_window_exceeded", result) } else { val dataResult = Consumer<Result<Void>> { r -> flowControl.onDataConsumed(this@AsyncHttp2Connection, stream, flowControlLength) result.accept(r) } val http2Stream = stream as AsyncHttp2Stream http2Stream.process(frame, dataResult) } } else { log.debug("Stream #{} not found", streamId) // We must enlarge the session flow control window, // otherwise, the other requests will be stalled. flowControl.onDataConsumed(this, null, flowControlLength) val local = (streamId and 1) == (getCurrentLocalStreamId() and 1) val closed = if (local) isLocalStreamClosed(streamId) else isRemoteStreamClosed(streamId) if (closed) reset(ResetFrame(streamId, ErrorCode.STREAM_CLOSED_ERROR.code), result) else onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "unexpected_data_frame", result) } } fun sendDataFrame(stream: Stream, frame: DataFrame) = flusher.sendDataFrame(stream, frame) // priority frame override fun priority(frame: PriorityFrame, result: Consumer<Result<Void>>): Int { val stream = http2StreamMap[frame.streamId] return if (stream == null) { val newStreamId = getNextStreamId() val newFrame = PriorityFrame(newStreamId, frame.parentStreamId, frame.weight, frame.isExclusive) sendControlFrame(null, newFrame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } newStreamId } else { sendControlFrame(stream, frame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } stream.id } } override fun onPriority(frame: PriorityFrame) { log.debug { "Received $frame" } } // settings frame override fun settings(frame: SettingsFrame, result: Consumer<Result<Void>>) { sendControlFrame(null, frame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } } override fun onSettings(frame: SettingsFrame) { // SPEC: SETTINGS frame MUST be replied. onSettings(frame, true) } fun onSettings(frame: SettingsFrame, reply: Boolean) { log.debug { "received frame: $frame" } if (frame.isReply) { return } frame.settings.forEach { (key, value) -> when (key) { SettingsFrame.HEADER_TABLE_SIZE -> { log.debug { "Updating HPACK header table size to $value for $this" } generator.setHeaderTableSize(value) } SettingsFrame.ENABLE_PUSH -> { val enabled = value == 1 log.debug { "${if (enabled) "Enabling" else "Disabling"} push for $this" } pushEnabled = enabled } SettingsFrame.MAX_CONCURRENT_STREAMS -> { log.debug { "Updating max local concurrent streams to $value for $this" } maxLocalStreams = value } SettingsFrame.INITIAL_WINDOW_SIZE -> { log.debug { "Updating initial window size to $value for $this" } flowControl.updateInitialStreamWindow(this, value, false) } SettingsFrame.MAX_FRAME_SIZE -> { log.debug { "Updating max frame size to $value for $this" } generator.setMaxFrameSize(value) } SettingsFrame.MAX_HEADER_LIST_SIZE -> { log.debug { "Updating max header list size to $value for $this" } generator.setMaxHeaderListSize(value) } else -> { log.debug { "Unknown setting $key:$value for $this" } } } } notifySettings(this, frame) if (reply) { val replyFrame = SettingsFrame(emptyMap(), true) settings(replyFrame, discard()) } } private fun notifySettings(connection: Http2Connection, frame: SettingsFrame) { try { listener.onSettings(connection, frame) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } // window update override fun onWindowUpdate(frame: WindowUpdateFrame) { log.debug { "Received $frame" } val streamId = frame.streamId val windowDelta = frame.windowDelta if (frame.isStreamWindowUpdate) { val stream = getStream(streamId) if (stream != null && stream is AsyncHttp2Stream) { val streamSendWindow: Int = stream.updateSendWindow(0) if (MathUtils.sumOverflows(streamSendWindow, windowDelta)) { reset(ResetFrame(streamId, ErrorCode.FLOW_CONTROL_ERROR.code), discard()) } else { stream.process(frame, discard()) onWindowUpdate(stream, frame) } } else { if (!isRemoteStreamClosed(streamId)) { onConnectionFailure(ErrorCode.PROTOCOL_ERROR.code, "unexpected_window_update_frame") } } } else { val sessionSendWindow = getSendWindow() if (MathUtils.sumOverflows(sessionSendWindow, windowDelta)) { onConnectionFailure(ErrorCode.FLOW_CONTROL_ERROR.code, "invalid_flow_control_window") } else { onWindowUpdate(null, frame) } } } fun onWindowUpdate(stream: Stream?, frame: WindowUpdateFrame) { flusher.onWindowUpdate(stream, frame) } fun updateRecvWindow(delta: Int): Int { return recvWindow.getAndAdd(delta) } fun updateSendWindow(delta: Int): Int { return sendWindow.getAndAdd(delta) } fun getSendWindow(): Int { return sendWindow.get() } fun getRecvWindow(): Int { return recvWindow.get() } // ping frame override fun ping(frame: PingFrame, result: Consumer<Result<Void>>) { if (frame.isReply) { result.accept(createFailedResult(IllegalArgumentException("The reply must be false"))) } else { sendControlFrame(null, frame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } } } override fun onPing(frame: PingFrame) { log.debug { "Received $frame" } if (frame.isReply) { notifyPing(this, frame) } else { sendControlFrame(null, PingFrame(frame.payload, true)) } } private fun notifyPing(connection: Http2Connection, frame: PingFrame) { try { listener.onPing(connection, frame) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } // close connection override fun close(error: Int, reason: String, result: Consumer<Result<Void>>): Boolean { while (true) { when (val current: CloseState = closeState.get()) { CloseState.NOT_CLOSED -> { if (closeState.compareAndSet(current, CloseState.LOCALLY_CLOSED)) { val goAwayFrame = newGoAwayFrame(CloseState.LOCALLY_CLOSED, error, reason) closeFrame = goAwayFrame sendControlFrame(null, goAwayFrame) .thenAccept { result.accept(SUCCESS) } .exceptionallyAccept { result.accept(createFailedResult(it)) } return true } } else -> { log.debug { "Ignoring close $error/$reason, already closed" } result.accept(SUCCESS) return false } } } } suspend fun close(error: Int, reason: String): Boolean { val future = CompletableFuture<Void>() val success = close(error, reason, futureToConsumer(future)) future.await() return success } private fun terminate() { terminateLoop@ while (true) { when (val current = closeState.get()) { CloseState.NOT_CLOSED, CloseState.LOCALLY_CLOSED, CloseState.REMOTELY_CLOSED -> { if (closeState.compareAndSet(current, CloseState.CLOSED)) { clearStreams() disconnect() break@terminateLoop } } else -> { // ignore the other close states break@terminateLoop } } } } private fun disconnect() { log.debug { "Disconnecting $this" } tcpConnection.close() } private fun clearStreams() { log.debug { "HTTP2 connection terminated. id: $id, stream size: ${http2StreamMap.size}" } http2StreamMap.values.map { it as AsyncHttp2Stream }.forEach { it.notifyTerminal(it) it.close() } http2StreamMap.clear() } override fun closeAsync(): CompletableFuture<Void> { val future = CompletableFuture<Void>() close(ErrorCode.NO_ERROR.code, "no_error", futureToConsumer(future)) return future } override fun close() { closeAsync() } // go away frame override fun onGoAway(frame: GoAwayFrame) { log.debug { "Received $frame" } closeLoop@ while (true) { when (val current: CloseState = closeState.get()) { CloseState.NOT_CLOSED -> { if (closeState.compareAndSet(current, CloseState.REMOTELY_CLOSED)) { // We received a GO_AWAY, so try to write what's in the queue and then disconnect. closeFrame = frame notifyClose(this, frame) { val goAwayFrame = newGoAwayFrame(CloseState.CLOSED, ErrorCode.NO_ERROR.code, null) val disconnectFrame = DisconnectFrame() sendControlFrame(null, goAwayFrame, disconnectFrame) } break@closeLoop } } else -> { log.debug { "Ignored $frame, already closed" } break@closeLoop } } } } private fun notifyClose(connection: Http2Connection, frame: GoAwayFrame, consumer: Consumer<Result<Void>>) { try { listener.onClose(connection, frame, consumer) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } private fun newGoAwayFrame(closeState: CloseState, error: Int, reason: String?): GoAwayFrame { var payload: ByteArray? = null if (reason != null) { // Trim the reason to avoid attack vectors. payload = reason.substring(0, min(reason.length, 32)).toByteArray(StandardCharsets.UTF_8) } return GoAwayFrame(closeState, getLastRemoteStreamId(), error, payload) } override fun onConnectionFailure(error: Int, reason: String) { onConnectionFailure(error, reason, discard()) } protected fun onConnectionFailure(error: Int, reason: String, result: Consumer<Result<Void>>) { notifyFailure(this, IOException(String.format("%d/%s", error, reason))) { close(error, reason, result) } } private fun notifyFailure(connection: Http2Connection, throwable: Throwable, consumer: Consumer<Result<Void>>) { try { listener.onFailure(connection, throwable, consumer) } catch (e: Exception) { log.error(e) { "failure while notifying listener" } } } override fun toString(): String { return java.lang.String.format( "%s@%x{l:%s <-> r:%s,sendWindow=%s,recvWindow=%s,streams=%d,%s,%s}", this::class.java.simpleName, hashCode(), tcpConnection.localAddress, tcpConnection.remoteAddress, sendWindow, recvWindow, streams.size, closeState.get(), closeFrame?.toString() ) } } fun getAndIncreaseStreamId(id: AtomicInteger, initStreamId: Int) = id.getAndUpdate { prev -> val currentId = prev + 2 if (currentId <= 0) initStreamId else currentId } sealed class FlushFrameMessage class ControlFrameEntry(val stream: Stream?, val frames: Array<Frame>, val result: Consumer<Result<Long>>) : FlushFrameMessage() class DataFrameEntry(val stream: Stream, val frame: DataFrame, val result: Consumer<Result<Long>>) : FlushFrameMessage() { var dataRemaining = frame.remaining() var writtenBytes: Long = 0 } data class OnWindowUpdateMessage(val stream: Stream?, val frame: WindowUpdateFrame) : FlushFrameMessage()
apache-2.0
bab53ca0f5df32fa72cde6ab963ffc1f
39.589608
132
0.596839
4.915875
false
false
false
false
yh-kim/gachi-android
Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/festival/FestivalPresenter.kt
1
3377
package com.pickth.gachi.view.main.fragments.festival import com.pickth.commons.mvp.BaseView import com.pickth.gachi.net.service.FestivalService import com.pickth.gachi.util.OnFestivalClickListener import com.pickth.gachi.view.festival.adapter.FestivalDetailAdapter import com.pickth.gachi.view.gachi.Gachi import com.pickth.gachi.view.main.fragments.festival.adapter.Festival import com.pickth.gachi.view.main.fragments.festival.adapter.FestivalAdapter import okhttp3.ResponseBody import org.json.JSONArray import retrofit2.Call import retrofit2.Callback import retrofit2.Response /** * Created by yonghoon on 2017-07-20. * Mail : [email protected] */ class FestivalPresenter: FestivalContract.Presenter, OnFestivalClickListener { private lateinit var mView: FestivalContract.View private lateinit var mPopularAdapter: FestivalAdapter private lateinit var mPopularGachiAdapter: FestivalDetailAdapter override fun attachView(view: BaseView<*>) { this.mView = view as FestivalContract.View } override fun setPopularAdapter(adapter: FestivalAdapter) { mPopularAdapter = adapter mPopularAdapter.setItemClickListener(this) } override fun setPopularGachiAdapter(adapter: FestivalDetailAdapter) { mPopularGachiAdapter = adapter // mPopularGachiAdapter.setItemClickListener(this) } override fun getPopularFestivalItem(position: Int): Festival = mPopularAdapter.getItem(position) override fun getPopularGachiItem(position: Int): Gachi = mPopularGachiAdapter.getItem(position) override fun getPopularFestivalList() { FestivalService().getFestivalList(1) .enqueue(object: Callback<ResponseBody> { override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) { } override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) { if(response?.code() != 200) return val retArr = JSONArray(response.body()!!.string()) for(position in 0..retArr.length() - 1) { retArr.getJSONObject(position).let { val fid = it.getString("fid") val title = it.getString("title") val image = it.getString("image") val from = it.getString("from").split("T")[0].replace("-",".") val until = it.getString("until").split("T")[0].replace("-",".") val type = "popular" var date = "$from - $until" mPopularAdapter.addItem(Festival(fid, date, image, title, type)) } } } }) } override fun getPopularGachiList() { for(i in 0..4) mPopularGachiAdapter.addItem(Gachi("a", "d", "")) } override fun onPopularFestivalClick(position: Int) { val fid = mPopularAdapter.getItem(position).fid mView.intentToFestivalDetailActivity(fid) } override fun onImmediateFestivalClick(position: Int) { // val fid = mPopularGachiAdapter.getItem(position).fid // mView.intentToFestivalDetailActivity(fid) } }
apache-2.0
c47f55a3515684fcf3baafb2c7f4b04b
38.27907
107
0.629257
4.466931
false
false
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/common/HttpUrlExtensions.kt
1
4212
package com.chimbori.crux.common import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull // Checks heuristically whether a given URL is likely to be an article, video, image, or other types. Can optionally // resolve redirects such as when Facebook or Google show an interstitial page instead of redirecting the user to the // actual URL. public fun HttpUrl.isAdImage(): Boolean = toString().countMatches("ad") >= 2 public fun HttpUrl.isLikelyArticle(): Boolean = !isLikelyImage() && !isLikelyVideo() && !isLikelyAudio() && !isLikelyBinaryDocument() && !isLikelyExecutable() && !isLikelyArchive() public fun HttpUrl.isLikelyVideo(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "3g2", "3gp", "amv", "asf", "avi", "drc", "flv", "gif", "gifv", "m2v", "m4p", "m4v", "mkv", "mng", "mov", "mp2", "mp4", "mpe", "mpeg", "mpg", "mpg4", "mpv", "mxf", "nsv", "ogg", "ogv", "qt", "rm", "rmvb", "roq", "svi", "swf", "viv", "vob", "webm", "wmv", "yuv", -> true else -> false } public fun HttpUrl.isLikelyAudio(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "3gp", "8svx", "aa", "aac", "aax", "act", "aiff", "alac", "amr", "ape", "au", "awb", "cda", "dss", "dvf", "flac", "gsm", "iklax", "ivs", "m3u", "m4a", "m4b", "m4p", "mmf", "mogg", "mp3", "mpc", "msv", "nmf", "ogg", "opus", "raw", "rf64", "rm", "sln", "tta", "voc", "vox", "wav", "webm", "wma", "wv", -> true else -> false } public fun HttpUrl.isLikelyImage(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "ai", "arw", "bmp", "cr2", "dib", "eps", "gif", "heic", "heif", "ico", "ind", "indd", "indt", "j2k", "jfi", "jfif", "jif", "jp2", "jpe", "jpeg", "jpf", "jpg", "jpm", "jpx", "k25", "mj2", "nrw", "pdf", "png", "psd", "raw", "svg", "svgz", "tif", "tiff", "webp", -> true else -> false } public fun HttpUrl.isLikelyBinaryDocument(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "doc", "pdf", "ppt", "rtf", "swf", "xls", -> true else -> false } public fun HttpUrl.isLikelyArchive(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "7z", "deb", "gz", "rar", "rpm", "tgz", "zip", -> true else -> false } public fun HttpUrl.isLikelyExecutable(): Boolean = when (encodedPath.substringAfterLast(".").lowercase()) { "bat", "bin", "dmg", "exe", -> true else -> false } @Suppress("unused") public fun HttpUrl.resolveRedirects(): HttpUrl { var urlBeforeThisPass = this var urlAfterThisPass = this while (true) { // Go through redirectors multiple times while the URL is still being changed. REDIRECTORS.forEach { redirector -> if (redirector.matches(urlBeforeThisPass)) { urlAfterThisPass = redirector.resolve(urlBeforeThisPass) } } if (urlBeforeThisPass == urlAfterThisPass) { return urlAfterThisPass } else { urlBeforeThisPass = urlAfterThisPass } } } private val REDIRECTORS = listOf( object : RedirectPattern { // Facebook. override fun matches(url: HttpUrl) = url.host.endsWith(".facebook.com") && url.encodedPath == "/l.php" override fun resolve(url: HttpUrl) = url.queryParameter("u")?.toHttpUrlOrNull() ?: url }, object : RedirectPattern { // Google. override fun matches(url: HttpUrl) = url.host.endsWith(".google.com") && url.encodedPath == "/url" override fun resolve(url: HttpUrl) = (url.queryParameter("q") ?: url.queryParameter("url"))?.toHttpUrlOrNull() ?: url } ) /** * Defines a pattern used by a specific service for URL redirection. This should be stateless, and will be called for * each URL that needs to be resolved. */ internal interface RedirectPattern { /** @return true if this RedirectPattern can handle the provided URL, false if not. */ fun matches(url: HttpUrl): Boolean /** @return the actual URL that is pointed to by this redirector URL. */ fun resolve(url: HttpUrl): HttpUrl }
apache-2.0
5f4aa9f4b31c6ecfe6c1e0832a27b2fc
17.887892
117
0.599003
3.155056
false
false
false
false
HouHanLab/Android-HHLibrary
listofbooks/src/main/java/library/houhan/com/listofbooks/ListOfBooksFragment.kt
1
4426
package library.houhan.com.listofbooks import android.animation.ObjectAnimator import android.content.Context import android.support.design.widget.FloatingActionButton import android.support.design.widget.Snackbar import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.GestureDetector import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import bean.ListOfBooksBean import com.alibaba.android.arouter.facade.annotation.Route import constant.Constant import library.houhan.com.base.BaseAdapter import library.houhan.com.base.BaseFragment import kotlinx.android.synthetic.main.fragment_list_of_books.* import util.EndLessOnScrollListener import util.LogUtil /** * 作用 书籍列表的Fragment * Created by 司马林 on 2017/10/13. */ @Route(path = Constant.LIST_OF_BOOKS) class ListOfBooksFragment : BaseFragment<ListOfBooksView, ListOfBooksPresenter>(), ListOfBooksView { var status: Int = 0//筛选条件 0:全部 1:可借 2:不可借 val pageSize: Int = 10//列表数据尺寸 var pageIndex: Int = 1//列表页数 val linearLayoutManager: LinearLayoutManager = LinearLayoutManager(activity) lateinit var adapter: BaseAdapter<ListOfBooksBean.Content> val rv: RecyclerView by lazy { list_of_books_rv } val refresh: SwipeRefreshLayout by lazy { books_refresh } val top: FloatingActionButton by lazy { move_top } val presenter: ListOfBooksPresenterImpl = ListOfBooksPresenterImpl(ListOfBooksModelImpl()) override fun showSnack(msg: String) { Snackbar.make(coordinator, msg, Snackbar.LENGTH_SHORT).show() } override fun getLayoutId(): Int = R.layout.fragment_list_of_books override fun initPresenter(): ListOfBooksPresenter = presenter override fun initView() { refresh.setOnRefreshListener { pageIndex = 1 presenter.refresh(pageSize, pageIndex, status) } rv.addOnScrollListener(object : EndLessOnScrollListener(linearLayoutManager) { override fun onSlideUp() { top.visibility = View.VISIBLE } override fun onSlideDown() { top.visibility = View.GONE } override fun isFirst(isFirst: Boolean) { if (isFirst) { top.visibility = View.GONE } } override fun onLoadMore(pageIndex: Int) { LogUtil.i("pageIndex = " + pageIndex) presenter.loadMore(pageSize, pageIndex, status) } }) } override fun initData() { presenter.refresh(pageSize, pageIndex, status) //置顶 top.setOnClickListener { rv.smoothScrollToPosition(0) } } override fun setRvAdapter(mAdapter: BaseAdapter<ListOfBooksBean.Content>) { adapter = mAdapter rv.layoutManager = linearLayoutManager rv.itemAnimator = DefaultItemAnimator() rv.adapter = adapter val headerView: View = LayoutInflater.from(activity).inflate(R.layout.list_of_books_header, rv, false) adapter.setHeaderView(headerView) val spinner: Spinner = headerView.findViewById(R.id.spinner) setSpinner(spinner) } fun setSpinner(spinner: Spinner) { val spinnerAdapter: ArrayAdapter<String> = ArrayAdapter(activity, R.layout.spinner_item, arrayOf("全部", "闲置", "已借出")) spinner.adapter = spinnerAdapter spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) { status = i presenter.refresh(pageSize, pageIndex, status) } override fun onNothingSelected(adapterView: AdapterView<*>) { } } } override fun getListOfBooksActivity(): Context = activity override fun adapterNotifyDataSetChanged() { adapter.notifyDataSetChanged() } override fun adapterRefresh() { adapter.notifyDataSetChanged() refresh.isRefreshing = false } }
apache-2.0
98402b08dd8ad06e78efa92b58d12e50
31.155556
124
0.686866
4.686825
false
false
false
false
Ztiany/Repository
Gradle/gradle_plugin_android_aspectjx_source_v2/app/src/main/java/com/ztiany/androidnew/MainActivity.kt
2
2138
package com.ztiany.androidnew import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import com.ztiany.androidnew.aop.StatisticEvent import com.ztiany.androidnew.ui.BlankFragment import com.ztiany.androidnew.ui.main.MainFragment import com.ztiany.androidnew.ui.page2.Page2Fragment import com.ztiany.androidnew.ui.page3.Page3Fragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .add(R.id.container, MainFragment.newInstance()) .add(BlankFragment(), "BlankFragment") .commit() } } @StatisticEvent("open2") fun open2(view: View) { supportFragmentManager.beginTransaction() .addToBackStack("Page 2") .add(R.id.container, Page2Fragment()) .apply { supportFragmentManager.findFragmentById(R.id.container)?.let { hide(it) } } .commit() } private fun currentVisibleFragment(): List<Fragment> { supportFragmentManager.fragments.forEach { Log.d("MainActivity", "${it::class.java.simpleName} it.isHidden = ${it.isHidden} isAdded = ${it.isAdded} isVisible = ${it.isVisible} isResumed = ${it.isResumed}") } return supportFragmentManager.fragments.filter { it.isVisible } } @StatisticEvent("open3") fun open3(view: View) { supportFragmentManager.beginTransaction() .addToBackStack("Page 3") .add(R.id.container, Page3Fragment()) .apply { supportFragmentManager.findFragmentById(R.id.container)?.let { hide(it) } } .commit() } }
apache-2.0
80934682c1be9501225309a46f19dbba
32.40625
177
0.600094
4.772321
false
false
false
false
cashapp/sqldelight
sqldelight-gradle-plugin/src/main/kotlin/app/cash/sqldelight/gradle/android/PackageName.kt
1
1133
package app.cash.sqldelight.gradle.android import app.cash.sqldelight.VERSION import com.android.build.gradle.BaseExtension import org.gradle.api.GradleException import org.gradle.api.Project internal fun Project.packageName(): String { val androidExtension = extensions.getByType(BaseExtension::class.java) return androidExtension.namespace ?: throw GradleException( """ |SqlDelight requires a package name to be set. This can be done via the android namespace: | |android { | namespace "com.example.mypackage" |} | |or the sqldelight configuration: | |sqldelight { | MyDatabase { | packageName = "com.example.mypackage" | } |} """.trimMargin(), ) } internal fun Project.sqliteVersion(): String? { val androidExtension = extensions.getByType(BaseExtension::class.java) val minSdk = androidExtension.defaultConfig.minSdk ?: return null if (minSdk >= 31) return "app.cash.sqldelight:sqlite-3-30-dialect:$VERSION" if (minSdk >= 30) return "app.cash.sqldelight:sqlite-3-25-dialect:$VERSION" return "app.cash.sqldelight:sqlite-3-18-dialect:$VERSION" }
apache-2.0
1559ee083498e482662f89c5e67e71be
31.371429
94
0.719329
3.961538
false
true
false
false
google-developer-training/basic-android-kotlin-compose-training-cupcake
app/src/main/java/com/example/cupcake/ui/OrderViewModel.kt
1
3952
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.cupcake.ui import androidx.lifecycle.ViewModel import com.example.cupcake.data.OrderUiState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale /** Price for a single cupcake */ private const val PRICE_PER_CUPCAKE = 2.00 /** Additional cost for same day pickup of an order */ private const val PRICE_FOR_SAME_DAY_PICKUP = 3.00 /** * [OrderViewModel] holds information about a cupcake order in terms of quantity, flavor, and * pickup date. It also knows how to calculate the total price based on these order details. */ class OrderViewModel : ViewModel() { /** * Cupcake state for this order */ private val _uiState = MutableStateFlow(OrderUiState(pickupOptions = pickupOptions())) val uiState: StateFlow<OrderUiState> = _uiState.asStateFlow() /** * Set the quantity [numberCupcakes] of cupcakes for this order's state and update the price */ fun setQuantity(numberCupcakes: Int) { _uiState.update { currentState -> currentState.copy( quantity = numberCupcakes, price = calculatePrice(quantity = numberCupcakes) ) } } /** * Set the [desiredFlavor] of cupcakes for this order's state. * Only 1 flavor can be selected for the whole order. */ fun setFlavor(desiredFlavor: String) { _uiState.update { currentState -> currentState.copy(flavor = desiredFlavor) } } /** * Set the [pickupDate] for this order's state and update the price */ fun setDate(pickupDate: String) { _uiState.update { currentState -> currentState.copy( date = pickupDate, price = calculatePrice(pickupDate = pickupDate) ) } } /** * Reset the order state */ fun resetOrder() { _uiState.value = OrderUiState(pickupOptions = pickupOptions()) } /** * Returns the calculated price based on the order details. */ private fun calculatePrice( quantity: Int = _uiState.value.quantity, pickupDate: String = _uiState.value.date ): String { var calculatedPrice = quantity * PRICE_PER_CUPCAKE // If the user selected the first option (today) for pickup, add the surcharge if (pickupOptions()[0] == pickupDate) { calculatedPrice += PRICE_FOR_SAME_DAY_PICKUP } val formattedPrice = NumberFormat.getCurrencyInstance().format(calculatedPrice) return formattedPrice } /** * Returns a list of date options starting with the current date and the following 3 dates. */ private fun pickupOptions(): List<String> { val dateOptions = mutableListOf<String>() val formatter = SimpleDateFormat("E MMM d", Locale.getDefault()) val calendar = Calendar.getInstance() // add current date and the following 3 dates. repeat(4) { dateOptions.add(formatter.format(calendar.time)) calendar.add(Calendar.DATE, 1) } return dateOptions } }
apache-2.0
ea5c3c45e6edbf5f6a666b386bdba19c
32.491525
96
0.663968
4.420582
false
false
false
false
hannesa2/owncloud-android
owncloudApp/src/main/java/com/owncloud/android/ui/activity/DrawerActivity.kt
1
30033
/* * ownCloud Android client application * * @author Andy Scherzinger * @author Christian Schabesberger * @author David González Verdugo * @author Shashvat Kedia * @author Abel García de Prada * @author Juan Carlos Garrote Gascón * Copyright (C) 2021 ownCloud GmbH. * <p> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * <p> * 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. * <p> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.ui.activity import android.accounts.Account import android.accounts.AccountManager import android.accounts.AccountManagerFuture import android.accounts.OnAccountsUpdateListener import android.app.Activity import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import android.widget.ImageView import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.widget.AppCompatImageView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.view.GravityCompat import androidx.core.view.isVisible import androidx.drawerlayout.widget.DrawerLayout import androidx.drawerlayout.widget.DrawerLayout.DrawerListener import com.google.android.material.bottomnavigation.BottomNavigationView import com.google.android.material.navigation.NavigationView import com.google.zxing.integration.android.IntentIntegrator import com.owncloud.android.BuildConfig import com.owncloud.android.MainApp.Companion.initDependencyInjection import com.owncloud.android.R import com.owncloud.android.authentication.AccountUtils import com.owncloud.android.extensions.goToUrl import com.owncloud.android.extensions.openPrivacyPolicy import com.owncloud.android.extensions.sendEmail import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.ui.settings.SettingsActivity import com.owncloud.android.presentation.viewmodels.drawer.DrawerViewModel import com.owncloud.android.utils.AvatarUtils import com.owncloud.android.utils.DisplayUtils import com.owncloud.android.utils.PreferenceUtils import info.hannes.github.AppUpdateHelper.checkForNewVersion import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber import kotlin.math.ceil /** * Base class to handle setup of the drawer implementation including user switching and avatar fetching and fallback * generation. */ abstract class DrawerActivity : ToolbarActivity() { private val drawerViewModel by viewModel<DrawerViewModel>() private var menuAccountAvatarRadiusDimension = 0f private var currentAccountAvatarRadiusDimension = 0f private var otherAccountAvatarRadiusDimension = 0f private var drawerToggle: ActionBarDrawerToggle? = null private var isAccountChooserActive = false private var checkedMenuItem = Menu.NONE /** * accounts for the (max) three displayed accounts in the drawer header. */ private var accountsWithAvatars = arrayOfNulls<Account>(3) /** * Initializes the drawer and its content. * This method needs to be called after the content view has been set. */ protected open fun setupDrawer() { // Allow or disallow touches with other visible windows getDrawerLayout()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this) getNavView()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this) // Set background header image and logo, if any if (resources.getBoolean(R.bool.use_drawer_background_header)) { getDrawerHeaderBackground()?.setImageResource(R.drawable.drawer_header_background) } if (resources.getBoolean(R.bool.use_drawer_logo)) { getDrawerLogo()?.setImageResource(R.drawable.drawer_logo) } getDrawerAccountChooserToggle()?.setImageResource(R.drawable.ic_down) isAccountChooserActive = false //Notch support getNavView()?.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { v.rootWindowInsets.displayCutout?.let { getDrawerActiveUser()?.layoutParams?.height = DisplayUtils.getDrawerHeaderHeight(it.safeInsetTop, resources) } } } override fun onViewDetachedFromWindow(v: View) {} }) setupDrawerContent() getDrawerActiveUser()?.setOnClickListener { toggleAccountList() } drawerToggle = object : ActionBarDrawerToggle(this, getDrawerLayout(), R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely closed state. */ override fun onDrawerClosed(view: View) { super.onDrawerClosed(view) // standard behavior of drawer is to switch to the standard menu on closing if (isAccountChooserActive) { toggleAccountList() } drawerToggle?.isDrawerIndicatorEnabled = false invalidateOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ override fun onDrawerOpened(drawerView: View) { super.onDrawerOpened(drawerView) drawerToggle?.isDrawerIndicatorEnabled = true invalidateOptionsMenu() } } // Set the drawer toggle as the DrawerListener getDrawerLayout()?.addDrawerListener(drawerToggle as ActionBarDrawerToggle) drawerToggle?.isDrawerIndicatorEnabled = false } /** * setup drawer content, basically setting the item selected listener. * */ protected open fun setupDrawerContent() { val navigationView: NavigationView = getNavView() ?: return // Disable help or feedback on customization if (!resources.getBoolean(R.bool.help_enabled)) { navigationView.menu.removeItem(R.id.drawer_menu_help) } if (!resources.getBoolean(R.bool.feedback_enabled)) { navigationView.menu.removeItem(R.id.drawer_menu_feedback) } if (!resources.getBoolean(R.bool.multiaccount_support)) { navigationView.menu.removeItem(R.id.drawer_menu_accounts) } if (!resources.getBoolean(R.bool.privacy_policy_enabled)) { navigationView.menu.removeItem(R.id.drawer_menu_privacy_policy) } navigationView.setNavigationItemSelectedListener { menuItem: MenuItem -> getDrawerLayout()?.closeDrawers() when (menuItem.itemId) { R.id.nav_settings -> { val settingsIntent = Intent(applicationContext, SettingsActivity::class.java) startActivity(settingsIntent) } R.id.drawer_menu_account_add -> createAccount(false) R.id.drawer_menu_account_manage -> { val manageAccountsIntent = Intent(applicationContext, ManageAccountsActivity::class.java) startActivityForResult(manageAccountsIntent, ACTION_MANAGE_ACCOUNTS) } R.id.drawer_menu_feedback -> openFeedback() R.id.nav_check_update -> checkForNewVersion( this@DrawerActivity, BuildConfig.GIT_REPOSITORY, BuildConfig.VERSION_NAME ) R.id.nav_qr -> IntentIntegrator(this).initiateScan() R.id.drawer_menu_help -> openHelp() R.id.drawer_menu_privacy_policy -> openPrivacyPolicy() Menu.NONE -> { accountClicked(menuItem.title.toString()) } else -> Timber.i("Unknown drawer menu item clicked: %s", menuItem.title) } true } // handle correct state navigationView.menu.setGroupVisible(R.id.drawer_menu_accounts, isAccountChooserActive) } fun setCheckedItemAtBottomBar(checkedMenuItem: Int) { getBottomNavigationView()?.menu?.findItem(checkedMenuItem)?.isChecked = true } /** * Initializes the bottom navigation bar, its content and highlights the menu item with the given id. * This method needs to be called after the content view has been set. * * @param menuItemId the menu item to be checked/highlighted */ open fun setupNavigationBottomBar(menuItemId: Int) { // Allow or disallow touches with other visible windows getBottomNavigationView()?.filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(this) setCheckedItemAtBottomBar(menuItemId) getBottomNavigationView()?.setOnNavigationItemSelectedListener { menuItem: MenuItem -> bottomBarNavigationTo(menuItem.itemId, getBottomNavigationView()?.selectedItemId == menuItem.itemId) true } } private fun bottomBarNavigationTo(menuItemId: Int, isCurrentOptionActive: Boolean) { when (menuItemId) { R.id.nav_all_files -> navigateToOption(FileListOption.ALL_FILES) R.id.nav_uploads -> if (!isCurrentOptionActive) { val uploadListIntent = Intent(applicationContext, UploadListActivity::class.java) uploadListIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) startActivity(uploadListIntent) } R.id.nav_available_offline_files -> navigateToOption(FileListOption.AV_OFFLINE) R.id.nav_shared_by_link_files -> navigateToOption(FileListOption.SHARED_BY_LINK) } } private fun openHelp() { goToUrl(url = getString(R.string.url_help)) } private fun openFeedback() { val feedbackMail = getString(R.string.mail_feedback) val feedback = "Android v" + BuildConfig.VERSION_NAME + " - " + getString(R.string.drawer_feedback) sendEmail(email = feedbackMail, subject = feedback) } /** * sets the new/current account and restarts. In case the given account equals the actual/current account the * call will be ignored. * * @param accountName The account name to be set */ private fun accountClicked(accountName: String) { if (drawerViewModel.getCurrentAccount(this)?.name != accountName) { if (drawerViewModel.setCurrentAccount(applicationContext, accountName)) { // Refresh dependencies to be used in selected account initDependencyInjection() restart() } else { Timber.d("Was not able to change account") // TODO: Handle this error (?) } } } /** * click method for mini avatars in drawer header. * * @param view the clicked ImageView */ open fun onAccountDrawerClick(view: View) { accountClicked(view.contentDescription.toString()) } /** * checks if the drawer exists and is opened. * * @return `true` if the drawer is open, else `false` */ open fun isDrawerOpen(): Boolean = getDrawerLayout()?.isDrawerOpen(GravityCompat.START) ?: false /** * closes the drawer. */ open fun closeDrawer() { getDrawerLayout()?.closeDrawer(GravityCompat.START) } /** * opens the drawer. */ open fun openDrawer() { getDrawerLayout()?.openDrawer(GravityCompat.START) } /** * Enable or disable interaction with all drawers. * * @param lockMode The new lock mode for the given drawer. One of [DrawerLayout.LOCK_MODE_UNLOCKED], * [DrawerLayout.LOCK_MODE_LOCKED_CLOSED] or [DrawerLayout.LOCK_MODE_LOCKED_OPEN]. */ open fun setDrawerLockMode(lockMode: Int) { getDrawerLayout()?.setDrawerLockMode(lockMode) } /** * updates the account list in the drawer. */ private fun updateAccountList() { val accounts = drawerViewModel.getAccounts(this) if (getNavView() != null && getDrawerLayout() != null) { if (accounts.isNotEmpty()) { repopulateAccountList(accounts) setAccountInDrawer(drawerViewModel.getCurrentAccount(this) ?: accounts.first()) populateDrawerOwnCloudAccounts() // activate second/end account avatar accountsWithAvatars[1]?.let { account -> getDrawerAccountEnd()?.let { AvatarUtils().loadAvatarForAccount( imageView = it, account = account, displayRadius = otherAccountAvatarRadiusDimension ) } } if (accountsWithAvatars[1] == null) { getDrawerAccountEnd()?.isVisible = false } // activate third/middle account avatar accountsWithAvatars[2]?.let { account -> getDrawerAccountMiddle()?.let { AvatarUtils().loadAvatarForAccount( imageView = it, account = account, displayRadius = otherAccountAvatarRadiusDimension ) } } if (accountsWithAvatars[2] == null) { getDrawerAccountMiddle()?.isVisible = false } } else { getDrawerAccountEnd()?.isVisible = false getDrawerAccountMiddle()?.isVisible = false } } } /** * re-populates the account list. * * @param accounts list of accounts */ private fun repopulateAccountList(accounts: List<Account>?) { val navigationView = getNavView() ?: return val navigationMenu = navigationView.menu // remove all accounts from list navigationMenu.removeGroup(R.id.drawer_menu_accounts) // add all accounts to list except current one accounts?.filter { it.name != account?.name }?.forEach { val accountMenuItem: MenuItem = navigationMenu.add(R.id.drawer_menu_accounts, Menu.NONE, MENU_ORDER_ACCOUNT, it.name) AvatarUtils().loadAvatarForAccount( menuItem = accountMenuItem, account = it, fetchIfNotCached = false, displayRadius = menuAccountAvatarRadiusDimension ) } // re-add add-account and manage-accounts if (getResources().getBoolean(R.bool.multiaccount_support)) { navigationMenu.add( R.id.drawer_menu_accounts, R.id.drawer_menu_account_add, MENU_ORDER_ACCOUNT_FUNCTION, resources.getString(R.string.prefs_add_account) ).setIcon(R.drawable.ic_plus_grey) } navigationMenu.add( R.id.drawer_menu_accounts, R.id.drawer_menu_account_manage, MENU_ORDER_ACCOUNT_FUNCTION, resources.getString(R.string.drawer_manage_accounts) ).setIcon(R.drawable.ic_group) // adding sets menu group back to visible, so safety check and setting invisible showMenu() } /** * Updates the quota in the drawer */ private fun updateQuota() { Timber.d("Update Quota") val account = drawerViewModel.getCurrentAccount(this) ?: return drawerViewModel.getStoredQuota(account.name) drawerViewModel.userQuota.observe(this) { event -> when (val uiResult = event.peekContent()) { is UIResult.Success -> { uiResult.data?.let { userQuota -> when { userQuota.available < 0 -> { // Pending, unknown or unlimited free storage getAccountQuotaBar()?.run { isVisible = true progress = 0 } getAccountQuotaText()?.text = String.format( getString(R.string.drawer_unavailable_free_storage), DisplayUtils.bytesToHumanReadable(userQuota.used, this) ) } userQuota.available == 0L -> { // Quota 0, guest users getAccountQuotaBar()?.isVisible = false getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage) } else -> { // Limited quota // Update progress bar rounding up to next int. Example: quota is 0.54 => 1 getAccountQuotaBar()?.run { progress = ceil(userQuota.getRelative()).toInt() isVisible = true } getAccountQuotaText()?.text = String.format( getString(R.string.drawer_quota), DisplayUtils.bytesToHumanReadable(userQuota.used, this), DisplayUtils.bytesToHumanReadable(userQuota.getTotal(), this), userQuota.getRelative() ) } } } } is UIResult.Loading -> getAccountQuotaText()?.text = getString(R.string.drawer_loading_quota) is UIResult.Error -> getAccountQuotaText()?.text = getString(R.string.drawer_unavailable_used_storage) } } } override fun setupRootToolbar(title: String, isSearchEnabled: Boolean) { super.setupRootToolbar(title, isSearchEnabled) val toolbarLeftIcon = findViewById<ImageView>(R.id.root_toolbar_left_icon) toolbarLeftIcon.setOnClickListener { openDrawer() } } /** * Sets the given account data in the drawer in case the drawer is available. The account name is shortened * beginning from the @-sign in the username. * * @param account the account to be set in the drawer */ protected fun setAccountInDrawer(account: Account) { if (getDrawerLayout() != null) { getDrawerUserNameFull()?.text = account.name try { val ocAccount = OwnCloudAccount(account, this) getDrawerUserName()?.text = ocAccount.displayName } catch (e: Exception) { Timber.w("Couldn't read display name of account; using account name instead") getDrawerUserName()?.text = AccountUtils.getUsernameOfAccount(account.name) } getDrawerCurrentAccount()?.let { AvatarUtils().loadAvatarForAccount( imageView = it, account = account, displayRadius = currentAccountAvatarRadiusDimension ) updateQuota() } } } /** * Toggle between standard menu and account list including saving the state. */ private fun toggleAccountList() { isAccountChooserActive = !isAccountChooserActive showMenu() } /** * depending on the #mIsAccountChooserActive flag shows the account chooser or the standard menu. */ private fun showMenu() { val navigationView = getNavView() ?: return val accountCount = drawerViewModel.getAccounts(this).size getDrawerAccountChooserToggle()?.setImageResource(if (isAccountChooserActive) R.drawable.ic_up else R.drawable.ic_down) navigationView.menu.setGroupVisible(R.id.drawer_menu_accounts, isAccountChooserActive) navigationView.menu.setGroupVisible(R.id.drawer_menu_settings_etc, !isAccountChooserActive) getDrawerLogo()?.isVisible = !isAccountChooserActive || accountCount < USER_ITEMS_ALLOWED_BEFORE_REMOVING_CLOUD } /** * checks/highlights the provided menu item if the drawer has been initialized and the menu item exists. * * @param menuItemId the menu item to be highlighted */ protected open fun setDrawerMenuItemChecked(menuItemId: Int) { val navigationView = getNavView() if (navigationView != null && navigationView.menu.findItem(menuItemId) != null) { navigationView.menu.findItem(menuItemId).isChecked = true checkedMenuItem = menuItemId } else { Timber.w("setDrawerMenuItemChecked has been called with invalid menu-item-ID") } } private fun cleanupUnusedAccountDirectories() { val accountManager = AccountManager.get(this) accountManager.addOnAccountsUpdatedListener(OnAccountsUpdateListener { val accounts = AccountUtils.getAccounts(this) drawerViewModel.deleteUnusedUserDirs(accounts) updateAccountList() }, Handler(), false) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { isAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false) checkedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE) } currentAccountAvatarRadiusDimension = resources.getDimension(R.dimen.nav_drawer_header_avatar_radius) otherAccountAvatarRadiusDimension = resources.getDimension(R.dimen.nav_drawer_header_avatar_other_accounts_radius) menuAccountAvatarRadiusDimension = resources.getDimension(R.dimen.nav_drawer_menu_avatar_radius) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, isAccountChooserActive) outState.putInt(KEY_CHECKED_MENU_ITEM, checkedMenuItem) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) isAccountChooserActive = savedInstanceState.getBoolean(KEY_IS_ACCOUNT_CHOOSER_ACTIVE, false) checkedMenuItem = savedInstanceState.getInt(KEY_CHECKED_MENU_ITEM, Menu.NONE) // (re-)setup drawer state showMenu() // check/highlight the menu item if present if (checkedMenuItem != Menu.NONE) { setDrawerMenuItemChecked(checkedMenuItem) } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle?.let { it.syncState() if (isDrawerOpen()) { it.isDrawerIndicatorEnabled = true } } updateAccountList() updateQuota() cleanupUnusedAccountDirectories() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) drawerToggle?.onConfigurationChanged(newConfig) } override fun onBackPressed() { if (isDrawerOpen()) { closeDrawer() return } super.onBackPressed() } override fun onResume() { super.onResume() setDrawerMenuItemChecked(checkedMenuItem) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // update Account list and active account if Manage Account activity replies with // - ACCOUNT_LIST_CHANGED = true // - RESULT_OK if (requestCode == ACTION_MANAGE_ACCOUNTS && resultCode == Activity.RESULT_OK && data!!.getBooleanExtra( ManageAccountsActivity.KEY_ACCOUNT_LIST_CHANGED, false ) ) { // current account has changed if (data.getBooleanExtra(ManageAccountsActivity.KEY_CURRENT_ACCOUNT_CHANGED, false)) { account = AccountUtils.getCurrentOwnCloudAccount(this) // Refresh dependencies to be used in selected account initDependencyInjection() restart() } else { updateAccountList() updateQuota() } } val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data) if (result != null) { if (result.contents == null) { displayToast("Cancelled from fragment") } else { var url = result.contents if (!result.contents.startsWith("http://") && !result.contents.startsWith("https://")) url = "http://" + result.contents val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(browserIntent) displayToast(result.contents) } finish() } } private fun displayToast(toast: String) { Toast.makeText(this, toast, Toast.LENGTH_LONG).show() } override fun onAccountCreationSuccessful(future: AccountManagerFuture<Bundle?>?) { super.onAccountCreationSuccessful(future) updateAccountList() updateQuota() // Refresh dependencies to be used in selected account initDependencyInjection() restart() } /** * populates the avatar drawer array with the first three ownCloud [Account]s while the first element is * always the current account. */ private fun populateDrawerOwnCloudAccounts() { accountsWithAvatars = arrayOfNulls(3) val accountsAll = drawerViewModel.getAccounts(this) val currentAccount = drawerViewModel.getCurrentAccount(this) val otherAccounts = accountsAll.filter { it != currentAccount } accountsWithAvatars[0] = currentAccount accountsWithAvatars[1] = otherAccounts.getOrNull(0) accountsWithAvatars[2] = otherAccounts.getOrNull(1) } private fun getDrawerLayout(): DrawerLayout? = findViewById(R.id.drawer_layout) private fun getNavView(): NavigationView? = findViewById(R.id.nav_view) private fun getDrawerLogo(): AppCompatImageView? = findViewById(R.id.drawer_logo) private fun getBottomNavigationView(): BottomNavigationView? = findViewById(R.id.bottom_nav_view) private fun getAccountQuotaText(): TextView? = findViewById(R.id.account_quota_text) private fun getAccountQuotaBar(): ProgressBar? = findViewById(R.id.account_quota_bar) private fun getDrawerAccountChooserToggle() = findNavigationViewChildById(R.id.drawer_account_chooser_toggle) as ImageView? private fun getDrawerAccountEnd() = findNavigationViewChildById(R.id.drawer_account_end) as ImageView? private fun getDrawerAccountMiddle() = findNavigationViewChildById(R.id.drawer_account_middle) as ImageView? private fun getDrawerActiveUser() = findNavigationViewChildById(R.id.drawer_active_user) as ConstraintLayout? private fun getDrawerCurrentAccount() = findNavigationViewChildById(R.id.drawer_current_account) as AppCompatImageView? private fun getDrawerHeaderBackground() = findNavigationViewChildById(R.id.drawer_header_background) as ImageView? private fun getDrawerUserName(): TextView? = findNavigationViewChildById(R.id.drawer_username) as TextView? private fun getDrawerUserNameFull(): TextView? = findNavigationViewChildById(R.id.drawer_username_full) as TextView? /** * Finds a view that was identified by the id attribute from the drawer header. * * @param id the view's id * @return The view if found or `null` otherwise. */ private fun findNavigationViewChildById(id: Int): View { return (findViewById<View>(R.id.nav_view) as NavigationView).getHeaderView(0).findViewById(id) } /** * Adds other listeners to react on changes of the drawer layout. * * @param listener Object interested in changes of the drawer layout. */ open fun addDrawerListener(listener: DrawerListener) { getDrawerLayout()?.addDrawerListener(listener) } abstract fun navigateToOption(fileListOption: FileListOption) /** * restart helper method which is called after a changing the current account. */ protected abstract fun restart() companion object { private const val KEY_IS_ACCOUNT_CHOOSER_ACTIVE = "IS_ACCOUNT_CHOOSER_ACTIVE" private const val KEY_CHECKED_MENU_ITEM = "CHECKED_MENU_ITEM" private const val ACTION_MANAGE_ACCOUNTS = 101 private const val MENU_ORDER_ACCOUNT = 1 private const val MENU_ORDER_ACCOUNT_FUNCTION = 2 private const val USER_ITEMS_ALLOWED_BEFORE_REMOVING_CLOUD = 4 } }
gpl-2.0
4f0c142f7d0b60de33cf98ea7b947cc2
41.176966
129
0.636663
5.095876
false
false
false
false
arsich/messenger
app/src/main/kotlin/ru/arsich/messenger/mvp/models/DialogsRepository.kt
1
2525
package ru.arsich.messenger.mvp.models import com.vk.sdk.api.VKError import com.vk.sdk.api.VKRequest import com.vk.sdk.api.VKResponse import com.vk.sdk.api.model.VKList import ru.arsich.messenger.vk.VKApiChat import ru.arsich.messenger.vk.VKChat import java.lang.Exception class DialogsRepository { private val dialogsSubscribers: MutableList<RequestDialogsListener> = mutableListOf() private var dialogsRequest: VKRequest? = null private var dialogsList: List<VKChat> = listOf() fun addDialogsSubscriber(subscriber: RequestDialogsListener) { dialogsSubscribers.add(subscriber) } fun removeDialogsSubscriber(subscriber: RequestDialogsListener) { dialogsSubscribers.remove(subscriber) } fun requestDialogs() { if (dialogsList.isNotEmpty()) { sendDialogsListToSubscribers() return } if (dialogsRequest != null) { return } dialogsRequest = VKApiChat.get() dialogsRequest?.attempts = 3 dialogsRequest?.executeWithListener(object: VKRequest.VKRequestListener() { override fun onComplete(response: VKResponse?) { if (response != null) { dialogsList = (response.parsedModel as VKList<VKChat>).toList() sendDialogsListToSubscribers() } dialogsRequest = null } override fun onError(error: VKError?) { error?.let { if (it.httpError != null) { sendErrorToDialogsSubscribers(it.httpError) } else if (it.apiError != null) { sendErrorToDialogsSubscribers(Exception(it.apiError.errorMessage)) } else { sendErrorToDialogsSubscribers(Exception(it.errorMessage)) } } dialogsRequest = null } }) } fun clearCache() { dialogsList = listOf() } private fun sendDialogsListToSubscribers() { for (subscriber in dialogsSubscribers) { subscriber.onDialogsReceived(dialogsList) } } private fun sendErrorToDialogsSubscribers(error: Exception) { for (subscriber in dialogsSubscribers) { subscriber.onDialogsError(error) } } interface RequestDialogsListener { fun onDialogsReceived(list: List<VKChat>) fun onDialogsError(error: Exception) } }
mit
c3ca019a593d765718abe7283f003e9a
29.804878
90
0.608317
4.95098
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/test/java/com/habitrpg/android/habitica/models/SubscriptionPlanTest.kt
2
1363
package com.habitrpg.android.habitica.models import com.habitrpg.android.habitica.BaseAnnotationTestCase import com.habitrpg.android.habitica.models.user.SubscriptionPlan import io.kotest.core.spec.style.AnnotationSpec import io.kotest.matchers.shouldBe import java.util.Calendar import java.util.Date class SubscriptionPlanTest : BaseAnnotationTestCase() { private var plan: SubscriptionPlan? = null @AnnotationSpec.BeforeEach fun setUp() { plan = SubscriptionPlan() plan!!.customerId = "fake_customer_id" plan!!.planId = "test" } @get:Test val isActiveForNoTerminationDate: Unit get() { plan?.isActive shouldBe true } @get:Test val isActiveForLaterTerminationDate: Unit get() { val calendar = Calendar.getInstance() calendar.time = Date() calendar.add(Calendar.DATE, 1) plan!!.dateTerminated = calendar.time plan?.isActive shouldBe true } @get:Test val isInactiveForEarlierTerminationDate: Unit get() { val calendar = Calendar.getInstance() calendar.time = Date() calendar.add(Calendar.DATE, -1) plan!!.dateTerminated = calendar.time plan?.isActive shouldBe false } }
gpl-3.0
e9e4bffad181b2ca9cf48177a19c14ea
28.977273
65
0.627293
4.620339
false
true
false
false
yzbzz/beautifullife
app/src/main/java/com/ddu/ui/activity/phrase/OneSeparatorActivity.kt
2
1778
package com.ddu.ui.activity.phrase import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.text.style.StrikethroughSpan import android.text.style.StyleSpan import android.text.style.UnderlineSpan import androidx.appcompat.app.AppCompatActivity import com.ddu.R import com.ddu.icore.util.StylePhrase import kotlinx.android.synthetic.main.activity_one_separator.* class OneSeparatorActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_one_separator) val oneSeparatorString = getString(R.string.text_phrase_one) tv_description.text = "一种分割符" tv_original.text = oneSeparatorString // 设置字体和颜色 val colorAndSize = StylePhrase(oneSeparatorString) .setInnerFirstColor(Color.BLUE) .setInnerFirstSize(20) tv_content.text = colorAndSize.format() // 设置粗斜体 val boldPhrase = StylePhrase(oneSeparatorString) boldPhrase.firstBuilder.addParcelableSpan(StyleSpan(Typeface.BOLD_ITALIC)) tv_content_bold_italic.text = boldPhrase.format() // 设置删除线 val strikeThroughPhrase = StylePhrase(oneSeparatorString) strikeThroughPhrase.firstBuilder.addParcelableSpan(StrikethroughSpan()) tv_content_strike_through.text = strikeThroughPhrase.format() // 设置下划线 val underlinePhrase = StylePhrase(oneSeparatorString) underlinePhrase.firstBuilder.addParcelableSpan(UnderlineSpan()) tv_content_underline.text = underlinePhrase.format() tv_separator.text = colorAndSize.firstBuilder.separator } }
apache-2.0
aeb5e305e08fe488cc2f2a3ca9649e3b
34.916667
82
0.733179
4.536842
false
false
false
false
yakov116/FastHub
app/src/main/java/com/fastaccess/ui/modules/main/notifications/FastHubNotificationDialog.kt
2
2867
package com.fastaccess.ui.modules.main.notifications import android.os.Bundle import android.support.v4.app.FragmentManager import android.view.View import butterknife.BindView import butterknife.OnClick import com.fastaccess.R import com.fastaccess.data.dao.model.AbstractFastHubNotification.NotificationType import com.fastaccess.data.dao.model.FastHubNotification import com.fastaccess.helper.BundleConstant import com.fastaccess.helper.Bundler import com.fastaccess.helper.PrefGetter import com.fastaccess.ui.base.BaseDialogFragment import com.fastaccess.ui.base.mvp.BaseMvp import com.fastaccess.ui.base.mvp.presenter.BasePresenter import com.fastaccess.ui.widgets.FontTextView import com.prettifier.pretty.PrettifyWebView /** * Created by Kosh on 17.11.17. */ class FastHubNotificationDialog : BaseDialogFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() { init { suppressAnimation = true isCancelable = false } @BindView(R.id.title) @JvmField var title: FontTextView? = null @BindView(R.id.webView) @JvmField var webView: PrettifyWebView? = null private val model by lazy { arguments?.getParcelable<FastHubNotification>(BundleConstant.ITEM) } @OnClick(R.id.cancel) fun onCancel() { dismiss() } override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { model?.let { title?.text = it.title webView?.setGithubContent(it.body, null, false, false) it.isRead = true FastHubNotification.update(it) } ?: dismiss() } override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter() override fun fragmentLayout(): Int = R.layout.dialog_guide_layout companion object { @JvmStatic private val TAG = FastHubNotificationDialog::class.java.simpleName fun newInstance(model: FastHubNotification): FastHubNotificationDialog { val fragment = FastHubNotificationDialog() fragment.arguments = Bundler.start() .put(BundleConstant.ITEM, model) .end() return fragment } fun show(fragmentManager: FragmentManager, model: FastHubNotification? = null) { val notification = model ?: FastHubNotification.getLatest() notification?.let { if (it.type == NotificationType.PROMOTION || it.type == NotificationType.PURCHASE && model == null) { if (PrefGetter.isProEnabled()) { it.isRead = true FastHubNotification.update(it) return } } newInstance(it).show(fragmentManager, TAG) } } fun show(fragmentManager: FragmentManager) { show(fragmentManager, null) } } }
gpl-3.0
fcea81273dd17ae766466d5e86a467cc
34.85
117
0.665853
4.738843
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/jobs/CheckServiceReachabilityJob.kt
1
4380
package org.thoughtcrime.securesms.jobs import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.dependencies.ApplicationDependencies import org.thoughtcrime.securesms.jobmanager.Data import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.jobmanager.impl.NetworkConstraint import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.stories.Stories import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState import org.whispersystems.signalservice.internal.util.StaticCredentialsProvider import org.whispersystems.signalservice.internal.websocket.WebSocketConnection import java.util.Optional import java.util.concurrent.TimeUnit /** * Checks to see if a censored user can establish a websocket connection with an uncensored network configuration. */ class CheckServiceReachabilityJob private constructor(params: Parameters) : BaseJob(params) { constructor() : this( Parameters.Builder() .addConstraint(NetworkConstraint.KEY) .setLifespan(TimeUnit.HOURS.toMillis(12)) .setMaxAttempts(1) .build() ) companion object { private val TAG = Log.tag(CheckServiceReachabilityJob::class.java) const val KEY = "CheckServiceReachabilityJob" @JvmStatic fun enqueueIfNecessary() { val isCensored = ApplicationDependencies.getSignalServiceNetworkAccess().isCensored() val timeSinceLastCheck = System.currentTimeMillis() - SignalStore.misc().lastCensorshipServiceReachabilityCheckTime if (SignalStore.account().isRegistered && isCensored && timeSinceLastCheck > TimeUnit.DAYS.toMillis(1)) { ApplicationDependencies.getJobManager().add(CheckServiceReachabilityJob()) } } } override fun serialize(): Data { return Data.EMPTY } override fun getFactoryKey(): String { return KEY } override fun onRun() { if (!SignalStore.account().isRegistered) { Log.w(TAG, "Not registered, skipping.") SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis() return } if (!ApplicationDependencies.getSignalServiceNetworkAccess().isCensored()) { Log.w(TAG, "Not currently censored, skipping.") SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis() return } SignalStore.misc().lastCensorshipServiceReachabilityCheckTime = System.currentTimeMillis() val uncensoredWebsocket = WebSocketConnection( "uncensored-test", ApplicationDependencies.getSignalServiceNetworkAccess().uncensoredConfiguration, Optional.of( StaticCredentialsProvider( SignalStore.account().aci, SignalStore.account().pni, SignalStore.account().e164, SignalStore.account().deviceId, SignalStore.account().servicePassword ) ), BuildConfig.SIGNAL_AGENT, null, "", Stories.isFeatureEnabled() ) try { val startTime = System.currentTimeMillis() val state: WebSocketConnectionState = uncensoredWebsocket.connect() .filter { it == WebSocketConnectionState.CONNECTED || it == WebSocketConnectionState.FAILED } .timeout(30, TimeUnit.SECONDS) .blockingFirst(WebSocketConnectionState.FAILED) if (state == WebSocketConnectionState.CONNECTED) { Log.i(TAG, "Established connection in ${System.currentTimeMillis() - startTime} ms! Service is reachable!") SignalStore.misc().isServiceReachableWithoutCircumvention = true } else { Log.w(TAG, "Failed to establish a connection in ${System.currentTimeMillis() - startTime} ms.") SignalStore.misc().isServiceReachableWithoutCircumvention = false } } catch (exception: Exception) { Log.w(TAG, "Failed to connect to the websocket.", exception) SignalStore.misc().isServiceReachableWithoutCircumvention = false } finally { uncensoredWebsocket.disconnect() } } override fun onShouldRetry(e: Exception): Boolean { return false } override fun onFailure() { } class Factory : Job.Factory<CheckServiceReachabilityJob> { override fun create(parameters: Parameters, data: Data): CheckServiceReachabilityJob { return CheckServiceReachabilityJob(parameters) } } }
gpl-3.0
de5be52a613c5b92dc6289910466d0a4
35.198347
121
0.736758
4.776445
false
false
false
false
androidx/androidx
security/security-crypto-ktx/src/androidTest/java/androidx/security/crypto/KtxTests.kt
3
5497
/* * 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.security.crypto import android.content.Context import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import java.io.File import java.nio.charset.StandardCharsets import java.security.KeyStore private const val PREFS_FILE = "test_shared_prefs" @MediumTest @RunWith(AndroidJUnit4::class) class KtxTests { @Before @Throws(Exception::class) fun setup() { val context = ApplicationProvider.getApplicationContext<Context>() // Delete all previous keys and shared preferences. val parentDir = context.filesDir?.parent ?: throw IllegalStateException("filesDir?.parent is null?") var filePath = ( parentDir + "/shared_prefs/" + "__androidx_security__crypto_encrypted_prefs__" ) var deletePrefFile = File(filePath) deletePrefFile.delete() val notEncryptedSharedPrefs = context.getSharedPreferences( PREFS_FILE, Context.MODE_PRIVATE ) notEncryptedSharedPrefs.edit().clear().commit() filePath = ("$parentDir/shared_prefs/$PREFS_FILE") deletePrefFile = File(filePath) deletePrefFile.delete() val encryptedSharedPrefs = context.getSharedPreferences( "TinkTestPrefs", Context.MODE_PRIVATE ) encryptedSharedPrefs.edit().clear().commit() filePath = ("$parentDir/shared_prefs/TinkTestPrefs") deletePrefFile = File(filePath) deletePrefFile.delete() // Delete MasterKeys val keyStore = KeyStore.getInstance("AndroidKeyStore") keyStore.load(null) keyStore.deleteEntry("_androidx_security_master_key_") } @Test fun testMasterKeyExtension() { val context = ApplicationProvider.getApplicationContext<Context>() val ktxMasterKey = MasterKey( context = context, authenticationRequired = false, userAuthenticationValidityDurationSeconds = 123 ) val jMasterKey = MasterKey.Builder(context) .setKeyScheme(MasterKey.KeyScheme.AES256_GCM) .setUserAuthenticationRequired(false, 123) .build() Assert.assertEquals(ktxMasterKey.keyAlias, jMasterKey.keyAlias) Assert.assertEquals( ktxMasterKey.isUserAuthenticationRequired, jMasterKey.isUserAuthenticationRequired ) Assert.assertEquals( ktxMasterKey.userAuthenticationValidityDurationSeconds, jMasterKey.userAuthenticationValidityDurationSeconds ) } @Test fun testEncryptedSharedPreferencesExtension() { val context = ApplicationProvider.getApplicationContext<Context>() val masterKey = MasterKey(context) val filename = "test" val ktxSharedPreferences = EncryptedSharedPreferences( context = context, fileName = filename, masterKey = masterKey ) ktxSharedPreferences.edit().putString("test_key", "KTX Write").commit() val jSharedPreferences = EncryptedSharedPreferences.create( context, filename, masterKey, EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) val readValue = jSharedPreferences.getString("test_key", "error") Assert.assertEquals(readValue, "KTX Write") } @Test fun testEncryptedFileExtension() { val context = ApplicationProvider.getApplicationContext<Context>() val masterKey = MasterKey(context) val file = File(context.cacheDir, "test.file") val testContent = "This is a test" if (file.exists()) { file.delete() } val ktFile = EncryptedFile(context, file, masterKey) ktFile.openFileOutput().use { it.write("This is a test".toByteArray(StandardCharsets.UTF_8)) } val jFile = EncryptedFile.Builder( context, file, masterKey, EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB ).build() val buffer = ByteArray(1024) jFile.openFileInput().use { val size = it.read(buffer) Assert.assertEquals(size, testContent.length) val contentBuffer = buffer.slice(IntRange(0, size - 1)).toByteArray() val content = String(contentBuffer, StandardCharsets.UTF_8) Assert.assertEquals(testContent, content) } if (!file.exists()) { Assert.fail("File didn't exist?") } file.delete() } }
apache-2.0
c6f58673559a6ac6c63c50d614972f10
33.791139
81
0.655267
4.899287
false
true
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/wordSelection/ElmDeclAnnotationSelectionHandler.kt
1
3538
package org.elm.ide.wordSelection import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.elm.lang.core.psi.elements.ElmTypeAnnotation import org.elm.lang.core.psi.elements.ElmValueDeclaration import org.elm.lang.core.psi.parentOfType /** * Adjusts the 'extend selection' behavior for [ElmValueDeclaration] and [ElmTypeAnnotation] so that they * mutually extend the selection to include the other. */ class ElmDeclAnnotationSelectionHandler : ExtendWordSelectionHandlerBase() { /* The plugin mechanism for refining the default 'extend selection' behavior is poor. Based on tracing the code, here is my understanding of how the internal logic works: It all starts in `SelectWordHandler.doExecute`. Starting with the element at the caret, it creates a selection range that just covers the caret position itself. And it defines an initial minimum range which spans the entire document. It then asks each registered `ExtendWordSelectionHandler` plugin extension point if it can select the thing and if so, to return a list of text ranges describing what it would like to select. Each candidate range is then checked to see if: (a) it would expand the current selection range (b) it is smaller than any candidate range seen so far If both conditions pass, the remaining candidates are ignored and IntelliJ will select the text in the editor described by the candidate that succeeded. Otherwise, the algorithm will walk the Psi tree upwards until it finds a larger selection. In terms of how this affects plugin authors, it appears that the following guidelines should be followed: (1) if you want to return a *larger* selection than would normally be returned for the given element, then you must call `ExtendWordSelectionHandlerBase.expandToWholeLine` with your desired range and return the resulting list of ranges. I have no idea why this is, but it appears to work. (2) if you want to return a *smaller* selection than would normally be returned for the given element, then you can just return the desired range directly. */ override fun canSelect(e: PsiElement): Boolean = e is ElmValueDeclaration || e is ElmTypeAnnotation override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange>? { when (e) { is ElmValueDeclaration -> { // extend the selection so that it also includes the preceding type annotation val typeAnnotation = e.typeAnnotation ?: return null val range = TextRange(typeAnnotation.textRange.startOffset, e.textRange.endOffset) return expandToWholeLine(editorText, range) } is ElmTypeAnnotation -> { // extend the selection so that it also includes the function body val targetDecl = e.reference.resolve() ?: return null val valueDecl = targetDecl.parentOfType<ElmValueDeclaration>()!! val range = TextRange(e.textRange.startOffset, valueDecl.textRange.endOffset) return expandToWholeLine(editorText, range) } else -> return null } } }
mit
c0964e9c088e82478fbd36524e691898
49.557143
119
0.697569
5.149927
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/account/dto/AccountAccountCounters.kt
1
3267
/** * 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.account.dto import com.google.gson.annotations.SerializedName import kotlin.Int /** * @param appRequests - New app requests number * @param events - New events number * @param faves - New faves number * @param friends - New friends requests number * @param friendsSuggestions - New friends suggestions number * @param friendsRecommendations - New friends recommendations number * @param gifts - New gifts number * @param groups - New groups number * @param menuDiscoverBadge * @param menuClipsBadge * @param messages - New messages number * @param memories - New memories number * @param notes - New notes number * @param notifications - New notifications number * @param photos - New photo tags number * @param sdk - New sdk number */ data class AccountAccountCounters( @SerializedName("app_requests") val appRequests: Int? = null, @SerializedName("events") val events: Int? = null, @SerializedName("faves") val faves: Int? = null, @SerializedName("friends") val friends: Int? = null, @SerializedName("friends_suggestions") val friendsSuggestions: Int? = null, @SerializedName("friends_recommendations") val friendsRecommendations: Int? = null, @SerializedName("gifts") val gifts: Int? = null, @SerializedName("groups") val groups: Int? = null, @SerializedName("menu_discover_badge") val menuDiscoverBadge: Int? = null, @SerializedName("menu_clips_badge") val menuClipsBadge: Int? = null, @SerializedName("messages") val messages: Int? = null, @SerializedName("memories") val memories: Int? = null, @SerializedName("notes") val notes: Int? = null, @SerializedName("notifications") val notifications: Int? = null, @SerializedName("photos") val photos: Int? = null, @SerializedName("sdk") val sdk: Int? = null )
mit
4b949b4e1f8981e3291106ea8699418e
37.892857
81
0.685338
4.356
false
false
false
false
angryziber/synology-cast-photos-android
src/net/azib/photos/cast/CastClient.kt
1
5919
package net.azib.photos.cast import android.app.Activity import android.os.Bundle import androidx.mediarouter.media.MediaRouteSelector import androidx.mediarouter.media.MediaRouter import androidx.mediarouter.media.MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY import android.util.Log import android.widget.Toast import com.google.android.gms.cast.Cast import com.google.android.gms.cast.CastDevice import com.google.android.gms.cast.CastMediaControlIntent.categoryForCast import com.google.android.gms.cast.LaunchOptions import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import java.io.IOException class CastClient(var activity: Activity, var appId: String, var receiver: Receiver) { private val TAG = javaClass.simpleName private val notification = NotificationWithControls(activity) private val api = Cast.CastApi private var apiClient: GoogleApiClient? = null private var castSessionId: String? = null private var receiverStarted = false private var reconnecting = false private val channel = CastChannel() private val mediaRouterCallback = MediaRouterCallback() private val mediaRouter = MediaRouter.getInstance(activity.applicationContext) val mediaRouteSelector = MediaRouteSelector.Builder().addControlCategory(categoryForCast(appId)).build() fun startDiscovery() { mediaRouter.addCallback(mediaRouteSelector, mediaRouterCallback, CALLBACK_FLAG_REQUEST_DISCOVERY) } fun stopDiscovery() { mediaRouter.removeCallback(mediaRouterCallback) } private inner class MediaRouterCallback : MediaRouter.Callback() { override fun onRouteSelected(router: MediaRouter, info: MediaRouter.RouteInfo) { connect(CastDevice.getFromBundle(info.extras)) } override fun onRouteUnselected(router: MediaRouter, info: MediaRouter.RouteInfo) { if (receiverStarted) stopReceiver() teardown() } } private fun connect(device: CastDevice) { try { apiClient = GoogleApiClient.Builder(activity) .addApi(Cast.API, Cast.CastOptions.Builder(device, DisconnectListener()).build()) .addConnectionCallbacks(ConnectionCallbacks()) .addOnConnectionFailedListener(ConnectionFailedListener()) .build() apiClient!!.connect() } catch (e: Exception) { Log.e(TAG, "Failed connect", e) } } internal fun teardown() { Log.d(TAG, "teardown") val client = apiClient ?: return if (receiverStarted && (client.isConnected || client.isConnecting)) { channel.unregister() client.disconnect() } apiClient = null castSessionId = null receiverStarted = false reconnecting = false notification.cancel() } private inner class ConnectionFailedListener : GoogleApiClient.OnConnectionFailedListener { override fun onConnectionFailed(result: ConnectionResult) { Log.e(TAG, "onConnectionFailed ") teardown() } } private inner class DisconnectListener : Cast.Listener() { override fun onApplicationDisconnected(errorCode: Int) { Log.d(TAG, "application has stopped") teardown() } } private inner class CastChannel : Cast.MessageReceivedCallback { val namespace = activity.getString(R.string.namespace) override fun onMessageReceived(castDevice: CastDevice, namespace: String, message: String) { Log.d(TAG, "onMessageReceived: $message") val parts = message.split("|", limit = 2) notification.notify(parts[0], mediaRouter.mediaSessionToken) (activity as MainActivity).onMessageReceived(parts) } fun register() { try { api.setMessageReceivedCallbacks(apiClient, namespace, channel) } catch (e: IOException) { Log.e(TAG, "Exception while creating channel", e) } } fun unregister() { try { api.removeMessageReceivedCallbacks(apiClient, namespace) } catch (e: IOException) { Log.e(TAG, "Exception while removing channel", e) } } } private inner class ConnectionCallbacks : GoogleApiClient.ConnectionCallbacks { override fun onConnected(hint: Bundle?) { Log.d(TAG, "onConnected") if (apiClient == null) return // We got disconnected while this runnable was pending execution. try { if (!reconnecting) launchReceiver() else { reconnecting = false if (hint != null && hint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING)) { Log.d(TAG, "App is no longer running") teardown() } else { channel.register() } } } catch (e: Exception) { Log.e(TAG, "Failed to launch application", e) } } override fun onConnectionSuspended(cause: Int) { Log.d(TAG, "onConnectionSuspended") reconnecting = true } } private fun launchReceiver() { api.launchApplication(apiClient, appId, LaunchOptions()).setResultCallback { result -> Log.d(TAG, "ApplicationConnectionResultCallback.onResult: statusCode " + result.status.statusCode) if (result.status.isSuccess) { castSessionId = result.sessionId Log.d(TAG, "application name: ${result.applicationMetadata.name}, status: ${result.applicationStatus}, sessionId: ${castSessionId}, wasLaunched: ${result.wasLaunched}") receiverStarted = true channel.register() sendCommand("url:${receiver.fullUrl}") } else { Log.e(TAG, "application could not launch") teardown() } } } private fun stopReceiver() { if (apiClient == null || castSessionId == null) return api.stopApplication(apiClient, castSessionId) } fun sendCommand(message: String) { if (apiClient != null) api.sendMessage(apiClient, channel.namespace, message) else Toast.makeText(activity, "Chromecast not connected", Toast.LENGTH_SHORT).show() } }
apache-2.0
5c63dc2422b8eb491a061d827f365e43
32.630682
176
0.697922
4.528692
false
false
false
false
kryptnostic/rhizome
src/main/kotlin/com/geekbeast/rhizome/aws/S3ListingIterator.kt
1
2284
package com.geekbeast.rhizome.aws import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.model.ListObjectsV2Request import com.amazonaws.services.s3.model.ListObjectsV2Result import java.util.concurrent.locks.ReentrantLock /** * This is the base class for s3 listing iterator. * * This class will make a call to s3 using the provided client at creation in order to initialize * the listing iterator and paging mechanism. */ abstract class S3ListingIterator<T> @JvmOverloads constructor( private val s3: AmazonS3, private val bucket: String, protected val folderPrefix: String, private val maxKeys: Int = 1000, protected val delimiter: String = "/", private val mapper: (String) -> T ) : Iterator<T> { private val lock = ReentrantLock() private var continuationToken: String? = null protected var result = getNextListing() protected var index = 0 init { continuationToken = result.nextContinuationToken } override fun next(): T { val nextElem = try { lock.lock() require(hasNext()) { "No element available." } if (index == result.commonPrefixes.size) { result = getNextListing() continuationToken = result.nextContinuationToken index = 0 } getElement(index++) } finally { lock.unlock() } return mapper(trimElement(nextElem)) } abstract fun trimElement(nextElem: String): String abstract fun getElement( index: Int ) : String abstract fun getBufferLength() : Int override fun hasNext(): Boolean { return try { lock.lock() (index < getBufferLength()) || (continuationToken != null) } finally { lock.unlock() } } private fun getNextListing(): ListObjectsV2Result { val request = ListObjectsV2Request() .withBucketName(bucket) .withPrefix(folderPrefix) .withDelimiter(delimiter) .withMaxKeys(maxKeys) if (continuationToken != null) { request.continuationToken = continuationToken } return s3.listObjectsV2(request) } }
apache-2.0
b5d3cc748dca31051b175a6d345460ea
29.878378
97
0.622154
4.719008
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/ex/CommandNode.kt
1
1121
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.ex import java.util.* class CommandNode(command: CommandHandler? = null) { var commandHandler: CommandHandler? = command private val nodes = HashMap<Char, CommandNode>() fun addChild(ch: Char, command: CommandHandler?) = CommandNode(command).also { nodes[ch] = it } fun getChild(ch: Char) = nodes[ch] }
gpl-2.0
7f67b335f534eb52b181d2dda5ca40f4
32.969697
80
0.734166
4.076364
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/widget/TachiyomiBottomNavigationView.kt
1
6146
package eu.kanade.tachiyomi.widget import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.TimeInterpolator import android.content.Context import android.os.Parcel import android.os.Parcelable import android.util.AttributeSet import android.view.ViewPropertyAnimator import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.max import androidx.customview.view.AbsSavedState import androidx.interpolator.view.animation.FastOutLinearInInterpolator import androidx.interpolator.view.animation.LinearOutSlowInInterpolator import com.google.android.material.bottomnavigation.BottomNavigationView import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.applySystemAnimatorScale import eu.kanade.tachiyomi.util.system.pxToDp class TachiyomiBottomNavigationView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.bottomNavigationStyle, defStyleRes: Int = R.style.Widget_Design_BottomNavigationView, ) : BottomNavigationView(context, attrs, defStyleAttr, defStyleRes) { private var currentAnimator: ViewPropertyAnimator? = null private var currentState = STATE_UP override fun onSaveInstanceState(): Parcelable { val superState = super.onSaveInstanceState() return SavedState(superState).also { it.currentState = currentState it.translationY = translationY } } override fun onRestoreInstanceState(state: Parcelable?) { if (state is SavedState) { super.onRestoreInstanceState(state.superState) super.setTranslationY(state.translationY) currentState = state.currentState } else { super.onRestoreInstanceState(state) } } override fun setTranslationY(translationY: Float) { // Disallow translation change when state down if (currentState == STATE_DOWN) return super.setTranslationY(translationY) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) bottomNavPadding = h.pxToDp.dp } /** * Shows this view up. */ fun slideUp() = post { currentAnimator?.cancel() clearAnimation() currentState = STATE_UP animateTranslation( 0F, SLIDE_UP_ANIMATION_DURATION, LinearOutSlowInInterpolator(), ) bottomNavPadding = height.pxToDp.dp } /** * Hides this view down. [setTranslationY] won't work until [slideUp] is called. */ fun slideDown() = post { currentAnimator?.cancel() clearAnimation() currentState = STATE_DOWN animateTranslation( height.toFloat(), SLIDE_DOWN_ANIMATION_DURATION, FastOutLinearInInterpolator(), ) bottomNavPadding = 0.dp } private fun animateTranslation(targetY: Float, duration: Long, interpolator: TimeInterpolator) { currentAnimator = animate() .translationY(targetY) .setInterpolator(interpolator) .setDuration(duration) .applySystemAnimatorScale(context) .setListener( object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { currentAnimator = null postInvalidate() } }, ) } internal class SavedState : AbsSavedState { var currentState = STATE_UP var translationY = 0F constructor(superState: Parcelable) : super(superState) constructor(source: Parcel, loader: ClassLoader?) : super(source, loader) { currentState = source.readInt() translationY = source.readFloat() } override fun writeToParcel(out: Parcel, flags: Int) { super.writeToParcel(out, flags) out.writeInt(currentState) out.writeFloat(translationY) } companion object { @JvmField val CREATOR: Parcelable.ClassLoaderCreator<SavedState> = object : Parcelable.ClassLoaderCreator<SavedState> { override fun createFromParcel(source: Parcel, loader: ClassLoader): SavedState { return SavedState(source, loader) } override fun createFromParcel(source: Parcel): SavedState { return SavedState(source, null) } override fun newArray(size: Int): Array<SavedState> { return newArray(size) } } } } companion object { private const val STATE_DOWN = 1 private const val STATE_UP = 2 private const val SLIDE_UP_ANIMATION_DURATION = 225L private const val SLIDE_DOWN_ANIMATION_DURATION = 175L private var bottomNavPadding by mutableStateOf(0.dp) /** * Merges [bottomNavPadding] to the origin's [PaddingValues] bottom side. */ @ReadOnlyComposable @Composable fun withBottomNavPadding(origin: PaddingValues = PaddingValues()): PaddingValues { val layoutDirection = LocalLayoutDirection.current return PaddingValues( start = origin.calculateStartPadding(layoutDirection), top = origin.calculateTopPadding(), end = origin.calculateEndPadding(layoutDirection), bottom = max(origin.calculateBottomPadding(), bottomNavPadding), ) } } }
apache-2.0
f90c29ae98ebb2cff4d36e5af2722c25
33.723164
121
0.658314
5.344348
false
false
false
false
Asqatasun/Asqatasun
engine/crawler/src/main/kotlin/org/asqatasun/crawler/AsqatasunWebCrawlerImpl.kt
1
4778
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2021 Asqatasun.org * * This file is part of Asqatasun. * * Asqatasun is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.crawler import edu.uci.ics.crawler4j.crawler.Page import edu.uci.ics.crawler4j.crawler.WebCrawler import edu.uci.ics.crawler4j.parser.HtmlParseData import edu.uci.ics.crawler4j.url.WebURL import org.apache.http.Header import org.springframework.web.util.UriUtils import java.net.URL import java.util.* import java.util.regex.Pattern class AsqatasunWebCrawlerImpl(private val siteUrl: URL, private val crawler: CrawlerImpl, private val maxDuration: Int, private val exclusionRegexp: String?, private val inclusionRegexp: String?): WebCrawler() { private var startedTime: Long = 0 companion object { private val BLACKLIST = Pattern.compile(".*(\\.(mp3|mp4|zip|gz|txt|css|js|xml|jpg|jpeg|png|gif|pdf))$") } override fun onStart() { startedTime = Date().time / 1000 } /** * You should implement this function to specify whether the given url * should be crawled or not (based on your crawling logic). */ override fun shouldVisit(referringPage: Page?, url: WebURL): Boolean { if (!super.shouldVisit(referringPage, url)) { return false } val href = url.url.lowercase(Locale.getDefault()) if (BLACKLIST.matcher(href).matches()) return false // Ignore the url if it has an extension that matches our defined set of image extensions. if (!exclusionRegexp.isNullOrBlank() && Pattern.compile(exclusionRegexp).matcher(href).matches()) return false if (!inclusionRegexp.isNullOrBlank() && Pattern.compile(inclusionRegexp).matcher(href).matches()) return true val currentHost = if(url.subDomain.isNotBlank()) url.subDomain+"."+url.domain else url.domain return currentHost.equals(siteUrl.host) } /** * This function is called when a page is fetched and ready to be processed * by your program. */ override fun visit(page: Page) { val docid: Int = page.webURL.docid val url: String = page.webURL.url val domain: String = page.webURL.domain val path: String = page.webURL.path val subDomain: String = page.webURL.subDomain logger.debug("Docid: {}", docid) logger.debug("Domain: '{}'", domain) logger.debug("Sub-domain: '{}'", subDomain) logger.debug("Path: '{}'", path) // @TODO Deal with status code // https://gitlab.com/asqatasun/Asqatasun/-/issues/579 if(page.contentType == null || !page.contentType.contains("text/html")){ logger.error("Page content does not match html"); return; } if (page.parseData is HtmlParseData) { val htmlParseData = page.parseData as HtmlParseData val text = htmlParseData.text val html = htmlParseData.html val links = htmlParseData.outgoingUrls logger.debug("Text length: {}", text.length) logger.debug("Html length: {}", html.length) logger.debug("Number of outgoing links: {}", links.size) } val responseHeaders: Array<Header> = page.fetchResponseHeaders logger.debug("Response headers:") for (header in responseHeaders) { logger.debug("\t{}: {}", header.name, header.value) } crawler.fireNewPage(url) if (maxDuration != 0 && maxDuration != -1) checkDurationLimit() } override fun handleUrlBeforeProcess(curURL: WebURL): WebURL { curURL.url = UriUtils.encodePath(curURL.url, "UTF-8") return curURL } private fun checkDurationLimit() { if (Date().time /1000 - startedTime >= maxDuration) { logger.info("[CRAWLER - " + getMyId() + "] Crawler time over, stop crawling...") myController.shutdown() } } }
agpl-3.0
016ab67303257dc74a967d4b8d438fad
37.845528
118
0.644412
4.183888
false
false
false
false
Unpublished/AmazeFileManager
app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/AbstractExtractorPasswordProtectedArchivesTest.kt
2
3797
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents import android.os.Environment import com.amaze.filemanager.file_operations.filesystem.compressed.ArchivePasswordCache import org.junit.Assert import org.junit.Test import java.io.File import java.io.IOException abstract class AbstractExtractorPasswordProtectedArchivesTest : AbstractExtractorTest() { /** * Test extract files without password. */ @Test(expected = IOException::class) @Throws(Exception::class) fun testExtractFilesWithoutPassword() { ArchivePasswordCache.getInstance().clear() try { doTestExtractFiles() } catch (e: IOException) { assertExceptionIsExpected(e) throw e } } /** * Test extract fils with wrong password. */ @Test(expected = IOException::class) @Throws(Exception::class) fun testExtractFilesWithWrongPassword() { ArchivePasswordCache.getInstance().clear() ArchivePasswordCache.getInstance()[archiveFile.absolutePath] = "abcdef" try { doTestExtractFiles() } catch (e: IOException) { e.printStackTrace() assertExceptionIsExpected(e) throw e } } /** * Test extract files with repeatedly wrong password. */ @Test(expected = IOException::class) @Throws(Exception::class) fun testExtractFilesWithRepeatedWrongPassword() { ArchivePasswordCache.getInstance().clear() ArchivePasswordCache.getInstance()[archiveFile.absolutePath] = "abcdef" try { doTestExtractFiles() } catch (e: IOException) { assertExceptionIsExpected(e) throw e } ArchivePasswordCache.getInstance()[archiveFile.absolutePath] = "pqrstuv" try { doTestExtractFiles() } catch (e: IOException) { assertExceptionIsExpected(e) throw e } } @Test @Throws(Exception::class) override fun testExtractFiles() { ArchivePasswordCache.getInstance()[archiveFile.absolutePath] = "123456" doTestExtractFiles() } override val archiveFile: File get() = File( Environment.getExternalStorageDirectory(), "test-archive-encrypted.$archiveType" ) protected abstract fun expectedRootExceptionClass(): Array<Class<*>> @Throws(IOException::class) protected fun assertExceptionIsExpected(e: IOException) { for (c in expectedRootExceptionClass()) { if ( if (e.cause != null) { c.isAssignableFrom(e.cause!!.javaClass) } else { c.isAssignableFrom(e.javaClass) } ) return } Assert.fail("Exception verification failed.") throw e } }
gpl-3.0
98844267ede8738d2cec9ca08fcaadba
32.307018
107
0.652094
4.806329
false
true
false
false
hurricup/intellij-community
plugins/settings-repository/src/IcsManager.kt
1
9750
/* * 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 import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.configurationStore.StreamProvider import com.intellij.ide.ApplicationLoadListener import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.runBackgroundableTask import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.ProjectLifecycleListener import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SingleAlarm import com.intellij.util.exists import com.intellij.util.move import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.GitRepositoryService import org.jetbrains.settingsRepository.git.processChildren import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths import kotlin.properties.Delegates internal const val PLUGIN_NAME = "Settings Repository" internal val LOG: Logger = Logger.getInstance(IcsManager::class.java) val icsManager by lazy(LazyThreadSafetyMode.NONE) { ApplicationLoadListener.EP_NAME.findExtension(IcsApplicationLoadListener::class.java).icsManager } class IcsManager(dir: Path) { val credentialsStore = lazy { IcsCredentialsStore() } val settingsFile: Path = dir.resolve("config.json") val settings: IcsSettings val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, dir.resolve("repository")) init { try { settings = loadSettings(settingsFile) } catch (e: Exception) { settings = IcsSettings() LOG.error(e) } } val readOnlySourcesManager = ReadOnlySourcesManager(settings, dir) val repositoryService: RepositoryService = GitRepositoryService() private val commitAlarm = SingleAlarm(Runnable { runBackgroundableTask(icsMessage("task.commit.title")) { indicator -> try { repositoryManager.commit(indicator, fixStateIfCannotCommit = false) } catch (e: Throwable) { LOG.error(e) } } }, settings.commitDelay) private @Volatile var autoCommitEnabled = true @Volatile var repositoryActive = false internal val autoSyncManager = AutoSyncManager(this) private val syncManager = SyncManager(this, autoSyncManager) private fun scheduleCommit() { if (autoCommitEnabled && !ApplicationManager.getApplication()!!.isUnitTestMode) { commitAlarm.cancelAndRequest() } } inner class ApplicationLevelProvider : IcsStreamProvider(null) { override fun delete(fileSpec: String, roamingType: RoamingType) { if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Delete is prohibited now") } if (repositoryManager.delete(toRepositoryPath(fileSpec, roamingType))) { scheduleCommit() } } } // private inner class ProjectLevelProvider(projectId: String) : IcsStreamProvider(projectId) { // override fun isAutoCommit(fileSpec: String, roamingType: RoamingType) = !isProjectOrModuleFile(fileSpec) // // override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean { // if (isProjectOrModuleFile(fileSpec)) { // // applicable only if file was committed to Settings Server explicitly // return repositoryManager.has(buildPath(fileSpec, roamingType, this.projectId)) // } // return settings.shareProjectWorkspace || fileSpec != StoragePathMacros.WORKSPACE_FILE // } // } fun sync(syncType: SyncType, project: Project? = null, localRepositoryInitializer: (() -> Unit)? = null) = syncManager.sync(syncType, project, localRepositoryInitializer) private fun cancelAndDisableAutoCommit() { if (autoCommitEnabled) { autoCommitEnabled = false commitAlarm.cancel() } } fun runInAutoCommitDisabledMode(task: ()->Unit) { cancelAndDisableAutoCommit() try { task() } finally { autoCommitEnabled = true repositoryActive = repositoryManager.isRepositoryExists() } } fun newStreamProvider() { val application = ApplicationManager.getApplication() (application.stateStore.stateStorageManager as StateStorageManagerImpl).streamProvider = ApplicationLevelProvider() } fun beforeApplicationLoaded(application: Application) { repositoryActive = repositoryManager.isRepositoryExists() val storage = application.stateStore.stateStorageManager as StateStorageManagerImpl if (storage.streamProvider == null || !storage.streamProvider!!.enabled) { storage.streamProvider = ApplicationLevelProvider() } autoSyncManager.registerListeners(application) application.messageBus.connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener { override fun beforeProjectLoaded(project: Project) { if (project.isDefault) { return } //registerProjectLevelProviders(project) autoSyncManager.registerListeners(project) } override fun afterProjectClosed(project: Project) { autoSyncManager.autoSync() } }) } open inner class IcsStreamProvider(protected val projectId: String?) : StreamProvider { override val enabled: Boolean get() = repositoryActive override fun isApplicable(fileSpec: String, roamingType: RoamingType): Boolean = enabled override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) { val fullPath = toRepositoryPath(path, roamingType, null) // first of all we must load read-only schemes - scheme could be overridden if bundled or read-only, so, such schemes must be loaded first for (repository in readOnlySourcesManager.repositories) { repository.processChildren(fullPath, filter) { name, input -> processor(name, input, true) } } repositoryManager.processChildren(fullPath, filter) { name, input -> processor(name, input, false) } } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { if (syncManager.writeAndDeleteProhibited) { throw IllegalStateException("Save is prohibited now") } if (doSave(fileSpec, content, size, roamingType) && isAutoCommit(fileSpec, roamingType)) { scheduleCommit() } } fun doSave(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) = repositoryManager.write(toRepositoryPath(fileSpec, roamingType, projectId), content, size) protected open fun isAutoCommit(fileSpec: String, roamingType: RoamingType) = true override fun read(fileSpec: String, roamingType: RoamingType) = repositoryManager.read(toRepositoryPath(fileSpec, roamingType, projectId)) override fun delete(fileSpec: String, roamingType: RoamingType) { } } } class IcsApplicationLoadListener : ApplicationLoadListener { var icsManager: IcsManager by Delegates.notNull() private set override fun beforeApplicationLoaded(application: Application, configPath: String) { val customPath = System.getProperty("ics.settingsRepository") val pluginSystemDir = if (customPath == null) Paths.get(configPath, "settingsRepository") else Paths.get(FileUtil.expandUserHome(customPath)) icsManager = IcsManager(pluginSystemDir) if (!pluginSystemDir.exists()) { try { val oldPluginDir = Paths.get(PathManager.getSystemPath(), "settingsRepository") if (oldPluginDir.exists()) { oldPluginDir.move(pluginSystemDir) } } catch (e: Throwable) { LOG.error(e) } } val repositoryManager = icsManager.repositoryManager if (repositoryManager.isRepositoryExists() && repositoryManager is GitRepositoryManager) { val migrateSchemes = repositoryManager.renameDirectory(linkedMapOf( Pair("\$ROOT_CONFIG$", null), Pair("_mac/\$ROOT_CONFIG$", "_mac"), Pair("_windows/\$ROOT_CONFIG$", "_windows"), Pair("_linux/\$ROOT_CONFIG$", "_linux"), Pair("_freebsd/\$ROOT_CONFIG$", "_freebsd"), Pair("_unix/\$ROOT_CONFIG$", "_unix"), Pair("_unknown/\$ROOT_CONFIG$", "_unknown"), Pair("\$APP_CONFIG$", null), Pair("_mac/\$APP_CONFIG$", "_mac"), Pair("_windows/\$APP_CONFIG$", "_windows"), Pair("_linux/\$APP_CONFIG$", "_linux"), Pair("_freebsd/\$APP_CONFIG$", "_freebsd"), Pair("_unix/\$APP_CONFIG$", "_unix"), Pair("_unknown/\$APP_CONFIG$", "_unknown") )) val removeOtherXml = repositoryManager.delete("other.xml") if (migrateSchemes || removeOtherXml) { // schedule push to avoid merge conflicts application.invokeLater({ icsManager.autoSyncManager.autoSync(force = true) }) } } icsManager.beforeApplicationLoaded(application) } }
apache-2.0
ffdc04f0128e9577ee15169d947ce052
36.648649
186
0.722154
4.848334
false
true
false
false
Maccimo/intellij-community
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/PluginXmlPatcher.kt
1
8594
// 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.intellij.build.impl import de.pdark.decentxml.* import io.opentelemetry.api.trace.Span import org.jetbrains.annotations.TestOnly import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.CompatibleBuildRange import java.nio.file.Files import java.time.ZonedDateTime import java.time.format.DateTimeFormatter internal val pluginDateFormat = DateTimeFormatter.ofPattern("yyyyMMdd") private val buildNumberRegex = Regex("(\\d+\\.)+\\d+") fun getCompatiblePlatformVersionRange(compatibleBuildRange: CompatibleBuildRange, buildNumber: String): Pair<String, String> { if (compatibleBuildRange == CompatibleBuildRange.EXACT || !buildNumber.matches(buildNumberRegex)) { return Pair(buildNumber, buildNumber) } val sinceBuild: String val untilBuild: String if (compatibleBuildRange == CompatibleBuildRange.ANY_WITH_SAME_BASELINE) { sinceBuild = buildNumber.substring(0, buildNumber.indexOf(".")) untilBuild = buildNumber.substring(0, buildNumber.indexOf(".")) + ".*" } else { sinceBuild = if (buildNumber.matches(Regex("\\d+\\.\\d+"))) buildNumber else buildNumber.substring(0, buildNumber.lastIndexOf(".")) val end = if ((compatibleBuildRange == CompatibleBuildRange.RESTRICTED_TO_SAME_RELEASE)) { buildNumber.lastIndexOf(".") } else { buildNumber.indexOf(".") } untilBuild = "${buildNumber.substring(0, end)}.*" } return Pair(sinceBuild, untilBuild) } fun patchPluginXml(moduleOutputPatcher: ModuleOutputPatcher, plugin: PluginLayout, releaseDate: String, releaseVersion: String, pluginsToPublish: Set<PluginLayout?>, context: BuildContext) { val moduleOutput = context.getModuleOutputDir(context.findRequiredModule(plugin.mainModule)) val pluginXmlFile = moduleOutput.resolve("META-INF/plugin.xml") if (Files.notExists(pluginXmlFile)) { context.messages.error("plugin.xml not found in ${plugin.mainModule} module: $pluginXmlFile") } val includeInBuiltinCustomRepository = context.productProperties.productLayout.prepareCustomPluginRepositoryForPublishedPlugins && context.proprietaryBuildTools.artifactsServer != null val isBundled = !pluginsToPublish.contains(plugin) val compatibleBuildRange = when { isBundled || plugin.pluginCompatibilityExactVersion || includeInBuiltinCustomRepository -> CompatibleBuildRange.EXACT context.applicationInfo.isEAP -> CompatibleBuildRange.RESTRICTED_TO_SAME_RELEASE else -> CompatibleBuildRange.NEWER_WITH_SAME_BASELINE } val defaultPluginVersion = if (context.buildNumber.endsWith(".SNAPSHOT")) { "${context.buildNumber}.${pluginDateFormat.format(ZonedDateTime.now())}" } else { context.buildNumber } val pluginVersion = plugin.versionEvaluator.evaluate(pluginXmlFile, defaultPluginVersion, context) val sinceUntil = getCompatiblePlatformVersionRange(compatibleBuildRange, context.buildNumber) @Suppress("TestOnlyProblems") val content = try { plugin.pluginXmlPatcher.apply( // using input stream allows us to support BOM doPatchPluginXml(document = Files.newInputStream(pluginXmlFile).use { XMLParser().parse(XMLIOSource(it)) }, pluginModuleName = plugin.mainModule, pluginVersion = pluginVersion, releaseDate = releaseDate, releaseVersion = releaseVersion, compatibleSinceUntil = sinceUntil, toPublish = pluginsToPublish.contains(plugin), retainProductDescriptorForBundledPlugin = plugin.retainProductDescriptorForBundledPlugin, isEap = context.applicationInfo.isEAP, productName = context.applicationInfo.productName) ) } catch (e: Throwable) { throw RuntimeException("Could not patch $pluginXmlFile", e) } moduleOutputPatcher.patchModuleOutput(plugin.mainModule, "META-INF/plugin.xml", content) } @TestOnly fun doPatchPluginXml(document: Document, pluginModuleName: String, pluginVersion: String?, releaseDate: String, releaseVersion: String, compatibleSinceUntil: Pair<String, String>, toPublish: Boolean, retainProductDescriptorForBundledPlugin: Boolean, isEap: Boolean, productName: String): String { val rootElement = document.rootElement val ideaVersionElement = getOrCreateTopElement(rootElement, "idea-version", listOf("id", "name")) ideaVersionElement.setAttribute("since-build", compatibleSinceUntil.first) ideaVersionElement.setAttribute("until-build", compatibleSinceUntil.second) val versionElement = getOrCreateTopElement(rootElement, "version", listOf("id", "name")) versionElement.text = pluginVersion val productDescriptor = rootElement.getChild("product-descriptor") if (productDescriptor != null) { if (!toPublish && !retainProductDescriptorForBundledPlugin) { Span.current().addEvent("skip $pluginModuleName <product-descriptor/>") removeTextBeforeElement(productDescriptor) productDescriptor.remove() } else { Span.current().addEvent("patch $pluginModuleName <product-descriptor/>") setProductDescriptorEapAttribute(productDescriptor, isEap) productDescriptor.setAttribute("release-date", releaseDate) productDescriptor.setAttribute("release-version", releaseVersion) } } // patch Database plugin for WebStorm, see WEB-48278 if (toPublish && productDescriptor != null && productDescriptor.getAttributeValue("code") == "PDB" && productName == "WebStorm") { Span.current().addEvent("patch $pluginModuleName for WebStorm") val pluginName = rootElement.getChild("name") check(pluginName.text == "Database Tools and SQL") { "Plugin name for \'$pluginModuleName\' should be \'Database Tools and SQL\'" } pluginName.text = "Database Tools and SQL for WebStorm" val description = rootElement.getChild("description") val replaced = replaceInElementText(description, "IntelliJ-based IDEs", "WebStorm") check(replaced) { "Could not find \'IntelliJ-based IDEs\' in plugin description of $pluginModuleName" } } return document.toXML() } private fun getOrCreateTopElement(rootElement: Element, tagName: String, anchors: List<String>): Element { rootElement.getChild(tagName)?.let { return it } val newElement = Element(tagName) val anchor = anchors.asSequence().mapNotNull { rootElement.getChild(it) }.firstOrNull() if (anchor == null) { rootElement.addNode(0, newElement) rootElement.addNode(0, Text("\n ")) } else { val anchorIndex = rootElement.nodeIndexOf(anchor) // should not happen check(anchorIndex >= 0) { "anchor < 0 when getting child index of \'${anchor.name}\' in root element of ${rootElement.toXML()}" } var indent = rootElement.getNode(anchorIndex - 1) indent = if (indent is Text) indent.copy() else Text("") rootElement.addNode(anchorIndex + 1, newElement) rootElement.addNode(anchorIndex + 1, indent) } return newElement } private fun removeTextBeforeElement(element: Element) { val parentElement = element.parentElement ?: throw IllegalStateException("Could not find parent of \'${element.toXML()}\'") val elementIndex = parentElement.nodeIndexOf(element) check(elementIndex >= 0) { "Could not find element index \'${element.toXML()}\' in parent \'${parentElement.toXML()}\'" } if (elementIndex > 0) { val text = parentElement.getNode(elementIndex - 1) if (text is Text) { parentElement.removeNode(elementIndex - 1) } } } @Suppress("SameParameterValue") private fun replaceInElementText(element: Element, oldText: String, newText: String): Boolean { var replaced = false for (node in element.nodes) { if (node is Text) { val textBefore = node.text val text = textBefore.replace(oldText, newText) if (textBefore != text) { replaced = true node.text = text } } } return replaced } private fun setProductDescriptorEapAttribute(productDescriptor: Element, isEap: Boolean) { if (isEap) { productDescriptor.setAttribute("eap", "true") } else { productDescriptor.removeAttribute("eap") } }
apache-2.0
51e56f6a9125967aab582d0c92c132d5
42.629442
135
0.70235
4.956171
false
false
false
false
dgngulcan/nytclient-android
app/src/main/java/com/nytclient/util/DateTimeUtils.kt
1
1077
package com.nytclient.util import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import javax.inject.Singleton /** * Created by Dogan Gulcan on 9/16/17. */ @Singleton class DateTimeUtils { companion object { private val nytSimpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ", Locale.US) @Volatile private var INSTANCE: DateTimeUtils? = null fun getInstance(): DateTimeUtils = INSTANCE ?: synchronized(this) { INSTANCE ?: DateTimeUtils().also { it -> INSTANCE = it } } } init { nytSimpleDateFormat.timeZone = TimeZone.getTimeZone("UTC") } fun getTimeStampFromDate(date: String, simpleDateFormat: SimpleDateFormat = nytSimpleDateFormat): Long? { var mDate: Date? = null try { mDate = simpleDateFormat.parse(date) } catch (e: ParseException) { e.printStackTrace() } finally { return mDate?.time } } }
apache-2.0
ae3fcaf8d7c282ecfc9be5c89567353b
24.069767
109
0.593315
4.744493
false
false
false
false
JetBrains/ideavim
src/test/java/org/jetbrains/plugins/ideavim/action/change/delete/JoinNotificationTest.kt
1
2883
/* * 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. */ @file:Suppress("RemoveCurlyBracesFromTemplate") package org.jetbrains.plugins.ideavim.action.change.delete import com.intellij.notification.ActionCenter import com.intellij.notification.EventLog import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.group.NotificationService import com.maddyhome.idea.vim.vimscript.services.IjVimOptionService import org.jetbrains.plugins.ideavim.OptionValueType import org.jetbrains.plugins.ideavim.VimOptionTestCase import org.jetbrains.plugins.ideavim.VimOptionTestConfiguration import org.jetbrains.plugins.ideavim.VimTestOption /** * @author Alex Plate */ class JoinNotificationTest : VimOptionTestCase(IjVimOptionService.ideajoinName) { @VimOptionTestConfiguration(VimTestOption(IjVimOptionService.ideajoinName, OptionValueType.NUMBER, "0")) fun `test notification shown for no ideajoin`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(false) typeText(injector.parser.parseKeys("J")) val notification = ActionCenter.getNotifications(myFixture.project, true).last() try { assertEquals(NotificationService.IDEAVIM_NOTIFICATION_TITLE, notification.title) assertTrue(IjVimOptionService.ideajoinName in notification.content) assertEquals(3, notification.actions.size) } finally { notification.expire() } } @VimOptionTestConfiguration(VimTestOption(IjVimOptionService.ideajoinName, OptionValueType.NUMBER, "1")) fun `test notification not shown for ideajoin`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(false) typeText(injector.parser.parseKeys("J")) val notifications = ActionCenter.getNotifications(myFixture.project, true) assertTrue(notifications.isEmpty() || notifications.last().isExpired || IjVimOptionService.ideajoinName !in notifications.last().content) } @VimOptionTestConfiguration(VimTestOption(IjVimOptionService.ideajoinName, OptionValueType.NUMBER, "0")) fun `test notification not shown if was shown already`() { val before = "I found${c} it\n in a legendary land" configureByText(before) appReadySetup(true) typeText(injector.parser.parseKeys("J")) val notifications = EventLog.getLogModel(myFixture.project).notifications assertTrue(notifications.isEmpty() || notifications.last().isExpired || IjVimOptionService.ideajoinName !in notifications.last().content) } private fun appReadySetup(notifierEnabled: Boolean) { EventLog.markAllAsRead(myFixture.project) VimPlugin.getVimState().isIdeaJoinNotified = notifierEnabled } }
mit
e28d6dea7dd46b6f0a2179a94d090d51
39.605634
141
0.778009
4.302985
false
true
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/common/TextRange.kt
1
2408
/* * 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.common import org.jetbrains.annotations.Contract import org.jetbrains.annotations.NonNls import kotlin.math.max import kotlin.math.min /** * Please prefer [com.maddyhome.idea.vim.group.visual.VimSelection] for visual selection */ class TextRange(val startOffsets: IntArray, val endOffsets: IntArray) { constructor(start: Int, end: Int) : this(intArrayOf(start), intArrayOf(end)) val isMultiple get() = startOffsets.size > 1 val maxLength: Int get() { var max = 0 for (i in 0 until size()) { max = max(max, endOffsets[i] - startOffsets[i]) } return max } val selectionCount: Int get() { var res = 0 for (i in 0 until size()) { res += endOffsets[i] - startOffsets[i] } return res } fun size(): Int = startOffsets.size val startOffset: Int get() = startOffsets.first() val endOffset: Int get() = endOffsets.last() fun normalize(): TextRange { normalizeIndex(0) return this } private fun normalizeIndex(index: Int) { if (index < size() && endOffsets[index] < startOffsets[index]) { val t = startOffsets[index] startOffsets[index] = endOffsets[index] endOffsets[index] = t } } @Contract(mutates = "this") fun normalize(fileSize: Int): Boolean { for (i in 0 until size()) { normalizeIndex(i) startOffsets[i] = max(0, min(startOffsets[i], fileSize)) if (startOffsets[i] == fileSize && fileSize != 0) { return false } endOffsets[i] = max(0, min(endOffsets[i], fileSize)) } return true } operator fun contains(offset: Int): Boolean = if (isMultiple) false else offset in startOffset until endOffset override fun toString(): String { @NonNls val sb = StringBuilder() sb.append("TextRange") sb.append("{starts=") var i = 0 while (i < startOffsets.size) { sb.append(if (i == 0) "" else ", ").append(startOffsets[i]) ++i } sb.append(", ends=") i = 0 while (i < endOffsets.size) { sb.append(if (i == 0) "" else ", ").append(endOffsets[i]) ++i } sb.append('}') return sb.toString() } }
mit
49e6d5b8e3890b8a49f77aa66069b301
23.571429
112
0.620847
3.768388
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/embeddings/lmdb/EmbeddingsMap.kt
1
1254
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.embeddings.lmdb import com.kotlinnlp.simplednn.core.embeddings.EmbeddingsMap import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer /** * @param storage the embeddings storage * @param initializer the initializer of the values of the embeddings (zeros if null, default: Glorot) * @param pseudoRandomDropout a Boolean indicating if embeddings must be dropped out with pseudo random probability * (default = true) */ class EmbeddingsMap( storage: EmbeddingsStorage, initializer: Initializer? = GlorotInitializer(), pseudoRandomDropout: Boolean = true ) : EmbeddingsMap<String>( size = storage.embeddingsSize, initializer = initializer, pseudoRandomDropout = pseudoRandomDropout ) { override val embeddings = storage }
mpl-2.0
68baa91c591d930102bdc8146829fe2c
40.8
115
0.724083
4.462633
false
false
false
false
akakim/akakim.github.io
Android/KotlinRepository/QSalesPrototypeKotilnVersion/main/java/tripath/com/samplekapp/widget/DialogDone.kt
1
1859
package tripath.com.samplekapp.widget import android.app.Dialog import android.content.Context import android.content.DialogInterface import android.widget.Button import android.widget.TextView import tripath.com.samplekapp.R /** * Created by SSLAB on 2017-08-01. */ class DialogDone : Dialog { private lateinit var titleView : TextView private lateinit var contentView : TextView private lateinit var confirmBtn : Button constructor(context: Context?) : this(context,-1) constructor(context: Context?, themeResId: Int) : super(context, themeResId) { setContentView( R.layout.dialog_done ) setCancelable(false) titleView = findViewById<TextView>(R.id.textTitle) contentView = findViewById<TextView>(R.id.textContent) confirmBtn = findViewById<Button>(R.id.btnDone) } constructor(context: Context?, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener){ setContentView( R.layout.dialog_done ) titleView = findViewById<TextView>(R.id.textTitle) contentView = findViewById<TextView>(R.id.textContent) confirmBtn = findViewById<Button>(R.id.btnDone) } constructor(context: Context?, cancelable: Boolean, cancelListener: ((DialogInterface) -> Unit)?) : super(context, cancelable, cancelListener){ setContentView( R.layout.dialog_done ) titleView = findViewById<TextView>(R.id.textTitle) contentView = findViewById<TextView>(R.id.textContent) confirmBtn = findViewById<Button>(R.id.btnDone) } fun setDialogTitle(title: CharSequence?) : DialogDone { titleView?.setText( title ) return this } fun setContent(contents : CharSequence?) : DialogDone{ contentView?.setText(contents) return this } }
gpl-3.0
26782211b5c19c73fb7cfc28dbce7a5d
32.214286
152
0.70737
4.501211
false
false
false
false
benjamin-bader/thrifty
thrifty-runtime/src/commonMain/kotlin/com/microsoft/thrifty/service/MethodCall.kt
1
1653
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.service import com.microsoft.thrifty.protocol.MessageMetadata import com.microsoft.thrifty.protocol.Protocol import okio.IOException import kotlin.jvm.JvmField /** * A closure capturing all data necessary to send and receive an asynchronous * service method call. */ abstract class MethodCall<T>( @JvmField val name: String, @JvmField val callTypeId: Byte, @JvmField val callback: ServiceMethodCallback<T>?, ) { @Throws(IOException::class) abstract fun send(protocol: Protocol) @Throws(Exception::class) abstract fun receive(protocol: Protocol, metadata: MessageMetadata): T init { require(callTypeId == TMessageType.CALL || callTypeId == TMessageType.ONEWAY) { "Unexpected call type: $callTypeId" } require(callback != null || callTypeId == TMessageType.ONEWAY) { "callback is required" } } }
apache-2.0
39eb5ac20f7b8fa82458265b589da365
30.788462
116
0.710829
4.315927
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/card/iso7816/ISO7816Application.kt
1
7837
/* * ISO7816Application.kt * * Copyright 2018 Michael Farrell <[email protected]> * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.card.iso7816 import au.id.micolous.metrodroid.card.TagReaderFeedbackInterface import au.id.micolous.metrodroid.card.iso7816.ISO7816Data.TAG_PROPRIETARY_BER_TLV import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.VisibleForTesting import au.id.micolous.metrodroid.transit.TransitData import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.ImmutableByteArray import kotlinx.serialization.Serializable import kotlinx.serialization.Transient @Serializable data class ISO7816ApplicationCapsule( val files: Map<ISO7816Selector, ISO7816File> = emptyMap(), val sfiFiles: Map<Int, ISO7816File> = emptyMap(), val appFci: ImmutableByteArray? = null, val appName: ImmutableByteArray? = null) { constructor(mc: ISO7816ApplicationMutableCapsule) : this( files = mc.files, sfiFiles = mc.sfiFiles, appFci = mc.appFci, appName = mc.appName ) } class ISO7816ApplicationMutableCapsule(val appFci: ImmutableByteArray?, val appName: ImmutableByteArray?, val files: MutableMap<ISO7816Selector, ISO7816File> = mutableMapOf(), val sfiFiles: MutableMap<Int, ISO7816File> = mutableMapOf()) { suspend fun dumpFileSFI(protocol: ISO7816Protocol, sfi: Int, recordLen: Int): ISO7816File? { val data = try { protocol.readBinary(sfi) } catch (e: Exception) { null } val records : MutableMap<Int, ImmutableByteArray> = mutableMapOf() var recordEOF = false try { for (r in 1..255) { try { val record = protocol.readRecord(sfi, r.toByte(), recordLen.toByte()) ?: break records[r] = record } catch (e: ISOEOFException) { recordEOF = true // End of file, stop here. break } } } catch (e: Exception) { } if (data == null && records.isEmpty() && !recordEOF) return null val f = ISO7816File(records = records, binaryData = data) sfiFiles[sfi] = f return f } suspend fun dumpAllSfis(protocol: ISO7816Protocol, feedbackInterface: TagReaderFeedbackInterface, start: Int, total: Int) { var counter = start for (sfi in 1..31) { feedbackInterface.updateProgressBar(counter++, total) dumpFileSFI(protocol, sfi, 0) } } suspend fun dumpFile(protocol: ISO7816Protocol, sel: ISO7816Selector, recordLen: Int): ISO7816File? { // Start dumping... val fci: ImmutableByteArray? try { protocol.unselectFile() } catch (e: ISO7816Exception) { Log.d(TAG, "Unselect failed, trying select nevertheless") } try { fci = sel.select(protocol) } catch (e: ISO7816Exception) { Log.d(TAG, "Select failed, aborting") return null } val data = protocol.readBinary() val records = mutableMapOf<Int, ImmutableByteArray>() for (r in 1..255) { try { records[r] = protocol.readRecord(r.toByte(), recordLen.toByte()) ?: break } catch (e: ISOEOFException) { // End of file, stop here. break } } val file = ISO7816File(records = records, binaryData = data, fci = fci) files[sel] = file return file } fun getFile(sel: ISO7816Selector): ISO7816File? = files[sel] fun freeze() = ISO7816ApplicationCapsule(this) @Transient val appProprietaryBerTlv : ImmutableByteArray? get() = getProprietaryBerTlv(this.appFci) companion object { private const val TAG = "ISO7816ApplicationMutableCapsule" } } fun getProprietaryBerTlv(fci: ImmutableByteArray?): ImmutableByteArray? { return fci?.let { ISO7816TLV.findBERTLV(it, TAG_PROPRIETARY_BER_TLV, true) } } /** * Returns `true` if the [List] of [ISO7816Application] contains the given [appName]. */ fun List<ISO7816Application>.any(appName: ImmutableByteArray) = this.any { it.appName == appName } /** * Returns true if the [List] of [ISO7816Application] contains any of the given [appNames]. */ fun List<ISO7816Application>.any(appNames: List<ImmutableByteArray>) = this.any { appNames.contains(it.appName) } /** * Generic card implementation for ISO7816. This doesn't have many smarts, but dispatches to other * readers. */ @Serializable(with = ISO7816AppSerializer::class) abstract class ISO7816Application { abstract val generic: ISO7816ApplicationCapsule abstract val type: String @Transient @VisibleForTesting val files get() = generic.files @Transient @VisibleForTesting val sfiFiles get() = generic.sfiFiles @Transient val appName get() = generic.appName @Transient val appFci get() = generic.appFci @Transient val appProprietaryBerTlv : ImmutableByteArray? get() = getProprietaryBerTlv(this.appFci) @Transient open val rawData: List<ListItem>? get() = null @Transient val rawFiles: List<ListItem> get() = files.map {(selector, file) -> var selectorStr = selector.formatString() val fileDesc = nameFile(selector) if (fileDesc != null) selectorStr = "$selectorStr ($fileDesc)" file.showRawData(selectorStr) } + sfiFiles.map { (sfi, value) -> var selectorStr = Localizer.localizeString(R.string.iso7816_sfi, sfi.toString(16)) val fileDesc = nameSfiFile(sfi) if (fileDesc != null) selectorStr = "$selectorStr ($fileDesc)" value.showRawData(selectorStr) } @Transient open val manufacturingInfo: List<ListItem>? get() = null protected open fun nameFile(selector: ISO7816Selector): String? = null protected open fun nameSfiFile(sfi: Int): String? = null fun getFile(sel: ISO7816Selector): ISO7816File? = files[sel] /** * If the selector given is a parent of one or more [ISO7816File]s in this application, * return true. * * @param sel The selector to look up. */ fun pathExists(sel: ISO7816Selector): Boolean = files.keys.find { it.startsWith(sel) } != null fun getSfiFile(sfi: Int): ISO7816File? = sfiFiles[sfi] open fun parseTransitIdentity(card: ISO7816Card): TransitIdentity? = null open fun parseTransitData(card: ISO7816Card): TransitData? = null companion object { private const val TAG = "ISO7816Application" } }
gpl-3.0
e1e442074f183b1d80bfc1a27ddc49ad
33.222707
127
0.633661
4.243097
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/membership/job/CheckMembershipStatusScheduler.kt
1
4135
package io.ipoli.android.store.membership.job import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingClientStateListener import com.crashlytics.android.Crashlytics import com.evernote.android.job.DailyJob import com.evernote.android.job.JobRequest import io.ipoli.android.BuildConfig import io.ipoli.android.MyPoliApp import io.ipoli.android.common.billing.BillingError import io.ipoli.android.common.di.BackgroundModule import io.ipoli.android.store.membership.error.SubscriptionError import io.ipoli.android.store.membership.usecase.RemoveMembershipUseCase import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.runBlocking import kotlinx.coroutines.experimental.withContext import space.traversal.kapsule.Injects import space.traversal.kapsule.Kapsule import java.util.concurrent.TimeUnit import kotlin.coroutines.experimental.suspendCoroutine /** * Created by Venelin Valkov <[email protected]> * on 03/23/2018. */ class CheckMembershipStatusJob : DailyJob(), Injects<BackgroundModule> { override fun onRunDailyJob(params: Params): DailyJobResult { val kap = Kapsule<BackgroundModule>() val playerRepository by kap.required { playerRepository } val removeMembershipUseCase by kap.required { removeMembershipUseCase } kap.inject(MyPoliApp.backgroundModule(context)) val p = playerRepository.find() requireNotNull(p) runBlocking { val billingClient = withContext(Dispatchers.Main) { try { val c = BillingClient.newBuilder(context).setListener { _, _ -> }.build() c.connect() c } catch (e: BillingError) { logError(e) null } } ?: return@runBlocking checkMembershipStatus(billingClient, removeMembershipUseCase) withContext(Dispatchers.Main) { billingClient.endConnection() } } return DailyJobResult.SUCCESS } private suspend fun BillingClient.connect() { suspendCoroutine<Unit> { startConnection(object : BillingClientStateListener { override fun onBillingServiceDisconnected() { it.resumeWithException(BillingError("Unable to connect")) } override fun onBillingSetupFinished(responseCode: Int) { if (responseCode == BillingClient.BillingResponse.OK) { it.resume(Unit) } else { it.resumeWithException(BillingError("Unable to establish connection $responseCode")) } } }) } } private suspend fun checkMembershipStatus( billingClient: BillingClient, removeMembershipUseCase: RemoveMembershipUseCase ) { val purchasesResult = withContext(Dispatchers.Main) { billingClient.queryPurchases(BillingClient.SkuType.SUBS) } if (purchasesResult.responseCode != BillingClient.BillingResponse.OK) { return } if (purchasesResult.purchasesList.isEmpty()) { removeMembershipUseCase.execute(Unit) } } private fun logError(e: Exception) { if (!BuildConfig.DEBUG) { Crashlytics.logException( SubscriptionError( "Check membership status job failed", e ) ) } } companion object { const val TAG = "check_membership_status_tag" } } class AndroidCheckMembershipStatusScheduler : CheckMembershipStatusScheduler { override fun schedule() { DailyJob.schedule( JobRequest.Builder(CheckMembershipStatusJob.TAG) .setUpdateCurrent(true) .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED) .setRequirementsEnforced(true), 0, TimeUnit.HOURS.toMillis(8) ) } } interface CheckMembershipStatusScheduler { fun schedule() }
gpl-3.0
2e495405c93f6e8779317eb4768cb63a
33.181818
108
0.650302
5.260814
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildFirstEntityImpl.kt
2
10628
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildFirstEntityImpl(val dataSource: ChildFirstEntityData) : ChildFirstEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentAbEntity::class.java, ChildAbstractBaseEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, false) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val commonData: String get() = dataSource.commonData override val parentEntity: ParentAbEntity get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)!! override val firstData: String get() = dataSource.firstData override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: ChildFirstEntityData?) : ModifiableWorkspaceEntityBase<ChildFirstEntity, ChildFirstEntityData>( result), ChildFirstEntity.Builder { constructor() : this(ChildFirstEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildFirstEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isCommonDataInitialized()) { error("Field ChildAbstractBaseEntity#commonData should be initialized") } if (_diff != null) { if (_diff.extractOneToAbstractManyParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } else { if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) { error("Field ChildAbstractBaseEntity#parentEntity should be initialized") } } if (!getEntityData().isFirstDataInitialized()) { error("Field ChildFirstEntity#firstData should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ChildFirstEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.commonData != dataSource.commonData) this.commonData = dataSource.commonData if (this.firstData != dataSource.firstData) this.firstData = dataSource.firstData if (parents != null) { val parentEntityNew = parents.filterIsInstance<ParentAbEntity>().single() if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) { this.parentEntity = parentEntityNew } } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var commonData: String get() = getEntityData().commonData set(value) { checkModificationAllowed() getEntityData(true).commonData = value changedProperty.add("commonData") } override var parentEntity: ParentAbEntity get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentAbEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*, *>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var firstData: String get() = getEntityData().firstData set(value) { checkModificationAllowed() getEntityData(true).firstData = value changedProperty.add("firstData") } override fun getEntityClass(): Class<ChildFirstEntity> = ChildFirstEntity::class.java } } class ChildFirstEntityData : WorkspaceEntityData<ChildFirstEntity>() { lateinit var commonData: String lateinit var firstData: String fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized fun isFirstDataInitialized(): Boolean = ::firstData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildFirstEntity> { val modifiable = ChildFirstEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildFirstEntity { return getCached(snapshot) { val entity = ChildFirstEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildFirstEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ChildFirstEntity(commonData, firstData, entitySource) { this.parentEntity = parents.filterIsInstance<ParentAbEntity>().single() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() res.add(ParentAbEntity::class.java) return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ChildFirstEntityData if (this.entitySource != other.entitySource) return false if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as ChildFirstEntityData if (this.commonData != other.commonData) return false if (this.firstData != other.firstData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + commonData.hashCode() result = 31 * result + firstData.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
5098431e64fab44387b8a55c2eb17267
37.230216
160
0.695145
5.486835
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/PlatformModuleInfo.kt
6
6849
// 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.base.projectStructure.moduleInfo import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.analyzer.* import org.jetbrains.kotlin.descriptors.ModuleCapability import org.jetbrains.kotlin.idea.base.platforms.isSharedNative import org.jetbrains.kotlin.idea.base.projectStructure.KotlinBaseProjectStructureBundle import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices import org.jetbrains.kotlin.konan.library.KONAN_STDLIB_NAME import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.platform.js.isJs import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.platform.konan.NativePlatform import org.jetbrains.kotlin.platform.konan.NativePlatforms import org.jetbrains.kotlin.platform.konan.isNative import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices data class PlatformModuleInfo( override val platformModule: ModuleSourceInfo, private val commonModules: List<ModuleSourceInfo> // NOTE: usually contains a single element for current implementation ) : IdeaModuleInfo, CombinedModuleInfo, TrackableModuleInfo { override val capabilities: Map<ModuleCapability<*>, Any?> get() = platformModule.capabilities override val contentScope get() = GlobalSearchScope.union(containedModules.map { it.contentScope }.toTypedArray()) override val containedModules: List<ModuleSourceInfo> = listOf(platformModule) + commonModules override val project: Project get() = platformModule.module.project override val platform: TargetPlatform get() = platformModule.platform override val moduleOrigin: ModuleOrigin get() = platformModule.moduleOrigin override val analyzerServices: PlatformDependentAnalyzerServices get() = platform.findAnalyzerServices(platformModule.module.project) override fun dependencies() = platformModule.dependencies() // This is needed for cases when we create PlatformModuleInfo in Kotlin Multiplatform Analysis Mode is set to COMPOSITE, see // KotlinCacheService.getResolutionFacadeWithForcedPlatform. // For SEPARATE-mode, this filter will be executed in getSourceModuleDependencies.kt anyway, so it's essentially a no-op .filter { NonHmppSourceModuleDependenciesFilter(platformModule.platform).isSupportedDependency(it) } override val expectedBy: List<ModuleInfo> get() = platformModule.expectedBy override fun modulesWhoseInternalsAreVisible() = containedModules.flatMap { it.modulesWhoseInternalsAreVisible() } override val name: Name = Name.special("<Platform module ${platformModule.name} including ${commonModules.map { it.name }}>") override val displayedName: String get() = KotlinBaseProjectStructureBundle.message( "platform.module.0.including.1", platformModule.displayedName, commonModules.map { it.displayedName } ) override fun createModificationTracker() = platformModule.createModificationTracker() } /** * Filter for dependencies on source modules. * This shall act as last line of defense for catastrophic misconfiguration of order entries. * Generally, we do trust Gradle/Import/Users to select only 'reasonable' dependencies for source modules. * However: Passing dependencies produced by one Kotlin backend into analysis of another platform might have unpredictable/unwanted * consequences and is forbidden under the implementations rules (even if users added those order entries themselves explicitly) */ internal interface SourceModuleDependenciesFilter { fun isSupportedDependency(dependency: IdeaModuleInfo): Boolean } @ApiStatus.Internal class HmppSourceModuleDependencyFilter(private val dependeePlatform: TargetPlatform) : SourceModuleDependenciesFilter { data class KlibLibraryGist(val isStdlib: Boolean) private fun klibLibraryGistOrNull(info: IdeaModuleInfo): KlibLibraryGist? { return if (info is AbstractKlibLibraryInfo) KlibLibraryGist(isStdlib = info.libraryRoot.endsWith(KONAN_STDLIB_NAME)) else null } override fun isSupportedDependency(dependency: IdeaModuleInfo): Boolean { /* Filter only acts on LibraryInfo */ return if (dependency is LibraryInfo) { isSupportedDependency(dependency.platform, klibLibraryGistOrNull(dependency)) } else true } fun isSupportedDependency( dependencyPlatform: TargetPlatform, klibLibraryGist: KlibLibraryGist? = null, ): Boolean { // HACK: allow depending on stdlib even if platforms do not match if (dependeePlatform.isNative() && klibLibraryGist != null && klibLibraryGist.isStdlib) return true val platformsWhichAreNotContainedInOther = dependeePlatform.componentPlatforms - dependencyPlatform.componentPlatforms if (platformsWhichAreNotContainedInOther.isEmpty()) return true // unspecifiedNativePlatform is effectively a wildcard for NativePlatform if (platformsWhichAreNotContainedInOther.all { it is NativePlatform } && NativePlatforms.unspecifiedNativePlatform.componentPlatforms.single() in dependencyPlatform.componentPlatforms ) return true // Allow dependencies from any shared native to any other shared native platform. // This will also include dependencies built by the commonizer with one or more missing targets // The Kotlin Gradle Plugin will decide if the dependency is still used in that case. // Since compiling metadata will be possible with this KLIB, the IDE also analyzes the code with it. if (dependeePlatform.isSharedNative() && klibLibraryGist != null && dependencyPlatform.isSharedNative()) return true return false } } @ApiStatus.Internal class NonHmppSourceModuleDependenciesFilter(private val dependeePlatform: TargetPlatform) : SourceModuleDependenciesFilter { override fun isSupportedDependency(dependency: IdeaModuleInfo): Boolean { /* Filter only acts on LibraryInfo */ return if (dependency is LibraryInfo) { isSupportedDependency(dependency.platform) } else true } private fun isSupportedDependency(dependencyPlatform: TargetPlatform): Boolean { return dependeePlatform.isJvm() && dependencyPlatform.isJvm() || dependeePlatform.isJs() && dependencyPlatform.isJs() || dependeePlatform.isNative() && dependencyPlatform.isNative() || dependeePlatform.isCommon() && dependencyPlatform.isCommon() } }
apache-2.0
87bdb299ad1f75c8451fb64e3cb5fc4a
49.740741
132
0.765659
5.138035
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/search/usagesSearch/operators/IndexingOperatorReferenceSearcher.kt
4
2346
// 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.search.usagesSearch.operators import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchRequestCollector import com.intellij.psi.search.SearchScope import com.intellij.util.Processor import org.jetbrains.kotlin.idea.references.KtArrayAccessReference import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.psi.KtArrayAccessExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance class IndexingOperatorReferenceSearcher( targetFunction: PsiElement, searchScope: SearchScope, consumer: Processor<in PsiReference>, optimizer: SearchRequestCollector, options: KotlinReferencesSearchOptions, private val isSet: Boolean ) : OperatorReferenceSearcher<KtArrayAccessExpression>( targetFunction, searchScope, consumer, optimizer, options, wordsToSearch = listOf("[") ) { override fun processPossibleReceiverExpression(expression: KtExpression) { val accessExpression = expression.parent as? KtArrayAccessExpression ?: return if (expression != accessExpression.arrayExpression) return if (!checkAccessExpression(accessExpression)) return processReferenceElement(accessExpression) } override fun isReferenceToCheck(ref: PsiReference) = ref is KtArrayAccessReference && checkAccessExpression(ref.element) override fun extractReference(element: KtElement): PsiReference? { val accessExpression = element as? KtArrayAccessExpression ?: return null if (!checkAccessExpression(accessExpression)) return null return accessExpression.references.firstIsInstance<KtArrayAccessReference>() } private fun checkAccessExpression(accessExpression: KtArrayAccessExpression): Boolean { val readWriteAccess = accessExpression.readWriteAccess(useResolveForReadWrite = false) return if (isSet) readWriteAccess.isWrite else readWriteAccess.isRead } }
apache-2.0
8a5b3ee5f182486f5dc3b2a76a28a426
42.462963
158
0.792839
5.368421
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/preferences/ButtonStripPreference.kt
2
4521
package org.thoughtcrime.securesms.components.settings.conversation.preferences import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.appcompat.content.res.AppCompatResources import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon import org.thoughtcrime.securesms.components.settings.PreferenceModel import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder import org.thoughtcrime.securesms.util.visible /** * Renders a configurable strip of buttons */ object ButtonStripPreference { fun register(adapter: MappingAdapter) { adapter.registerFactory(Model::class.java, LayoutFactory(::ViewHolder, R.layout.conversation_settings_button_strip)) } class Model( val state: State, val background: DSLSettingsIcon? = null, val onMessageClick: () -> Unit = {}, val onVideoClick: () -> Unit = {}, val onAudioClick: () -> Unit = {}, val onMuteClick: () -> Unit = {}, val onSearchClick: () -> Unit = {} ) : PreferenceModel<Model>() { override fun areContentsTheSame(newItem: Model): Boolean { return super.areContentsTheSame(newItem) && state == newItem.state } override fun areItemsTheSame(newItem: Model): Boolean { return true } } class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) { private val message: View = itemView.findViewById(R.id.message) private val messageContainer: View = itemView.findViewById(R.id.button_strip_message_container) private val videoCall: View = itemView.findViewById(R.id.start_video) private val videoContainer: View = itemView.findViewById(R.id.button_strip_video_container) private val audioCall: ImageView = itemView.findViewById(R.id.start_audio) private val audioLabel: TextView = itemView.findViewById(R.id.start_audio_label) private val audioContainer: View = itemView.findViewById(R.id.button_strip_audio_container) private val mute: ImageView = itemView.findViewById(R.id.mute) private val muteLabel: TextView = itemView.findViewById(R.id.mute_label) private val muteContainer: View = itemView.findViewById(R.id.button_strip_mute_container) private val search: View = itemView.findViewById(R.id.search) private val searchContainer: View = itemView.findViewById(R.id.button_strip_search_container) override fun bind(model: Model) { messageContainer.visible = model.state.isMessageAvailable videoContainer.visible = model.state.isVideoAvailable audioContainer.visible = model.state.isAudioAvailable muteContainer.visible = model.state.isMuteAvailable searchContainer.visible = model.state.isSearchAvailable if (model.state.isAudioSecure) { audioLabel.setText(R.string.ConversationSettingsFragment__audio) audioCall.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_phone_right_24)) } else { audioLabel.setText(R.string.ConversationSettingsFragment__call) audioCall.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_phone_right_unlock_primary_accent_24)) } if (model.state.isMuted) { mute.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_bell_disabled_24)) muteLabel.setText(R.string.ConversationSettingsFragment__muted) } else { mute.setImageDrawable(AppCompatResources.getDrawable(context, R.drawable.ic_bell_24)) muteLabel.setText(R.string.ConversationSettingsFragment__mute) } if (model.background != null) { listOf(message, videoCall, audioCall, mute, search).forEach { it.background = model.background.resolve(context) } } message.setOnClickListener { model.onMessageClick() } videoCall.setOnClickListener { model.onVideoClick() } audioCall.setOnClickListener { model.onAudioClick() } mute.setOnClickListener { model.onMuteClick() } search.setOnClickListener { model.onSearchClick() } } } data class State( val isMessageAvailable: Boolean = false, val isVideoAvailable: Boolean = false, val isAudioAvailable: Boolean = false, val isMuteAvailable: Boolean = false, val isSearchAvailable: Boolean = false, val isAudioSecure: Boolean = false, val isMuted: Boolean = false, ) }
gpl-3.0
caa48801c514e0e505bbedf0bc329c4f
42.893204
127
0.743198
4.402142
false
false
false
false
roylanceMichael/yaclib
core/src/main/java/org/roylance/yaclib/core/services/typescript/TypeScriptServiceImplementationJsonBuilder.kt
1
2731
package org.roylance.yaclib.core.services.typescript import org.roylance.common.service.IBuilder import org.roylance.yaclib.YaclibModel import org.roylance.yaclib.core.enums.CommonTokens import org.roylance.yaclib.core.utilities.StringUtilities import org.roylance.yaclib.core.utilities.TypeScriptUtilities class TypeScriptServiceImplementationJsonBuilder(private val controller: YaclibModel.Controller, private val mainDependency: YaclibModel.Dependency) : IBuilder<YaclibModel.File> { override fun build(): YaclibModel.File { val workspace = StringBuilder() val interfaceName = StringUtilities.convertServiceNameToInterfaceName(controller) val initialTemplate = """${CommonTokens.DoNotAlterMessage} import {$interfaceName} from "./$interfaceName"; import {${HttpExecuteServiceBuilder.FileName}} from "./${HttpExecuteServiceBuilder.FileName}"; import {${TypeScriptUtilities.getFirstGroup( mainDependency.group)}} from "./${mainDependency.typescriptModelFile}"; export class ${controller.name}${CommonTokens.ServiceName} implements $interfaceName { ${HttpExecuteServiceBuilder.VariableName}:${HttpExecuteServiceBuilder.FileName}; constructor(${HttpExecuteServiceBuilder.VariableName}:${HttpExecuteServiceBuilder.FileName}) { this.${HttpExecuteServiceBuilder.VariableName} = ${HttpExecuteServiceBuilder.VariableName}; } """ workspace.append(initialTemplate) controller.actionsList.forEach { action -> // for now, only processing one input and one output if (action.inputsCount == 1) { val colonSeparatedInputs = action.inputsList.map { input -> "${input.argumentName}: ${input.filePackage}.${input.messageClass}" }.joinToString() val actionTemplate = "\t${action.name}($colonSeparatedInputs, onSuccess:(response: ${action.output.filePackage}.${action.output.messageClass})=>void, onError:(response:any)=>void) {" val fullUrl = StringUtilities.buildUrl("/rest/${controller.name}/${action.name}") val functionTemplate = """ const self = this; this.${HttpExecuteServiceBuilder.VariableName}.performPost("$fullUrl", ${action.inputsList.first().argumentName}, onSuccess, onError); } """ workspace.append(actionTemplate) workspace.append(functionTemplate) } } workspace.append("}") val returnFile = YaclibModel.File.newBuilder() .setFileToWrite(workspace.toString()) .setFileExtension(YaclibModel.FileExtension.TS_EXT) .setFileName("${controller.name}${CommonTokens.ServiceName}") .setFullDirectoryLocation("") .build() return returnFile } }
mit
03e54e8ed30997eeb8bc89e2613b0ffd
43.064516
190
0.718052
4.947464
false
false
false
false
AshishKayastha/Movie-Guide
app/src/main/kotlin/com/ashish/movieguide/ui/people/list/PersonDelegateAdapter.kt
1
1554
package com.ashish.movieguide.ui.people.list import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.ashish.movieguide.data.models.Person import com.ashish.movieguide.ui.base.recyclerview.BaseContentHolder import com.ashish.movieguide.ui.common.adapter.OnItemClickListener import com.ashish.movieguide.ui.common.adapter.RemoveListener import com.ashish.movieguide.ui.common.adapter.ViewType import com.ashish.movieguide.ui.common.adapter.ViewTypeDelegateAdapter import com.ashish.movieguide.utils.extensions.getProfileUrl import com.ashish.movieguide.utils.extensions.hide /** * Created by Ashish on Dec 31. */ class PersonDelegateAdapter( private val layoutId: Int, private var onItemClickListener: OnItemClickListener? ) : ViewTypeDelegateAdapter, RemoveListener { override fun onCreateViewHolder(parent: ViewGroup) = PersonHolder(parent) override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType) { (holder as PersonHolder).bindData(item as Person) } override fun removeListener() { onItemClickListener = null } inner class PersonHolder(parent: ViewGroup) : BaseContentHolder<Person>(parent, layoutId) { override fun bindData(item: Person) = with(item) { contentTitle.text = name contentSubtitle.hide() super.bindData(item) } override fun getItemClickListener() = onItemClickListener override fun getImageUrl(item: Person) = item.profilePath.getProfileUrl() } }
apache-2.0
b978d12fa4ddd878f9daf62d508297f2
34.340909
95
0.75547
4.611276
false
false
false
false
dhis2/dhis2-android-sdk
core/src/androidTest/java/org/hisp/dhis/android/core/EventWithLimitCallMockIntegrationShould.kt
1
3406
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core import com.google.common.truth.Truth import org.hisp.dhis.android.core.event.internal.EventStoreImpl import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestMetadataEnqueable import org.hisp.dhis.android.core.utils.runner.D2JunitRunner import org.junit.After import org.junit.Test import org.junit.runner.RunWith @RunWith(D2JunitRunner::class) class EventWithLimitCallMockIntegrationShould : BaseMockIntegrationTestMetadataEnqueable() { @After @Throws(D2Error::class) fun tearDown() { d2.wipeModule().wipeData() } @Test fun download_events() { val eventLimitByOrgUnit = 1 dhis2MockServer.enqueueSystemInfoResponse() dhis2MockServer.enqueueMockResponse("event/events_1.json") d2.eventModule().eventDownloader().limit(eventLimitByOrgUnit).blockingDownload() val eventStore = EventStoreImpl.create(databaseAdapter) val downloadedEvents = eventStore.querySingleEvents() Truth.assertThat(downloadedEvents.size).isEqualTo(eventLimitByOrgUnit) } // @Test TODO https://jira.dhis2.org/browse/ANDROSDK-1328 fun download_events_by_uid_limited_by_one() { val eventLimitByOrgUnit = 1 dhis2MockServer.enqueueSystemInfoResponse() dhis2MockServer.enqueueMockResponse("event/events_with_uids.json") d2.eventModule().eventDownloader() .byUid() .`in`("wAiGPfJGMxt", "PpNGhvEYnXe") .limit(eventLimitByOrgUnit) .blockingDownload() val eventStore = EventStoreImpl.create(databaseAdapter) val downloadedEvents = eventStore.querySingleEvents() Truth.assertThat(downloadedEvents.size).isEqualTo(eventLimitByOrgUnit) } }
bsd-3-clause
eaf46a8b2b720c0383e01109204a62ca
45.657534
97
0.748972
4.316857
false
true
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ide/plugins/marketplace/MarketplaceRequests.kt
3
20272
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.plugins.marketplace import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.ide.IdeBundle import com.intellij.ide.plugins.PluginInfoProvider import com.intellij.ide.plugins.PluginNode import com.intellij.ide.plugins.auth.PluginRepositoryAuthService import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.components.serviceOrNull import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.BuildNumber import com.intellij.util.Url import com.intellij.util.Urls import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.io.* import com.intellij.util.ui.IoErrorText import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import org.jetbrains.annotations.VisibleForTesting import org.xml.sax.InputSource import org.xml.sax.SAXException import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URLConnection import java.nio.file.Files import java.nio.file.NoSuchFileException import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.Callable import java.util.concurrent.Future import javax.xml.parsers.ParserConfigurationException import javax.xml.parsers.SAXParserFactory private val LOG = logger<MarketplaceRequests>() private const val FULL_PLUGINS_XML_IDS_FILENAME = "pluginsXMLIds.json" private val objectMapper by lazy { ObjectMapper() } private val pluginManagerUrl by lazy(LazyThreadSafetyMode.PUBLICATION) { ApplicationInfoImpl.getShadowInstance().pluginManagerUrl.trimEnd('/') } private val compatibleUpdateUrl: String get() = "${pluginManagerUrl}/api/search/compatibleUpdates" @ApiStatus.Internal class MarketplaceRequests : PluginInfoProvider { companion object { @JvmStatic fun getInstance(): MarketplaceRequests = PluginInfoProvider.getInstance() as MarketplaceRequests @JvmStatic fun parsePluginList(input: InputStream): List<PluginNode> { try { val handler = RepositoryContentHandler() SAXParserFactory.newDefaultInstance().newSAXParser().parse(InputSource(input), handler) return handler.pluginsList } catch (e: Exception) { when (e) { is ParserConfigurationException, is SAXException, is RuntimeException -> throw IOException(e) else -> throw e } } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads fun loadLastCompatiblePluginDescriptors( pluginIds: Set<PluginId>, buildNumber: BuildNumber? = null, ): List<PluginNode> { return getLastCompatiblePluginUpdate(pluginIds, buildNumber) .map { loadPluginDescriptor(it.pluginId, it, null) } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads fun getLastCompatiblePluginUpdate( ids: Set<PluginId>, buildNumber: BuildNumber? = null, ): List<IdeCompatibleUpdate> { try { if (ids.isEmpty()) { return emptyList() } val data = objectMapper.writeValueAsString(CompatibleUpdateRequest(ids, buildNumber)) return HttpRequests .post(Urls.newFromEncoded(compatibleUpdateUrl).toExternalForm(), HttpRequests.JSON_CONTENT_TYPE) .productNameAsUserAgent() .throwStatusCodeException(false) .connect { it.write(data) objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {}) } } catch (e: Exception) { LOG.infoOrDebug("Can not get compatible updates from Marketplace", e) return emptyList() } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmStatic @JvmOverloads @Throws(IOException::class) internal fun loadPluginDescriptor( xmlId: String, ideCompatibleUpdate: IdeCompatibleUpdate, indicator: ProgressIndicator? = null, ): PluginNode { val updateMetadataFile = Paths.get(PathManager.getPluginTempPath(), "meta") return readOrUpdateFile( updateMetadataFile.resolve(ideCompatibleUpdate.externalUpdateId + ".json"), "$pluginManagerUrl/files/${ideCompatibleUpdate.externalPluginId}/${ideCompatibleUpdate.externalUpdateId}/meta.json", indicator, IdeBundle.message("progress.downloading.plugins.meta", xmlId) ) { objectMapper.readValue(it, IntellijUpdateMetadata::class.java) }.toPluginNode() } @JvmStatic @JvmName("readOrUpdateFile") @Throws(IOException::class) internal fun <T> readOrUpdateFile( file: Path?, url: String, indicator: ProgressIndicator?, @Nls indicatorMessage: String, parser: (InputStream) -> T ): T { val eTag = if (file == null) null else loadETagForFile(file) return HttpRequests .request(url) .tuner { connection -> if (eTag != null) { connection.setRequestProperty("If-None-Match", eTag) } if (ApplicationManager.getApplication() != null) { serviceOrNull<PluginRepositoryAuthService>() ?.connectionTuner ?.tune(connection) } } .productNameAsUserAgent() .connect { request -> try { indicator?.checkCanceled() val connection = request.connection if (file != null && isNotModified(connection, file)) { return@connect Files.newInputStream(file).use(parser) } if (indicator != null) { indicator.checkCanceled() indicator.text2 = indicatorMessage } if (file == null) { return@connect request.inputStream.use(parser) } synchronized(this) { request.saveToFile(file, indicator) connection.getHeaderField("ETag")?.let { saveETagForFile(file, it) } } return@connect Files.newInputStream(file).use(parser) } catch (e: HttpRequests.HttpStatusException) { LOG.infoWithDebug("Cannot load data from ${url} (statusCode=${e.statusCode})", e) throw e } catch (e: Exception) { LOG.infoWithDebug("Error reading Marketplace file: ${e} (file=${file} URL=${url})", e) if (file != null && LOG.isDebugEnabled) { LOG.debug("File content:\n${runCatching { Files.readString(file) }.getOrElse { IoErrorText.message(e) }}") } throw e } } } } private val IDE_BUILD_FOR_REQUEST = URLUtil.encodeURIComponent(ApplicationInfoImpl.getShadowInstanceImpl().pluginsCompatibleBuild) private val MARKETPLACE_ORGANIZATIONS_URL = Urls.newFromEncoded("${pluginManagerUrl}/api/search/aggregation/organizations") .addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private val JETBRAINS_PLUGINS_URL = Urls.newFromEncoded( "${pluginManagerUrl}/api/search/plugins?organization=JetBrains&max=1000" ).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private val IDE_EXTENSIONS_URL = Urls.newFromEncoded("${pluginManagerUrl}/files/IDE/extensions.json") .addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST)) private fun createSearchUrl(query: String, count: Int): Url { return Urls.newFromEncoded("$pluginManagerUrl/api/search/plugins?$query&build=$IDE_BUILD_FOR_REQUEST&max=$count") } private fun createFeatureUrl(param: Map<String, String>): Url { return Urls.newFromEncoded("${pluginManagerUrl}/feature/getImplementations").addParameters(param) } @Throws(IOException::class) fun getFeatures(param: Map<String, String>): List<FeatureImpl> { if (param.isEmpty()) { return emptyList() } try { return HttpRequests .request(createFeatureUrl(param)) .throwStatusCodeException(false) .productNameAsUserAgent() .setHeadersViaTuner() .connect { objectMapper.readValue( it.inputStream, object : TypeReference<List<FeatureImpl>>() {} ) } } catch (e: Exception) { LOG.infoOrDebug("Can not get features from Marketplace", e) return emptyList() } } @Throws(IOException::class) internal fun getFeatures( featureType: String, implementationName: String, ): List<FeatureImpl> { val param = mapOf( "featureType" to featureType, "implementationName" to implementationName, "build" to ApplicationInfoImpl.getShadowInstanceImpl().pluginsCompatibleBuild, ) return getFeatures(param) } @RequiresBackgroundThread @JvmOverloads @Throws(IOException::class) fun getMarketplacePlugins(indicator: ProgressIndicator? = null): Set<PluginId> { return readOrUpdateFile( Path.of(PathManager.getPluginTempPath(), FULL_PLUGINS_XML_IDS_FILENAME), "${pluginManagerUrl}/files/$FULL_PLUGINS_XML_IDS_FILENAME", indicator, IdeBundle.message("progress.downloading.available.plugins"), ::parseXmlIds, ) } override fun loadPlugins(indicator: ProgressIndicator?): Future<Set<PluginId>> { return ApplicationManager.getApplication().executeOnPooledThread(Callable { try { getMarketplacePlugins(indicator) } catch (e: IOException) { LOG.infoOrDebug("Cannot get plugins from Marketplace", e) emptySet() } }) } override fun loadCachedPlugins(): Set<PluginId>? { val pluginXmlIdsFile = Paths.get(PathManager.getPluginTempPath(), FULL_PLUGINS_XML_IDS_FILENAME) try { if (Files.size(pluginXmlIdsFile) > 0) { return Files.newInputStream(pluginXmlIdsFile).use(::parseXmlIds) } } catch (ignore: IOException) { } return null } @Throws(IOException::class) fun searchPlugins(query: String, count: Int): List<PluginNode> { val marketplaceSearchPluginData = HttpRequests .request(createSearchUrl(query, count)) .setHeadersViaTuner() .throwStatusCodeException(false) .connect { objectMapper.readValue( it.inputStream, object : TypeReference<List<MarketplaceSearchPluginData>>() {} ) } // Marketplace Search Service can produce objects without "externalUpdateId". It means that an update is not in the search index yet. return marketplaceSearchPluginData.filter { it.externalUpdateId != null }.map { it.toPluginNode() } } fun getAllPluginsVendors(): List<String> { try { return HttpRequests .request(MARKETPLACE_ORGANIZATIONS_URL) .setHeadersViaTuner() .productNameAsUserAgent() .throwStatusCodeException(false) .connect { objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList() } } catch (e: Exception) { LOG.infoOrDebug("Can not get organizations from Marketplace", e) return emptyList() } } fun getBrokenPlugins(currentBuild: BuildNumber): Map<PluginId, Set<String>> { val brokenPlugins = try { readOrUpdateFile( Paths.get(PathManager.getPluginTempPath(), "brokenPlugins.json"), "${pluginManagerUrl}/files/brokenPlugins.json", null, "" ) { objectMapper.readValue(it, object : TypeReference<List<MarketplaceBrokenPlugin>>() {}) } } catch (e: Exception) { LOG.infoOrDebug("Can not get broken plugins file from Marketplace", e) return emptyMap() } val brokenPluginsMap = HashMap<PluginId, MutableSet<String>>() brokenPlugins.forEach { record -> try { val parsedOriginalUntil = record.originalUntil?.trim() val parsedOriginalSince = record.originalSince?.trim() if (!parsedOriginalUntil.isNullOrEmpty() && !parsedOriginalSince.isNullOrEmpty()) { val originalUntil = BuildNumber.fromString(parsedOriginalUntil, record.id, null) ?: currentBuild val originalSince = BuildNumber.fromString(parsedOriginalSince, record.id, null) ?: currentBuild val until = BuildNumber.fromString(record.until) ?: currentBuild val since = BuildNumber.fromString(record.since) ?: currentBuild if (currentBuild in originalSince..originalUntil && currentBuild !in since..until) { brokenPluginsMap.computeIfAbsent(PluginId.getId(record.id)) { HashSet() }.add(record.version) } } } catch (e: Exception) { LOG.error("cannot parse ${record}", e) } } return brokenPluginsMap } fun getAllPluginsTags(): List<String> { try { return HttpRequests .request(Urls.newFromEncoded( "${pluginManagerUrl}/api/search/aggregation/tags" ).addParameters(mapOf("build" to IDE_BUILD_FOR_REQUEST))) .setHeadersViaTuner() .productNameAsUserAgent() .throwStatusCodeException(false) .connect { objectMapper.readValue(it.inputStream, AggregationSearchResponse::class.java).aggregations.keys.toList() } } catch (e: Exception) { LOG.infoOrDebug("Can not get tags from Marketplace", e) return emptyList() } } @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun loadPluginDetails( pluginNode: PluginNode, indicator: ProgressIndicator? = null, ): PluginNode? { val externalPluginId = pluginNode.externalPluginId ?: return pluginNode val externalUpdateId = pluginNode.externalUpdateId ?: return pluginNode try { return loadPluginDescriptor( pluginNode.pluginId.idString, IdeCompatibleUpdate(externalUpdateId = externalUpdateId, externalPluginId = externalPluginId), indicator, ).apply { // these three fields are not present in `IntellijUpdateMetadata`, but present in `MarketplaceSearchPluginData` rating = pluginNode.rating downloads = pluginNode.downloads date = pluginNode.date } } catch (e: IOException) { LOG.error(e) return null } } @Deprecated("Please use `PluginId`", replaceWith = ReplaceWith("getLastCompatiblePluginUpdate(PluginId.get(id), buildNumber, indicator)")) @ApiStatus.ScheduledForRemoval @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun getLastCompatiblePluginUpdate( id: String, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): PluginNode? = getLastCompatiblePluginUpdate(PluginId.getId(id), buildNumber, indicator) @RequiresBackgroundThread @RequiresReadLockAbsence @JvmOverloads fun getLastCompatiblePluginUpdate( pluginId: PluginId, buildNumber: BuildNumber? = null, indicator: ProgressIndicator? = null, ): PluginNode? { return getLastCompatiblePluginUpdate(setOf(pluginId), buildNumber).firstOrNull() ?.let { loadPluginDescriptor(pluginId.idString, it, indicator) } } fun getCompatibleUpdateByModule(module: String): PluginId? { try { val data = objectMapper.writeValueAsString(CompatibleUpdateForModuleRequest(module)) return HttpRequests.post( Urls.newFromEncoded(compatibleUpdateUrl).toExternalForm(), HttpRequests.JSON_CONTENT_TYPE, ).productNameAsUserAgent() .throwStatusCodeException(false) .connect { it.write(data) objectMapper.readValue(it.inputStream, object : TypeReference<List<IdeCompatibleUpdate>>() {}) }.firstOrNull() ?.pluginId ?.let { PluginId.getId(it) } } catch (e: Exception) { LOG.infoOrDebug("Can not get compatible update by module from Marketplace", e) return null } } var jetBrainsPluginsIds: Set<String>? = null private set fun loadJetBrainsPluginsIds() { if (jetBrainsPluginsIds != null) { return } try { HttpRequests .request(JETBRAINS_PLUGINS_URL) .productNameAsUserAgent() .setHeadersViaTuner() .throwStatusCodeException(false) .connect { deserializeJetBrainsPluginsIds(it.inputStream) } } catch (e: Exception) { LOG.infoOrDebug("Can not get JetBrains plugins' IDs from Marketplace", e) jetBrainsPluginsIds = null } } @VisibleForTesting fun deserializeJetBrainsPluginsIds(stream: InputStream) { jetBrainsPluginsIds = objectMapper.readValue(stream, object : TypeReference<List<MarketplaceSearchPluginData>>() {}) .asSequence() .map(MarketplaceSearchPluginData::id) .toCollection(HashSet()) } var extensionsForIdes: Map<String, List<String>>? = null private set fun loadExtensionsForIdes() { if (extensionsForIdes != null) { return } try { HttpRequests .request(IDE_EXTENSIONS_URL) .productNameAsUserAgent() .setHeadersViaTuner() .throwStatusCodeException(false) .connect { deserializeExtensionsForIdes(it.inputStream) } } catch (e: Exception) { LOG.infoOrDebug("Can not get supported extensions from Marketplace", e) extensionsForIdes = null } } @VisibleForTesting fun deserializeExtensionsForIdes(stream: InputStream) { extensionsForIdes = objectMapper.readValue(stream, object : TypeReference<Map<String, List<String>>>() {}) } private fun parseXmlIds(input: InputStream) = objectMapper.readValue(input, object : TypeReference<Set<PluginId>>() {}) } /** * NB!: any previous tuners set by {@link RequestBuilder#tuner} will be overwritten by this call */ fun RequestBuilder.setHeadersViaTuner(): RequestBuilder { return ApplicationManager.getApplication() ?.getService(PluginRepositoryAuthService::class.java) ?.connectionTuner ?.let(::tuner) ?: this } private fun loadETagForFile(file: Path): String { val eTagFile = getETagFile(file) try { val lines = Files.readAllLines(eTagFile) if (lines.size == 1) { return lines[0] } LOG.warn("Can't load ETag from '" + eTagFile + "'. Unexpected number of lines: " + lines.size) Files.deleteIfExists(eTagFile) } catch (ignore: NoSuchFileException) { } catch (e: IOException) { LOG.warn("Can't load ETag from '$eTagFile'", e) } return "" } @Suppress("SpellCheckingInspection") private fun getETagFile(file: Path): Path = file.parent.resolve("${file.fileName}.etag") private fun saveETagForFile(file: Path, eTag: String) { val eTagFile = getETagFile(file) try { eTagFile.write(eTag) } catch (e: IOException) { LOG.warn("Can't save ETag to '$eTagFile'", e) } } private fun isNotModified(urlConnection: URLConnection, file: Path?): Boolean { return file != null && file.exists() && Files.size(file) > 0 && urlConnection is HttpURLConnection && urlConnection.responseCode == HttpURLConnection.HTTP_NOT_MODIFIED } private data class CompatibleUpdateRequest( val build: String, val pluginXMLIds: List<String>, ) { @JvmOverloads constructor( pluginIds: Set<PluginId>, buildNumber: BuildNumber? = null, ) : this( ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber), pluginIds.map { it.idString }, ) } private data class CompatibleUpdateForModuleRequest( val module: String, val build: String, ) { @JvmOverloads constructor( module: String, buildNumber: BuildNumber? = null, ) : this( module, ApplicationInfoImpl.orFromPluginsCompatibleBuild(buildNumber), ) } private fun Logger.infoOrDebug( message: String, throwable: Throwable, ) { if (isDebugEnabled) { debug(message, throwable) } else { info("$message: ${throwable.message}") } }
apache-2.0
370e8390b1c94c1e27624c4cd1e45965
32.618574
144
0.685675
4.615665
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt
3
3839
// 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.rename import com.intellij.lang.Language import com.intellij.openapi.editor.Editor import com.intellij.psi.* import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler import com.intellij.refactoring.rename.inplace.MemberInplaceRenamer import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtPrimaryConstructor class KotlinMemberInplaceRenameHandler : MemberInplaceRenameHandler() { private class RenamerImpl( elementToRename: PsiNamedElement, substitutedElement: PsiElement?, editor: Editor, currentName: String, oldName: String ) : MemberInplaceRenamer(elementToRename, substitutedElement, editor, currentName, oldName) { override fun isIdentifier(newName: String?, language: Language?): Boolean { if (newName == "" && (variable as? KtObjectDeclaration)?.isCompanion() == true) return true return super.isIdentifier(newName, language) } override fun acceptReference(reference: PsiReference): Boolean { val refElement = reference.element val textRange = reference.rangeInElement val referenceText = refElement.text.substring(textRange.startOffset, textRange.endOffset).unquoteKotlinIdentifier() return referenceText == myElementToRename.name } override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean { return variable == element && (handler is MemberInplaceRenameHandler || handler is KotlinRenameDispatcherHandler) } override fun createInplaceRenamerToRestart(variable: PsiNamedElement, editor: Editor, initialName: String): VariableInplaceRenamer { return RenamerImpl(variable, substituted, editor, initialName, myOldName) } } private fun PsiElement.substitute(): PsiElement { if (this is KtPrimaryConstructor) return getContainingClassOrObject() return this } override fun createMemberRenamer(element: PsiElement, elementToRename: PsiNameIdentifierOwner, editor: Editor): MemberInplaceRenamer { val currentElementToRename = elementToRename.substitute() as PsiNameIdentifierOwner val nameIdentifier = currentElementToRename.nameIdentifier // Move caret if constructor range doesn't intersect with the one of the containing class val offset = editor.caretModel.offset val editorPsiFile = PsiDocumentManager.getInstance(element.project).getPsiFile(editor.document) if (nameIdentifier != null && editorPsiFile == elementToRename.containingFile && elementToRename is KtPrimaryConstructor && offset !in nameIdentifier.textRange && offset in elementToRename.textRange) { editor.caretModel.moveToOffset(nameIdentifier.textOffset) } val currentName = nameIdentifier?.text ?: "" return RenamerImpl(currentElementToRename, element, editor, currentName, currentName) } override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean { if (!editor.settings.isVariableInplaceRenameEnabled) return false val currentElement = element?.substitute() as? KtNamedDeclaration ?: return false return currentElement.nameIdentifier != null && !KotlinVariableInplaceRenameHandler.isInplaceRenameAvailable(currentElement) } }
apache-2.0
2711c0a429b1afbb01f9f97cc90e2d07
53.070423
209
0.753321
5.629032
false
false
false
false
dahlstrom-g/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/MavenRootModelAdapterBridge.kt
2
11082
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing.workspaceModel import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.RootConfigurationAccessor import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.pom.java.LanguageLevel import com.intellij.workspaceModel.ide.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge 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.idea.maven.importing.MavenModelUtil import org.jetbrains.idea.maven.importing.MavenRootModelAdapterInterface import org.jetbrains.idea.maven.importing.ModifiableModelsProviderProxy import org.jetbrains.idea.maven.model.MavenArtifact import org.jetbrains.idea.maven.model.MavenConstants import org.jetbrains.idea.maven.project.MavenProject import org.jetbrains.idea.maven.utils.Path import org.jetbrains.idea.maven.utils.Url import org.jetbrains.jps.model.JpsElement import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModuleSourceRootType import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer import java.io.File @Retention(AnnotationRetention.SOURCE) private annotation class NotRequiredToImplement class MavenRootModelAdapterBridge(private val myMavenProject: MavenProject, private val module: ModuleBridge, private val project: Project, initialModuleEntity: ModuleEntity, private val legacyBridgeModifiableModelsProvider: IdeModifiableModelsProviderBridge, private val builder: MutableEntityStorage) : MavenRootModelAdapterInterface { private var moduleEntity: ModuleEntity = initialModuleEntity private val legacyBridge = ModuleRootComponentBridge.getInstance(module) private val modifiableModel = legacyBridge.getModifiableModel(builder, RootConfigurationAccessor()) private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project) private val entitySource = MavenExternalSource.INSTANCE override fun init(isNewlyCreatedModule: Boolean) {} override fun getRootModel(): ModifiableRootModel { return modifiableModel } override fun getSourceRootUrls(includingTests: Boolean): Array<String> { return legacyBridge.sourceRootUrls } override fun getModule(): Module { return module } @NotRequiredToImplement override fun clearSourceFolders() { } override fun <P : JpsElement?> addSourceFolder(path: String, rootType: JpsModuleSourceRootType<P>) { createSourceRoot(rootType, path, false) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType, ifNotEmpty: Boolean) { createSourceRoot(rootType, path, true) } override fun addGeneratedJavaSourceFolder(path: String, rootType: JavaSourceRootType) { createSourceRoot(rootType, path, true) } private fun <P : JpsElement?> createSourceRoot(rootType: JpsModuleSourceRootType<P>, path: String, generated: Boolean) { val typeId = getTypeId(rootType) val contentRootEntity = getContentRootFor(toUrl(path)) ?: error("Can't find content root for the source root $path") val sourceRootEntity = builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(path)), typeId, entitySource) when (rootType) { is JavaSourceRootType -> builder.addJavaSourceRootEntity(sourceRootEntity, generated, "") is JavaResourceRootType -> builder.addJavaResourceRootEntity(sourceRootEntity, generated, "") else -> TODO() } } private fun <P : JpsElement?> getTypeId(rootType: JpsModuleSourceRootType<P>): String { return if (rootType.isForTests()) return JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID else JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID } override fun hasRegisteredSourceSubfolder(f: File): Boolean { val url: String = toUrl(f.path).url return builder.entities(SourceRootEntity::class.java).filter { VfsUtilCore.isEqualOrAncestor(url, it.url.url) }.any() } private fun toUrl(path: String): Url { return toPath(path).toUrl() } override fun toPath(path: String): Path { if (!FileUtil.isAbsolute(path)) { return Path(File(myMavenProject.directory, path).path) } return Path(path) } override fun getSourceFolder(folder: File): SourceFolder? { return legacyBridge.contentEntries.flatMap { it.sourceFolders.asList() }.find { it.url == VfsUtilCore.fileToUrl(folder) } } override fun isAlreadyExcluded(f: File): Boolean { val url = toUrl(f.path).url return moduleEntity.contentRoots.filter { cre -> VfsUtilCore.isUnder(url, cre.excludedUrls.map { it.url }) }.any() } override fun addExcludedFolder(path: String) { getContentRootFor(toUrl(path))?.let { builder.modifyEntity(it) { this.excludedUrls = this.excludedUrls + virtualFileManager.fromUrl(VfsUtilCore.pathToUrl(path)) } } } private fun getContentRootFor(url: Url): ContentRootEntity? { return moduleEntity.contentRoots.firstOrNull { VfsUtilCore.isEqualOrAncestor(it.url.url, url.url) } } @NotRequiredToImplement override fun unregisterAll(path: String, under: Boolean, unregisterSources: Boolean) { } @NotRequiredToImplement override fun hasCollision(sourceRootPath: String): Boolean { return false } override fun useModuleOutput(production: String, test: String) { TODO("not implemented") } override fun addModuleDependency(moduleName: String, scope: DependencyScope, testJar: Boolean) { val dependency = ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(moduleName), false, toEntityScope(scope), testJar) moduleEntity = builder.modifyEntity(moduleEntity) { this.dependencies = this.dependencies + dependency } } private fun toEntityScope(scope: DependencyScope): ModuleDependencyItem.DependencyScope { return when (scope) { DependencyScope.COMPILE -> ModuleDependencyItem.DependencyScope.COMPILE DependencyScope.PROVIDED -> ModuleDependencyItem.DependencyScope.PROVIDED DependencyScope.RUNTIME -> ModuleDependencyItem.DependencyScope.RUNTIME DependencyScope.TEST -> ModuleDependencyItem.DependencyScope.TEST } } override fun findModuleByName(moduleName: String): Module? { return ModuleManagerComponentBridge(project).modules.firstOrNull { it.name == moduleName } } private fun MavenArtifact.ideaLibraryName(): String = "${this.libraryName}" override fun addSystemDependency(artifact: MavenArtifact, scope: DependencyScope) { assert(MavenConstants.SCOPE_SYSTEM == artifact.scope) { "Artifact scope should be \"system\"" } val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) val libraryTableId = LibraryTableId.ModuleLibraryTableId(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />") } override fun addLibraryDependency(artifact: MavenArtifact, scope: DependencyScope, provider: ModifiableModelsProviderProxy, project: MavenProject): LibraryOrderEntry { val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, null, null)), LibraryRootTypeId.COMPILED)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "javadoc", "jar")), WorkspaceModuleImporter.JAVADOC_TYPE)) roots.add( LibraryRoot(virtualFileManager.fromUrl(MavenModelUtil.getArtifactUrlForClassifierAndExtension(artifact, "sources", "jar")), LibraryRootTypeId.SOURCES)) val libraryTableId = LibraryTableId.ProjectLibraryTableId //(ModuleId(moduleEntity.name)) val libraryEntity = builder.addLibraryEntity(artifact.ideaLibraryName(), libraryTableId, roots, emptyList(), entitySource) builder.addLibraryPropertiesEntity(libraryEntity, "repository", "<properties maven-id=\"${artifact.mavenId}\" />") val libDependency = ModuleDependencyItem.Exportable.LibraryDependency(LibraryId(libraryEntity.name, libraryTableId), false, toEntityScope(scope)) moduleEntity = builder.modifyEntity(moduleEntity) { this.dependencies += this.dependencies + libDependency } val last = legacyBridge.orderEntries.last() assert(last is LibraryOrderEntry && last.libraryName == artifact.ideaLibraryName()) return last as LibraryOrderEntry } override fun findLibrary(artifact: MavenArtifact): Library? { return legacyBridge.getModuleLibraryTable().libraries.firstOrNull { it.name == artifact.ideaLibraryName() } } override fun setLanguageLevel(level: LanguageLevel) { try { modifiableModel.getModuleExtension(LanguageLevelModuleExtension::class.java)?.apply { languageLevel = level } } catch (e: IllegalArgumentException) { //bad value was stored } } }
apache-2.0
604b74d0d9298e5ccb11f3ed21032ee7
43.332
155
0.701949
5.549324
false
false
false
false
zbeboy/ISY
src/main/java/top/zbeboy/isy/web/system/log/SystemLogController.kt
1
1870
package top.zbeboy.isy.web.system.log import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody import top.zbeboy.isy.glue.system.SystemLogGlue import top.zbeboy.isy.web.bean.system.log.SystemLogBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.ArrayList import javax.annotation.Resource import javax.servlet.http.HttpServletRequest /** * Created by zbeboy 2017-11-11 . **/ @Controller @RequestMapping("/web") open class SystemLogController { @Resource open lateinit var systemLogGlue: SystemLogGlue /** * 系统日志 * * @return 系统日志页面 */ @RequestMapping("/menu/system/log") fun systemLog(): String { return "web/system/log/system_log::#page-wrapper" } /** * datatables ajax查询数据 * * @param request 请求 * @return datatables数据 */ @RequestMapping(value = ["/system/log/data"], method = [(RequestMethod.GET)]) @ResponseBody fun systemLogs(request: HttpServletRequest): DataTablesUtils<SystemLogBean> { // 前台数据标题 注:要和前台标题顺序一致,获取order用 val headers = ArrayList<String>() headers.add("username") headers.add("behavior") headers.add("operating_time") headers.add("ip_address") val dataTablesUtils = DataTablesUtils<SystemLogBean>(request, headers) val resultUtils = systemLogGlue.findAllByPage(dataTablesUtils) dataTablesUtils.data = resultUtils.getData() dataTablesUtils.setiTotalRecords(systemLogGlue.countAll()) dataTablesUtils.setiTotalDisplayRecords(resultUtils.getTotalElements()) return dataTablesUtils } }
mit
93a7f622262eded126e2105e0426db8e
30.982143
81
0.71676
4.46384
false
false
false
false
rafaeltoledo/kotlin-sandbox
app/src/main/java/net/rafaeltoledo/stak/ui/adapter/UserAdapter.kt
1
1806
package net.rafaeltoledo.stak.ui.adapter import android.os.Parcelable import android.support.v7.widget.RecyclerView import android.view.ViewGroup import net.rafaeltoledo.stak.R import net.rafaeltoledo.stak.data.User import net.rafaeltoledo.stak.ui.LoadingViewHolder import net.rafaeltoledo.stak.ui.UserViewHolder import net.rafaeltoledo.stak.util.inflate class UserAdapter(private val listener: (User) -> Unit, private val loadMore: (Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var page = 0 var items: MutableList<User> = arrayListOf() private var dontNotify = false override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is UserViewHolder) { holder.bind(items[position], listener) } else { if (!dontNotify) loadMore(++page) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { return if (viewType == 0) UserViewHolder(parent.inflate(R.layout.item_user)) else LoadingViewHolder(parent.inflate(R.layout.item_loading)) } override fun getItemViewType(position: Int) = if (dontNotify || position != itemCount - 1) 0 else 1 override fun getItemCount() = items.size + if (dontNotify) 0 else 1 fun addAll(items: List<User>, continueLoading: Boolean = true) { this.items.addAll(items) dontNotify = continueLoading.not() notifyDataSetChanged() } fun onRestoreInstanceState(state: Parcelable) { if (state is SavedState) { page = state.page items = state.items.toMutableList() as MutableList<User> } } fun onSaveInstanceState(): Parcelable? { return SavedState(page, items.toTypedArray()) } }
apache-2.0
0798ce4643b48636276498f5fff01ca5
33.75
103
0.692137
4.085973
false
false
false
false
paplorinc/intellij-community
java/java-analysis-api/src/com/intellij/lang/jvm/actions/actions.kt
2
2439
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("JvmElementActionFactories") package com.intellij.lang.jvm.actions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.jvm.JvmClass import com.intellij.lang.jvm.JvmMethod import com.intellij.lang.jvm.JvmModifiersOwner import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.util.registry.Registry fun useInterlaguageActions(): Boolean = ApplicationManager.getApplication().isUnitTestMode || Registry.`is`("ide.interlanguage.fixes") val EP_NAME: ExtensionPointName<JvmElementActionsFactory> = ExtensionPointName.create<JvmElementActionsFactory>("com.intellij.lang.jvm.actions.jvmElementActionsFactory") private inline fun createActions(crossinline actions: (JvmElementActionsFactory) -> List<IntentionAction>): List<IntentionAction> { return EP_NAME.extensionList.flatMap { actions(it) } } fun createMethodActions(target: JvmClass, request: CreateMethodRequest): List<IntentionAction> { return createActions { it.createAddMethodActions(target, request) } } fun createConstructorActions(target: JvmClass, request: CreateConstructorRequest): List<IntentionAction> { return createActions { it.createAddConstructorActions(target, request) } } fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> { return createActions { it.createAddAnnotationActions(target, request) } } fun createModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> = createActions { it.createChangeModifierActions(target, request) } @Deprecated("use createModifierActions(JvmModifiersOwner, ChangeModifierRequest)") fun createModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> { return createActions { it.createChangeModifierActions(target, request) } } fun createAddFieldActions(target: JvmClass, request: CreateFieldRequest): List<IntentionAction> = createActions { it.createAddFieldActions(target, request) } fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> = createActions { it.createChangeParametersActions(target, request) }
apache-2.0
323c1513031d620fc72f13bba645571e
42.553571
169
0.817548
4.645714
false
false
false
false
paplorinc/intellij-community
platform/platform-api/src/com/intellij/ui/list/LeftRightRenderer.kt
2
1798
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.list import com.intellij.util.ui.JBUI import java.awt.BorderLayout import java.awt.Component import javax.swing.JList import javax.swing.JPanel import javax.swing.ListCellRenderer /** * A renderer which combines two renderers. * * [mainRenderer] component is aligned to the left, [rightRenderer] component is aligned to the right. * This renderer uses background from [mainRenderer] component. */ abstract class LeftRightRenderer<T> : ListCellRenderer<T> { protected abstract val mainRenderer: ListCellRenderer<T> protected abstract val rightRenderer: ListCellRenderer<T> private val spacer = JPanel().apply { border = JBUI.Borders.empty(0, 2) } private val component = JPanel(BorderLayout()) final override fun getListCellRendererComponent(list: JList<out T>, value: T, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { val mainComponent = mainRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) val rightComponent = rightRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) mainComponent.background.let { component.background = it spacer.background = it rightComponent.background = it } component.apply { removeAll() add(mainComponent, BorderLayout.WEST) add(spacer, BorderLayout.CENTER) add(rightComponent, BorderLayout.EAST) } return component } }
apache-2.0
1e80fbd8a820fbcba92f71b7f37c710a
36.458333
140
0.669633
4.966851
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/TAB_LAYOUT_XML.kt
2
12302
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.demo2_0_0 import org.apache.causeway.client.kroviz.snapshots.Response object TAB_LAYOUT_XML: Response() { override val url = "http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/object-layout" override val str = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <bs3:grid xmlns:cpt="http://causeway.apache.org/applib/layout/component" xmlns:lnk="http://causeway.apache.org/applib/layout/links" xmlns:bs3="http://causeway.apache.org/applib/layout/grid/bootstrap3"> <bs3:row> <bs3:col span="12" unreferencedActions="true"> <cpt:domainObject> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/element</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg== </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object"</lnk:type> </cpt:link> </cpt:domainObject> <cpt:action id="clearHints"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/clearHints </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action id="downloadLayoutXml"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/downloadLayoutXml </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action id="openRestApi"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/openRestApi </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action id="rebuildMetamodel"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/rebuildMetamodel </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action id="doHideField"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/doHideField </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action id="doShowField"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/doShowField </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> <cpt:action bookmarking="NEVER" cssClassFa="fa fa-fw fa-download" cssClassFaPosition="LEFT" id="downloadMetaModelXml"> <cpt:named>Download Meta Model Xml</cpt:named> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/action</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/actions/downloadMetaModelXml </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-action"</lnk:type> </cpt:link> </cpt:action> </bs3:col> </bs3:row> <bs3:row> <bs3:col span="6"> <bs3:tabGroup> <bs3:tab name="Tab 1"> <bs3:row> <bs3:col span="12"> <cpt:fieldSet name="Hideable Field" id="fs1"> <cpt:property id="field1"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/property</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/field1 </lnk:href> <lnk:type> application/json;profile="urn:org.restfulobjects:repr-types/object-property" </lnk:type> </cpt:link> </cpt:property> </cpt:fieldSet> </bs3:col> </bs3:row> </bs3:tab> <bs3:tab name="Tab 2"> <bs3:row> <bs3:col span="12"> <cpt:fieldSet id="fs2"> <cpt:property id="field2"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/property</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/field2 </lnk:href> <lnk:type> application/json;profile="urn:org.restfulobjects:repr-types/object-property" </lnk:type> </cpt:link> </cpt:property> </cpt:fieldSet> </bs3:col> </bs3:row> </bs3:tab> </bs3:tabGroup> </bs3:col> <bs3:col span="6" unreferencedCollections="true"> <cpt:fieldSet name="Description" id="description" unreferencedProperties="true"> <cpt:property id="description" labelPosition="NONE"> <cpt:link> <lnk:rel>urn:org.restfulobjects:rels/property</lnk:rel> <lnk:method>GET</lnk:method> <lnk:href> http://localhost:8080/restful/objects/demo.Tab/ADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPERlbW8-CiAgICA8ZmllbGQxPmZpZWxkIDE8L2ZpZWxkMT4KICAgIDxmaWVsZDI-ZmllbGQgMjwvZmllbGQyPgogICAgPGhpZGRlbj5mYWxzZTwvaGlkZGVuPgo8L0RlbW8-Cg==/properties/description </lnk:href> <lnk:type>application/json;profile="urn:org.restfulobjects:repr-types/object-property" </lnk:type> </cpt:link> </cpt:property> </cpt:fieldSet> </bs3:col> </bs3:row> </bs3:grid> """ }
apache-2.0
633f0fe6d42457301ea3c103175832f7
64.43617
321
0.60478
3.183747
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/kotlin.searching/base/src/org/jetbrains/kotlin/idea/base/searching/usages/KotlinUsageTypeProvider.kt
1
7251
// 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.base.searching.usages import com.intellij.psi.PsiElement import com.intellij.usages.UsageTarget import com.intellij.usages.impl.rules.UsageType import com.intellij.usages.impl.rules.UsageTypeProviderEx import org.jetbrains.kotlin.idea.base.searching.usages.KotlinUsageTypes.toUsageType import org.jetbrains.kotlin.idea.base.searching.usages.UsageTypeEnum.* import org.jetbrains.kotlin.idea.references.readWriteAccess import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.isAncestor import org.jetbrains.kotlin.resolve.references.ReferenceAccess abstract class KotlinUsageTypeProvider : UsageTypeProviderEx { abstract fun getUsageTypeEnumByReference(refExpr: KtReferenceExpression): UsageTypeEnum? private fun getUsageTypeEnum(element: PsiElement?): UsageTypeEnum? { when (element) { is KtForExpression -> return IMPLICIT_ITERATION is KtDestructuringDeclarationEntry -> return READ is KtPropertyDelegate -> return PROPERTY_DELEGATION is KtStringTemplateExpression -> return USAGE_IN_STRING_LITERAL is KtConstructorDelegationReferenceExpression -> return CONSTRUCTOR_DELEGATION_REFERENCE } val refExpr = element?.getNonStrictParentOfType<KtReferenceExpression>() ?: return null return getCommonUsageType(refExpr) ?: getUsageTypeEnumByReference(refExpr) } override fun getUsageType(element: PsiElement): UsageType? = getUsageType(element, UsageTarget.EMPTY_ARRAY) override fun getUsageType(element: PsiElement?, targets: Array<out UsageTarget>): UsageType? { val usageType = getUsageTypeEnum(element) ?: return null return usageType.toUsageType() } private fun getCommonUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? = when { refExpr.getNonStrictParentOfType<KtImportDirective>() != null -> CLASS_IMPORT refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression> { callableReference } != null -> CALLABLE_REFERENCE else -> null } protected fun getClassUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? { if (refExpr.getNonStrictParentOfType<KtTypeProjection>() != null) return TYPE_PARAMETER val property = refExpr.getNonStrictParentOfType<KtProperty>() if (property != null) { when { property.typeReference.isAncestor(refExpr) -> return if (property.isLocal) CLASS_LOCAL_VAR_DECLARATION else NON_LOCAL_PROPERTY_TYPE property.receiverTypeReference.isAncestor(refExpr) -> return EXTENSION_RECEIVER_TYPE } } val function = refExpr.getNonStrictParentOfType<KtFunction>() if (function != null) { when { function.typeReference.isAncestor(refExpr) -> return FUNCTION_RETURN_TYPE function.receiverTypeReference.isAncestor(refExpr) -> return EXTENSION_RECEIVER_TYPE } } return when { refExpr.getParentOfTypeAndBranch<KtTypeParameter> { extendsBound } != null || refExpr.getParentOfTypeAndBranch<KtTypeConstraint> { boundTypeReference } != null -> TYPE_CONSTRAINT refExpr is KtSuperTypeListEntry || refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry> { typeReference } != null -> SUPER_TYPE refExpr.getParentOfTypeAndBranch<KtParameter> { typeReference } != null -> VALUE_PARAMETER_TYPE refExpr.getParentOfTypeAndBranch<KtIsExpression> { typeReference } != null || refExpr.getParentOfTypeAndBranch<KtWhenConditionIsPattern> { typeReference } != null -> IS with(refExpr.getParentOfTypeAndBranch<KtBinaryExpressionWithTypeRHS> { right }) { val opType = this?.operationReference?.getReferencedNameElementType() opType == org.jetbrains.kotlin.lexer.KtTokens.AS_KEYWORD || opType == org.jetbrains.kotlin.lexer.KtTokens.AS_SAFE } -> CLASS_CAST_TO with(refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()) { when { this == null -> { false } receiverExpression == refExpr -> { true } else -> { selectorExpression == refExpr && getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { receiverExpression } != null } } } -> CLASS_OBJECT_ACCESS refExpr.getParentOfTypeAndBranch<KtSuperExpression> { superTypeQualifier } != null -> SUPER_TYPE_QUALIFIER refExpr.getParentOfTypeAndBranch<KtTypeAlias> { getTypeReference() } != null -> TYPE_ALIAS else -> null } } protected fun getVariableUsageType(refExpr: KtReferenceExpression): UsageTypeEnum { if (refExpr.getParentOfTypeAndBranch<KtDelegatedSuperTypeEntry> { delegateExpression } != null) return DELEGATE if (refExpr.parent is KtValueArgumentName) return NAMED_ARGUMENT val dotQualifiedExpression = refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>() if (dotQualifiedExpression != null) { val parent = dotQualifiedExpression.parent when { dotQualifiedExpression.receiverExpression.isAncestor(refExpr) -> return RECEIVER parent is KtDotQualifiedExpression && parent.receiverExpression.isAncestor(refExpr) -> return RECEIVER } } return when (refExpr.readWriteAccess(useResolveForReadWrite = true)) { ReferenceAccess.READ -> READ ReferenceAccess.WRITE, ReferenceAccess.READ_WRITE -> WRITE } } protected fun getPackageUsageType(refExpr: KtReferenceExpression): UsageTypeEnum? = when { refExpr.getNonStrictParentOfType<KtPackageDirective>() != null -> PACKAGE_DIRECTIVE refExpr.getNonStrictParentOfType<KtQualifiedExpression>() != null -> PACKAGE_MEMBER_ACCESS else -> getClassUsageType(refExpr) } } enum class UsageTypeEnum { TYPE_CONSTRAINT, VALUE_PARAMETER_TYPE, NON_LOCAL_PROPERTY_TYPE, FUNCTION_RETURN_TYPE, SUPER_TYPE, IS, CLASS_OBJECT_ACCESS, COMPANION_OBJECT_ACCESS, EXTENSION_RECEIVER_TYPE, SUPER_TYPE_QUALIFIER, TYPE_ALIAS, FUNCTION_CALL, IMPLICIT_GET, IMPLICIT_SET, IMPLICIT_INVOKE, IMPLICIT_ITERATION, PROPERTY_DELEGATION, RECEIVER, DELEGATE, PACKAGE_DIRECTIVE, PACKAGE_MEMBER_ACCESS, CALLABLE_REFERENCE, READ, WRITE, CLASS_IMPORT, CLASS_LOCAL_VAR_DECLARATION, TYPE_PARAMETER, CLASS_CAST_TO, ANNOTATION, CLASS_NEW_OPERATOR, NAMED_ARGUMENT, USAGE_IN_STRING_LITERAL, CONSTRUCTOR_DELEGATION_REFERENCE, }
apache-2.0
35893446ecc94c797dfd3fd1a6e0b38d
38.840659
190
0.676596
5.612229
false
false
false
false
sakki54/RLGdx
src/main/kotlin/com/brekcel/RLGdx/map/pathfinding/AStar.kt
1
4010
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2017 Clayton Breckel //////////////////////////////////////////////////////////////////////////////// package com.brekcel.RLGdx.map.pathfinding import com.brekcel.RLGdx.map.Map import com.brekcel.RLGdx.misc.Direction import java.util.* /** A* algorithm for the Map class */ class AStar : PathFinder { /** The cost to move horizontally/vertically */ var normalCost: Int /** The cost to move diagonally */ var diagCost: Int /** Creates an A* object * @param map The map object that this A* works for * @param normalCost The [normalCost] *@param diagCost The [diagCost] */ constructor(map: Map, normalCost: Int, diagCost: Int) : super(map) { this.normalCost = normalCost this.diagCost = diagCost } /** The heuristic from source to dest */ private fun heuristic(source: Point, destination: Point): Int { val dx = Math.abs(destination.x - source.y) val dy = Math.abs(destination.y - source.y) val diagonal = Math.min(dx, dy) val orthogonal = dx + dy - 2 * diagonal return diagonal * diagCost + orthogonal * normalCost } /** Get's a queue of directions from sx,sy to dx,dy * @param sx The source x coord * @param sy The source y coord * @param dx The destination x coord * @param dy The destination y coord */ fun getQueue(sx: Int, sy: Int, dx: Int, dy: Int): LinkedList<Direction> { val openList = PriorityQueue<Node>() val closedList = hashMapOf<Point, Cost>() var solution: Node? = null val start = Point(sx, sy) val dest = Point(dx, dy) openList.add(Node(null, start, Cost(0, heuristic(Point.EMPTY, dest)))) fun addNeighbors(node: Node) { (-1).rangeTo(1).forEach { x -> (-1).rangeTo(1).forEach y@ { y -> if (x == 0 && y == 0) return@y val newPos = Point(node.position.x + x, node.position.y + y) if (!map.inBounds(newPos.x, newPos.y) || !map.canWalk(newPos.x, newPos.y)) return@y val cost = node.cost.distTravelled + if (x == 0 || y == 0) normalCost else diagCost openList.add(Node(node, newPos, Cost(cost, cost + heuristic(newPos, dest)))) } } } while (!openList.isEmpty()) { val node = openList.poll() if (closedList.containsKey(node.position)) continue closedList.put(node.position, node.cost) if (node.position == dest) { solution = node break } addNeighbors(node) } val retList = LinkedList<Direction>() if (solution == null) { retList.add(Direction.ZERO) return retList } var node: Node = solution while (node.parent != null) { val pos = node.position - node.parent!!.position retList.add(Direction.getEnum(pos.x, pos.y)) node = node.parent!! } return retList } /** Get's the direction that you need to be moving to reach dx,dy from sx,sy * @param sx The source x coord * @param sy The source y coord * @param dx The destination x coord * @param dy The destination y coord */ fun getDir(sx: Int, sy: Int, dx: Int, dy: Int) = getQueue(sx, sy, dx, dy).poll() /** A point */ private data class Point( /** The x coord */ var x: Int, /** The y coord */ var y: Int) { /** The companion object */ companion object { /** An empty Point. Point(0,0) */ val EMPTY get() = Point(0, 0) } /** Subtract two points from each other */ operator fun minus(other: Point) = Point(x - other.x, y - other.y) } /** A node for the A* */ private data class Node( /** The parent node */ var parent: Node?, /** This node's position */ var position: Point, /** This node's cost */ var cost: Cost) : Comparable<Node> { /** Compare two Nodes */ override fun compareTo(other: Node) = cost.compareTo(other.cost) } /** The cost for the A* */ data class Cost( /** The distance travelled for this node*/ val distTravelled: Int, /** The total cost for this distance */ val totalCost: Int) { /** Compare two Costs */ fun compareTo(other: Cost) = totalCost.compareTo(other.totalCost) } }
mit
506757b95295164ad2040986a2255e06
29.157895
88
0.622693
3.246964
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/ConvertConcatenationToBuildStringIntention.kt
1
2198
// 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.k2.codeinsight.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferences import org.jetbrains.kotlin.idea.base.psi.isAnnotationArgument import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicable.intentions.AbstractKotlinApplicableIntention import org.jetbrains.kotlin.idea.codeinsight.api.applicators.KotlinApplicabilityRange import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges import org.jetbrains.kotlin.idea.codeinsights.impl.base.intentions.convertConcatenationToBuildStringCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression internal class ConvertConcatenationToBuildStringIntention : AbstractKotlinApplicableIntention<KtBinaryExpression>(KtBinaryExpression::class) { override fun getFamilyName(): String = KotlinBundle.message("convert.concatenation.to.build.string") override fun getActionName(element: KtBinaryExpression): String = familyName override fun getApplicabilityRange(): KotlinApplicabilityRange<KtBinaryExpression> = ApplicabilityRanges.SELF override fun isApplicableByPsi(element: KtBinaryExpression): Boolean = element.operationToken == KtTokens.PLUS && !element.isAnnotationArgument() context(KtAnalysisSession) override fun isApplicableByAnalyze(element: KtBinaryExpression): Boolean { val parent = element.parent return element.getKtType()?.isString == true && ( parent !is KtBinaryExpression || parent.operationToken != KtTokens.PLUS || parent.getKtType()?.isString == false) } override fun apply(element: KtBinaryExpression, project: Project, editor: Editor?) { val buildStringCall = convertConcatenationToBuildStringCall(element) shortenReferences(buildStringCall) } }
apache-2.0
95ddfcf4071d7df6fc4ede7dd81a7c92
55.384615
142
0.798453
5.087963
false
false
false
false
exercism/xkotlin
exercises/practice/bank-account/.meta/src/reference/kotlin/BankAccount.kt
2
526
class BankAccount { var balance: Long = 0 get() { synchronized(lock) { if (!isOpen) throw IllegalStateException("Account is closed") return field } } private set var isOpen = true private set fun adjustBalance(amount: Long) { synchronized(lock) { balance += amount } } fun close() { synchronized(lock) { isOpen = false } } private val lock = Any() }
mit
4020550a7aa573acab2801e29d17302d
18.481481
77
0.475285
5.057692
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/channels/BroadcastChannelLeakTest.kt
1
1123
package kotlinx.coroutines.channels import kotlinx.coroutines.* import org.junit.Test import kotlin.test.* class BroadcastChannelLeakTest : TestBase() { @Test fun testArrayBroadcastChannelSubscriptionLeak() { checkLeak { ArrayBroadcastChannel(1) } } @Test fun testConflatedBroadcastChannelSubscriptionLeak() { checkLeak { ConflatedBroadcastChannel() } } enum class TestKind { BROADCAST_CLOSE, SUB_CANCEL, BOTH } private fun checkLeak(factory: () -> BroadcastChannel<String>) = runTest { for (kind in TestKind.values()) { val broadcast = factory() val sub = broadcast.openSubscription() broadcast.send("OK") assertEquals("OK", sub.receive()) // now close broadcast if (kind != TestKind.SUB_CANCEL) broadcast.close() // and then cancel subscription if (kind != TestKind.BROADCAST_CLOSE) sub.cancel() // subscription should not be reachable from the channel anymore FieldWalker.assertReachableCount(0, broadcast) { it === sub } } } }
apache-2.0
e2ce43d267cec624c63e702415751dfb
32.058824
78
0.638468
4.738397
false
true
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiSignal.kt
1
2778
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.vrem.wifianalyzer.wifi.model import com.vrem.wifianalyzer.wifi.band.WiFiBand import com.vrem.wifianalyzer.wifi.band.WiFiChannel data class WiFiSignal( val primaryFrequency: Int = 0, val centerFrequency: Int = 0, val wiFiWidth: WiFiWidth = WiFiWidth.MHZ_20, val level: Int = 0, val is80211mc: Boolean = false, val wiFiStandard: WiFiStandard = WiFiStandard.UNKNOWN, val timestamp: Long = 0 ) { val wiFiBand: WiFiBand = WiFiBand.find(primaryFrequency) val frequencyStart: Int get() = centerFrequency - wiFiWidth.frequencyWidthHalf val frequencyEnd: Int get() = centerFrequency + wiFiWidth.frequencyWidthHalf val primaryWiFiChannel: WiFiChannel get() = wiFiBand.wiFiChannels.wiFiChannelByFrequency(primaryFrequency) val centerWiFiChannel: WiFiChannel get() = wiFiBand.wiFiChannels.wiFiChannelByFrequency(centerFrequency) val strength: Strength get() = Strength.calculate(level) val distance: String get() = String.format("~%.1fm", calculateDistance(primaryFrequency, level)) fun inRange(frequency: Int): Boolean = frequency in frequencyStart..frequencyEnd fun channelDisplay(): String { val primaryChannel: Int = primaryWiFiChannel.channel val centerChannel: Int = centerWiFiChannel.channel val channel: String = primaryChannel.toString() return if (primaryChannel != centerChannel) "$channel($centerChannel)" else channel } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WiFiSignal if (primaryFrequency != other.primaryFrequency) return false if (wiFiWidth != other.wiFiWidth) return false return true } override fun hashCode(): Int = 31 * primaryFrequency + wiFiWidth.hashCode() companion object { const val FREQUENCY_UNITS = "MHz" val EMPTY = WiFiSignal() } }
gpl-3.0
e43d33005276ea23197a058f7ecaa65a
33.7375
91
0.706263
4.381703
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/main/MainViewModel.kt
1
20949
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.view.main import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.benoitletondor.easybudgetapp.iab.Iab import com.benoitletondor.easybudgetapp.model.Expense import com.benoitletondor.easybudgetapp.model.RecurringExpense import com.benoitletondor.easybudgetapp.model.RecurringExpenseDeleteType import com.benoitletondor.easybudgetapp.db.DB import com.benoitletondor.easybudgetapp.helper.Logger import com.benoitletondor.easybudgetapp.helper.MutableLiveFlow import com.benoitletondor.easybudgetapp.parameters.Parameters import com.benoitletondor.easybudgetapp.parameters.getShouldShowCheckedBalance import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.lang.Exception import java.time.LocalDate import java.util.* import javax.inject.Inject @HiltViewModel class MainViewModel @Inject constructor( private val db: DB, private val iab: Iab, private val parameters: Parameters, ) : ViewModel() { private val selectDateMutableStateFlow = MutableStateFlow(LocalDate.now()) private val premiumStatusMutableStateFlow = MutableStateFlow(iab.isUserPremium()) val premiumStatusFlow: StateFlow<Boolean> = premiumStatusMutableStateFlow private val expenseDeletionSuccessEventMutableFlow = MutableLiveFlow<ExpenseDeletionSuccessData>() val expenseDeletionSuccessEventFlow: Flow<ExpenseDeletionSuccessData> = expenseDeletionSuccessEventMutableFlow private val expenseDeletionErrorEventMutableFlow = MutableLiveFlow<Expense>() val expenseDeletionErrorEventFlow: Flow<Expense> = expenseDeletionErrorEventMutableFlow private val recurringExpenseDeletionProgressStateMutableFlow = MutableStateFlow<RecurringExpenseDeleteProgressState>(RecurringExpenseDeleteProgressState.Idle) val recurringExpenseDeletionProgressStateFlow: Flow<RecurringExpenseDeleteProgressState> = recurringExpenseDeletionProgressStateMutableFlow private val recurringExpenseDeletionEventMutableFlow = MutableLiveFlow<RecurringExpenseDeletionEvent>() val recurringExpenseDeletionEventFlow: Flow<RecurringExpenseDeletionEvent> = recurringExpenseDeletionEventMutableFlow private val recurringExpenseRestoreProgressStateMutableFlow = MutableStateFlow<RecurringExpenseRestoreProgressState>(RecurringExpenseRestoreProgressState.Idle) val recurringExpenseRestoreProgressStateFlow: Flow<RecurringExpenseRestoreProgressState> = recurringExpenseRestoreProgressStateMutableFlow private val recurringExpenseRestoreEventMutableFlow = MutableLiveFlow<RecurringExpenseRestoreEvent>() val recurringExpenseRestoreEventFlow: Flow<RecurringExpenseRestoreEvent> = recurringExpenseRestoreEventMutableFlow private val startCurrentBalanceEditorEventMutableFlow = MutableLiveFlow<Double>() val startCurrentBalanceEditorEventFlow: Flow<Double> = startCurrentBalanceEditorEventMutableFlow private val showGoToCurrentMonthButtonStateMutableFlow = MutableStateFlow(false) val showGoToCurrentMonthButtonStateFlow: StateFlow<Boolean> = showGoToCurrentMonthButtonStateMutableFlow private val currentBalanceEditingErrorEventMutableFlow = MutableLiveFlow<Exception>() val currentBalanceEditingErrorEventFlow: Flow<Exception> = currentBalanceEditingErrorEventMutableFlow private val currentBalanceEditedEventMutableFlow = MutableLiveFlow<BalanceAdjustedData>() val currentBalanceEditedEventFlow: Flow<BalanceAdjustedData> = currentBalanceEditedEventMutableFlow private val currentBalanceRestoringErrorEventMutableFlow = MutableLiveFlow<Exception>() val currentBalanceRestoringErrorEventFlow: Flow<Exception> = currentBalanceRestoringErrorEventMutableFlow private val expenseCheckedErrorEventMutableFlow = MutableLiveFlow<Exception>() val expenseCheckedErrorEventFlow: Flow<Exception> = expenseCheckedErrorEventMutableFlow private val goBackToCurrentMonthEventMutableFlow = MutableLiveFlow<Unit>() val goBackToCurrentMonthEventFlow: Flow<Unit> = goBackToCurrentMonthEventMutableFlow private val confirmCheckAllPastEntriesEventMutableFlow = MutableLiveFlow<Unit>() val confirmCheckAllPastEntriesEventFlow: Flow<Unit> = confirmCheckAllPastEntriesEventMutableFlow private val checkAllPastEntriesErrorEventMutableFlow = MutableLiveFlow<Throwable>() val checkAllPastEntriesErrorEventFlow: Flow<Throwable> = checkAllPastEntriesErrorEventMutableFlow private val forceRefreshMutableFlow = MutableSharedFlow<Unit>() val refreshDatesFlow: Flow<Unit> = forceRefreshMutableFlow val selectedDateDataFlow = combine( selectDateMutableStateFlow, forceRefreshMutableFlow, ) { date, _ -> val (balance, expenses, checkedBalance) = withContext(Dispatchers.Default) { Triple( getBalanceForDay(date), db.getExpensesForDay(date), if (parameters.getShouldShowCheckedBalance()) { getCheckedBalanceForDay(date) } else { null }, ) } SelectedDateExpensesData(date, balance, checkedBalance, expenses) }.stateIn(viewModelScope, SharingStarted.Eagerly, SelectedDateExpensesData(selectDateMutableStateFlow.value, 0.0, null, emptyList())) init { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } sealed class RecurringExpenseDeleteProgressState { object Idle : RecurringExpenseDeleteProgressState() class Deleting(val expense: Expense): RecurringExpenseDeleteProgressState() } sealed class RecurringExpenseDeletionEvent { class ErrorRecurringExpenseDeleteNotAssociated(val expense: Expense): RecurringExpenseDeletionEvent() class ErrorCantDeleteBeforeFirstOccurrence(val expense: Expense): RecurringExpenseDeletionEvent() class ErrorIO(val expense: Expense): RecurringExpenseDeletionEvent() class Success(val recurringExpense: RecurringExpense, val restoreRecurring: Boolean, val expensesToRestore: List<Expense>): RecurringExpenseDeletionEvent() } sealed class RecurringExpenseRestoreProgressState { object Idle : RecurringExpenseRestoreProgressState() class Restoring(val recurringExpense: RecurringExpense): RecurringExpenseRestoreProgressState() } sealed class RecurringExpenseRestoreEvent { class ErrorIO(val recurringExpense: RecurringExpense): RecurringExpenseRestoreEvent() class Success(val recurringExpense: RecurringExpense): RecurringExpenseRestoreEvent() } fun onDeleteExpenseClicked(expense: Expense) { viewModelScope.launch { try { withContext(Dispatchers.Default) { db.deleteExpense(expense) } val selectedDate = selectDateMutableStateFlow.value expenseDeletionSuccessEventMutableFlow.emit(ExpenseDeletionSuccessData( expense, getBalanceForDay(selectedDate), if (parameters.getShouldShowCheckedBalance()) { db.getCheckedBalanceForDay(selectedDate) } else { null }, )) forceRefreshMutableFlow.emit(Unit) } catch (t: Throwable) { Logger.error("Error while deleting expense", t) expenseDeletionErrorEventMutableFlow.emit(expense) } } } fun onExpenseDeletionCancelled(expense: Expense) { viewModelScope.launch { try { withContext(Dispatchers.Default) { db.persistExpense(expense) } forceRefreshMutableFlow.emit(Unit) } catch (t: Throwable) { Logger.error("Error while restoring expense", t) } } } fun onDeleteRecurringExpenseClicked(expense: Expense, deleteType: RecurringExpenseDeleteType) { viewModelScope.launch { recurringExpenseDeletionProgressStateMutableFlow.value = RecurringExpenseDeleteProgressState.Deleting(expense) try { val associatedRecurringExpense = expense.associatedRecurringExpense if( associatedRecurringExpense == null ) { recurringExpenseDeletionEventMutableFlow.emit(RecurringExpenseDeletionEvent.ErrorRecurringExpenseDeleteNotAssociated(expense)) return@launch } val firstOccurrenceError = withContext(Dispatchers.Default) { deleteType == RecurringExpenseDeleteType.TO && !db.hasExpensesForRecurringExpenseBeforeDate(associatedRecurringExpense, expense.date) } if ( firstOccurrenceError ) { recurringExpenseDeletionEventMutableFlow.emit(RecurringExpenseDeletionEvent.ErrorCantDeleteBeforeFirstOccurrence(expense)) return@launch } val expensesToRestore: List<Expense>? = withContext(Dispatchers.Default) { when (deleteType) { RecurringExpenseDeleteType.ALL -> { val expensesToRestore = db.getAllExpenseForRecurringExpense(associatedRecurringExpense) try { db.deleteAllExpenseForRecurringExpense(associatedRecurringExpense) } catch (t: Throwable) { return@withContext null } try { db.deleteRecurringExpense(associatedRecurringExpense) } catch (t: Throwable) { return@withContext null } expensesToRestore } RecurringExpenseDeleteType.FROM -> { val expensesToRestore = db.getAllExpensesForRecurringExpenseAfterDate(associatedRecurringExpense, expense.date) try { db.deleteAllExpenseForRecurringExpenseAfterDate(associatedRecurringExpense, expense.date) } catch (t: Throwable) { return@withContext null } expensesToRestore } RecurringExpenseDeleteType.TO -> { val expensesToRestore = db.getAllExpensesForRecurringExpenseBeforeDate(associatedRecurringExpense, expense.date) try { db.deleteAllExpenseForRecurringExpenseBeforeDate(associatedRecurringExpense, expense.date) } catch (t: Throwable) { return@withContext null } expensesToRestore } RecurringExpenseDeleteType.ONE -> { val expensesToRestore = listOf(expense) try { db.deleteExpense(expense) } catch (t: Throwable) { return@withContext null } expensesToRestore } } } if( expensesToRestore == null ) { recurringExpenseDeletionEventMutableFlow.emit(RecurringExpenseDeletionEvent.ErrorIO(expense)) return@launch } recurringExpenseDeletionEventMutableFlow.emit(RecurringExpenseDeletionEvent.Success(associatedRecurringExpense, deleteType == RecurringExpenseDeleteType.ALL, expensesToRestore)) } finally { recurringExpenseDeletionProgressStateMutableFlow.value = RecurringExpenseDeleteProgressState.Idle } forceRefreshMutableFlow.emit(Unit) } } fun onRestoreRecurringExpenseClicked(recurringExpense: RecurringExpense, restoreRecurring: Boolean, expensesToRestore: List<Expense>) { viewModelScope.launch { recurringExpenseRestoreProgressStateMutableFlow.value = RecurringExpenseRestoreProgressState.Restoring(recurringExpense) try { if( restoreRecurring ) { try { withContext(Dispatchers.Default) { db.persistRecurringExpense(recurringExpense) } } catch (t: Throwable) { recurringExpenseRestoreEventMutableFlow.emit(RecurringExpenseRestoreEvent.ErrorIO(recurringExpense)) return@launch } } val expensesAdd = withContext(Dispatchers.Default) { for (expense in expensesToRestore) { try { db.persistExpense(expense) } catch (t: Throwable) { return@withContext false } } return@withContext true } if( !expensesAdd ) { recurringExpenseRestoreEventMutableFlow.emit(RecurringExpenseRestoreEvent.ErrorIO(recurringExpense)) return@launch } recurringExpenseRestoreEventMutableFlow.emit(RecurringExpenseRestoreEvent.Success(recurringExpense)) } finally { recurringExpenseRestoreProgressStateMutableFlow.value = RecurringExpenseRestoreProgressState.Idle } forceRefreshMutableFlow.emit(Unit) } } fun onAdjustCurrentBalanceClicked() { viewModelScope.launch { val balance = withContext(Dispatchers.Default) { -db.getBalanceForDay(LocalDate.now()) } startCurrentBalanceEditorEventMutableFlow.emit(balance) } } fun onNewBalanceSelected(newBalance: Double, balanceExpenseTitle: String) { viewModelScope.launch { try { val currentBalance = withContext(Dispatchers.Default) { -db.getBalanceForDay(LocalDate.now()) } if (newBalance == currentBalance) { // Nothing to do, balance hasn't change return@launch } val diff = newBalance - currentBalance // Look for an existing balance for the day val existingExpense = withContext(Dispatchers.Default) { db.getExpensesForDay(LocalDate.now()).find { it.title == balanceExpenseTitle } } if (existingExpense != null) { // If the adjust balance exists, just add the diff and persist it val newExpense = withContext(Dispatchers.Default) { db.persistExpense(existingExpense.copy(amount = existingExpense.amount - diff)) } currentBalanceEditedEventMutableFlow.emit(BalanceAdjustedData(newExpense, diff, newBalance)) } else { // If no adjust balance yet, create a new one val persistedExpense = withContext(Dispatchers.Default) { db.persistExpense(Expense(balanceExpenseTitle, -diff, LocalDate.now(), true)) } currentBalanceEditedEventMutableFlow.emit(BalanceAdjustedData(persistedExpense, diff, newBalance)) } forceRefreshMutableFlow.emit(Unit) } catch (e: Exception) { Logger.error("Error while editing balance", e) currentBalanceEditingErrorEventMutableFlow.emit(e) } } } fun onCurrentBalanceEditedCancelled(expense: Expense, diff: Double) { viewModelScope.launch { try { withContext(Dispatchers.Default) { if( expense.amount + diff == 0.0 ) { db.deleteExpense(expense) } else { val newExpense = expense.copy(amount = expense.amount + diff) db.persistExpense(newExpense) } } forceRefreshMutableFlow.emit(Unit) } catch (e: Exception) { Logger.error("Error while restoring balance", e) currentBalanceRestoringErrorEventMutableFlow.emit(e) } } } fun onIabStatusChanged() { premiumStatusMutableStateFlow.value = iab.isUserPremium() viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } fun onSelectDate(date: LocalDate) { selectDateMutableStateFlow.value = date } fun onCurrencySelected() { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } private suspend fun getBalanceForDay(date: LocalDate): Double { var balance = 0.0 // Just to keep a positive number if balance == 0 balance -= db.getBalanceForDay(date) return balance } private suspend fun getCheckedBalanceForDay(date: LocalDate): Double { var balance = 0.0 // Just to keep a positive number if balance == 0 balance -= db.getCheckedBalanceForDay(date) return balance } fun onDayChanged() { selectDateMutableStateFlow.value = LocalDate.now() } fun onExpenseAdded() { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } fun onWelcomeScreenFinished() { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } fun onExpenseChecked(expense: Expense, checked: Boolean) { viewModelScope.launch { try { withContext(Dispatchers.Default) { db.persistExpense(expense.copy(checked = checked)) } forceRefreshMutableFlow.emit(Unit) } catch (e: Exception) { Logger.error("Error while checking expense", e) expenseCheckedErrorEventMutableFlow.emit(e) } } } fun onMonthChanged(month: Int, year: Int) { val cal = Calendar.getInstance() showGoToCurrentMonthButtonStateMutableFlow.value = cal.get(Calendar.MONTH) != month || cal.get(Calendar.YEAR) != year } fun onGoBackToCurrentMonthButtonPressed() { viewModelScope.launch { goBackToCurrentMonthEventMutableFlow.emit(Unit) selectDateMutableStateFlow.value = LocalDate.now() } } fun onShowCheckedBalanceChanged() { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } fun onCheckAllPastEntriesPressed() { viewModelScope.launch { confirmCheckAllPastEntriesEventMutableFlow.emit(Unit) } } fun onCheckAllPastEntriesConfirmPressed() { viewModelScope.launch { try { withContext(Dispatchers.Default) { db.markAllEntriesAsChecked(LocalDate.now()) } forceRefreshMutableFlow.emit(Unit) } catch (e: Exception) { Logger.error("Error while checking all past entries", e) checkAllPastEntriesErrorEventMutableFlow.emit(e) } } } fun onLowMoneyWarningThresholdChanged() { viewModelScope.launch { forceRefreshMutableFlow.emit(Unit) } } } data class SelectedDateExpensesData(val date: LocalDate, val balance: Double, val checkedBalance: Double?, val expenses: List<Expense>) data class ExpenseDeletionSuccessData(val deletedExpense: Expense, val newDayBalance: Double, val newCheckedBalance: Double?) data class BalanceAdjustedData(val balanceExpense: Expense, val diffWithOldBalance: Double, val newBalance: Double)
apache-2.0
47593e683d47dbf04d711695f7cb7814
41.323232
193
0.64447
6.019828
false
false
false
false
romannurik/muzei
main/src/main/java/com/google/android/apps/muzei/quicksettings/NextArtworkTileService.kt
1
6479
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.muzei.quicksettings import android.app.WallpaperManager import android.content.ActivityNotFoundException import android.content.ComponentName import android.content.Intent import android.graphics.drawable.Icon import android.os.Build import android.service.quicksettings.Tile import android.service.quicksettings.TileService import android.widget.Toast import androidx.annotation.RequiresApi import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.lifecycle.lifecycleScope import com.google.android.apps.muzei.MuzeiWallpaperService import com.google.android.apps.muzei.legacy.LegacySourceManager import com.google.android.apps.muzei.legacy.allowsNextArtwork import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.room.Provider import com.google.android.apps.muzei.util.collectIn import com.google.android.apps.muzei.util.toast import com.google.android.apps.muzei.wallpaper.WallpaperActiveState import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import net.nurik.roman.muzei.R /** * Quick Settings Tile which allows users quick access to the 'Next Artwork' command, if supported. * In cases where Muzei is not activated, the tile also allows users to activate Muzei directly * from the tile */ @RequiresApi(Build.VERSION_CODES.N) class NextArtworkTileService : TileService(), LifecycleOwner { private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this) private var currentProvider: Provider? = null override fun onCreate() { super.onCreate() lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE) WallpaperActiveState.collectIn(this) { updateTile() } // Start listening for source changes, which will include when a source // starts or stops supporting the 'Next Artwork' command val database = MuzeiDatabase.getInstance(this) database.providerDao().currentProvider.collectIn(this) { provider -> currentProvider = provider updateTile() } } override fun getLifecycle(): Lifecycle { return lifecycleRegistry } override fun onTileAdded() { Firebase.analytics.logEvent("tile_next_artwork_added", null) } override fun onStartListening() { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) } private suspend fun updateTile() { val context = this qsTile?.takeIf { !WallpaperActiveState.value || currentProvider != null }?.apply { when { !WallpaperActiveState.value -> { // If the wallpaper isn't active, the quick tile will activate it state = Tile.STATE_INACTIVE label = getString(R.string.action_activate) icon = Icon.createWithResource(context, R.drawable.ic_stat_muzei) } currentProvider.allowsNextArtwork(context) -> { state = Tile.STATE_ACTIVE label = getString(R.string.action_next_artwork) icon = Icon.createWithResource(context, R.drawable.ic_notif_next_artwork) } else -> { state = Tile.STATE_UNAVAILABLE label = getString(R.string.action_next_artwork) icon = Icon.createWithResource(context, R.drawable.ic_notif_next_artwork) } } }?.updateTile() } override fun onClick() { val context = this qsTile?.run { when (state) { Tile.STATE_ACTIVE -> { // Active means we send the 'Next Artwork' command lifecycleScope.launch(NonCancellable) { Firebase.analytics.logEvent("next_artwork") { param(FirebaseAnalytics.Param.CONTENT_TYPE, "tile") } LegacySourceManager.getInstance(context).nextArtwork() } } else -> unlockAndRun { // Inactive means we attempt to activate Muzei Firebase.analytics.logEvent("tile_next_artwork_activate", null) try { startActivityAndCollapse(Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER) .putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, ComponentName(context, MuzeiWallpaperService::class.java)) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (_: ActivityNotFoundException) { try { startActivityAndCollapse(Intent(WallpaperManager.ACTION_LIVE_WALLPAPER_CHOOSER) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } catch (e: ActivityNotFoundException) { context.toast(R.string.error_wallpaper_chooser, Toast.LENGTH_LONG) } } } } } } override fun onStopListening() { lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP) } override fun onTileRemoved() { Firebase.analytics.logEvent("tile_next_artwork_removed", null) } override fun onDestroy() { super.onDestroy() lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) } }
apache-2.0
5a99456adf8e6b0d4ae288a4f10d162f
40.273885
107
0.644235
5.085557
false
false
false
false
leafclick/intellij-community
java/java-tests/testSrc/com/intellij/internal/SharedIndexMetadataTest.kt
1
4536
// 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 com.intellij.internal import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import com.intellij.internal.SharedIndexMetadata.writeIndexMetadata import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.indexing.IndexInfrastructureVersion import com.intellij.util.indexing.IndexInfrastructureVersion.getIdeVersion import org.junit.Assert import org.junit.Test class SharedIndexMetadataTest : BasePlatformTestCase() { @Test fun testAliasesAreIncluded() { val selfVersion = getIdeVersion() val data = writeIndexMetadata("mock1", "jdk", "123", selfVersion, aliases = setOf("jonnyzzz", "intellij", "jdk")) val om = ObjectMapper() val root = om.readTree(data) as ObjectNode val aliases = root["sources"]["aliases"] as ArrayNode val texts = aliases.elements().asSequence().map { it.asText() }.toSet() Assert.assertEquals(setOf("jonnyzzz", "intellij", "jdk"), texts) } @Test fun testSourcesAreIncluded() { val selfVersion = getIdeVersion() val data = writeIndexMetadata("mock1", "jdk2", "123", selfVersion) val om = ObjectMapper() val root = om.readTree(data) as ObjectNode val hash = root["sources"]["hash"].asText() val kind = root["sources"]["kind"].asText() Assert.assertEquals("123", hash) Assert.assertEquals("jdk2", kind) } @Test fun testSelfVersionShouldMatch() = doMatchTest(true) { this } @Test fun testSelfVersionWithExtraKeyShouldNotMatch() = doMatchTest(false) { this.copy(addToBase = mapOf("jonnyzzz" to "42")) } @Test fun testSelfVersionWithMissingKeyShouldNotMatch() = doMatchTest(false) {this.copy(removeFromBase = setOf(baseIndexes.keys.first())) } @Test fun testEmptyIndexersVersionShouldNotMatch() = doMatchTest(false) { this.copy(file = emptyMap(), stub = emptyMap()) } @Test fun testNoBaseIndexesShouldNotMatch() = doMatchTest(false) { this.copy(base = emptyMap()) } @Test fun testNoFileIndexesShouldNotMatch() = doMatchTest(false) { this.copy(file = emptyMap()) } @Test fun testExtraFileIndexesShouldMatch() = doMatchTest(true) { this.copy(addToFile = mapOf("jonnyzzz" to "42")) } @Test fun testMissingFileIndexesShouldMatch() = doMatchTest(true) { this.copy(removeFromFile = setOf(fileBasedIndexVersions.keys.first())) } @Test fun testNoStubIndexesShouldNotMatch() = doMatchTest(false) { this.copy(stub = emptyMap()) } @Test fun testExtraStubIndexShouldNotMatch() = doMatchTest(true) { this.copy(addToStub = mapOf("jonnyzzz" to "42")) } @Test fun testMissingStubIndexShouldNotMatch() = doMatchTest(true) { this.copy(removeFromStub = setOf(stubIndexVersions.keys.first())) } @Test fun testSelfSerializationIsStable() { val (a,b) = List(2) { val selfVersion = getIdeVersion() writeIndexMetadata("mock1", "jdk", "123", selfVersion) } Assert.assertArrayEquals(a, b) } private fun doMatchTest(shouldBeEqual: Boolean, tuneSelfVersion: IndexInfrastructureVersion.() -> IndexInfrastructureVersion) { val version = getIdeVersion() Assert.assertEquals(version, version.copy()) val json = writeIndexMetadata("mock1", "jdk", "123", version.copy().tuneSelfVersion()) val om = ObjectMapper() val selfVersion = version.copy() val info1 = SharedIndexInfo("http://mock", "123", om.readTree(json) as ObjectNode) if (shouldBeEqual) { Assert.assertEquals(info1, SharedIndexMetadata.selectBestSuitableIndex(selfVersion, listOf(info1))?.first) } else { Assert.assertNotEquals(info1, SharedIndexMetadata.selectBestSuitableIndex(selfVersion, listOf(info1))?.first) } } private fun IndexInfrastructureVersion.copy( removeFromBase: Set<String> = emptySet(), addToBase: Map<String, String> = emptyMap(), base: Map<String, String> = this.baseIndexes - removeFromBase + addToBase, removeFromFile: Set<String> = emptySet(), addToFile: Map<String, String> = emptyMap(), file: Map<String, String> = this.fileBasedIndexVersions - removeFromFile + addToFile, removeFromStub: Set<String> = emptySet(), addToStub: Map<String, String> = emptyMap(), stub: Map<String, String> = this.stubIndexVersions - removeFromStub + addToStub ) = IndexInfrastructureVersion(base, file, stub) }
apache-2.0
b8fafbd5bb86df0b7d0094044930ec1a
37.440678
140
0.724427
4.05
false
true
false
false
stefanosiano/PowerfulImageView
powerfulimageview_rs/src/main/java/com/stefanosiano/powerful_libraries/imageview/progress/ProgressOptions.kt
2
26670
package com.stefanosiano.powerful_libraries.imageview.progress import android.graphics.RectF import java.lang.ref.WeakReference import kotlin.math.roundToInt /** Class that helps managing the options that will be used by the progress drawers. */ class ProgressOptions() { // Options used directly by drawers /** If the (determinate or horizontal_determinate) drawer should update its progress with an animation. */ var determinateAnimationEnabled: Boolean = false set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** * Width of the progress indicator. If it's lower than 0, it is ignored. * To use dp, use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, borderWidth, resources.displayMetrics). * If you want the real progress border width, check [calculatedBorderWidth]. */ var borderWidth: Int = 0 set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** Progress animation duration (in milliseconds). */ var animationDuration: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** * Width of the progress indicator as percentage of the progress indicator size. * If you want the real progress border width, check [calculatedBorderWidth]. */ var borderWidthPercent: Float = 0f /** Percentage value of the progress indicator, used by determinate drawers. */ var valuePercent: Float = 0f /** * Front color of the progress indicator, used by determinate drawers. * If the drawer is not determinate or horizontal_determinate it's ignored. * * Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not * pre-multiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. * See the Color class for more details. */ var frontColor: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** * Back color of the progress indicator, used by determinate drawers. * If the drawer is not determinate or horizontal_determinate it's ignored. * * Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not * pre-multiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. * See the Color class for more details. */ var backColor: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** * Color of the progress indicator, used by indeterminate drawers. * If the drawer is not indeterminate or horizontal_indeterminate it's ignored. * * Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not * pre-multiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. * See the Color class for more details. */ var indeterminateColor: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** If should show a wedge, used by circular determinate drawer. If the drawer is not determinate it's ignored. */ var drawWedge: Boolean = false set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** If should show a shadow. */ var shadowEnabled: Boolean = false set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** * Shadow color of the progress indicator. * Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not * pre-multiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. * See the Color class for more details. */ var shadowColor: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } /** * Padding of the progress indicator relative to its shadow. If it's lower than 0, it is ignored. * If you want the real shadow padding, check [calculatedShadowPadding]. */ var shadowPadding: Int = 0 set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** * Padding of the progress indicator relative to its shadow, as a percentage of the whole shadow. * If you want the real shadow padding, check [calculatedShadowPadding]. */ var shadowPaddingPercent: Float = 0f /** * Width of the progress indicator shadow border. * To use dp, use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, borderWidth, resources.displayMetrics) * If you want the real shadow border width, check [calculatedShadowBorderWidth]. */ var shadowBorderWidth: Float = 0f set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** Width of the progress indicator shadow border after calculations. */ var calculatedShadowBorderWidth: Float = 0f /** * Color of the progress indicator shadow border. * Note that the color is an int containing alpha as well as r,g,b. This 32bit value is not * pre-multiplied, meaning that its alpha can be any value, regardless of the values of r,g,b. * See the Color class for more details. */ var shadowBorderColor: Int = 0 set(value) { field = value if (isInitialized) { listener.get()?.onOptionsUpdated(this) } } // Variables used to calculate bounds /** Size of the progress indicator. If you want the real progress indicator size, check [calculatedSize]. */ var mSize: Int = 0 /** * Padding of the progress indicator. * To use dp, use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, borderWidth, resources.displayMetrics). */ var padding: Int = 0 set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** Size of the progress indicator, as a percentage of the whole View. * If you want the real progress indicator size, check [calculatedSize]. */ var sizePercent: Float = 0f /** Gravity of the progress indicator. It will follow the right to left layout (on api 17+), if not disabled. */ var gravity: PivProgressGravity? = null set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** Whether the view should use right to left layout (used for gravity option). */ var isProgressReversed: Boolean = false set(value) { field = value listener.get()?.onOptionsUpdated(this) } get() = (isRtl && !isRtlDisabled) != field /** Whether the progress should be reset on drawable change. */ var isRemovedOnChange: Boolean = false /** Whether the view is using right to left layout (used for gravity option and progress direction). */ var isRtl: Boolean = false /** Whether the view should use or ignore right to left layout (used for gravity option and progress direction). */ var isRtlDisabled: Boolean = false set(value) { field = value if (isInitialized) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } } /** Whether the progress indicator is indeterminate or not. */ var isIndeterminate: Boolean = false private set // ************** Calculated fields ***************** /** Calculated size of the indicator, base on mSize, sizePercent and View size. It's the real value used by the * progress indicator. */ var calculatedSize: Float = 0f /** Calculated padding of the indicator shadow. It's the real value used by the progress indicator. */ var calculatedShadowPadding: Int = 0 /** Border width of the progress indicator, after calculations. It's the real value used by the progress * indicator. */ var calculatedBorderWidth: Int = 0 // Bounds of the progress and shadow indicator /** Progress bounds calculated after [calculateSizeAndBounds]. DON'T change directly its values! */ var rect = RectF(0f, 0f, 0f, 0f) /** Shadow bounds calculated after [calculateSizeAndBounds]. DON'T change directly its values! */ var shadowRect = RectF(0f, 0f, 0f, 0f) /** Shadow border bounds calculated after [calculateSizeAndBounds]. DON'T change directly its values! */ var shadowBorderRect = RectF(0f, 0f, 0f, 0f) // Last calculated width and height /** Last width calculated. Used when changing programmatically the options, so bounds can be recalculated. */ private var mCalculatedLastW: Int = 0 /** Last height calculated. Used when changing programmatically the options, so bounds can be recalculated. */ private var mCalculatedLastH: Int = 0 /** Last progress mode used. Used when changing programmatically the options, so bounds can be recalculated. */ private var mCalculatedLastMode = PivProgressMode.NONE /** Listener that will update the progress drawers on changes, with a weak reference to not leak memory. */ private var listener = WeakReference<ProgressOptionsListener>(null) /** Flag to check if the object's constructor was called. */ private var isInitialized = false /** * Creates the object that will be used by progress drawers. * * [determinateAnimationEnabled] If the determinate drawer should update its progress with an animation * [animationDuration] Progress animation duration (in milliseconds) * [borderWidth] Width of the progress indicator. If it's 0 or more, it applies and overrides [borderWidthPercent] * [borderWidthPercent] Width of the progress indicator as a percentage of the progress indicator size * [size] Size of the progress indicator. If it's 0 or more, it applies and overrides [sizePercent] * [sizePercent] Size of the progress indicator as a percentage of the whole View * [padding] Padding of the progress indicator * [valuePercent] Percentage value of the progress indicator, used by determinate drawers * [frontColor] Front color of the indicator, used by determinate drawers * [backColor] Back color of the indicator, used by determinate drawers * [indeterminateColor] Color of the indicator, used by indeterminate drawers * [gravity] Gravity of the indicator * [rtl] Whether the view should use right to left layout (used for gravity option) * [disableRtlSupport] If true, rtl attribute will be ignored (start will always be treated as left) * [isIndeterminate] If true, indeterminate progress is drawn * [drawWedge] If should show a wedge, used by circular determinate drawer * [shadowEnabled] If should show a shadow under progress indicator * [shadowColor] Color of the shadow * [shadowPadding] Padding of the progress indicator, relative to its shadow. * If it's 0 or more, it applies and overrides [shadowPaddingPercent] * [shadowPaddingPercent] Padding of the progress indicator, relative to its shadow, as a percentage of the shadow * [shadowBorderWidth] Width of the progress indicator shadow border * [shadowBorderColor] Color of the progress indicator shadow border * [isProgressReversed] Whether the progress should be reversed * [isRemovedOnChange] Whether the progress should be reset on drawable change */ @Suppress("LongParameterList") constructor( determinateAnimationEnabled: Boolean, animationDuration: Int, borderWidth: Int, borderWidthPercent: Float, size: Int, sizePercent: Float, padding: Int, valuePercent: Float, frontColor: Int, backColor: Int, indeterminateColor: Int, gravity: Int, rtl: Boolean, disableRtlSupport: Boolean, isIndeterminate: Boolean, drawWedge: Boolean, shadowEnabled: Boolean, shadowColor: Int, shadowPadding: Int, shadowPaddingPercent: Float, shadowBorderWidth: Float, shadowBorderColor: Int, isProgressReversed: Boolean, isRemovedOnChange: Boolean ) : this() { this.determinateAnimationEnabled = determinateAnimationEnabled this.animationDuration = animationDuration this.borderWidth = borderWidth this.borderWidthPercent = borderWidthPercent if (this.borderWidthPercent > 100) { this.borderWidthPercent = this.borderWidthPercent % 100 } this.mSize = size this.padding = padding this.sizePercent = sizePercent this.valuePercent = valuePercent this.frontColor = frontColor this.backColor = backColor this.indeterminateColor = indeterminateColor this.gravity = PivProgressGravity.fromValue(gravity) this.isRtl = rtl this.isRtlDisabled = disableRtlSupport this.isIndeterminate = isIndeterminate this.drawWedge = drawWedge this.shadowEnabled = shadowEnabled this.shadowColor = shadowColor this.shadowPadding = shadowPadding this.shadowPaddingPercent = shadowPaddingPercent this.shadowBorderWidth = shadowBorderWidth this.shadowBorderColor = shadowBorderColor this.isProgressReversed = isProgressReversed this.isRemovedOnChange = isRemovedOnChange this.isInitialized = true } /** Updates the values of the current options, copying the passed values. */ fun setOptions(other: ProgressOptions) { this.determinateAnimationEnabled = other.determinateAnimationEnabled this.borderWidth = other.borderWidth this.borderWidthPercent = other.borderWidthPercent this.valuePercent = other.valuePercent this.frontColor = other.frontColor this.backColor = other.backColor this.indeterminateColor = other.indeterminateColor this.drawWedge = other.drawWedge this.shadowEnabled = other.shadowEnabled this.shadowColor = other.shadowColor this.shadowPadding = other.shadowPadding this.shadowPaddingPercent = other.shadowPaddingPercent this.shadowBorderWidth = other.shadowBorderWidth this.calculatedShadowBorderWidth = other.calculatedShadowBorderWidth this.shadowBorderColor = other.shadowBorderColor this.mSize = other.mSize this.padding = other.padding this.sizePercent = other.sizePercent this.gravity = other.gravity this.isRtl = other.isRtl this.isRtlDisabled = other.isRtlDisabled this.isIndeterminate = other.isIndeterminate this.calculatedSize = other.calculatedSize this.calculatedShadowPadding = other.calculatedShadowPadding this.calculatedBorderWidth = other.calculatedBorderWidth this.rect.set(other.rect) this.shadowRect.set(shadowRect) this.shadowBorderRect.set(shadowBorderRect) this.mCalculatedLastW = other.mCalculatedLastW this.mCalculatedLastH = other.mCalculatedLastH this.mCalculatedLastMode = other.mCalculatedLastMode this.isProgressReversed = other.isProgressReversed this.listener = other.listener this.isInitialized = true } /** * Forces recalculation of the bounds of the progress indicator, based on progress options and [mode]. * Calculated bounds are accessible after this call through getLeft(), getTop(), getRight() and getBottom() methods. */ internal fun recalculateBounds(mode: PivProgressMode) { calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mode) } /** * Calculates the bounds of the progress indicator, based on [w], [h] and [mode]. * Calculated bounds are accessible after this call through getLeft(), getTop(), getRight() and getBottom() methods. */ internal fun calculateSizeAndBounds(w: Int, h: Int, mode: PivProgressMode) { // Saving last width and height, so i can later call this function from this class mCalculatedLastW = w mCalculatedLastH = h mCalculatedLastMode = mode // If there's no shadow, no border of the shadow should be considered calculatedShadowBorderWidth = if (shadowEnabled) shadowBorderWidth else 0f if (mode == PivProgressMode.NONE) { this.rect.set(0f, 0f, 0f, 0f) this.shadowRect.set(0f, 0f, 0f, 0f) this.shadowBorderRect.set(0f, 0f, 0f, 0f) listener.get()?.onSizeUpdated(this) return } // Calculate the maximum possible size of the progress indicator var maxSize = w.coerceAtMost(h) when (mode) { // Calculation of circular bounds PivProgressMode.CIRCULAR -> maxSize = w.coerceAtMost(h) PivProgressMode.HORIZONTAL -> maxSize = w PivProgressMode.NONE -> mSize = 0 } // ********** SIZE *********** calculatedSize = maxSize * sizePercent / 100 // If mSize is 0 or more, it overrides sizePercent parameter if (mSize >= 0) calculatedSize = mSize.toFloat() // The progress indicator cannot be bigger than the view (minus padding) calculatedSize = calculatedSize.coerceAtMost((maxSize - padding - padding).toFloat()) // ********** SHADOW PADDING *********** calculatedShadowPadding = ((calculatedSize - calculatedShadowBorderWidth * 2) * shadowPaddingPercent / 100).toInt() // If shadowPadding is 0 or more, it overrides shadowPaddingPercent parameter if (shadowPadding >= 0) calculatedShadowPadding = shadowPadding // If shadow is not enabled, shadow padding is set to 0 if (!shadowEnabled) calculatedShadowPadding = 0 // ********** BORDER WIDTH *********** calculatedBorderWidth = ((calculatedSize - calculatedShadowBorderWidth * 2) * borderWidthPercent / 100).roundToInt() // If borderWidth is 0 or more, it overrides borderWidthPercent parameter if (borderWidth >= 0) calculatedBorderWidth = borderWidth // Width of the border should be at least 1 px calculatedBorderWidth = calculatedBorderWidth.coerceAtLeast(1) // ********** BOUNDS *********** calculateBounds(mode, w, h) listener.get()?.onSizeUpdated(this) } @Suppress("UnnecessaryParentheses") private fun calculateBounds(mode: PivProgressMode, w: Int, h: Int) { val considerRtl = isRtl && !isRtlDisabled // Horizontal gravity val left: Float = when { gravity?.isGravityLeft(considerRtl) == true -> padding.toFloat() gravity?.isGravityRight(considerRtl) == true -> w - calculatedSize - padding.toFloat() else -> (w - calculatedSize) / 2 } val top: Float when (mode) { // Calculation of circular bounds PivProgressMode.CIRCULAR -> { // Vertical gravity top = when { gravity?.isGravityTop() == true -> padding.toFloat() gravity?.isGravityBottom() == true -> h.toFloat() - calculatedSize - padding.toFloat() else -> (h - calculatedSize) / 2 } this.shadowBorderRect.set( left + (calculatedShadowBorderWidth / 2), top + (calculatedShadowBorderWidth / 2), left + calculatedSize - calculatedShadowBorderWidth, top + calculatedSize - calculatedShadowBorderWidth ) this.shadowRect.set(shadowBorderRect) this.shadowRect.inset(calculatedShadowBorderWidth / 2, calculatedShadowBorderWidth / 2) this.rect.set(shadowRect) this.rect.inset( (calculatedShadowPadding + calculatedBorderWidth / 2).toFloat(), (calculatedShadowPadding + calculatedBorderWidth / 2).toFloat() ) } // Calculation of horizontal bounds PivProgressMode.HORIZONTAL -> { // Vertical gravity top = when { gravity?.isGravityTop() == true -> padding.toFloat() gravity?.isGravityBottom() == true -> (h - calculatedBorderWidth - padding).toFloat() else -> ((h - calculatedBorderWidth - padding) / 2).toFloat() } this.shadowBorderRect.set( left + (calculatedShadowBorderWidth / 2), top + (calculatedShadowBorderWidth / 2), left + calculatedSize - calculatedShadowBorderWidth, top + calculatedBorderWidth - (calculatedShadowBorderWidth / 2) ) this.shadowRect.set(shadowBorderRect) this.shadowRect.inset(calculatedShadowBorderWidth / 2, calculatedShadowBorderWidth / 2) this.rect.set(shadowRect) this.rect.inset(calculatedShadowPadding.toFloat(), calculatedShadowPadding.toFloat()) } // If everything goes right, it should never come here. Just a precaution PivProgressMode.NONE -> { this.rect.set(0f, 0f, 0f, 0f) this.shadowRect.set(0f, 0f, 0f, 0f) this.shadowBorderRect.set(0f, 0f, 0f, 0f) } } } /** * Set the [borderWidthPercent] of the progress indicator as percentage of the progress indicator size. * It's used only if borderWidth is less than 0. * If the percentage is higher than 100, it is treated as (value % 100). */ fun setBorderWidth(borderWidthPercent: Float) { this.borderWidth = -1 this.borderWidthPercent = if (borderWidthPercent > 100) borderWidthPercent % 100 else borderWidthPercent calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } /** * Set the [valuePercent] of the progress indicator, used by determinate drawers. * If the drawer is indeterminate, it will change its state and make it determinate. * If the percentage is higher than 100, it is treated as (value % 100). * If the percentage is lower than 0, it is treated as 0. * If the drawer is not determinate or horizontal_determinate it's ignored. * Note: multiplies of 100 (e.g. 200, 300, ...) will be treated as 0! */ fun setValue(valuePercent: Float) { this.valuePercent = if (valuePercent > 100) valuePercent % 100 else valuePercent.coerceAtLeast(0F) // If it's indeterminate, I change it to determinate changing the mode, otherwise I just update current drawer val modeChanged = isIndeterminate this.isIndeterminate = false if (modeChanged) { listener.get()?.onModeUpdated(this) } else { listener.get()?.onOptionsUpdated(this) } } /** * Set the [size] of the progress indicator. * * Note that it may be different from the actual size used to draw the progress, since it is * calculated based on the View size and on the padding option. * To use dp, use TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, borderWidth, resources.displayMetrics) */ fun setSize(size: Int) { this.mSize = size calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } /** * Set the [sizePercent] of the progress indicator as a percentage of the whole View. * If the percentage is higher than 100, it is treated as (value % 100). */ fun setSize(sizePercent: Float) { this.mSize = -1 this.sizePercent = if (sizePercent > 100) sizePercent % 100 else sizePercent calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } /** Set whether the view draw and indeterminate progress, based on [isIndeterminate]. */ fun setIsIndeterminate(isIndeterminate: Boolean) { // If it's indeterminate, I change it to determinate, changing the mode, otherwise I just update current drawer val modeChanged = this.isIndeterminate != isIndeterminate this.isIndeterminate = isIndeterminate if (modeChanged) { listener.get()?.onModeUpdated(this) } else { listener.get()?.onOptionsUpdated(this) } } /** * Set the [paddingPercent] of the progress indicator relative to its shadow as a percentage of the shadow. * If the percentage is higher than 100, it is treated as (value % 100). */ fun setShadowPadding(paddingPercent: Float) { this.shadowPadding = -1 if (paddingPercent > 100) { shadowPaddingPercent = paddingPercent % 100 } calculateSizeAndBounds(mCalculatedLastW, mCalculatedLastH, mCalculatedLastMode) } // *************** Fields used by drawers **************** /** Set the [listener] that will update the progress drawers on changes. */ internal fun setListener(listener: ProgressOptionsListener) { this.listener = WeakReference(listener) } internal interface ProgressOptionsListener { fun onOptionsUpdated(options: ProgressOptions) fun onSizeUpdated(options: ProgressOptions) fun onModeUpdated(options: ProgressOptions) } }
mit
56e40dfe1cf11df169050f2c799afd8b
41.132701
120
0.645744
4.7608
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/casts/mutableCollections/isWithMutable.kt
2
5331
// IGNORE_BACKEND: NATIVE // WITH_RUNTIME class Itr : Iterator<String> by ArrayList<String>().iterator() class MItr : MutableIterator<String> by ArrayList<String>().iterator() class LItr : ListIterator<String> by ArrayList<String>().listIterator() class MLItr : MutableListIterator<String> by ArrayList<String>().listIterator() class It : Iterable<String> by ArrayList<String>() class MIt : MutableIterable<String> by ArrayList<String>() class C : Collection<String> by ArrayList<String>() class MC : MutableCollection<String> by ArrayList<String>() class L : List<String> by ArrayList<String>() class ML : MutableList<String> by ArrayList<String>() class S : Set<String> by HashSet<String>() class MS : MutableSet<String> by HashSet<String>() class M : Map<String, String> by HashMap<String, String>() class MM : MutableMap<String, String> by HashMap<String, String>() class ME : Map.Entry<String, String> { override val key: String get() = throw UnsupportedOperationException() override val value: String get() = throw UnsupportedOperationException() } class MME : MutableMap.MutableEntry<String, String> { override val key: String get() = throw UnsupportedOperationException() override val value: String get() = throw UnsupportedOperationException() override fun setValue(value: String): String = throw UnsupportedOperationException() } fun assert(condition: Boolean, message: () -> String) { if (!condition) throw AssertionError(message())} fun box(): String { val itr = Itr() as Any val mitr = MItr() assert(itr !is MutableIterator<*>) { "Itr should satisfy '!is MutableIterator'" } assert(mitr is MutableIterator<*>) { "MItr should satisfy 'is MutableIterator'" } val litr = LItr() as Any val mlitr = MLItr() assert(litr !is MutableIterator<*>) { "LItr should satisfy '!is MutableIterator'" } assert(litr !is MutableListIterator<*>) { "LItr should satisfy '!is MutableListIterator'" } assert(mlitr is MutableListIterator<*>) { "MLItr should satisfy 'is MutableListIterator'" } val it = It() as Any val mit = MIt() val arrayList = ArrayList<String>() assert(it !is MutableIterable<*>) { "It should satisfy '!is MutableIterable'" } assert(mit is MutableIterable<*>) { "MIt should satisfy 'is MutableIterable'" } assert(arrayList is MutableIterable<*>) { "ArrayList should satisfy 'is MutableIterable'" } val coll = C() as Any val mcoll = MC() assert(coll !is MutableCollection<*>) { "C should satisfy '!is MutableCollection'" } assert(coll !is MutableIterable<*>) { "C should satisfy '!is MutableIterable'" } assert(mcoll is MutableCollection<*>) { "MC should satisfy 'is MutableCollection'" } assert(mcoll is MutableIterable<*>) { "MC should satisfy 'is MutableIterable'" } assert(arrayList is MutableCollection<*>) { "ArrayList should satisfy 'is MutableCollection'" } val list = L() as Any val mlist = ML() assert(list !is MutableList<*>) { "L should satisfy '!is MutableList'" } assert(list !is MutableCollection<*>) { "L should satisfy '!is MutableCollection'" } assert(list !is MutableIterable<*>) { "L should satisfy '!is MutableIterable'" } assert(mlist is MutableList<*>) { "ML should satisfy 'is MutableList'" } assert(mlist is MutableCollection<*>) { "ML should satisfy 'is MutableCollection'" } assert(mlist is MutableIterable<*>) { "ML should satisfy 'is MutableIterable'" } assert(arrayList is MutableList<*>) { "ArrayList should satisfy 'is MutableList'" } val set = S() as Any val mset = MS() val hashSet = HashSet<String>() assert(set !is MutableSet<*>) { "S should satisfy '!is MutableSet'" } assert(set !is MutableCollection<*>) { "S should satisfy '!is MutableCollection'" } assert(set !is MutableIterable<*>) { "S should satisfy '!is MutableIterable'" } assert(mset is MutableSet<*>) { "MS should satisfy 'is MutableSet'" } assert(mset is MutableCollection<*>) { "MS should satisfy 'is MutableCollection'" } assert(mset is MutableIterable<*>) { "MS should satisfy 'is MutableIterable'" } assert(hashSet is MutableSet<*>) { "HashSet should satisfy 'is MutableSet'" } assert(hashSet is MutableCollection<*>) { "HashSet should satisfy 'is MutableCollection'" } assert(hashSet is MutableIterable<*>) { "HashSet should satisfy 'is MutableIterable'" } val map = M() as Any val mmap = MM() val hashMap = HashMap<String, String>() assert(map !is MutableMap<*, *>) { "M should satisfy '!is MutableMap'" } assert(mmap is MutableMap<*, *>) { "MM should satisfy 'is MutableMap'"} assert(hashMap is MutableMap<*, *>) { "HashMap should satisfy 'is MutableMap'" } val entry = ME() as Any val mentry = MME() hashMap[""] = "" val hashMapEntry = hashMap.entries.first() assert(entry !is MutableMap.MutableEntry<*, *>) { "ME should satisfy '!is MutableMap.MutableEntry'"} assert(mentry is MutableMap.MutableEntry<*, *>) { "MME should satisfy 'is MutableMap.MutableEntry'"} assert(hashMapEntry is MutableMap.MutableEntry<*, *>) { "HashMap.Entry should satisfy 'is MutableMap.MutableEntry'"} assert((mlist as Any) !is MutableSet<*>) { "ML !is MutableSet" } assert((mlist as Any) !is MutableIterator<*>) { "ML !is MutableIterator" } return "OK" }
apache-2.0
3cee48a5cf8aaa2e014d114a023a3a54
46.598214
120
0.691615
4.435108
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/constructors/primaryConstructor.kt
1
1250
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.test.assertNull import kotlin.test.assertNotNull import kotlin.reflect.full.* class OnlyPrimary class PrimaryWithSecondary(val s: String) { constructor(x: Int) : this(x.toString()) override fun toString() = s } class OnlySecondary { constructor(s: String) } class TwoSecondaries { constructor(s: String) constructor(d: Double) } enum class En interface I object O class C { companion object } fun box(): String { val p1 = OnlyPrimary::class.primaryConstructor assertNotNull(p1) assert(p1!!.call() is OnlyPrimary) val p2 = PrimaryWithSecondary::class.primaryConstructor assertNotNull(p2) assert(p2!!.call("beer").toString() == "beer") val p3 = OnlySecondary::class.primaryConstructor assertNull(p3) val p4 = TwoSecondaries::class.primaryConstructor assertNull(p4) assertNotNull(En::class.primaryConstructor) // TODO: maybe primaryConstructor should be null for enum classes assertNull(I::class.primaryConstructor) assertNull(O::class.primaryConstructor) assertNull(C.Companion::class.primaryConstructor) return "OK" }
apache-2.0
b24bd2fe910446d27bc455ec4f6a303e
20.929825
113
0.7232
3.968254
false
false
false
false
AndroidX/androidx
wear/compose/compose-material/samples/src/main/java/androidx/wear/compose/material/samples/ToggleButtonSample.kt
3
1829
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.wear.compose.material.Icon import androidx.wear.compose.material.ToggleButton import androidx.wear.compose.material.ToggleButtonDefaults @Sampled @Composable fun ToggleButtonWithIcon() { var checked by remember { mutableStateOf(true) } ToggleButton( checked = checked, onCheckedChange = { checked = it }, enabled = true, ) { Icon( painter = painterResource(id = R.drawable.ic_airplanemode_active_24px), contentDescription = "airplane", modifier = Modifier .size(ToggleButtonDefaults.DefaultIconSize) .wrapContentSize(align = Alignment.Center), ) } }
apache-2.0
0dba3ef0d98d9c2e0b9a88b7dd696790
34.862745
83
0.745763
4.561097
false
false
false
false
LouisCAD/Splitties
modules/views-dsl/src/androidMain/kotlin/splitties/views/dsl/core/styles/Styles.kt
1
1250
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ package splitties.views.dsl.core.styles import android.content.Context import android.util.AttributeSet import android.view.View import androidx.annotation.AttrRes import androidx.annotation.IdRes import androidx.annotation.StyleRes import splitties.views.dsl.core.NO_THEME import splitties.views.dsl.core.getThemeAttrStyledView import splitties.views.dsl.core.viewFactory import splitties.views.dsl.core.wrapCtxIfNeeded typealias NewViewWithStyleAttrRef<V> = (Context, AttributeSet?, Int) -> V inline operator fun <reified V : View> XmlStyle<V>.invoke( ctx: Context, @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: V.() -> Unit = {} ): V = ctx.viewFactory.getThemeAttrStyledView<V>(ctx.wrapCtxIfNeeded(theme), null, styleAttr).also { it.id = id }.apply(initView) inline fun <V : View> Context.styledView( newViewRef: NewViewWithStyleAttrRef<V>, @AttrRes styleAttr: Int, @IdRes id: Int = View.NO_ID, @StyleRes theme: Int = NO_THEME, initView: V.() -> Unit = {} ): V = newViewRef(this.wrapCtxIfNeeded(theme), null, styleAttr).also { it.id = id }.apply(initView)
apache-2.0
228f01b23bd31b1a2490a209c692c2f7
33.722222
109
0.7376
3.581662
false
false
false
false
smmribeiro/intellij-community
images/src/org/intellij/images/options/impl/ImageEditorColorSchemeSettings.kt
12
2370
// 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.intellij.images.options.impl import com.intellij.openapi.editor.colors.ColorKey import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.PlainSyntaxHighlighter import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import com.intellij.psi.codeStyle.DisplayPriority import com.intellij.psi.codeStyle.DisplayPrioritySortable import com.intellij.ui.Gray import com.intellij.ui.JBColor import org.intellij.images.ImagesBundle import org.intellij.images.fileTypes.impl.ImageFileType /** * @author Konstantin Bulenkov */ val BACKGROUND_COLOR_KEY = ColorKey.createColorKey("IMAGES_BACKGROUND", JBColor.background()) val WHITE_CELL_COLOR_KEY = ColorKey.createColorKey("IMAGES_WHITE_CELL_COLOR", Gray.xFF) val GRID_LINE_COLOR_KEY = ColorKey.createColorKey("IMAGES_GRID_LINE_COLOR", JBColor.DARK_GRAY) val BLACK_CELL_COLOR_KEY = ColorKey.createColorKey("IMAGES_WHITE_CELL_COLOR", Gray.xC0) class ImageEditorColorSchemeSettings : ColorSettingsPage, DisplayPrioritySortable { override fun getColorDescriptors(): Array<ColorDescriptor> { return arrayOf( ColorDescriptor(ImagesBundle.message("background.color.descriptor"), BACKGROUND_COLOR_KEY, ColorDescriptor.Kind.BACKGROUND), ColorDescriptor(ImagesBundle.message("grid.line.color.descriptor"), GRID_LINE_COLOR_KEY, ColorDescriptor.Kind.BACKGROUND), ColorDescriptor(ImagesBundle.message("white.cell.color.descriptor"), WHITE_CELL_COLOR_KEY, ColorDescriptor.Kind.BACKGROUND), ColorDescriptor(ImagesBundle.message("black.cell.color.descriptor"), BLACK_CELL_COLOR_KEY, ColorDescriptor.Kind.BACKGROUND)) } override fun getPriority() = DisplayPriority.OTHER_SETTINGS override fun getDisplayName() = ImagesBundle.message("settings.page.name") override fun getIcon() = ImageFileType.INSTANCE.icon override fun getDemoText() = " " override fun getHighlighter() = PlainSyntaxHighlighter() override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? = null override fun getAttributeDescriptors() = emptyArray<AttributesDescriptor>() }
apache-2.0
8b48810994808b7d0bf4e087ff8a235e
56.829268
140
0.811814
4.397032
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/project-wizard/maven/src/org/jetbrains/kotlin/tools/projectWizard/maven/MavenKotlinNewProjectWizard.kt
1
1418
// 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.tools.projectWizard.maven import com.intellij.openapi.project.Project import com.intellij.util.io.systemIndependentPath import org.jetbrains.idea.maven.wizards.MavenNewProjectWizardStep import org.jetbrains.kotlin.tools.projectWizard.BuildSystemKotlinNewProjectWizard import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizard import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType internal class MavenKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard { override val name = "Maven" override fun createStep(parent: KotlinNewProjectWizard.Step) = object : MavenNewProjectWizardStep<KotlinNewProjectWizard.Step>(parent) { override fun setupProject(project: Project) { KotlinNewProjectWizard.generateProject( project = project, projectPath = parent.projectPath.systemIndependentPath, projectName = parent.name, sdk = sdk, buildSystemType = BuildSystemType.Maven, projectGroupId = groupId, artifactId = artifactId, version = version ) } } }
apache-2.0
ecf0eade6c437cb75e8b5a061f117e4f
46.266667
158
0.697461
5.582677
false
false
false
false
jotomo/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt
1
4693
package info.nightscout.androidaps.plugins.general.openhumans import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.lifecycle.Observer import androidx.work.WorkInfo import androidx.work.WorkManager import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.Event import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.BackpressureStrategy import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject class OpenHumansFragment : DaggerFragment() { private var viewsCreated = false private var login: Button? = null private var logout: Button? = null private var memberId: TextView? = null private var queueSize: TextView? = null private var workerState: TextView? = null private var queueSizeValue = 0L private val compositeDisposable = CompositeDisposable() @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var resourceHelper: ResourceHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) compositeDisposable += Single.fromCallable { MainApp.getDbHelper().ohQueueSize } .subscribeOn(Schedulers.io()) .repeatWhen { rxBus.toObservable(UpdateViewEvent::class.java) .cast(Any::class.java) .mergeWith(rxBus.toObservable(UpdateQueueEvent::class.java) .throttleLatest(5, TimeUnit.SECONDS)) .toFlowable(BackpressureStrategy.LATEST) } .observeOn(AndroidSchedulers.mainThread()) .subscribe({ queueSizeValue = it updateGUI() }, {}) context?.applicationContext?.let { appContext -> WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, Observer<List<WorkInfo>> { val workInfo = it.lastOrNull() if (workInfo == null) { workerState?.visibility = View.GONE } else { workerState?.visibility = View.VISIBLE workerState?.text = getString(R.string.worker_state, workInfo.state.toString()) } }) } } override fun onDestroy() { compositeDisposable.clear() super.onDestroy() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val view = inflater.inflate(R.layout.fragment_open_humans, container, false) login = view.findViewById(R.id.login) logout = view.findViewById(R.id.logout) memberId = view.findViewById(R.id.member_id) queueSize = view.findViewById(R.id.queue_size) workerState = view.findViewById(R.id.worker_state) login!!.setOnClickListener { startActivity(Intent(context, OpenHumansLoginActivity::class.java)) } logout!!.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.oh_logout_confirmation), Runnable { openHumansUploader.logout() }) } } viewsCreated = true updateGUI() return view } override fun onDestroyView() { viewsCreated = false login = null logout = null memberId = null queueSize = null super.onDestroyView() } fun updateGUI() { if (viewsCreated) { queueSize!!.text = getString(R.string.queue_size, queueSizeValue) val projectMemberId = openHumansUploader.projectMemberId memberId!!.text = getString(R.string.project_member_id, projectMemberId ?: getString(R.string.not_logged_in)) login!!.visibility = if (projectMemberId == null) View.VISIBLE else View.GONE logout!!.visibility = if (projectMemberId != null) View.VISIBLE else View.GONE } } object UpdateViewEvent : Event() object UpdateQueueEvent : Event() }
agpl-3.0
fcd5665fe011d6bb67e062d8f64d6329
38.116667
171
0.688685
4.873313
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/models/PhotoTest.kt
1
2083
package com.kickstarter.models import com.kickstarter.mock.factories.PhotoFactory import junit.framework.TestCase import org.junit.Test class PhotoTest : TestCase() { @Test fun testPhotoInitializationDefault() { val photo = Photo.builder() .build() assertTrue(photo.ed() == "") assertTrue(photo.full() == "") assertTrue(photo.little() == "") assertTrue(photo.med() == "") assertTrue(photo.small() == "") assertTrue(photo.thumb() == "") } @Test fun testPhotoInitializationNull() { val photoUrl = null val photo = Photo.builder() .ed(photoUrl) .full(photoUrl) .little(photoUrl) .med(photoUrl) .small(photoUrl) .thumb(photoUrl) .build() assertTrue(photo.ed() == "") assertTrue(photo.full() == "") assertTrue(photo.little() == "") assertTrue(photo.med() == "") assertTrue(photo.small() == "") assertTrue(photo.thumb() == "") } @Test fun testPhotoInitializationEquals() { val photoUrl = "https://ksr-ugc.imgix.net/assets/012/032/069/46817a8c099133d5bf8b64aad282a696_original.png?crop=faces&w=1552&h=873&fit=crop&v=1463725702&auto=format&q=92&s=72501d155e4a5e399276632687c77959" val photo = PhotoFactory.photo() val photo2 = Photo.builder() .ed(photoUrl) .full(photoUrl) .little(photoUrl) .med(photoUrl) .small(photoUrl) .thumb(photoUrl) .build() assertTrue(photo.ed() == photo2.ed()) assertTrue(photo.full() == photo2.full()) assertTrue(photo.little() == photo2.little()) assertTrue(photo.med() == photo2.med()) assertTrue(photo.small() == photo2.small()) assertTrue(photo.thumb() == photo2.thumb()) assertTrue(photo == photo2) val photo3 = photo2.toBuilder() .full("other url") .build() assertFalse(photo2 == photo3) } }
apache-2.0
150b95aeac87518bda93a4cd4ec64684
29.188406
213
0.56169
3.908068
false
true
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/HintsDescriptorRendererOptions.kt
1
5891
// 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.parameterInfo import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.renderer.* import org.jetbrains.kotlin.types.KotlinType import kotlin.properties.Delegates import kotlin.properties.ReadWriteProperty interface HintsClassifierNamePolicy { fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String } /** * Almost copy-paste from [ClassifierNamePolicy.SOURCE_CODE_QUALIFIED] * * for local declarations qualified up to function scope */ object SOURCE_CODE_QUALIFIED : HintsClassifierNamePolicy { override fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String = qualifiedNameForSourceCode(classifier) private fun qualifiedNameForSourceCode(descriptor: ClassifierDescriptor): String { val nameString = descriptor.name.render() if (descriptor is TypeParameterDescriptor) { return nameString } val qualifier = qualifierName(descriptor.containingDeclaration) return if (qualifier != null && qualifier != "") "$qualifier.$nameString" else nameString } private fun qualifierName(descriptor: DeclarationDescriptor): String? = when (descriptor) { is ClassDescriptor -> qualifiedNameForSourceCode(descriptor) is PackageFragmentDescriptor -> descriptor.fqName.toUnsafe().render() else -> null } } /** * Almost copy-paste from [DescriptorRendererOptionsImpl] */ class HintsDescriptorRendererOptions : DescriptorRendererOptions { var hintsClassifierNamePolicy: HintsClassifierNamePolicy by property(SOURCE_CODE_QUALIFIED) var isLocked: Boolean = false private set fun lock() { check(!isLocked) { "options have been already locked to prevent mutability" } isLocked = true } private fun <T> property(initialValue: T): ReadWriteProperty<HintsDescriptorRendererOptions, T> { return Delegates.vetoable(initialValue) { _, _, _ -> check(!isLocked) { "Cannot modify readonly DescriptorRendererOptions" } true } } override var classifierNamePolicy: ClassifierNamePolicy by property(ClassifierNamePolicy.SOURCE_CODE_QUALIFIED) override var withDefinedIn by property(true) override var withSourceFileForTopLevel by property(true) override var modifiers: Set<DescriptorRendererModifier> by property(DescriptorRendererModifier.ALL_EXCEPT_ANNOTATIONS) override var startFromName by property(false) override var startFromDeclarationKeyword by property(false) override var debugMode by property(false) override var classWithPrimaryConstructor by property(false) override var verbose by property(false) override var unitReturnType by property(true) override var withoutReturnType by property(false) override var enhancedTypes by property(false) override var normalizedVisibilities by property(false) override var renderDefaultVisibility by property(true) override var renderDefaultModality by property(true) override var renderConstructorDelegation by property(false) override var renderPrimaryConstructorParametersAsProperties by property(false) override var actualPropertiesInPrimaryConstructor: Boolean by property(false) override var uninferredTypeParameterAsName by property(false) override var includePropertyConstant by property(false) override var withoutTypeParameters by property(false) override var withoutSuperTypes by property(false) override var typeNormalizer by property<(KotlinType) -> KotlinType> { it } override var defaultParameterValueRenderer by property<((ValueParameterDescriptor) -> String)?> { "..." } override var secondaryConstructorsAsPrimary by property(true) override var overrideRenderingPolicy by property(OverrideRenderingPolicy.RENDER_OPEN) override var valueParametersHandler: DescriptorRenderer.ValueParametersHandler by property(DescriptorRenderer.ValueParametersHandler.DEFAULT) override var textFormat by property(RenderingFormat.PLAIN) override var parameterNameRenderingPolicy by property(ParameterNameRenderingPolicy.ALL) override var receiverAfterName by property(false) override var renderCompanionObjectName by property(false) override var propertyAccessorRenderingPolicy by property(PropertyAccessorRenderingPolicy.DEBUG) override var renderDefaultAnnotationArguments by property(false) override var eachAnnotationOnNewLine: Boolean by property(false) override var excludedAnnotationClasses by property(emptySet<FqName>()) override var excludedTypeAnnotationClasses by property(ExcludedTypeAnnotations.internalAnnotationsForResolve) override var annotationFilter: ((AnnotationDescriptor) -> Boolean)? by property(null) override var annotationArgumentsRenderingPolicy by property(AnnotationArgumentsRenderingPolicy.NO_ARGUMENTS) override var alwaysRenderModifiers by property(false) override var renderConstructorKeyword by property(true) override var renderUnabbreviatedType: Boolean by property(true) override var renderTypeExpansions: Boolean by property(false) override var includeAdditionalModifiers: Boolean by property(true) override var parameterNamesInFunctionalTypes: Boolean by property(true) override var renderFunctionContracts: Boolean by property(false) override var presentableUnresolvedTypes: Boolean by property(false) override var boldOnlyForNamesInHtml: Boolean by property(false) override var informativeErrorType: Boolean by property(true) }
apache-2.0
12b7132c86342bfc011def0f72f911ed
46.128
158
0.787812
5.424494
false
false
false
false
PeteGabriel/Yamda
app/src/main/java/com/dev/moviedb/mvvm/repository/remote/dto/ResultImageDTO.kt
1
1610
package com.dev.moviedb.mvvm.repository.remote.dto import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * Images that belong to a movie. * * Yamda 1.0.0. */ class ResultImageDTO() :Parcelable{ @SerializedName("aspect_ratio") @Expose var aspectRatio: Float = 0.0f @SerializedName("file_path") @Expose var filePath: String = "" var height: Float = 0.0f @SerializedName("vote_average") @Expose var voteAverage: Float = 0.0f @SerializedName("vote_count") @Expose var voteCount: Int = 0 var width: Int = 0 constructor(parcel: Parcel) : this() { aspectRatio = parcel.readFloat() filePath = parcel.readString() height = parcel.readFloat() voteAverage = parcel.readFloat() voteCount = parcel.readInt() width = parcel.readInt() } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeFloat(aspectRatio) parcel.writeString(filePath) parcel.writeFloat(height) parcel.writeFloat(voteAverage) parcel.writeInt(voteCount) parcel.writeInt(width) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ResultImageDTO> { override fun createFromParcel(parcel: Parcel): ResultImageDTO { return ResultImageDTO(parcel) } override fun newArray(size: Int): Array<ResultImageDTO?> { return arrayOfNulls(size) } } }
gpl-3.0
cbb8f41620d2c4dbd4bb929210e1134b
23.044776
71
0.647205
4.327957
false
false
false
false
jovr/imgui
core/src/main/kotlin/imgui/classes/Context.kt
1
26597
package imgui.classes import glm_.vec2.Vec2 import glm_.vec4.Vec4 import imgui.* import imgui.ImGui.callHooks import imgui.ImGui.saveIniSettingsToDisk import imgui.ImGui.tableSettingsInstallHandler import imgui.api.g import imgui.api.gImGui import imgui.font.Font import imgui.font.FontAtlas import imgui.internal.DrawChannel import imgui.internal.DrawData import imgui.internal.classes.* import imgui.internal.hashStr import imgui.internal.sections.* import imgui.static.* import kool.free import java.io.File import java.nio.ByteBuffer import java.util.* import kotlin.collections.ArrayList /** Main Dear ImGui context * * Dear ImGui context (opaque structure, unless including imgui_internal.h) * * ~CreateContext */ class Context(sharedFontAtlas: FontAtlas? = null) { var initialized = false /** Io.Fonts-> is owned by the ImGuiContext and will be destructed along with it. */ var fontAtlasOwnedByContext = sharedFontAtlas == null var io = IO(sharedFontAtlas) var style = Style() lateinit var font: Font /** (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window. */ var fontSize = 0f /** (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height. */ var fontBaseSize = 0f var drawListSharedData = DrawListSharedData() var time = 0.0 var frameCount = 0 var frameCountEnded = -1 var frameCountRendered = -1 /** Set by NewFrame(), cleared by EndFrame() */ var withinFrameScope = false /** Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed */ var withinFrameScopeWithImplicitWindow = false /** Set within EndChild() */ var withinEndChild = false /** Request full GC */ var gcCompactAll = false /** Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log() */ var testEngineHookItems = false /** Will call test engine hooks: ImGuiTestEngineHook_IdInfo() from GetID() */ var testEngineHookIdInfo: ID = 0 /** Test engine user data */ var testEngine: Any? = null // Windows state /** Windows, sorted in display order, back to front */ val windows = ArrayList<Window>() /** Windows, sorted in focus order, back to front. * (FIXME: We could only store root windows here! Need to sort out the Docking equivalent which is RootWindowDockStop and is unfortunately a little more dynamic) */ val windowsFocusOrder = ArrayList<Window>() val windowsTempSortBuffer = ArrayList<Window>() val currentWindowStack = Stack<Window>() /** Map window's ImGuiID to ImGuiWindow* */ val windowsById = mutableMapOf<Int, Window>() /** Number of unique windows submitted by frame */ var windowsActiveCount = 0 /** Window being drawn into */ var currentWindow: Window? = null /** Window the mouse is hovering. Will typically catch mouse inputs. */ var hoveredWindow: Window? = null /** == HoveredWindow ? HoveredWindow->RootWindow : NULL, merely a shortcut to avoid null test in some situation. */ var hoveredRootWindow: Window? = null /** Hovered window ignoring MovingWindow. Only set if MovingWindow is set. */ var hoveredWindowUnderMovingWindow: Window? = null /** Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow. */ var movingWindow: Window? = null /** Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. */ var wheelingWindow: Window? = null var wheelingWindowRefMousePos: Vec2 = Vec2() var wheelingWindowTimer = 0f // Item/widgets state and tracking information /** Hovered widget, filled during the frame */ var hoveredId: ID = 0 var hoveredIdPreviousFrame: ID = 0 var hoveredIdAllowOverlap = false /** Hovered widget will use mouse wheel. Blocks scrolling the underlying window. */ var hoveredIdUsingMouseWheel = false var hoveredIdPreviousFrameUsingMouseWheel = false /** At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. * May be true even if HoveredId == 0. */ var hoveredIdDisabled = false /** Measure contiguous hovering time */ var hoveredIdTimer = 0f /** Measure contiguous hovering time where the item has not been active */ var hoveredIdNotActiveTimer = 0f /** Active widget */ var activeId: ID = 0 /** Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) */ var activeIdIsAlive: ID = 0 var activeIdTimer = 0f /** Set at the time of activation for one frame */ var activeIdIsJustActivated = false /** Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) */ var activeIdAllowOverlap = false /** Disable losing active id if the active id window gets unfocused. */ var activeIdNoClearOnFocusLoss = false /** Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. */ var activeIdHasBeenPressedBefore = false /** Was the value associated to the widget edited over the course of the Active state. */ var activeIdHasBeenEditedBefore = false var activeIdHasBeenEditedThisFrame = false /** Active widget will want to read mouse wheel. Blocks scrolling the underlying window. */ var activeIdUsingMouseWheel = false /** Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) */ var activeIdUsingNavDirMask = 0 /** Active widget will want to read those nav inputs. */ var activeIdUsingNavInputMask = 0 /** Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order the enum to make useful keys come first, either redesign this into e.g. a small array. */ var activeIdUsingKeyInputMask = 0L /** Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) */ var activeIdClickOffset = Vec2(-1) var activeIdWindow: Window? = null /** Activating with mouse or nav (gamepad/keyboard) */ var activeIdSource = InputSource.None var activeIdMouseButton = 0 var activeIdPreviousFrame: ID = 0 var activeIdPreviousFrameIsAlive = false var activeIdPreviousFrameHasBeenEdited = false var activeIdPreviousFrameWindow: Window? = null /** Store the last non-zero ActiveId, useful for animation. */ var lastActiveId: ID = 0 /** Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. */ var lastActiveIdTimer = 0f // Next window/item data /** Storage for SetNextWindow** functions */ val nextWindowData = NextWindowData() /** Storage for SetNextItem** functions */ var nextItemData = NextItemData() /** Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() */ var colorStack = Stack<ColorMod>() /** Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() */ val styleVarStack = Stack<StyleMod>() /** Stack for PushFont()/PopFont() - inherited by Begin() */ val fontStack = Stack<Font>() /** Stack for PushFocusScope()/PopFocusScope() - not inherited by Begin(), unless child window */ val focusScopeStack = Stack<ID>() /** Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() */ val itemFlagsStack = Stack<ItemFlags>() /** Stack for BeginGroup()/EndGroup() - not inherited by Begin() */ val groupStack = Stack<GroupData>() /** Which popups are open (persistent) */ val openPopupStack = Stack<PopupData>() /** Which level of BeginPopup() we are in (reset every frame) */ val beginPopupStack = Stack<PopupData>() //------------------------------------------------------------------ // Gamepad/keyboard Navigation //------------------------------------------------------------------ /** Focused window for navigation. Could be called 'FocusWindow' */ var navWindow: Window? = null /** Focused item for navigation */ var navId: ID = 0 /** Identify a selection scope (selection code often wants to "clear other items" when landing on an item of the selection set) */ var navFocusScopeId = 0 /** ~~ (g.activeId == 0) && NavInput.Activate.isPressed() ? navId : 0, also set when calling activateItem() */ var navActivateId: ID = 0 /** ~~ isNavInputDown(NavInput.Activate) ? navId : 0 */ var navActivateDownId: ID = 0 /** ~~ NavInput.Activate.isPressed() ? navId : 0 */ var navActivatePressedId: ID = 0 /** ~~ NavInput.Input.isPressed() ? navId : 0 */ var navInputId: ID = 0 /** Just tabbed to this id. */ var navJustTabbedId: ID = 0 /** Just navigated to this id (result of a successfully MoveRequest) */ var navJustMovedToId: ID = 0 /** Just navigated to this focus scope id (result of a successfully MoveRequest). */ var navJustMovedToFocusScopeId: ID = 0 var navJustMovedToKeyMods: KeyModFlags = KeyMod.None.i /** Set by ActivateItem(), queued until next frame */ var navNextActivateId: ID = 0 /** Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard. */ var navInputSource = InputSource.None /** Rectangle used for scoring, in screen space. Based of window.NavRectRel[], modified for directional navigation scoring. */ var navScoringRect = Rect() /** Metrics for debugging */ var navScoringCount = 0 /** Layer we are navigating on. For now the system is hard-coded for 0 = main contents and 1 = menu/title bar, * may expose layers later. */ var navLayer = NavLayer.Main /** == NavWindow->DC.FocusIdxTabCounter at time of NavId processing */ var navIdTabCounter = Int.MAX_VALUE /** Nav widget has been seen this frame ~~ NavRectRel is valid */ var navIdIsAlive = false /** When set we will update mouse position if (io.ConfigFlag & ConfigFlag.NavMoveMouse) if set (NB: this not enabled by default) */ var navMousePosDirty = false /** When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why * NavDisableHighlight isn't always != NavDisableMouseHover) */ var navDisableHighlight = true /** When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again. */ var navDisableMouseHover = false /** ~~ navMoveRequest || navInitRequest */ var navAnyRequest = false /** Init request for appearing window to select first item */ var navInitRequest = false var navInitRequestFromMove = false /** Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) */ var navInitResultId: ID = 0 /** Init request result rectangle (relative to parent window) */ var navInitResultRectRel = Rect() /** Move request for this frame */ var navMoveRequest = false var navMoveRequestFlags = NavMoveFlag.None.i /** None / ForwardQueued / ForwardActive (this is used to navigate sibling parent menus from a child menu) */ var navMoveRequestForward = NavForward.None var navMoveRequestKeyMods: KeyModFlags = KeyMod.None.i /** Direction of the move request (left/right/up/down), direction of the previous move request */ var navMoveDir = Dir.None /** Direction of the move request (left/right/up/down), direction of the previous move request */ var navMoveDirLast = Dir.None /** FIXME-NAV: Describe the purpose of this better. Might want to rename? */ var navMoveClipDir = Dir.None /** Best move request candidate within NavWindow */ var navMoveResultLocal = NavMoveResult() /** Best move request candidate within NavWindow that are mostly visible (when using NavMoveFlags.AlsoScoreVisibleSet flag) */ val navMoveResultLocalVisibleSet = NavMoveResult() /** Best move request candidate within NavWindow's flattened hierarchy (when using WindowFlags.NavFlattened flag) */ var navMoveResultOther = NavMoveResult() /** Window which requested trying nav wrap-around. */ var navWrapRequestWindow: Window? = null /** Wrap-around operation flags. */ var navWrapRequestFlags: NavMoveFlags = NavMoveFlag.None.i // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize) /** Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! */ var navWindowingTarget: Window? = null /** Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it. */ var navWindowingTargetAnim: Window? = null /** Internal window actually listing the CTRL+Tab contents */ var navWindowingListWindow: Window? = null var navWindowingTimer = 0f var navWindowingHighlightAlpha = 0f var navWindowingToggleLayer = false // Legacy Focus/Tabbing system (older than Nav, active even if Nav is disabled, misnamed. FIXME-NAV: This needs a redesign!) var focusRequestCurrWindow: Window? = null var focusRequestNextWindow: Window? = null /** Any item being requested for focus, stored as an index (we on layout to be stable between the frame pressing TAB and the next frame, semi-ouch) */ var focusRequestCurrCounterRegular = Int.MAX_VALUE /** Tab item being requested for focus, stored as an index */ var focusRequestCurrCounterTabStop = Int.MAX_VALUE /** Stored for next frame */ var focusRequestNextCounterRegular = Int.MAX_VALUE /** Stored for next frame */ var focusRequestNextCounterTabStop = Int.MAX_VALUE var focusTabPressed = false // ------------------------------------------------------------------ // Render //------------------------------------------------------------------ /** Main ImDrawData instance to pass render information to the user */ var drawData = DrawData() val drawDataBuilder = DrawDataBuilder() /** 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list) */ var dimBgRatio = 0f val backgroundDrawList: DrawList = DrawList(drawListSharedData).apply { _ownerName = "##Background" // Give it a name for debugging } /** Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays */ val foregroundDrawList: DrawList = DrawList(drawListSharedData).apply { _ownerName = "##Foreground" // Give it a name for debugging } var mouseCursor = MouseCursor.Arrow //------------------------------------------------------------------ // Drag and Drop //------------------------------------------------------------------ var dragDropActive = false /** Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. */ var dragDropWithinSource = false /** Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. */ var dragDropWithinTarget = false var dragDropSourceFlags = DragDropFlag.None.i var dragDropSourceFrameCount = -1 var dragDropMouseButton = MouseButton.None // -1 at start var dragDropPayload = Payload() /** Store rectangle of current target candidate (we favor small targets when overlapping) */ var dragDropTargetRect = Rect() var dragDropTargetId: ID = 0 var dragDropAcceptFlags = DragDropFlag.None.i /** Target item surface (we resolve overlapping targets by prioritizing the smaller surface) */ var dragDropAcceptIdCurrRectSurface = 0f /** Target item id (set at the time of accepting the payload) */ var dragDropAcceptIdCurr: ID = 0 /** Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) */ var dragDropAcceptIdPrev: ID = 0 /** Last time a target expressed a desire to accept the source */ var dragDropAcceptFrameCount = -1 /** Set when holding a payload just made ButtonBehavior() return a press. */ var dragDropHoldJustPressedId: ID = 0 /** We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size */ var dragDropPayloadBufHeap = ByteBuffer.allocate(0) /** Local buffer for small payloads */ var dragDropPayloadBufLocal = ByteBuffer.allocate(16) // Table var currentTable: Table? = null val tables = Pool { Table() } val currentTableStack = ArrayList<PtrOrIndex>() /** Last used timestamp of each tables (SOA, for efficient GC) */ val tablesLastTimeActive = ArrayList<Float>() val drawChannelsTempMergeBuffer = ArrayList<DrawChannel>() // Tab bars var currentTabBar: TabBar? = null val tabBars = TabBarPool() val currentTabBarStack = Stack<PtrOrIndex>() val shrinkWidthBuffer = ArrayList<ShrinkWidthItem>() //------------------------------------------------------------------ // Widget state //------------------------------------------------------------------ var lastValidMousePos = Vec2() var inputTextState = InputTextState() var inputTextPasswordFont = Font() /** Temporary text input when CTRL+clicking on a slider, etc. */ var tempInputId: ID = 0 /** Store user options for color edit widgets */ var colorEditOptions: ColorEditFlags = ColorEditFlag._OptionsDefault.i /** Backup of last Hue associated to LastColor[3], so we can restore Hue in lossy RGB<>HSV round trips */ var colorEditLastHue = 0f /** Backup of last Saturation associated to LastColor[3], so we can restore Saturation in lossy RGB<>HSV round trips */ var colorEditLastSat = 0f var colorEditLastColor = FloatArray(3) { Float.MAX_VALUE } /** Initial/reference color at the time of opening the color picker. */ val colorPickerRef = Vec4() /** Accumulated slider delta when using navigation controls. */ var sliderCurrentAccum = 0f /** Has the accumulated slider delta changed since last time we tried to apply it? */ var sliderCurrentAccumDirty = false var dragCurrentAccumDirty = false /** Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings */ var dragCurrentAccum = 0f /** If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio */ var dragSpeedDefaultRatio = 1f / 100f /** Distance between mouse and center of grab box, normalized in parent space. Use storage? */ var scrollbarClickDeltaToGrabCenter = 0f var tooltipOverrideCount = 0 /** Time before slow tooltips appears (FIXME: This is temporary until we merge in tooltip timer+priority work) */ var tooltipSlowDelay = 0.5f /** If no custom clipboard handler is defined */ var clipboardHandlerData = "" /** A list of menu IDs that were rendered at least once */ val menusIdSubmittedThisFrame = ArrayList<ID>() // Platform support /** Cursor position request to the OS Input Method Editor */ var platformImePos = Vec2(Float.MAX_VALUE) /** Last cursor position passed to the OS Input Method Editor */ var platformImeLastPos = Vec2(Float.MAX_VALUE) /** '.' or *localeconv()->decimal_point */ var platformLocaleDecimalPoint = '.' //------------------------------------------------------------------ // Settings //------------------------------------------------------------------ var settingsLoaded = false /** Save .ini Settings to memory when time reaches zero */ var settingsDirtyTimer = 0f /** In memory .ini Settings for Window */ var settingsIniData = "" /** List of .ini settings handlers */ val settingsHandlers = ArrayList<SettingsHandler>() /** ImGuiWindow .ini settings entries (parsed from the last loaded .ini file and maintained on saving) */ val settingsWindows = ArrayList<WindowSettings>() /** ImGuiTable .ini settings entries */ val settingsTables = ArrayList<TableSettings>() /** Hooks for extensions (e.g. test engine) */ val hooks = ArrayList<ContextHook>() //------------------------------------------------------------------ // Capture/Logging //------------------------------------------------------------------ /** Currently capturing */ var logEnabled = false /** Capture target */ var logType = LogType.None /** If != NULL log to stdout/ file */ var logFile: File? = null /** Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. */ var logBuffer = StringBuilder() var logLinePosY = Float.MAX_VALUE var logLineFirstItem = false var logDepthRef = 0 var logDepthToExpand = 2 var logDepthToExpandDefault = 2 // Debug Tools /** Item picker is active (started with DebugStartItemPicker()) */ var debugItemPickerActive = false /** Will call IM_DEBUG_BREAK() when encountering this id */ var debugItemPickerBreakId: ID = 0 var debugMetricsConfig = MetricsConfig() //------------------------------------------------------------------ // Misc //------------------------------------------------------------------ /** Calculate estimate of framerate for user over the last 2 seconds. */ val framerateSecPerFrame = FloatArray(120) var framerateSecPerFrameIdx = 0 var framerateSecPerFrameAccum = 0f /** Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags */ var wantCaptureMouseNextFrame = -1 var wantCaptureKeyboardNextFrame = -1 var wantTextInputNextFrame = -1 /** Temporary text buffer */ val tempBuffer = ByteArray(1024 * 3) /* Context creation and access Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to Context() to share a font atlas between imgui contexts. None of those functions is reliant on the current context. ~CreateContext */ init { if (gImGui == null) setCurrent() initialize() } fun initialize() { assert(!initialized && !g.settingsLoaded) // Add .ini handle for ImGuiWindow type settingsHandlers += SettingsHandler().apply { typeName = "Window" typeHash = hashStr("Window") clearAllFn = ::windowSettingsHandler_ClearAll readOpenFn = ::windowSettingsHandler_ReadOpen readLineFn = ::windowSettingsHandler_ReadLine applyAllFn = ::windowSettingsHandler_ApplyAll writeAllFn = ::windowSettingsHandler_WriteAll } // Add .ini handle for ImGuiTable type tableSettingsInstallHandler(this) // #ifdef IMGUI_HAS_DOCK // #endif // #ifdef IMGUI_HAS_DOCK initialized = true } fun setCurrent() { gImGui = this } /** Destroy current context * ~DestroyContext */ fun destroy() { shutdown() if (gImGui === this) gImGui = null // SetCurrentContext(NULL); } /** This function is merely here to free heap allocations. * ~Shutdown(ImGuiContext* context) */ fun shutdown() { /* The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) */ if (fontAtlasOwnedByContext) io.fonts.locked = false io.fonts.clear() // Cleanup of other data are conditional on actually having initialized Dear ImGui. if (!initialized) return // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) if (settingsLoaded) io.iniFilename?.let(::saveIniSettingsToDisk) // Notify hooked test engine, if any g callHooks ContextHookType.Shutdown // Clear everything else windows.forEach { it.destroy() } windows.clear() windowsFocusOrder.clear() windowsTempSortBuffer.clear() currentWindow = null currentWindowStack.clear() windowsById.clear() navWindow = null hoveredWindow = null hoveredRootWindow = null hoveredWindowUnderMovingWindow = null activeIdWindow = null activeIdPreviousFrameWindow = null movingWindow = null settingsWindows.clear() colorStack.clear() styleVarStack.clear() fontStack.clear() openPopupStack.clear() beginPopupStack.clear() drawDataBuilder.clear() backgroundDrawList._clearFreeMemory(destroy = true) foregroundDrawList._clearFreeMemory(destroy = true) tabBars.clear() currentTabBarStack.clear() shrinkWidthBuffer.clear() g.tables.clear() g.currentTableStack.clear() g.drawChannelsTempMergeBuffer.clear() // TODO check if this needs proper deallocation clipboardHandlerData = "" menusIdSubmittedThisFrame.clear() inputTextState.textW = CharArray(0) inputTextState.initialTextA = ByteArray(0) inputTextState.textA = ByteArray(0) if (logFile != null) { logFile = null } logBuffer.setLength(0) initialized = false } } //----------------------------------------------------------------------------- // [SECTION] Generic context hooks //----------------------------------------------------------------------------- typealias ContextHookCallback = (ctx: Context, hook: ContextHook) -> Unit enum class ContextHookType { NewFramePre, NewFramePost, EndFramePre, EndFramePost, RenderPre, RenderPost, Shutdown } /** Hook for extensions like ImGuiTestEngine */ class ContextHook( var type: ContextHookType = ContextHookType.NewFramePre, var owner: ID = 0, var callback: ContextHookCallback? = null, var userData: Any? = null)
mit
96ae9e6fff421bf69933251a0fd6507c
33.723238
221
0.65748
4.567577
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/native/internal/KTypeImpl.kt
1
2209
/* * Copyright 2010-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 kotlin.native.internal import kotlin.reflect.* internal class KTypeImpl( override val classifier: KClassifier?, override val arguments: List<KTypeProjection>, override val isMarkedNullable: Boolean ) : KType { override fun equals(other: Any?) = other is KTypeImpl && this.classifier == other.classifier && this.arguments == other.arguments && this.isMarkedNullable == other.isMarkedNullable override fun hashCode(): Int { return (classifier?.hashCode() ?: 0) * 31 * 31 + this.arguments.hashCode() * 31 + if (isMarkedNullable) 1 else 0 } override fun toString(): String { val classifierString = when (classifier) { is KClass<*> -> classifier.qualifiedName ?: classifier.simpleName is KTypeParameter -> classifier.name else -> null } ?: return "(non-denotable type)" return buildString { append(classifierString) if (arguments.isNotEmpty()) { append('<') arguments.forEachIndexed { index, argument -> if (index > 0) append(", ") append(argument) } append('>') } if (isMarkedNullable) append('?') } } } internal class KTypeImplForTypeParametersWithRecursiveBounds : KType { override val classifier: KClassifier? get() = error("Type parameters with recursive bounds are not yet supported in reflection") override val arguments: List<KTypeProjection> get() = emptyList() override val isMarkedNullable: Boolean get() = error("Type parameters with recursive bounds are not yet supported in reflection") override fun equals(other: Any?) = error("Type parameters with recursive bounds are not yet supported in reflection") override fun hashCode(): Int = error("Type parameters with recursive bounds are not yet supported in reflection") }
apache-2.0
7a568fdc5382be72dd7d480cb0602510
32.469697
120
0.613852
5.234597
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/ProgressIndicatorUtils.kt
3
3390
// 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.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.util.ExceptionUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.utils.addToStdlib.cast import java.util.concurrent.CancellationException import java.util.concurrent.Future import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException /** * Copied from [com.intellij.openapi.progress.util.ProgressIndicatorUtils] */ object ProgressIndicatorUtils { @Suppress("ObjectLiteralToLambda") // Workaround for KT-43812. @JvmStatic fun <T> underModalProgress( project: Project, @Nls progressTitle: String, computable: () -> T ): T = com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress(project, progressTitle, object : Computable<T> { override fun compute(): T = computable() }) @JvmStatic fun <T> underModalProgressOrUnderWriteActionWithNonCancellableProgressInDispatchThread( project: Project, @Nls progressTitle: String, computable: () -> T ): T = if (CommandProcessor.getInstance().currentCommandName != null) { var result: T? = null ApplicationManager.getApplication().cast<ApplicationEx>().runWriteActionWithNonCancellableProgressInDispatchThread( progressTitle, project, null ) { result = computable() } result!! } else { underModalProgress(project, progressTitle, computable) } fun <T> runUnderDisposeAwareIndicator( parent: Disposable, computable: () -> T ): T = BackgroundTaskUtil.runUnderDisposeAwareIndicator(parent, Computable { computable() }) @JvmStatic fun <T> awaitWithCheckCanceled(future: Future<T>): T { val indicator = ProgressManager.getInstance().progressIndicator while (true) { checkCancelledEvenWithPCEDisabled(indicator) try { return future[10, TimeUnit.MILLISECONDS] } catch (ignore: TimeoutException) { } catch (e: Throwable) { val cause = e.cause if (cause is CancellationException) { throw ProcessCanceledException(cause) } else { ExceptionUtil.rethrowUnchecked(e) throw RuntimeException(e) } } } } private fun checkCancelledEvenWithPCEDisabled(indicator: ProgressIndicator?) = indicator?.let { if (it.isCanceled) { it.checkCanceled() // maybe it'll throw with some useful additional information throw ProcessCanceledException() } } }
apache-2.0
010ed785717c99ffa59e03953ecc5bf3
37.534091
158
0.684366
5.105422
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/adapters/TornadoFXColumns.kt
1
2795
package tornadofx.adapters import javafx.beans.property.DoubleProperty import javafx.scene.control.TableColumn import javafx.scene.control.TreeTableColumn fun TreeTableColumn<*,*>.toTornadoFXColumn() = TornadoFXTreeTableColumn(this) fun TableColumn<*,*>.toTornadoFXColumn() = TornadoFxNormalTableColumn(this) interface TornadoFXColumn<COLUMN> { val column: COLUMN val properties: Properties var prefWidth: Double var maxWidth: Double var minWidth: Double val width: Double val minWidthProperty: DoubleProperty val maxWidthProperty: DoubleProperty } class TornadoFXTreeTableColumn(override val column: TreeTableColumn<*, *>) : TornadoFXColumn<TreeTableColumn<*, *>> { override val minWidthProperty get() = column.minWidthProperty() override val maxWidthProperty get() = column.maxWidthProperty() override var minWidth: Double get() = column.minWidth set(value) { column.minWidth = value } override val properties = column.properties override var prefWidth: Double get() = column.prefWidth set(value) { column.prefWidth = value } override var maxWidth: Double get() = column.maxWidth set(value) { column.maxWidth = value } override val width: Double get() = column.width override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TornadoFXTreeTableColumn if (column != other.column) return false return true } override fun hashCode(): Int { return column.hashCode() } } class TornadoFxNormalTableColumn(override val column: TableColumn<*, *>) : TornadoFXColumn<TableColumn<*, *>> { override var minWidth: Double get() = column.minWidth set(value) { column.minWidth = value } override var maxWidth: Double get() = column.maxWidth set(value) { column.maxWidth = value } override var prefWidth: Double get() = column.prefWidth set(value) { column.prefWidth = value } override val properties = column.properties override val width: Double get() = column.width override val minWidthProperty get() = column.minWidthProperty() override val maxWidthProperty get() = column.maxWidthProperty() override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TornadoFxNormalTableColumn if (column != other.column) return false return true } override fun hashCode(): Int { return column.hashCode() } }
apache-2.0
b0e49177bcf2edfb4458bd70a7d7d57e
28.114583
117
0.650089
4.920775
false
false
false
false
androidx/androidx
graphics/graphics-core/src/main/java/androidx/graphics/surface/SurfaceControlImpl.kt
3
15365
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.graphics.surface import android.graphics.Rect import android.graphics.Region import android.hardware.HardwareBuffer import android.os.Build import android.view.AttachedSurfaceControl import android.view.Surface import android.view.SurfaceControl import android.view.SurfaceView import androidx.annotation.RequiresApi import androidx.graphics.lowlatency.SyncFenceCompat import androidx.graphics.lowlatency.SyncFenceImpl import androidx.graphics.surface.SurfaceControlCompat.TransactionCommittedListener import java.util.concurrent.Executor /** * Interface that abstracts the implementation of the [SurfaceControl] APIs depending on API level */ internal interface SurfaceControlImpl { /** * Check whether this instance points to a valid layer with the system-compositor. * For example this may be false if the layer was released ([release]). */ fun isValid(): Boolean /** * Release the local reference to the server-side surface. The [Surface] may continue to exist * on-screen as long as its parent continues to exist. To explicitly remove a [Surface] from the * screen use [Transaction.reparent] with a null-parent. After release, [isValid] will return * false and other methods will throw an exception. Always call [release] when you are done with * a [SurfaceControlCompat] instance. */ fun release() /** * Interface that abstracts the implementation of [SurfaceControl.Builder] APIs depending on * API level */ interface Builder { /** * Set a parent [Surface] from the provided [SurfaceView] for our new * [SurfaceControlImpl]. Child surfaces are constrained to the onscreen region of their * parent. Furthermore they stack relatively in Z order, and inherit the transformation of * the parent. * @param surfaceView Target [SurfaceView] used to provide the [Surface] this * [SurfaceControlImpl] is associated with. */ fun setParent(surfaceView: SurfaceView): Builder /** * Set a debugging-name for the [SurfaceControlImpl]. * @param name Debugging name configured on the [SurfaceControlCompat] instance. */ fun setName(name: String): Builder /** * Construct a new [SurfaceControlImpl] with the set parameters. * The builder remains valid after the [SurfaceControlImpl] instance is created. */ fun build(): SurfaceControlImpl } @JvmDefaultWithCompatibility @RequiresApi(Build.VERSION_CODES.KITKAT) interface Transaction : AutoCloseable { /** * Indicates whether the surface must be considered opaque, even if its pixel format is * set to translucent. This can be useful if an application needs full RGBA 8888 support for * instance but will still draw every pixel opaque. * This flag only determines whether opacity will be sampled from the alpha channel. * Plane-alpha from calls to setAlpha() can still result in blended composition regardless * of the opaque setting. Combined effects are (assuming a buffer format with an alpha * channel): * * OPAQUE + alpha(1.0) == opaque composition * OPAQUE + alpha(0.x) == blended composition * OPAQUE + alpha(0.0) == no composition * !OPAQUE + alpha(1.0) == blended composition * !OPAQUE + alpha(0.x) == blended composition * !OPAQUE + alpha(0.0) == no composition * If the underlying buffer lacks an alpha channel, it is as if setOpaque(true) were set * automatically. * * @param surfaceControl Target [SurfaceControlCompat] to change the opaque flag for * @param isOpaque Flag indicating if the [SurfaceControlCompat] should be fully opaque or * transparent */ fun setOpaque(surfaceControl: SurfaceControlImpl, isOpaque: Boolean): Transaction /** * Sets the visibility of a given Layer and it's sub-tree. * @param surfaceControl Target [SurfaceControlImpl] */ fun setVisibility(surfaceControl: SurfaceControlImpl, visible: Boolean): Transaction /** * Re-parents a given [SurfaceControlImpl] to a new parent. Children inherit transform * (position, scaling) crop, visibility, and Z-ordering from their parents, as if the * children were pixels within the parent [Surface]. * @param surfaceControl Target [SurfaceControlImpl] instance to reparent * @param newParent Parent [SurfaceControlImpl] that the target [SurfaceControlCompat] * instance is added to. This can be null indicating that the target [SurfaceControlCompat] * should be removed from the scene. */ fun reparent( surfaceControl: SurfaceControlImpl, newParent: SurfaceControlImpl? ): Transaction /** * Re-parents a given [SurfaceControlImpl] to be a child of the [AttachedSurfaceControl]. * Children inherit transform (position, scaling) crop, visibility, and Z-ordering from * their parents, as if the children were pixels within the parent [Surface]. * @param surfaceControl Target [SurfaceControlImpl] instance to reparent * @param attachedSurfaceControl [AttachedSurfaceControl] instance that acts as the new * parent of the provided [SurfaceControlImpl] instance. */ @RequiresApi(Build.VERSION_CODES.TIRAMISU) fun reparent( surfaceControl: SurfaceControlImpl, attachedSurfaceControl: AttachedSurfaceControl ): Transaction /** * Updates the [HardwareBuffer] displayed for the [SurfaceControlImpl]. Note that the * buffer must be allocated with [HardwareBuffer.USAGE_COMPOSER_OVERLAY] as well as * [HardwareBuffer.USAGE_GPU_SAMPLED_IMAGE] as the surface control might be composited using * either an overlay or using the GPU. A presentation fence may be passed to improve * performance by allowing the buffer to complete rendering while it is waiting for the * transaction to be applied. For example, if the buffer is being produced by rendering with * OpenGL ES then a fence created with the eglDupNativeFenceFDANDROID EGL extension API * can be used to allow the GPU rendering to be concurrent with the transaction. * The compositor will wait for the fence to be signaled before the buffer is displayed. * If multiple buffers are set as part of the same transaction, the presentation fences of * all of them must signal before any buffer is displayed. That is, the entire transaction * is delayed until all presentation fences have signaled, ensuring the transaction remains * consistent. * * @param surfaceControl Target [SurfaceControlImpl] to configure the provided buffer. * @param buffer [HardwareBuffer] instance to be rendered by the [SurfaceControlImpl] * instance. * @param fence Optional [SyncFenceCompat] that serves as the presentation fence. If set, * the [SurfaceControlCompat.Transaction] will not apply until the fence signals. * @param releaseCallback Optional callback invoked when the buffer is ready for re-use * after being presented to the display. */ fun setBuffer( surfaceControl: SurfaceControlImpl, buffer: HardwareBuffer, fence: SyncFenceImpl? = null, releaseCallback: (() -> Unit)? = null ): Transaction /** * Set the Z-order for a given [SurfaceControlImpl], relative to it's siblings. * If two siblings share the same Z order the ordering is undefined. * [Surface]s with a negative Z will be placed below the parent [Surface]. */ fun setLayer( surfaceControl: SurfaceControlImpl, z: Int ): Transaction /** * Request to add a [SurfaceControlCompat.TransactionCommittedListener]. The callback is * invoked when transaction is applied and the updates are ready to be presented. Once * applied, any callbacks added before the commit will be cleared from the Transaction. * This callback does not mean buffers have been released! It simply means that any new * transactions applied will not overwrite the transaction for which we are receiving a * callback and instead will be included in the next frame. * If you are trying to avoid dropping frames (overwriting transactions), and unable to * use timestamps (Which provide a more efficient solution), then this method provides a * method to pace your transaction application. * @param executor [Executor] to provide the thread the callback is invoked on. * @param listener [TransactionCommittedListener] instance that is invoked when the * transaction has been committed. */ @RequiresApi(Build.VERSION_CODES.S) fun addTransactionCommittedListener( executor: Executor, listener: TransactionCommittedListener ): Transaction /** * Updates the region for the content on this surface updated in this transaction. The * damage region is the area of the buffer that has changed since the previously * sent buffer. This can be used to reduce the amount of recomposition that needs to * happen when only a small region of the buffer is being updated, such as for a small * blinking cursor or a loading indicator. * @param surfaceControl Target [SurfaceControlImpl] to set damage region of. * @param region The region to be set. If null, the entire buffer is assumed dirty. This is * equivalent to not setting a damage region at all. */ fun setDamageRegion( surfaceControl: SurfaceControlImpl, region: Region? ): Transaction /** * Set the alpha for a given surface. If the alpha is non-zero the SurfaceControl will * be blended with the Surfaces under it according to the specified ratio. * @param surfaceControl Target [SurfaceControlImpl] to set the alpha of. * @param alpha The alpha to set. Value is between 0.0 and 1.0 inclusive. */ fun setAlpha( surfaceControl: SurfaceControlImpl, alpha: Float ): Transaction /** * Bounds the surface and its children to the bounds specified. Size of the surface * will be ignored and only the crop and buffer size will be used to determine the * bounds of the surface. If no crop is specified and the surface has no buffer, * the surface bounds is only constrained by the size of its parent bounds. * * @param surfaceControl The [SurfaceControlImpl] to apply the crop to. This value * cannot be null. * * @param crop Bounds of the crop to apply. This value can be null. * * @throws IllegalArgumentException if crop is not a valid rectangle. */ fun setCrop( surfaceControl: SurfaceControlImpl, crop: Rect? ): Transaction /** * Sets the SurfaceControl to the specified position relative to the parent SurfaceControl * * @param surfaceControl The [SurfaceControlImpl] to change position. This value cannot * be null * * @param x the X position * * @param y the Y position */ fun setPosition( surfaceControl: SurfaceControlImpl, x: Float, y: Float ): Transaction /** * Sets the SurfaceControl to the specified scale with (0, 0) as the * center point of the scale. * * @param surfaceControl The [SurfaceControlImpl] to change scale. This value cannot * be null. * * @param scaleX the X scale * * @param scaleY the Y scale */ fun setScale( surfaceControl: SurfaceControlImpl, scaleX: Float, scaleY: Float ): Transaction /** * Sets the buffer transform that should be applied to the current buffer * * @param surfaceControl the [SurfaceControlImpl] to update. This value cannot be null. * * @param transformation The transform to apply to the buffer. Value is * [SurfaceControlCompat.BUFFER_TRANSFORM_IDENTITY], * [SurfaceControlCompat.BUFFER_TRANSFORM_MIRROR_HORIZONTAL], * [SurfaceControlCompat.BUFFER_TRANSFORM_MIRROR_VERTICAL], * [SurfaceControlCompat.BUFFER_TRANSFORM_ROTATE_90], * [SurfaceControlCompat.BUFFER_TRANSFORM_ROTATE_180], * [SurfaceControlCompat.BUFFER_TRANSFORM_ROTATE_270], * [SurfaceControlCompat.BUFFER_TRANSFORM_MIRROR_HORIZONTAL] | * [SurfaceControlCompat.BUFFER_TRANSFORM_ROTATE_90], or * [SurfaceControlCompat.BUFFER_TRANSFORM_MIRROR_VERTICAL] | * [SurfaceControlCompat.BUFFER_TRANSFORM_ROTATE_90] */ fun setBufferTransform( surfaceControl: SurfaceControlImpl, @SurfaceControlCompat.Companion.BufferTransform transformation: Int ): Transaction /** * Commit the transaction, clearing it's state, and making it usable as a new transaction. * This will not release any resources and [SurfaceControlImpl.Transaction.close] must be * called to release the transaction. */ fun commit() /** * Release the native transaction object, without committing it. */ override fun close() /** * Consume the passed in transaction, and request the View hierarchy to apply it atomically * with the next draw. This transaction will be merged with the buffer transaction from the * ViewRoot and they will show up on-screen atomically synced. This will not cause a draw to * be scheduled, and if there are no other changes to the View hierarchy you may need to * call View.invalidate() * @param attachedSurfaceControl [AttachedSurfaceControl] associated with the ViewRoot that * will apply the provided transaction on the next draw pass */ @RequiresApi(Build.VERSION_CODES.TIRAMISU) fun commitTransactionOnDraw(attachedSurfaceControl: AttachedSurfaceControl) } }
apache-2.0
daa82fb8aba63e0668af1c6c8a3c04cf
45.990826
100
0.66632
5.022883
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListState.kt
3
17828
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState import androidx.compose.foundation.lazy.layout.animateScrollToItem import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.OnGloballyPositionedModifier import androidx.compose.ui.layout.Remeasurement import androidx.compose.ui.layout.RemeasurementModifier import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import kotlin.math.abs /** * Creates a [LazyListState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param initialFirstVisibleItemIndex the initial value for [LazyListState.firstVisibleItemIndex] * @param initialFirstVisibleItemScrollOffset the initial value for * [LazyListState.firstVisibleItemScrollOffset] */ @Composable fun rememberLazyListState( initialFirstVisibleItemIndex: Int = 0, initialFirstVisibleItemScrollOffset: Int = 0 ): LazyListState { return rememberSaveable(saver = LazyListState.Saver) { LazyListState( initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset ) } } /** * A state object that can be hoisted to control and observe scrolling. * * In most cases, this will be created via [rememberLazyListState]. * * @param firstVisibleItemIndex the initial value for [LazyListState.firstVisibleItemIndex] * @param firstVisibleItemScrollOffset the initial value for * [LazyListState.firstVisibleItemScrollOffset] */ @OptIn(ExperimentalFoundationApi::class) @Stable class LazyListState constructor( firstVisibleItemIndex: Int = 0, firstVisibleItemScrollOffset: Int = 0 ) : ScrollableState { /** * The holder class for the current scroll position. */ private val scrollPosition = LazyListScrollPosition(firstVisibleItemIndex, firstVisibleItemScrollOffset) private val animateScrollScope = LazyListAnimateScrollScope(this) /** * The index of the first item that is visible. * * Note that this property is observable and if you use it in the composable function it will * be recomposed on every change causing potential performance issues. * * If you want to run some side effects like sending an analytics event or updating a state * based on this value consider using "snapshotFlow": * @sample androidx.compose.foundation.samples.UsingListScrollPositionForSideEffectSample * * If you need to use it in the composition then consider wrapping the calculation into a * derived state in order to only have recompositions when the derived value changes: * @sample androidx.compose.foundation.samples.UsingListScrollPositionInCompositionSample */ val firstVisibleItemIndex: Int get() = scrollPosition.index.value /** * The scroll offset of the first visible item. Scrolling forward is positive - i.e., the * amount that the item is offset backwards. * * Note that this property is observable and if you use it in the composable function it will * be recomposed on every scroll causing potential performance issues. * @see firstVisibleItemIndex for samples with the recommended usage patterns. */ val firstVisibleItemScrollOffset: Int get() = scrollPosition.scrollOffset /** Backing state for [layoutInfo] */ private val layoutInfoState = mutableStateOf<LazyListLayoutInfo>(EmptyLazyListLayoutInfo) /** * The object of [LazyListLayoutInfo] calculated during the last layout pass. For example, * you can use it to calculate what items are currently visible. * * Note that this property is observable and is updated after every scroll or remeasure. * If you use it in the composable function it will be recomposed on every change causing * potential performance issues including infinity recomposition loop. * Therefore, avoid using it in the composition. * * If you want to run some side effects like sending an analytics event or updating a state * based on this value consider using "snapshotFlow": * @sample androidx.compose.foundation.samples.UsingListLayoutInfoForSideEffectSample */ val layoutInfo: LazyListLayoutInfo get() = layoutInfoState.value /** * [InteractionSource] that will be used to dispatch drag events when this * list is being dragged. If you want to know whether the fling (or animated scroll) is in * progress, use [isScrollInProgress]. */ val interactionSource: InteractionSource get() = internalInteractionSource internal val internalInteractionSource: MutableInteractionSource = MutableInteractionSource() /** * The amount of scroll to be consumed in the next layout pass. Scrolling forward is negative * - that is, it is the amount that the items are offset in y */ internal var scrollToBeConsumed = 0f private set /** * Needed for [animateScrollToItem]. Updated on every measure. */ internal var density: Density by mutableStateOf(Density(1f, 1f)) /** * The ScrollableController instance. We keep it as we need to call stopAnimation on it once * we reached the end of the list. */ private val scrollableState = ScrollableState { -onScroll(-it) } /** * Only used for testing to confirm that we're not making too many measure passes */ /*@VisibleForTesting*/ internal var numMeasurePasses: Int = 0 private set /** * Only used for testing to disable prefetching when needed to test the main logic. */ /*@VisibleForTesting*/ internal var prefetchingEnabled: Boolean = true /** * The index scheduled to be prefetched (or the last prefetched index if the prefetch is done). */ private var indexToPrefetch = -1 /** * The handle associated with the current index from [indexToPrefetch]. */ private var currentPrefetchHandle: LazyLayoutPrefetchState.PrefetchHandle? = null /** * Keeps the scrolling direction during the previous calculation in order to be able to * detect the scrolling direction change. */ private var wasScrollingForward = false /** * The [Remeasurement] object associated with our layout. It allows us to remeasure * synchronously during scroll. */ internal var remeasurement: Remeasurement? by mutableStateOf(null) private set /** * The modifier which provides [remeasurement]. */ internal val remeasurementModifier = object : RemeasurementModifier { override fun onRemeasurementAvailable(remeasurement: Remeasurement) { [email protected] = remeasurement } } /** * Provides a modifier which allows to delay some interactions (e.g. scroll) * until layout is ready. */ internal val awaitLayoutModifier = AwaitFirstLayoutModifier() internal var placementAnimator by mutableStateOf<LazyListItemPlacementAnimator?>(null) /** * Constraints passed to the prefetcher for premeasuring the prefetched items. */ internal var premeasureConstraints by mutableStateOf(Constraints()) /** * Instantly brings the item at [index] to the top of the viewport, offset by [scrollOffset] * pixels. * * @param index the index to which to scroll. Must be non-negative. * @param scrollOffset the offset that the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun scrollToItem( /*@IntRange(from = 0)*/ index: Int, scrollOffset: Int = 0 ) { scroll { snapToItemIndexInternal(index, scrollOffset) } } internal fun snapToItemIndexInternal(index: Int, scrollOffset: Int) { scrollPosition.requestPosition(DataIndex(index), scrollOffset) // placement animation is not needed because we snap into a new position. placementAnimator?.reset() remeasurement?.forceRemeasure() } /** * Call this function to take control of scrolling and gain the ability to send scroll events * via [ScrollScope.scrollBy]. All actions that change the logical scroll position must be * performed within a [scroll] block (even if they don't call any other methods on this * object) in order to guarantee that mutual exclusion is enforced. * * If [scroll] is called from elsewhere, this will be canceled. */ override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { awaitLayoutModifier.waitForFirstLayout() scrollableState.scroll(scrollPriority, block) } override fun dispatchRawDelta(delta: Float): Float = scrollableState.dispatchRawDelta(delta) override val isScrollInProgress: Boolean get() = scrollableState.isScrollInProgress override var canScrollForward: Boolean by mutableStateOf(false) private set override var canScrollBackward: Boolean by mutableStateOf(false) private set // TODO: Coroutine scrolling APIs will allow this to be private again once we have more // fine-grained control over scrolling /*@VisibleForTesting*/ internal fun onScroll(distance: Float): Float { if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) { return 0f } check(abs(scrollToBeConsumed) <= 0.5f) { "entered drag with non-zero pending scroll: $scrollToBeConsumed" } scrollToBeConsumed += distance // scrollToBeConsumed will be consumed synchronously during the forceRemeasure invocation // inside measuring we do scrollToBeConsumed.roundToInt() so there will be no scroll if // we have less than 0.5 pixels if (abs(scrollToBeConsumed) > 0.5f) { val preScrollToBeConsumed = scrollToBeConsumed remeasurement?.forceRemeasure() if (prefetchingEnabled) { notifyPrefetch(preScrollToBeConsumed - scrollToBeConsumed) } } // here scrollToBeConsumed is already consumed during the forceRemeasure invocation if (abs(scrollToBeConsumed) <= 0.5f) { // We consumed all of it - we'll hold onto the fractional scroll for later, so report // that we consumed the whole thing return distance } else { val scrollConsumed = distance - scrollToBeConsumed // We did not consume all of it - return the rest to be consumed elsewhere (e.g., // nested scrolling) scrollToBeConsumed = 0f // We're not consuming the rest, give it back return scrollConsumed } } private fun notifyPrefetch(delta: Float) { if (!prefetchingEnabled) { return } val info = layoutInfo if (info.visibleItemsInfo.isNotEmpty()) { val scrollingForward = delta < 0 val indexToPrefetch = if (scrollingForward) { info.visibleItemsInfo.last().index + 1 } else { info.visibleItemsInfo.first().index - 1 } if (indexToPrefetch != this.indexToPrefetch && indexToPrefetch in 0 until info.totalItemsCount ) { if (wasScrollingForward != scrollingForward) { // the scrolling direction has been changed which means the last prefetched // is not going to be reached anytime soon so it is safer to dispose it. // if this item is already visible it is safe to call the method anyway // as it will be no-op currentPrefetchHandle?.cancel() } this.wasScrollingForward = scrollingForward this.indexToPrefetch = indexToPrefetch currentPrefetchHandle = prefetchState.schedulePrefetch( indexToPrefetch, premeasureConstraints ) } } } private fun cancelPrefetchIfVisibleItemsChanged(info: LazyListLayoutInfo) { if (indexToPrefetch != -1 && info.visibleItemsInfo.isNotEmpty()) { val expectedPrefetchIndex = if (wasScrollingForward) { info.visibleItemsInfo.last().index + 1 } else { info.visibleItemsInfo.first().index - 1 } if (indexToPrefetch != expectedPrefetchIndex) { indexToPrefetch = -1 currentPrefetchHandle?.cancel() currentPrefetchHandle = null } } } internal val prefetchState = LazyLayoutPrefetchState() /** * Animate (smooth scroll) to the given item. * * @param index the index to which to scroll. Must be non-negative. * @param scrollOffset the offset that the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun animateScrollToItem( /*@IntRange(from = 0)*/ index: Int, scrollOffset: Int = 0 ) { animateScrollScope.animateScrollToItem(index, scrollOffset) } /** * Updates the state with the new calculated scroll position and consumed scroll. */ internal fun applyMeasureResult(result: LazyListMeasureResult) { scrollPosition.updateFromMeasureResult(result) scrollToBeConsumed -= result.consumedScroll layoutInfoState.value = result canScrollForward = result.canScrollForward canScrollBackward = (result.firstVisibleItem?.index ?: 0) != 0 || result.firstVisibleItemScrollOffset != 0 numMeasurePasses++ cancelPrefetchIfVisibleItemsChanged(result) } /** * When the user provided custom keys for the items we can try to detect when there were * items added or removed before our current first visible item and keep this item * as the first visible one even given that its index has been changed. */ internal fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyListItemProvider) { scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider) } companion object { /** * The default [Saver] implementation for [LazyListState]. */ val Saver: Saver<LazyListState, *> = listSaver( save = { listOf(it.firstVisibleItemIndex, it.firstVisibleItemScrollOffset) }, restore = { LazyListState( firstVisibleItemIndex = it[0], firstVisibleItemScrollOffset = it[1] ) } ) } } private object EmptyLazyListLayoutInfo : LazyListLayoutInfo { override val visibleItemsInfo = emptyList<LazyListItemInfo>() override val viewportStartOffset = 0 override val viewportEndOffset = 0 override val totalItemsCount = 0 override val viewportSize = IntSize.Zero override val orientation = Orientation.Vertical override val reverseLayout = false override val beforeContentPadding = 0 override val afterContentPadding = 0 } internal class AwaitFirstLayoutModifier : OnGloballyPositionedModifier { private var wasPositioned = false private var continuation: Continuation<Unit>? = null suspend fun waitForFirstLayout() { if (!wasPositioned) { val oldContinuation = continuation suspendCoroutine<Unit> { continuation = it } oldContinuation?.resume(Unit) } } override fun onGloballyPositioned(coordinates: LayoutCoordinates) { if (!wasPositioned) { wasPositioned = true continuation?.resume(Unit) continuation = null } } }
apache-2.0
cd177c69ebcb66016e28c82f987bb938
38.62
99
0.692282
5.181052
false
false
false
false
androidx/androidx
lifecycle/lifecycle-livedata-core-ktx/src/test/java/androidx/lifecycle/LiveDataTest.kt
3
1491
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.lifecycle import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.testing.TestLifecycleOwner import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.Rule import org.junit.Test @Suppress("DEPRECATION") class LiveDataTest { @get:Rule val mInstantTaskExecutorRule = InstantTaskExecutorRule() @Test fun observe() { @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) val lifecycleOwner = TestLifecycleOwner(coroutineDispatcher = UnconfinedTestDispatcher()) val liveData = MutableLiveData<String>() var value = "" liveData.observe<String>(lifecycleOwner) { newValue -> value = newValue } liveData.value = "261" assertThat(value).isEqualTo("261") } }
apache-2.0
8f312adb666a2158a3b8a08800e0a87e
31.413043
97
0.732394
4.718354
false
true
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/PowerRecord.kt
3
5650
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.aggregate.AggregateMetric import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.AVERAGE import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.MAXIMUM import androidx.health.connect.client.aggregate.AggregateMetric.AggregationType.MINIMUM import androidx.health.connect.client.aggregate.AggregateMetric.Companion.doubleMetric import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Power import androidx.health.connect.client.units.watts import java.time.Instant import java.time.ZoneOffset /** * Captures the power generated by the user, e.g. during cycling or rowing with a power meter. Each * record represents a series of measurements. */ public class PowerRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, override val samples: List<Sample>, override val metadata: Metadata = Metadata.EMPTY, ) : SeriesRecord<PowerRecord.Sample> { init { require(!startTime.isAfter(endTime)) { "startTime must not be after endTime." } } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PowerRecord) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (samples != other.samples) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + samples.hashCode() result = 31 * result + metadata.hashCode() return result } companion object { private const val TYPE = "PowerSeries" private const val POWER_FIELD = "power" private val MAX_POWER = 100_000.watts /** * Metric identifier to retrieve average power from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val POWER_AVG: AggregateMetric<Power> = doubleMetric( dataTypeName = TYPE, aggregationType = AVERAGE, fieldName = POWER_FIELD, mapper = Power::watts, ) /** * Metric identifier to retrieve minimum power from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val POWER_MIN: AggregateMetric<Power> = doubleMetric( dataTypeName = TYPE, aggregationType = MINIMUM, fieldName = POWER_FIELD, mapper = Power::watts, ) /** * Metric identifier to retrieve maximum power from * [androidx.health.connect.client.aggregate.AggregationResult]. */ @JvmField val POWER_MAX: AggregateMetric<Power> = doubleMetric( dataTypeName = TYPE, aggregationType = MAXIMUM, fieldName = POWER_FIELD, mapper = Power::watts, ) } /** * Represents a single measurement of power. For example, using a power meter when exercising on * a stationary bike. * * @param time The point in time when the measurement was taken. * @param power Power generated, in [Power] unit. Valid range: 0-100000 Watts. * * @see PowerRecord */ public class Sample( val time: Instant, val power: Power, ) { init { power.requireNotLess(other = power.zero(), name = "power") power.requireNotMore(other = MAX_POWER, name = "power") } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Sample) return false if (time != other.time) return false if (power != other.power) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = time.hashCode() result = 31 * result + power.hashCode() return result } } }
apache-2.0
4733c0d29e3c2099b7685bac2c2dc1c4
33.876543
100
0.624779
4.720134
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/AddFunctionParametersFix.kt
1
12859
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.searches.ReferencesSearch import org.jetbrains.kotlin.builtins.isKFunctionType import org.jetbrains.kotlin.builtins.isKSuspendFunctionType import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.DiagnosticFactory import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.reflectToRegularFunctionType import org.jetbrains.kotlin.idea.refactoring.changeSignature.* import com.intellij.openapi.application.runReadAction import org.jetbrains.kotlin.idea.util.getDataFlowAwareTypes import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getCall import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker class AddFunctionParametersFix( callElement: KtCallElement, functionDescriptor: FunctionDescriptor, private val kind: Kind ) : ChangeFunctionSignatureFix(callElement, functionDescriptor) { sealed class Kind { object ChangeSignature : Kind() object AddParameterGeneric : Kind() class AddParameter(val argumentIndex: Int) : Kind() } private val argumentIndex: Int? get() = (kind as? Kind.AddParameter)?.argumentIndex private val callElement: KtCallElement? get() = element as? KtCallElement private val typesToShorten = ArrayList<KotlinType>() override fun getText(): String { val callElement = callElement ?: return "" val parameters = functionDescriptor.valueParameters val arguments = callElement.valueArguments val newParametersCnt = arguments.size - parameters.size assert(newParametersCnt > 0) val declarationName = when { isConstructor() -> functionDescriptor.containingDeclaration.name.asString() else -> functionDescriptor.name.asString() } return when (kind) { is Kind.ChangeSignature -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.change.signature.constructor", declarationName) } else { KotlinBundle.message("fix.add.function.parameters.change.signature.function", declarationName) } } is Kind.AddParameterGeneric -> { if (isConstructor()) { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.constructor", newParametersCnt, declarationName) } else { KotlinBundle.message("fix.add.function.parameters.add.parameter.generic.function", newParametersCnt, declarationName) } } is Kind.AddParameter -> { if (isConstructor()) { KotlinBundle.message( "fix.add.function.parameters.add.parameter.constructor", kind.argumentIndex + 1, newParametersCnt, declarationName ) } else { KotlinBundle.message( "fix.add.function.parameters.add.parameter.function", kind.argumentIndex + 1, newParametersCnt, declarationName ) } } } } override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { if (!super.isAvailable(project, editor, file)) return false val callElement = callElement ?: return false // newParametersCnt <= 0: psi for this quickfix is no longer valid val newParametersCnt = callElement.valueArguments.size - functionDescriptor.valueParameters.size if (argumentIndex != null && newParametersCnt != 1) return false return newParametersCnt > 0 } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val callElement = callElement ?: return runChangeSignature(project, editor, functionDescriptor, addParameterConfiguration(), callElement, text) } private fun addParameterConfiguration(): KotlinChangeSignatureConfiguration { return object : KotlinChangeSignatureConfiguration { override fun configure(originalDescriptor: KotlinMethodDescriptor): KotlinMethodDescriptor { val argumentIndex = [email protected] return originalDescriptor.modify(fun(descriptor: KotlinMutableMethodDescriptor) { val callElement = callElement ?: return val arguments = callElement.valueArguments val parameters = functionDescriptor.valueParameters val validator = CollectingNameValidator() val receiverCount = if (descriptor.receiver != null) 1 else 0 if (argumentIndex != null) { parameters.forEach { validator.addName(it.name.asString()) } val argument = arguments[argumentIndex] val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(argumentIndex + receiverCount, parameterInfo) return } val call = callElement.getCall(callElement.analyze()) ?: return for (i in arguments.indices) { val argument = arguments[i] val expression = argument.getArgumentExpression() if (i < parameters.size) { validator.addName(parameters[i].name.asString()) val argumentType = expression?.let { val bindingContext = it.analyze() val smartCasts = bindingContext[BindingContext.SMARTCAST, it] smartCasts?.defaultType ?: smartCasts?.type(call) ?: bindingContext.getType(it) } val parameterType = parameters[i].type if (argumentType != null && !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameterType)) { descriptor.parameters[i + receiverCount].currentTypeInfo = KotlinTypeInfo(false, argumentType) typesToShorten.add(argumentType) } } else { val parameterInfo = getNewParameterInfo( originalDescriptor.baseDescriptor as FunctionDescriptor, argument, validator, ) descriptor.addParameter(parameterInfo) } } }) } override fun performSilently(affectedFunctions: Collection<PsiElement>): Boolean { val onlyFunction = affectedFunctions.singleOrNull() ?: return false return kind != Kind.ChangeSignature && !isConstructor() && !hasOtherUsages(onlyFunction) } } } private fun getNewParameterInfo( functionDescriptor: FunctionDescriptor, argument: ValueArgument, validator: (String) -> Boolean ): KotlinParameterInfo { val name = getNewArgumentName(argument, validator) val expression = argument.getArgumentExpression() val type = (expression?.let { getDataFlowAwareTypes(it).firstOrNull() } ?: functionDescriptor.builtIns.nullableAnyType).let { if (it.isKFunctionType || it.isKSuspendFunctionType) it.reflectToRegularFunctionType() else it } return KotlinParameterInfo(functionDescriptor, -1, name, KotlinTypeInfo(false, null)).apply { currentTypeInfo = KotlinTypeInfo(false, type) originalTypeInfo.type?.let { typesToShorten.add(it) } if (expression != null) defaultValueForCall = expression } } private fun hasOtherUsages(function: PsiElement): Boolean { (function as? PsiNamedElement)?.let { val name = it.name ?: return false val project = runReadAction { it.project } val psiSearchHelper = PsiSearchHelper.getInstance(project) val globalSearchScope = GlobalSearchScope.projectScope(project) val cheapEnoughToSearch = psiSearchHelper.isCheapEnoughToSearch(name, globalSearchScope, null, null) if (cheapEnoughToSearch == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES) return false } return ReferencesSearch.search(function).any { val call = it.element.getParentOfType<KtCallElement>(false) call != null && callElement != call } } private fun isConstructor() = functionDescriptor is ConstructorDescriptor companion object TypeMismatchFactory : KotlinSingleIntentionActionFactoryWithDelegate<KtCallElement, Pair<FunctionDescriptor, Int>>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtCallElement? { val (_, valueArgumentList) = diagnostic.valueArgument() ?: return null return valueArgumentList.getStrictParentOfType() } override fun extractFixData(element: KtCallElement, diagnostic: Diagnostic): Pair<FunctionDescriptor, Int>? { val (valueArgument, valueArgumentList) = diagnostic.valueArgument() ?: return null val arguments = valueArgumentList.arguments + element.lambdaArguments val argumentIndex = arguments.indexOfFirst { it == valueArgument } val context = element.analyze() val functionDescriptor = element.getResolvedCall(context)?.resultingDescriptor as? FunctionDescriptor ?: return null val parameters = functionDescriptor.valueParameters if (arguments.size - 1 != parameters.size) return null if ((arguments - valueArgument).zip(parameters).any { (argument, parameter) -> val argumentType = argument.getArgumentExpression()?.let { context.getType(it) } argumentType == null || !KotlinTypeChecker.DEFAULT.isSubtypeOf(argumentType, parameter.type) }) return null return functionDescriptor to argumentIndex } override fun createFix(originalElement: KtCallElement, data: Pair<FunctionDescriptor, Int>): IntentionAction? { val (functionDescriptor, argumentIndex) = data val parameters = functionDescriptor.valueParameters val arguments = originalElement.valueArguments return if (arguments.size > parameters.size) { AddFunctionParametersFix(originalElement, functionDescriptor, Kind.AddParameter(argumentIndex)) } else { null } } private fun Diagnostic.valueArgument(): Pair<KtValueArgument, KtValueArgumentList>? { val element = DiagnosticFactory.cast( this, Errors.TYPE_MISMATCH, Errors.TYPE_MISMATCH_WARNING, Errors.CONSTANT_EXPECTED_TYPE_MISMATCH, Errors.NULL_FOR_NONNULL_TYPE, ).psiElement val valueArgument = element.getStrictParentOfType<KtValueArgument>() ?: return null val valueArgumentList = valueArgument.getStrictParentOfType<KtValueArgumentList>() ?: return null return valueArgument to valueArgumentList } } }
apache-2.0
b3084edb145baeea0a220fd8e8d44bfa
48.457692
158
0.64414
6.006072
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/learn/lesson/general/refactorings/ExtractMethodCocktailSortLesson.kt
3
3304
// 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 training.learn.lesson.general.refactorings import com.intellij.CommonBundle import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.extractMethod.ExtractMethodHelper import com.intellij.ui.UIBundle import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.LessonsBundle import training.learn.course.KLesson import javax.swing.JDialog class ExtractMethodCocktailSortLesson(private val sample: LessonSample) : KLesson("Extract method", LessonsBundle.message("extract.method.lesson.name")) { override val lessonContent: LessonContext.() -> Unit get() = { prepareSample(sample) val extractMethodDialogTitle = RefactoringBundle.message("extract.method.title") lateinit var startTaskId: TaskContext.TaskId task("ExtractMethod") { startTaskId = taskId text(LessonsBundle.message("extract.method.invoke.action", action(it))) triggerUI().component { dialog: JDialog -> dialog.title == extractMethodDialogTitle } restoreIfModifiedOrMoved(sample) test { actions(it) } } // Now will be open the first dialog val okButtonText = CommonBundle.getOkButtonText() val yesButtonText = CommonBundle.getYesButtonText().dropMnemonic() val replaceFragmentDialogTitle = RefactoringBundle.message("replace.fragment") task { text(LessonsBundle.message("extract.method.start.refactoring", strong(okButtonText))) // Wait until the first dialog will be gone but we st stateCheck { val ui = previous.ui ?: return@stateCheck false !ui.isShowing && insideRefactoring() } restoreByUi(delayMillis = defaultRestoreDelay) test(waitEditorToBeReady = false) { dialog(extractMethodDialogTitle) { button(okButtonText).click() } } } task { text(LessonsBundle.message("extract.method.confirm.several.replaces", strong(yesButtonText))) // Wait until the third dialog triggerUI().component { dialog: JDialog -> dialog.title == replaceFragmentDialogTitle } restoreState(restoreId = startTaskId, delayMillis = defaultRestoreDelay) { !insideRefactoring() } test(waitEditorToBeReady = false) { dialog { button(yesButtonText).click() } } } task { text(LessonsBundle.message("extract.method.second.fragment")) stateCheck { previous.ui?.isShowing?.not() ?: true } test(waitEditorToBeReady = false) { dialog(replaceFragmentDialogTitle) { button(UIBundle.message("replace.prompt.replace.button").dropMnemonic()).click() } } } } private fun insideRefactoring() = Thread.currentThread().stackTrace.any { it.className.contains(ExtractMethodHelper::class.java.simpleName) } override val helpLinks: Map<String, String> get() = mapOf( Pair(LessonsBundle.message("extract.method.help.link"), LessonUtil.getHelpLink("extract-method.html")), ) }
apache-2.0
717fe1e6af0259da2f09b51f5e4291d2
34.913043
140
0.677361
5.044275
false
false
false
false
GunoH/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/autoimport/ExternalSystemProjectNotificationAware.kt
1
3212
// 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.openapi.externalSystem.autoimport import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.observable.properties.ObservableProperty import com.intellij.openapi.project.Project import com.intellij.util.messages.Topic import org.jetbrains.annotations.ApiStatus /** * Bridge between auto-reload backend and notification view about that project is needed to reload. * Notifications can be shown in editor floating toolbar, editor banner, etc. */ @ApiStatus.NonExtendable interface ExternalSystemProjectNotificationAware { /** * Requests to show notifications for reload project that defined by [projectAware] */ fun notificationNotify(projectAware: ExternalSystemProjectAware) /** * Requests to hide all notifications for all projects. */ fun notificationExpire() /** * Requests to hide all notifications for project that defined by [projectId] * @see ExternalSystemProjectAware.projectId */ fun notificationExpire(projectId: ExternalSystemProjectId) /** * Checks that notifications should be shown. */ fun isNotificationVisible(): Boolean /** * Gets list of project ids which should be reloaded. */ fun getSystemIds(): Set<ProjectSystemId> interface Listener { /** * Happens when notification should be shown or hidden. */ fun onNotificationChanged(project: Project) { } } companion object { @JvmField @Topic.AppLevel val TOPIC = Topic.create("ExternalSystemProjectNotificationAware", Listener::class.java) @JvmStatic fun getInstance(project: Project): ExternalSystemProjectNotificationAware = project.getService(ExternalSystemProjectNotificationAware::class.java) /** * Function for simple subscription onto notification change events * @see ExternalSystemProjectNotificationAware.Listener.onNotificationChanged */ fun whenNotificationChanged(project: Project, listener: () -> Unit) = whenNotificationChanged(project, null, listener) fun whenNotificationChanged(project: Project, parentDisposable: Disposable?, listener: () -> Unit) { val aProject = project val messageBus = ApplicationManager.getApplication().messageBus val connection = messageBus.connect(parentDisposable ?: project) connection.subscribe(TOPIC, object : Listener { override fun onNotificationChanged(project: Project) { if (aProject === project) { listener() } } }) } fun isNotificationVisibleProperty(project: Project, systemId: ProjectSystemId): ObservableProperty<Boolean> { return object : ObservableProperty<Boolean> { override fun get() = systemId in getInstance(project).getSystemIds() override fun afterChange(listener: (Boolean) -> Unit, parentDisposable: Disposable) { whenNotificationChanged(project, parentDisposable) { listener(get()) } } } } } }
apache-2.0
690794c82cd702a8062ba764a2304699
34.307692
122
0.730697
5.248366
false
false
false
false
vickychijwani/kotlin-koans-android
app/src/main/code/me/vickychijwani/kotlinkoans/features/viewkoan/KoanCodeFragment.kt
1
2811
package me.vickychijwani.kotlinkoans.features.viewkoan import android.arch.lifecycle.* import android.os.Bundle import android.support.v4.app.Fragment import android.view.* import kotlinx.android.synthetic.main.code_editor.* import me.vickychijwani.kotlinkoans.R import me.vickychijwani.kotlinkoans.data.KoanFile import me.vickychijwani.kotlinkoans.features.common.getSizeDimen import me.vickychijwani.kotlinkoans.util.* class KoanCodeFragment(): Fragment(), Observer<KoanViewModel.KoanData> { companion object { val KEY_FILE_INDEX = "key:file-index" fun newInstance(fileIndex: Int): KoanCodeFragment { val fragment = KoanCodeFragment() fragment.arguments = Bundle() fragment.arguments!!.putInt(KEY_FILE_INDEX, fileIndex) return fragment } } private var mFileIndex: Int = -1 private lateinit var mKoanFile: KoanFile override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { super.onCreateView(inflater, container, savedInstanceState) mFileIndex = arguments?.getInt(KEY_FILE_INDEX) ?: mFileIndex return inflater.inflate(R.layout.fragment_koan_code, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) code_editor.setupForEditing() // assume it's editable, will be updated later code_editor.minHeight = getSizeDimen(context, R.dimen.code_editor_min_height) code_editor.waitForMeasurement { val editorHorizontalPadding = code_padding.paddingStart + code_padding.paddingEnd code_editor.minWidth = getScreenWidth(context) - editorHorizontalPadding } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val vm = ViewModelProviders.of(activity!!).get(KoanViewModel::class.java) vm.liveData.observe(activity as LifecycleOwner, this@KoanCodeFragment) } override fun onChanged(koanData: KoanViewModel.KoanData?) { val koan = koanData?.koan if (koan?.files != null && mFileIndex < koan.files.size) { mKoanFile = koan.files[mFileIndex] showCode() } } private fun showCode() { val koanFile = mKoanFile code_editor.setText(koanFile.contents) if (koanFile.modifiable) { code_editor.enableEditing() } else { code_editor.disableEditing() } } fun getUserCode(): KoanFile? { return if (mKoanFile.modifiable) { mKoanFile.copy(contents = code_editor.text.toString()) } else { null } } }
mit
c990cdb9007a0e0e9a23d849b2ac384e
35.506494
93
0.672714
4.371695
false
false
false
false
GunoH/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/ModuleModelProxyImpl.kt
2
7230
// 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.idea.maven.importing import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.module.ModifiableModuleModel import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleWithNameAlreadyExists import com.intellij.openapi.module.impl.ModulePath import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.util.io.FileUtil import com.intellij.util.PathUtil import com.intellij.util.containers.map2Array import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.getInstance import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModuleEntity import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.VersionedEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.addModuleGroupPathEntity import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.impl.VersionedEntityStorageOnBuilder import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager interface ModuleModelProxy { fun disposeModule(module: Module) fun findModuleByName(name: String): Module? fun newModule(path: String, moduleTypeId: String): Module fun setModuleGroupPath(module: Module, groupPath: Array<String>?) @Throws(ModuleWithNameAlreadyExists::class) fun renameModule(module: Module, moduleName: String) val modules: Array<Module> } class ModuleModelProxyWrapper(val delegate: ModifiableModuleModel) : ModuleModelProxy { override fun disposeModule(module: Module) { delegate.disposeModule(module) } override fun findModuleByName(name: String): Module? { return delegate.findModuleByName(name) } override fun newModule(path: String, moduleTypeId: String): Module { return delegate.newModule(path, moduleTypeId) } override fun setModuleGroupPath(module: Module, groupPath: Array<String>?) { delegate.setModuleGroupPath(module, groupPath) } override fun renameModule(module: Module, moduleName: String) { delegate.renameModule(module, moduleName) } override val modules: Array<Module> get() = delegate.modules } class ModuleModelProxyImpl(private val diff: MutableEntityStorage, private val project: Project) : ModuleModelProxy { private val virtualFileManager: VirtualFileUrlManager = project.getService(VirtualFileUrlManager::class.java) private val versionedStorage: VersionedEntityStorage override fun disposeModule(module: Module) { if (module.project.isDisposed) { //if the project is being disposed now, removing module won't work because WorkspaceModelImpl won't fire events and the module won't be disposed //it looks like this may happen in tests only so it's ok to skip removal of the module since the project will be disposed anyway return } if (module !is ModuleBridge) return val moduleEntity: ModuleEntity = module.findModuleEntity(diff) ?: return //MavenProjectImporterImpl.LOG.error("Could not find module entity to remove by $module"); moduleEntity.dependencies .asSequence() .filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>() .filter { (it.library.tableId as? LibraryTableId.ModuleLibraryTableId)?.moduleId == module.moduleEntityId } .mapNotNull { it.library.resolve(diff) } .forEach { diff.removeEntity(it) } diff.removeEntity(moduleEntity) } override val modules: Array<Module> get() = diff.entities(ModuleEntity::class.java) .map { moduleEntity -> moduleEntity.findModule(diff) } .filterNotNull() .toList() .map2Array { it } override fun findModuleByName(name: String): Module? { return diff.resolve(ModuleId(name))?.findModule(diff) } override fun newModule(path: String, moduleTypeId: String): Module { val systemIndependentPath = FileUtil.toSystemIndependentName(path) val modulePath = ModulePath(systemIndependentPath, null) val name = modulePath.moduleName val source = JpsEntitySourceFactory.createEntitySourceForModule(project, virtualFileManager.fromPath( PathUtil.getParentPath( systemIndependentPath)), ExternalProjectSystemRegistry.getInstance().getSourceById( ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID)) val moduleEntity = ModuleEntity(name, listOf(ModuleDependencyItem.ModuleSourceDependency), source) { type = moduleTypeId } diff.addEntity(moduleEntity) val moduleManager = getInstance(project) val plugins = PluginManagerCore.getPluginSet().getEnabledModules() val module = moduleManager.createModuleInstance(moduleEntity = moduleEntity, versionedStorage = versionedStorage, diff = diff, isNew = true, precomputedExtensionModel = null, plugins = plugins, corePlugin = plugins.firstOrNull { it.pluginId == PluginManagerCore.CORE_ID }) diff.getMutableExternalMapping<Module>("intellij.modules.bridge").addMapping(moduleEntity, module) return module } override fun setModuleGroupPath(module: Module, groupPath: Array<String>?) { if (module !is ModuleBridge) return val moduleEntity = module.findModuleEntity(diff) ?: error("Could not resolve module entity for $module") val moduleGroupEntity = moduleEntity.groupPath val groupPathList = groupPath?.toMutableList() if (moduleGroupEntity?.path != groupPathList) { when { moduleGroupEntity == null && groupPathList != null -> diff.addModuleGroupPathEntity( module = moduleEntity, path = groupPathList, source = moduleEntity.entitySource ) moduleGroupEntity == null && groupPathList == null -> Unit moduleGroupEntity != null && groupPathList == null -> diff.removeEntity(moduleGroupEntity) moduleGroupEntity != null && groupPathList != null -> diff.modifyEntity(ModuleGroupPathEntity.Builder::class.java, moduleGroupEntity) { path = groupPathList } else -> error("Should not be reached") } } } override fun renameModule(module: Module, moduleName: String) { TODO("Not yet implemented") } init { versionedStorage = VersionedEntityStorageOnBuilder(diff) } }
apache-2.0
5daa4c172b8c13181771d197409cb2fe
44.19375
167
0.702351
5.399552
false
false
false
false