repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
appnexus/mobile-sdk-android
tests/AppNexusSDKTestApp/app/src/main/java/appnexus/com/appnexussdktestapp/BannerLazyLoadActivity.kt
1
7877
/* * Copyright 2020 APPNEXUS 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 appnexus.com.appnexussdktestapp import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.test.espresso.idling.CountingIdlingResource import com.appnexus.opensdk.* import com.appnexus.opensdk.utils.Clog import com.appnexus.opensdk.utils.ClogListener class BannerLazyLoadActivity : AppCompatActivity(), AppEventListener { val banner_id: Int = 1234 lateinit var banner: BannerAdView var onAdImpression = false var msg = "" var logListener = LogListener() var idlingResource: CountingIdlingResource = CountingIdlingResource("Banner Load Count", true) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_banner_lazy_load) Clog.registerListener(logListener) banner = BannerAdView(this) banner.appEventListener = this banner.id = banner_id // This is your AppNexus placement ID. banner.placementID = "17058950" // Turning this on so we always get an ad during testing. banner.shouldServePSAs = false // By default ad clicks open in an in-app WebView. banner.clickThroughAction = ANClickThroughAction.OPEN_SDK_BROWSER // Get a 300x50 ad. banner.setAdSize(300, 250) // Resizes the container size to fit the banner ad banner.resizeAdToFitContainer = true // Set up a listener on this ad view that logs events. val adListener: AdListener = object : AdListener { override fun onAdRequestFailed(bav: AdView, errorCode: ResultCode) { if (errorCode == null) { Clog.v("SIMPLEBANNER", "Call to loadAd failed") } else { Clog.v("SIMPLEBANNER", "Ad request failed: $errorCode") } if (!idlingResource.isIdleNow) { idlingResource.decrement() } } override fun onAdLoaded(bav: AdView) { msg = "onAdLoaded" toast() Clog.v("SIMPLEBANNER", "The Ad Loaded!") Handler().postDelayed({ showAd() }, 5000) if (!idlingResource.isIdleNow) { idlingResource.decrement() } } override fun onAdLoaded(nativeAdResponse: NativeAdResponse) { Clog.v("SIMPLEBANNER", "Ad onAdLoaded NativeAdResponse") } override fun onAdExpanded(bav: AdView) { Clog.v("SIMPLEBANNER", "Ad expanded") } override fun onAdCollapsed(bav: AdView) { Clog.v("SIMPLEBANNER", "Ad collapsed") } override fun onAdClicked(bav: AdView) { Clog.v("SIMPLEBANNER", "Ad clicked; opening browser") } override fun onAdClicked(adView: AdView, clickUrl: String) { Clog.v("SIMPLEBANNER", "onAdClicked with click URL") } override fun onLazyAdLoaded(adView: AdView) { msg = "onLazyAdLoaded" toast() if (!idlingResource.isIdleNow) { idlingResource.decrement() } } override fun onAdImpression(adView: AdView?) { msg = "onAdImpression" onAdImpression = true toast() } } banner.adListener = adListener banner.enableLazyLoad() load() } open fun showAd() { removeFromParent() val layout = findViewById<View>(R.id.main_content) as RelativeLayout val layoutParams = RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT ) layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT) banner.layoutParams = layoutParams layout.addView(banner) msg += "Banner Added to the Screen." toast() } open fun removeFromParent() { if (banner.parent != null && banner!!.parent is ViewGroup) { (banner.parent as ViewGroup).removeView(banner) msg = "Banner removed From Parent, " } } open fun load() { // If auto-refresh is enabled (the default), a call to // `FrameLayout.addView()` followed directly by // `BannerAdView.loadAd()` will succeed. However, if // auto-refresh is disabled, the call to // `BannerAdView.loadAd()` needs to be wrapped in a `Handler` // block to ensure that the banner ad view is in the view // hierarchy *before* the call to `loadAd()`. Otherwise the // visibility check in `loadAd()` will fail, and no ad will be // shown. if (idlingResource.isIdleNow) { idlingResource.increment() } onAdImpression = false Handler().postDelayed({ banner!!.loadAd() msg += " loadAd() triggered" toast() }, 0) } fun toggleLazyLoadAndReload(v: View?) { val tv = findViewById<View>(R.id.enableAndReload) as TextView banner.enableLazyLoad() if (banner.isLazyLoadEnabled) { tv.text = "Disable And Reload" msg = "Lazy Load Enabled" } else { tv.text = "Enable And Reload" msg = "Lazy Load Disabled" } load() } fun activateWebview(v: View?) { if (idlingResource.isIdleNow) { idlingResource.increment() } banner.loadLazyAd() msg = "Webview Activated" toast() } open fun toast() { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() Clog.e("LAZYLOAD", msg) } class LogListener : ClogListener() { var logMsg: String = "" override fun onReceiveMessage( level: ClogListener.LOG_LEVEL?, LogTag: String?, message: String? ) { if (LogTag.equals("LAZYLOAD", true)) { logMsg += message + "\n" } } override fun onReceiveMessage( level: ClogListener.LOG_LEVEL?, LogTag: String?, message: String?, tr: Throwable? ) { } override fun getLogLevel(): ClogListener.LOG_LEVEL { return LOG_LEVEL.E } } fun displayBanner(display: Boolean = true) { Handler(Looper.getMainLooper()).post({ if (!display) { banner.visibility = View.GONE } else { banner.visibility = View.VISIBLE } }) } override fun onAppEvent(adView: AdView?, name: String?, data: String?) { Clog.e("LAZYLOAD", name) // appEvent = name } override fun onDestroy() { if (banner != null) { banner.activityOnDestroy() } super.onDestroy() } }
apache-2.0
6674ca8295dd0a6335e581143deb0549
31.825
98
0.579408
4.765275
false
false
false
false
DUCodeWars/TournamentFramework
src/integration-test/java/org/DUCodeWars/competitions/guessnumber/server/packets/TurnPacket.kt
2
2765
package org.DUCodeWars.competitions.guessnumber.server.packets import com.google.gson.JsonArray import com.google.gson.JsonObject import org.DUCodeWars.framework.server.net.packets.JsonSerialiser import org.DUCodeWars.framework.server.net.packets.PacketSer import org.DUCodeWars.framework.server.net.packets.Request import org.DUCodeWars.framework.server.net.packets.Response private val action = "turn" class TurnPS : PacketSer<TurnRequest, TurnResponse>(action) { override val reqSer = TurnReqSer() override val resSer = TurnResSer() } class TurnRequest(val guesses: Map<Int, Int>) : Request<TurnResponse>(action, 1000) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as TurnRequest if (guesses != other.guesses) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + guesses.hashCode() return result } } class TurnReqSer : JsonSerialiser<TurnRequest>() { override fun ser(packet: TurnRequest): JsonObject { val json = JsonObject() val guesses = JsonArray() packet.guesses.forEach { playerId, guess -> val innerJson = JsonObject() innerJson.addProperty("id", playerId) innerJson.addProperty("guess", guess) guesses.add(innerJson) } json.add("guesses", guesses) return json } override fun deserialise(json: JsonObject): TurnRequest { val guesses = json["guesses"].asJsonArray.map { val inner = it.asJsonObject val id = inner["id"].asInt val guess = inner["guess"].asInt return@map id to guess }.toMap() return TurnRequest(guesses) } } class TurnResponse(val guess: Int) : Response(action) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false if (!super.equals(other)) return false other as TurnResponse if (guess != other.guess) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + guess return result } } class TurnResSer : JsonSerialiser<TurnResponse>() { override fun ser(packet: TurnResponse): JsonObject { val json = JsonObject() json.addProperty("guess", packet.guess) return json } override fun deserialise(json: JsonObject): TurnResponse { val guess = json["guess"].asInt return TurnResponse(guess) } }
mit
72c86e91886138bcdf6ace422f2c6aab
27.8125
85
0.642315
4.313573
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/models/parcelable/MealParcelable.kt
1
2847
package com.nlefler.glucloser.a.models.parcelable import android.os.Parcel import android.os.Parcelable import com.nlefler.glucloser.a.models.BloodSugar import com.nlefler.glucloser.a.models.BloodSugarEntity import com.nlefler.glucloser.a.models.BolusPattern import com.nlefler.glucloser.a.models.parcelable.BloodSugarParcelable import com.nlefler.glucloser.a.models.parcelable.BolusEventParcelable import com.nlefler.glucloser.a.models.parcelable.BolusPatternParcelable import java.util.* /** * Created by Nathan Lefler on 12/24/14. */ public class MealParcelable() : Parcelable, BolusEventParcelable { var placeParcelable: PlaceParcelable? = null override var primaryId: String = UUID.randomUUID().toString() override var date: Date = Date() override var bolusPatternParcelable: BolusPatternParcelable? = null override var carbs: Int = 0 override var insulin: Float = 0f override var bloodSugarParcelable: BloodSugarParcelable? = null override var isCorrection: Boolean = false override var foodParcelables: MutableList<FoodParcelable> = ArrayList<FoodParcelable>() /** Parcelable */ protected constructor(parcel: Parcel): this() { primaryId = parcel.readString() placeParcelable = parcel.readParcelable<PlaceParcelable>(PlaceParcelable::class.java.classLoader) carbs = parcel.readInt() insulin = parcel.readFloat() isCorrection = parcel.readInt() != 0 bloodSugarParcelable = parcel.readParcelable<BloodSugarParcelable>(BloodSugarEntity::class.java.classLoader) val time = parcel.readLong() if (time > 0) { date = Date(time) } bolusPatternParcelable = parcel.readParcelable<BolusPatternParcelable>(BolusPatternParcelable::class.java.classLoader) parcel.readTypedList(this.foodParcelables, FoodParcelable.CREATOR) } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(primaryId) dest.writeParcelable(placeParcelable, flags) dest.writeInt(carbs) dest.writeFloat(insulin) dest.writeInt(if (isCorrection) 1 else 0) dest.writeParcelable(bloodSugarParcelable, flags) dest.writeLong(date.time) dest.writeParcelable(bolusPatternParcelable, flags) dest.writeTypedList(this.foodParcelables) } companion object { @JvmField val CREATOR: Parcelable.Creator<MealParcelable> = object : Parcelable.Creator<MealParcelable> { override fun createFromParcel(parcel: Parcel): MealParcelable { return MealParcelable(parcel) } override fun newArray(size: Int): Array<MealParcelable> { return Array(size, {i -> MealParcelable() }) } } } }
gpl-2.0
a4185003f522ba87508079fe762c5497
38.541667
126
0.710573
4.584541
false
false
false
false
mikegehard/kotlinArchiveChannel
src/test/kotlin/io/github/mikegehard/slack/archiveSpec.kt
1
6332
// Notice no package declaration // Experimenting with only exposing a small public interface import io.damo.kspec.Spec import io.github.mikegehard.slack.SlackHost import io.github.mikegehard.slack.archiveChannels import io.github.mikegehard.slack.archiveStaleChannels import org.mockserver.client.server.MockServerClient import org.mockserver.integration.ClientAndServer.startClientAndServer import org.mockserver.model.HttpRequest import org.mockserver.model.HttpResponse import org.mockserver.model.Parameter import org.mockserver.socket.PortFactory import org.mockserver.verify.VerificationTimes import java.time.Duration import java.time.Instant class ArchiveSpec : Spec({ describe("archiving empty channels") { test { val server = "localhost" val port = PortFactory.findFreePort() val mockServer = startClientAndServer(port) val client = MockServerClient(server, port) val slackToken = "some-long-token" val slackHost = SlackHost("$server:$port", false, slackToken) val channelWithMinimumNumberOfMembersId = "channelWithMinimumNumberOfMembersId" val channelWithoutMinimumNumberOfMembersId = "channelWithoutMinimumNumberOfMembersId" val archivingMessage = "Archiving Channel" client.`when`(getChannelsRequestFor(slackToken)).respond(getChannelsResponseFor(channelWithMinimumNumberOfMembersId, channelWithoutMinimumNumberOfMembersId)) archiveChannels(slackHost, 1, archivingMessage) client.verify(archiveRequestFor(channelWithoutMinimumNumberOfMembersId, slackToken)) client.verify(sendMessageTo(channelWithoutMinimumNumberOfMembersId, archivingMessage, slackToken)) client.verify(archiveRequestFor(channelWithMinimumNumberOfMembersId, slackToken), VerificationTimes.exactly(0)) client.verify(sendMessageTo(channelWithMinimumNumberOfMembersId, archivingMessage, slackToken), VerificationTimes.exactly(0)) mockServer.stop() } } describe("archiving stale channels") { test { val server = "localhost" val port = PortFactory.findFreePort() val mockServer = startClientAndServer(port) val client = MockServerClient(server, port) val slackToken = "some-long-token" val slackHost = SlackHost("$server:$port", false, slackToken) val staleChannel = "staleChannel" val freshChannel = "freshChannel" val archivingMessage = "Archiving Channel" client.`when`(getChannelsRequestFor(slackToken)).respond(getChannelsResponseFor(staleChannel, freshChannel)) client.`when`(getChannelInfoRequestFor(slackToken, freshChannel)).respond(getChannelInfoResponseFor(freshChannel, Instant.now().minus(Duration.ofDays(1)))) client.`when`(getChannelInfoRequestFor(slackToken, staleChannel)).respond(getChannelInfoResponseFor(staleChannel, Instant.now().minus(Duration.ofDays(3)))) archiveStaleChannels(slackHost, 2, archivingMessage) client.verify(archiveRequestFor(staleChannel, slackToken)) client.verify(sendMessageTo(staleChannel, archivingMessage, slackToken)) client.verify(archiveRequestFor(freshChannel, slackToken), VerificationTimes.exactly(0)) client.verify(sendMessageTo(freshChannel, archivingMessage, slackToken), VerificationTimes.exactly(0)) mockServer.stop() } } }) private fun getChannelsRequestFor(token: String): HttpRequest = HttpRequest().apply { withMethod("GET") withPath("/api/channels.list") withQueryStringParameters(Parameter("token", token)) withQueryStringParameters(Parameter("exclude_archived", "1")) } private fun getChannelInfoRequestFor(token: String, channelId: String): HttpRequest = HttpRequest().apply { withMethod("GET") withPath("/api/channels.info") withQueryStringParameters(Parameter("token", token)) withQueryStringParameters(Parameter("channel", channelId)) } private fun getChannelsResponseFor(channelWithMembersId: String, channelWithoutMembersId: String) = HttpResponse().apply { withBody(getChannelsJsonFor(channelWithMembersId, channelWithoutMembersId)) } private fun getChannelInfoResponseFor(channelId: String, lastMessageDate: Instant) = HttpResponse().apply { withBody(getChannelJsonFor(channelId, lastMessageDate)) } private fun archiveRequestFor(channelId: String, token: String): HttpRequest = HttpRequest().apply { withMethod("GET") withPath("/api/channels.archive") withQueryStringParameters(Parameter("token", token)) withQueryStringParameters(Parameter("channel", channelId)) } private fun sendMessageTo(channelId: String, text: String, token: String): HttpRequest = HttpRequest().apply { withMethod("GET") withPath("/api/chat.postMessage") withQueryStringParameters(Parameter("token", token)) withQueryStringParameters(Parameter("channel", channelId)) withQueryStringParameter(Parameter("text", text)) } private fun getChannelsJsonFor(channelWithMembersId: String, channelWithoutMembersId: String): String { // make sure you have some extra fields so that you test the annotations // that ignore json attributes that aren't fields in the object return """ { "ok": true, "channels": [ { "id": "$channelWithMembersId", "num_members": 6, "name": "With members" }, { "id": "$channelWithoutMembersId", "num_members": 0, "name": "Without members" } ] } """ } private fun getChannelJsonFor(channelId: String, lastMessageDate: Instant): String { // make sure you have some extra fields so that you test the annotations // that ignore json attributes that aren't fields in the object // TODO: Extract test helper because this is duplicated in SlackChannelSpec.kt return """ { "ok": true, "channel": { "id": "$channelId", "latest": { "type": "message", "user": "U0ENFT3JT", "text": "travel would be no fun", "ts": "${lastMessageDate.toEpochMilli()/1000}" }, "unread_count": 0 } } """ }
mit
79b560603a37cf10e08026299cba626a
39.589744
169
0.705148
4.601744
false
false
false
false
proxer/ProxerLibJava
library/src/main/kotlin/me/proxer/library/enums/UserMediaListSortCriteria.kt
2
772
package me.proxer.library.enums import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Enum holding the available sort types for the user media list. * * @author Ruben Gees */ @JsonClass(generateAdapter = false) enum class UserMediaListSortCriteria { @Json(name = "nameASC") NAME_ASCENDING, @Json(name = "nameDESC") NAME_DESCENDING, @Json(name = "stateNameASC") STATE_NAME_ASCENDING, @Json(name = "stateNameDESC") STATE_NAME_DESCENDING, @Json(name = "changeDateASC") CHANGE_DATE_ASCENDING, @Json(name = "changeDateDESC") CHANGE_DATE_DESCENDING, @Json(name = "stateChangeDateASC") STATE_CHANGE_DATE_ASCENDING, @Json(name = "stateChangeDateDESC") STATE_CHANGE_DATE_DESCENDING }
mit
369639eb4ad39e098a576d049bb6c6d9
19.864865
65
0.690415
3.641509
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/editor/EditorFragment.kt
1
18088
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.editor import android.app.Activity import android.content.Context import android.content.Intent import android.media.MediaScannerConnection import android.net.Uri import android.os.Bundle import android.text.Editable import android.text.Html import android.text.TextWatcher import android.text.format.DateFormat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.Dimension import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.core.content.ContextCompat import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.google.android.material.snackbar.Snackbar import jp.toastkid.article_viewer.article.data.ArticleInsertion import jp.toastkid.lib.AppBarViewModel import jp.toastkid.lib.ContentScrollable import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.FileExtractorFromUri import jp.toastkid.lib.TabListViewModel import jp.toastkid.lib.dialog.ConfirmDialogFragment import jp.toastkid.lib.fragment.CommonFragmentAction import jp.toastkid.lib.intent.GetContentIntentFactory import jp.toastkid.lib.intent.ShareIntentFactory import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.storage.ExternalFileAssignment import jp.toastkid.lib.tab.TabUiFragment import jp.toastkid.lib.view.TextViewColorApplier import jp.toastkid.lib.viewmodel.PageSearcherViewModel import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.AppBarEditorBinding import jp.toastkid.yobidashi.databinding.FragmentEditorBinding import jp.toastkid.yobidashi.editor.load.LoadFromStorageDialogFragment import jp.toastkid.yobidashi.editor.usecase.RestoreContentUseCase import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.libs.speech.SpeechMaker import okio.buffer import okio.sink import okio.source import java.io.File import java.util.Calendar /** * @author toastkidjp */ class EditorFragment : Fragment(), TabUiFragment, CommonFragmentAction, ContentScrollable { private lateinit var binding: FragmentEditorBinding private lateinit var menuBinding: AppBarEditorBinding /** * Preferences wrapper. */ private lateinit var preferenceApplier: PreferenceApplier private val externalFileAssignment = ExternalFileAssignment() private var speechMaker: SpeechMaker? = null /** * Last saved text. */ private lateinit var lastSavedTitle: String /** * File path. */ private var path: String = "" private val contentHolderService = ContentHolderService() /** * Text finder for [EditText]. */ private lateinit var finder: EditTextFinder private var appBarViewModel: AppBarViewModel? = null private var tabListViewModel: TabListViewModel? = null private var contentViewModel: ContentViewModel? = null private var loadAs: ActivityResultLauncher<Intent>? = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } it.data?.data?.let { uri -> readFromFileUri(uri) saveAs() } } private var loadResultLauncher: ActivityResultLauncher<Intent>? = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } it.data?.data?.let { uri -> readFromFileUri(uri) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false) menuBinding = DataBindingUtil.inflate( LayoutInflater.from(context), R.layout.app_bar_editor, container, false ) menuBinding.fragment = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val context = context ?: return preferenceApplier = PreferenceApplier(context) finder = EditTextFinder(binding.editorInput) speechMaker = SpeechMaker(context) binding.editorInput.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(contentEditable: Editable?) { setContentTextLengthCount(context) } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit }) lastSavedTitle = context.getString(R.string.last_saved) activity?.let { activity -> val viewModelProvider = ViewModelProvider(activity) appBarViewModel = viewModelProvider.get(AppBarViewModel::class.java) tabListViewModel = viewModelProvider.get(TabListViewModel::class.java) EditorContextMenuInitializer().invoke(binding.editorInput, speechMaker, viewModelProvider) tabListViewModel ?.tabCount ?.observe(activity, { menuBinding.tabCount.text = it.toString() }) (viewModelProvider.get(PageSearcherViewModel::class.java)).let { viewModel -> var currentWord = "" viewModel.find.observe(viewLifecycleOwner, { if (currentWord != it) { currentWord = it } finder.findDown(currentWord) }) viewModel.upward.observe(viewLifecycleOwner, Observer { if (currentWord != it) { currentWord = it } finder.findUp(currentWord) }) viewModel.downward.observe(viewLifecycleOwner, Observer { if (currentWord != it) { currentWord = it } finder.findDown(currentWord) }) } contentViewModel = viewModelProvider.get(ContentViewModel::class.java) } parentFragmentManager.setFragmentResultListener( "clear_input", viewLifecycleOwner, { _, _ -> clearInput() } ) parentFragmentManager.setFragmentResultListener( "input_text", viewLifecycleOwner, { key, result -> val fileName = result.getString(key) if (fileName.isNullOrBlank()) { return@setFragmentResultListener } assignNewFile(fileName) } ) reload() } fun reload() { if (arguments?.containsKey("path") == true) { path = arguments?.getString("path") ?: "" } if (path.isEmpty()) { clearInput() } else { readFromFile(File(path)) } } override fun onResume() { super.onResume() applySettings() val view = menuBinding.root appBarViewModel?.replace(view) } override fun onPause() { super.onPause() saveIfNeed() } override fun onDetach() { if (path.isNotEmpty()) { saveToFile(path) } speechMaker?.dispose() loadAs?.unregister() loadResultLauncher?.unregister() parentFragmentManager.clearFragmentResultListener("clear_input") parentFragmentManager.clearFragmentResultListener("input_text") parentFragmentManager.clearFragmentResultListener("load_from_storage") super.onDetach() } /** * Apply color and font setting. */ private fun applySettings() { val colorPair = preferenceApplier.colorPair() TextViewColorApplier()( colorPair.fontColor(), menuBinding.save, menuBinding.saveAs, menuBinding.load, menuBinding.loadAs, menuBinding.loadFrom, menuBinding.exportArticleViewer, menuBinding.restore, menuBinding.lastSaved, menuBinding.counter, menuBinding.backup, menuBinding.clear ) menuBinding.tabIcon.setColorFilter(colorPair.fontColor()) menuBinding.tabCount.setTextColor(colorPair.fontColor()) menuBinding.editorMenu.setBackgroundColor(colorPair.bgColor()) binding.editorScroll.setBackgroundColor(preferenceApplier.editorBackgroundColor()) binding.editorInput.setTextColor(preferenceApplier.editorFontColor()) binding.editorInput.setTextSize(Dimension.SP, preferenceApplier.editorFontSize().toFloat()) CursorColorSetter().invoke(binding.editorInput, preferenceApplier.editorCursorColor(ContextCompat.getColor(binding.root.context, R.color.editor_cursor))) binding.editorInput.highlightColor = preferenceApplier.editorHighlightColor(ContextCompat.getColor(binding.root.context, R.color.light_blue_200_dd)) } /** * Set content text length count to binding.counter. * * @param context Context */ private fun setContentTextLengthCount(context: Context) { menuBinding.counter.text = context.getString(R.string.message_character_count, content().length) } fun tabList() { contentViewModel?.switchTabList() } fun openNewTab(): Boolean { tabListViewModel?.openNewTab() return true } /** * Backup current file. */ fun backup() { if (path.isEmpty()) { save() return } val fileName = File(path).nameWithoutExtension + "_backup.txt" saveToFile(externalFileAssignment(binding.root.context, fileName).absolutePath) } fun clear() { ConfirmDialogFragment.show( parentFragmentManager, getString(R.string.title_clear_text), Html.fromHtml( getString(R.string.confirm_clear_all_settings), Html.FROM_HTML_MODE_COMPACT ), "clear_input" ) } /** * Go to top. */ override fun toTop() { moveToIndex(0) } /** * Go to bottom. */ override fun toBottom() { moveToIndex(binding.editorInput.length()) } /** * Move cursor to specified index. * * @param index index of editor. */ private fun moveToIndex(index: Int) { binding.editorInput.requestFocus() binding.editorInput.setSelection(index) } /** * Save current content to file. */ fun save() { if (path.isNotEmpty()) { saveToFile(path) return } InputNameDialogFragment.show(parentFragmentManager) } /** * Save current text as other file. */ fun saveAs() { InputNameDialogFragment.show(parentFragmentManager) } /** * Load text as other file. */ fun loadAs() { loadAs?.launch(GetContentIntentFactory()("text/plain")) } fun loadFromStorage() { parentFragmentManager.setFragmentResultListener( "load_from_storage", viewLifecycleOwner, { key, result -> val file = result[key] as? File ?: return@setFragmentResultListener readFromFileUri(Uri.fromFile(file)) parentFragmentManager.clearFragmentResultListener("load_from_storage") } ) LoadFromStorageDialogFragment().show(parentFragmentManager, "load_from_storage") } fun exportToArticleViewer() { val context = context ?: return ArticleInsertion(context).invoke( if (path.isEmpty()) Calendar.getInstance().time.toString() else path.split("/").last(), content() ) contentViewModel?.snackShort(R.string.done_save) } fun restore() { RestoreContentUseCase( contentHolderService, contentViewModel, binding.editorInput, ::setContentText ).invoke() } /** * Share current content. */ override fun share() { val title = if (path.contains("/")) path.substring(path.lastIndexOf("/") + 1) else path startActivity(ShareIntentFactory()(content(), title)) } /** * Call from fragment's onPause(). */ private fun saveIfNeed() { if (path.isNotEmpty()) { saveToFile(path) } } private fun saveToFile(filePath: String) { val file = File(filePath) if (!file.exists()) { file.createNewFile() } val content = content() contentHolderService.setContent(content) file.sink().use { sink -> sink.buffer().use { bufferedSink -> bufferedSink.writeUtf8(content) } } val context = context ?: return MediaScannerConnection.scanFile( context, arrayOf(filePath), null ) { _, _ -> } if (isVisible) { snackText("${context.getString(R.string.done_save)}: $filePath") } setLastSaved(file.lastModified()) } /** * Load content from file with Storage Access Framework. */ fun load() { loadResultLauncher?.launch(GetContentIntentFactory()("text/plain")) } /** * Read content from file [Uri]. * * @param data [Uri] */ private fun readFromFileUri(data: Uri) { val context = context ?: return FileExtractorFromUri(context, data)?.let { if (it == path) { return } readFromFile(File(it)) } } /** * Read content from [File]. * * @param file [File] */ private fun readFromFile(file: File) { if (!file.exists() || !file.canRead()) { snackText(R.string.message_cannot_read_file) clearPath() return } val text = file.source().use { source -> source.buffer().use { bufferedSource -> bufferedSource.readUtf8() } } setContentText(text) snackText(R.string.done_load) path = file.absolutePath tabListViewModel?.saveEditorTab(file) setLastSaved(file.lastModified()) } /** * Set last modified time. * * @param ms */ private fun setLastSaved(ms: Long) { menuBinding.lastSaved.text = DateFormat.format("$lastSavedTitle HH:mm:ss", ms) } /** * Clear current file path and reset edit-text. */ private fun clearPath() { path = "" clearInput() menuBinding.lastSaved.text = "" } /** * Clear input text. */ private fun clearInput() { setContentText("") } /** * Set content string and set text length. */ private fun setContentText(contentStr: String) { binding.editorInput.setText(contentStr) context?.let { setContentTextLengthCount(it) } contentHolderService.setContent(contentStr) } /** * Return current content. * * @return content [String] */ private fun content(): String = binding.editorInput.text.toString() /** * Assign new file object. * * @param fileName */ fun assignNewFile(fileName: String) { val context = context ?: return var newFile = externalFileAssignment(context, fileName) while (newFile.exists()) { newFile = externalFileAssignment( context, "${newFile.nameWithoutExtension}_.txt" ) } path = newFile.absolutePath tabListViewModel?.saveEditorTab(newFile) saveToFile(path) } /** * Show menu's name. * * @param view [View] (TextView) */ fun showName(view: View): Boolean { if (view is TextView) { Toaster.withAction( view, view.text.toString(), R.string.run, { view.performClick() }, preferenceApplier.colorPair(), Snackbar.LENGTH_LONG ) } return true } /** * Show snackbar with specified id text. * * @param id */ private fun snackText(@StringRes id: Int) { contentViewModel?.snackShort(id) } /** * Show message by [com.google.android.material.snackbar.Snackbar]. * * @param message */ private fun snackText(message: String) { contentViewModel?.snackShort(message) } /** * Insert text to [EditText]. * @param text insert text */ fun insert(text: CharSequence?) { binding.editorInput.text.insert(binding.editorInput.selectionStart, text) } companion object { @LayoutRes private const val LAYOUT_ID = R.layout.fragment_editor } }
epl-1.0
498a11eee5c16bd987f123a55b1e126c
27.576619
161
0.610349
4.98292
false
false
false
false
chenxyu/android-banner
bannerlibrary/src/main/java/com/chenxyu/bannerlibrary/transformer/ScalePageTransformer.kt
1
2920
package com.chenxyu.bannerlibrary.transformer import android.view.View import androidx.viewpager2.widget.ViewPager2 import com.chenxyu.bannerlibrary.BannerView /** * @Author: ChenXingYu * @CreateDate: 2020/4/15 17:47 * @Description: * @Version: 1.0 * @param orientation */ class ScalePageTransformer(private val orientation: Int) : ViewPager2.PageTransformer { companion object { const val MIN_SCALE = 0.9f const val LEFT = 0.8f const val RIGHT = 1 - LEFT } override fun transformPage(page: View, position: Float) { page.apply { val pageWidth = width val pageHeight = height pivotY = (pageHeight / 2).toFloat() pivotX = (pageWidth / 2).toFloat() when (orientation) { BannerView.HORIZONTAL -> { when { position < 0 -> { val scaleFactor = (1 + position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotX = pageWidth * LEFT } position < 1 -> { val scaleFactor = (1 - position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotX = (pageWidth / 2).toFloat() } else -> { val scaleFactor = (1 - position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotX = pageWidth * RIGHT } } } BannerView.VERTICAL -> { when { position < 0 -> { val scaleFactor = (1 + position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotY = pageHeight * LEFT } position < 1 -> { val scaleFactor = (1 - position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotY = (pageHeight / 2).toFloat() } else -> { val scaleFactor = (1 - position) * (1 - MIN_SCALE) + MIN_SCALE scaleX = scaleFactor scaleY = scaleFactor pivotY = pageHeight * RIGHT } } } } } } }
mit
ba77686155cb72da0074bea2f96cd1ac
36.935065
90
0.4
5.816733
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/objects/Torus.kt
1
4162
package net.dinkla.raytracer.objects import net.dinkla.raytracer.hits.Hit import net.dinkla.raytracer.hits.ShadowHit import net.dinkla.raytracer.math.* class Torus(val a: Double, val b: Double) : GeometricObject() { init { boundingBox = BBox(Point3D(-a - b, -b, -a - b), Point3D(a + b, b, a + b)) } override fun hit(ray: Ray, sr: Hit): Boolean { if (!boundingBox.hit(ray)) { return false } val x1 = ray.origin.x val y1 = ray.origin.y val z1 = ray.origin.z val d1 = ray.direction.x val d2 = ray.direction.y val d3 = ray.direction.z val coeffs = DoubleArray(5) val roots = DoubleArray(4) val sumDSqrd = d1 * d1 + d2 * d2 + d3 * d3 val e = x1 * x1 + y1 * y1 + z1 * z1 - a * a - b * b val f = x1 * d1 + y1 * d2 + z1 * d3 val fourASqrd = 4.0 * a * a coeffs[0] = e * e - fourASqrd * (b * b - y1 * y1) coeffs[1] = 4.0 * f * e + 2.0 * fourASqrd * y1 * d2 coeffs[2] = 2.0 * sumDSqrd * e + 4.0 * f * f + fourASqrd * d2 * d2 coeffs[3] = 4.0 * sumDSqrd * f coeffs[4] = sumDSqrd * sumDSqrd val numRealRoots = Polynomials.solveQuartic(coeffs, roots) var intersected = false var t = java.lang.Double.MAX_VALUE if (numRealRoots == 0) { return false } for (j in 0 until numRealRoots) { if (roots[j] > MathUtils.K_EPSILON) { intersected = true if (roots[j] < t) { t = roots[j] } } } if (!intersected) { return false } sr.t = t sr.normal = computeNormal(ray.linear(t)) return true } fun hitF(ray: Ray, sr: Hit): Boolean { if (!boundingBox.hit(ray)) { return false } val x1 = ray.origin.x val y1 = ray.origin.y val z1 = ray.origin.z val d1 = ray.direction.x val d2 = ray.direction.y val d3 = ray.direction.z val coeffs = DoubleArray(5) val roots = DoubleArray(4) val sumDSqrd = d1 * d1 + d2 * d2 + d3 * d3 val e = x1 * x1 + y1 * y1 + z1 * z1 - a * a - b * b val f = x1 * d1 + y1 * d2 + z1 * d3 val fourASqrd = 4.0 * a * a coeffs[0] = e * e - fourASqrd * (b * b - y1 * y1) coeffs[1] = 4.0 * f * e + 2.0 * fourASqrd * y1 * d2 coeffs[2] = 2.0 * sumDSqrd * e + 4.0 * f * f + fourASqrd * d2 * d2 coeffs[3] = 4.0 * sumDSqrd * f coeffs[4] = sumDSqrd * sumDSqrd val numRealRoots = Polynomials.solveQuartic(coeffs, roots) var intersected = false var t = java.lang.Double.MAX_VALUE if (numRealRoots == 0) { return false } for (j in 0 until numRealRoots) { if (roots[j] > MathUtils.K_EPSILON) { intersected = true if (roots[j] < t) { t = roots[j] } } } if (!intersected) { return false } sr.t = t sr.normal = computeNormal(ray.linear(t)) return true } override fun shadowHit(ray: Ray, tmin: ShadowHit): Boolean { return false } private fun computeNormal(p: Point3D): Normal { val paramSquared = a * a + b * b val sumSquared = p.x * p.x + p.y * p.y + p.z * p.z val diff = sumSquared - paramSquared val x = 4.0 * p.x * diff val y = 4.0 * p.y * (diff + 2.0 * a * a) val z = 4.0 * p.z * diff return Normal(x, y, z).normalize() } /* private Normal computeNormal(Point3D p) { final double paramSquared = a * a + b * b; final double sumSquared = p.x * p.x + p.y * p.y + p.z * p.z; final double x = 4.0 * p.x * (sumSquared - paramSquared); final double y = 4.0 * p.y * (sumSquared - paramSquared + 2.0 * a * a); final double z = 4.0 * p.z * (sumSquared - paramSquared); final Normal normal = new Normal(x, y, z).normalize(); return normal; } */ }
apache-2.0
f1256e4cf04204b81a66224229b7dbb4
29.15942
81
0.491591
3.099032
false
false
false
false
maballesteros/vertx3-kotlin-rest-jdbc-tutorial
step05/src/db_utils.kt
1
2503
import io.vertx.core.AsyncResult import io.vertx.core.json.JsonArray import io.vertx.ext.jdbc.JDBCClient import io.vertx.ext.sql.ResultSet import io.vertx.ext.sql.SQLConnection import io.vertx.ext.sql.UpdateResult /** * Created by mike on 15/11/15. */ fun <T : Any> AsyncResult<T>.handle(deferred: Promise.Deferred<T>) = if (succeeded()) { deferred.resolve(result()) } else { cause().printStackTrace() deferred.reject(cause()) } // --------------------------------------------------------------------------- // Promisified Vertx SQL API fun JDBCClient.getConnection(): Promise<SQLConnection> { val deferred = Promise.Deferred<SQLConnection>() getConnection { it.handle(deferred) } return deferred.promise } fun SQLConnection.queryWithParams(query: String, params: JsonArray): Promise<ResultSet> { val deferred = Promise.Deferred<ResultSet>() queryWithParams(query, params) { it.handle(deferred) } return deferred.promise } fun SQLConnection.updateWithParams(query: String, params: JsonArray): Promise<UpdateResult> { val deferred = Promise.Deferred<UpdateResult>() updateWithParams(query, params) { it.handle(deferred) } return deferred.promise } fun SQLConnection.execute(query: String): Promise<Boolean> { val deferred = Promise.Deferred<Boolean>() execute(query) { if (it.succeeded()) deferred.resolve(true) else deferred.reject(it.cause()) } return deferred.promise } // --------------------------------------------------------------------------- // Handy SQL API fun JDBCClient.withConnection<T : Any?>(res: (SQLConnection) -> Promise<T>): Promise<T> = getConnection().pipe { res(it).always { it.close() } } fun JDBCClient.query<T>(query: String, params: List<Any>, rsHandler: (ResultSet) -> List<T>): Promise<List<T>> = withConnection { it.queryWithParams(query, JsonArray(params)).then { rsHandler(it) } } fun JDBCClient.queryOne<T : Any>(query: String, params: List<Any>, rsHandler: (JsonArray) -> T?): Promise<T?> = withConnection { it.queryWithParams(query, JsonArray(params)) .then { rsHandler(it.results.first()) } } fun JDBCClient.update(query: String, params: List<Any>): Promise<Int> = withConnection { it.updateWithParams(query, JsonArray(params)).then { it.updated } } fun JDBCClient.execute(query: String): Promise<Boolean> = withConnection { it.execute(query).then { true } }
apache-2.0
95a24a75731a3818b0d0713e35620e4b
35.275362
112
0.642429
4.037097
false
false
false
false
android/camera-samples
CameraX-MLKit/app/src/main/java/com/example/camerax_mlkit/QrCodeViewModel.kt
1
1682
package com.example.camerax_mlkit import android.content.Intent import android.graphics.Rect import android.net.Uri import android.view.MotionEvent import android.view.View import com.google.mlkit.vision.barcode.common.Barcode /** * A ViewModel for encapsulating the data for a QR Code, including the encoded data, the bounding * box, and the touch behavior on the QR Code. * * As is, this class only handles displaying the QR Code data if it's a URL. Other data types * can be handled by adding more cases of Barcode.TYPE_URL in the init block. */ class QrCodeViewModel(barcode: Barcode) { var boundingRect: Rect = barcode.boundingBox!! var qrContent: String = "" var qrCodeTouchCallback = { v: View, e: MotionEvent -> false} //no-op init { when (barcode.valueType) { Barcode.TYPE_URL -> { qrContent = barcode.url!!.url!! qrCodeTouchCallback = { v: View, e: MotionEvent -> if (e.action == MotionEvent.ACTION_DOWN && boundingRect.contains(e.getX().toInt(), e.getY().toInt())) { val openBrowserIntent = Intent(Intent.ACTION_VIEW) openBrowserIntent.data = Uri.parse(qrContent) v.context.startActivity(openBrowserIntent) } true // return true from the callback to signify the event was handled } } // Add other QR Code types here to handle other types of data, // like Wifi credentials. else -> { qrContent = "Unsupported data type: ${barcode.rawValue.toString()}" } } } }
apache-2.0
c226356a0d67380af6f55c4932613a64
39.071429
123
0.612961
4.509383
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/rawg/game/get/GameGet.kt
1
9463
package uk.co.ourfriendirony.medianotifier.clients.rawg.game.get import com.fasterxml.jackson.annotation.* import java.util.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder( "id", "slug", "name", "name_original", "description", "metacritic", "metacritic_platforms", "released", "tba", "updated", "background_image", "background_image_additional", "website", "rating", "rating_top", "ratings", "reactions", "added", "added_by_status", "playtime", "screenshots_count", "movies_count", "creators_count", "achievements_count", "parent_achievements_count", "reddit_url", "reddit_name", "reddit_description", "reddit_logo", "reddit_count", "twitch_count", "youtube_count", "reviews_text_count", "ratings_count", "suggestions_count", "alternative_names", "metacritic_url", "parents_count", "additions_count", "game_series_count", "user_game", "reviews_count", "saturated_color", "dominant_color", "parent_platforms", "platforms", "stores", "developers", "genres", "tags", "publishers", "esrb_rating", "clip", "description_raw" ) class GameGet { @get:JsonProperty("id") @set:JsonProperty("id") @JsonProperty("id") var id: Int? = null @get:JsonProperty("slug") @set:JsonProperty("slug") @JsonProperty("slug") var slug: String? = null @get:JsonProperty("name") @set:JsonProperty("name") @JsonProperty("name") var name: String? = null @get:JsonProperty("name_original") @set:JsonProperty("name_original") @JsonProperty("name_original") var nameOriginal: String? = null @get:JsonProperty("description") @set:JsonProperty("description") @JsonProperty("description") var description: String? = null @get:JsonProperty("metacritic") @set:JsonProperty("metacritic") @JsonProperty("metacritic") var metacritic: Int? = null @get:JsonProperty("metacritic_platforms") @set:JsonProperty("metacritic_platforms") @JsonProperty("metacritic_platforms") var metacriticPlatforms: List<Any>? = null @get:JsonProperty("released") @set:JsonProperty("released") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @JsonProperty("released") var released: Date? = null @get:JsonProperty("tba") @set:JsonProperty("tba") @JsonProperty("tba") var tba: Boolean? = null @get:JsonProperty("updated") @set:JsonProperty("updated") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss") @JsonProperty("updated") var updated: Date? = null @get:JsonProperty("background_image") @set:JsonProperty("background_image") @JsonProperty("background_image") var backgroundImage: String? = null @get:JsonProperty("background_image_additional") @set:JsonProperty("background_image_additional") @JsonProperty("background_image_additional") var backgroundImageAdditional: String? = null @get:JsonProperty("website") @set:JsonProperty("website") @JsonProperty("website") var website: String? = null @get:JsonProperty("rating") @set:JsonProperty("rating") @JsonProperty("rating") var rating: Double? = null @get:JsonProperty("rating_top") @set:JsonProperty("rating_top") @JsonProperty("rating_top") var ratingTop: Int? = null @get:JsonProperty("ratings") @set:JsonProperty("ratings") @JsonProperty("ratings") var ratings: List<GameGetRating>? = null @get:JsonProperty("reactions") @set:JsonProperty("reactions") @JsonProperty("reactions") var reactions: GameGetReactions? = null @get:JsonProperty("added") @set:JsonProperty("added") @JsonProperty("added") var added: Int? = null @get:JsonProperty("added_by_status") @set:JsonProperty("added_by_status") @JsonProperty("added_by_status") var addedByStatus: GameGetAddedByStatus? = null @get:JsonProperty("playtime") @set:JsonProperty("playtime") @JsonProperty("playtime") var playtime: Int? = null @get:JsonProperty("screenshots_count") @set:JsonProperty("screenshots_count") @JsonProperty("screenshots_count") var screenshotsCount: Int? = null @get:JsonProperty("movies_count") @set:JsonProperty("movies_count") @JsonProperty("movies_count") var moviesCount: Int? = null @get:JsonProperty("creators_count") @set:JsonProperty("creators_count") @JsonProperty("creators_count") var creatorsCount: Int? = null @get:JsonProperty("achievements_count") @set:JsonProperty("achievements_count") @JsonProperty("achievements_count") var achievementsCount: Int? = null @get:JsonProperty("parent_achievements_count") @set:JsonProperty("parent_achievements_count") @JsonProperty("parent_achievements_count") var parentAchievementsCount: Int? = null @get:JsonProperty("reddit_url") @set:JsonProperty("reddit_url") @JsonProperty("reddit_url") var redditUrl: String? = null @get:JsonProperty("reddit_name") @set:JsonProperty("reddit_name") @JsonProperty("reddit_name") var redditName: String? = null @get:JsonProperty("reddit_description") @set:JsonProperty("reddit_description") @JsonProperty("reddit_description") var redditDescription: String? = null @get:JsonProperty("reddit_logo") @set:JsonProperty("reddit_logo") @JsonProperty("reddit_logo") var redditLogo: String? = null @get:JsonProperty("reddit_count") @set:JsonProperty("reddit_count") @JsonProperty("reddit_count") var redditCount: Int? = null @get:JsonProperty("twitch_count") @set:JsonProperty("twitch_count") @JsonProperty("twitch_count") var twitchCount: Int? = null @get:JsonProperty("youtube_count") @set:JsonProperty("youtube_count") @JsonProperty("youtube_count") var youtubeCount: Int? = null @get:JsonProperty("reviews_text_count") @set:JsonProperty("reviews_text_count") @JsonProperty("reviews_text_count") var reviewsTextCount: Int? = null @get:JsonProperty("ratings_count") @set:JsonProperty("ratings_count") @JsonProperty("ratings_count") var ratingsCount: Int? = null @get:JsonProperty("suggestions_count") @set:JsonProperty("suggestions_count") @JsonProperty("suggestions_count") var suggestionsCount: Int? = null @get:JsonProperty("alternative_names") @set:JsonProperty("alternative_names") @JsonProperty("alternative_names") var alternativeNames: List<String>? = null @get:JsonProperty("metacritic_url") @set:JsonProperty("metacritic_url") @JsonProperty("metacritic_url") var metacriticUrl: String? = null @get:JsonProperty("parents_count") @set:JsonProperty("parents_count") @JsonProperty("parents_count") var parentsCount: Int? = null @get:JsonProperty("additions_count") @set:JsonProperty("additions_count") @JsonProperty("additions_count") var additionsCount: Int? = null @get:JsonProperty("game_series_count") @set:JsonProperty("game_series_count") @JsonProperty("game_series_count") var gameSeriesCount: Int? = null @get:JsonProperty("user_game") @set:JsonProperty("user_game") @JsonProperty("user_game") var userGame: Any? = null @get:JsonProperty("reviews_count") @set:JsonProperty("reviews_count") @JsonProperty("reviews_count") var reviewsCount: Int? = null @get:JsonProperty("saturated_color") @set:JsonProperty("saturated_color") @JsonProperty("saturated_color") var saturatedColor: String? = null @get:JsonProperty("dominant_color") @set:JsonProperty("dominant_color") @JsonProperty("dominant_color") var dominantColor: String? = null @get:JsonProperty("parent_platforms") @set:JsonProperty("parent_platforms") @JsonProperty("parent_platforms") var parentPlatforms: List<GameGetParentPlatformGroup>? = null @get:JsonProperty("platforms") @set:JsonProperty("platforms") @JsonProperty("platforms") var platforms: List<GameGetPlatformGroup>? = null @get:JsonProperty("stores") @set:JsonProperty("stores") @JsonProperty("stores") var stores: List<GameGetStoreGroup>? = null @get:JsonProperty("developers") @set:JsonProperty("developers") @JsonProperty("developers") var developers: List<GameGetDeveloper>? = null @get:JsonProperty("genres") @set:JsonProperty("genres") @JsonProperty("genres") var genres: List<GameGetGenre>? = null @get:JsonProperty("tags") @set:JsonProperty("tags") @JsonProperty("tags") var tags: List<GameGetTag>? = null @get:JsonProperty("publishers") @set:JsonProperty("publishers") @JsonProperty("publishers") var publishers: List<GameGetPublisher>? = null @get:JsonProperty("esrb_rating") @set:JsonProperty("esrb_rating") @JsonProperty("esrb_rating") var esrbRating: GameGetEsrbRating? = null @get:JsonProperty("clip") @set:JsonProperty("clip") @JsonProperty("clip") var clip: Any? = null @get:JsonProperty("description_raw") @set:JsonProperty("description_raw") @JsonProperty("description_raw") var descriptionRaw: String? = null }
apache-2.0
f1feba13c47d055259bafed99af3e4af
27.166667
83
0.669555
3.959414
false
false
false
false
chrisbanes/tivi
common/ui/compose/src/main/java/app/tivi/common/compose/ui/SortMenuPopup.kt
1
2789
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.tivi.common.compose.ui import androidx.compose.foundation.layout.Box import androidx.compose.material.DropdownMenu import androidx.compose.material.DropdownMenuItem import androidx.compose.material.IconButton import androidx.compose.material.Text 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.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import app.tivi.data.entities.SortOption import app.tivi.common.ui.resources.R as UiR @Composable fun SortMenuPopup( sortOptions: List<SortOption>, onSortSelected: (SortOption) -> Unit, modifier: Modifier = Modifier, currentSortOption: SortOption? = null, content: @Composable () -> Unit ) { Box(modifier) { var sortPopupOpen by remember { mutableStateOf(false) } IconButton( onClick = { sortPopupOpen = true }, content = content ) DropdownMenu( expanded = sortPopupOpen, onDismissRequest = { sortPopupOpen = false } ) { for (sort in sortOptions) { DropdownMenuItem( onClick = { onSortSelected(sort) // Dismiss the popup sortPopupOpen = false } ) { Text( text = when (sort) { SortOption.SUPER_SORT -> stringResource(UiR.string.popup_sort_super) SortOption.ALPHABETICAL -> stringResource(UiR.string.popup_sort_alpha) SortOption.LAST_WATCHED -> stringResource(UiR.string.popup_sort_last_watched) SortOption.DATE_ADDED -> stringResource(UiR.string.popup_sort_date_followed) }, fontWeight = if (sort == currentSortOption) FontWeight.Bold else null ) } } } } }
apache-2.0
6cb844ae2d8dc54b10f89d68a32ebbac
35.697368
105
0.634278
4.743197
false
false
false
false
chrisbanes/tivi
ui/watched/src/main/java/app/tivi/home/watched/WatchedViewModel.kt
1
6418
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.home.watched import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.PagingConfig import androidx.paging.PagingData import androidx.paging.cachedIn import app.tivi.api.UiMessageManager import app.tivi.data.entities.SortOption import app.tivi.data.entities.TiviShow import app.tivi.data.resultentities.WatchedShowEntryWithShow import app.tivi.domain.interactors.ChangeShowFollowStatus import app.tivi.domain.interactors.GetTraktAuthState import app.tivi.domain.interactors.UpdateWatchedShows import app.tivi.domain.observers.ObservePagedWatchedShows import app.tivi.domain.observers.ObserveTraktAuthState import app.tivi.domain.observers.ObserveUserDetails import app.tivi.extensions.combine import app.tivi.trakt.TraktAuthState import app.tivi.util.Logger import app.tivi.util.ObservableLoadingCounter import app.tivi.util.ShowStateSelector import app.tivi.util.collectStatus import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class WatchedViewModel @Inject constructor( private val updateWatchedShows: UpdateWatchedShows, private val changeShowFollowStatus: ChangeShowFollowStatus, private val observePagedWatchedShows: ObservePagedWatchedShows, observeTraktAuthState: ObserveTraktAuthState, private val getTraktAuthState: GetTraktAuthState, observeUserDetails: ObserveUserDetails, private val logger: Logger ) : ViewModel() { private val uiMessageManager = UiMessageManager() private val availableSorts = listOf(SortOption.LAST_WATCHED, SortOption.ALPHABETICAL) private val loadingState = ObservableLoadingCounter() private val showSelection = ShowStateSelector() val pagedList: Flow<PagingData<WatchedShowEntryWithShow>> = observePagedWatchedShows.flow.cachedIn(viewModelScope) private val filter = MutableStateFlow<String?>(null) private val sort = MutableStateFlow(SortOption.LAST_WATCHED) val state: StateFlow<WatchedViewState> = combine( loadingState.observable, showSelection.observeSelectedShowIds(), showSelection.observeIsSelectionOpen(), observeTraktAuthState.flow, observeUserDetails.flow, filter, sort, uiMessageManager.message ) { loading, selectedShowIds, isSelectionOpen, authState, user, filter, sort, message -> WatchedViewState( user = user, authState = authState, isLoading = loading, selectionOpen = isSelectionOpen, selectedShowIds = selectedShowIds, filter = filter, filterActive = !filter.isNullOrEmpty(), availableSorts = availableSorts, sort = sort, message = message ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(), initialValue = WatchedViewState.Empty ) init { observeTraktAuthState(Unit) observeUserDetails(ObserveUserDetails.Params("me")) // When the filter and sort options change, update the data source viewModelScope.launch { filter.collect { updateDataSource() } } viewModelScope.launch { sort.collect { updateDataSource() } } viewModelScope.launch { // When the user logs in, refresh... observeTraktAuthState.flow .filter { it == TraktAuthState.LOGGED_IN } .collect { refresh(false) } } } private fun updateDataSource() { observePagedWatchedShows( ObservePagedWatchedShows.Params( sort = sort.value, filter = filter.value, pagingConfig = PAGING_CONFIG ) ) } fun refresh(fromUser: Boolean = true) { viewModelScope.launch { if (getTraktAuthState.executeSync(Unit) == TraktAuthState.LOGGED_IN) { refreshWatched(fromUser) } } } fun setFilter(filter: String?) { viewModelScope.launch { [email protected](filter) } } fun setSort(sort: SortOption) { viewModelScope.launch { [email protected](sort) } } fun clearSelection() { showSelection.clearSelection() } fun onItemClick(show: TiviShow): Boolean { return showSelection.onItemClick(show) } fun onItemLongClick(show: TiviShow): Boolean { return showSelection.onItemLongClick(show) } fun followSelectedShows() { viewModelScope.launch { changeShowFollowStatus.executeSync( ChangeShowFollowStatus.Params( showSelection.getSelectedShowIds(), ChangeShowFollowStatus.Action.FOLLOW, deferDataFetch = true ) ) } showSelection.clearSelection() } private fun refreshWatched(fromUser: Boolean) { viewModelScope.launch { updateWatchedShows( UpdateWatchedShows.Params(forceRefresh = fromUser) ).collectStatus(loadingState, logger, uiMessageManager) } } fun clearMessage(id: Long) { viewModelScope.launch { uiMessageManager.clearMessage(id) } } companion object { private val PAGING_CONFIG = PagingConfig( pageSize = 16, initialLoadSize = 32 ) } }
apache-2.0
f057ffa98849bba9f9537d24a83ba362
31.744898
92
0.683235
4.888043
false
false
false
false
HerbLuo/shop-api
src/main/java/cn/cloudself/model/UserPublicOfCommentEntity.kt
1
903
package cn.cloudself.model import org.hibernate.annotations.DynamicInsert import javax.persistence.* /** * @author HerbLuo * @version 1.0.0.d */ @Entity @DynamicInsert @Table(name = "user", schema = "shop") data class UserPublicOfCommentEntity ( @get:Id @get:Column(name = "id", nullable = false, updatable = false, insertable = false) var id: Int = 0, @get:Basic @get:Column(name = "nickname", length = 16, updatable = false, insertable = false) var nickname: String? = null, @get:Basic @get:Column(name = "avatar_src", length = 100, updatable = false, insertable = false) var avatarSrc: String? = null, @get:Basic @get:Column(name = "credit") var credit: Int = 0 ) { fun clone(): UserPublicOfCommentEntity { return UserPublicOfCommentEntity(id, nickname, avatarSrc, credit) } }
mit
380e8cd12bf2681c6fd6b5294f9ccfec
24.083333
93
0.624585
3.641129
false
false
false
false
asymmetric-team/secure-messenger-android
repository/src/main/java/com/safechat/repository/RepositoryImpl.kt
1
2955
package com.safechat.repository import android.content.Context import android.preference.PreferenceManager import com.elpassion.android.commons.sharedpreferences.createSharedPrefs import com.safechat.conversation.ConversationRepository import com.safechat.conversation.create.CreateConversationRepository import com.safechat.conversation.select.ConversationsListRepository import com.safechat.conversation.symmetrickey.ExchangeSymmetricKeyRepository import com.safechat.conversation.symmetrickey.post.PostSymmetricKeyRepository import com.safechat.conversation.symmetrickey.retrieve.RetrieveSymmetricKeyRepository import com.safechat.message.Message import com.safechat.register.KeyPairString import com.safechat.register.RegisterRepository class RepositoryImpl(context: Context) : RegisterRepository, ExchangeSymmetricKeyRepository, PostSymmetricKeyRepository, RetrieveSymmetricKeyRepository, ConversationRepository, CreateConversationRepository, ConversationsListRepository { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) override fun isKeySaved(): Boolean { return sharedPreferences.contains(PUBLIC_KEY) && sharedPreferences.contains(PRIVATE_KEY) } override fun saveNewKey(keyPair: KeyPairString) { sharedPreferences.edit() .putString(PUBLIC_KEY, keyPair.publicKey) .putString(PRIVATE_KEY, keyPair.privateKey) .apply() } override fun containsSymmetricKey(otherPublicKey: String): Boolean { return sharedPreferences.contains(otherPublicKey) } override fun saveDecryptedSymmetricKey(otherPublicKey: String, decryptedSymmetricKey: String) { sharedPreferences.edit().putString(otherPublicKey, decryptedSymmetricKey).apply() } override fun getPublicKeyString(): String { return sharedPreferences.getString(PUBLIC_KEY, null) } override fun getPrivateKeyString(): String { return sharedPreferences.getString(PRIVATE_KEY, null) } override fun saveConversationMessage(otherPublicKey: String, message: Message) { val typedSharedPrefs = createSharedPrefs<Map<String, Message>>({ sharedPreferences }) val conversations = typedSharedPrefs.read(CONVERSATIONS) ?: emptyMap() typedSharedPrefs.write(CONVERSATIONS, conversations + (otherPublicKey to message)) } override fun getDecryptedSymmetricKey(otherPublicKey: String): String { return sharedPreferences.getString(otherPublicKey, null) } override fun getConversationsMessages(): Map<String, Message> { val typedSharedPrefs = createSharedPrefs<Map<String, Message>>({ sharedPreferences }) return typedSharedPrefs.read(CONVERSATIONS) ?: emptyMap() } companion object { val PUBLIC_KEY = "public_key" val PRIVATE_KEY = "private_key" val CONVERSATIONS = "conversations" } }
apache-2.0
d52bede6edc58ffe7c8c9c5190fc3825
39.493151
99
0.759052
5.422018
false
false
false
false
GlimpseFramework/glimpse-framework
api/src/test/kotlin/glimpse/test/_Gen.kt
1
899
package glimpse.test import glimpse.* import io.kotlintest.properties.Gen fun Gen.Companion.chooseFloat(min: Int, max: Int) = object : Gen<Float> { val intGen = choose(min, max) override fun generate(): Float = intGen.generate().toFloat() } fun Gen.Companion.angle(floatGen: Gen<Float>) = object : Gen<Angle> { override fun generate(): Angle = floatGen.generate().degrees } fun Gen.Companion.point(floatGen: Gen<Float>) = object : Gen<Point> { override fun generate(): Point = Point(floatGen.generate(), floatGen.generate(), floatGen.generate()) } fun Gen.Companion.vector(floatGen: Gen<Float>) = object : Gen<Vector> { override fun generate(): Vector = Vector(floatGen.generate(), floatGen.generate(), floatGen.generate()) } fun Gen.Companion.matrix(floatGen: Gen<Float>) = object : Gen<Matrix> { override fun generate(): Matrix = Matrix((0..15).map { floatGen.generate() }.toList()) }
apache-2.0
0e038ed262f1915ec547e4c703300790
34.96
104
0.718576
3.379699
false
true
false
false
paintmonkey/foresale-ai
foresale-ai/app/src/main/java/nl/pixelcloud/foresale_ai/ui/fragments/JoinGameFragment.kt
1
3658
package nl.pixelcloud.foresale_ai.ui.fragments import android.os.Bundle import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.NumberPicker import android.widget.TextView import nl.pixelcloud.foresale_ai.R import nl.pixelcloud.foresale_ai.api.Client import nl.pixelcloud.foresale_ai.api.game.request.CreateGameRequest import nl.pixelcloud.foresale_ai.game.GameRunner import nl.pixelcloud.foresale_ai.service.GameEndpoint import nl.pixelcloud.foresale_ai.util.logError import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers /** * Created by Rob Peek on 22/06/16. */ class JoinGameFragment() : Fragment(){ var client: Client? = null var noPlayersPicker : NumberPicker? = null var noBotsPicker : NumberPicker? = null var hashView : TextView? = null // Interface to define communications with the activity. interface onJoinGameListener { fun onGameReady(ready:Boolean) fun onGameJoined() } // Companion methods. companion object { fun newInstance(client:Client) : JoinGameFragment { val fragment = JoinGameFragment() fragment.client = client return fragment; } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root:View = inflater!!.inflate(R.layout.fragment_join_game, container, false); hashView = root.findViewById(R.id.game_hash_text_view) as EditText? hashView!!.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { (activity as onJoinGameListener).onGameReady(s.length == 36) } override fun afterTextChanged(s: Editable) { } }) noPlayersPicker = root.findViewById(R.id.no_player_picker) as NumberPicker; noBotsPicker = root.findViewById(R.id.no_bots_picker) as NumberPicker; // Attach the new game button. val startGame = root.findViewById(R.id.create_game_button); startGame!!.setOnClickListener { view -> createGame(view) } return root } private fun getGameRequest() : CreateGameRequest { val request = CreateGameRequest() request.noBots = noBotsPicker!!.value request.noPlayers = noPlayersPicker!!.value return request } private fun createGame(view: View) { // Create a default game request. val request = getGameRequest() val endpoint: GameEndpoint = client!!.getGameEndpoint() endpoint.createGame(request) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> Snackbar.make(view, resources.getString(R.string.game_created), Snackbar.LENGTH_LONG).setAction("Action", null).show() hashView!!.setText(response.gameId) }, { error -> logError(error.message!!) }) } fun joinGame() { val runner = GameRunner(activity) runner.join("Kotlin", hashView!!.text.toString()) } }
mit
7baca236e1f875c02f27072c9061642f
31.963964
138
0.677693
4.407229
false
false
false
false
envoyproxy/envoy
mobile/library/kotlin/io/envoyproxy/envoymobile/grpc/GRPCStream.kt
2
1841
package io.envoyproxy.envoymobile import java.nio.ByteBuffer import java.nio.ByteOrder /** * A type representing a gRPC stream that is actively transferring data. * * Constructed using `GRPCStreamPrototype`, and used to write to the network. */ class GRPCStream( private val underlyingStream: Stream ) { /** * Send headers over the gRPC stream. * * @param headers Headers to send over the stream. * @param endStream Whether this is a headers-only request. * @return This stream, for chaining syntax. */ fun sendHeaders(headers: GRPCRequestHeaders, endStream: Boolean): GRPCStream { underlyingStream.sendHeaders(headers as RequestHeaders, endStream) return this } /** * Send a protobuf message's binary data over the gRPC stream. * * @param messageData Binary data of a protobuf message to send. * @return This stream, for chaining syntax. */ fun sendMessage(messageData: ByteBuffer): GRPCStream { // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests // Length-Prefixed-Message = Compressed-Flag | Message-Length | Message // Compressed-Flag = 0 / 1, encoded as 1 byte unsigned integer // Message-Length = length of Message, encoded as 4 byte unsigned integer (big endian) // Message = binary representation of protobuf messageData val byteBuffer = ByteBuffer.allocate(GRPC_PREFIX_LENGTH) // Compression flag (1 byte) - 0, not compressed byteBuffer.put(0) // Message length val messageLength = messageData.remaining() byteBuffer.order(ByteOrder.BIG_ENDIAN) byteBuffer.putInt(messageLength) underlyingStream.sendData(byteBuffer) underlyingStream.sendData(messageData) return this } /** * Close this connection. */ fun close() { underlyingStream.close(ByteBuffer.allocate(0)) } }
apache-2.0
9d1afc0a1fd6d82318344b2ccb6c7904
30.20339
90
0.717002
4.301402
false
false
false
false
tipsy/javalin
javalin/src/test/java/io/javalin/TestLogging.kt
1
3885
/* * Javalin - https://javalin.io * Copyright 2017 David Åse * Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE */ package io.javalin import io.javalin.testing.HttpUtil import io.javalin.testing.TestLoggingUtil.captureStdOut import io.javalin.testing.TestUtil import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.io.File import java.util.concurrent.CompletableFuture import java.util.concurrent.Executors import java.util.concurrent.TimeUnit class TestLogging { @Test fun `default logging works`() { val log = captureStdOut { runTest(Javalin.create()) } assertThat(log).contains("[main] INFO io.javalin.Javalin - Starting Javalin ...") } @Test fun `dev logging works`() { val log = captureStdOut { runTest(Javalin.create { it.enableDevLogging() }) } assertThat(log).contains("JAVALIN REQUEST DEBUG LOG") assertThat(log).contains("Hello Blocking World!") assertThat(log).contains("Hello Async World!") assertThat(log).contains("JAVALIN HANDLER REGISTRATION DEBUG LOG: GET[/blocking]") assertThat(log).contains("JAVALIN HANDLER REGISTRATION DEBUG LOG: GET[/async]") } @Test fun `dev logging works with inputstreams`() = TestUtil.test(Javalin.create { it.enableDevLogging() }) { app, http -> val fileStream = TestLogging::class.java.getResourceAsStream("/public/file") app.get("/") { it.result(fileStream) } val log = captureStdOut { http.getBody("/") } assertThat(log).doesNotContain("Stream closed") assertThat(log).contains("Body is an InputStream which can't be reset, so it can't be logged") } @Test fun `custom requestlogger is called`() { var loggerCalled = false TestUtil.runAndCaptureLogs { runTest(Javalin.create { it.requestLogger { _, _ -> loggerCalled = true } }) } assertThat(loggerCalled).isTrue() } private fun runTest(app: Javalin) { app.get("/blocking") { it.result("Hello Blocking World!") } app.get("/async") { ctx -> val future = CompletableFuture<String>() Executors.newSingleThreadScheduledExecutor().schedule<Boolean>({ future.complete("Hello Async World!") }, 10, TimeUnit.MILLISECONDS) ctx.future(future) } app.start(0) assertThat(HttpUtil(app.port()).getBody("/async")).isEqualTo("Hello Async World!") assertThat(HttpUtil(app.port()).getBody("/blocking")).isEqualTo("Hello Blocking World!") app.stop() } @Test fun `resultString is available in request logger and can be read multiple times`() { val loggerLog = mutableListOf<String?>() val bodyLoggingJavalin = Javalin.create { it.requestLogger { ctx, _ -> loggerLog.add(ctx.resultString()) loggerLog.add(ctx.resultString()) } } TestUtil.test(bodyLoggingJavalin) { app, http -> app.get("/") { it.result("Hello") } http.get("/") // trigger log assertThat(loggerLog[0]).isEqualTo("Hello") assertThat(loggerLog[1]).isEqualTo("Hello") } } @Test fun `debug logging works with binary stream`() = TestUtil.test(Javalin.create { it.enableDevLogging() }) { app, http -> app.get("/") { val imagePath = this::class.java.classLoader.getResource("upload-test/image.png") val stream = File(imagePath.toURI()).inputStream() it.result(stream) } val log = captureStdOut { http.getBody("/") http.getBody("/") // TODO: why must this be called twice on windows to avoid empty log output? } assertThat(log).contains("Body is binary (not logged)") } }
apache-2.0
23bf079a7cdd750a2349cec8a3b477f4
37.84
144
0.629763
4.418658
false
true
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/car_wash_type/AddCarWashType.kt
1
1475
package de.westnordost.streetcomplete.quests.car_wash_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR import de.westnordost.streetcomplete.ktx.toYesNo import de.westnordost.streetcomplete.quests.car_wash_type.CarWashType.* class AddCarWashType : OsmFilterQuestType<List<CarWashType>>() { override val elementFilter = "nodes, ways with amenity = car_wash and !automated and !self_service" override val commitMessage = "Add car wash type" override val wikiLink = "Tag:amenity=car_wash" override val icon = R.drawable.ic_quest_car_wash override val questTypeAchievements = listOf(CAR) override fun getTitle(tags: Map<String, String>) = R.string.quest_carWashType_title override fun createForm() = AddCarWashTypeForm() override fun applyAnswerTo(answer: List<CarWashType>, changes: StringMapChangesBuilder) { val isAutomated = answer.contains(AUTOMATED) changes.add("automated", isAutomated.toYesNo()) val hasSelfService = answer.contains(SELF_SERVICE) val selfService = when { hasSelfService && answer.size == 1 -> "only" hasSelfService -> "yes" else -> "no" } changes.add("self_service", selfService) } }
gpl-3.0
b86aa76b36d9aea238f74f29fbb3c808
41.142857
103
0.738983
4.275362
false
false
false
false
SpryServers/sprycloud-android
src/main/java/com/nextcloud/client/media/PlayerServiceConnection.kt
2
4021
/** * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program 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/>. */ package com.nextcloud.client.media import android.accounts.Account import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.IBinder import android.widget.MediaController import com.owncloud.android.datamodel.OCFile @Suppress("TooManyFunctions") // implementing large interface class PlayerServiceConnection(private val context: Context) : MediaController.MediaPlayerControl { var isConnected: Boolean = false private set private var binder: PlayerService.Binder? = null fun bind() { val intent = Intent(context, PlayerService::class.java) context.bindService(intent, connection, Context.BIND_AUTO_CREATE) } fun unbind() { if (isConnected) { binder = null isConnected = false context.unbindService(connection) } } fun start(account: Account, file: OCFile, playImmediately: Boolean, position: Int) { val i = Intent(context, PlayerService::class.java) i.putExtra(PlayerService.EXTRA_ACCOUNT, account) i.putExtra(PlayerService.EXTRA_FILE, file) i.putExtra(PlayerService.EXTRA_AUTO_PLAY, playImmediately) i.putExtra(PlayerService.EXTRA_START_POSITION_MS, position) i.action = PlayerService.ACTION_PLAY context.startService(i) } fun stop(file: OCFile) { val i = Intent(context, PlayerService::class.java) i.putExtra(PlayerService.EXTRA_FILE, file) i.action = PlayerService.ACTION_STOP_FILE context.startService(i) } fun stop() { val i = Intent(context, PlayerService::class.java) i.action = PlayerService.ACTION_STOP context.startService(i) } private val connection = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { isConnected = false binder = null } override fun onServiceConnected(name: ComponentName?, localBinder: IBinder?) { binder = localBinder as PlayerService.Binder isConnected = true } } // region Media controller override fun isPlaying(): Boolean { return binder?.player?.isPlaying ?: false } override fun canSeekForward(): Boolean { return binder?.player?.canSeekForward() ?: false } override fun getDuration(): Int { return binder?.player?.duration ?: 0 } override fun pause() { binder?.player?.pause() } override fun getBufferPercentage(): Int { return binder?.player?.bufferPercentage ?: 0 } override fun seekTo(pos: Int) { binder?.player?.seekTo(pos) } override fun getCurrentPosition(): Int { return binder?.player?.currentPosition ?: 0 } override fun canSeekBackward(): Boolean { return binder?.player?.canSeekBackward() ?: false } override fun start() { binder?.player?.start() } override fun getAudioSessionId(): Int { return 0 } override fun canPause(): Boolean { return binder?.player?.canPause() ?: false } // endregion }
gpl-2.0
ddc424c31706057e04fa15593b1faaa1
29.007463
98
0.671475
4.691949
false
false
false
false
strykeforce/thirdcoast
src/main/kotlin/org/strykeforce/telemetry/measurable/UltrasonicRangefinderMeasurable.kt
1
1104
package org.strykeforce.telemetry.measurable import com.ctre.phoenix.CANifier import com.ctre.phoenix.CANifier.PWMChannel /** Represents a PWM ultrasonic rangefinder telemetry-enable `Measurable` item connected to a `CANifier`. */ class UltrasonicRangefinderMeasurable @JvmOverloads constructor( canId: Int, private val pwmChannel: PWMChannel, override val description: String = "Sensor ${canId * 10 + pwmChannel.value}" ) : Measurable { override val deviceId = canId * 10 + pwmChannel.value override val measures = setOf(Measure(VALUE, "PWM Duty Cycle") { canifier.getPWMInput(pwmChannel, dutyCycleAndPeriod) dutyCycleAndPeriod[0] }) private val canifier: CANifier = CANifier(canId) private val dutyCycleAndPeriod = DoubleArray(2) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UltrasonicRangefinderMeasurable if (deviceId != other.deviceId) return false return true } override fun hashCode() = deviceId }
mit
441851b7b7642614c3d74fe49bb70b6b
30.542857
109
0.711051
4.119403
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/calendarpager/CalendarPager.kt
1
7210
package com.byagowi.persiancalendar.ui.calendar.calendarpager import android.content.Context import android.os.Build import android.util.AttributeSet import android.util.TypedValue import android.view.ViewGroup import android.widget.FrameLayout import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager2.widget.ViewPager2 import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.databinding.FragmentMonthBinding import com.byagowi.persiancalendar.utils.* import io.github.persiancalendar.calendar.AbstractDate import java.lang.ref.WeakReference import java.util.* class CalendarPager @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(context, attrs) { // Public API var onDayClicked = fun(jdn: Long) {} var onDayLongClicked = fun(jdn: Long) {} // Selected month is visible current month of the pager, maybe a day is not selected on it yet var onMonthSelected = fun() {} val selectedMonth: AbstractDate get() = getDateFromOffset(mainCalendar, applyOffset(viewPager.currentItem)) fun setSelectedDay(jdn: Long, highlight: Boolean = true, monthChange: Boolean = true) { selectedJdn = if (highlight) jdn else -1 if (monthChange) { val today = getTodayOfCalendar(mainCalendar) val date = getDateFromJdnOfCalendar(mainCalendar, jdn) viewPager.setCurrentItem( applyOffset((today.year - date.year) * 12 + today.month - date.month), true ) } refresh() } // Public API, to be reviewed fun refresh(isEventsModified: Boolean = false) = pagesViewHolders.forEach { it.get()?.apply { refresh(isEventsModified, selectedJdn) } } private val pagesViewHolders = ArrayList<WeakReference<PagerAdapter.ViewHolder>>() // Package API, to be rewritten with viewPager.adapter.notifyItemChanged() fun addViewHolder(vh: PagerAdapter.ViewHolder) = pagesViewHolders.add(WeakReference(vh)) private val monthsLimit = 5000 // this should be an even number private fun getDateFromOffset(calendar: CalendarType, offset: Int): AbstractDate { val date = getTodayOfCalendar(calendar) var month = date.month - offset month -= 1 var year = date.year year += month / 12 month %= 12 if (month < 0) { year -= 1 month += 12 } month += 1 return getDateOfCalendar(calendar, year, month, 1) } private fun applyOffset(position: Int) = monthsLimit / 2 - position private val viewPager = ViewPager2(context) private var selectedJdn: Long = -1 init { viewPager.adapter = PagerAdapter() viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) = refresh() }) addView(viewPager) viewPager.setCurrentItem(applyOffset(0), false) } inner class PagerAdapter : RecyclerView.Adapter<PagerAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder( FragmentMonthBinding.inflate(parent.context.layoutInflater, parent, false) ) override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(position) override fun getItemCount() = monthsLimit inner class ViewHolder(val binding: FragmentMonthBinding) : RecyclerView.ViewHolder(binding.root) { private val selectableItemBackground = TypedValue().also { context.theme.resolveAttribute( if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) android.R.attr.selectableItemBackgroundBorderless else android.R.attr.selectableItemBackground, it, true ) }.resourceId private val daysAdapter = DaysAdapter( binding.root.context, this@CalendarPager, selectableItemBackground ) var refresh = fun(_: Boolean, _: Long) {} init { val isRTL = isRTL(binding.root.context) binding.next.apply { setImageResource( if (isRTL) R.drawable.ic_keyboard_arrow_left else R.drawable.ic_keyboard_arrow_right ) setOnClickListener { viewPager.setCurrentItem(viewPager.currentItem + 1, true) } setBackgroundResource(selectableItemBackground) } binding.prev.apply { setImageResource( if (isRTL) R.drawable.ic_keyboard_arrow_right else R.drawable.ic_keyboard_arrow_left ) setOnClickListener { viewPager.setCurrentItem(viewPager.currentItem - 1, true) } setBackgroundResource(selectableItemBackground) } binding.monthDays.apply { setHasFixedSize(true) layoutManager = GridLayoutManager( binding.root.context, if (isShowWeekOfYearEnabled) 8 else 7 ) } addViewHolder(this) binding.monthDays.adapter = daysAdapter } fun bind(position: Int) { val offset = applyOffset(position) val date = getDateFromOffset(mainCalendar, offset) val baseJdn = date.toJdn() val monthLength = getMonthLength(mainCalendar, date.year, date.month) val startOfYearJdn = getDateOfCalendar(mainCalendar, date.year, 1, 1).toJdn() daysAdapter.apply { startingDayOfWeek = getDayOfWeekFromJdn(baseJdn) weekOfYearStart = calculateWeekOfYear(baseJdn, startOfYearJdn) weeksCount = calculateWeekOfYear(baseJdn + monthLength - 1, startOfYearJdn) - weekOfYearStart + 1 days = (baseJdn until baseJdn + monthLength).toList() initializeMonthEvents() notifyItemRangeChanged(0, daysAdapter.itemCount) } refresh = fun(isEventsModification: Boolean, jdn: Long) { if (viewPager.currentItem == position) { if (isEventsModification) { daysAdapter.initializeMonthEvents() onDayClicked(jdn) } else { onMonthSelected() } val selectedDay = 1 + jdn - baseJdn if (jdn != -1L && jdn >= baseJdn && selectedDay <= monthLength) daysAdapter.selectDay(selectedDay.toInt()) else daysAdapter.selectDay(-1) } else daysAdapter.selectDay(-1) } refresh() } } } }
gpl-3.0
2ade27909126e326740fc4ee458283b3
37.768817
100
0.597365
5.301471
false
false
false
false
devulex/eventorage
frontend/src/com/devulex/eventorage/locale/Messages.kt
1
5513
package com.devulex.eventorage.locale import com.devulex.eventorage.model.Language enum class Messages(val en: String, val ru: String) { MAIN_MENU_DATA(en = "Data", ru = "Данные"), MAIN_MENU_DASHBOARD(en = "Dashboard", ru = "Мониторинг"), MAIN_MENU_SEARCH(en = "Search", ru = "Поиск"), MAIN_MENU_METRICS(en = "Metrics", ru = "Метрики"), MAIN_MENU_REST(en = "REST", ru = "REST"), MAIN_MENU_SETTINGS(en = "Settings", ru = "Настройки"), DATA_GRID_DATE(en = "Date", ru = "Дата"), DATA_GRID_UUID(en = "UUID", ru = "UUID"), DATA_GRID_DOCS_COUNT(en = "Docs Count", ru = "Количество документов"), DATA_GRID_STORE_SIZE(en = "Store Size", ru = "Размер"), DATA_GRID_PRIMARY(en = "Primary Shards", ru = "Первичные осколки"), DATA_GRID_REPLICAS(en = "Replicas", ru = "Реплики"), DATA_GRID_STATE(en = "State", ru = "Состояние"), DATA_GRID_HEALTH(en = "Health", ru = "Статус"), LOADING(en = "Loading...", ru = "Загрузка..."), NAME(en = "Name", ru = "Название"), INDEX_PATTERN(en = "Index pattern", ru = "Шаблон индекса"), REPOSITORY_PATH(en = "Repository path", ru = "Путь к репозиторию"), REPEAT_REQUEST(en = "Repeat Request", ru = "Повторить запрос"), INDEX_GROUPS(en = "Index Groups", ru = "Группы индексов"), DELETE_INDEX_GROUP(en = "Delete Index Group", ru = "Удалить группу"), DELETE_INDEX_GROUP_HINT(en = "Delete index group (indices will not be deleted)", ru = "Удалить группу индексов (индексы не будут удалены)"), CREATE_INDEX_GROUP(en = "Create Index Group", ru = "Создать группу"), LEARN_MORE(en = "Learn More", ru = "Узнать подробнее"), CREATE(en = "Create", ru = "Создать"), EXAMPLES(en = "Examples", ru = "Примеры"), CONNECTED_TO_ES(en = "Connected to Elasticsearch at ", ru = "Подключено к Elasticsearch на "), FAILED_REQUEST_GROUPS(en = "Failed to request a list of groups of indices", ru = "Не удалось запросить список групп индексов"), UNABLE_TO_CONNECT_TO_ES(en = "Unable to connect to Elasticsearch at ", ru = "Не удалось подключиться к Elasticsearch на "), UNABLE_TO_CONNECT_TO_ES_TITLE(en = "Unable to connect to Elasticsearch", ru = "Не удалось подключиться к Elasticsearch"), NO_INDICES_FOUND(en = "No indices found", ru = "Индексы не найдены"), INDICES_FOUND(en = "indices found", ru = "индексов найдено"), NO_INDEX_GROUP_CREATED(en = "No Index Group Created", ru = "Группа индексов не создана"), EVENTORAGE_IS_DESIGNED(en = "Eventorage is designed to manage the indexes per time frame.", ru = "Eventorage предназначен для управления индексами за период времени."), COMBINE_INDICES_AND_AUTOMATE(en = "Combine the indexes into a group and automate their life cycle.", ru = "Объедините индексы в группу и автоматизируйте их жизненный цикл."), PAGE_IN_DEVELOPMENT(en = "Page in Development", ru = "Страница в разработке"), YOU_USE_VERY_EARLY_VERSION(en = "You use a very early version of Eventorage ", ru = "Вы используете очень раннюю версию Eventorage "), MANY_FUNCTIONS_ARE_STILL_BEING_DEVELOP(en = "Many functions are still being developed and will appear in future versions.", ru = "Многие функции все еще разрабатываются и появятся в будущих версиях."), IN_INDEX_PATTERN_YOU_MUST_USE_SPECIAL_SYMBOLS(en = "In index pattern, you must use special symbols:", ru = "В шаблоне индекса допускаются специальные символы:"), ANY_CHARACTERS_INCLUDING_NODE(en = "any characters including none", ru = "любые символы или ничего"), ANY_SINGLE_CHARACTER(en = "any single character", ru = "любой одиночный символ"), YEAR(en = "year", ru = "год"), MONTH_OF_YEAR(en = "month of year", ru = "месяц в году"), DAY_OF_MONTH(en = "day of month", ru = "день месяца"), WEEK_OF_YEAR(en = "week of year", ru = "неделя в году"), ESCAPED_TEXT(en = "escaped text", ru = "экранированный текст"), YOU_CAN_CHANGE_CLUSTER_SETTINGS(en = "You can change the cluster settings in", ru = "Вы можете изменить настройки кластера в"), CLUSTER_NAME(en = "Cluster Name", ru = "Название кластера"), CLUSTER_NODES(en = "Cluster Nodes", ru = "Узлы кластера"), LANGUAGE(en = "Interface Language", ru = "Язык интерфейса"), DATE_FORMAT(en = "Date Format", ru = "Формат даты"), AUTOMATICALLY_CHECK_FOR_UPDATES_TO_EVENTORAGE(en = "Automatically check for updates to Eventorage", ru = "Автоматически проверять наличие обновлений Eventorage"); companion object { var locale = Language.EN } operator fun unaryPlus(): String = this.toString() override fun toString() = if (locale == Language.RU) ru else en }
mit
aaf54787d8ee87c75b95475d73ed20ed
60.506667
205
0.674832
2.788996
false
false
false
false
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/ui/fragment/SettingsFragment.kt
1
2471
package com.makeevapps.simpletodolist.ui.fragment import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v14.preference.SwitchPreference import android.support.v4.app.TaskStackBuilder import android.support.v7.preference.ListPreference import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceFragmentCompat import com.makeevapps.simpletodolist.R import com.makeevapps.simpletodolist.ui.activity.AboutActivity import com.makeevapps.simpletodolist.ui.activity.MainActivity import com.makeevapps.simpletodolist.ui.activity.SettingsActivity import com.makeevapps.simpletodolist.viewmodel.SettingsViewModel class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceClickListener, Preference.OnPreferenceChangeListener { private lateinit var model: SettingsViewModel private lateinit var themeListPreference: ListPreference override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preference_settings) model = ViewModelProviders.of(this).get(SettingsViewModel::class.java) //PreferenceManager.setDefaultValues(context, R.xml.settings, false) themeListPreference = findPreference(getString(R.string.themeId)) as ListPreference themeListPreference.onPreferenceChangeListener = this val is24HourFormat = findPreference(getString(R.string.is24HourFormat)) as SwitchPreference is24HourFormat.isChecked = model.preferenceManager.is24HourFormat() findPreference(getString(R.string.aboutScreen)).onPreferenceClickListener = this } override fun onPreferenceChange(preference: Preference?, newValue: Any?): Boolean { when (preference?.key) { getString(R.string.themeId) -> { restartApp() } } return true } override fun onPreferenceClick(preference: Preference?): Boolean { when (preference?.key) { getString(R.string.aboutScreen) -> { startActivity(AboutActivity.getActivityIntent(context!!)) } } return false } private fun restartApp() { TaskStackBuilder.create(context!!) .addNextIntent(MainActivity.getActivityIntent(context!!, false)) .addNextIntent(SettingsActivity.getActivityIntent(context!!)) .startActivities() } }
mit
cece40016e4e8384bacf6079ac409e12
39.52459
99
0.740591
5.466814
false
false
false
false
MaKToff/Codename_Ghost
core/src/com/cypress/Screens/MenuScreen.kt
1
5677
package com.cypress.Screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.cypress.CGHelpers.AssetLoader import com.cypress.codenameghost.CGGame /** Contains definition of pause menu. */ public class MenuScreen(private val game : CGGame, private val level : Screen?) : Screen { private val assets = AssetLoader.getInstance() private val batcher = SpriteBatch() private val stage = Stage() init { // style of big text buttons val font = assets.generateFont("Calibri.ttf", 32, Color.GREEN) val textButtonStyle = assets.getTextButtonStyle(314, 128, 41, 128, 191, 127, font) // initializing table val table = Table() table.setFillParent(true) // initializing buttons val sounds = when (assets.musicOn) { true -> ImageButton(assets.getImageButtonStyle(684, 168, 789, 168, 90, 90, true)) false -> ImageButton(assets.getImageButtonStyle(789, 168, 684, 168, 90, 90, true)) } val language = when (assets.language) { "english" -> TextButton("Language:\n" + assets.language, textButtonStyle) else -> TextButton("Язык:\n" + assets.language, textButtonStyle) } val backToMain = when (assets.language) { "english" -> TextButton("Back to \nmain menu", textButtonStyle) else -> TextButton("В главное \nменю", textButtonStyle) } val back = ImageButton(assets.getImageButtonStyle(525, 116, 663, 116, 129, 65, false)) language.addListener(object : ClickListener() { override fun touchDown(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) = true override fun touchUp(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) { when (assets.language) { "english" -> { assets.language = "русский" language.setText("Язык:\n" + assets.language) backToMain.setText("В главное \nменю") } else -> { assets.language = "english" language.setText("Language:\n" + assets.language) backToMain.setText("Back to \nmain menu") } } } }) sounds.addListener(object : ClickListener() { override fun touchDown(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) = true override fun touchUp(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) { if (assets.musicOn) { assets.musicOn = false assets.activeMusic?.stop() } else { assets.musicOn = true assets.activeMusic?.play() } } }) backToMain.addListener(object : ClickListener() { override fun touchDown(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) = true override fun touchUp(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) { assets.activeMusic?.stop() game.screen = MainScreen(game) level?.dispose() dispose() } }) back.addListener(object : ClickListener() { override fun touchDown(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) = true override fun touchUp(event : InputEvent?, x : Float, y : Float, ptr : Int, button : Int) { level?.resume() dispose() } }) table.add(sounds) table.row() table.add(language) table.row() table.add(backToMain) table.setPosition(-230f, 30f) back.setPosition(10f, 10f) stage.addActor(table) stage.addActor(back) Gdx.input.inputProcessor = stage Gdx.input.isCatchBackKey = true } /** Draws pause menu. */ public override fun render(delta : Float) { // drawing background color Gdx.gl.glClearColor(0f, 0f, 0f, 1f) Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT) // drawing picture batcher.begin() batcher.disableBlending() batcher.draw(assets.settings, 0f, 0f, 800f, 480f) batcher.end() // playing music if (!(assets.activeMusic?.isPlaying ?: false) && assets.musicOn) assets.activeMusic?.play() // keyboard control if (Gdx.input.isKeyJustPressed(Input.Keys.BACKSPACE)) { level?.resume() dispose() } // drawing stage stage.act(delta) stage.draw() } public override fun resize(width : Int, height : Int) {} public override fun show() {} public override fun hide() {} public override fun pause() {} public override fun resume() {} /** Clears this screen. */ public override fun dispose() { stage.dispose() game.dispose() } }
apache-2.0
f533921d8d8d4b1e6de446b7cb4b99e8
35.616883
110
0.554807
4.43239
false
false
false
false
andreyfomenkov/green-cat
plugin/src/ru/fomenkov/runner/Runner.kt
1
11594
package ru.fomenkov.runner import ru.fomenkov.plugin.util.* import ru.fomenkov.runner.diff.GitDiffParser import ru.fomenkov.runner.logger.Log import ru.fomenkov.runner.params.ParamsReader import ru.fomenkov.runner.params.RunnerMode import ru.fomenkov.runner.params.RunnerParams import ru.fomenkov.runner.ssh.setRemoteHost import ru.fomenkov.runner.ssh.ssh import ru.fomenkov.runner.update.CompilerUpdater import ru.fomenkov.runner.update.PluginUpdater import java.io.File import java.util.concurrent.Callable import java.util.concurrent.Executors import java.util.concurrent.Future private val uiTestTaskExecutor = Executors.newSingleThreadExecutor() private var displayTotalTime = false private var uiTestTask: Future<List<String>>? = null fun main(args: Array<String>) { try { Mixpanel.launch() var params: RunnerParams? = null val time = timeMillis { params = launch(args) } if (displayTotalTime) { displayTotalTime(time) } params?.apply(::restartApplication) Mixpanel.complete(duration = time) uiTestTask?.run { val uiTestOutput = try { get() } catch (e: Throwable) { error("Failed to get UI test output (message = ${e.localizedMessage})") } uiTestOutput.forEach(Telemetry::log) } } catch (error: Throwable) { // Wait and show error message at the end, because System.out and System.err // streams are not mutually synchronized Thread.sleep(FINAL_ERROR_MESSAGE_DELAY) Mixpanel.failed(message = error.message ?: "") when (error.message.isNullOrBlank()) { true -> Log.e("\n# FAILED #") else -> Log.e("\n# FAILED: ${error.message} #") } } finally { uiTestTaskExecutor.shutdown() } } private fun launch(args: Array<String>): RunnerParams? { Log.d("Starting GreenCat Runner") Log.d("Project on GitHub: $PROJECT_GITHUB\n") validateShellCommands() val pluginUpdater = PluginUpdater(PLUGIN_UPDATE_TIMESTAMP_FILE, PLUGIN_ARTIFACT_VERSION_INFO_URL) val compilerUpdated = CompilerUpdater(COMPILER_UPDATE_TIMESTAMP_FILE, COMPILER_ARTIFACT_VERSION_INFO_URL) val params = readParams(args) ?: return null setRemoteHost(host = params.sshHost) if (params.mode is RunnerMode.UiTest) { val testClass = params.mode.testClass val testRunner = params.mode.testRunner val callable = Callable { exec("adb shell am instrument -w -m -e waitPatch $WAIT_PATCH_DELAY -e debug false -e class '$testClass' $testRunner") } Log.d("Prelaunching UI test $testClass...") Log.d("Patch waiting timeout: ${WAIT_PATCH_DELAY / 1000L} sec\n") uiTestTask = uiTestTaskExecutor.submit(callable) } if (params.mode == RunnerMode.Update) { pluginUpdater.checkForUpdate(params, forceCheck = true) compilerUpdated.checkForUpdate(params, forceCheck = true) return null } else { checkSingleAndroidDeviceConnected() checkApplicationStoragePermissions(params) val supported = checkGitDiff() if (supported == null) { Runtime.getRuntime().exit(0) return null } syncWithMainframer(params, supported) pluginUpdater.checkForUpdate(params, forceCheck = false) compilerUpdated.checkForUpdate(params, forceCheck = false) startGreenCatPlugin(params) pushDexToAndroidDevice(params) displayTotalTime = true return params } } private fun checkSingleAndroidDeviceConnected() { val devices = exec("adb devices") .map { line -> line.trim() } .filter { line -> line.endsWith("device") } .map { line -> line.substring(0, line.length - 6).trim() } when (devices.size) { 0 -> error("No Android devices connected") 1 -> Telemetry.log("Device '${devices.first()}' connected (API ${getApiLevel()})") else -> error("Multiple devices connected") } } private fun checkApplicationStoragePermissions(params: RunnerParams) { val packageName = when (val mode = params.mode) { is RunnerMode.UiTest -> { mode.appPackage } is RunnerMode.Debug -> { mode.componentName.split("/").first() } is RunnerMode.Patch -> { return } else -> error("Unexpected runner mode: ${params.mode}") } val output = exec("adb shell dumpsys package $packageName | grep -i $READ_EXTERNAL_STORAGE_PERMISSION") .map { line -> line.lowercase().replace(" ", "") } if (output.isEmpty()) { error("No package '$packageName' installed") } output.forEach { line -> if (line.contains("granted=true")) { return } else if (line.contains("granted=false")) { error("Package '$packageName' has no external storage permission") } } error("Unable to check storage permissions for package '$packageName'") } private fun restartApplication(params: RunnerParams) { when (params.mode) { is RunnerMode.Debug -> { Log.d("\nRestarting application on the Android device...") val action = "android.intent.action.MAIN" val category = "android.intent.category.LAUNCHER" val componentName = params.mode.componentName val appPackage = componentName.split("/").first() exec("adb shell am force-stop $appPackage") exec("adb shell am start -n $componentName -a $action -c $category") } is RunnerMode.UiTest -> { // NOP, prelaunching on start } is RunnerMode.Patch -> { // NOP, don't start app } else -> { // NOP } } } private fun pushDexToAndroidDevice(params: RunnerParams) { val tmpDir = exec("echo \$TMPDIR").firstOrNull() ?: "" check(tmpDir.isNotBlank()) { "Failed to get /tmp directory" } exec("scp ${params.sshHost}:${params.greencatRoot}/$DEX_FILES_DIR/$OUTPUT_DEX_FILE $tmpDir") val output = exec("adb push $tmpDir/$OUTPUT_DEX_FILE $ANDROID_DEVICE_DEX_DIR/$OUTPUT_DEX_FILE") if (output.find { line -> line.contains("error:") } != null) { output.forEach(Telemetry::err) error("Failed to push DEX file via adb") } } private fun displayTotalTime(time: Long) { val str = "| Build & deploy complete in ${formatMillis(time)} |" val border = "-".repeat(str.length - 2) val space = " ".repeat(str.length - 2) Log.d("\n") Log.d("+$border+") Log.d("|$space|") Log.d(str) Log.d("|$space|") Log.d("+$border+") } private fun startGreenCatPlugin(params: RunnerParams) { val greencatJar = "${params.greencatRoot}/$GREENCAT_JAR" val version = ssh { cmd("java -jar $greencatJar -v") }.firstOrNull() ?: "???" val apiLevel = getApiLevel() ?: 0 Log.d("Launching GreenCat v$version on the remote host. It may take a while...") val mappedModulesParam = formatMappedModulesParameter(params.modulesMap) val lines = ssh(print = true) { cmd("cd ${params.projectRoot}") cmd("java -jar $greencatJar -s ${params.androidSdkRoot} -g ${params.greencatRoot} $mappedModulesParam -l $apiLevel") } val errorMessages = mutableSetOf<String>() lines .map(String::trim) .forEach { line -> if (line.startsWith("Build failed:") || line.startsWith("Error")) { errorMessages += line.take(ERROR_MESSAGE_LENGTH_LIMIT) } } if (errorMessages.isNotEmpty()) { error(errorMessages.joinToString(separator = " / ")) } } private fun checkGitDiff(): List<String>? { Log.d("Checking diff...") val gitDiffParser = GitDiffParser() val diff = gitDiffParser.parse() Log.d("On branch: ${diff.branch}") val (supported, ignored) = diff.paths.partition { path -> isFileSupported(path) } if (supported.isEmpty() && ignored.isEmpty()) { Log.d("Nothing to compile") Mixpanel.drop("Nothing to compile") return null } if (supported.isNotEmpty()) { Log.d("\nSource file(s) to be compiled:\n") supported.sorted().forEach { path -> Log.d(" [+] $path") } } if (ignored.isNotEmpty()) { Log.d("\nIgnored (not supported):\n") ignored.sorted().forEach { path -> Log.d(" [-] $path") } } if (supported.isEmpty()) { Log.d("\nNo supported changes to compile") Mixpanel.drop("No supported changes to compile") return null } return supported } private fun formatMappedModulesParameter(mappedModules: Map<String, String>) = when (mappedModules.isEmpty()) { true -> "" else -> { "-a " + mappedModules.entries.joinToString(separator = ",") { (moduleFrom, moduleTo) -> "$moduleFrom:$moduleTo" } } } private fun syncWithMainframer( params: RunnerParams, supported: List<String>, ) { Log.d("\nSync with the remote host...") ssh { cmd("mkdir -p ${params.greencatRoot}") cmd("cd ${params.greencatRoot}") cmd("mkdir $CLASSPATH_DIR") cmd("rm -rf $SOURCE_FILES_DIR; mkdir $SOURCE_FILES_DIR") cmd("rm -rf $CLASS_FILES_DIR; mkdir $CLASS_FILES_DIR") cmd("rm -rf $DEX_FILES_DIR; mkdir $DEX_FILES_DIR") supported .map { path -> File(path).parent } .forEach { dir -> cmd("mkdir -p $SOURCE_FILES_DIR/$dir") } } supported.forEach { path -> val dstPath = "${params.sshHost}:${params.greencatRoot}/$SOURCE_FILES_DIR/$path" exec("scp $path $dstPath").forEach { Log.d("[SCP] $it") } } val copiedSources = ssh { cmd("find ${params.greencatRoot}/$SOURCE_FILES_DIR") } .map(String::trim) .filter { path -> isFileSupported(path) } if (copiedSources.size < supported.size) { error("Not all files copied to the remote host") } else { Log.d("Copying ${copiedSources.size} source file(s) complete\n") } } private fun readParams(args: Array<String>) = when (args.isEmpty()) { true -> { ParamsReader.displayHelp() null } else -> ParamsReader(args).read() } private fun validateShellCommands() { listOf("git", "adb", "find", "rm", "ls", "ssh", "scp", "curl").forEach { cmd -> val exists = exec("command -v $cmd").isNotEmpty() if (!exists) { error("Command '$cmd' not found") } } } const val PROJECT_GITHUB = "https://github.com/andreyfomenkov/green-cat" const val PLUGIN_ARTIFACT_VERSION_INFO_URL = "https://raw.githubusercontent.com/andreyfomenkov/green-cat/master/artifacts/version-info" const val COMPILER_ARTIFACT_VERSION_INFO_URL = "https://raw.githubusercontent.com/andreyfomenkov/kotlin-relaxed/relaxed-restrictions/artifact/date" const val GREENCAT_JAR = "greencat.jar" const val CLASSPATH_DIR = "cp" const val SOURCE_FILES_DIR = "src" const val CLASS_FILES_DIR = "class" const val DEX_FILES_DIR = "dex" const val KOTLINC_DIR = "kotlinc" const val KOTLINC_VERSION_FILE = "date" const val ANDROID_DEVICE_DEX_DIR = "/data/local/tmp" const val OUTPUT_DEX_FILE = "patch.dex" const val PLUGIN_UPDATE_TIMESTAMP_FILE = "greencat_update" const val COMPILER_UPDATE_TIMESTAMP_FILE = "compiler_update" const val READ_EXTERNAL_STORAGE_PERMISSION = "android.permission.READ_EXTERNAL_STORAGE" const val FINAL_ERROR_MESSAGE_DELAY = 100L const val WAIT_PATCH_DELAY = 60000L const val ERROR_MESSAGE_LENGTH_LIMIT = 150
apache-2.0
289c9b16d89e8a02c64ade9603248dfe
34.897833
153
0.63024
3.901077
false
true
false
false
Mauin/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/NotImplementedDeclaration.kt
1
2160
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtThrowExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny /** * This rule reports all exceptions of the type `NotImplementedError` that are thrown. It also reports all `TODO(..)` * functions. * These indicate that functionality is still under development and will not work properly. Both of these should only * serve as temporary declarations and should not be put into production environments. * * <noncompliant> * fun foo() { * throw NotImplementedError() * } * * fun todo() { * TODO("") * } * </noncompliant> * * @author schalkms * @author Marvin Ramin */ class NotImplementedDeclaration(config: Config = Config.empty) : Rule(config) { override val issue = Issue("NotImplementedDeclaration", Severity.CodeSmell, "The NotImplementedDeclaration should only be used when a method stub is necessary. " + "This defers the development of the functionality of this function. " + "Hence, the NotImplementedDeclaration should only serve as a temporary declaration. " + "Before releasing, this type of declaration should be removed.", Debt.TWENTY_MINS) override fun visitThrowExpression(expression: KtThrowExpression) { val calleeExpression = expression.thrownExpression?.getCalleeExpressionIfAny() if (calleeExpression?.text == "NotImplementedError") { report(CodeSmell(issue, Entity.from(expression), issue.description)) } } override fun visitCallExpression(expression: KtCallExpression) { if (expression.calleeExpression?.text == "TODO") { val size = expression.valueArguments.size if (size == 0 || size == 1) { report(CodeSmell(issue, Entity.from(expression), issue.description)) } } } }
apache-2.0
5fd7336c045284f5cdfa5134ba8b18cc
36.894737
117
0.760185
4.153846
false
true
false
false
dafi/photoshelf
birthday/src/main/java/com/ternaryop/photoshelf/birthday/browser/fragment/BirthdayBrowserFragment.kt
1
18672
package com.ternaryop.photoshelf.birthday.browser.fragment import android.app.AlertDialog import android.app.DatePickerDialog import android.content.DialogInterface import android.os.Bundle import android.view.ActionMode import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.core.view.MenuProvider import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.ternaryop.photoshelf.activity.ImageViewerActivityStarter import com.ternaryop.photoshelf.activity.TagPhotoBrowserData import com.ternaryop.photoshelf.api.birthday.Birthday import com.ternaryop.photoshelf.birthday.R import com.ternaryop.photoshelf.birthday.browser.adapter.BirthdayAdapter import com.ternaryop.photoshelf.birthday.browser.adapter.BirthdayShowFlags import com.ternaryop.photoshelf.fragment.AbsPhotoShelfFragment import com.ternaryop.photoshelf.lifecycle.EventObserver import com.ternaryop.photoshelf.lifecycle.Status import com.ternaryop.photoshelf.util.post.OnPagingScrollListener import com.ternaryop.util.coroutine.DebouncingQueryTextListener import com.ternaryop.utils.date.dayOfMonth import com.ternaryop.utils.date.month import com.ternaryop.utils.date.year import com.ternaryop.utils.dialog.showErrorDialog import com.ternaryop.utils.recyclerview.scrollItemOnTopByPosition import dagger.hilt.android.AndroidEntryPoint import java.text.DateFormatSymbols import java.util.Calendar private const val PARAM_LAST_PATTERN = "lastPattern" private const val PARAM_SELECTED_OPTIONS_ITEM_ID = "selectedOptionItemId" private const val DEBOUNCE_TIMEOUT_MILLIS = 600L @AndroidEntryPoint class BirthdayBrowserFragment( private val imageViewerActivityStarter: ImageViewerActivityStarter ) : AbsPhotoShelfFragment(), OnPagingScrollListener.OnScrollListener, View.OnClickListener, View.OnLongClickListener, ActionMode.Callback, MenuProvider { private lateinit var toolbarSpinner: Spinner private var currentSelectedItemId = R.id.action_show_all private val singleSelectionMenuIds = intArrayOf(R.id.item_edit) private val actionModeMenuId: Int get() = R.menu.birthday_browser_context private val viewModel: BirthdayBrowserViewModel by viewModels() enum class ItemAction { MARK_AS_IGNORED, DELETE } private lateinit var adapter: BirthdayAdapter private lateinit var recyclerView: RecyclerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_birthday_browser, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) adapter = BirthdayAdapter(requireContext(), requireBlogName) adapter.onClickListener = this adapter.onLongClickListener = this recyclerView = view.findViewById(R.id.list) recyclerView.setHasFixedSize(true) recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.adapter = adapter recyclerView.addOnScrollListener(OnPagingScrollListener(this)) val searchView = view.findViewById<SearchView>(R.id.searchView1) // Set up the query listener that executes the search searchView.setOnQueryTextListener( DebouncingQueryTextListener(DEBOUNCE_TIMEOUT_MILLIS) { pattern -> // this is called after rotation so we ensure the find runs only when the pattern changes if (adapter.pattern != pattern) { adapter.pattern = pattern viewModel.pageFetcher.clear() viewModel.find(BirthdayBrowserModelResult.ActionId.QUERY_BY_TYPING, adapter.pattern, false) } } ) savedInstanceState?.apply { getString(PARAM_LAST_PATTERN)?.also { adapter.pattern = it } currentSelectedItemId = getInt(PARAM_SELECTED_OPTIONS_ITEM_ID) viewModel.find(BirthdayBrowserModelResult.ActionId.RESUBMIT_QUERY, adapter.pattern, true) } viewModel.result.observe( viewLifecycleOwner, EventObserver { result -> when (result) { is BirthdayBrowserModelResult.Find -> when (result.actionId) { BirthdayBrowserModelResult.ActionId.QUERY_BY_TYPING -> onQueryByTyping(result) BirthdayBrowserModelResult.ActionId.RESUBMIT_QUERY -> onResubmitQuery(result) } is BirthdayBrowserModelResult.MarkAsIgnored -> onMarkAsIgnored(result) is BirthdayBrowserModelResult.UpdateByName -> onUpdateByName(result) is BirthdayBrowserModelResult.DeleteBirthday -> onDeleteBirthdays(result) } } ) setupActionBar() requireActivity().addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(PARAM_LAST_PATTERN, adapter.pattern) outState.putInt(PARAM_SELECTED_OPTIONS_ITEM_ID, currentSelectedItemId) } override fun onScrolled( onPagingScrollListener: OnPagingScrollListener, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int ) { if (viewModel.pageFetcher.changedScrollPosition(firstVisibleItem, visibleItemCount, totalItemCount)) { viewModel.find(BirthdayBrowserModelResult.ActionId.RESUBMIT_QUERY, adapter.pattern, false) } } private fun onQueryByTyping(result: BirthdayBrowserModelResult.Find) { when (result.command.status) { Status.SUCCESS -> { result.command.data?.also { fetched -> adapter.setBirthdays(fetched.list) } } Status.ERROR -> result.command.error?.also { it.showErrorDialog(requireContext()) } Status.PROGRESS -> {} } } private fun onResubmitQuery(result: BirthdayBrowserModelResult.Find) { when (result.command.status) { Status.SUCCESS -> { result.command.data?.also { fetched -> adapter.setBirthdays(fetched.list) scrollToFirstTodayBirthday() } } Status.ERROR -> {} Status.PROGRESS -> {} } } override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { mode.setTitle(R.string.select_items) mode.subtitle = resources.getQuantityString(R.plurals.selected_items, 1, 1) val inflater = mode.menuInflater inflater.inflate(actionModeMenuId, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { return when (item.itemId) { R.id.item_delete -> { showConfirmDialog(ItemAction.DELETE, mode) true } R.id.item_mark_as_ignored -> { showConfirmDialog(ItemAction.MARK_AS_IGNORED, mode) true } R.id.item_edit -> { showEditBirthdateDialog(mode) true } else -> false } } override fun onDestroyActionMode(mode: ActionMode) { this.actionMode = null adapter.selection.clear() } private fun showEditBirthdateDialog(mode: ActionMode) { val birthdays = adapter.selectedPosts if (birthdays.size != 1) { return } val birthday = birthdays[0] val c = birthday.birthdate ?: Calendar.getInstance() DatePickerDialog(requireContext(), { _, pickedYear, pickedMonth, pickedDay -> c.year = pickedYear c.month = pickedMonth c.dayOfMonth = pickedDay birthday.birthdate = c viewModel.updateByName(birthday) mode.finish() }, c.year, c.month, c.dayOfMonth).show() } private fun showConfirmDialog(postAction: ItemAction, mode: ActionMode) { val birthdays = adapter.selectedPosts val dialogClickListener = DialogInterface.OnClickListener { _, which -> when (which) { DialogInterface.BUTTON_POSITIVE -> when (postAction) { ItemAction.DELETE -> deleteBirthdays(birthdays, mode) ItemAction.MARK_AS_IGNORED -> markAsIgnored(birthdays, mode) } } } val message = when (postAction) { ItemAction.DELETE -> resources.getQuantityString( R.plurals.delete_items_confirm, birthdays.size, birthdays.size, birthdays[0].name ) ItemAction.MARK_AS_IGNORED -> resources.getQuantityString( R.plurals.update_items_confirm, birthdays.size, birthdays.size, birthdays[0].name ) } AlertDialog.Builder(requireContext()) .setMessage(message) .setPositiveButton(android.R.string.ok, dialogClickListener) .setNegativeButton(android.R.string.cancel, dialogClickListener) .show() } private fun markAsIgnored(list: List<Birthday>, mode: ActionMode) { viewModel.markAsIgnored(list) mode.finish() } private fun onMarkAsIgnored(result: BirthdayBrowserModelResult.MarkAsIgnored) { when (result.command.status) { Status.SUCCESS -> result.command.data?.also { adapter.updateItems(it) } Status.ERROR -> result.command.error?.also { Toast.makeText(context, it.message, Toast.LENGTH_LONG).show() } Status.PROGRESS -> {} } } private fun onUpdateByName(result: BirthdayBrowserModelResult.UpdateByName) { when (result.command.status) { Status.SUCCESS -> result.command.data?.also { adapter.updateItems(listOf(it)) } Status.ERROR -> result.command.error?.also { Toast.makeText(context, it.message, Toast.LENGTH_LONG).show() } Status.PROGRESS -> {} } } private fun deleteBirthdays(list: List<Birthday>, mode: ActionMode) { viewModel.deleteBirthdays(list) mode.finish() } private fun onDeleteBirthdays(result: BirthdayBrowserModelResult.DeleteBirthday) { when (result.command.status) { Status.SUCCESS -> result.command.data?.also { adapter.removeItems(it) } Status.ERROR -> { result.command.data?.also { adapter.removeItems(it) } result.command.error?.also { Toast.makeText(context, it.message, Toast.LENGTH_LONG).show() } } Status.PROGRESS -> {} } } override fun onCreateMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.birthday_browser, menu) } override fun onMenuItemSelected(item: MenuItem): Boolean { // if selected item is already selected don't change anything if (currentSelectedItemId == item.itemId) { return true } currentSelectedItemId = item.itemId val isChecked = !item.isChecked updateSubTitle(item) item.isChecked = isChecked val showFlag = when (item.itemId) { R.id.action_show_all -> BirthdayShowFlags.SHOW_ALL R.id.action_show_ignored -> BirthdayShowFlags.SHOW_IGNORED R.id.action_show_birthdays_in_same_day -> BirthdayShowFlags.SHOW_IN_SAME_DAY R.id.action_show_birthdays_missing -> BirthdayShowFlags.SHOW_MISSING R.id.action_show_birthdays_without_posts -> BirthdayShowFlags.SHOW_WITHOUT_POSTS else -> return false } viewModel.showFlags.setFlag(showFlag, isChecked) viewModel.pageFetcher.clear() viewModel.find(BirthdayBrowserModelResult.ActionId.RESUBMIT_QUERY, adapter.pattern, false) return true } private fun updateSubTitle(item: MenuItem) { supportActionBar?.subtitle = when (item.itemId) { R.id.action_show_all -> { setSpinnerVisibility(true) null } R.id.action_show_ignored -> { setSpinnerVisibility(false) item.title } R.id.action_show_birthdays_in_same_day -> { setSpinnerVisibility(false) item.title } R.id.action_show_birthdays_missing -> { setSpinnerVisibility(false) item.title } R.id.action_show_birthdays_without_posts -> { setSpinnerVisibility(false) item.title } else -> null } } private fun setSpinnerVisibility(visible: Boolean) { if (visible) { toolbarSpinner.visibility = View.VISIBLE supportActionBar?.setDisplayShowTitleEnabled(false) } else { toolbarSpinner.visibility = View.GONE supportActionBar?.setDisplayShowTitleEnabled(true) } } override fun onPrepareMenu(menu: Menu) { if (fragmentActivityStatus.isDrawerMenuOpen) { fragmentActivityStatus.drawerToolbar.removeView(toolbarSpinner) supportActionBar?.setDisplayShowTitleEnabled(true) } else { // check if view is already added (eg when the overflow menu is opened) if (viewModel.showFlags.isOn(BirthdayShowFlags.SHOW_ALL) && fragmentActivityStatus.drawerToolbar.indexOfChild(toolbarSpinner) == -1 ) { fragmentActivityStatus.drawerToolbar.addView(toolbarSpinner) supportActionBar?.setDisplayShowTitleEnabled(false) } menu.findItem(currentSelectedItemId).apply { isChecked = true updateSubTitle(this) } } super.onPrepareMenu(menu) } private fun setupActionBar() { val supportActionBar = supportActionBar ?: return supportActionBar.setDisplayShowTitleEnabled(false) val months = arrayOfNulls<String>(MONTH_COUNT + 1) months[0] = getString(R.string.all) System.arraycopy(DateFormatSymbols().months, 0, months, 1, MONTH_COUNT) val monthAdapter = ArrayAdapter<String>( supportActionBar.themedContext, android.R.layout.simple_spinner_item, months ) monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) toolbarSpinner = LayoutInflater .from(supportActionBar.themedContext) .inflate( R.layout.toolbar_spinner, fragmentActivityStatus.drawerToolbar, false ) as Spinner toolbarSpinner.adapter = monthAdapter toolbarSpinner.setSelection(Calendar.getInstance().month + 1) toolbarSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, pos: Int, id: Long) { changeMonth(pos) } override fun onNothingSelected(parent: AdapterView<*>?) = Unit } } fun changeMonth(month: Int) { if (viewModel.month == month) { return } viewModel.month = month viewModel.pageFetcher.clear() viewModel.find(BirthdayBrowserModelResult.ActionId.RESUBMIT_QUERY, adapter.pattern, false) } private fun scrollToFirstTodayBirthday() { if (!viewModel.showFlags.isOn(BirthdayShowFlags.SHOW_ALL)) { return } val dayPos = adapter.findDayPosition(Calendar.getInstance().dayOfMonth) if (dayPos >= 0) { recyclerView.scrollItemOnTopByPosition(dayPos) } } override fun onClick(view: View?) { view?.let { val position = it.tag as Int if (actionMode == null) { browsePhotos(position) } else { updateSelection(position) } } } override fun onLongClick(v: View): Boolean { if (actionMode == null) { actionMode = requireActivity().startActionMode(this) } updateSelection(v.tag as Int) return true } private fun updateSelection(position: Int) { val selection = adapter.selection selection.toggle(position) if (selection.itemCount == 0) { actionMode?.finish() } else { updateMenuItems() val selectionCount = selection.itemCount actionMode?.subtitle = resources.getQuantityString( R.plurals.selected_items, selectionCount, selectionCount ) } } private fun updateMenuItems() { val selectCount = adapter.selection.itemCount val singleSelection = selectCount == 1 for (itemId in singleSelectionMenuIds) { actionMode?.menu?.findItem(itemId)?.isVisible = singleSelection } if (viewModel.showFlags.isShowMissing) { actionMode?.menu?.let { menu -> for (i in 0 until menu.size()) { val itemId = menu.getItem(i).itemId menu.getItem(i).isVisible = MISSING_BIRTHDAYS_ITEMS.contains(itemId) } } } } private fun browsePhotos(position: Int) { val tag = adapter.getItem(position).name requireContext().startActivity( imageViewerActivityStarter.tagPhotoBrowserIntent( requireContext(), TagPhotoBrowserData(requireBlogName, tag, false) ) ) } companion object { private const val MONTH_COUNT = 12 private val MISSING_BIRTHDAYS_ITEMS = intArrayOf(R.id.item_edit) } }
mit
cedbe375b07fbb6f287d392d27926e5b
36.344
120
0.635015
4.983187
false
false
false
false
michaelgallacher/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.kt
3
20872
/* * 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 com.intellij.openapi.updateSettings.impl import com.intellij.diagnostic.IdeErrorsDialog import com.intellij.externalDependencies.DependencyOnPlugin import com.intellij.externalDependencies.ExternalDependenciesManager import com.intellij.ide.IdeBundle import com.intellij.ide.externalComponents.ExternalComponentManager import com.intellij.ide.externalComponents.UpdatableExternalComponent import com.intellij.ide.plugins.* import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.* import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.IdeaLoggingEvent import com.intellij.openapi.diagnostic.LogUtil import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.ActionCallback import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.util.SystemProperties import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.MultiMap import com.intellij.util.io.HttpRequests import com.intellij.util.io.URLUtil import com.intellij.util.loadElement import com.intellij.util.ui.UIUtil import com.intellij.xml.util.XmlStringUtil import org.apache.http.client.utils.URIBuilder import org.jdom.JDOMException import java.io.File import java.io.IOException import java.util.* /** * See XML file by [ApplicationInfoEx.getUpdateUrls] for reference. * * @author mike * @since Oct 31, 2002 */ object UpdateChecker { private val LOG = Logger.getInstance("#com.intellij.openapi.updateSettings.impl.UpdateChecker") @JvmField val NOTIFICATIONS = NotificationGroup(IdeBundle.message("update.notifications.title"), NotificationDisplayType.STICKY_BALLOON, true) private val DISABLED_UPDATE = "disabled_update.txt" private val NO_PLATFORM_UPDATE = "ide.no.platform.update" private var ourDisabledToUpdatePlugins: MutableSet<String>? = null private val ourAdditionalRequestOptions = hashMapOf<String, String>() private val ourUpdatedPlugins = hashMapOf<String, PluginDownloader>() private val ourShownNotifications = MultiMap<NotificationUniqueType, Notification>() val excludedFromUpdateCheckPlugins = hashSetOf<String>() private val updateUrl: String get() = System.getProperty("idea.updates.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls.checkingUrl /** * For scheduled update checks. */ @JvmStatic fun updateAndShowResult(): ActionCallback { val callback = ActionCallback() ApplicationManager.getApplication().executeOnPooledThread { doUpdateAndShowResult(null, true, false, UpdateSettings.getInstance(), null, callback) } return callback } /** * For manual update checks (Help | Check for Updates, Settings | Updates | Check Now) * (the latter action may pass customised update settings). */ @JvmStatic fun updateAndShowResult(project: Project?, customSettings: UpdateSettings?) { val settings = customSettings ?: UpdateSettings.getInstance() val fromSettings = customSettings != null ProgressManager.getInstance().run(object : Task.Backgroundable(project, IdeBundle.message("updates.checking.progress"), true) { override fun run(indicator: ProgressIndicator) = doUpdateAndShowResult(getProject(), fromSettings, true, settings, indicator, null) override fun isConditionalModal(): Boolean = fromSettings override fun shouldStartInBackground(): Boolean = !fromSettings }) } private fun doUpdateAndShowResult(project: Project?, fromSettings: Boolean, manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?, callback: ActionCallback?) { // check platform update indicator?.text = IdeBundle.message("updates.checking.platform") val result = checkPlatformUpdate(updateSettings) if (manualCheck && result.state == UpdateStrategy.State.LOADED) { UpdateSettings.getInstance().saveLastCheckedInfo() } else if (result.state == UpdateStrategy.State.CONNECTION_ERROR) { val e = result.error if (e != null) LOG.debug(e) showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e?.message ?: "internal error")) return } // check plugins update (with regard to potential platform update) indicator?.text = IdeBundle.message("updates.checking.plugins") val buildNumber: BuildNumber? = result.newBuild?.apiVersion val incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>? = if (buildNumber != null) HashSet<IdeaPluginDescriptor>() else null val updatedPlugins: Collection<PluginDownloader>? val externalUpdates: Collection<ExternalUpdate>? try { updatedPlugins = checkPluginsUpdate(updateSettings, indicator, incompatiblePlugins, buildNumber) externalUpdates = updateExternal(manualCheck, updateSettings, indicator) } catch (e: IOException) { showErrorMessage(manualCheck, IdeBundle.message("updates.error.connection.failed", e.message)) return } // show result ApplicationManager.getApplication().invokeLater({ showUpdateResult(project, result, updateSettings, updatedPlugins, incompatiblePlugins, externalUpdates, !fromSettings, manualCheck) callback?.setDone() }, if (fromSettings) ModalityState.any() else ModalityState.NON_MODAL) } private fun checkPlatformUpdate(settings: UpdateSettings): CheckForUpdateResult { if (SystemProperties.getBooleanProperty(NO_PLATFORM_UPDATE, false)) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val updateInfo: UpdatesInfo? try { val uriBuilder = URIBuilder(updateUrl) if (URLUtil.FILE_PROTOCOL != uriBuilder.scheme) { prepareUpdateCheckArgs(uriBuilder) } val updateUrl = uriBuilder.build().toString() LogUtil.debug(LOG, "load update xml (UPDATE_URL='%s')", updateUrl) updateInfo = HttpRequests.request(updateUrl) .forceHttps(settings.canUseSecureConnection()) .connect { try { UpdatesInfo(loadElement(it.reader)) } catch (e: JDOMException) { // corrupted content, don't bother telling user LOG.info(e) null } } } catch (e: Exception) { LOG.info(e) return CheckForUpdateResult(UpdateStrategy.State.CONNECTION_ERROR, e) } if (updateInfo == null) { return CheckForUpdateResult(UpdateStrategy.State.NOTHING_LOADED, null) } val strategy = UpdateStrategy(ApplicationInfo.getInstance().build, updateInfo, settings) return strategy.checkForUpdates() } private fun checkPluginsUpdate(updateSettings: UpdateSettings, indicator: ProgressIndicator?, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, buildNumber: BuildNumber?): Collection<PluginDownloader>? { val updateable = collectUpdateablePlugins() if (updateable.isEmpty()) return null // check custom repositories and the main one for updates val toUpdate = ContainerUtil.newTroveMap<PluginId, PluginDownloader>() val hosts = RepositoryHelper.getPluginHosts() val state = InstalledPluginsState.getInstance() outer@ for (host in hosts) { try { val forceHttps = host == null && updateSettings.canUseSecureConnection() val list = RepositoryHelper.loadPlugins(host, buildNumber, null, forceHttps, indicator) for (descriptor in list) { val id = descriptor.pluginId if (updateable.containsKey(id)) { updateable.remove(id) state.onDescriptorDownload(descriptor) val downloader = PluginDownloader.createDownloader(descriptor, host, buildNumber, forceHttps) checkAndPrepareToInstall(downloader, state, toUpdate, incompatiblePlugins, indicator) if (updateable.isEmpty()) { break@outer } } } } catch (e: IOException) { LOG.debug(e) if (host != null) { LOG.info("failed to load plugin descriptions from " + host + ": " + e.message) } else { throw e } } } return if (toUpdate.isEmpty) null else toUpdate.values } /** * Returns a list of plugins which are currently installed or were installed in the previous installation from which * we're importing the settings. */ private fun collectUpdateablePlugins(): MutableMap<PluginId, IdeaPluginDescriptor> { val updateable = ContainerUtil.newTroveMap<PluginId, IdeaPluginDescriptor>() updateable += PluginManagerCore.getPlugins().filter { !it.isBundled || it.allowBundledUpdate()}.associateBy { it.pluginId } val onceInstalled = PluginManager.getOnceInstalledIfExists() if (onceInstalled != null) { try { for (line in FileUtil.loadLines(onceInstalled)) { val id = PluginId.getId(line.trim { it <= ' ' }) if (id !in updateable) { updateable.put(id, null) } } } catch (e: IOException) { LOG.error(onceInstalled.path, e) } //noinspection SSBasedInspection onceInstalled.deleteOnExit() } for (excludedPluginId in excludedFromUpdateCheckPlugins) { if (!isRequiredForAnyOpenProject(excludedPluginId)) { updateable.remove(PluginId.getId(excludedPluginId)) } } return updateable } private fun isRequiredForAnyOpenProject(pluginId: String) = ProjectManager.getInstance().openProjects.any { isRequiredForProject(it, pluginId) } private fun isRequiredForProject(project: Project, pluginId: String) = ExternalDependenciesManager.getInstance(project).getDependencies(DependencyOnPlugin::class.java).any { it.pluginId == pluginId } @Throws(IOException::class) @JvmStatic fun updateExternal(manualCheck: Boolean, updateSettings: UpdateSettings, indicator: ProgressIndicator?) : Collection<ExternalUpdate> { val result = arrayListOf<ExternalUpdate>() val manager = ExternalComponentManager.getInstance() indicator?.text = IdeBundle.message("updates.external.progress") for (source in manager.componentSources) { indicator?.checkCanceled() if (source.name in updateSettings.enabledExternalUpdateSources) { try { val siteResult = arrayListOf<UpdatableExternalComponent>() for (component in source.getAvailableVersions(indicator, updateSettings)) { if (component.isUpdateFor(manager.findExistingComponentMatching(component, source))) { siteResult.add(component) } } if (!siteResult.isEmpty()) { result.add(ExternalUpdate(siteResult, source)) } } catch (e: Exception) { LOG.warn(e) showErrorMessage(manualCheck, IdeBundle.message("updates.external.error.message", source.name, e.message ?: "internal error")) } } } return result } @Throws(IOException::class) @JvmStatic fun checkAndPrepareToInstall(downloader: PluginDownloader, state: InstalledPluginsState, toUpdate: MutableMap<PluginId, PluginDownloader>, incompatiblePlugins: MutableCollection<IdeaPluginDescriptor>?, indicator: ProgressIndicator?) { @Suppress("NAME_SHADOWING") var downloader = downloader val pluginId = downloader.pluginId if (PluginManagerCore.getDisabledPlugins().contains(pluginId)) return val pluginVersion = downloader.pluginVersion val installedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId)) if (installedPlugin == null || pluginVersion == null || PluginDownloader.compareVersionsSkipBrokenAndIncompatible(installedPlugin, pluginVersion) > 0) { var descriptor: IdeaPluginDescriptor? val oldDownloader = ourUpdatedPlugins[pluginId] if (oldDownloader == null || StringUtil.compareVersionNumbers(pluginVersion, oldDownloader.pluginVersion) > 0) { descriptor = downloader.descriptor if (descriptor is PluginNode && descriptor.isIncomplete) { if (downloader.prepareToInstall(indicator ?: EmptyProgressIndicator())) { descriptor = downloader.descriptor } ourUpdatedPlugins.put(pluginId, downloader) } } else { downloader = oldDownloader descriptor = oldDownloader.descriptor } if (descriptor != null && PluginManagerCore.isCompatible(descriptor, downloader.buildNumber) && !state.wasUpdated(descriptor.pluginId)) { toUpdate.put(PluginId.getId(pluginId), downloader) } } //collect plugins which were not updated and would be incompatible with new version if (incompatiblePlugins != null && installedPlugin != null && installedPlugin.isEnabled && !toUpdate.containsKey(installedPlugin.pluginId) && PluginManagerCore.isIncompatible(installedPlugin, downloader.buildNumber)) { incompatiblePlugins.add(installedPlugin) } } private fun showErrorMessage(showDialog: Boolean, message: String) { LOG.info(message) if (showDialog) { UIUtil.invokeLaterIfNeeded { Messages.showErrorDialog(message, IdeBundle.message("updates.error.connection.title")) } } } private fun showUpdateResult(project: Project?, checkForUpdateResult: CheckForUpdateResult, updateSettings: UpdateSettings, updatedPlugins: Collection<PluginDownloader>?, incompatiblePlugins: Collection<IdeaPluginDescriptor>?, externalUpdates: Collection<ExternalUpdate>?, enableLink: Boolean, alwaysShowResults: Boolean) { val updatedChannel = checkForUpdateResult.updatedChannel val newBuild = checkForUpdateResult.newBuild if (updatedChannel != null && newBuild != null) { val runnable = { val patch = checkForUpdateResult.findPatchForBuild(ApplicationInfo.getInstance().build) val forceHttps = updateSettings.canUseSecureConnection() UpdateInfoDialog(updatedChannel, newBuild, patch, enableLink, forceHttps, updatedPlugins, incompatiblePlugins).show() } ourShownNotifications.remove(NotificationUniqueType.PLATFORM)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { val message = IdeBundle.message("updates.ready.message", ApplicationNamesInfo.getInstance().fullProductName) showNotification(project, message, runnable, NotificationUniqueType.PLATFORM) } return } var updateFound = false if (updatedPlugins != null && !updatedPlugins.isEmpty()) { updateFound = true val runnable = { PluginUpdateInfoDialog(updatedPlugins, enableLink).show() } ourShownNotifications.remove(NotificationUniqueType.PLUGINS)?.forEach { it.expire() } if (alwaysShowResults) { runnable.invoke() } else { val plugins = updatedPlugins.joinToString { downloader -> downloader.pluginName } val message = IdeBundle.message("updates.plugins.ready.message", updatedPlugins.size, plugins) showNotification(project, message, runnable, NotificationUniqueType.PLUGINS) } } if (externalUpdates != null && !externalUpdates.isEmpty()) { updateFound = true ourShownNotifications.remove(NotificationUniqueType.EXTERNAL)?.forEach { it.expire() } for (update in externalUpdates) { val runnable = { update.source.installUpdates(update.components) } if (alwaysShowResults) { runnable.invoke() } else { val updates = update.components.joinToString(", ") val message = IdeBundle.message("updates.external.ready.message", update.components.size, updates) showNotification(project, message, runnable, NotificationUniqueType.EXTERNAL) } } } if (!updateFound && alwaysShowResults) { NoUpdatesDialog(enableLink).show() } } private fun showNotification(project: Project?, message: String, action: () -> Unit, notificationType: NotificationUniqueType) { val listener = NotificationListener { notification, event -> notification.expire() action.invoke() } val title = IdeBundle.message("update.notifications.title") val notification = NOTIFICATIONS.createNotification(title, XmlStringUtil.wrapInHtml(message), NotificationType.INFORMATION, listener) notification.whenExpired { ourShownNotifications.remove(notificationType, notification) } notification.notify(project) ourShownNotifications.putValue(notificationType, notification) } @JvmStatic fun addUpdateRequestParameter(name: String, value: String) { ourAdditionalRequestOptions.put(name, value) } private fun prepareUpdateCheckArgs(uriBuilder: URIBuilder) { addUpdateRequestParameter("build", ApplicationInfo.getInstance().build.asString()) addUpdateRequestParameter("uid", PermanentInstallationID.get()) addUpdateRequestParameter("os", SystemInfo.OS_NAME + ' ' + SystemInfo.OS_VERSION) if (ApplicationInfoEx.getInstanceEx().isEAP) { addUpdateRequestParameter("eap", "") } for ((name, value) in ourAdditionalRequestOptions) { uriBuilder.addParameter(name, if (StringUtil.isEmpty(value)) null else value) } } @Deprecated("Replaced", ReplaceWith("PermanentInstallationID.get()", "com.intellij.openapi.application.PermanentInstallationID")) @JvmStatic @Suppress("unused", "UNUSED_PARAMETER") fun getInstallationUID(c: PropertiesComponent) = PermanentInstallationID.get() @JvmStatic val disabledToUpdatePlugins: Set<String> get() { if (ourDisabledToUpdatePlugins == null) { ourDisabledToUpdatePlugins = TreeSet<String>() if (!ApplicationManager.getApplication().isUnitTestMode) { try { val file = File(PathManager.getConfigPath(), DISABLED_UPDATE) if (file.isFile) { FileUtil.loadFile(file) .split("[\\s]".toRegex()) .map { it.trim() } .filterTo(ourDisabledToUpdatePlugins!!) { it.isNotEmpty() } } } catch (e: IOException) { LOG.error(e) } } } return ourDisabledToUpdatePlugins!! } @JvmStatic fun saveDisabledToUpdatePlugins() { val plugins = File(PathManager.getConfigPath(), DISABLED_UPDATE) try { PluginManagerCore.savePluginsList(disabledToUpdatePlugins, false, plugins) } catch (e: IOException) { LOG.error(e) } } private var ourHasFailedPlugins = false @JvmStatic fun checkForUpdate(event: IdeaLoggingEvent) { if (!ourHasFailedPlugins) { val app = ApplicationManager.getApplication() if (!app.isDisposed && !app.isDisposeInProgress && UpdateSettings.getInstance().isCheckNeeded) { val pluginDescriptor = PluginManager.getPlugin(IdeErrorsDialog.findPluginId(event.throwable)) if (pluginDescriptor != null && !pluginDescriptor.isBundled) { ourHasFailedPlugins = true updateAndShowResult() } } } } private enum class NotificationUniqueType { PLATFORM, PLUGINS, EXTERNAL } }
apache-2.0
c160a55b25b1790033c413c10eac58d1
38.383019
156
0.694998
5.362795
false
false
false
false
nemerosa/ontrack
ontrack-extension-auto-versioning/src/test/java/net/nemerosa/ontrack/extension/av/config/AutoVersioningConfigTest.kt
1
1207
package net.nemerosa.ontrack.extension.av.config import net.nemerosa.ontrack.extension.av.AutoVersioningTestFixtures.sourceConfig import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class AutoVersioningConfigTest { @Test fun `Checking duplicates OK`() { AutoVersioningConfig( listOf( sourceConfig(sourceProject = "P1"), sourceConfig(sourceProject = "P2") ) ).validate() } @Test fun `Checking duplicates NOT OK`() { val ex = assertFailsWith<AutoVersioningConfigDuplicateProjectException> { AutoVersioningConfig( listOf( sourceConfig(sourceProject = "P1"), sourceConfig(sourceProject = "P1"), sourceConfig(sourceProject = "P2"), sourceConfig(sourceProject = "P3"), sourceConfig(sourceProject = "P3") ) ).validate() } assertEquals( "It is not possible to configure a source project multiple times. Duplicate projects are: P1, P3", ex.message ) } }
mit
a390e72c26b1a7b844c3af6cf42941bf
29.948718
110
0.586578
4.967078
false
true
false
false
nemerosa/ontrack
ontrack-extension-delivery-metrics/src/main/java/net/nemerosa/ontrack/extension/dm/charts/PromotionLevelSuccessRateChartProvider.kt
1
2615
package net.nemerosa.ontrack.extension.dm.charts import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.NullNode import net.nemerosa.ontrack.extension.chart.ChartDefinition import net.nemerosa.ontrack.extension.chart.ChartProvider import net.nemerosa.ontrack.extension.chart.GetChartOptions import net.nemerosa.ontrack.extension.chart.support.ChartUtils import net.nemerosa.ontrack.extension.chart.support.PercentageChart import net.nemerosa.ontrack.extension.chart.support.PercentageChartItemData import net.nemerosa.ontrack.extension.dm.data.EndToEndPromotionFilter import net.nemerosa.ontrack.extension.dm.data.EndToEndPromotionsHelper import net.nemerosa.ontrack.json.asJson import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.model.structure.PromotionLevel import org.springframework.stereotype.Component import kotlin.reflect.KClass @Component class PromotionLevelSuccessRateChartProvider( private val endToEndPromotionsHelper: EndToEndPromotionsHelper, ) : ChartProvider<PromotionLevel, PromotionLevelChartParameters, PercentageChart> { override val subjectClass: KClass<PromotionLevel> = PromotionLevel::class override fun getChartDefinition(subject: PromotionLevel) = ChartDefinition( id = name, title = "Promotion success rate", type = "percentage", config = mapOf("name" to "% of success").asJson(), parameters = mapOf("id" to subject.id()).asJson() ) override val name: String = "promotion-level-success-rate" override fun parseParameters(data: JsonNode): PromotionLevelChartParameters = data.parse() override fun getChart(options: GetChartOptions, parameters: PromotionLevelChartParameters): PercentageChart { val filter = EndToEndPromotionFilter( maxDepth = 1, promotionId = parameters.id, afterTime = options.actualInterval.start, beforeTime = options.actualInterval.end, ) val items = mutableListOf<PercentageChartItemData>() endToEndPromotionsHelper.forEachEndToEndPromotionRecord(filter) { record -> val buildCreation = record.ref.buildCreation val promoted = record.ref.promotionCreation != null val value = ChartUtils.percentageFromBoolean(promoted) items += PercentageChartItemData( timestamp = buildCreation, value = value, ) } return PercentageChart.compute( items, interval = options.actualInterval, period = options.period, ) } }
mit
1b1b8f374ce8169f3638d5696921f361
41.885246
113
0.73652
4.763206
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/typing/utils.kt
1
1963
package org.rust.ide.typing import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.highlighter.HighlighterIterator import com.intellij.psi.impl.source.tree.LeafPsiElement import com.intellij.psi.tree.IElementType import com.intellij.util.text.CharSequenceSubSequence import org.rust.lang.core.psi.RsComplexLiteral import org.rust.lang.core.psi.RsLiteralKind fun isValidOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset <= text.length /** * Beware that this returns `false` for EOF! */ fun isValidInnerOffset(offset: Int, text: CharSequence): Boolean = 0 <= offset && offset < text.length /** * Get previous and next token types relative to [iterator] position. */ fun getSiblingTokens(iterator: HighlighterIterator): Pair<IElementType?, IElementType?> { iterator.retreat() val prev = if (iterator.atEnd()) null else iterator.tokenType iterator.advance() iterator.advance() val next = if (iterator.atEnd()) null else iterator.tokenType iterator.retreat() return prev to next } /** * Creates virtual [RsLiteralKind] PSI element assuming that it is represented as * single, contiguous token in highlighter, in other words - it doesn't contain * any escape sequences etc. (hence 'dumb'). */ fun getLiteralDumb(iterator: HighlighterIterator): RsComplexLiteral? { val start = iterator.start val end = iterator.end val document = iterator.document val text = document.charsSequence val literalText = CharSequenceSubSequence(text, start, end) val elementType = iterator.tokenType ?: return null return RsLiteralKind.fromAstNode(LeafPsiElement(elementType, literalText)) as? RsComplexLiteral } fun Document.deleteChar(offset: Int) { deleteString(offset, offset + 1) } // BACKCOMPAT: 2016.3 @Suppress("DEPRECATED_BINARY_MOD_AS_REM") fun CharSequence.endsWithUnescapedBackslash(): Boolean = takeLastWhile { it == '\\' }.length % 2 == 1
mit
a1fb4687ca5fbfe350f0afdd8f81c975
32.271186
99
0.745797
4.167728
false
false
false
false
Kerr1Gan/ShareBox
share/src/main/java/com/flybd/sharebox/util/activity/ActivityUtil.kt
1
1914
package com.flybd.sharebox.util.activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import android.app.ActivityManager /** * Created by Ethan_Xiang on 2017/8/10. */ object ActivityUtil{ //Settings.ACTION_APPLICATION_DETAIL_SETTING fun getAppDetailSettingIntent(context: Context): Intent { var localIntent = Intent() localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) localIntent.setData(Uri.fromParts("package", context.getPackageName(), null)) } else if (Build.VERSION.SDK_INT <= 8) { localIntent.setAction(Intent.ACTION_VIEW) localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails") localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName()) } return localIntent } /** * 程序是否在前台运行 * */ fun isAppOnForeground(context: Context): Boolean { val activityManager = context.getApplicationContext() .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val packageName = context.getApplicationContext().getPackageName() /** * 获取Android设备中所有正在运行的App */ val appProcesses = activityManager .runningAppProcesses ?: return false for (appProcess in appProcesses) { // The name of the process that this object is associated with. if (appProcess.processName == packageName && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return true } } return false } }
apache-2.0
b90b8ad0355dab6b811ab52176e325b1
35.019231
144
0.669872
4.739241
false
false
false
false
Kerr1Gan/ShareBox
share/src/main/java/com/flybd/sharebox/notification/SimpleNotification.kt
1
2789
package com.flybd.sharebox.notification import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.preference.PreferenceManager import android.support.v4.app.NotificationCompat import android.support.v4.app.NotificationManagerCompat import android.text.TextUtils import com.flybd.sharebox.R /** * Created by KerriGan on 2017/9/3. */ abstract class SimpleNotification(val context: Context) { private var mBuilder: NotificationCompat.Builder? = null open fun buildNotification(id: Int, title: String, contentText: String, ticker: String, smallIcon: Int = R.mipmap.ic_launcher): NotificationCompat.Builder { val builder = NotificationCompat.Builder(context) builder.setContentTitle(title) builder.setContentText(contentText) builder.setSmallIcon(smallIcon) builder.setWhen(System.currentTimeMillis()) builder.setTicker(ticker) builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) builder.setAutoCancel(true) val pref = PreferenceManager.getDefaultSharedPreferences(context) val ringtoneUri = pref.getString(context.getString(R.string.key_notification_message_ringtone), context.getString(R.string.key_default_notification_message_ringtone)) val vibrate = pref.getBoolean(context.getString(R.string.key_notification_vibrate), false) if (!TextUtils.isEmpty(ringtoneUri)) { builder.setSound(Uri.parse(ringtoneUri)) } if (vibrate) { builder.setDefaults(NotificationCompat.DEFAULT_ALL or NotificationCompat.DEFAULT_VIBRATE) } mBuilder = builder return builder } open fun fullScreenIntent(builder: NotificationCompat.Builder?, requestCode: Int, intent: Intent?, highPriority: Boolean = false) { if (intent == null) { builder?.setFullScreenIntent(null, highPriority) } else { val pending = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT) builder?.setFullScreenIntent(pending, highPriority) } } open fun sendNotification(id: Int, builder: NotificationCompat.Builder?, tag: String? = null) { NotificationManagerCompat.from(context).notify(tag, id, builder?.build()!!) } open fun cancelNotification(id: Int, tag: String? = null) { NotificationManagerCompat.from(context).cancel(tag, id) } open fun cancelAllNotification() { NotificationManagerCompat.from(context).cancelAll() } abstract fun send(tag: String? = null) abstract fun cancel(tag: String? = null) open fun getCurrentBuilder(): NotificationCompat.Builder? { return mBuilder } }
apache-2.0
0973a8836a18fc9dc6a61307a65e6b2b
37.75
160
0.713876
4.775685
false
false
false
false
material-components/material-components-android-examples
Reply/app/src/main/java/com/materialstudies/reply/util/ContextExtensions.kt
1
2133
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.materialstudies.reply.util import android.annotation.SuppressLint import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.util.TypedValue import android.view.animation.AnimationUtils import android.view.animation.Interpolator import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.StyleRes import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.res.use /** * Retrieve a color from the current [android.content.res.Resources.Theme]. */ @ColorInt @SuppressLint("Recycle") fun Context.themeColor( @AttrRes themeAttrId: Int ): Int { return obtainStyledAttributes( intArrayOf(themeAttrId) ).use { it.getColor(0, Color.MAGENTA) } } /** * Retrieve a style from the current [android.content.res.Resources.Theme]. */ @StyleRes fun Context.themeStyle(@AttrRes attr: Int): Int { val tv = TypedValue() theme.resolveAttribute(attr, tv, true) return tv.data } @SuppressLint("Recycle") fun Context.themeInterpolator(@AttrRes attr: Int): Interpolator { return AnimationUtils.loadInterpolator( this, obtainStyledAttributes(intArrayOf(attr)).use { it.getResourceId(0, android.R.interpolator.fast_out_slow_in) } ) } fun Context.getDrawableOrNull(@DrawableRes id: Int?): Drawable? { return if (id == null || id == 0) null else AppCompatResources.getDrawable(this, id) }
apache-2.0
2359ae4e1ae12ffe9ec98eda1e5da1cc
29.485714
88
0.746835
4.19057
false
false
false
false
REBOOTERS/AndroidAnimationExercise
game/src/main/java/com/engineer/android/game/ui/BaseWebViewActivity.kt
1
1084
package com.engineer.android.game.ui import android.os.Bundle import android.view.ViewGroup import android.view.WindowManager import android.webkit.WebView import androidx.appcompat.app.AppCompatActivity /** * @author Rookie * @since 03-03-2020 */ abstract class BaseWebViewActivity : AppCompatActivity() { lateinit var webView: WebView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) webView = WebView(this) addContentView( webView, ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) ) val settings = webView.settings settings.javaScriptEnabled = true settings.domStorageEnabled = true settings.databaseEnabled = true webView.loadUrl(provideUrl()) } abstract fun provideUrl(): String }
apache-2.0
fb9aabcba807166f95336735007c2e45
26.820513
58
0.671587
5.262136
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/translations/lang/LangParserDefinition.kt
1
1579
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.translations.lang import com.demonwav.mcdev.translations.lang.gen.parser.LangParser import com.demonwav.mcdev.translations.lang.gen.psi.LangTypes import com.intellij.lang.ASTNode import com.intellij.lang.LanguageUtil import com.intellij.lang.ParserDefinition import com.intellij.openapi.project.Project import com.intellij.psi.FileViewProvider import com.intellij.psi.TokenType import com.intellij.psi.tree.IFileElementType import com.intellij.psi.tree.TokenSet class LangParserDefinition : ParserDefinition { override fun createParser(project: Project) = LangParser() override fun createLexer(project: Project) = LangLexerAdapter() override fun createFile(viewProvider: FileViewProvider) = LangFile(viewProvider) override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode) = LanguageUtil.canStickTokensTogetherByLexer(left, right, LangLexerAdapter()) override fun getStringLiteralElements() = STRING_LITERALS override fun getWhitespaceTokens() = WHITE_SPACES override fun getFileNodeType() = FILE override fun createElement(node: ASTNode) = LangTypes.Factory.createElement(node)!! override fun getCommentTokens() = TokenSet.EMPTY!! companion object { val WHITE_SPACES = TokenSet.create(TokenType.WHITE_SPACE) val STRING_LITERALS = TokenSet.create(LangTypes.KEY, LangTypes.VALUE) val FILE = IFileElementType(MCLangLanguage) } }
mit
45dceaa8b196956aad4e424e9fe3fd59
34.886364
87
0.775807
4.447887
false
false
false
false
thatJavaNerd/JRAW
lib/src/main/kotlin/net/dean/jraw/databind/RedditModelAdapterFactory.kt
1
11735
package net.dean.jraw.databind import com.squareup.moshi.* import net.dean.jraw.models.KindConstants import net.dean.jraw.models.Listing import net.dean.jraw.models.Subreddit import net.dean.jraw.models.internal.RedditModelEnvelope import java.lang.reflect.ParameterizedType import java.lang.reflect.Type /** * Creates JsonAdapters for a class annotated with [RedditModel]. * * This class assumes that the data is encapsulated in an envelope like this: * * ```json * { * "kind": "<kind>", * "data": { ... } * } * ``` * * The [Enveloped] annotation must be specified in order for this adapter factory to produce anything. * * ```kt * val adapter = moshi.adapter<Something>(Something::class.java, Enveloped::class.java) * val something = adapter.fromJson(json) * ``` * * If the target type does NOT have the `@RedditModel` annotation, it will be deserialized dynamically. For example, if * the JSON contains either a `Foo` or a `Bar`, we can specify their closest comment parent instead of either `Foo` or * `Bar`. * * ```kt * // Get an adapter that can deserialize boths Foos and Bars * moshi.adapter<Parent>(Parent::class.java, Enveloped::class.java) * ``` * * Dynamic deserialization works like this: * * 1. Write the JSON value into a "simple" type (e.g. a Map) * 2. Lookup the value of the "kind" node * 3. Determine the correct concrete class by looking up the kind in the [registry] * 4. Transform the intermediate JSON (the Map) into an instance of that class * * Keep in mind that dynamic deserialization is a bit hacky and is probably slower than static deserialization. */ class RedditModelAdapterFactory( /** * A Map of kinds (the value of the 'kind' node) to the concrete classes they represent. Not necessary if only * deserializing statically. Adding [Listing] to this class may cause problems. */ private val registry: Map<String, Class<*>> ) : JsonAdapter.Factory { /** @inheritDoc */ override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? { // Require @Enveloped val delegateAnnotations = Types.nextAnnotations(annotations, Enveloped::class.java) ?: return null val rawType = Types.getRawType(type) // Special handling for Listings if (rawType == Listing::class.java) { val childType = (type as ParameterizedType).actualTypeArguments.first() // Assume children are enveloped val delegate = moshi.adapter<Any>(childType, Enveloped::class.java).nullSafe() return ListingAdapter(delegate) } // If a class is marked with @RedditModel, then we can deserialize that type directly. Otherwise we have to // assume that this type is a superclass of a class marked with @RedditModel and must be deserialized // dynamically. val staticDeserialization = rawType.isAnnotationPresent(RedditModel::class.java) return if (staticDeserialization) { // Static JsonAdapter val enveloped = rawType.getAnnotation(RedditModel::class.java).enveloped return if (enveloped) { val actualType = Types.newParameterizedType(RedditModelEnvelope::class.java, type) val delegate = moshi.adapter<RedditModelEnvelope<*>>(actualType).nullSafe() // A call to /r/{subreddit}/about can return a Listing if the subreddit doesn't exist. Other types are // probably fine, so we don't need to take the performance hit when deserialzing them val expectedKind = if (type == Subreddit::class.java) KindConstants.SUBREDDIT else null StaticAdapter(registry, delegate, expectedKind) } else { moshi.nextAdapter<Any>(this, type, delegateAnnotations).nullSafe() } } else { // Dynamic JsonAdapter DynamicAdapter(registry, moshi, rawType) } } /** * Statically (normally) deserializes some JSON value into a concrete class. All generic types must be resolved * beforehand. * * @param expectedKind If non-null, asserts that the value of the "kind" property is equal to this. Only applies to * deserialization. */ internal class StaticAdapter( private val registry: Map<String, Class<*>>, private val delegate: JsonAdapter<RedditModelEnvelope<*>>, internal val expectedKind: String? = null ) : JsonAdapter<Any>() { override fun toJson(writer: JsonWriter, value: Any?) { if (value == null) { writer.nullValue() return } // Reverse lookup the actual value of 'kind' from the registry var actualKind: String? = null for ((kind, clazz) in registry) if (clazz == value.javaClass) actualKind = kind if (actualKind == null) throw IllegalArgumentException("No registered kind for Class '${value.javaClass}'") delegate.toJson(writer, RedditModelEnvelope.create(actualKind, value)) } override fun fromJson(reader: JsonReader): Any? { val envelope = if (expectedKind != null) { val path = reader.path val properties = reader.readJsonValue() as? Map<*, *> ?: throw JsonDataException("Expected an object at $path") val kind = properties["kind"] ?: throw JsonDataException("Expected a value at $path.kind") if (kind != expectedKind) throw JsonDataException("Expected value at $path.kind to equal '$expectedKind', was ('$kind')") delegate.fromJsonValue(properties) } else { delegate.fromJson(reader) } return envelope?.data } } internal class DynamicAdapter( private val registry: Map<String, Class<*>>, private val moshi: Moshi, internal val upperBound: Class<*> ) : JsonAdapter<Any>() { override fun toJson(writer: JsonWriter?, value: Any?) { throw UnsupportedOperationException("Serializing dynamic models aren't supported right now") } override fun fromJson(reader: JsonReader): Any { val path = reader.path val json = expectType<Map<String, Any>>(reader.readJsonValue(), path) val kind = expectType<String>(json["kind"], "$path.kind") val clazz = registry[kind] ?: throw IllegalArgumentException("No registered class for kind '$kind'") val envelopeType = Types.newParameterizedType(RedditModelEnvelope::class.java, clazz) val adapter = moshi.adapter<RedditModelEnvelope<*>>(envelopeType) val result = adapter.fromJsonValue(json)!! return ensureInBounds(result.data) } /** * Asserts that the given object is not null and the same class or a subclass of [upperBound]. Returns the value * after the check. */ private fun ensureInBounds(obj: Any?): Any { if (!upperBound.isAssignableFrom(obj!!.javaClass)) throw IllegalArgumentException("Expected ${upperBound.name} to be assignable from $obj") return obj } } internal class ListingAdapter(private val childrenDelegate: JsonAdapter<Any>) : JsonAdapter<Listing<Any>>() { override fun fromJson(reader: JsonReader): Listing<Any> { val path = reader.path // Some very smart person at reddit decided the best way to represent an empty array was with an empty // string value. See: Message.replies and Comment.replies if (reader.peek() == JsonReader.Token.STRING) { reader.nextString() return Listing.empty() } // Assume that the JSON is enveloped, we have to strip that away and then parse the listing reader.beginObject() var listing: Listing<Any>? = null while (reader.hasNext()) { when (reader.selectName(envelopeOptions)) { 0 -> { // "kind" val kind = reader.nextString() if (kind != KindConstants.LISTING) throw IllegalArgumentException("Expected '${KindConstants.LISTING}' at ${reader.path}, got '$kind'") } 1 -> { // "data" if (reader.peek() == JsonReader.Token.NULL) throw JsonDataException("Expected a non-null value at $path.data") listing = readListing(reader) } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return listing ?: throw JsonDataException("Expected a value at $path.data") } private fun readListing(reader: JsonReader): Listing<Any> { var after: String? = null val children: MutableList<Any> = ArrayList() reader.beginObject() while (reader.hasNext()) { when (reader.selectName(listingOptions)) { 0 -> { // "after" after = if (reader.peek() == JsonReader.Token.NULL) reader.nextNull() else reader.nextString() } 1 -> { // "data" reader.beginArray() while (reader.hasNext()) children.add(childrenDelegate.fromJson(reader)!!) reader.endArray() } -1 -> { // Unknown, skip it reader.nextName() reader.skipValue() } } } reader.endObject() return Listing.create(after, children) } override fun toJson(writer: JsonWriter, value: Listing<Any>?) { if (value == null) { writer.nullValue() return } writer.beginObject() writer.name("kind") writer.value(KindConstants.LISTING) writer.name("data") writeListing(writer, value) writer.endObject() } private fun writeListing(writer: JsonWriter, value: Listing<Any>) { writer.beginObject() writer.name("after") writer.value(value.nextName) writer.name("children") writer.beginArray() for (child in value.children) childrenDelegate.toJson(writer, child) writer.endArray() writer.endObject() } companion object { private val envelopeOptions = JsonReader.Options.of("kind", "data") private val listingOptions = JsonReader.Options.of("after", "children") } } /** */ companion object { private inline fun <reified T> expectType(obj: Any?, path: String): T { if (obj == null) throw JsonDataException("Expected value at '$path' to be non-null") return obj as? T ?: throw JsonDataException("Expected value at '$path' to be a ${T::class.java.name}, was ${obj::class.java.name}") } } }
mit
4e00a1a47a050b9202fcd3a62ccc2588
39.605536
128
0.575714
5.077888
false
false
false
false
soywiz/korge
korge/src/jvmTest/kotlin/com/soywiz/korge/view/camera/CameraTest.kt
1
2539
package com.soywiz.korge.view.camera import com.soywiz.klock.* import com.soywiz.korge.* import com.soywiz.korge.input.* import com.soywiz.korge.time.* import com.soywiz.korge.view.* import com.soywiz.korge.view.tween.* import com.soywiz.korgw.* import com.soywiz.korim.color.* import com.soywiz.korma.geom.* import kotlinx.coroutines.* import kotlin.math.* fun main(): Unit = runBlocking { korge() } suspend fun korge() = Korge(quality = GameWindow.Quality.PERFORMANCE, title = "Camera test", bgcolor = Colors.WHITE) { onClick { speed = abs(speed - 1.0) } val cam = CameraOld(0.0, 0.0, 400.0, 400.0) val cam2 = cam.copy() val container = cameraContainerOld(400.0, 400.0, decoration = { solidRect(width, height, Colors.PINK) }) { solidRect(400.0, 400.0, Colors.YELLOW) solidRect(350.0, 350.0, Colors.YELLOWGREEN) solidRect(300.0, 300.0, Colors.GREENYELLOW) solidRect(250.0, 250.0, Colors.GREEN) polygon(50.0, 7, Colors.DARKGREY).position(200.0, 100.0) } container.camera = cam val container2 = cameraContainerOld(800.0, 800.0, decoration = { position(500.0, 0.0); solidRect(width, height, Colors.PINK) }) { //TODO: implement container that copies content view of another container } container2.camera.zoom = 0.5 delay(1.seconds) cam.x -= 50.0 delay(1.seconds) cam.x += 50.0 delay(1.seconds) cam.size(350.0, 350.0) delay(1.seconds) cam.size(300.0, 300.0) delay(1.seconds) cam.size(250.0, 250.0) delay(1.seconds) cam.setTo(cam2) delay(1.seconds) cam.anchor(0.5, 0.5) cam.xy(200.0, 200.0) cam.rotate(90.degrees, 1.seconds) cam.rotate((-90).degrees, 1.seconds) cam.setTo(cam2) cam.moveTo(10.0, 10.0, time = 1.seconds) cam.moveTo(50.0, 50.0, time = 1.seconds) cam.moveTo(0.0, 0.0, time = 1.seconds) cam.resizeTo(350.0, 300.0, 1.seconds) cam.resizeTo(300.0, 200.0, 1.seconds) cam.resizeTo(250.0, 100.0, 1.seconds) cam.zoom(0.25, time = 2.seconds) cam.tweenTo(cam2, time = 2.seconds) lateinit var actor: View container.updateContent { actor = solidRect(50.0, 50.0, Colors.RED) actor.centerOn(this) } delay(1.seconds) cam.xy(200.0, 200.0) cam.anchor(0.5, 0.5) cam.tweenTo(zoom = 2.0, time = 1.seconds) delay(1.seconds) cam.follow(actor, 20.0) actor.moveBy(150.0, 150.0, 3.seconds) actor.moveBy(-100.0, -100.0, 2.seconds) cam.unfollow() actor.moveBy(100.0, 100.0, 1.seconds) }
apache-2.0
c13b0fdac2588c5574c0a0e17e91ec1b
28.523256
133
0.64356
2.875425
false
false
false
false
jitsi/jicofo
jicofo/src/main/kotlin/org/jitsi/jicofo/xmpp/AvModerationHandler.kt
1
6311
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2021-Present 8x8, 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 org.jitsi.jicofo.xmpp import org.jitsi.impl.protocol.xmpp.RegistrationListener import org.jitsi.impl.protocol.xmpp.XmppProvider import org.jitsi.jicofo.ConferenceStore import org.jitsi.jicofo.TaskPools import org.jitsi.utils.MediaType import org.jitsi.utils.logging2.createLogger import org.jitsi.xmpp.extensions.jitsimeet.JsonMessageExtension import org.jivesoftware.smack.StanzaListener import org.jivesoftware.smack.filter.MessageTypeFilter import org.jivesoftware.smack.packet.Stanza import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import org.jxmpp.jid.DomainBareJid import org.jxmpp.jid.impl.JidCreate import java.lang.IllegalArgumentException import kotlin.jvm.Throws /** * Adds the A/V moderation handling. Process incoming messages and when audio or video moderation is enabled, * muted all participants in the meeting (that are not moderators). Moderators are always allowed to unmute. */ class AvModerationHandler( private val xmppProvider: XmppProvider, private val conferenceStore: ConferenceStore ) : RegistrationListener, StanzaListener { private var avModerationAddress: DomainBareJid? = null private val logger = createLogger() init { xmppProvider.xmppConnection.addSyncStanzaListener(this, MessageTypeFilter.NORMAL) xmppProvider.addRegistrationListener(this) registrationChanged(xmppProvider.isRegistered) } override fun processStanza(stanza: Stanza) { if (stanza.from != avModerationAddress) { return } val jsonMessage = stanza.getExtension( JsonMessageExtension::class.java ) ?: return Unit.also { logger.warn("Skip processing stanza without JsonMessageExtension") } TaskPools.ioPool.execute { try { val incomingJson = JSONParser().parse(jsonMessage.json) as JSONObject if (incomingJson["type"] == "av_moderation") { val conferenceJid = JidCreate.entityBareFrom(incomingJson["room"]?.toString()) val conference = conferenceStore.getConference(conferenceJid) ?: throw IllegalStateException("Conference $conferenceJid does not exist.") val chatRoom = conference.chatRoom ?: throw IllegalStateException("Conference has no associated chatRoom.") val enabled = incomingJson["enabled"] as Boolean? if (enabled != null) { val mediaType = MediaType.parseString(incomingJson["mediaType"] as String) val oldEnabledValue = chatRoom.isAvModerationEnabled(mediaType) chatRoom.setAvModerationEnabled(mediaType, enabled) if (oldEnabledValue != enabled && enabled) { logger.info( "Moderation for $mediaType in $conferenceJid was enabled by ${incomingJson["actor"]}" ) // let's mute everyone conference.muteAllParticipants(mediaType) } } else { incomingJson["whitelists"]?.let { chatRoom.updateAvModerationWhitelists(parseAsMapOfStringToListOfString(it)) } } } } catch (e: Exception) { logger.warn("Failed to process av_moderation request from ${stanza.from}", e) } } } /** * When the connection is registered we do disco-info query to check for 'av_moderation' component * and we use that address to verify incoming messages. * We do that only once for the life of jicofo and skip it on reconnections. */ override fun registrationChanged(registered: Boolean) { if (!registered) { avModerationAddress = null return } try { val info = xmppProvider.discoverInfo(JidCreate.bareFrom(XmppConfig.client.xmppDomain)) val avModIdentities = info?.getIdentities("component", "av_moderation") if (avModIdentities != null && avModIdentities.size > 0) { avModerationAddress = JidCreate.domainBareFrom(avModIdentities[0].name) logger.info("Discovered av_moderation component at $avModerationAddress.") } else { avModerationAddress = null logger.info("Did not discover av_moderation component.") } } catch (e: Exception) { avModerationAddress = null logger.error("Error checking for av_moderation component", e) } } fun shutdown() { xmppProvider.xmppConnection.removeSyncStanzaListener(this) } } /** * Parses the given object (expected to be a [JSONObject]) as a Map<String, List<String>>. Throws * [IllegalArgumentException] if [o] is not of the expected type. * @return a map that is guaranteed to have a runtime type of Map<String, List<String>>. */ @Throws(IllegalArgumentException::class) private fun parseAsMapOfStringToListOfString(o: Any): Map<String, List<String>> { val jsonObject: JSONObject = o as? JSONObject ?: throw IllegalArgumentException("Not a JSONObject") val map = mutableMapOf<String, List<String>>() jsonObject.forEach { (k, v) -> k as? String ?: throw IllegalArgumentException("Key is not a string") v as? List<*> ?: throw IllegalArgumentException("Value is not a list") map[k] = v.map { it.toString() } } return map }
apache-2.0
704d491e8ba3f1290bb0a765846ce7bb
41.355705
117
0.648709
4.880897
false
false
false
false
martin-nordberg/KatyDOM
Katydid-CSS-JS/src/main/kotlin/i/katydid/css/colors/RgbColor.kt
1
9193
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.css.colors import o.katydid.css.colors.Color import o.katydid.css.colors.rgba import x.katydid.css.infrastructure.makeDecimalString //--------------------------------------------------------------------------------------------------------------------- internal class RgbColor( itsRedByte: Int, itsGreenByte: Int, itsBlueByte: Int, itsAlpha: Float, itsColorName: String? = null ) : Color { private val myRedByte = if (itsRedByte < 0) 0 else if (itsRedByte > 255) 255 else itsRedByte private val myGreenByte = if (itsGreenByte < 0) 0 else if (itsGreenByte > 255) 255 else itsGreenByte private val myBlueByte = if (itsBlueByte < 0) 0 else if (itsBlueByte > 255) 255 else itsBlueByte private val myAlpha = if (itsAlpha < 0) 0f else if (itsAlpha > 1) 1f else itsAlpha private val myColorName = itsColorName //// init { if (myColorName != null && !namedColorsByHashCode.containsKey(this.hashCode())) { namedColorsByHashCode.put(this.hashCode(), this) } } constructor( itsRed: Int, itsGreen: Int, itsBlue: Int, itsAlpha: Float ) : this( itsRed, itsGreen, itsBlue, itsAlpha, null ) constructor( itsRedFraction: Float, itsGreenFraction: Float, itsBlueFraction: Float, itsAlpha: Float = 1.0f ) : this( (itsRedFraction * 255 + 0.49).toInt(), (itsGreenFraction * 255 + 0.49).toInt(), (itsBlueFraction * 255 + 0.49).toInt(), itsAlpha, null ) override fun equals(other: Any?): Boolean { if (other is RgbColor) { return this.myAlpha == other.myAlpha && this.myRedByte == other.myRedByte && this.myGreenByte == other.myGreenByte && this.myBlueByte == other.myBlueByte } if (other is HslColor) { return this.toHslColor().equals(other) } return false } override fun hashCode(): Int { return myRedByte.shl(24) + myGreenByte.shl(16) + myBlueByte.shl(8) + (myAlpha * 255).toInt() } override fun opacified(alphaIncrement: Float) = RgbColor(myRedByte, myGreenByte, myBlueByte, myAlpha + alphaIncrement) override fun toString(): String { if (myColorName != null) { return myColorName } if (myAlpha < 1f) { val alphaStr = makeDecimalString(myAlpha) return "rgba($myRedByte,$myGreenByte,$myBlueByte,$alphaStr)" } return "#" + HEX_STRINGS[myRedByte] + HEX_STRINGS[myGreenByte] + HEX_STRINGS[myBlueByte] } override fun toHslColor(): Color { TODO("not yet implemented") } override fun toRgbColor() = this override fun transparentized(alphaDecrement: Float) = RgbColor(myRedByte, myGreenByte, myBlueByte, myAlpha - alphaDecrement) //// companion object { private val HEX_STRINGS = arrayListOf( "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" ) private val INV_HEX_STRINGS: Map<String, Int> private var namedColorsByHashCode = HashMap<Int, RgbColor>() //// init { val inv = mutableMapOf<String, Int>() for (index in 0..255) { inv[HEX_STRINGS[index]] = index } INV_HEX_STRINGS = inv } //// fun fromHex(_s: String): Color? { val s = (if (_s[0] == '#') _s.drop(1) else _s).toUpperCase() return when (s.length) { 1 -> { // 0xb (odd) val b = parseShortHandByte(s[0]) rgba(0, 0, b, 1f) } 2 -> { // 0xgb (odd) val g = parseShortHandByte(s[0]) val b = parseShortHandByte(s[1]) rgba(0, g, b, 1f) } 3 -> { // 0xrgb (shorthand) val r = parseShortHandByte(s[0]) val g = parseShortHandByte(s[1]) val b = parseShortHandByte(s[2]) rgba(r, g, b, 1f) } 4 -> { // 0xrgba (CSS4 shorthand) val r = parseShortHandByte(s[0]) val g = parseShortHandByte(s[1]) val b = parseShortHandByte(s[2]) val a = parseShortHandByte(s[3]) rgba(r, g, b, (a + 0.49f) / 255f) } 5 -> { // 0xrggbb (odd) val r = parseByte("0" + s[0]) val g = parseByte(s.substring(1, 3)) val b = parseByte(s.substring(3, 5)) rgba(r, g, b, 1f) } 6 -> { // 0xrrggbb (usual) val r = parseByte(s.substring(0, 2)) val g = parseByte(s.substring(2, 4)) val b = parseByte(s.substring(4, 6)) rgba(r, g, b, 1f) } 7 -> { // 0xrggbbaa (odd) val r = parseByte("0" + s[0]) val g = parseByte(s.substring(1, 3)) val b = parseByte(s.substring(3, 5)) val a = parseByte(s.substring(5, 7)) rgba(r, g, b, (a + 0.49f) / 255) } 8 -> { // 0xrrggbbaa (CSS4) val r = parseByte(s.substring(0, 2)) val g = parseByte(s.substring(2, 4)) val b = parseByte(s.substring(4, 6)) val a = parseByte(s.substring(6, 8)) rgba(r, g, b, (a + 0.49f) / 255) } else -> null } } // TODO: not sure this is useful. If it is needs to be non-Java dependent // fun fromHex(value: Int): RgbColor? { // // if (value < 0x1000) { // return fromHex(Integer.toHexString(value).padStart(3, '0')) // } // else if (value < 0x1000000) { // return fromHex(Integer.toHexString(value).padStart(6, '0')) // } // else { // return fromHex(Integer.toHexString(value).padStart(8, '0')) // } // // } fun getNamedColorByHashCode(hashCode: Int): RgbColor? = namedColorsByHashCode.get(hashCode) private fun parseByte(byteStr: String) = INV_HEX_STRINGS[byteStr] ?: throw IllegalArgumentException("Invalid hex byte: '$byteStr'.") private fun parseShortHandByte(byteChar: Char) = when (byteChar) { '0' -> 0 '1' -> 0x11 '2' -> 0x22 '3' -> 0x33 '4' -> 0x44 '5' -> 0x55 '6' -> 0x66 '7' -> 0x77 '8' -> 0x88 '9' -> 0x99 'A' -> 0xAA 'B' -> 0xBB 'C' -> 0xCC 'D' -> 0xDD 'E' -> 0xEE 'F' -> 0xFF else -> throw IllegalArgumentException("Invalid hex byte shorthand: '$byteChar'.") } } } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
e940524d0dc430af34ce2bbf4d16bc5c
33.690566
119
0.431742
3.27386
false
false
false
false
apixandru/intellij-community
python/pluginMinor/com/jetbrains/python/minor/sdk/PyPluginSdkModuleConfigurable.kt
18
2595
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.minor.sdk import com.intellij.facet.FacetManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.options.UnnamedConfigurable import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.jetbrains.python.configuration.PyActiveSdkConfigurable import com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable import com.jetbrains.python.facet.PythonFacetUtil import com.jetbrains.python.minor.facet.PythonFacet import com.jetbrains.python.minor.facet.PythonFacetType /** * @author traff */ class PyPluginSdkModuleConfigurable(project: Project?) : PyActiveSdkModuleConfigurable(project) { override fun createModuleConfigurable(module: Module): UnnamedConfigurable { return object : PyActiveSdkConfigurable(module) { override fun setSdk(item: Sdk?) { val facetManager = FacetManager.getInstance(module) val facet = facetManager.getFacetByType(PythonFacet.ID) if (facet == null) { ApplicationManager.getApplication().runWriteAction { addFacet(facetManager, item, module) } } else { setFacetSdk(facet, item, module) } } override fun getSdk(): Sdk? { val facetManager = FacetManager.getInstance(module) val facet = facetManager.getFacetByType(PythonFacet.ID) return facet?.configuration?.sdk } } } private fun setFacetSdk(facet: PythonFacet, item: Sdk?, module: Module) { facet.configuration.sdk = item PythonFacetUtil.updateLibrary(module, facet.configuration) } private fun addFacet(facetManager: FacetManager, sdk: Sdk?, module: Module) { val facet = facetManager.addFacet(PythonFacetType.getInstance(), "Python facet", null) setFacetSdk(facet, sdk, module) } }
apache-2.0
e11ce6f3d2f7a8b05b2c0c4f9a243479
34.561644
97
0.713295
4.520906
false
true
false
false
niranjan94/show-java
app/src/main/kotlin/com/njlabs/showjava/utils/ProcessNotifier.kt
1
9661
/* * Show Java - A java/apk decompiler for android * Copyright (c) 2018 Niranjan Rajendran * * 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 <https://www.gnu.org/licenses/>. */ package com.njlabs.showjava.utils import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.BitmapFactory import android.os.Build import androidx.core.app.NotificationCompat import com.njlabs.showjava.Constants import com.njlabs.showjava.R import com.njlabs.showjava.activities.decompiler.DecompilerActivity import com.njlabs.showjava.activities.decompiler.DecompilerProcessActivity import com.njlabs.showjava.activities.decompiler.LowMemoryActivity import com.njlabs.showjava.activities.explorer.navigator.NavigatorActivity import com.njlabs.showjava.data.PackageInfo import com.njlabs.showjava.data.SourceInfo import com.njlabs.showjava.receivers.DecompilerActionReceiver import com.njlabs.showjava.utils.ktx.sourceDir import java.io.File /** * Takes care of creating, updates progress notifications along with success and failure notifications * for the decompiler process. */ class ProcessNotifier( private val context: Context, private val notificationTag: String?, private val notificationId: Int = Constants.WORKER.PROGRESS_NOTIFICATION_ID ) { private var time: Long = 0 private var isCancelled: Boolean = false private var manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager private lateinit var builder: NotificationCompat.Builder private lateinit var notification: Notification private lateinit var packageName: String private lateinit var packageLabel: String private lateinit var packageFile: File fun withPackageInfo(packageName: String, packageLabel: String, packageFile: File): ProcessNotifier { this.packageName = packageName this.packageFile = packageFile this.packageLabel = packageLabel return this } fun buildFor(title: String, packageName: String, packageLabel: String, packageFile: File, decompilerIndex: Int): ProcessNotifier { this.packageName = packageName this.packageFile = packageFile this.packageLabel = packageLabel val stopIntent = Intent(context, DecompilerActionReceiver::class.java) stopIntent.action = Constants.WORKER.ACTION.STOP stopIntent.putExtra("id", packageName) stopIntent.putExtra("packageFilePath", packageFile.canonicalFile) stopIntent.putExtra("packageName", packageName) val pendingIntentForStop = PendingIntent.getBroadcast(context, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT) val viewIntent = Intent(context, DecompilerProcessActivity::class.java) viewIntent.putExtra("packageInfo", PackageInfo(packageLabel, packageName)) viewIntent.putExtra("decompilerIndex", decompilerIndex) val manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val pendingIntentForView = PendingIntent.getActivity( context, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( Constants.WORKER.PROGRESS_NOTIFICATION_CHANNEL, "Decompiler notification", NotificationManager.IMPORTANCE_LOW ) channel.setSound(null, null) channel.enableVibration(false) manager.createNotificationChannel(channel) } val actionIcon = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) R.drawable.ic_stop_black else R.drawable.ic_stat_stop builder = NotificationCompat.Builder(context, Constants.WORKER.PROGRESS_NOTIFICATION_CHANNEL) .setDefaults(NotificationCompat.DEFAULT_ALL) .setContentTitle(packageLabel) .setContentText(title) .setSmallIcon(R.drawable.ic_stat_code) .setContentIntent(pendingIntentForView) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) .addAction(actionIcon, "Stop decompiler", pendingIntentForStop) .setOngoing(true) .setSound(null) .setAutoCancel(false) .setPriority(NotificationCompat.PRIORITY_LOW) manager.notify( notificationTag, Constants.WORKER.PROGRESS_NOTIFICATION_ID, silence(builder.build()) ) return this } private fun silence(notification: Notification): Notification { notification.sound = null notification.vibrate = null notification.defaults = notification.defaults and NotificationCompat.DEFAULT_SOUND.inv() notification.defaults = notification.defaults and NotificationCompat.DEFAULT_VIBRATE.inv() return notification } fun updateTitle(title: String, forceSet: Boolean = false) { val currentTime = System.currentTimeMillis() if (!isCancelled && (currentTime - time >= 500 || forceSet) && ::builder.isInitialized) { builder.setContentTitle(title) manager.notify(notificationTag, notificationId, silence(builder.build())) time = currentTime } } fun updateText(text: String, forceSet: Boolean = false) { val currentTime = System.currentTimeMillis() if (!isCancelled && (currentTime - time >= 500 || forceSet) && ::builder.isInitialized) { builder.setContentText(text) manager.notify(notificationTag, notificationId, silence(builder.build())) time = currentTime } } fun updateTitleText(title: String, text: String, forceSet: Boolean = false) { val currentTime = System.currentTimeMillis() if (!isCancelled && (currentTime - time >= 500 || forceSet) && ::builder.isInitialized) { builder.setContentTitle(title) builder.setContentText(text) manager.notify(notificationTag, notificationId, silence(builder.build())) time = currentTime } } fun cancel() { isCancelled = true manager.cancel(notificationTag, notificationId) } private fun complete(intent: Intent, title: String, text: String, icon: Int) { val manager: NotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val resultPendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( Constants.WORKER.COMPLETION_NOTIFICATION_CHANNEL, "Decompile complete notification", NotificationManager.IMPORTANCE_HIGH ) manager.createNotificationChannel(channel) } val builder = NotificationCompat.Builder(context, Constants.WORKER.COMPLETION_NOTIFICATION_CHANNEL) .setContentTitle(title) .setContentText(text) .setSmallIcon(icon) .setContentIntent(resultPendingIntent) .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher)) .setAutoCancel(true) manager.notify( packageName, Constants.WORKER.COMPLETED_NOTIFICATION_ID, builder.build() ) } fun error() { val intent = Intent(context, DecompilerActivity::class.java) intent.putExtra("packageInfo", PackageInfo.fromFile(context, packageFile)) complete( intent, context.getString(R.string.errorDecompilingApp, packageLabel), context.getString(R.string.tapToRetry), R.drawable.ic_stat_error ) } fun lowMemory(decompiler: String) { val intent = Intent(context, LowMemoryActivity::class.java) val packageInfo = PackageInfo.fromFile(context, packageFile) intent.putExtra("packageInfo", packageInfo) intent.putExtra("decompiler", decompiler) complete( intent, context.getString(R.string.errorDecompilingApp, packageLabel), context.getString(R.string.lowMemoryStatusInfo), R.drawable.ic_stat_error ) } fun success() { val intent = Intent(context, NavigatorActivity::class.java) intent.putExtra("selectedApp", SourceInfo.from( sourceDir( packageName ) )) complete( intent, context.getString(R.string.appHasBeenDecompiled, packageLabel), context.getString(R.string.tapToViewSource), R.drawable.ic_stat_code ) } }
gpl-3.0
8448dcb2667c67f9b1ec5bfe213bc73f
39.258333
134
0.683366
5.018701
false
false
false
false
panpf/sketch
sketch/src/androidTest/java/com/github/panpf/sketch/test/utils/TestRequest.kt
1
5142
/* * Copyright (C) 2022 panpf <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.panpf.sketch.test.utils import android.content.Context import android.graphics.ColorSpace import androidx.lifecycle.Lifecycle import com.github.panpf.sketch.ComponentRegistry import com.github.panpf.sketch.cache.CachePolicy import com.github.panpf.sketch.cache.CachePolicy.ENABLED import com.github.panpf.sketch.decode.BitmapConfig import com.github.panpf.sketch.http.HttpHeaders import com.github.panpf.sketch.request.Depth import com.github.panpf.sketch.request.Depth.NETWORK import com.github.panpf.sketch.request.GlobalLifecycle import com.github.panpf.sketch.request.ImageOptions import com.github.panpf.sketch.request.ImageRequest import com.github.panpf.sketch.request.ImageRequest.Builder import com.github.panpf.sketch.request.ImageResult.Error import com.github.panpf.sketch.request.ImageResult.Success import com.github.panpf.sketch.request.Listener import com.github.panpf.sketch.request.Parameters import com.github.panpf.sketch.request.ProgressListener import com.github.panpf.sketch.resize.FixedPrecisionDecider import com.github.panpf.sketch.resize.FixedScaleDecider import com.github.panpf.sketch.resize.Precision.EXACTLY import com.github.panpf.sketch.resize.PrecisionDecider import com.github.panpf.sketch.resize.Scale.FILL import com.github.panpf.sketch.resize.ScaleDecider import com.github.panpf.sketch.resize.SizeResolver import com.github.panpf.sketch.resize.internal.DisplaySizeResolver import com.github.panpf.sketch.stateimage.ErrorStateImage import com.github.panpf.sketch.stateimage.StateImage import com.github.panpf.sketch.target.Target import com.github.panpf.sketch.transform.Transformation import com.github.panpf.sketch.transition.Transition class TestRequest( override val context: Context, override val uriString: String, override val listener: Listener<ImageRequest, Success, Error>?, override val progressListener: ProgressListener<ImageRequest>?, override val target: Target?, override val lifecycle: Lifecycle, override val definedOptions: ImageOptions, override val defaultOptions: ImageOptions?, override val depth: Depth, override val parameters: Parameters?, override val httpHeaders: HttpHeaders?, override val downloadCachePolicy: CachePolicy, override val bitmapConfig: BitmapConfig?, override val colorSpace: ColorSpace?, @Suppress("OVERRIDE_DEPRECATION") override val preferQualityOverSpeed: Boolean, override val resizeSizeResolver: SizeResolver, override val resizePrecisionDecider: PrecisionDecider, override val resizeScaleDecider: ScaleDecider, override val transformations: List<Transformation>?, override val disallowReuseBitmap: Boolean, override val ignoreExifOrientation: Boolean, override val resultCachePolicy: CachePolicy, override val placeholder: StateImage?, override val error: ErrorStateImage?, override val transitionFactory: Transition.Factory?, override val disallowAnimatedImage: Boolean, override val resizeApplyToDrawable: Boolean, override val memoryCachePolicy: CachePolicy, override val componentRegistry: ComponentRegistry?, ) : ImageRequest { constructor( context: Context, uriString: String, ) : this( context = context, uriString = uriString, listener = null, progressListener = null, target = null, lifecycle = GlobalLifecycle, definedOptions = ImageOptions(), defaultOptions = null, depth = NETWORK, parameters = null, httpHeaders = null, downloadCachePolicy = ENABLED, bitmapConfig = null, colorSpace = null, preferQualityOverSpeed = true, resizeSizeResolver = DisplaySizeResolver(context), resizePrecisionDecider = FixedPrecisionDecider(EXACTLY), resizeScaleDecider = FixedScaleDecider(FILL), transformations = null, disallowReuseBitmap = true, ignoreExifOrientation = true, resultCachePolicy = ENABLED, placeholder = null, error = null, transitionFactory = null, disallowAnimatedImage = true, resizeApplyToDrawable = true, memoryCachePolicy = ENABLED, componentRegistry = null, ) override fun newBuilder(configBlock: (Builder.() -> Unit)?): Builder { throw UnsupportedOperationException() } override fun newRequest(configBlock: (Builder.() -> Unit)?): ImageRequest { throw UnsupportedOperationException() } }
apache-2.0
acf0149da2e47a52fbd6e2787efc656e
40.144
83
0.758071
4.944231
false
false
false
false
sauloaguiar/githubcorecommitter
app/src/main/kotlin/com/sauloaguiar/githubcorecommitter/adapter/BarGraphAdapter.kt
1
2527
package com.sauloaguiar.githubcorecommitter.adapter import android.animation.ValueAnimator import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import br.com.renanbandeira.bargraphlib.adapter.BaseGraphBarAdapter import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.sauloaguiar.githubcorecommitter.R import com.sauloaguiar.githubcorecommitter.model.GithubUser import de.hdodenhof.circleimageview.CircleImageView /** * Created by sauloaguiar on 12/16/16. */ class BarGraphAdapter(var values: List<GithubUser>) : BaseGraphBarAdapter<BarGraphAdapter.ViewHolder>() { init { values = values.sortedDescending() } override fun getHighestValue(): Double { return values[0].contributions.toDouble() } override fun onBindViewHolder(holder: BarGraphAdapter.ViewHolder, position: Int) { val githubUser = values[position] holder.value.text = githubUser.contributions.toString() val valueHeight = getItemBarHeight(githubUser.contributions.toDouble()) holder.line?.layoutParams?.height = valueHeight val valueAnimator = ValueAnimator.ofInt(10, valueHeight) valueAnimator.duration = 2500 valueAnimator.addUpdateListener { animation -> val value = animation.animatedValue as Int holder.line?.layoutParams?.height = value holder.line?.requestLayout() } valueAnimator.start() holder.photo.setImageResource(R.drawable.womam_1) Glide.with(holder.itemView.context) .load(githubUser.imageUrl) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .crossFade() .error(R.drawable.github) .into(holder.photo) } override fun getItemCount(): Int { return this.values.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): BarGraphAdapter.ViewHolder { val view = LayoutInflater.from(parent?.context).inflate(R.layout.recycler_item_graph, parent, false) return ViewHolder(view) } class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { val value:TextView = itemView?.findViewById(R.id.value) as TextView val line = itemView?.findViewById(R.id.line) val photo:CircleImageView = itemView?.findViewById(R.id.friendPhoto) as CircleImageView } }
gpl-3.0
b664bab5ba29490d33300dd02232cd4e
35.623188
108
0.713494
4.371972
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/receivers/AutoMuteSetup.kt
1
2919
package com.sapuseven.untis.receivers import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Context.ALARM_SERVICE import android.content.Intent import android.util.Log import com.sapuseven.untis.data.timetable.TimegridItem import com.sapuseven.untis.helpers.config.PreferenceManager import com.sapuseven.untis.helpers.config.PreferenceUtils import com.sapuseven.untis.receivers.AutoMuteReceiver.Companion.EXTRA_BOOLEAN_MUTE import com.sapuseven.untis.receivers.AutoMuteReceiver.Companion.EXTRA_INT_ID import org.joda.time.LocalDateTime class AutoMuteSetup : LessonEventSetup() { private lateinit var preferenceManager: PreferenceManager override fun onReceive(context: Context, intent: Intent) { Log.d("AutoMuteSetup", "AutoMuteSetup received") preferenceManager = PreferenceManager(context) if (PreferenceUtils.getPrefBool(preferenceManager, "preference_automute_enable")) super.onReceive(context, intent) } override fun onLoadingSuccess(context: Context, items: List<TimegridItem>) { items.merged().sortedBy { it.startDateTime }.zipWithNext().withLast().forEach { it.first?.let { item -> val alarmManager = context.getSystemService(ALARM_SERVICE) as AlarmManager val id = item.startDateTime.millisOfDay / 1000 if (item.endDateTime.millisOfDay <= LocalDateTime.now().millisOfDay) return@forEach if (item.periodData.isCancelled() && !PreferenceUtils.getPrefBool(preferenceManager, "preference_automute_cancelled_lessons")) return@forEach val muteIntent = Intent(context, AutoMuteReceiver::class.java) .putExtra(EXTRA_INT_ID, id) .putExtra(EXTRA_BOOLEAN_MUTE, true) val pendingMuteIntent = PendingIntent.getBroadcast(context, item.startDateTime.millisOfDay, muteIntent, 0) alarmManager.setExact(AlarmManager.RTC_WAKEUP, item.startDateTime.millis, pendingMuteIntent) Log.d("AutoMuteSetup", "${item.periodData.getShortTitle()} mute scheduled for ${item.startDateTime}") val minimumBreakLengthMillis = PreferenceUtils.getPrefInt(preferenceManager, "preference_automute_minimum_break_length") * 60 * 1000 if (it.second != null && it.second!!.startDateTime.millisOfDay - item.endDateTime.millisOfDay < minimumBreakLengthMillis) return@forEach // No break exists or break it's short, don't unmute val unmuteIntent = Intent(context, AutoMuteReceiver::class.java) .putExtra(EXTRA_INT_ID, id) .putExtra(EXTRA_BOOLEAN_MUTE, false) val pendingUnmuteIntent = PendingIntent.getBroadcast(context, item.endDateTime.millisOfDay, unmuteIntent, 0) alarmManager.setExact(AlarmManager.RTC_WAKEUP, item.endDateTime.millis, pendingUnmuteIntent) Log.d("AutoMuteSetup", "${item.periodData.getShortTitle()} unmute scheduled for ${item.endDateTime}") } } } override fun onLoadingError(context: Context, requestId: Int, code: Int?, message: String?) {} }
gpl-3.0
8be4f3bdea09964847f489b1eac839d9
49.327586
145
0.782117
4.076816
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/storage/Domain.kt
1
19634
package pl.wendigo.chrome.api.storage import kotlinx.serialization.json.Json /** * StorageDomain represents Storage protocol domain request/response operations and events that can be captured. * * This API is marked as experimental in protocol definition and can change in the future. * @link Protocol [Storage](https://chromedevtools.github.io/devtools-protocol/tot/Storage) domain documentation. */ @pl.wendigo.chrome.protocol.Experimental class StorageDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain("Storage", """""", connection) { /** * Clears storage for origin. * * @link Protocol [Storage#clearDataForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForOrigin) method documentation. */ fun clearDataForOrigin(input: ClearDataForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.clearDataForOrigin", Json.encodeToJsonElement(ClearDataForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Returns all browser cookies. * * @link Protocol [Storage#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies) method documentation. */ fun getCookies(input: GetCookiesRequest): io.reactivex.rxjava3.core.Single<GetCookiesResponse> = connection.request("Storage.getCookies", Json.encodeToJsonElement(GetCookiesRequest.serializer(), input), GetCookiesResponse.serializer()) /** * Sets given cookies. * * @link Protocol [Storage#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setCookies) method documentation. */ fun setCookies(input: SetCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.setCookies", Json.encodeToJsonElement(SetCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Clears cookies. * * @link Protocol [Storage#clearCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearCookies) method documentation. */ fun clearCookies(input: ClearCookiesRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.clearCookies", Json.encodeToJsonElement(ClearCookiesRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Returns usage and quota in bytes. * * @link Protocol [Storage#getUsageAndQuota](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota) method documentation. */ fun getUsageAndQuota(input: GetUsageAndQuotaRequest): io.reactivex.rxjava3.core.Single<GetUsageAndQuotaResponse> = connection.request("Storage.getUsageAndQuota", Json.encodeToJsonElement(GetUsageAndQuotaRequest.serializer(), input), GetUsageAndQuotaResponse.serializer()) /** * Override quota for the specified origin * * @link Protocol [Storage#overrideQuotaForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-overrideQuotaForOrigin) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun overrideQuotaForOrigin(input: OverrideQuotaForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.overrideQuotaForOrigin", Json.encodeToJsonElement(OverrideQuotaForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Registers origin to be notified when an update occurs to its cache storage list. * * @link Protocol [Storage#trackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForOrigin) method documentation. */ fun trackCacheStorageForOrigin(input: TrackCacheStorageForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.trackCacheStorageForOrigin", Json.encodeToJsonElement(TrackCacheStorageForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Registers origin to be notified when an update occurs to its IndexedDB. * * @link Protocol [Storage#trackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForOrigin) method documentation. */ fun trackIndexedDBForOrigin(input: TrackIndexedDBForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.trackIndexedDBForOrigin", Json.encodeToJsonElement(TrackIndexedDBForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Unregisters origin from receiving notifications for cache storage. * * @link Protocol [Storage#untrackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForOrigin) method documentation. */ fun untrackCacheStorageForOrigin(input: UntrackCacheStorageForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.untrackCacheStorageForOrigin", Json.encodeToJsonElement(UntrackCacheStorageForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Unregisters origin from receiving notifications for IndexedDB. * * @link Protocol [Storage#untrackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForOrigin) method documentation. */ fun untrackIndexedDBForOrigin(input: UntrackIndexedDBForOriginRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Storage.untrackIndexedDBForOrigin", Json.encodeToJsonElement(UntrackIndexedDBForOriginRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Returns the number of stored Trust Tokens per issuer for the current browsing context. * * @link Protocol [Storage#getTrustTokens](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getTrustTokens) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun getTrustTokens(): io.reactivex.rxjava3.core.Single<GetTrustTokensResponse> = connection.request("Storage.getTrustTokens", null, GetTrustTokensResponse.serializer()) /** * A cache's contents have been modified. */ fun cacheStorageContentUpdated(): io.reactivex.rxjava3.core.Flowable<CacheStorageContentUpdatedEvent> = connection.events("Storage.cacheStorageContentUpdated", CacheStorageContentUpdatedEvent.serializer()) /** * A cache has been added/deleted. */ fun cacheStorageListUpdated(): io.reactivex.rxjava3.core.Flowable<CacheStorageListUpdatedEvent> = connection.events("Storage.cacheStorageListUpdated", CacheStorageListUpdatedEvent.serializer()) /** * The origin's IndexedDB object store has been modified. */ fun indexedDBContentUpdated(): io.reactivex.rxjava3.core.Flowable<IndexedDBContentUpdatedEvent> = connection.events("Storage.indexedDBContentUpdated", IndexedDBContentUpdatedEvent.serializer()) /** * The origin's IndexedDB database list has been modified. */ fun indexedDBListUpdated(): io.reactivex.rxjava3.core.Flowable<IndexedDBListUpdatedEvent> = connection.events("Storage.indexedDBListUpdated", IndexedDBListUpdatedEvent.serializer()) /** * Returns list of dependant domains that should be enabled prior to enabling this domain. */ override fun getDependencies(): List<pl.wendigo.chrome.protocol.Domain> { return arrayListOf( pl.wendigo.chrome.api.browser.BrowserDomain(connection), pl.wendigo.chrome.api.network.NetworkDomain(connection), ) } } /** * Represents request frame that can be used with [Storage#clearDataForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForOrigin) operation call. * * Clears storage for origin. * @link [Storage#clearDataForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForOrigin) method documentation. * @see [StorageDomain.clearDataForOrigin] */ @kotlinx.serialization.Serializable data class ClearDataForOriginRequest( /** * Security origin. */ val origin: String, /** * Comma separated list of StorageType to clear. */ val storageTypes: String ) /** * Represents request frame that can be used with [Storage#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies) operation call. * * Returns all browser cookies. * @link [Storage#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies) method documentation. * @see [StorageDomain.getCookies] */ @kotlinx.serialization.Serializable data class GetCookiesRequest( /** * Browser context to use when called on the browser endpoint. */ val browserContextId: pl.wendigo.chrome.api.browser.BrowserContextID? = null ) /** * Represents response frame that is returned from [Storage#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies) operation call. * Returns all browser cookies. * * @link [Storage#getCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getCookies) method documentation. * @see [StorageDomain.getCookies] */ @kotlinx.serialization.Serializable data class GetCookiesResponse( /** * Array of cookie objects. */ val cookies: List<pl.wendigo.chrome.api.network.Cookie> ) /** * Represents request frame that can be used with [Storage#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setCookies) operation call. * * Sets given cookies. * @link [Storage#setCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-setCookies) method documentation. * @see [StorageDomain.setCookies] */ @kotlinx.serialization.Serializable data class SetCookiesRequest( /** * Cookies to be set. */ val cookies: List<pl.wendigo.chrome.api.network.CookieParam>, /** * Browser context to use when called on the browser endpoint. */ val browserContextId: pl.wendigo.chrome.api.browser.BrowserContextID? = null ) /** * Represents request frame that can be used with [Storage#clearCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearCookies) operation call. * * Clears cookies. * @link [Storage#clearCookies](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearCookies) method documentation. * @see [StorageDomain.clearCookies] */ @kotlinx.serialization.Serializable data class ClearCookiesRequest( /** * Browser context to use when called on the browser endpoint. */ val browserContextId: pl.wendigo.chrome.api.browser.BrowserContextID? = null ) /** * Represents request frame that can be used with [Storage#getUsageAndQuota](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota) operation call. * * Returns usage and quota in bytes. * @link [Storage#getUsageAndQuota](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota) method documentation. * @see [StorageDomain.getUsageAndQuota] */ @kotlinx.serialization.Serializable data class GetUsageAndQuotaRequest( /** * Security origin. */ val origin: String ) /** * Represents response frame that is returned from [Storage#getUsageAndQuota](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota) operation call. * Returns usage and quota in bytes. * * @link [Storage#getUsageAndQuota](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota) method documentation. * @see [StorageDomain.getUsageAndQuota] */ @kotlinx.serialization.Serializable data class GetUsageAndQuotaResponse( /** * Storage usage (bytes). */ val usage: Double, /** * Storage quota (bytes). */ val quota: Double, /** * Whether or not the origin has an active storage quota override */ val overrideActive: Boolean, /** * Storage usage per type (bytes). */ val usageBreakdown: List<UsageForType> ) /** * Represents request frame that can be used with [Storage#overrideQuotaForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-overrideQuotaForOrigin) operation call. * * Override quota for the specified origin * @link [Storage#overrideQuotaForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-overrideQuotaForOrigin) method documentation. * @see [StorageDomain.overrideQuotaForOrigin] */ @kotlinx.serialization.Serializable data class OverrideQuotaForOriginRequest( /** * Security origin. */ val origin: String, /** * The quota size (in bytes) to override the original quota with. If this is called multiple times, the overriden quota will be equal to the quotaSize provided in the final call. If this is called without specifying a quotaSize, the quota will be reset to the default value for the specified origin. If this is called multiple times with different origins, the override will be maintained for each origin until it is disabled (called without a quotaSize). */ val quotaSize: Double? = null ) /** * Represents request frame that can be used with [Storage#trackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForOrigin) operation call. * * Registers origin to be notified when an update occurs to its cache storage list. * @link [Storage#trackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForOrigin) method documentation. * @see [StorageDomain.trackCacheStorageForOrigin] */ @kotlinx.serialization.Serializable data class TrackCacheStorageForOriginRequest( /** * Security origin. */ val origin: String ) /** * Represents request frame that can be used with [Storage#trackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForOrigin) operation call. * * Registers origin to be notified when an update occurs to its IndexedDB. * @link [Storage#trackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForOrigin) method documentation. * @see [StorageDomain.trackIndexedDBForOrigin] */ @kotlinx.serialization.Serializable data class TrackIndexedDBForOriginRequest( /** * Security origin. */ val origin: String ) /** * Represents request frame that can be used with [Storage#untrackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForOrigin) operation call. * * Unregisters origin from receiving notifications for cache storage. * @link [Storage#untrackCacheStorageForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForOrigin) method documentation. * @see [StorageDomain.untrackCacheStorageForOrigin] */ @kotlinx.serialization.Serializable data class UntrackCacheStorageForOriginRequest( /** * Security origin. */ val origin: String ) /** * Represents request frame that can be used with [Storage#untrackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForOrigin) operation call. * * Unregisters origin from receiving notifications for IndexedDB. * @link [Storage#untrackIndexedDBForOrigin](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForOrigin) method documentation. * @see [StorageDomain.untrackIndexedDBForOrigin] */ @kotlinx.serialization.Serializable data class UntrackIndexedDBForOriginRequest( /** * Security origin. */ val origin: String ) /** * Represents response frame that is returned from [Storage#getTrustTokens](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getTrustTokens) operation call. * Returns the number of stored Trust Tokens per issuer for the current browsing context. * * @link [Storage#getTrustTokens](https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getTrustTokens) method documentation. * @see [StorageDomain.getTrustTokens] */ @kotlinx.serialization.Serializable data class GetTrustTokensResponse( /** * */ val tokens: List<TrustTokens> ) /** * A cache's contents have been modified. * * @link [Storage#cacheStorageContentUpdated](https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-cacheStorageContentUpdated) event documentation. */ @kotlinx.serialization.Serializable data class CacheStorageContentUpdatedEvent( /** * Origin to update. */ val origin: String, /** * Name of cache in origin. */ val cacheName: String ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Storage" override fun eventName() = "cacheStorageContentUpdated" } /** * A cache has been added/deleted. * * @link [Storage#cacheStorageListUpdated](https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-cacheStorageListUpdated) event documentation. */ @kotlinx.serialization.Serializable data class CacheStorageListUpdatedEvent( /** * Origin to update. */ val origin: String ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Storage" override fun eventName() = "cacheStorageListUpdated" } /** * The origin's IndexedDB object store has been modified. * * @link [Storage#indexedDBContentUpdated](https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-indexedDBContentUpdated) event documentation. */ @kotlinx.serialization.Serializable data class IndexedDBContentUpdatedEvent( /** * Origin to update. */ val origin: String, /** * Database to update. */ val databaseName: String, /** * ObjectStore to update. */ val objectStoreName: String ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Storage" override fun eventName() = "indexedDBContentUpdated" } /** * The origin's IndexedDB database list has been modified. * * @link [Storage#indexedDBListUpdated](https://chromedevtools.github.io/devtools-protocol/tot/Storage#event-indexedDBListUpdated) event documentation. */ @kotlinx.serialization.Serializable data class IndexedDBListUpdatedEvent( /** * Origin to update. */ val origin: String ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Storage" override fun eventName() = "indexedDBListUpdated" }
apache-2.0
15bf85920d2abcd9878fda3d77741926
41.406048
389
0.758786
4.339965
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/util/gpx/GPXParser.kt
1
9230
package com.peterlaurence.trekme.util.gpx import android.util.Xml import com.peterlaurence.trekme.core.track.TrackStatistics import com.peterlaurence.trekme.util.gpx.model.* import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import java.io.IOException import java.io.InputStream import java.text.ParseException import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList /** * A GPX parser compliant with the [GPX 1.1 schema](https://www.topografix.com/gpx/1/1/) * * @author peterLaurence on 12/02/17. */ object GPXParser { private val ns: String? = null private val DATE_PARSER = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH) /** * A version of [parse] method which returns a [Gpx] instance or null if any exception occurs. */ fun parseSafely(input: InputStream): Gpx? { try { input.use { return parse(it) } } catch (e: Exception) { return null } } @Throws(XmlPullParserException::class, IOException::class, ParseException::class) fun parse(`in`: InputStream): Gpx { `in`.use { val parser = Xml.newPullParser() parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) parser.setInput(it, null) parser.nextTag() return readGpx(parser) } } @Throws(XmlPullParserException::class, IOException::class, ParseException::class) private fun readGpx(parser: XmlPullParser): Gpx { val tracks = ArrayList<Track>() val wayPoints = ArrayList<TrackPoint>() parser.require(XmlPullParser.START_TAG, ns, TAG_GPX) while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } val name = parser.name // Starts by looking for the entry tag when (name) { TAG_TRACK -> tracks.add(readTrack(parser)) TAG_WAYPOINT -> wayPoints.add(readPoint(parser, tag = TAG_WAYPOINT)) else -> skip(parser) } } parser.require(XmlPullParser.END_TAG, ns, TAG_GPX) return Gpx(tracks = tracks, wayPoints = wayPoints) } /** * Parses the contents of an entry. * * If it encounters a title, summary, or link tag, hands them off to their respective "read" * methods for processing. Otherwise, skips the tag. */ @Throws(XmlPullParserException::class, IOException::class, ParseException::class) private fun readTrack(parser: XmlPullParser): Track { val segments = ArrayList<TrackSegment>() parser.require(XmlPullParser.START_TAG, ns, TAG_TRACK) var trackName = "" var trackStatistics: TrackStatistics? = null while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } val name = parser.name when (name) { TAG_NAME -> trackName = readName(parser) TAG_SEGMENT -> segments.add(readSegment(parser)) TAG_EXTENSIONS -> trackStatistics = readTrackExtensions(parser) else -> skip(parser) } } parser.require(XmlPullParser.END_TAG, ns, TAG_TRACK) return Track(trackSegments = segments, name = trackName, statistics = trackStatistics) } @Throws(IOException::class, XmlPullParserException::class, ParseException::class) private fun readTrackExtensions(parser: XmlPullParser): TrackStatistics? { parser.require(XmlPullParser.START_TAG, ns, TAG_EXTENSIONS) var trackStatistics: TrackStatistics? = null while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } when (parser.name) { TAG_TRACK_STATISTICS -> trackStatistics = readTrackStatistics(parser) else -> skip(parser) } } parser.require(XmlPullParser.END_TAG, ns, TAG_EXTENSIONS) return trackStatistics } @Throws(IOException::class, XmlPullParserException::class, ParseException::class) private fun readTrackStatistics(parser: XmlPullParser): TrackStatistics { parser.require(XmlPullParser.START_TAG, ns, TAG_TRACK_STATISTICS) val trackStatistics = TrackStatistics(0.0, 0.0, 0.0, 0.0, 0) trackStatistics.distance = parser.getAttributeValue(null, ATTR_TRK_STAT_DIST)?.toDouble() ?: 0.0 trackStatistics.elevationDifferenceMax = parser.getAttributeValue(null, ATTR_TRK_STAT_ELE_DIFF_MAX)?.toDouble() ?: 0.0 trackStatistics.elevationUpStack = parser.getAttributeValue(null, ATTR_TRK_STAT_ELE_UP_STACK)?.toDouble() ?: 0.0 trackStatistics.elevationDownStack = parser.getAttributeValue(null, ATTR_TRK_STAT_ELE_DOWN_STACK)?.toDouble() ?: 0.0 trackStatistics.durationInSecond = parser.getAttributeValue(null, ATTR_TRK_STAT_DURATION)?.toLong() ?: 0 while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } skip(parser) } parser.require(XmlPullParser.END_TAG, ns, TAG_TRACK_STATISTICS) return trackStatistics } /* Process summary tags in the feed */ @Throws(IOException::class, XmlPullParserException::class, ParseException::class) private fun readSegment(parser: XmlPullParser): TrackSegment { val points = ArrayList<TrackPoint>() parser.require(XmlPullParser.START_TAG, ns, TAG_SEGMENT) while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } val name = parser.name when (name) { TAG_POINT -> points.add(readPoint(parser)) else -> skip(parser) } } parser.require(XmlPullParser.END_TAG, ns, TAG_SEGMENT) return TrackSegment(points) } /* Process summary tags in the feed */ @Throws(IOException::class, XmlPullParserException::class, ParseException::class) private fun readPoint(parser: XmlPullParser, tag: String = TAG_POINT): TrackPoint { val trackPoint = TrackPoint() parser.require(XmlPullParser.START_TAG, ns, tag) trackPoint.latitude = java.lang.Double.valueOf(parser.getAttributeValue(null, ATTR_LAT)) trackPoint.longitude = java.lang.Double.valueOf(parser.getAttributeValue(null, ATTR_LON)) while (parser.next() != XmlPullParser.END_TAG) { if (parser.eventType != XmlPullParser.START_TAG) { continue } val name = parser.name when (name) { TAG_ELEVATION -> trackPoint.elevation = readElevation(parser) TAG_TIME -> trackPoint.time = readTime(parser) TAG_NAME -> trackPoint.name = readName(parser) else -> skip(parser) } } parser.require(XmlPullParser.END_TAG, ns, tag) return trackPoint } @Throws(IOException::class, XmlPullParserException::class) private fun readName(parser: XmlPullParser): String { parser.require(XmlPullParser.START_TAG, ns, TAG_NAME) val name = readText(parser) parser.require(XmlPullParser.END_TAG, ns, TAG_NAME) return name } @Throws(IOException::class, XmlPullParserException::class) private fun readElevation(parser: XmlPullParser): Double? { parser.require(XmlPullParser.START_TAG, ns, TAG_ELEVATION) val ele = java.lang.Double.valueOf(readText(parser)) parser.require(XmlPullParser.END_TAG, ns, TAG_ELEVATION) return ele } @Throws(IOException::class, XmlPullParserException::class, ParseException::class) private fun readTime(parser: XmlPullParser): Long? { return try { parser.require(XmlPullParser.START_TAG, ns, TAG_TIME) val time = DATE_PARSER.parse(readText(parser)) parser.require(XmlPullParser.END_TAG, ns, TAG_TIME) time.time } catch (e: Exception) { null } } @Throws(IOException::class, XmlPullParserException::class) private fun readText(parser: XmlPullParser): String { var result = "" if (parser.next() == XmlPullParser.TEXT) { result = parser.text parser.nextTag() } return result } @Throws(XmlPullParserException::class, IOException::class) private fun skip(parser: XmlPullParser) { if (parser.eventType != XmlPullParser.START_TAG) { throw IllegalStateException() } var depth = 1 while (depth != 0) { when (parser.next()) { XmlPullParser.END_TAG -> depth-- XmlPullParser.START_TAG -> depth++ } } } /** * For unit test purposes */ fun getDateParser(): SimpleDateFormat { return DATE_PARSER } }
gpl-3.0
24dc72d67027c68b07e1e09e043bb5b5
37.949367
126
0.621885
4.441771
false
false
false
false
Undin/intellij-rust
src/test/kotlin/org/rust/ide/typing/RsQuoteHandlerTest.kt
4
3167
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.typing class RsQuoteHandlerTest : RsTypingTestBase() { override val dataPath = "org/rust/ide/typing/quoteHandler/fixtures" fun `test don't complete char quotes`() = doTestByText(""" fn main() { <caret> } """, """ fn main() { '<caret> } """, '\'') fun `test complete byte quotes`() = doTestByText(""" fn main() { b<caret> } """, """ fn main() { b'<caret>' } """, '\'') fun `test byte literal with single quote before`() = doTestByText(""" b'<caret> """, """ b''<caret> """, '\'') fun `test byte literal with single quote after`() = doTestByText(""" b<caret>' """, """ b'<caret> """, '\'') fun `test complete string quotes`() = doTestByText(""" <caret> """, """ "<caret>" """, '"') fun `test complete byte string quotes`() = doTestByText(""" b<caret> """, """ b"<caret>" """, '"') fun `test complete raw string quotes with hashes`() = doTestByText(""" fn f() { let _ = r###<caret> } """, """ fn f() { let _ = r###"<caret>"### } """, '"') fun `test complete raw string quotes no hashes`() = doTestByText(""" fn f() { let _ = r<caret> } """, """ fn f() { let _ = r"<caret>" } """, '"') fun `test complete raw byte string quotes with hashes`() = doTestByText(""" fn f() { let _ = r###<caret> } """, """ fn f() { let _ = r###"<caret>"### } """, '"') fun `test complete raw byte string quotes no hashes`() = doTestByText(""" fn f() { let _ = r<caret> } """, """ fn f() { let _ = r"<caret>" } """, '"') // https://github.com/intellij-rust/intellij-rust/issues/687 fun `test double quote in raw string`() = doTestByText(""" r###"Hello, <caret> World!"### """, """ r###"Hello, "<caret> World!"### """, '"') fun `test single quote in raw string`() = doTestByText(""" r###"Hello, <caret> World!"### """, """ r###"Hello, '<caret> World!"### """, '\'') fun `test double quote in empty raw string`() = doTestByText(""" r#"<caret>"# """, """ r#""<caret>"# """, '"') fun `test single quote in empty raw string`() = doTestByText(""" r#"<caret>"# """, """ r#"'<caret>"# """, '\'') private fun checkUnclosedHeuristic(nextLiteral: String) = doTestByText(""" fn main() { let _ = <caret>; let _ = "$nextLiteral"; } """, """ fn main() { let _ = "<caret>"; let _ = "$nextLiteral"; } """, '"') fun `test test next string is empty`() = checkUnclosedHeuristic("") fun `test test next string starts with space and word`() = checkUnclosedHeuristic("\nhello world\n") fun `test test next string starts with number`() = checkUnclosedHeuristic("92") fun `test test next string starts with brace`() = checkUnclosedHeuristic("{") }
mit
59ee6a9b68f6282cfbe340c05a4704a4
26.780702
104
0.481213
4.112987
false
true
false
false
RSDT/Japp16
app/src/main/java/nl/rsdt/japp/jotial/maps/kml/KmlLocation.kt
2
923
package nl.rsdt.japp.jotial.maps.kml import java.util.* class KmlLocation(val lon: Double?, val lat: Double?, val alt: Double?) { companion object { fun readCoordinates(coordinates: String): List<KmlLocation> { val result = ArrayList<KmlLocation>() for (c in coordinates.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { val c2 = c.trim { it <= ' ' } val coordinate = c2.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (coordinate.size == 3) { result.add(KmlLocation( java.lang.Double.valueOf(coordinate[0]), java.lang.Double.valueOf(coordinate[1]), java.lang.Double.valueOf(coordinate[2]) )) } } return result } } }
apache-2.0
d8aef7507eba379e7bee54c21725b73c
37.458333
104
0.511376
4.546798
false
false
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/docker/build/DockerImageBuildIgnoreEntrySpec.kt
1
11627
/* Copyright 2017-2020 Charles Korn. 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 batect.docker.build import batect.docker.DockerException import batect.testutils.equalTo import batect.testutils.given import batect.testutils.withMessage import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.throws import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object DockerImageBuildIgnoreEntrySpec : Spek({ describe("a Docker image build ignore entry") { given("a wildcard pattern") { val entry = DockerImageBuildIgnoreEntry("*", false) it("should match anything") { assertThat(entry.matches("fileutils.go"), equalTo(MatchResult.MatchedExclude)) } } given("an inverted wildcard pattern") { val entry = DockerImageBuildIgnoreEntry("*", true) it("should match nothing") { assertThat(entry.matches("fileutils.go"), equalTo(MatchResult.MatchedInclude)) } } given("a partial wildcard pattern") { val entry = DockerImageBuildIgnoreEntry("*.go", false) it("should match anything that ends in the same suffix") { assertThat(entry.matches("fileutils.go"), equalTo(MatchResult.MatchedExclude)) } it("should match anything that just has the same suffix") { assertThat(entry.matches(".go"), equalTo(MatchResult.MatchedExclude)) } it("should not match anything that does not have the same suffix") { assertThat(entry.matches("something.else"), equalTo(MatchResult.NoMatch)) } } given("a pattern that matches a directory") { val entry = DockerImageBuildIgnoreEntry("docs", false) it("should match that directory") { assertThat(entry.matches("docs"), equalTo(MatchResult.MatchedExclude)) } it("should match anything inside that directory") { assertThat(entry.matches("docs/README.md"), equalTo(MatchResult.MatchedExclude)) } it("should not match a different directory") { assertThat(entry.matches("docs2"), equalTo(MatchResult.NoMatch)) } it("should not match anything in a different directory") { assertThat(entry.matches("docs2/README.md"), equalTo(MatchResult.NoMatch)) } } given("a pattern that matches a directory with a trailing slash") { val entry = DockerImageBuildIgnoreEntry("docs/", false) it("should match the directory, even if it is not given with a trailing slash") { assertThat(entry.matches("docs"), equalTo(MatchResult.MatchedExclude)) } it("should match anything inside that directory") { assertThat(entry.matches("docs/README.md"), equalTo(MatchResult.MatchedExclude)) } it("should not match a different directory") { assertThat(entry.matches("docs2"), equalTo(MatchResult.NoMatch)) } it("should not match anything in a different directory") { assertThat(entry.matches("docs2/README.md"), equalTo(MatchResult.NoMatch)) } } listOf( "[", "[^", "[^]", "[^bc", "\\", "[\\", "[a-", "[a-]", "[-x]", "[a-b-c]", "[]", "[]a]", "[-]", "a[" ).forEach { pattern -> given("the invalid pattern '$pattern'") { it("should throw an appropriate exception when creating the entry") { assertThat({ DockerImageBuildIgnoreEntry(pattern, false) }, throws<DockerException>(withMessage("The .dockerignore pattern '$pattern' is invalid."))) } } } // These tests are all based on https://github.com/docker/engine/blob/master/pkg/fileutils/fileutils_test.go mapOf( "**" to mapOf( "file" to true, "file/" to true, "/" to true, "dir/file" to true, "dir/file/" to true ), "**/" to mapOf( "file" to true, "file/" to true, "/" to true, "dir/file" to true, "dir/file/" to true ), "**/**" to mapOf( "dir/file" to true, "dir/file/" to true ), "dir/**" to mapOf( "dir/file" to true, "dir/file/" to true, "dir/dir2/file" to true, "dir/dir2/file/" to true ), "**/dir2/*" to mapOf( "dir/dir2/file" to true, "dir/dir2/file/" to true, "dir/dir2/dir3/file" to true, "dir/dir2/dir3/file/" to true ), "**file" to mapOf( "file" to true, "dir/file" to true ), "**file" to mapOf( "dir/dir/file" to true ), "**/file" to mapOf( "dir/file" to true, "dir/dir/file" to true ), "**/file*" to mapOf( "dir/dir/file" to true, "dir/dir/file.txt" to true ), "**/file*txt" to mapOf( "dir/dir/file.txt" to true ), "**/file*.txt" to mapOf( "dir/dir/file.txt" to true, "dir/dir/file.txt" to true ), "**/**/*.txt" to mapOf( "dir/dir/file.txt" to true ), "**/**/*.txt2" to mapOf( "dir/dir/file.txt" to false ), "**/*.txt" to mapOf( "file.txt" to true ), "**/**/*.txt" to mapOf( "file.txt" to true ), "a**/*.txt" to mapOf( "a/file.txt" to true, "a/dir/file.txt" to true, "a/dir/dir/file.txt" to true ), "a/*.txt" to mapOf( "a/dir/file.txt" to false, "a/file.txt" to true ), "a/*.txt**" to mapOf( "a/file.txt" to true ), "a[b-d]e" to mapOf( "ae" to false, "ace" to true, "aae" to false ), "a[^b-d]e" to mapOf( "aze" to true ), ".*" to mapOf( ".foo" to true, "foo" to false ), "abc.def" to mapOf( "abcdef" to false, "abc.def" to true, "abcZdef" to false ), "abc?def" to mapOf( "abcZdef" to true, "abcdef" to false ), "a\\\\" to mapOf( "a\\" to true ), "a\\b" to mapOf( "ab" to true, "ac" to false ), "**/foo/bar" to mapOf( "foo/bar" to true, "dir/foo/bar" to true, "dir/dir2/foo/bar" to true ), "abc/**" to mapOf( "abc" to false, "abc/def" to true, "abc/def/ghi" to true ), "**/.foo" to mapOf( ".foo" to true, "bar.foo" to false ), "*c" to mapOf( "abc" to true ), "a*" to mapOf( "a" to true, "abc" to true, "ab/c" to true ), "a*/b" to mapOf( "abc/b" to true, "a/c/b" to false ), "a*b*c*d*e*/f" to mapOf( "axbxcxdxe/f" to true, "axbxcxdxexxx/f" to true, "axbxcxdxe/xxx/f" to false, "axbxcxdxexxx/fff" to false ), "a*b?c*x" to mapOf( "abxbbxdbxebxczzx" to true, "abxbbxdbxebxczzy" to false ), "ab[c]" to mapOf( "abc" to true ), "ab[b-d]" to mapOf( "abc" to true ), "ab[e-g]" to mapOf( "abc" to false ), "ab[^c]" to mapOf( "abc" to false ), "ab[^b-d]" to mapOf( "abc" to false ), "ab[^e-g]" to mapOf( "abc" to true ), "a\\*b" to mapOf( "a*b" to true, "ab" to false ), "a?b" to mapOf( "a☺b" to true ), "a[^a]b" to mapOf( "a☺b" to true ), "a???b" to mapOf( "a☺b" to false ), "a[^a][^a][^a]b" to mapOf( "a☺b" to false ), "[a-ζ]*" to mapOf( "α" to true ), "*[a-ζ]" to mapOf( "A" to false ), "a?b" to mapOf( "a/b" to false ), "a*b" to mapOf( "a/b" to false ), "[\\]a]" to mapOf( "]" to true ), "[\\-]" to mapOf( "-" to true ), "[x\\-]" to mapOf( "x" to true, "-" to true, "z" to false ), "[\\-x]" to mapOf( "x" to true, "-" to true, "a" to false ), "*x" to mapOf( "xxx" to true ), " docs" to mapOf( "docs" to true ), "docs " to mapOf( "docs" to true ), "docs/ " to mapOf( "docs" to true, "docs/thing" to true ) ).forEach { (pattern, testCases) -> given("the pattern '$pattern'") { val entry = DockerImageBuildIgnoreEntry(pattern, false) testCases.forEach { (path, shouldMatch) -> if (shouldMatch) { it("should match the path '$path'") { assertThat(entry.matches(path), equalTo(MatchResult.MatchedExclude)) } } else { it("should not match the path '$path'") { assertThat(entry.matches(path), equalTo(MatchResult.NoMatch)) } } } } } } })
apache-2.0
1c680c9fbbc16cfd48a1ead6023b51e4
31.266667
169
0.425189
4.541048
false
false
false
false
androidx/androidx
health/health-services-client/src/main/java/androidx/health/services/client/data/UserActivityInfo.kt
3
4019
/* * Copyright (C) 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.health.services.client.data import androidx.health.services.client.data.UserActivityState.Companion.USER_ACTIVITY_ASLEEP import androidx.health.services.client.data.UserActivityState.Companion.USER_ACTIVITY_EXERCISE import androidx.health.services.client.data.UserActivityState.Companion.USER_ACTIVITY_PASSIVE import androidx.health.services.client.data.UserActivityState.Companion.USER_ACTIVITY_UNKNOWN import androidx.health.services.client.proto.DataProto import androidx.health.services.client.proto.DataProto.UserActivityInfo as UserActivityInfoProto import java.time.Instant /** * Represents an update from Passive tracking. * * Provides [DataPoint]s associated with the Passive tracking, in addition to data related to the * user's [UserActivityState]. */ @Suppress("ParcelCreator") public class UserActivityInfo( /** The [UserActivityState] of the user from Passive tracking. */ public val userActivityState: UserActivityState, /** * The [ExerciseInfo] of the user for a [UserActivityState.USER_ACTIVITY_EXERCISE] state, and * `null` for other [UserActivityState]s. */ public val exerciseInfo: ExerciseInfo?, /** The time at which the current state took effect. */ public val stateChangeTime: Instant, ) { internal constructor( proto: DataProto.UserActivityInfo ) : this( UserActivityState.fromProto(proto.state), if (proto.hasExerciseInfo()) ExerciseInfo(proto.exerciseInfo) else null, Instant.ofEpochMilli(proto.stateChangeTimeEpochMs) ) internal val proto: UserActivityInfoProto = getUserActivityInfoProto() private fun getUserActivityInfoProto(): UserActivityInfoProto { val builder = UserActivityInfoProto.newBuilder() .setState(userActivityState.toProto()) .setStateChangeTimeEpochMs(stateChangeTime.toEpochMilli()) exerciseInfo?.let { builder.exerciseInfo = it.proto } return builder.build() } override fun toString(): String = "UserActivityInfo(" + "userActivityState=$userActivityState, " + "stateChangeTime=$stateChangeTime, " + "exerciseInfo=$exerciseInfo)" public companion object { /** Creates a [UserActivityInfo] for [USER_ACTIVITY_UNKNOWN]. */ @JvmStatic public fun createUnknownTypeState(stateChangeTime: Instant): UserActivityInfo = UserActivityInfo(USER_ACTIVITY_UNKNOWN, exerciseInfo = null, stateChangeTime) /** Creates a [UserActivityInfo] for [USER_ACTIVITY_EXERCISE]. */ @JvmStatic public fun createActiveExerciseState( exerciseInfo: ExerciseInfo, stateChangeTime: Instant ): UserActivityInfo = UserActivityInfo(USER_ACTIVITY_EXERCISE, exerciseInfo, stateChangeTime) /** Creates a [UserActivityInfo] for [USER_ACTIVITY_PASSIVE]. */ @JvmStatic public fun createPassiveActivityState(stateChangeTime: Instant): UserActivityInfo = UserActivityInfo(USER_ACTIVITY_PASSIVE, exerciseInfo = null, stateChangeTime) /** Creates a [UserActivityInfo] for [USER_ACTIVITY_ASLEEP]. */ @JvmStatic public fun createAsleepState(stateChangeTime: Instant): UserActivityInfo = UserActivityInfo(USER_ACTIVITY_ASLEEP, exerciseInfo = null, stateChangeTime) } }
apache-2.0
61780f1d7ab1fd8d0c708ad8229ba89a
40.010204
97
0.719582
4.739387
false
false
false
false
androidx/androidx
fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentViewLifecycleTest.kt
3
20736
/* * 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.fragment.app import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.fragment.app.test.FragmentTestActivity import androidx.fragment.test.R import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewTreeLifecycleOwner import androidx.lifecycle.ViewTreeViewModelStoreOwner import androidx.savedstate.findViewTreeSavedStateRegistryOwner import androidx.test.annotation.UiThreadTest import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Assert.fail import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import leakcanary.DetectLeaksAfterTestSuccess import org.junit.rules.RuleChain @RunWith(AndroidJUnit4::class) @LargeTest class FragmentViewLifecycleTest { @Suppress("DEPRECATION") var activityRule = androidx.test.rule.ActivityTestRule(FragmentTestActivity::class.java) // Detect leaks BEFORE and AFTER activity is destroyed @get:Rule val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess()) .around(activityRule) @Test @UiThreadTest fun testFragmentViewLifecycle() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = StrictViewFragment(R.layout.fragment_a) fm.beginTransaction().add(R.id.content, fragment).commitNow() assertThat(fragment.viewLifecycleOwner.lifecycle.currentState) .isEqualTo(Lifecycle.State.RESUMED) } @Test @UiThreadTest fun testFragmentViewLifecycleNullView() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = Fragment() fm.beginTransaction().add(fragment, "fragment").commitNow() try { fragment.viewLifecycleOwner fail("getViewLifecycleOwner should be unavailable if onCreateView returned null") } catch (expected: IllegalStateException) { assertThat(expected) .hasMessageThat().contains( "Can't access the Fragment View's LifecycleOwner when" + " getView() is null i.e., before onCreateView() or after onDestroyView()" ) } } @Test @UiThreadTest fun testObserveInOnCreateViewNullView() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = ObserveInOnCreateViewFragment() try { fm.beginTransaction().add(fragment, "fragment").commitNow() fail("Fragments accessing view lifecycle should fail if onCreateView returned null") } catch (expected: IllegalStateException) { assertThat(expected) .hasMessageThat() .contains("Called getViewLifecycleOwner() but onCreateView() returned null") // We need to clean up the Fragment to avoid it still being around // when the instrumentation test Activity pauses. Real apps would have // just crashed right after onCreateView(). fm.beginTransaction().remove(fragment).commitNow() } } @Test fun testFragmentViewLifecycleRunOnCommit() { val activity = activityRule.activity val fm = activity.supportFragmentManager val countDownLatch = CountDownLatch(1) val fragment = StrictViewFragment(R.layout.fragment_a) fm.beginTransaction().add(R.id.content, fragment).runOnCommit { assertThat(fragment.viewLifecycleOwner.lifecycle.currentState) .isEqualTo(Lifecycle.State.RESUMED) countDownLatch.countDown() }.commit() countDownLatch.await(1, TimeUnit.SECONDS) } @Test fun testFragmentViewLifecycleOwnerLiveData() { val activity = activityRule.activity val fm = activity.supportFragmentManager val countDownLatch = CountDownLatch(2) val fragment = StrictViewFragment(R.layout.fragment_a) activityRule.runOnUiThread { fragment.viewLifecycleOwnerLiveData.observe( activity, Observer { lifecycleOwner -> if (lifecycleOwner != null) { assertWithMessage( "Fragment View LifecycleOwner should be only be set" + "after onCreateView()" ) .that(fragment.onCreateViewCalled) .isTrue() countDownLatch.countDown() } else { assertWithMessage( "Fragment View LifecycleOwner should be set to null" + " after onDestroyView()" ) .that(fragment.onDestroyViewCalled) .isTrue() countDownLatch.countDown() } } ) fm.beginTransaction().add(R.id.content, fragment).commitNow() // Now remove the Fragment to trigger the destruction of the view fm.beginTransaction().remove(fragment).commitNow() } countDownLatch.await(1, TimeUnit.SECONDS) } @Test fun testViewLifecycleInFragmentLifecycle() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = StrictViewFragment(R.layout.fragment_a) val lifecycleObserver = TestLifecycleEventObserver() lateinit var viewLifecycleOwner: LifecycleOwner activityRule.runOnUiThread { fragment.viewLifecycleOwnerLiveData.observe( activity, Observer { lifecycleOwner -> if (lifecycleOwner != null) { viewLifecycleOwner = lifecycleOwner lifecycleOwner.lifecycle.addObserver(lifecycleObserver) } } ) fragment.lifecycle.addObserver(lifecycleObserver) fm.beginTransaction().add(R.id.content, fragment).commitNow() // Now remove the Fragment to trigger the destruction of the view fm.beginTransaction().remove(fragment).commitNow() } assertThat(lifecycleObserver.collectedEvents) .containsExactly( // The Fragment's lifecycle should change first, followed by the fragment's view lifecycle fragment to Lifecycle.Event.ON_CREATE, viewLifecycleOwner to Lifecycle.Event.ON_CREATE, fragment to Lifecycle.Event.ON_START, viewLifecycleOwner to Lifecycle.Event.ON_START, fragment to Lifecycle.Event.ON_RESUME, viewLifecycleOwner to Lifecycle.Event.ON_RESUME, // Now the order reverses as things unwind viewLifecycleOwner to Lifecycle.Event.ON_PAUSE, fragment to Lifecycle.Event.ON_PAUSE, viewLifecycleOwner to Lifecycle.Event.ON_STOP, fragment to Lifecycle.Event.ON_STOP, viewLifecycleOwner to Lifecycle.Event.ON_DESTROY, fragment to Lifecycle.Event.ON_DESTROY ).inOrder() } @Test @UiThreadTest fun testFragmentViewLifecycleDetach() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = ObservingFragment() fm.beginTransaction().add(R.id.content, fragment).commitNow() val viewLifecycleOwner = fragment.viewLifecycleOwner assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED) assertWithMessage("LiveData should have active observers when RESUMED") .that(fragment.liveData.hasActiveObservers()).isTrue() fm.beginTransaction().detach(fragment).commitNow() assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED) assertWithMessage("LiveData should not have active observers after detach()") .that(fragment.liveData.hasActiveObservers()).isFalse() try { fragment.viewLifecycleOwner fail("getViewLifecycleOwner should be unavailable after onDestroyView") } catch (expected: IllegalStateException) { assertThat(expected) .hasMessageThat().contains( "Can't access the Fragment View's LifecycleOwner when" + " getView() is null i.e., before onCreateView() or after onDestroyView()" ) } } @Test @UiThreadTest fun testFragmentViewLifecycleReattach() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = ObservingFragment() fm.beginTransaction().add(R.id.content, fragment).commitNow() val viewLifecycleOwner = fragment.viewLifecycleOwner assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.RESUMED) assertWithMessage("LiveData should have active observers when RESUMED") .that(fragment.liveData.hasActiveObservers()).isTrue() fm.beginTransaction().detach(fragment).commitNow() // The existing view lifecycle should be destroyed assertThat(viewLifecycleOwner.lifecycle.currentState).isEqualTo(Lifecycle.State.DESTROYED) assertWithMessage("LiveData should not have active observers after detach()") .that(fragment.liveData.hasActiveObservers()).isFalse() fm.beginTransaction().attach(fragment).commitNow() assertWithMessage("A new view LifecycleOwner should be returned after reattachment") .that(fragment.viewLifecycleOwner).isNotEqualTo(viewLifecycleOwner) assertThat(fragment.viewLifecycleOwner.lifecycle.currentState) .isEqualTo(Lifecycle.State.RESUMED) assertWithMessage("LiveData should have active observers when RESUMED") .that(fragment.liveData.hasActiveObservers()).isTrue() } /** * Test that the ViewTree get() methods for a fragment's view work correctly. */ @Test fun testFragmentViewTree() { val activity = activityRule.activity val fm = activity.supportFragmentManager val fragment = ViewTreeCheckFragment() var observedLifecycleOwner: Any? = "not set" var observedTreeLifecycleOwner: Any? = "not set" var observedTreeViewModelStoreOwner: Any? = "not set" var observedTreeViewSavedStateRegistryOwner: Any? = "not set" val latch = CountDownLatch(1) activity.runOnUiThread { fragment.viewLifecycleOwnerLiveData.observeForever { owner -> // Don't check when we're destroying the fragment. // We should never get more than one. if (owner == null) return@observeForever observedLifecycleOwner = owner observedTreeLifecycleOwner = fragment.view?.let { ViewTreeLifecycleOwner.get(it) } observedTreeViewModelStoreOwner = fragment.view?.let { ViewTreeViewModelStoreOwner.get(it) } observedTreeViewSavedStateRegistryOwner = fragment.view?.let { it.findViewTreeSavedStateRegistryOwner() } } fm.beginTransaction().add(R.id.content, fragment).commitNow() latch.countDown() } assertThat(latch.await(1, TimeUnit.SECONDS)).isTrue() assertWithMessage("ViewTreeLifecycleOwner should match viewLifecycleOwner after commitNow") .that(ViewTreeLifecycleOwner.get(fragment.view ?: error("no fragment view created"))) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeViewModelStoreOwner should match viewLifecycleOwner" + " after commitNow" ) .that( ViewTreeViewModelStoreOwner.get( fragment.view ?: error("no fragment view created") ) ) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeSavedStateRegistryOwner should match viewLifecycleOwner" + " after commitNow" ) .that( (fragment.view ?: error("no fragment view created")) .findViewTreeSavedStateRegistryOwner() ) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeLifecycleOwner should match viewLifecycleOwner in " + "viewLifecycleOwnerLiveData observer" ) .that(observedTreeLifecycleOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeViewModelStoreOwner should match viewLifecycleOwner in " + "viewLifecycleOwnerLiveData observer" ) .that(observedTreeViewModelStoreOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeSavedStateRegistryOwner should match viewLifecycleOwner in " + "viewLifecycleOwnerLiveData observer" ) .that(observedTreeViewSavedStateRegistryOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeLifecycleOwner should match observed LifecycleOwner in " + "viewLifecycleOwnerLiveData observer" ) .that(observedTreeLifecycleOwner) .isSameInstanceAs(observedLifecycleOwner) assertWithMessage( "ViewTreeLifecycleOwner should match viewLifecycleOwner in " + "onViewCreated" ) .that(fragment.onViewCreatedLifecycleOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeViewModelStoreOwner should match viewLifecycleOwner in " + "onViewCreated" ) .that(fragment.onViewCreatedViewModelStoreOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) assertWithMessage( "ViewTreeSavedStateRegistryOwner should match viewLifecycleOwner in " + "onViewCreated" ) .that(fragment.onViewCreatedSavedStateRegistryOwner) .isSameInstanceAs(fragment.viewLifecycleOwner) } @Test fun testViewTreeSavedStateRegistryOwnerWithBackStack() { val activity = activityRule.activity val fm = activity.supportFragmentManager val savedStateFragment = ViewTreeSavedStateFragment() fm.beginTransaction().add(R.id.content, savedStateFragment).commit() activityRule.executePendingTransactions() assertThat(savedStateFragment.stateIsSaved).isFalse() fm.beginTransaction() .replace(R.id.content, StrictViewFragment()) .addToBackStack(null) .commit() activityRule.executePendingTransactions() assertThat(savedStateFragment.stateIsSaved).isTrue() activityRule.popBackStackImmediate() assertThat(savedStateFragment.stateIsRestored).isTrue() assertThat(savedStateFragment.restoredState).isEqualTo("test") } class TestLifecycleEventObserver : LifecycleEventObserver { val collectedEvents = mutableListOf<Pair<LifecycleOwner, Lifecycle.Event>>() override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { collectedEvents.add(source to event) } } class ViewTreeCheckFragment : Fragment() { var onViewCreatedLifecycleOwner: Any? = "not set" var onViewCreatedViewModelStoreOwner: Any? = "not set" var onViewCreatedSavedStateRegistryOwner: Any? = "not set" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = FrameLayout(inflater.context) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { onViewCreatedLifecycleOwner = ViewTreeLifecycleOwner.get(view) onViewCreatedViewModelStoreOwner = ViewTreeViewModelStoreOwner.get(view) onViewCreatedSavedStateRegistryOwner = view.findViewTreeSavedStateRegistryOwner() } } class ObserveInOnCreateViewFragment : Fragment() { private val liveData = MutableLiveData<Boolean>() private val onCreateViewObserver = Observer<Boolean> { } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { liveData.observe(viewLifecycleOwner, onCreateViewObserver) assertWithMessage("LiveData should have observers after onCreateView observe") .that(liveData.hasObservers()).isTrue() // Return null - oops! return null } } class ObservingFragment : StrictViewFragment(R.layout.fragment_a) { val liveData = MutableLiveData<Boolean>() private val onCreateViewObserver = Observer<Boolean> { } private val onViewCreatedObserver = Observer<Boolean> { } private val onViewStateRestoredObserver = Observer<Boolean> { } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = super.onCreateView(inflater, container, savedInstanceState).also { liveData.observe(viewLifecycleOwner, onCreateViewObserver) assertWithMessage("LiveData should have observers after onCreateView observe") .that(liveData.hasObservers()).isTrue() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) liveData.observe(viewLifecycleOwner, onViewCreatedObserver) assertWithMessage("LiveData should have observers after onViewCreated observe") .that(liveData.hasObservers()).isTrue() } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) liveData.observe(viewLifecycleOwner, onViewStateRestoredObserver) assertWithMessage("LiveData should have observers after onViewStateRestored observe") .that(liveData.hasObservers()).isTrue() } } class ViewTreeSavedStateFragment : StrictViewFragment(R.layout.fragment_a) { var stateIsSaved = false var stateIsRestored = false var restoredState: String? = null override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val savedStateRegistryOwner = view.findViewTreeSavedStateRegistryOwner()!! val savedStateRegistry = savedStateRegistryOwner.savedStateRegistry val restoredBundle = savedStateRegistry.consumeRestoredStateForKey( "savedState" ) stateIsRestored = restoredBundle != null restoredState = restoredBundle?.getString("state") savedStateRegistry.registerSavedStateProvider("savedState") { stateIsSaved = true Bundle().apply { putString("state", "test") } } } } }
apache-2.0
709d06c928f5f62771d7f6f89ba5e77a
41.146341
106
0.653694
6.013921
false
true
false
false
kamerok/Orny
app/src/main/kotlin/com/kamer/orny/utils/AndroidExt.kt
1
2208
package com.kamer.orny.utils import android.content.Context import android.content.pm.PackageManager import android.net.ConnectivityManager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.Editable import android.text.TextWatcher import android.view.View import android.widget.TextView import android.widget.Toast import java.util.* fun Context.toast(message: CharSequence) = Toast.makeText(this.applicationContext, message, Toast.LENGTH_SHORT).show() fun View.visible() { visibility = View.VISIBLE } fun View.gone() { visibility = View.GONE } fun View.setVisible(isVisible: Boolean) { visibility = if (isVisible) View.VISIBLE else View.GONE } fun Context.isDeviceOnline(): Boolean { val connMgr = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connMgr.activeNetworkInfo return networkInfo != null && networkInfo.isConnected } fun Context.hasPermission(permission: String): Boolean = packageManager.checkPermission(permission, packageName) == PackageManager.PERMISSION_GRANTED fun AppCompatActivity.setupToolbar(toolbarView: Toolbar) { setSupportActionBar(toolbarView) val supportActionBar = supportActionBar if (supportActionBar != null) { supportActionBar.setDisplayHomeAsUpEnabled(true) supportActionBar.setDisplayShowHomeEnabled(true) } toolbarView.setNavigationOnClickListener { _ -> onBackPressed() } } fun TextView.onTextChanged(listener: (String) -> Unit) = addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { listener.invoke(s.toString()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) fun Calendar.dayStart() = this.apply { set(get(Calendar.YEAR), get(Calendar.MONTH), get(Calendar.DAY_OF_MONTH), 0, 0, 0) set(Calendar.MILLISECOND, 0) } fun Date.dayStart(): Date = Calendar .getInstance() .apply { time = this@dayStart dayStart() } .time
apache-2.0
30e818157b96a629233abdf55f7d2acb
28.851351
102
0.730525
4.372277
false
false
false
false
groupon/kmond
src/test/kotlin/com/groupon/aint/kmond/config/HttpFetchHandlerTest.kt
1
3803
/** * Copyright 2015 Groupon 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.groupon.aint.kmond.config import io.vertx.core.AsyncResult import io.vertx.core.Future import io.vertx.core.Handler import io.vertx.core.Vertx import io.vertx.core.buffer.Buffer import io.vertx.core.eventbus.MessageProducer import io.vertx.core.file.FileSystem import io.vertx.core.http.HttpClient import io.vertx.core.http.HttpClientRequest import io.vertx.core.http.HttpClientResponse import org.junit.Before import org.junit.Test import org.mockito.Matchers import org.mockito.Mockito import org.mockito.MockitoAnnotations import java.io.File /** * Tests for HttpFetchHandler. * * @author Stuart Siegrist (fsiegrist at groupon dot com) */ class HttpFetchHandlerTest { val vertx = mock<Vertx>() val fileSystem = mock<FileSystem>() val httpClient = mock<HttpClient>() val httpRequest = mock<HttpClientRequest>() val responseHandler = captor<Handler<HttpClientResponse>>() val httpResponse = mock<HttpClientResponse>() val responseBody = captor<Handler<Buffer>>() val voidHandler = captor<Handler<AsyncResult<Void>>>() val producer = mock<MessageProducer<String>>() @Before fun setUp() { MockitoAnnotations.initMocks(this) Mockito.`when`(vertx.fileSystem()).thenReturn(fileSystem) Mockito.`when`(vertx.createHttpClient()).thenReturn(httpClient) } @Test fun testSimpleGet() { val buffer = Buffer.buffer(javaClass.getResourceAsStream("/ganglia_cluster.yml").reader(Charsets.UTF_8).readText()) Mockito.`when`(httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), responseHandler.capture())).thenReturn(httpRequest) Mockito.`when`(httpResponse.statusCode()).thenReturn(200) Mockito.`when`(producer.write(Mockito.anyString())).thenReturn(producer) val testFile = File("target") HttpFetchHandler(vertx, producer, "host", 80, "urlPath", testFile, testFile, "filename").handle(1L) responseHandler.value.handle(httpResponse) Mockito.verify(httpResponse).bodyHandler(responseBody.capture()) responseBody.value.handle(buffer) Mockito.verify(fileSystem).writeFile(Matchers.eq(File(testFile, "filename.tmp").absolutePath), Matchers.eq(buffer), voidHandler.capture()) voidHandler.value.handle(Future.succeededFuture<Void>()) } @Test fun testGetFailure() { val buffer = Buffer.buffer(javaClass.getResourceAsStream("/ganglia_cluster.yml").reader(Charsets.UTF_8).readText()) Mockito.`when`(httpClient.get(Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), responseHandler.capture())).thenReturn(httpRequest) Mockito.`when`(httpResponse.statusCode()).thenReturn(400) Mockito.`when`(httpResponse.statusMessage()).thenReturn("Bad request") val testFile = File("target") HttpFetchHandler(vertx, producer, "host", 80, "urlPath", testFile, testFile, "filename").handle(1L) responseHandler.value.handle(httpResponse) Mockito.verify(httpResponse).bodyHandler(responseBody.capture()) responseBody.value.handle(buffer) Mockito.verifyZeroInteractions(fileSystem) } }
apache-2.0
2afced34793fd4c4390099e87d321027
38.206186
123
0.719695
4.371264
false
true
false
false
android/views-widgets-samples
RecyclerViewKotlin/app/src/main/java/com/example/recyclersample/data/Flowers.kt
1
3334
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.recyclersample.data import android.content.res.Resources import com.example.recyclersample.R /* Returns initial list of flowers. */ fun flowerList(resources: Resources): List<Flower> { return listOf( Flower( id = 1, name = resources.getString(R.string.flower1_name), image = R.drawable.rose, description = resources.getString(R.string.flower1_description) ), Flower( id = 2, name = resources.getString(R.string.flower2_name), image = R.drawable.freesia, description = resources.getString(R.string.flower2_description) ), Flower( id = 3, name = resources.getString(R.string.flower3_name), image = R.drawable.lily, description = resources.getString(R.string.flower3_description) ), Flower( id = 4, name = resources.getString(R.string.flower4_name), image = R.drawable.sunflower, description = resources.getString(R.string.flower4_description) ), Flower( id = 5, name = resources.getString(R.string.flower5_name), image = R.drawable.peony, description = resources.getString(R.string.flower5_description) ), Flower( id = 6, name = resources.getString(R.string.flower6_name), image = R.drawable.daisy, description = resources.getString(R.string.flower6_description) ), Flower( id = 7, name = resources.getString(R.string.flower7_name), image = R.drawable.lilac, description = resources.getString(R.string.flower7_description) ), Flower( id = 8, name = resources.getString(R.string.flower8_name), image = R.drawable.marigold, description = resources.getString(R.string.flower8_description) ), Flower( id = 9, name = resources.getString(R.string.flower9_name), image = R.drawable.poppy, description = resources.getString(R.string.flower9_description) ), Flower( id = 10, name = resources.getString(R.string.flower10_name), image = R.drawable.daffodil, description = resources.getString(R.string.flower10_description) ), Flower( id = 11, name = resources.getString(R.string.flower11_name), image = R.drawable.dahlia, description = resources.getString(R.string.flower11_description) ) ) }
apache-2.0
df729c5ae3a6cfe7dab007f96c67d854
35.25
76
0.59808
4.214918
false
false
false
false
ThomasVadeSmileLee/cyls
src/main/kotlin/com/scienjus/smartqq/client/SmartQQClient.kt
1
23797
package com.scienjus.smartqq.client import com.github.salomonbrys.kotson.castTo import com.github.salomonbrys.kotson.fromJson import com.github.salomonbrys.kotson.getAsJsonArrayOrNull import com.github.salomonbrys.kotson.getObject import com.github.salomonbrys.kotson.jsonObjectOf import com.github.salomonbrys.kotson.parseAsJsonObject import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser import com.scienjus.smartqq.LOGGER import com.scienjus.smartqq.callback.MessageCallback import com.scienjus.smartqq.constant.ApiURL import com.scienjus.smartqq.frame.QRCodeFrame import com.scienjus.smartqq.model.Category import com.scienjus.smartqq.model.Discuss import com.scienjus.smartqq.model.DiscussInfo import com.scienjus.smartqq.model.DiscussMessage import com.scienjus.smartqq.model.DiscussUser import com.scienjus.smartqq.model.Font import com.scienjus.smartqq.model.Friend import com.scienjus.smartqq.model.FriendStatus import com.scienjus.smartqq.model.Group import com.scienjus.smartqq.model.GroupInfo import com.scienjus.smartqq.model.GroupMessage import com.scienjus.smartqq.model.GroupUser import com.scienjus.smartqq.model.Message import com.scienjus.smartqq.model.Recent import com.scienjus.smartqq.model.UserInfo import net.dongliu.requests.Client import net.dongliu.requests.Response import net.dongliu.requests.Session import net.dongliu.requests.exception.RequestException import java.io.Closeable import java.io.File import java.io.IOException import java.net.SocketTimeoutException import java.util.* /** * Api客户端. * @author ScienJus * * * @author [Liang Ding](http://88250.b3log.org) * * * @date 2015/12/18. */ class SmartQQClient @JvmOverloads constructor( private val callback: MessageCallback, qrCodeFile: File = File("qrcode.png") ) : Closeable { //客户端 private val client = Client.pooled().maxPerRoute(5).maxTotal(10).build() ?: throw IllegalStateException("fail to get client") //会话 private val session: Session //二维码令牌 private lateinit var qrsig: String //二维码窗口 private val qrframe = QRCodeFrame() //鉴权参数 private lateinit var ptwebqq: String private lateinit var vfwebqq: String private lateinit var psessionid: String private var uin = 0L //线程开关 @Volatile private var pollStarted = false init { this.session = client.session() login(qrCodeFile) } /** * 登录 */ private fun login(qrCodeFile: File) { val url = getAndVerifyQRCode(qrCodeFile) getPtwebqq(url) getVfwebqq() getUinAndPsessionid() friendStatus //修复Api返回码[103]的问题 LOGGER.info("${accountInfo.nick},欢迎!") //登录成功欢迎语 } private val runner = Runnable { while (true) { if (!pollStarted) { return@Runnable } try { pollMessage(callback) } catch (e: RequestException) { //忽略SocketTimeoutException if (e.cause !is SocketTimeoutException) { LOGGER.error(e.message) } } catch (e: Exception) { LOGGER.error(e.message) } } } fun start() { this.pollStarted = true val pollThread = Thread(runner) pollThread.start() } //登录流程1:获取二维码 //登录流程2:验证二维码扫描 private fun getAndVerifyQRCode(qrCodeFile: File): String { //阻塞直到确认二维码认证成功 while (true) { LOGGER.debug("开始获取二维码") //本地存储二维码图片 val filePath: String try { filePath = qrCodeFile.canonicalPath } catch (e: IOException) { throw IllegalStateException("二维码保存失败") } val getQRCodeResponse = session.get(ApiURL.GET_QR_CODE.url) .addHeader("User-Agent", ApiURL.USER_AGENT) .file(filePath) getQRCodeResponse.cookies.forEach { cookie -> if (cookie.name == "qrsig") { qrsig = cookie.value return@forEach } } LOGGER.info("二维码已保存在 $filePath 文件中,请打开手机QQ并扫描二维码") qrframe.showQRCode(filePath) //显示二维码 LOGGER.debug("等待扫描二维码") while (true) { sleep(1) val verifyQRCodeResponse = get(ApiURL.VERIFY_QR_CODE, hash33(qrsig)) val result = verifyQRCodeResponse.body if (result.contains("成功")) { result.split("','".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().forEach { content -> if (content.startsWith("http")) { LOGGER.info("正在登录,请稍后") qrframe.dispose() //认证成功后释放窗体资源 return content } } } else if (result.contains("已失效")) { LOGGER.info("二维码已失效,尝试重新获取二维码") qrframe.waitForQRCode() //等待新的二维码 break } } } } //登录流程3:获取ptwebqq private fun getPtwebqq(url: String) { LOGGER.debug("开始获取ptwebqq") val response = get(ApiURL.GET_PTWEBQQ, url) this.ptwebqq = response.cookies.get("ptwebqq").iterator().next().value } //登录流程4:获取vfwebqq private fun getVfwebqq() { LOGGER.debug("开始获取vfwebqq") val response = get(ApiURL.GET_VFWEBQQ, ptwebqq) this.vfwebqq = getJsonObjectResult(response)?.getAsJsonPrimitive("vfwebqq")?.asString ?: throw IllegalStateException("fail to get vfwebqq") } //登录流程5:获取uin和psessionid private fun getUinAndPsessionid() { LOGGER.debug("开始获取uin和psessionid") val r = jsonObjectOf( "ptwebqq" to ptwebqq, "clientid" to Client_ID, "psessionid" to "", "status" to "online" ) val response = post(ApiURL.GET_UIN_AND_PSESSIONID, r) val result = getJsonObjectResult(response) this.psessionid = result?.getAsJsonPrimitive("psessionid")?.asString ?: throw IllegalStateException("fail to get psessionid") this.uin = result.getAsJsonPrimitive("uin")?.asLong ?: throw IllegalStateException("fail to get uin") } /** * 获取群列表 * @return */ val groupList: List<Group> get() { LOGGER.debug("开始获取群列表") val r = jsonObjectOf( "vfwebqq" to vfwebqq, "hash" to hash() ) val response = post(ApiURL.GET_GROUP_LIST, r) val result = getJsonObjectResult(response) return Gson().fromJson(result?.getAsJsonArrayOrNull("gnamelist") ?: throw IllegalStateException("fail to get group list")) } /** * 拉取消息 * @param callback 获取消息后的回调 */ private fun pollMessage(callback: MessageCallback) { LOGGER.debug("开始接收消息") val r = jsonObjectOf( "ptwebqq" to ptwebqq, "clientid" to Client_ID, "psessionid" to psessionid, "key" to "" ) val response = post(ApiURL.POLL_MESSAGE, r) getJsonArrayResult(response) ?.forEach { it as JsonObject val type = it["poll_type"].asString when (type) { "message" -> callback.onMessage(Message(it.getAsJsonObject("value"))) "group_message" -> callback.onGroupMessage(GroupMessage(it.getAsJsonObject("value"))) "discu_message" -> callback.onDiscussMessage(DiscussMessage(it.getAsJsonObject("value"))) } } } /** * 发送群消息 * @param groupId 群id * * * @param msg 消息内容 */ fun sendMessageToGroup(groupId: Long, msg: String) { LOGGER.debug("开始发送群消息") //注意这里虽然格式是Json,但是实际是String val content = Gson().toJson(arrayListOf(msg, arrayListOf("font", Font.DEFAULT_FONT))) val r = jsonObjectOf( "group_uin" to groupId, "content" to content, "face" to 573, "clientid" to Client_ID, "msg_id" to MESSAGE_ID++, "psessionid" to psessionid ) val response = postWithRetry(ApiURL.SEND_MESSAGE_TO_GROUP, r) checkSendMsgResult(response) } /** * 发送讨论组消息 * @param discussId 讨论组id * * * @param msg 消息内容 */ fun sendMessageToDiscuss(discussId: Long, msg: String) { LOGGER.debug("开始发送讨论组消息") //注意这里虽然格式是Json,但是实际是String val content = Gson().toJson(arrayListOf(msg, arrayListOf("font", Font.DEFAULT_FONT))) val r = jsonObjectOf( "did" to discussId, "content" to content, "face" to 573, "clientid" to Client_ID, "msg_id" to MESSAGE_ID++, "psessionid" to psessionid ) val response = postWithRetry(ApiURL.SEND_MESSAGE_TO_DISCUSS, r) checkSendMsgResult(response) } /** * 发送消息 * @param friendId 好友id * * * @param msg 消息内容 */ fun sendMessageToFriend(friendId: Long, msg: String) { LOGGER.debug("开始发送消息") //注意这里虽然格式是Json,但是实际是String val content = Gson().toJson(arrayListOf(msg, arrayListOf("font", Font.DEFAULT_FONT))) val r = jsonObjectOf( "to" to friendId, "content" to content, "face" to 573, "clientid" to Client_ID, "msg_id" to MESSAGE_ID++, "psessionid" to psessionid ) val response = postWithRetry(ApiURL.SEND_MESSAGE_TO_FRIEND, r) checkSendMsgResult(response) } /** * 获得讨论组列表 * @return */ val discussList: List<Discuss> get() { LOGGER.debug("开始获取讨论组列表") val response = get(ApiURL.GET_DISCUSS_LIST, psessionid, vfwebqq) return Gson().fromJson(getJsonObjectResult(response)?.getAsJsonArrayOrNull("dnamelist") ?: throw IllegalStateException("fail to get discuss list")) } /** * 获得好友列表(包含分组信息) * @return */ //获得好友信息 //获得分组 val friendListWithCategory: List<Category> get() { LOGGER.debug("开始获取好友列表") val r = jsonObjectOf( "vfwebqq" to vfwebqq, "hash" to hash() ) val response = post(ApiURL.GET_FRIEND_LIST, r) val result = getJsonObjectResult(response) val friendMap = parseFriendMap(result) val categoryMap = HashMap<Int, Category>() categoryMap.put(0, Category.defaultCategory()) result?.getAsJsonArrayOrNull("categories") ?.map { it.castTo<Category>() } ?.forEach { categoryMap.put(it.index, it) } result?.getAsJsonArrayOrNull("friends") ?.forEach { it as JsonObject val friend = friendMap[it["uin"].asLong] if (friend != null) { categoryMap[it["categories"].asInt]?.addFriend(friend) } } return ArrayList(categoryMap.values) } /** * 获取好友列表 * @return */ val friendList: List<Friend> get() { LOGGER.debug("开始获取好友列表") val r = jsonObjectOf( "vfwebqq" to vfwebqq, "hash" to hash() ) val response = post(ApiURL.GET_FRIEND_LIST, r) return ArrayList(parseFriendMap(getJsonObjectResult(response) ?: throw IllegalStateException("fail to get friend list")).values) } /** * 获得当前登录用户的详细信息 * @return */ private val accountInfo: UserInfo get() { LOGGER.debug("开始获取登录用户信息") val response = get(ApiURL.GET_ACCOUNT_INFO) return Gson().fromJson(getJsonObjectResult(response) ?: throw IllegalStateException("fail to get account info")) } /** * 获得好友的详细信息 * @return */ fun getFriendInfo(friendId: Long): UserInfo { LOGGER.debug("开始获取好友信息") val response = get(ApiURL.GET_FRIEND_INFO, friendId, vfwebqq, psessionid) return Gson().fromJson(getJsonObjectResult(response) ?: throw IllegalStateException("fail to get friend info")) } /** * 获得最近会话列表 * @return */ val recentList: List<Recent> get() { LOGGER.debug("开始获取最近会话列表") val r = jsonObjectOf( "vfwebqq" to vfwebqq, "clientid" to Client_ID, "psessionid" to "" ) val response = post(ApiURL.GET_RECENT_LIST, r) return Gson().fromJson(getJsonArrayResult(response) ?: throw IllegalStateException("recent list is null")) } /** * 获得登录状态 * @return */ val friendStatus: List<FriendStatus> get() { LOGGER.debug("开始获取好友状态") val response = get(ApiURL.GET_FRIEND_STATUS, vfwebqq, psessionid) return Gson().fromJson(getJsonArrayResult(response) ?: throw IllegalStateException("fail to get friend status")) } /** * 获得群的详细信息 * @param groupCode 群编号 * * * @return */ fun getGroupInfo(groupCode: Long): GroupInfo { LOGGER.debug("开始获取群资料") val response = get(ApiURL.GET_GROUP_INFO, groupCode, vfwebqq) val result = getJsonObjectResult(response) val groupInfo: GroupInfo = result?.getObject("ginfo") ?: throw IllegalStateException("fail to get group status") //获得群成员信息 val groupUserMap = HashMap<Long, GroupUser>() result.getAsJsonArrayOrNull("minfo") ?.map { it.castTo<GroupUser>() } ?.forEach { groupUserMap.put(it.userId, it) groupInfo.addUser(it) } result.getAsJsonArrayOrNull("stats") ?.forEach { it as JsonObject val groupUser = groupUserMap[it["uin"].asLong] groupUser?.clientType = it["client_type"].asInt groupUser?.status = it["stat"].asInt } result.getAsJsonArrayOrNull("cards") ?.forEach { it as JsonObject groupUserMap[it["muin"].asLong]?.card = it["card"].asString } result.getAsJsonArrayOrNull("vipinfo") ?.forEach { it as JsonObject val groupUser = groupUserMap[it["u"].asLong] groupUser?.isVip = it["is_vip"].asInt == 1 groupUser?.vipLevel = it["vip_level"].asInt } return groupInfo } /** * 获得讨论组的详细信息 * @param discussId 讨论组id * * * @return */ fun getDiscussInfo(discussId: Long): DiscussInfo { LOGGER.debug("开始获取讨论组资料") val response = get(ApiURL.GET_DISCUSS_INFO, discussId, vfwebqq, psessionid) val result = getJsonObjectResult(response) val discussInfo: DiscussInfo = result?.getObject("info") ?: throw IllegalStateException("fail to get discuss info") //获得讨论组成员信息 val discussUserMap = HashMap<Long, DiscussUser>() result.getAsJsonArrayOrNull("mem_info") ?.map { it.castTo<DiscussUser>() } ?.forEach { discussUserMap.put(it.userId, it) discussInfo.addUser(it) } result.getAsJsonArrayOrNull("mem_status") ?.forEach { it as JsonObject val discussUser = discussUserMap[it["uin"].asLong] discussUser?.clientType = it["client_type"].asInt discussUser?.status = it["status"].asString } return discussInfo } //发送get请求 private operator fun get(url: ApiURL, vararg params: Any): Response<String> { val request = session.get(url.buildUrl(*params)) .addHeader("User-Agent", ApiURL.USER_AGENT) if (url.referer != null) { request.addHeader("Referer", url.referer) } return request.text() } //发送post请求 private fun post(url: ApiURL, r: JsonObject) = session.post(url.url) .addHeader("User-Agent", ApiURL.USER_AGENT) .addHeader("Referer", url.referer ?: throw IllegalStateException("post referer is null")) .addHeader("Origin", url.origin) .addForm("r", r.toString()) .text() //发送post请求,失败时重试 private fun postWithRetry(url: ApiURL, r: JsonObject): Response<String> { var times = 0 var response: Response<String> do { response = post(url, r) times++ } while (times < RETRY_TIMES && response.statusCode != 200) return response } //hash加密方法 private fun hash() = hash(uin, ptwebqq) override fun close() { this.pollStarted = false this.client.close() } companion object { //消息id,这个好像可以随便设置,所以设成全局的 @JvmStatic private var MESSAGE_ID: Long = 43690001 //客户端id,固定的 @JvmStatic private val Client_ID: Long = 53999199 //消息发送失败重发次数 @JvmStatic private val RETRY_TIMES: Long = 5 //用于生成ptqrtoken的哈希函数 @JvmStatic private fun hash33(s: String): Int { var e = 0 val n = s.length for (i in 0 until n) { e += (e shl 5) + s[i].toInt() } return Int.MAX_VALUE and e } //将json解析为好友列表 @JvmStatic private fun parseFriendMap(result: JsonObject?): Map<Long, Friend> { val friendMap = HashMap<Long, Friend>() result?.getAsJsonArrayOrNull("info") ?.forEach { it as JsonObject val friend = Friend() friend.userId = it["uin"].asLong friend.nickname = it["nick"].asString friendMap.put(friend.userId, friend) } result?.getAsJsonArrayOrNull("marknames") ?.forEach { it as JsonObject friendMap[it["uin"].asLong]?.markname = it["markname"].asString } result?.getAsJsonArrayOrNull("vipinfo") ?.forEach { it as JsonObject val friend = friendMap[it["u"].asLong] friend?.isVip = it["is_vip"].asInt == 1 friend?.vipLevel = it["vip_level"].asInt } return friendMap } //获取返回json的result字段(JSONObject类型) private fun getJsonObjectResult(response: Response<String>) = getResponseJson(response).getAsJsonObject("result") //获取返回json的result字段(JSONArray类型) private fun getJsonArrayResult(response: Response<String>) = getResponseJson(response).getAsJsonArrayOrNull("result") //检查消息是否发送成功 @JvmStatic private fun checkSendMsgResult(response: Response<String>) { if (response.statusCode != 200) { LOGGER.error(String.format("发送失败,Http返回码[%d]", response.statusCode)) } val json = JsonParser().parseAsJsonObject(response.body) val errCode = json["errCode"].asInt if (errCode == 0) { LOGGER.debug("发送成功") } else { LOGGER.error(String.format("发送失败,Api返回码[%d]", json["retcode"].asInt)) } } //检验Json返回结果 @JvmStatic private fun getResponseJson(response: Response<String>): JsonObject { if (response.statusCode != 200) { throw RequestException(String.format("请求失败,Http返回码[%d]", response.statusCode)) } val json = JsonParser().parseAsJsonObject(response.body) val retCode = try { json.getAsJsonPrimitive("retcode")?.asInt } catch (_: ClassCastException) { null } when (retCode) { null -> throw RequestException("请求失败,Api返回异常") 0 -> run {} 103 -> LOGGER.error("请求失败,Api返回码[103]。你需要进入http://w.qq.com,检查是否能正常接收消息。如果可以的话点击[设置]->[退出登录]后查看是否恢复正常") 100100 -> LOGGER.debug("请求失败,Api返回码[100100]") else -> throw RequestException("请求失败,Api返回码[$retCode]") } return json } //线程暂停 @JvmStatic private fun sleep(seconds: Long) = Thread.sleep(seconds * 1000) //hash加密方法 private fun hash(x: Long, K: String): String { val N = IntArray(4) (0 until K.length).forEach { T -> N[T % 4] = N[T % 4] xor K[T].toInt() } val U = arrayOf("EC", "OK") val V = LongArray(4) V[0] = x shr 24 and 255 xor U[0][0].toLong() V[1] = x shr 16 and 255 xor U[0][1].toLong() V[2] = x shr 8 and 255 xor U[1][0].toLong() V[3] = x and 255 xor U[1][1].toLong() val U1 = LongArray(8) { T -> if (T % 2 == 0) N[T shr 1].toLong() else V[T shr 1] } val N1 = arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F") var V1 = "" U1.forEach { aU1 -> V1 += N1[(aU1 shr 4 and 15).toInt()] V1 += N1[(aU1 and 15).toInt()] } return V1 } } }
mit
8f017f9fb218994453c174b3e43b55f7
31.163295
121
0.540684
4.096632
false
false
false
false
TCA-Team/TumCampusApp
app/src/test/java/de/tum/in/tumcampusapp/activities/KinoActivityTest.kt
1
4382
package de.tum.`in`.tumcampusapp.activities import android.view.View import androidx.viewpager.widget.ViewPager import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.TestApp import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoActivity import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoAdapter import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoDao import de.tum.`in`.tumcampusapp.component.ui.tufilm.KinoViewModel import de.tum.`in`.tumcampusapp.component.ui.tufilm.model.Kino import de.tum.`in`.tumcampusapp.component.ui.tufilm.repository.KinoLocalRepository import de.tum.`in`.tumcampusapp.database.TcaDb import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.assertj.core.api.Assertions.assertThat import org.joda.time.DateTime import org.junit.After import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @Ignore @RunWith(RobolectricTestRunner::class) @Config(application = TestApp::class) class KinoActivityTest { private var kinoActivity: KinoActivity? = null private lateinit var dao: KinoDao private lateinit var viewModel: KinoViewModel @Before fun setUp() { val db = TcaDb.getInstance(RuntimeEnvironment.application) val localRepository = KinoLocalRepository(db) viewModel = KinoViewModel(localRepository) RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setComputationSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setNewThreadSchedulerHandler { Schedulers.trampoline() } RxJavaPlugins.setSingleSchedulerHandler { Schedulers.trampoline() } RxAndroidPlugins.setMainThreadSchedulerHandler { Schedulers.trampoline() } dao = db.kinoDao() dao.flush() } @After fun tearDown() { TcaDb.getInstance(RuntimeEnvironment.application).close() RxJavaPlugins.reset() RxAndroidPlugins.reset() } /** * Default usage - there are some movies * Expected output: default Kino activity layout */ @Test fun mainComponentDisplayedTest() { dao.insert(KINO) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() assertThat(kinoActivity!!.findViewById<View>(R.id.drawer_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are no movies to display * Expected output: no movies layout displayed */ @Test fun mainComponentNoMoviesDisplayedTest() { kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() // For some reason the ui needs a while until it's been updated. Thread.sleep(100) assertThat(kinoActivity!!.findViewById<View>(R.id.error_layout).visibility).isEqualTo(View.VISIBLE) } /** * There are movies available * Expected output: KinoAdapter is used for pager. */ @Test fun kinoAdapterUsedTest() { dao.insert(KINO) kinoActivity = Robolectric.buildActivity(KinoActivity::class.java).create().start().get() waitForUI() Thread.sleep(100) assertThat((kinoActivity!!.findViewById<View>(R.id.pager) as ViewPager).adapter!!.javaClass).isEqualTo(KinoAdapter::class.java) } /** * Since we have an immediate scheduler which runs on the same thread and thus can only execute actions sequentially, this will * make the test wait until any previous tasks (like the activity waiting for kinos) are done. */ private fun waitForUI() { viewModel.getAllKinos().blockingFirst() } companion object { private val KINO = Kino( "123", "Deadpool 2", "2018", "137 min", "Comedy", "Someone", "Ryan Reynolds and others", "The best", "I dunno stuff happens", "", null, DateTime.now(), DateTime.now(), "" ) } }
gpl-3.0
fd46b661979ad215e8aa577fd0cbe282
34.918033
135
0.68325
4.598111
false
true
false
false
Shockah/Godwit
ios/src/pl/shockah/godwit/ios/IosSafeAreaProvider.kt
1
813
package pl.shockah.godwit.ios import org.robovm.apple.foundation.Foundation import org.robovm.apple.uikit.UIApplication import pl.shockah.godwit.geom.EdgeInsets import pl.shockah.godwit.platform.SafeAreaProvider class IosSafeAreaProvider : SafeAreaProvider { override val safeAreaInsets: EdgeInsets get() { if (Foundation.getMajorSystemVersion() < 11) return EdgeInsets() val view = UIApplication.getSharedApplication().keyWindow.rootViewController.view val edgeInsets = view.safeAreaInsets return EdgeInsets( top = (edgeInsets.top * view.contentScaleFactor).toFloat(), bottom = (edgeInsets.bottom * view.contentScaleFactor).toFloat(), left = (edgeInsets.left * view.contentScaleFactor).toFloat(), right = (edgeInsets.right * view.contentScaleFactor).toFloat() ) } }
apache-2.0
209fdece24923c9c7d5bab1e568fdf8e
34.391304
84
0.765068
3.799065
false
false
false
false
JavaEden/Orchid
OrchidCore/src/main/kotlin/com/eden/orchid/api/theme/assets/CssPage.kt
2
4287
package com.eden.orchid.api.theme.assets import com.eden.orchid.api.options.OptionsHolder import com.eden.orchid.api.options.annotations.BooleanDefault import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.resources.resource.ExternalResource import com.eden.orchid.api.resources.resource.InlineResource import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.utilities.OrchidUtils private const val ASSET_DESCRIPTION = "The resource to load as an extra stylesheet" private const val ATTRS_DESCRIPTION = "Arbitrary attributes to apply to this element when rendered to page" private const val INLINED_DESCRIPTION = "Inlines the contents of this stylesheet directly into the page instead of being referenced from a URL." private const val DOWNLOAD_DESCRIPTION = "If the resource is external, download it and serve it from the built site so the site doesn't depend on other servers being available." interface CssPageAttributes { var attrs: MutableMap<String, String> var inlined: Boolean var download: Boolean } @Description(value = "A CSS static asset.", name = "CSS Asset") class CssPage( origin: AssetManagerDelegate, resource: OrchidResource, key: String, title: String ) : AssetPage(origin, resource, key, title), CssPageAttributes { @Option @Description(ATTRS_DESCRIPTION) override lateinit var attrs: MutableMap<String, String> @Option @Description(INLINED_DESCRIPTION) override var inlined: Boolean = false @Option @BooleanDefault(true) @Description(DOWNLOAD_DESCRIPTION) override var download: Boolean = true fun applyAttributes(config: CssPageAttributes) { this.attrs = config.attrs this.inlined = config.inlined this.download = config.download } override fun configureReferences() { reference = OrchidReference(resource.reference)// copy reference so we can update it reference.isUsePrettyUrl = false if (resource is ExternalResource) { // mark the user's request to download the resource offline resource.download = download if (resource.shouldDownload) { // if the resource should actually should be downloaded offline, then update our reference to point to // the offline file, and apply the prefix as needed reference.baseUrl = context.baseUrl if (origin.prefix != null) { reference.path = OrchidUtils.normalizePath(origin.prefix) + "/" + reference.path } } else { // keep it referencing the external location, don't change anything } } else { // it's just a local file, apply the prefix as needed if (origin.prefix != null) { reference.path = OrchidUtils.normalizePath(origin.prefix) + "/" + reference.path } } } override val shouldInline: Boolean get() { return when { resource is InlineResource -> true resource is ExternalResource && resource.shouldDownload && inlined -> true resource !is ExternalResource && inlined -> true else -> false } } override fun renderAssetToPage(): String { return if (shouldInline) { "<style ${renderAttrs(attrs)}>\n${resource.compileContent(context, this)}\n</style>" } else { """<link rel="stylesheet" type="text/css" href="${this.link}" ${renderAttrs(attrs)}/>""" } } } class ExtraCss : OptionsHolder, CssPageAttributes { @Option @Description(ASSET_DESCRIPTION) lateinit var asset: String @Option @Description(ATTRS_DESCRIPTION) override lateinit var attrs: MutableMap<String, String> @Option @Description(INLINED_DESCRIPTION) override var inlined: Boolean = false @Option @BooleanDefault(true) @Description(DOWNLOAD_DESCRIPTION) override var download: Boolean = true override fun toString(): String { return "ExtraCss(asset='$asset', inlined=$inlined, download=$download)" } }
lgpl-3.0
0667dda8037a528f7c3015ce355321be
35.641026
177
0.678563
4.675027
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_code/ui/adapter/delegate/CodeDetailLimitAdapterDelegate.kt
2
1689
package org.stepik.android.view.step_quiz_code.ui.adapter.delegate import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.item_step_quiz_code_detail_limit.view.* import org.stepic.droid.R import org.stepik.android.view.step_quiz_code.model.CodeDetail import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class CodeDetailLimitAdapterDelegate : AdapterDelegate<CodeDetail, DelegateViewHolder<CodeDetail>>() { override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<CodeDetail> = ViewHolder(createView(parent, R.layout.item_step_quiz_code_detail_limit)) override fun isForViewType(position: Int, data: CodeDetail): Boolean = data is CodeDetail.Limit private class ViewHolder(root: View) : DelegateViewHolder<CodeDetail>(root) { private val title = root.stepQuizCodeDetailLimitTitle private val value = root.stepQuizCodeDetailLimitValue override fun onBind(data: CodeDetail) { data as CodeDetail.Limit when (data.type) { CodeDetail.Limit.Type.TIME -> { title.setText(R.string.step_quiz_code_detail_limit_title_time) value.text = context.resources.getQuantityString(R.plurals.time_seconds, data.value, data.value) } CodeDetail.Limit.Type.MEMORY -> { title.setText(R.string.step_quiz_code_detail_limit_title_memory) value.text = context.getString(R.string.step_quiz_code_detail_limit_value_memory, data.value) } } } } }
apache-2.0
acae593db81564f12c93a3b4b383c891
43.473684
116
0.695678
4.2225
false
false
false
false
Cypher121/discordplayer
src/main/kotlin/coffee/cypher/discordplayer/commands/player.kt
1
2116
package coffee.cypher.discordplayer.commands import coffee.cypher.discordplayer.* import sx.blah.discord.util.audio.AudioPlayer import sx.blah.discord.util.audio.events.TrackQueueEvent import sx.blah.discord.util.audio.providers.FileProvider import java.io.File fun queueNext(context: CommandContext, indices: List<Int>) { val player = context.player if (player.playlist.isEmpty()) { queue(context, indices) } else { indices.reversed().mapNotNull { context.client.musicList.findIndex(it) }.forEach { val file = File(context.client.musicFolder, it.path) val track = AudioPlayer.Track(FileProvider(file)) track.metadata["file"] = file player.playlist.add(1, track) context.client.client.dispatcher.dispatch(TrackQueueEvent(player, track)) } } } fun queue(context: CommandContext, indices: List<Int>) { val player = context.player if (context.voiceChannel == null) { context.respond("You need to join a voice channel to play music") } else { if (!context.voiceChannel.isConnected) { context.voiceChannel.join() } indices.mapNotNull { context.client.musicList.findIndex(it) }.forEach { player.queue(File(context.client.musicFolder, it.path)) } } } fun displayQueue(context: CommandContext) { val list = context.player.playlist.map { val file = it.metadata["file"] (file as? File)?.let { context.client.findRecordByFile(it) }?.toString() ?: "Unknown (not a file?)" }.joinToString("\n").run { if (isEmpty()) "Queue is empty" else this } if (list.length < context.client.config.get("message.maxsize", 500)) { context.message.respond(list) } else { val url = createGist("queue.txt", list) if (url == null) { context.message.respond("Queue too long and failed to create gist") } else { context.message.respond("Queue too long, created gist: $url") } } }
mit
960e78a67d9d077ea8221d490eb9294d
31.075758
107
0.621928
4.084942
false
false
false
false
alangibson27/plus-f
plus-f/src/main/kotlin/com/socialthingy/p2p/Peer.kt
1
7595
package com.socialthingy.p2p import java.net.* import java.nio.ByteBuffer import java.util.concurrent.Executors import com.codahale.metrics.ExponentiallyDecayingReservoir import com.codahale.metrics.Histogram import com.codahale.metrics.Meter import org.slf4j.LoggerFactory import java.util.* enum class State { INITIAL, WAITING_FOR_PEER, CONNECTED, CLOSING } class Peer(private val bindAddress: InetSocketAddress, private val discoveryServiceAddress: InetSocketAddress, private val callbacks: Callbacks, private val serialiser: Serialiser, private val deserialiser: Deserialiser, private val timeout: java.time.Duration) { private val log = LoggerFactory.getLogger(javaClass)!! private var socket: Optional<DatagramSocket> = Optional.empty() private val socketHandlerExecutor = Executors.newSingleThreadExecutor()!! private val latencies = Histogram(ExponentiallyDecayingReservoir()) private val sizes = Histogram(ExponentiallyDecayingReservoir()) private val meter = Meter() private var outOfOrder = 0 private var peerConnection: Optional<InetSocketAddress> = Optional.empty() private val states = HashMap<State, (ByteBuffer, InetSocketAddress) -> Unit>() init { states[State.INITIAL] = put@{ _: ByteBuffer, _: InetSocketAddress -> return@put } states[State.WAITING_FOR_PEER] = this::waitForResponse states[State.CONNECTED] = this::connectedToPeer } private var currentState: State = State.INITIAL private var currentSessionId: Optional<String> = Optional.empty() private var lastReceivedTimestamp = -1L private fun connectedToPeer(data: ByteBuffer, source: InetSocketAddress) { try { val decompressed = WrappedData(PacketUtils.decompress(data), deserialiser) latencies.update(System.currentTimeMillis() - decompressed.systemTime) meter.mark() if (decompressed.timestamp >= lastReceivedTimestamp) { lastReceivedTimestamp = decompressed.timestamp callbacks.data(decompressed.content) } else { outOfOrder += 1 } peerConnection.ifPresent { x -> if (x != source) { log.info("Switching peer connection from {} to {}", x.toString(), source.toString()) } } peerConnection = Optional.of(source) } catch (ex: Exception) { log.error( String.format("Unable to decode received message %s from %s", data.toString(), source.toString()), ex ) } } private fun waitForResponse(data: ByteBuffer, source: InetSocketAddress) { val result = String(data.array(), data.position(), data.remaining()) val splitMessage = result.split('|') when { splitMessage.size == 3 && splitMessage[0] == "PEER" -> { val targetHost = splitMessage[1] val targetPort = splitMessage[2].toInt() connectDirectly(targetPort, targetHost) } splitMessage.size == 1 && splitMessage[0] == "WAIT" -> { callbacks.waitingForPeer() log.info("Waiting for peer to join") } else -> { log.error( "Unrecognised message received from {} with content {}, still waiting for peer", source.toString(), data.toString() ) } } } fun connectDirectly(targetPort: Int, targetHost: String) { startIfRequired() val targetAddress = InetSocketAddress(targetHost, targetPort) callbacks.connectedToPeer(targetAddress) log.info("Connected to peer at {}:{}", targetHost, targetPort) currentState = State.CONNECTED peerConnection = Optional.of(targetAddress) } private fun startIfRequired() { if (socket.map { it.isClosed }.orElse(true)) { val newSocket = DatagramSocket(bindAddress) socket = Optional.of(newSocket) newSocket.soTimeout = timeout.toMillis().toInt() socketHandlerExecutor.submit { val receivedPacket = DatagramPacket(ByteArray(16384), 16384) while (!newSocket.isClosed) { try { newSocket.receive(receivedPacket) log.debug("Received packet of size {} from {}", receivedPacket.length, receivedPacket.address.toString()) sizes.update(receivedPacket.length) states[currentState]?.invoke( ByteBuffer.wrap(receivedPacket.data, receivedPacket.offset, receivedPacket.length), receivedPacket.socketAddress as InetSocketAddress ) } catch (e: SocketTimeoutException) { if (currentState == State.WAITING_FOR_PEER) { callbacks.discoveryTimeout() close() } else if (e.message == "Socket closed") { // do nothing, expected } } catch (e: Exception) { log.error("Failure in receive loop", e) } } log.info("Socket closed") } } } fun join(sessionId: String, fwdPort: Optional<Int> = Optional.empty()) { startIfRequired() callbacks.discovering() val joinCommand = fwdPort.map { "JOIN|$sessionId|$it" }.orElse("JOIN|$sessionId") currentState = State.WAITING_FOR_PEER currentSessionId = Optional.of(sessionId) socket.ifPresent { it.send(PacketUtils.buildPacket(joinCommand, discoveryServiceAddress)) } } fun send(data: RawData) { when { !peerConnection.isPresent -> log.error("Unable to send data, no peer connection") socket.map { it.isClosed }.orElse(false) -> log.error("Unable to send data, socket closed") else -> { val compressed = PacketUtils.compress(data.wrap.pack(serialiser)) log.debug("Sending packet of size {} to {}", compressed.remaining(), peerConnection.get().toString()) socket.get().send(DatagramPacket(compressed.array(), compressed.position(), compressed.remaining(), peerConnection.get())) } } } fun statistics(): Statistics = Statistics( latencies.snapshot.get99thPercentile().toInt(), outOfOrder, sizes.snapshot.get99thPercentile().toInt(), meter.oneMinuteRate ) fun close() { if (currentState == State.WAITING_FOR_PEER && currentSessionId.isPresent) { socket.ifPresent { it.send(PacketUtils.buildPacket("CANCEL|${currentSessionId.get()}", discoveryServiceAddress)) } reset() callbacks.discoveryCancelled() } else { reset() callbacks.closed() } } private fun reset() { if (socket.isPresent) { socket.get().close() } currentSessionId = Optional.empty() currentState = State.INITIAL peerConnection = Optional.empty() } } data class Statistics(val latency: Int, val outOfOrder: Int, val size: Int, val oneMinuteRate: Double)
mit
ed1d7e5aad21ebf1656b7c4cf35ebf4d
37.358586
138
0.585253
5.070093
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/webview/WebViewActivity.kt
1
3274
package eu.kanade.tachiyomi.ui.webview import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Toast import eu.kanade.presentation.webview.WebViewScreen import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.network.NetworkHelper import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.base.activity.BaseActivity import eu.kanade.tachiyomi.util.system.WebViewUtil import eu.kanade.tachiyomi.util.system.logcat import eu.kanade.tachiyomi.util.system.openInBrowser import eu.kanade.tachiyomi.util.system.toast import eu.kanade.tachiyomi.util.view.setComposeContent import okhttp3.HttpUrl.Companion.toHttpUrl import uy.kohesive.injekt.injectLazy class WebViewActivity : BaseActivity() { private val sourceManager: SourceManager by injectLazy() private val network: NetworkHelper by injectLazy() init { registerSecureActivity(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!WebViewUtil.supportsWebView(this)) { toast(R.string.information_webview_required, Toast.LENGTH_LONG) finish() return } val url = intent.extras!!.getString(URL_KEY) ?: return var headers = mutableMapOf<String, String>() val source = sourceManager.get(intent.extras!!.getLong(SOURCE_KEY)) as? HttpSource if (source != null) { headers = source.headers.toMultimap().mapValues { it.value.getOrNull(0) ?: "" }.toMutableMap() } setComposeContent { WebViewScreen( onNavigateUp = { finish() }, initialTitle = intent.extras?.getString(TITLE_KEY), url = url, headers = headers, onShare = this::shareWebpage, onOpenInBrowser = this::openInBrowser, onClearCookies = this::clearCookies, ) } } private fun shareWebpage(url: String) { try { val intent = Intent(Intent.ACTION_SEND).apply { type = "text/plain" putExtra(Intent.EXTRA_TEXT, url) } startActivity(Intent.createChooser(intent, getString(R.string.action_share))) } catch (e: Exception) { toast(e.message) } } private fun openInBrowser(url: String) { openInBrowser(url, forceDefaultBrowser = true) } private fun clearCookies(url: String) { val cleared = network.cookieManager.remove(url.toHttpUrl()) logcat { "Cleared $cleared cookies for: $url" } } companion object { private const val URL_KEY = "url_key" private const val SOURCE_KEY = "source_key" private const val TITLE_KEY = "title_key" fun newIntent(context: Context, url: String, sourceId: Long? = null, title: String? = null): Intent { return Intent(context, WebViewActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) putExtra(URL_KEY, url) putExtra(SOURCE_KEY, sourceId) putExtra(TITLE_KEY, title) } } } }
apache-2.0
6cef748496c5be90353f1cf68dfc4928
33.829787
109
0.643861
4.478796
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeContainerView.kt
2
1367
package abi44_0_0.host.exp.exponent.modules.api.components.reactnativestripesdk import android.content.Context import android.graphics.Rect import android.view.MotionEvent import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.FrameLayout import abi44_0_0.com.facebook.react.uimanager.ThemedReactContext class StripeContainerView(private val context: ThemedReactContext) : FrameLayout(context) { private var keyboardShouldPersistTapsValue: Boolean = true init { rootView.isFocusable = true rootView.isFocusableInTouchMode = true rootView.isClickable = true } fun setKeyboardShouldPersistTaps(value: Boolean) { keyboardShouldPersistTapsValue = value } override fun dispatchTouchEvent(event: MotionEvent?): Boolean { if (event!!.action == MotionEvent.ACTION_DOWN && !keyboardShouldPersistTapsValue) { val v = context.currentActivity!!.currentFocus if (v is EditText) { val outRect = Rect() v.getGlobalVisibleRect(outRect) if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(v.windowToken, 0) rootView.requestFocus() } } } return super.dispatchTouchEvent(event) } }
bsd-3-clause
7ee9c6e37273dc21a804c4a2280f0d9e
34.051282
96
0.745428
4.713793
false
false
false
false
lhw5123/GmailKotlinSample
GmailKotlion/app/src/main/java/org/hevin/gmailkotlion/helper/DividerItemDecoration.kt
1
2722
package org.hevin.gmailkotlion.helper import android.content.Context import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View class DividerItemDecoration(context: Context, orientation: Int) : RecyclerView.ItemDecoration() { private val ATTRS: IntArray = intArrayOf(android.R.attr.listDivider) val HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL val VERTICAL_LIST = LinearLayoutManager.VERTICAL private var mDivider: Drawable? = null private var mOrientation: Int? = null init { val typeArr = context.obtainStyledAttributes(ATTRS) mDivider = typeArr.getDrawable(0) typeArr.recycle() setOrientation(orientation) } fun setOrientation(orientation: Int) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw IllegalArgumentException("Invalid orientation") } mOrientation = orientation } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) { if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent) } else { drawHorizontal(c, parent) } } fun drawVertical(c: Canvas, parent: RecyclerView) { val left = parent.paddingLeft val right = parent.width - parent.paddingRight for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + mDivider!!.intrinsicHeight mDivider!!.setBounds(left, top, right, bottom) mDivider!!.draw(c) } } fun drawHorizontal(c: Canvas, parent: RecyclerView) { val top = parent.paddingTop val bottom = parent.height - parent.paddingBottom for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) val params = child.layoutParams as RecyclerView.LayoutParams val left = child.right + params.rightMargin val right = left + mDivider!!.intrinsicHeight mDivider!!.setBounds(left, top, right, bottom) mDivider!!.draw(c) } } override fun getItemOffsets(outRect: Rect, view: View?, parent: RecyclerView?, state: RecyclerView.State?) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider!!.intrinsicHeight) } else { outRect.set(0, 0, mDivider!!.intrinsicWidth, 0) } } }
apache-2.0
b2a6e650c2c4b4e12cb676032d147ddf
33.897436
112
0.653196
4.800705
false
false
false
false
jkcclemens/khttp
src/test/kotlin/khttp/KHttpAsyncGetSpec.kt
1
26402
/* * 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 khttp import khttp.helpers.SslContextUtils import khttp.responses.Response import khttp.structures.authorization.BasicAuthorization import org.awaitility.kotlin.await import org.json.JSONObject import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.net.MalformedURLException import java.net.SocketTimeoutException import java.net.URLEncoder import java.util.concurrent.TimeUnit import java.util.zip.GZIPInputStream import java.util.zip.InflaterInputStream import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue class KHttpAsyncGetSpec : Spek({ describe("an async get request") { val url = "http://httpbin.org/range/26" var error: Throwable? = null var response: Response? = null async.get(url, onError = { error = this }, onResponse = {response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the string") { if (error != null) throw error!! val string = response!!.text it("should equal the alphabet in lowercase") { assertEquals("abcdefghijklmnopqrstuvwxyz", string) } } context("accessing the url") { if (error != null) throw error!! val resultantURL = response!!.url it("should equal the starting url") { assertEquals(url, resultantURL) } } context("accessing the status code") { if (error != null) throw error!! val statusCode = response!!.statusCode it("should be 200") { assertEquals(200, statusCode) } } context("converting it to a string") { if (error != null) throw error!! val string = response!!.toString() it("should be correct") { assertEquals("<Response [200]>", string) } } } describe("an async json object get request with parameters") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/get", params = mapOf("a" to "b", "c" to "d"), onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should contain the parameters") { val args = json.getJSONObject("args") assertEquals("b", args.getString("a")) assertEquals("d", args.getString("c")) } } } describe("an async json object get request with a map of parameters") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/get", params = mapOf("a" to "b", "c" to "d"), onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should contain the parameters") { val args = json.getJSONObject("args") assertEquals("b", args.getString("a")) assertEquals("d", args.getString("c")) } } } describe("an async get request with basic auth") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/basic-auth/khttp/isawesome", auth = BasicAuthorization("khttp", "isawesome"), onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should be authenticated") { assertTrue(json.getBoolean("authenticated")) } it("should have the correct user") { assertEquals("khttp", json.getString("user")) } } } describe("an async get request with cookies") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/cookies", cookies = mapOf("test" to "success"), onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should have the same cookies") { val cookies = json.getJSONObject("cookies") assertEquals("success", cookies.getString("test")) } } } describe("an async get request that redirects and allowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should have the redirected url") { assertEquals("http://httpbin.org/get", json.getString("url")) } } } describe("an async get request that redirects with HTTP 307 and allowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?status_code=307&url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should have the redirected url") { assertEquals("http://httpbin.org/get", json.getString("url")) } } } describe("an async get request that redirects with HTTP 308 and allowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?status_code=308&url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should have the redirected url") { assertEquals("http://httpbin.org/get", json.getString("url")) } } } describe("an async get request that redirects and disallowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", allowRedirects = false, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val code = response!!.statusCode it("should be 302") { assertEquals(302, code) } } } describe("an async get request that redirects with HTTP 307 and disallowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?status_code=307&url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", allowRedirects = false, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val code = response!!.statusCode it("should be 307") { assertEquals(307, code) } } } describe("an async get request that redirects with HTTP 308 and disallowing redirects") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect-to?status_code=308&url=${URLEncoder.encode("http://httpbin.org/get", "utf-8")}", allowRedirects = false, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val code = response!!.statusCode it("should be 308") { assertEquals(308, code) } } } describe("an async get request that redirects five times") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/redirect/5", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should have the get url") { assertEquals("http://httpbin.org/get", json.getString("url")) } } } describe("an async get request that takes ten seconds to complete") { var error: Throwable? = null async.get("http://httpbin.org/delay/10", timeout = 1.0, onError = { error = this }) await.atMost(5, TimeUnit.SECONDS) .until { error != null } context("request") { it("should throw a timeout exception") { assertFailsWith(SocketTimeoutException::class) { throw error!! } } } } describe("an async get request that sets cookies without redirects") { val cookieName = "test" val cookieValue = "quite" var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/cookies/set?$cookieName=$cookieValue", allowRedirects = false, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("inspecting the cookies") { if (error != null) throw error!! val cookies = response!!.cookies it("should set a cookie") { assertEquals(1, cookies.size) } val cookie = cookies.getCookie(cookieName) val text = cookies[cookieName] it("should have the specified cookie name") { assertNotNull(cookie) } it("should have the specified text") { assertNotNull(text) } it("should have the same value") { assertEquals(cookieValue, cookie!!.value) } it("should have the same text value") { // Attributes ignored assertEquals(cookieValue, text!!.toString().split(";")[0]) } } } describe("an async get request that sets cookies with redirects") { val cookieName = "test" val cookieValue = "quite" var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/cookies/set?$cookieName=$cookieValue", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("inspecting the cookies") { if (error != null) throw error!! val cookies = response!!.cookies it("should set a cookie") { assertEquals(1, cookies.size) } val cookie = cookies.getCookie(cookieName) val text = cookies[cookieName] it("should have the specified cookie name") { assertNotNull(cookie) } it("should have the specified text") { assertNotNull(text) } it("should have the same value") { assertEquals(cookieValue, cookie!!.value) } it("should have the same text value") { // Attributes ignored assertEquals(cookieValue, text!!.toString().split(";")[0]) } } } describe("an async get request that sets multiple cookies with redirects") { val cookieNameOne = "test" val cookieValueOne = "quite" val cookieNameTwo = "derp" val cookieValueTwo = "herp" var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/cookies/set?$cookieNameOne=$cookieValueOne&$cookieNameTwo=$cookieValueTwo", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("inspecting the cookies") { if (error != null) throw error!! val cookies = response!!.cookies it("should set two cookies") { assertEquals(2, cookies.size) } val cookie = cookies.getCookie(cookieNameOne) val text = cookies[cookieNameOne] it("should have the specified cookie name") { assertNotNull(cookie) } it("should have the specified text") { assertNotNull(text) } it("should have the same value") { assertEquals(cookieValueOne, cookie!!.value) } it("should have the same text value") { // Attributes ignored assertEquals(cookieValueOne, text!!.toString().split(";")[0]) } val cookieTwo = cookies.getCookie(cookieNameTwo) val textTwo = cookies[cookieNameTwo] it("should have the specified cookie name") { assertNotNull(cookieTwo) } it("should have the specified text") { assertNotNull(textTwo) } it("should have the same value") { assertEquals(cookieValueTwo, cookieTwo!!.value) } it("should have the same text value") { // Attributes ignored assertEquals(cookieValueTwo, textTwo!!.toString().split(";")[0]) } } } describe("an async gzip get request") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/gzip", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the stream") { if (error != null) throw error!! val stream = response!!.raw it("should be a GZIPInputStream") { assertTrue(stream is GZIPInputStream) } } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should be gzipped") { assertTrue(json.getBoolean("gzipped")) } } } describe("an async deflate get request") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/deflate", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the stream") { if (error != null) throw error!! val stream = response!!.raw it("should be a InflaterInputStream") { assertTrue(stream is InflaterInputStream) } } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should be deflated") { assertTrue(json.getBoolean("deflated")) } } } describe("an async get request that returns 418") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/status/418", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val status = response!!.statusCode it("should be 418") { assertEquals(418, status) } } context("accessing the text") { if (error != null) throw error!! val text = response!!.text it("should contain \"teapot\"") { assertTrue(text.contains("teapot")) } } } describe("an async get request for a UTF-8 document") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/encoding/utf8", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("checking the encoding") { if (error != null) throw error!! val encoding = response!!.encoding it("should be UTF-8") { assertEquals(Charsets.UTF_8, encoding) } } context("reading the text") { if (error != null) throw error!! val text = response!!.text it("should contain ∮") { assertTrue(text.contains("∮")) } } context("changing the encoding") { if (error != null) throw error!! response!!.encoding = Charsets.ISO_8859_1 val encoding = response!!.encoding it("should be ISO-8859-1") { assertEquals(Charsets.ISO_8859_1, encoding) } } context("reading the text") { if (error != null) throw error!! val text = response!!.text it("should not contain ∮") { assertFalse(text.contains("∮")) } } } describe("an async unsupported khttp schema") { var error: Throwable? = null async.get("ftp://google.com", onError = { error = this }) await.atMost(5, TimeUnit.SECONDS) .until { error != null } context("construction") { it("should throw an IllegalArgumentException") { assertFailsWith(IllegalArgumentException::class) { throw error!! } } } } describe("an async unsupported Java schema") { var error: Throwable? = null async.get("gopher://google.com", onError = { error = this }) await.atMost(5, TimeUnit.SECONDS) .until { error != null } context("construction") { it("should throw a MalformedURLException") { assertFailsWith(MalformedURLException::class) { throw error!! } } } } describe("an async request with a user agent set") { val userAgent = "khttp/test" var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/user-agent", headers = mapOf("User-Agent" to userAgent), onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject val responseUserAgent = json.getString("user-agent") it("should have the same user agent") { assertEquals(userAgent, responseUserAgent) } } } describe("an async request with a port") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org:443/get", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonObject it("should not be null") { assertNotNull(json) } } } describe("an async get request for a JSON array") { var error: Throwable? = null var response: Response? = null async.get("http://jsonplaceholder.typicode.com/users", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the json") { if (error != null) throw error!! val json = response!!.jsonArray it("should have ten items") { assertEquals(10, json.length()) } } } describe("an async non-streaming get request") { var error: Throwable? = null var response: Response? = null async.get("https://httpbin.org/get", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("checking the bytes available to be read") { if (error != null) throw error!! val available = response!!.raw.available() it("should be 0") { assertEquals(0, available) } } } describe("an async streaming get request with a streaming line response") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/stream/4", stream = true, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("iterating over the lines") { if (error != null) throw error!! val iterator = response!!.lineIterator() var counter = 0 for (line in iterator) { val json = JSONObject(line.toString(response!!.encoding)) assertEquals(counter++, json.getInt("id")) } it("should have iterated 4 times") { assertEquals(4, counter) } } } describe("an async streaming get request with a streaming byte response") { var error: Throwable? = null var response: Response? = null async.get("http://httpbin.org/stream-bytes/4?seed=1", stream = true, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("iterating over the bytes") { if (error != null) throw error!! val iterator = response!!.contentIterator(chunkSize = 1) var counter = 0 val expected = byteArrayOf(0x22, 0xD8.toByte(), 0xC3.toByte(), 0x41) for (byte in iterator) { assertEquals(1, byte.size) assertEquals(expected[counter++], byte[0]) } it("should have iterated 4 times") { assertEquals(4, counter) } } } describe("an async streaming get request without even lines") { val url = "https://httpbin.org/bytes/1690?seed=1" var error: Throwable? = null var response: Response? = null async.get(url, stream = true, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("iterating the lines") { if (error != null) throw error!! val iterator = response!!.lineIterator() val bytes = iterator.asSequence().toList().flatMap { it.toList() } val contentWithoutBytes = get(url).content.toList().filter { it != '\r'.toByte() && it != '\n'.toByte() } it("should be the same as the content without line breaks") { assertEquals(contentWithoutBytes, bytes) } } } describe("an async request where the client needs to authenticate itself by certificates") { val url = "https://httpbin.org/bytes/1690?seed=1" val sslContext = SslContextUtils.createFromKeyMaterial("keystores/badssl.com-client.p12", "badssl.com".toCharArray()) var error: Throwable? = null var response: Response? = null async.get(url, sslContext = sslContext, stream = true, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("iterating the lines") { if (error != null) throw error!! val statusCode = response!!.statusCode it("should be ok") { if (statusCode == 400) { print("WARNING: Certificate may have expired and needs to be updated") } else { assertEquals(200, statusCode) } } } } })
mpl-2.0
c00b77b20504829a4391dd56de73f54b
38.102222
213
0.548193
4.725027
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/test-framework/test/org/jetbrains/kotlin/idea/test/MockLibraryFacility.kt
3
2687
// 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.test import com.intellij.openapi.module.Module import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.roots.OrderRootType import com.intellij.testFramework.IdeaTestUtil import org.jetbrains.kotlin.idea.base.platforms.KotlinJavaScriptLibraryKind import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.platform.js.JsPlatform import java.io.File data class MockLibraryFacility( val sources: List<File>, val attachSources: Boolean = true, val platform: KotlinCompilerStandalone.Platform = KotlinCompilerStandalone.Platform.Jvm(), val options: List<String> = emptyList(), val classpath: List<File> = emptyList() ) { constructor( source: File, attachSources: Boolean = true, platform: KotlinCompilerStandalone.Platform = KotlinCompilerStandalone.Platform.Jvm(), options: List<String> = emptyList(), classpath: List<File> = emptyList() ) : this(listOf(source), attachSources, platform, options, classpath) companion object { const val MOCK_LIBRARY_NAME = "kotlinMockLibrary" fun tearDown(module: Module) { ConfigLibraryUtil.removeLibrary(module, MOCK_LIBRARY_NAME) } } fun setUp(module: Module) { val libraryJar = KotlinCompilerStandalone( sources, platform = platform, options = options, classpath = classpath ).compile() val kind = if (platform is JsPlatform) KotlinJavaScriptLibraryKind else null ConfigLibraryUtil.addLibrary(module, MOCK_LIBRARY_NAME, kind) { addRoot(libraryJar, OrderRootType.CLASSES) if (attachSources) { for (source in sources) { addRoot(source, OrderRootType.SOURCES) } } } } fun tearDown(module: Module) = Companion.tearDown(module) val asKotlinLightProjectDescriptor: KotlinLightProjectDescriptor get() = object : KotlinLightProjectDescriptor() { override fun configureModule(module: Module, model: ModifiableRootModel) = [email protected](module) override fun getSdk(): Sdk = if ([email protected] is KotlinCompilerStandalone.Platform.JavaScript) KotlinSdkType.INSTANCE.createSdkWithUniqueName(emptyList()) else IdeaTestUtil.getMockJdk18() } }
apache-2.0
69959bd61ae323e9e9258a1abf8720f3
38.514706
158
0.692222
5.050752
false
true
false
false
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/BaseCommitExecutorAction.kt
1
1851
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.vcs.actions.getContextCommitWorkflowHandler import com.intellij.openapi.vcs.changes.CommitExecutor import com.intellij.util.ui.JButtonAction import com.intellij.vcs.commit.CommitWorkflowHandler import javax.swing.JButton abstract class BaseCommitExecutorAction : JButtonAction(null) { init { isEnabledInModalContext = true } override fun createButton(): JButton = JButton().apply { isOpaque = false } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { val workflowHandler = e.getContextCommitWorkflowHandler() val executor = getCommitExecutor(workflowHandler) e.presentation.isVisible = workflowHandler != null && executor != null e.presentation.isEnabled = workflowHandler != null && executor != null && workflowHandler.isExecutorEnabled(executor) } override fun actionPerformed(e: AnActionEvent) { val workflowHandler = e.getContextCommitWorkflowHandler()!! val executor = getCommitExecutor(workflowHandler)!! workflowHandler.execute(executor) } protected open val executorId: String = "" protected open fun getCommitExecutor(handler: CommitWorkflowHandler?) = handler?.getExecutor(executorId) } internal class DefaultCommitExecutorAction(private val executor: CommitExecutor) : BaseCommitExecutorAction() { init { templatePresentation.text = executor.actionText } override fun getCommitExecutor(handler: CommitWorkflowHandler?): CommitExecutor = executor }
apache-2.0
f16cd4cf367afc3281493c606910f0ca
37.583333
140
0.790384
5.184874
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/PlatformExtensionReceiverOfInlineInspection.kt
1
5624
// 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.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.ui.LabeledComponent import com.intellij.ui.EditorTextField import org.intellij.lang.regexp.RegExpFileType import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.quickfix.getAddExclExclCallFix import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtVisitorVoid import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isNullabilityFlexible import org.jetbrains.kotlin.types.isNullable import java.awt.BorderLayout import java.util.regex.PatternSyntaxException import javax.swing.JPanel import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class PlatformExtensionReceiverOfInlineInspection : AbstractKotlinInspection() { private var nameRegex: Regex? = defaultNamePattern.toRegex() var namePattern: String = defaultNamePattern set(value) { field = value nameRegex = try { value.toRegex() } catch (e: PatternSyntaxException) { null } } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = object : KtVisitorVoid() { override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) { super.visitDotQualifiedExpression(expression) val languageVersionSettings = expression.languageVersionSettings if (!languageVersionSettings.supportsFeature(LanguageFeature.NullabilityAssertionOnExtensionReceiver)) { return } val nameRegex = nameRegex val callExpression = expression.selectorExpression as? KtCallExpression ?: return val calleeText = callExpression.calleeExpression?.text ?: return if (nameRegex != null && !nameRegex.matches(calleeText)) { return } val resolutionFacade = expression.getResolutionFacade() val context = expression.analyze(resolutionFacade, BodyResolveMode.PARTIAL) val resolvedCall = expression.getResolvedCall(context) ?: return val extensionReceiverType = resolvedCall.extensionReceiver?.type ?: return if (!extensionReceiverType.isNullabilityFlexible()) return val descriptor = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return if (!descriptor.isInline || descriptor.extensionReceiverParameter?.type?.isNullable() == true) return val receiverExpression = expression.receiverExpression val dataFlowValueFactory = resolutionFacade.dataFlowValueFactory val dataFlow = dataFlowValueFactory.createDataFlowValue(receiverExpression, extensionReceiverType, context, descriptor) val stableNullability = context.getDataFlowInfoBefore(receiverExpression).getStableNullability(dataFlow) if (!stableNullability.canBeNull()) return getAddExclExclCallFix(receiverExpression)?.let { holder.registerProblem( receiverExpression, KotlinBundle.message("call.of.inline.function.with.nullable.extension.receiver.can.cause.npe.in.kotlin.1.2"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(it, receiverExpression.containingKtFile) ) } } } override fun createOptionsPanel() = OptionsPanel(this) class OptionsPanel internal constructor(owner: PlatformExtensionReceiverOfInlineInspection) : JPanel() { init { layout = BorderLayout() val regexField = EditorTextField(owner.namePattern, null, RegExpFileType.INSTANCE).apply { setOneLineMode(true) } regexField.document.addDocumentListener(object : DocumentListener { override fun documentChanged(e: DocumentEvent) { owner.namePattern = regexField.text } }) val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("text.pattern"), BorderLayout.WEST) add(labeledComponent, BorderLayout.NORTH) } } companion object { const val defaultNamePattern = "(toBoolean)|(content.*)" } }
apache-2.0
6249725e901be14faa7a564d9ac93499
48.769912
158
0.711593
5.827979
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/FeedsGenerator.kt
2
3188
package com.eden.orchid.posts import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.generators.OrchidCollection import com.eden.orchid.api.generators.OrchidGenerator import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.IntDefault import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.render.RenderService import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.posts.model.FeedsModel import com.eden.orchid.utilities.SuppressedWarnings @Description("Generate feeds for you blog in RSS and Atom formats.", name = "RSS Feeds") class FeedsGenerator : OrchidGenerator<FeedsModel>(GENERATOR_KEY, Stage.META) { companion object { const val GENERATOR_KEY = "feeds" } @Option @StringDefault("rss", "atom") @Description( "A list of different feed types to render. Each feed type is rendered as `/{feedType}.xml` from the " + "`feeds/{feedType}.peb` resource." ) var feedTypes: Array<String> = emptyArray() @Option @StringDefault("posts") @Description("A list of generator keys whose pages are included in this feed.") lateinit var includeFrom: Array<String> @Option @IntDefault(25) @Description("The maximum number of entries to include in this feed.") var size = 25 override fun startIndexing(context: OrchidContext): FeedsModel { return FeedsModel(context, createFeeds(context)) } private fun createFeeds(context: OrchidContext): List<FeedPage> { val enabledGeneratorKeys = context.getGeneratorKeys(includeFrom, null) val feedItems = context.index.getChildIndices(enabledGeneratorKeys).flatMap { it.allPages } return if (feedItems.isNotEmpty()) { val sortedFeedItems = feedItems .sortedWith(compareBy({ it.lastModifiedDate }, { it.publishDate })) .reversed() .take(size) feedTypes .map { feedType -> feedType to context.getDefaultResourceSource(null, null).getResourceEntry(context, "feeds/$feedType.peb") } .filter { it.second != null } .map { (feedType, res) -> res!! res.reference.fileName = feedType res.reference.path = "" res.reference.outputExtension = "xml" res.reference.isUsePrettyUrl = false FeedPage(res, feedType, sortedFeedItems) } } else { emptyList() } } @Description(value = "A page with an RSS-like feed.", name = "RSS Feed") class FeedPage @Suppress(SuppressedWarnings.UNUSED_PARAMETER) constructor( resource: OrchidResource, filename: String, val items: List<OrchidPage> ) : OrchidPage(resource, RenderService.RenderMode.RAW, "rss", null) { @Option lateinit var mimeType: String @Option lateinit var feedName: String } }
mit
af1f9ba63ef3f8c6cbd7dbf996b2b2f4
34.422222
142
0.659034
4.452514
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/achievement/job/ShowUnlockedAchievementsScheduler.kt
1
1950
package io.ipoli.android.achievement.job import android.content.Context import android.graphics.Color import android.support.v4.content.ContextCompat import io.ipoli.android.R import io.ipoli.android.achievement.Achievement import io.ipoli.android.achievement.androidAchievement import io.ipoli.android.achievement.view.AchievementData import io.ipoli.android.achievement.view.AchievementUnlocked import io.ipoli.android.common.datetime.seconds import io.ipoli.android.common.view.asThemedWrapper import io.ipoli.android.common.view.attrData import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.GlobalScope import kotlinx.coroutines.experimental.launch /** * Created by Venelin Valkov <[email protected]> * on 06/09/2018. */ interface ShowUnlockedAchievementsScheduler { fun schedule(achievements: List<Achievement>) } class AndroidShowUnlockedAchievementsScheduler(private val context: Context) : ShowUnlockedAchievementsScheduler { override fun schedule(achievements: List<Achievement>) { val c = context.asThemedWrapper() val androidAchievements = achievements .map { it.androidAchievement }.map { AchievementData( title = c.getString(R.string.achievement_unlocked), subtitle = c.getString(it.title), textColor = Color.WHITE, backgroundColor = c.attrData(R.attr.colorAccent), icon = ContextCompat.getDrawable(c, it.icon), iconBackgroundColor = ContextCompat.getColor(c, it.color) ) } GlobalScope.launch(Dispatchers.Main) { AchievementUnlocked(c) .setRounded(true) .setLarge(true) .setTopAligned(true) .setReadingDelay(3.seconds.millisValue.toInt()) .show(androidAchievements) } } }
gpl-3.0
5ce11c53ad6c86b10db12cfdecb2a11a
33.839286
78
0.689744
4.653938
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/dsl/impl/LessonExecutorUtil.kt
4
10979
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.dsl.impl import com.intellij.ide.IdeBundle import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Disposer import com.intellij.ui.awt.RelativePoint import com.intellij.util.Alarm import com.intellij.util.ui.JBUI import training.dsl.* import training.learn.ActionsRecorder import training.ui.LearningUiHighlightingManager import training.ui.LessonMessagePane import training.ui.MessageFactory import training.ui.UISettings import java.awt.* import java.awt.event.ActionEvent import java.util.concurrent.CompletableFuture import java.util.concurrent.Future import javax.swing.* import javax.swing.border.EmptyBorder import javax.swing.tree.TreePath internal data class TaskProperties(var hasDetection: Boolean = false, var messagesNumber: Int = 0) internal object LessonExecutorUtil { /** This task is a real task with some event required and corresponding text. Used for progress indication. */ fun taskProperties(taskContent: TaskContext.() -> Unit, project: Project): TaskProperties { val fakeTaskContext = ExtractTaskPropertiesContext(project) taskContent(fakeTaskContext) return TaskProperties(fakeTaskContext.hasDetection, fakeTaskContext.textCount) } fun textMessages(taskContent: TaskContext.() -> Unit, project: Project): List<String> { val fakeTaskContext = ExtractTextTaskContext(project) taskContent(fakeTaskContext) return fakeTaskContext.messages } fun getTaskCallInfo(): String? { return Exception().stackTrace.first { element -> element.toString().let { it.startsWith("training.learn.lesson") || !it.startsWith("training.") } }?.toString() } fun showBalloonMessage(text: String, ui: JComponent, balloonConfig: LearningBalloonConfig, actionsRecorder: ActionsRecorder, lessonExecutor: LessonExecutor) { if (balloonConfig.delayBeforeShow == 0) { showBalloonMessage(text, ui, balloonConfig, actionsRecorder, lessonExecutor, true) } else { val delayed = { if (!actionsRecorder.disposed) { showBalloonMessage(text, ui, balloonConfig, actionsRecorder, lessonExecutor, true) } } Alarm().addRequest(delayed, balloonConfig.delayBeforeShow) } } private fun showBalloonMessage(text: String, ui: JComponent, balloonConfig: LearningBalloonConfig, actionsRecorder: ActionsRecorder, lessonExecutor: LessonExecutor, useAnimationCycle: Boolean) { val message = MessageFactory.convert(text).singleOrNull() ?: error("Balloon message should contain only one paragraph") val messagesPane = LessonMessagePane(false) messagesPane.border = null messagesPane.setBounds(0, 0, balloonConfig.width.takeIf { it != 0 } ?: 500, 1000) messagesPane.isOpaque = false messagesPane.addMessage(message, LessonMessagePane.MessageProperties(visualIndex = lessonExecutor.visualIndexNumber)) val preferredSize = messagesPane.preferredSize val balloonPanel = JPanel() balloonPanel.isOpaque = false balloonPanel.layout = BoxLayout(balloonPanel, BoxLayout.Y_AXIS) balloonPanel.border = UISettings.getInstance().balloonAdditionalBorder val insets = UISettings.getInstance().balloonAdditionalBorder.borderInsets var height = preferredSize.height + insets.top + insets.bottom val width = (if (balloonConfig.width != 0) balloonConfig.width else (preferredSize.width + insets.left + insets.right + 6)) balloonPanel.add(messagesPane) messagesPane.alignmentX = Component.LEFT_ALIGNMENT val gotItCallBack = balloonConfig.gotItCallBack val gotItButton = if (gotItCallBack != null) JButton().also { balloonPanel.add(it) it.alignmentX = Component.LEFT_ALIGNMENT it.border = EmptyBorder(JBUI.scale(10), UISettings.getInstance().balloonIndent, JBUI.scale(2), 0) it.background = Color(0, true) it.putClientProperty("gotItButton", true) it.putClientProperty("JButton.backgroundColor", UISettings.getInstance().tooltipButtonBackgroundColor) it.foreground = UISettings.getInstance().tooltipButtonForegroundColor it.action = object : AbstractAction(IdeBundle.message("got.it.button.name")) { override fun actionPerformed(e: ActionEvent?) { gotItCallBack() } } height += it.preferredSize.height } else null balloonPanel.preferredSize = Dimension(width, height) val balloon = JBPopupFactory.getInstance().createBalloonBuilder(balloonPanel) .setCloseButtonEnabled(false) .setAnimationCycle(if (useAnimationCycle) balloonConfig.animationCycle else 0) .setCornerToPointerDistance(balloonConfig.cornerToPointerDistance) .setPointerSize(Dimension(16, 8)) .setHideOnAction(false) .setHideOnClickOutside(false) .setBlockClicksThroughBalloon(true) .setFillColor(UISettings.getInstance().tooltipBackgroundColor) .setBorderColor(UISettings.getInstance().tooltipBorderColor) .setHideOnCloseClick(false) .setDisposable(actionsRecorder) .createBalloon() Disposer.register(balloon, messagesPane) balloon.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { val checkStopLesson = { lessonExecutor.taskInvokeLater { if (!actionsRecorder.disposed) showBalloonMessage(text, ui, balloonConfig, actionsRecorder, lessonExecutor, false) } } Alarm().addRequest(checkStopLesson, 500) // it is a hacky a little bit } }) balloon.show(getPosition(ui, balloonConfig.side), balloonConfig.side) gotItButton?.requestFocus() } private fun getPosition(component: JComponent, side: Balloon.Position): RelativePoint { val visibleRect = LearningUiHighlightingManager.getRectangle(component) ?: component.visibleRect val xShift = when (side) { Balloon.Position.atLeft -> 0 Balloon.Position.atRight -> visibleRect.width Balloon.Position.above, Balloon.Position.below -> visibleRect.width / 2 else -> error("Unexpected balloon position") } val yShift = when (side) { Balloon.Position.above -> 0 Balloon.Position.below -> visibleRect.height Balloon.Position.atLeft, Balloon.Position.atRight -> visibleRect.height / 2 else -> error("Unexpected balloon position") } val point = Point(visibleRect.x + xShift, visibleRect.y + yShift) return RelativePoint(component, point) } } private class ExtractTaskPropertiesContext(override val project: Project) : TaskContext() { var textCount = 0 var hasDetection = false override fun text(text: String, useBalloon: LearningBalloonConfig?) { if (useBalloon?.duplicateMessage == false) return textCount += text.split("\n").size } override fun trigger(actionId: String) { hasDetection = true } override fun trigger(checkId: (String) -> Boolean) { hasDetection = true } override fun <T> trigger(actionId: String, calculateState: TaskRuntimeContext.() -> T, checkState: TaskRuntimeContext.(T, T) -> Boolean) { hasDetection = true } override fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) { hasDetection = true } override fun triggers(vararg actionIds: String) { hasDetection = true } override fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> { hasDetection = true return CompletableFuture<Boolean>() } override fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> { hasDetection = true return CompletableFuture() } override fun timerCheck(delayMillis: Int, checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> { hasDetection = true return CompletableFuture() } override fun addFutureStep(p: DoneStepContext.() -> Unit) { hasDetection = true } override fun addStep(step: CompletableFuture<Boolean>) { hasDetection = true } override fun triggerUI(parameters: HighlightTriggerParametersContext.() -> Unit): HighlightingTriggerMethods { hasDetection = true return super.triggerUI(parameters) } @Suppress("OverridingDeprecatedMember") override fun <T : Component> triggerByPartOfComponentImpl(componentClass: Class<T>, options: LearningUiHighlightingManager.HighlightingOptions, selector: ((candidates: Collection<T>) -> T?)?, rectangle: TaskRuntimeContext.(T) -> Rectangle?) { hasDetection = true } @Suppress("OverridingDeprecatedMember") override fun <ComponentType : Component> triggerByUiComponentAndHighlightImpl(componentClass: Class<ComponentType>, options: LearningUiHighlightingManager.HighlightingOptions, selector: ((candidates: Collection<ComponentType>) -> ComponentType?)?, finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) { hasDetection = true } override fun triggerByFoundListItemAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkList: TaskRuntimeContext.(list: JList<*>) -> Int?) { hasDetection = true } override fun triggerByFoundPathAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions, checkTree: TaskRuntimeContext.(tree: JTree) -> TreePath?) { hasDetection = true } override fun action(actionId: String): String = "" //Doesn't matter what to return override fun code(sourceSample: String): String = "" //Doesn't matter what to return override fun strong(text: String): String = "" //Doesn't matter what to return override fun icon(icon: Icon): String = "" //Doesn't matter what to return } private class ExtractTextTaskContext(override val project: Project) : TaskContext() { val messages = ArrayList<String>() override fun text(text: String, useBalloon: LearningBalloonConfig?) { if (useBalloon?.duplicateMessage == false) return messages.add(text) } }
apache-2.0
ac4aae1737e4f5a1d79c1a82c764f6d3
40.587121
290
0.689407
5.001822
false
true
false
false
hellenxu/TipsProject
DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/issues/scrollview/PageAdapter.kt
1
986
package six.ca.droiddailyproject.issues.scrollview import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import android.util.SparseArray /** * @CopyRight six.ca * Created by Heavens on 2019-01-12. */ class PageAdapter(val fm: FragmentManager, val num: Int): FragmentPagerAdapter(fm) { private val fragmentArray = SparseArray<Fragment>() override fun getItem(p0: Int): Fragment { return createFragment(pos = p0) } private fun createFragment(pos: Int): Fragment { var fragment = fragmentArray.get(pos) if(fragment == null) { when(pos) { 0 -> fragment = FragmentOneOne() 1 -> fragment = FragmentOneTwo() 2 -> fragment = FragmentOneThree() } fragmentArray.put(pos, fragment) } return fragment } override fun getCount(): Int { return num } }
apache-2.0
92f36edea773b9389d9e5f5f99cd0ffd
24.973684
84
0.636917
4.461538
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/CustomHeader.kt
1
14796
// 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.wm.impl.customFrameDecorations.header import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.ide.ui.UISettings import com.intellij.openapi.Disposable import com.intellij.openapi.MnemonicHelper import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons import com.intellij.ui.AppUIUtil import com.intellij.ui.Gray import com.intellij.ui.JBColor import com.intellij.ui.awt.RelativeRectangle import com.intellij.ui.paint.LinePainter2D import com.intellij.ui.scale.JBUIScale import com.intellij.ui.scale.ScaleContext import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.jetbrains.JBR import java.awt.* import java.awt.event.* import java.beans.PropertyChangeListener import java.util.* import javax.swing.* import javax.swing.border.Border import kotlin.math.ceil import kotlin.math.floor import kotlin.math.roundToInt internal abstract class CustomHeader(private val window: Window) : JPanel(), Disposable { companion object { private val LOGGER = logger<CustomHeader>() val H get() = 12 val V get() = 5 val LABEL_BORDER: JBEmptyBorder get() = JBUI.Borders.empty(V, 0) fun create(window: Window): CustomHeader { return if (window is JFrame) { DefaultFrameHeader(window) } else { DialogHeader(window) } } private val windowBorderThicknessInPhysicalPx: Int = run { // Windows 10 (tested on 1809) determines the window border size by the main display scaling, rounded down. This value is // calculated once on desktop session start, so it should be okay to store once per IDE session. val scale = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice.defaultConfiguration.defaultTransform.scaleY floor(scale).toInt() } } private var windowListener: WindowAdapter private val myComponentListener: ComponentListener private val myIconProvider = ScaleContext.Cache { ctx -> getFrameIcon(ctx) } protected var myActive = false protected val windowRootPane: JRootPane? = when (window) { is JWindow -> window.rootPane is JDialog -> window.rootPane is JFrame -> window.rootPane else -> null } private var customFrameTopBorder: CustomFrameTopBorder? = null private val icon: Icon get() = getFrameIcon() private fun getFrameIcon(): Icon { val scaleContext = ScaleContext.create(window) //scaleContext.overrideScale(ScaleType.USR_SCALE.of(UISettings.defFontScale.toDouble())) return myIconProvider.getOrProvide(scaleContext)!! } protected open fun getFrameIcon(scaleContext: ScaleContext): Icon { val size = (JBUIScale.scale(16f) * UISettings.defFontScale).toInt() return AppUIUtil.loadSmallApplicationIcon(scaleContext, size) } protected val productIcon: JComponent by lazy { createProductIcon() } protected val buttonPanes: CustomFrameTitleButtons by lazy { createButtonsPane() } init { isOpaque = true background = getHeaderBackground() fun onClose() { Disposer.dispose(this) } windowListener = object : WindowAdapter() { override fun windowActivated(ev: WindowEvent?) { setActive(true) } override fun windowDeactivated(ev: WindowEvent?) { setActive(false) } override fun windowClosed(e: WindowEvent?) { onClose() } override fun windowStateChanged(e: WindowEvent?) { windowStateChanged() } } myComponentListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { SwingUtilities.invokeLater { updateCustomDecorationHitTestSpots() } } } setCustomFrameTopBorder() } protected open fun getHeaderBackground(active: Boolean = true) = JBUI.CurrentTheme.CustomFrameDecorations.titlePaneBackground(active) protected fun setCustomFrameTopBorder(isTopNeeded: () -> Boolean = { true }, isBottomNeeded: () -> Boolean = { false }) { customFrameTopBorder = CustomFrameTopBorder(isTopNeeded, isBottomNeeded) border = customFrameTopBorder } abstract fun createButtonsPane(): CustomFrameTitleButtons open fun windowStateChanged() { updateCustomDecorationHitTestSpots() } protected var added = false override fun addNotify() { super.addNotify() added = true installListeners() updateCustomDecorationHitTestSpots() customFrameTopBorder!!.addNotify() } override fun removeNotify() { added = false super.removeNotify() uninstallListeners() customFrameTopBorder!!.removeNotify() } protected open fun installListeners() { updateActive() window.addWindowListener(windowListener) window.addWindowStateListener(windowListener) window.addComponentListener(myComponentListener) } protected open fun uninstallListeners() { window.removeWindowListener(windowListener) window.removeWindowStateListener(windowListener) window.removeComponentListener(myComponentListener) } protected fun updateCustomDecorationHitTestSpots() { if (!added || !JBR.isCustomWindowDecorationSupported()) { return } val decor = JBR.getCustomWindowDecoration() if ((window is JDialog && window.isUndecorated) || (window is JFrame && window.isUndecorated)) { decor.setCustomDecorationHitTestSpots(window, Collections.emptyList()) decor.setCustomDecorationTitleBarHeight(window, 0) } else { if (height == 0) return val toList = getHitTestSpots().map { java.util.Map.entry(it.first.getRectangleOn(window), it.second) }.toList() decor.setCustomDecorationHitTestSpots(window, toList) decor.setCustomDecorationTitleBarHeight(window, height + window.insets.top) } } /** * Pairs of rectangles and integer constants from {@link com.jetbrains.CustomWindowDecoration} describing type of the spot */ abstract fun getHitTestSpots(): Sequence<Pair<RelativeRectangle, Int>> private fun setActive(value: Boolean) { myActive = value updateActive() updateCustomDecorationHitTestSpots() } protected open fun updateActive() { buttonPanes.isSelected = myActive buttonPanes.updateVisibility() customFrameTopBorder?.repaintBorder() background = getHeaderBackground(myActive) } protected val myCloseAction: Action = CustomFrameAction(CommonBundle.getCloseButtonText(), AllIcons.Windows.CloseSmall) { close() } protected fun close() { window.dispatchEvent(WindowEvent(window, WindowEvent.WINDOW_CLOSING)) } override fun dispose() { } protected class CustomFrameAction(@NlsActions.ActionText name: String, icon: Icon, val action: () -> Unit) : AbstractAction(name, icon) { override fun actionPerformed(e: ActionEvent) = action() } private fun createProductIcon(): JComponent { val menu = JPopupMenu() MnemonicHelper.init(menu) val ic = object : JLabel() { override fun getIcon(): Icon { return [email protected] } } ic.addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent?) { JBPopupMenu.showBelow(ic, menu) } }) menu.isFocusable = false menu.isBorderPainted = true addMenuItems(menu) return ic } open fun addMenuItems(menu: JPopupMenu) { val closeMenuItem = menu.add(myCloseAction) closeMenuItem.font = JBFont.label().deriveFont(Font.BOLD) } inner class CustomFrameTopBorder(val isTopNeeded: () -> Boolean = { true }, val isBottomNeeded: () -> Boolean = { false }) : Border { // Bottom border is a line between a window title/main menu area and the frame content. private val bottomBorderWidthLogicalPx = JBUI.scale(1) // In reality, Windows uses #262626 with alpha-blending with alpha=0.34, but we have no (easy) way of doing the same, so let's just // use the value on white background (since it is most noticeable on white). // // Unfortunately, DWM doesn't offer an API to determine this value, so it has to be hardcoded here. private val defaultActiveBorder = Color(0x707070) private val inactiveColor = Color(0xaaaaaa) private val menuBarBorderColor: Color = JBColor.namedColor("MenuBar.borderColor", JBColor(Gray.xCD, Gray.x51)) private var colorizationAffectsBorders: Boolean = false private var activeColor: Color = defaultActiveBorder private fun calculateAffectsBorders(): Boolean { val windowsBuild = SystemInfo.getWinBuildNumber() ?: 0 if (windowsBuild < 17763) return true // should always be active on older versions on Windows return Toolkit.getDefaultToolkit().getDesktopProperty("win.dwm.colorizationColor.affects.borders") as Boolean? ?: true } private fun calculateActiveBorderColor(): Color { if (!colorizationAffectsBorders) return defaultActiveBorder try { Toolkit.getDefaultToolkit().apply { val colorizationColor = getDesktopProperty("win.dwm.colorizationColor") as Color? if (colorizationColor != null) { // The border color is a result of an alpha blend of colorization color and #D9D9D9 with the alpha value set by the // colorization color balance. var colorizationColorBalance = getDesktopProperty("win.dwm.colorizationColorBalance") as Int? if (colorizationColorBalance != null) { if (colorizationColorBalance > 100) { // May be caused by custom Windows themes installed. colorizationColorBalance = 100 } // If the desktop setting "Automatically pick an accent color from my background" is active, then the border // color should be the same as the colorization color read from the registry. To detect that setting, we use the // fact that colorization color balance is set to 0xfffffff3 when the setting is active. if (colorizationColorBalance < 0) colorizationColorBalance = 100 return when (colorizationColorBalance) { 0 -> Color(0xD9D9D9) 100 -> colorizationColor else -> { val alpha = colorizationColorBalance / 100.0f val remainder = 1 - alpha val r = (colorizationColor.red * alpha + 0xD9 * remainder).roundToInt() val g = (colorizationColor.green * alpha + 0xD9 * remainder).roundToInt() val b = (colorizationColor.blue * alpha + 0xD9 * remainder).roundToInt() Color(r, g, b) } } } } return colorizationColor ?: getDesktopProperty("win.frame.activeBorderColor") as Color? ?: menuBarBorderColor } } catch (t: Throwable) { // Should be as fail-safe as possible, since any errors during border coloring could lead to an IDE being broken. LOGGER.error(t) return defaultActiveBorder } } private fun calculateWindowBorderThicknessInLogicalPx(): Double { return windowBorderThicknessInPhysicalPx.toDouble() / JBUIScale.sysScale(window) } private val listeners = mutableListOf<Pair<String, PropertyChangeListener>>() private inline fun listenForPropertyChanges(vararg propertyNames: String, crossinline action: () -> Unit) { val toolkit = Toolkit.getDefaultToolkit() val listener = PropertyChangeListener { action() } for (property in propertyNames) { toolkit.addPropertyChangeListener(property, listener) listeners.add(property to listener) } } fun addNotify() { colorizationAffectsBorders = calculateAffectsBorders() listenForPropertyChanges("win.dwm.colorizationColor.affects.borders") { colorizationAffectsBorders = calculateAffectsBorders() activeColor = calculateActiveBorderColor() // active border color is dependent on whether colorization affects borders or not } activeColor = calculateActiveBorderColor() listenForPropertyChanges("win.dwm.colorizationColor", "win.dwm.colorizationColorBalance", "win.frame.activeBorderColor") { activeColor = calculateActiveBorderColor() } } fun removeNotify() { val toolkit = Toolkit.getDefaultToolkit() for ((propertyName, listener) in listeners) toolkit.removePropertyChangeListener(propertyName, listener) listeners.clear() } fun repaintBorder() { val borderInsets = getBorderInsets(this@CustomHeader) val thickness = calculateWindowBorderThicknessInLogicalPx() repaint(0, 0, width, ceil(thickness).toInt()) repaint(0, height - borderInsets.bottom, width, borderInsets.bottom) } private val shouldDrawTopBorder: Boolean get() { val drawTopBorderActive = myActive && (colorizationAffectsBorders || UIUtil.isUnderIntelliJLaF()) // omit in Darcula with colorization disabled val drawTopBorderInactive = !myActive && UIUtil.isUnderIntelliJLaF() return drawTopBorderActive || drawTopBorderInactive } override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) { val thickness = calculateWindowBorderThicknessInLogicalPx() if (isTopNeeded() && shouldDrawTopBorder) { g.color = if (myActive) activeColor else inactiveColor LinePainter2D.paint(g as Graphics2D, x.toDouble(), y.toDouble(), width.toDouble(), y.toDouble(), LinePainter2D.StrokeType.INSIDE, thickness) } if (isBottomNeeded()) { g.color = menuBarBorderColor val y1 = y + height - bottomBorderWidthLogicalPx LinePainter2D.paint(g as Graphics2D, x.toDouble(), y1.toDouble(), width.toDouble(), y1.toDouble()) } } override fun getBorderInsets(c: Component): Insets { val thickness = calculateWindowBorderThicknessInLogicalPx() val top = if (isTopNeeded() && (colorizationAffectsBorders || UIUtil.isUnderIntelliJLaF())) ceil(thickness).toInt() else 0 val bottom = if (isBottomNeeded()) bottomBorderWidthLogicalPx else 0 return Insets(top, 0, bottom, 0) } override fun isBorderOpaque(): Boolean { return true } } }
apache-2.0
47f94b92b395e633eca9e98a3b86b778
35.264706
151
0.700392
4.619419
false
false
false
false
pdvrieze/kotlinsql
monadic/src/generators/kotlin/kotlinsql/builder/generate_monads.kt
1
7138
/* * Copyright (c) 2020. * * This file is part of ProcessManager. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Created by pdvrieze on 01/03/2020. */ package kotlinsql.builder import java.io.Writer @Suppress("unused") class GenerateConnectionSource { fun doGenerate(output: Writer, input: Any) { val count = input as Int output.apply { appendCopyright() appendLine() appendLine("package io.github.pdvrieze.kotlinsql.monadic") appendLine() appendLine("import io.github.pdvrieze.kotlinsql.ddl.Column") appendLine("import io.github.pdvrieze.kotlinsql.ddl.Database") appendLine("import io.github.pdvrieze.kotlinsql.dml.*") appendLine("import io.github.pdvrieze.kotlinsql.dml.impl.*") appendLine("import io.github.pdvrieze.kotlinsql.ddl.IColumnType") appendLine("import io.github.pdvrieze.kotlinsql.monadic.actions.*") appendLine("import io.github.pdvrieze.kotlinsql.monadic.actions.impl.*") appendLine("import io.github.pdvrieze.kotlinsql.monadic.impl.ResultSetIterator") appendLine("import java.sql.SQLException") appendLine("import javax.sql.DataSource") appendLine() appendLine("interface ConnectionSource<DB : Database> : ConnectionSourceBase<DB>, DBActionReceiver<DB> {") appendLine() appendLine(" override val datasource: DataSource") appendLine() appendLine(" fun <O> DBAction<DB, O>.commit(): O {") appendLine(" return commit(this@ConnectionSource)") appendLine(" }") appendLine("}") appendLine() appendLine("interface DBActionReceiver<DB: Database>: DBContext<DB> {") appendLine() appendLine(" val metadata: MonadicMetadata<DB>") for (op in Operation.values()) { for (n in 1..count) { appendLine() append(" ") generateOperationSignature(n, op) appendLine(" {") if (op == Operation.SELECT) { append(" return ${op.action}Impl(${op.base}$n(") } else { val update = if (op == Operation.INSERT_OR_UPDATE) "true" else "false" append(" return ${op.action}Impl(${op.base}$n(db[col1.table], $update, ") } (1..n).joinTo(this) { m -> "col$m" } appendLine("))") appendLine(" }") if (op == Operation.SELECT) { appendLine() append(" fun <") appendColumnGenerics(n, " ") appendLine(",") appendLine(" R>") val receiver = (1..n).joinToString(prefix = "SelectAction<DB, Select$n<", postfix = ">>") { i -> "T$i, S$i, C$i" } append(" ".repeat(8)).append(receiver) (1..n).joinTo(this, prefix = ".transform( transform: (", postfix = ") -> R): DBAction<DB, List<R>> {" ) { "T$it?" } appendLine("""| | return mapEach { | transform(""".trimMargin()) for (i in 1..n) { append(" ".repeat(16)) appendLine("it.value(query.select.col$i, $i),") } appendLine(""" | ) | } | } """.trimMargin()) } } } appendLine("}") // interface appendLine() appendLine("private class ConnectionSourceImpl<DB : Database>(") appendLine(" override val db: DB,") appendLine(" override val datasource: DataSource") appendLine(") : ConnectionSourceImplBase<DB>() {") // appendln() // appendln(" override fun metadata(): MonadicMetadata<DB> {") // appendln(" return MonadicMetadataImpl()") // appendln(" }") appendLine("}") appendLine() appendLine("@PublishedApi") appendLine("internal fun <DB : Database, R> DB.generatedInvoke(datasource: DataSource, action: ConnectionSource<DB>.() -> R): R {") appendLine(" return ConnectionSourceImpl(this, datasource).action()") appendLine("}") for (op in arrayOf(Operation.INSERT)) { for (n in 1..count) { appendLine() generateColumnOperationSignature( n, "VALUES", "T", "InsertAction<DB, _Insert$n<", "InsertActionCommon<DB, _Insert$n<", nullableParam = true, genericPrefix = "DB: Database, " ) appendLine("{") append(" return InsertActionImpl(insert.VALUES(") (1..n).joinTo(this) { "col$it" } appendLine("))") appendLine("}") /* fun <T1:Any, S1: IColumnType<T1, S1, C1>, C1: Column<T1, S1, C1>> DBAction.InsertStart<_Insert1<T1, S1, C1>>.VALUES(col1: T1): DBAction.Insert<_Insert1<T1, S1, C1>> { return DBAction.Insert(this.insert.VALUES(col1)) } */ } } } } private fun Writer.generateOperationSignature(n: Int, op: Operation, baseIndent: String = " ") { if (n == 1 && op == Operation.SELECT) { generateColumnOperationSignature(n, op.name, "C", "SelectAction<DB, Select1<", baseIndent = baseIndent) } else { generateColumnOperationSignature(n, op.name, "C", "${op.action}<DB, ${op.base}$n<", baseIndent = baseIndent) } } } private enum class Operation(val action: String, val base: String = action) { SELECT("SelectAction", "_Select"), INSERT("ValuelessInsertAction", "_Insert"), INSERT_OR_UPDATE("ValuelessInsertAction", "_Insert"), // UPDATE("Update") }
apache-2.0
0bfe806713b719cf359b4ac07bf907ca
41.236686
143
0.507705
4.787391
false
false
false
false
AsamK/TextSecure
app/src/spinner/java/org/thoughtcrime/securesms/database/IsStoryTransformer.kt
2
720
package org.thoughtcrime.securesms.database import android.database.Cursor import org.signal.core.util.requireInt import org.signal.spinner.ColumnTransformer import org.thoughtcrime.securesms.database.model.StoryType.Companion.fromCode object IsStoryTransformer : ColumnTransformer { override fun matches(tableName: String?, columnName: String): Boolean { return columnName == MmsDatabase.STORY_TYPE && (tableName == null || tableName == MmsDatabase.TABLE_NAME) } override fun transform(tableName: String?, columnName: String, cursor: Cursor): String { val storyType = fromCode(cursor.requireInt(MmsDatabase.STORY_TYPE)) return "${cursor.requireInt(MmsDatabase.STORY_TYPE)}<br><br>$storyType" } }
gpl-3.0
32220a4d9a314b47980eaeb224968490
41.352941
109
0.780556
4.210526
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyViewModel.kt
1
2227
package org.thoughtcrime.securesms.stories.viewer.reply.group import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.paging.ProxyPagingController import org.thoughtcrime.securesms.conversation.colors.NameColors import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.rx.RxStore class StoryGroupReplyViewModel(storyId: Long, repository: StoryGroupReplyRepository) : ViewModel() { private val sessionMemberCache: MutableMap<GroupId, Set<Recipient>> = NameColors.createSessionMembersCache() private val store = RxStore(StoryGroupReplyState()) private val disposables = CompositeDisposable() val stateSnapshot: StoryGroupReplyState = store.state val state: Flowable<StoryGroupReplyState> = store.stateFlowable val pagingController: ProxyPagingController<MessageId> = ProxyPagingController() init { disposables += repository.getThreadId(storyId).subscribe { threadId -> store.update { it.copy(threadId = threadId) } } disposables += repository.getPagedReplies(storyId) .doOnNext { pagingController.set(it.controller) } .flatMap { it.data } .subscribeBy { data -> store.update { state -> state.copy( replies = data, loadState = StoryGroupReplyState.LoadState.READY ) } } disposables += repository.getNameColorsMap(storyId, sessionMemberCache) .subscribeBy { nameColors -> store.update { state -> state.copy(nameColors = nameColors) } } } override fun onCleared() { disposables.clear() } class Factory(private val storyId: Long, private val repository: StoryGroupReplyRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(StoryGroupReplyViewModel(storyId, repository)) as T } } }
gpl-3.0
3ad3f3d54ed83bbd4d3767549028dd12
35.508197
123
0.74899
4.668763
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/view/mod/GenericTextDetectorActivity.kt
1
5752
package ch.abertschi.adfree.view.mod import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.Editable import android.text.Html import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.ImageView import android.widget.ScrollView import android.widget.TextView import ch.abertschi.adfree.R import ch.abertschi.adfree.model.TextRepositoryData import org.jetbrains.anko.* class GenericTextDetectorActivity : AppCompatActivity(), AnkoLogger { private lateinit var presenter: GenericTextDetectorPresenter private lateinit var viewAdapter: DetectorAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.mod_text_detector) val textView = findViewById<TextView>(R.id.textdetector_activity_title) val text = "the <font color=#FFFFFF>text detector</font> flags a notification based on the presence of text." textView.text = Html.fromHtml(text) findViewById<ScrollView>(R.id.mod_text_scroll).scrollTo(0, 0) presenter = GenericTextDetectorPresenter(this, this) var viewManager = LinearLayoutManager(this) viewAdapter = DetectorAdapter(presenter.getData(), presenter) var recyclerView = findViewById<RecyclerView>(R.id.detector_recycle_view).apply { layoutManager = viewManager adapter = viewAdapter } findViewById<TextView>(R.id.det_title_text).setOnClickListener { presenter.addNewEntry() } findViewById<TextView>(R.id.det_subtitle_text).setOnClickListener { presenter.addNewEntry() } findViewById<TextView>(R.id.det_title_help).setOnClickListener { presenter.browseHelp() } findViewById<TextView>(R.id.det_subtitle_help).setOnClickListener { presenter.browseHelp() } } fun showOptionDialog(entry: TextRepositoryData) { val d = AlertDialog.Builder(this) .setTitle("Options") .setView(LayoutInflater.from(this).inflate(R.layout.delete_dialog, null)) .setPositiveButton(android.R.string.yes) { dialog, which -> presenter.deleteEntry(entry) } .setNegativeButton(android.R.string.no) { dialog, which -> dialog.dismiss() } .setOnDismissListener { it.dismiss() } .create() d.window?.setBackgroundDrawableResource(R.color.colorBackground) d.show() } fun insertData() { viewAdapter.notifyDataSetChanged(); } private class DetectorAdapter( private val data: List<TextRepositoryData>, private val presenter: GenericTextDetectorPresenter ) : RecyclerView.Adapter<DetectorAdapter.MyViewHolder>(), AnkoLogger { class MyViewHolder( val view: View, val title: EditText, val subtitle: EditText, val more: ImageView, val sepView: View ) : RecyclerView.ViewHolder(view) override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): MyViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.mod_text_detector_view_element, parent, false) val title = view.findViewById(R.id.det_title) as EditText val subtitle = view.findViewById(R.id.det_subtitle) as EditText val more = view.findViewById<ImageView>(R.id.det_more) as ImageView val sep = view.findViewById<View>(R.id.mod_det_seperation) return MyViewHolder(view, title, subtitle, more, sep) } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { var entry = data[position] holder.more.onClick { presenter.onMoreClicked(entry) } holder.title.setText(entry.packageName) holder.subtitle.setText(entry.content.joinToString(separator = "\n")) holder.title.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable) { entry.packageName = s.toString() presenter.updateEntry(entry) } }) holder.subtitle.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence?, start: Int, count: Int, after: Int ) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } override fun afterTextChanged(s: Editable) { entry.content = s.toString().split("\n") presenter.updateEntry(entry) } }) holder.sepView.visibility = if (position == data.size - 1) View.INVISIBLE else View.VISIBLE } override fun getItemCount() = data.size } }
apache-2.0
695c9247ea2193b31976f66b4cce4c3f
34.95
110
0.612483
4.997394
false
false
false
false
ktorio/ktor
ktor-shared/ktor-websockets/common/src/io/ktor/websocket/RawWebSocketCommon.kt
1
7921
/* * Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket import io.ktor.util.* import io.ktor.util.cio.* import io.ktor.utils.io.* import io.ktor.utils.io.bits.* import io.ktor.utils.io.core.* import kotlinx.coroutines.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.channels.* import kotlin.coroutines.* import kotlin.random.* /** * Creates a RAW web socket session from connection * * @param input is a [ByteReadChannel] of connection * @param output is a [ByteWriteChannel] of connection * @param maxFrameSize is an initial [maxFrameSize] value for [WebSocketSession] * @param masking is an initial [masking] value for [WebSocketSession] * @param coroutineContext is a [CoroutineContext] to execute reading/writing from/to connection */ @Suppress("FunctionName") public expect fun RawWebSocket( input: ByteReadChannel, output: ByteWriteChannel, maxFrameSize: Long = Int.MAX_VALUE.toLong(), masking: Boolean = false, coroutineContext: CoroutineContext ): WebSocketSession @OptIn(ExperimentalCoroutinesApi::class, InternalAPI::class) internal class RawWebSocketCommon( private val input: ByteReadChannel, private val output: ByteWriteChannel, override var maxFrameSize: Long = Int.MAX_VALUE.toLong(), override var masking: Boolean = false, coroutineContext: CoroutineContext ) : WebSocketSession { private val socketJob: CompletableJob = Job(coroutineContext[Job]) private val _incoming = Channel<Frame>(capacity = 8) private val _outgoing = Channel<Any>(capacity = 8) private var lastOpcode = 0 override val coroutineContext: CoroutineContext = coroutineContext + socketJob + CoroutineName("raw-ws") override val incoming: ReceiveChannel<Frame> get() = _incoming override val outgoing: SendChannel<Frame> get() = _outgoing override val extensions: List<WebSocketExtension<*>> get() = emptyList() private val writerJob = launch(context = CoroutineName("ws-writer"), start = CoroutineStart.ATOMIC) { try { mainLoop@ while (true) when (val message = _outgoing.receive()) { is Frame -> { output.writeFrame(message, masking) output.flush() if (message is Frame.Close) break@mainLoop } is FlushRequest -> { message.complete() } else -> throw IllegalArgumentException("unknown message $message") } _outgoing.close() } catch (cause: ChannelWriteException) { _outgoing.close(CancellationException("Failed to write to WebSocket.", cause)) } catch (t: Throwable) { _outgoing.close(t) } finally { _outgoing.close(CancellationException("WebSocket closed.", null)) output.close() } while (true) when (val message = _outgoing.tryReceive().getOrNull() ?: break) { is FlushRequest -> message.complete() else -> {} } } private val readerJob = launch(CoroutineName("ws-reader"), start = CoroutineStart.ATOMIC) { try { while (true) { val frame = input.readFrame(maxFrameSize, lastOpcode) if (!frame.frameType.controlFrame) { lastOpcode = frame.frameType.opcode } _incoming.send(frame) } } catch (cause: FrameTooBigException) { outgoing.send(Frame.Close(CloseReason(CloseReason.Codes.TOO_BIG, cause.message))) _incoming.close(cause) } catch (cause: CancellationException) { _incoming.cancel(cause) } catch (eof: EOFException) { // no more bytes is possible to read } catch (eof: ClosedReceiveChannelException) { // no more bytes is possible to read } catch (io: ChannelIOException) { _incoming.cancel() } catch (cause: Throwable) { _incoming.close(cause) throw cause } finally { _incoming.close() } } init { socketJob.complete() } override suspend fun flush(): Unit = FlushRequest(coroutineContext[Job]).also { try { _outgoing.send(it) } catch (closed: ClosedSendChannelException) { it.complete() writerJob.join() } catch (sendFailure: Throwable) { it.complete() throw sendFailure } }.await() @Deprecated( "Use cancel() instead.", ReplaceWith("cancel()", "kotlinx.coroutines.cancel"), level = DeprecationLevel.ERROR ) override fun terminate() { outgoing.close() socketJob.complete() } private class FlushRequest(parent: Job?) { private val done: CompletableJob = Job(parent) fun complete(): Boolean = done.complete() suspend fun await(): Unit = done.join() } } private fun ByteReadPacket.mask(maskKey: Int): ByteReadPacket = withMemory(4) { maskMemory -> maskMemory.storeIntAt(0, maskKey) buildPacket { repeat(remaining.toInt()) { i -> writeByte((readByte().toInt() xor (maskMemory[i % 4].toInt())).toByte()) } } } /** * Serializes WebSocket [Frame] and writes the bits into the [ByteWriteChannel]. * If [masking] is true, then data will be masked with random mask */ @InternalAPI // used in tests public suspend fun ByteWriteChannel.writeFrame(frame: Frame, masking: Boolean) { val length = frame.data.size val flagsAndOpcode = frame.fin.flagAt(7) or frame.rsv1.flagAt(6) or frame.rsv2.flagAt(5) or frame.rsv3.flagAt(4) or frame.frameType.opcode writeByte(flagsAndOpcode.toByte()) val formattedLength = when { length < 126 -> length length <= 0xffff -> 126 else -> 127 } val maskAndLength = masking.flagAt(7) or formattedLength writeByte(maskAndLength.toByte()) when (formattedLength) { 126 -> writeShort(length.toShort()) 127 -> writeLong(length.toLong()) } val data = ByteReadPacket(frame.data) val maskedData = when (masking) { true -> { val maskKey = Random.nextInt() writeInt(maskKey) data.mask(maskKey) } false -> data } writePacket(maskedData) } /** * Reads bits from [ByteReadChannel] and converts into Websocket [Frame]. * * @param maxFrameSize maximum frame size that could be read * @param lastOpcode last read opcode */ @InternalAPI // used in tests public suspend fun ByteReadChannel.readFrame(maxFrameSize: Long, lastOpcode: Int): Frame { val flagsAndOpcode = readByte().toInt() val maskAndLength = readByte().toInt() val length = when (val length = maskAndLength and 0x7f) { 126 -> readShort().toLong() and 0xffff 127 -> readLong() else -> length.toLong() } val maskKey = when (maskAndLength and 0x80 != 0) { true -> readInt() false -> -1 } if (length > Int.MAX_VALUE || length > maxFrameSize) { throw FrameTooBigException(length) } val data = readPacket(length.toInt()) val maskedData = when (maskKey) { -1 -> data else -> data.mask(maskKey) } val opcode = (flagsAndOpcode and 0x0f).let { new -> if (new == 0) lastOpcode else new } val frameType = FrameType[opcode] ?: throw IllegalStateException("Unsupported opcode: $opcode") return Frame.byType( fin = flagsAndOpcode and 0x80 != 0, frameType = frameType, data = maskedData.readBytes(), rsv1 = flagsAndOpcode and 0x40 != 0, rsv2 = flagsAndOpcode and 0x20 != 0, rsv3 = flagsAndOpcode and 0x10 != 0 ) }
apache-2.0
0dc4c8f250dc4835585d8c47cd2b620e
31.86722
119
0.622775
4.410356
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Boolean/BoolVec3.kt
1
24645
package glm data class BoolVec3(val x: Boolean, val y: Boolean, val z: Boolean) { // Initializes each element by evaluating init from 0 until 2 constructor(init: (Int) -> Boolean) : this(init(0), init(1), init(2)) operator fun get(idx: Int): Boolean = when (idx) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun not(): BoolVec3 = BoolVec3(!x, !y, !z) inline fun map(func: (Boolean) -> Boolean): BoolVec3 = BoolVec3(func(x), func(y), func(z)) fun toList(): List<Boolean> = listOf(x, y, z) // Predefined vector constants companion object Constants { val zero: BoolVec3 = BoolVec3(false, false, false) val ones: BoolVec3 = BoolVec3(true, true, true) val unitX: BoolVec3 = BoolVec3(true, false, false) val unitY: BoolVec3 = BoolVec3(false, true, false) val unitZ: BoolVec3 = BoolVec3(false, false, true) } // Conversions to Float fun toVec(): Vec3 = Vec3(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f) inline fun toVec(conv: (Boolean) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec2(): Vec2 = Vec2(if (x) 1f else 0f, if (y) 1f else 0f) inline fun toVec2(conv: (Boolean) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(): Vec3 = Vec3(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f) inline fun toVec3(conv: (Boolean) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec4(w: Float = 0f): Vec4 = Vec4(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f, w) inline fun toVec4(w: Float = 0f, conv: (Boolean) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w) // Conversions to Float fun toMutableVec(): MutableVec3 = MutableVec3(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f) inline fun toMutableVec(conv: (Boolean) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec2(): MutableVec2 = MutableVec2(if (x) 1f else 0f, if (y) 1f else 0f) inline fun toMutableVec2(conv: (Boolean) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(): MutableVec3 = MutableVec3(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f) inline fun toMutableVec3(conv: (Boolean) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(if (x) 1f else 0f, if (y) 1f else 0f, if (z) 1f else 0f, w) inline fun toMutableVec4(w: Float = 0f, conv: (Boolean) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toDoubleVec(): DoubleVec3 = DoubleVec3(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0) inline fun toDoubleVec(conv: (Boolean) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0) inline fun toDoubleVec2(conv: (Boolean) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(): DoubleVec3 = DoubleVec3(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0) inline fun toDoubleVec3(conv: (Boolean) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0, w) inline fun toDoubleVec4(w: Double = 0.0, conv: (Boolean) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0) inline fun toMutableDoubleVec(conv: (Boolean) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0) inline fun toMutableDoubleVec2(conv: (Boolean) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0) inline fun toMutableDoubleVec3(conv: (Boolean) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(if (x) 1.0 else 0.0, if (y) 1.0 else 0.0, if (z) 1.0 else 0.0, w) inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Boolean) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toIntVec(): IntVec3 = IntVec3(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0) inline fun toIntVec(conv: (Boolean) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec2(): IntVec2 = IntVec2(if (x) 1 else 0, if (y) 1 else 0) inline fun toIntVec2(conv: (Boolean) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(): IntVec3 = IntVec3(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0) inline fun toIntVec3(conv: (Boolean) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0, w) inline fun toIntVec4(w: Int = 0, conv: (Boolean) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0) inline fun toMutableIntVec(conv: (Boolean) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(if (x) 1 else 0, if (y) 1 else 0) inline fun toMutableIntVec2(conv: (Boolean) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0) inline fun toMutableIntVec3(conv: (Boolean) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(if (x) 1 else 0, if (y) 1 else 0, if (z) 1 else 0, w) inline fun toMutableIntVec4(w: Int = 0, conv: (Boolean) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toLongVec(): LongVec3 = LongVec3(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L) inline fun toLongVec(conv: (Boolean) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec2(): LongVec2 = LongVec2(if (x) 1L else 0L, if (y) 1L else 0L) inline fun toLongVec2(conv: (Boolean) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(): LongVec3 = LongVec3(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L) inline fun toLongVec3(conv: (Boolean) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L, w) inline fun toLongVec4(w: Long = 0L, conv: (Boolean) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L) inline fun toMutableLongVec(conv: (Boolean) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(if (x) 1L else 0L, if (y) 1L else 0L) inline fun toMutableLongVec2(conv: (Boolean) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L) inline fun toMutableLongVec3(conv: (Boolean) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(if (x) 1L else 0L, if (y) 1L else 0L, if (z) 1L else 0L, w) inline fun toMutableLongVec4(w: Long = 0L, conv: (Boolean) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toShortVec(): ShortVec3 = ShortVec3(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort()) inline fun toShortVec(conv: (Boolean) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec2(): ShortVec2 = ShortVec2(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort()) inline fun toShortVec2(conv: (Boolean) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(): ShortVec3 = ShortVec3(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort()) inline fun toShortVec3(conv: (Boolean) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort(), w) inline fun toShortVec4(w: Short = 0.toShort(), conv: (Boolean) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort()) inline fun toMutableShortVec(conv: (Boolean) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort()) inline fun toMutableShortVec2(conv: (Boolean) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort()) inline fun toMutableShortVec3(conv: (Boolean) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(if (x) 1.toShort() else 0.toShort(), if (y) 1.toShort() else 0.toShort(), if (z) 1.toShort() else 0.toShort(), w) inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Boolean) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toByteVec(): ByteVec3 = ByteVec3(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte()) inline fun toByteVec(conv: (Boolean) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec2(): ByteVec2 = ByteVec2(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte()) inline fun toByteVec2(conv: (Boolean) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(): ByteVec3 = ByteVec3(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte()) inline fun toByteVec3(conv: (Boolean) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte(), w) inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Boolean) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte()) inline fun toMutableByteVec(conv: (Boolean) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte()) inline fun toMutableByteVec2(conv: (Boolean) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte()) inline fun toMutableByteVec3(conv: (Boolean) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(if (x) 1.toByte() else 0.toByte(), if (y) 1.toByte() else 0.toByte(), if (z) 1.toByte() else 0.toByte(), w) inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Boolean) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Char inline fun toCharVec(conv: (Boolean) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) inline fun toCharVec2(conv: (Boolean) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) inline fun toCharVec3(conv: (Boolean) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) inline fun toCharVec4(w: Char, conv: (Boolean) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w) // Conversions to Char inline fun toMutableCharVec(conv: (Boolean) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) inline fun toMutableCharVec2(conv: (Boolean) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) inline fun toMutableCharVec3(conv: (Boolean) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) inline fun toMutableCharVec4(w: Char, conv: (Boolean) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toBoolVec(): BoolVec3 = BoolVec3(x, y, z) inline fun toBoolVec(conv: (Boolean) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec2(): BoolVec2 = BoolVec2(x, y) inline fun toBoolVec2(conv: (Boolean) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x, y, z) inline fun toBoolVec3(conv: (Boolean) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x, y, z, w) inline fun toBoolVec4(w: Boolean = false, conv: (Boolean) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x, y, z) inline fun toMutableBoolVec(conv: (Boolean) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x, y) inline fun toMutableBoolVec2(conv: (Boolean) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x, y, z) inline fun toMutableBoolVec3(conv: (Boolean) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x, y, z, w) inline fun toMutableBoolVec4(w: Boolean = false, conv: (Boolean) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec(conv: (Boolean) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Boolean) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec3(conv: (Boolean) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toStringVec4(w: String = "", conv: (Boolean) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec(conv: (Boolean) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Boolean) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec3(conv: (Boolean) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toMutableStringVec4(w: String = "", conv: (Boolean) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toTVec(conv: (Boolean) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec2(conv: (Boolean) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (Boolean) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(w: T2, conv: (Boolean) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Boolean) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec2(conv: (Boolean) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (Boolean) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(w: T2, conv: (Boolean) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: BoolVec2 get() = BoolVec2(x, x) val xy: BoolVec2 get() = BoolVec2(x, y) val xz: BoolVec2 get() = BoolVec2(x, z) val yx: BoolVec2 get() = BoolVec2(y, x) val yy: BoolVec2 get() = BoolVec2(y, y) val yz: BoolVec2 get() = BoolVec2(y, z) val zx: BoolVec2 get() = BoolVec2(z, x) val zy: BoolVec2 get() = BoolVec2(z, y) val zz: BoolVec2 get() = BoolVec2(z, z) val xxx: BoolVec3 get() = BoolVec3(x, x, x) val xxy: BoolVec3 get() = BoolVec3(x, x, y) val xxz: BoolVec3 get() = BoolVec3(x, x, z) val xyx: BoolVec3 get() = BoolVec3(x, y, x) val xyy: BoolVec3 get() = BoolVec3(x, y, y) val xyz: BoolVec3 get() = BoolVec3(x, y, z) val xzx: BoolVec3 get() = BoolVec3(x, z, x) val xzy: BoolVec3 get() = BoolVec3(x, z, y) val xzz: BoolVec3 get() = BoolVec3(x, z, z) val yxx: BoolVec3 get() = BoolVec3(y, x, x) val yxy: BoolVec3 get() = BoolVec3(y, x, y) val yxz: BoolVec3 get() = BoolVec3(y, x, z) val yyx: BoolVec3 get() = BoolVec3(y, y, x) val yyy: BoolVec3 get() = BoolVec3(y, y, y) val yyz: BoolVec3 get() = BoolVec3(y, y, z) val yzx: BoolVec3 get() = BoolVec3(y, z, x) val yzy: BoolVec3 get() = BoolVec3(y, z, y) val yzz: BoolVec3 get() = BoolVec3(y, z, z) val zxx: BoolVec3 get() = BoolVec3(z, x, x) val zxy: BoolVec3 get() = BoolVec3(z, x, y) val zxz: BoolVec3 get() = BoolVec3(z, x, z) val zyx: BoolVec3 get() = BoolVec3(z, y, x) val zyy: BoolVec3 get() = BoolVec3(z, y, y) val zyz: BoolVec3 get() = BoolVec3(z, y, z) val zzx: BoolVec3 get() = BoolVec3(z, z, x) val zzy: BoolVec3 get() = BoolVec3(z, z, y) val zzz: BoolVec3 get() = BoolVec3(z, z, z) val xxxx: BoolVec4 get() = BoolVec4(x, x, x, x) val xxxy: BoolVec4 get() = BoolVec4(x, x, x, y) val xxxz: BoolVec4 get() = BoolVec4(x, x, x, z) val xxyx: BoolVec4 get() = BoolVec4(x, x, y, x) val xxyy: BoolVec4 get() = BoolVec4(x, x, y, y) val xxyz: BoolVec4 get() = BoolVec4(x, x, y, z) val xxzx: BoolVec4 get() = BoolVec4(x, x, z, x) val xxzy: BoolVec4 get() = BoolVec4(x, x, z, y) val xxzz: BoolVec4 get() = BoolVec4(x, x, z, z) val xyxx: BoolVec4 get() = BoolVec4(x, y, x, x) val xyxy: BoolVec4 get() = BoolVec4(x, y, x, y) val xyxz: BoolVec4 get() = BoolVec4(x, y, x, z) val xyyx: BoolVec4 get() = BoolVec4(x, y, y, x) val xyyy: BoolVec4 get() = BoolVec4(x, y, y, y) val xyyz: BoolVec4 get() = BoolVec4(x, y, y, z) val xyzx: BoolVec4 get() = BoolVec4(x, y, z, x) val xyzy: BoolVec4 get() = BoolVec4(x, y, z, y) val xyzz: BoolVec4 get() = BoolVec4(x, y, z, z) val xzxx: BoolVec4 get() = BoolVec4(x, z, x, x) val xzxy: BoolVec4 get() = BoolVec4(x, z, x, y) val xzxz: BoolVec4 get() = BoolVec4(x, z, x, z) val xzyx: BoolVec4 get() = BoolVec4(x, z, y, x) val xzyy: BoolVec4 get() = BoolVec4(x, z, y, y) val xzyz: BoolVec4 get() = BoolVec4(x, z, y, z) val xzzx: BoolVec4 get() = BoolVec4(x, z, z, x) val xzzy: BoolVec4 get() = BoolVec4(x, z, z, y) val xzzz: BoolVec4 get() = BoolVec4(x, z, z, z) val yxxx: BoolVec4 get() = BoolVec4(y, x, x, x) val yxxy: BoolVec4 get() = BoolVec4(y, x, x, y) val yxxz: BoolVec4 get() = BoolVec4(y, x, x, z) val yxyx: BoolVec4 get() = BoolVec4(y, x, y, x) val yxyy: BoolVec4 get() = BoolVec4(y, x, y, y) val yxyz: BoolVec4 get() = BoolVec4(y, x, y, z) val yxzx: BoolVec4 get() = BoolVec4(y, x, z, x) val yxzy: BoolVec4 get() = BoolVec4(y, x, z, y) val yxzz: BoolVec4 get() = BoolVec4(y, x, z, z) val yyxx: BoolVec4 get() = BoolVec4(y, y, x, x) val yyxy: BoolVec4 get() = BoolVec4(y, y, x, y) val yyxz: BoolVec4 get() = BoolVec4(y, y, x, z) val yyyx: BoolVec4 get() = BoolVec4(y, y, y, x) val yyyy: BoolVec4 get() = BoolVec4(y, y, y, y) val yyyz: BoolVec4 get() = BoolVec4(y, y, y, z) val yyzx: BoolVec4 get() = BoolVec4(y, y, z, x) val yyzy: BoolVec4 get() = BoolVec4(y, y, z, y) val yyzz: BoolVec4 get() = BoolVec4(y, y, z, z) val yzxx: BoolVec4 get() = BoolVec4(y, z, x, x) val yzxy: BoolVec4 get() = BoolVec4(y, z, x, y) val yzxz: BoolVec4 get() = BoolVec4(y, z, x, z) val yzyx: BoolVec4 get() = BoolVec4(y, z, y, x) val yzyy: BoolVec4 get() = BoolVec4(y, z, y, y) val yzyz: BoolVec4 get() = BoolVec4(y, z, y, z) val yzzx: BoolVec4 get() = BoolVec4(y, z, z, x) val yzzy: BoolVec4 get() = BoolVec4(y, z, z, y) val yzzz: BoolVec4 get() = BoolVec4(y, z, z, z) val zxxx: BoolVec4 get() = BoolVec4(z, x, x, x) val zxxy: BoolVec4 get() = BoolVec4(z, x, x, y) val zxxz: BoolVec4 get() = BoolVec4(z, x, x, z) val zxyx: BoolVec4 get() = BoolVec4(z, x, y, x) val zxyy: BoolVec4 get() = BoolVec4(z, x, y, y) val zxyz: BoolVec4 get() = BoolVec4(z, x, y, z) val zxzx: BoolVec4 get() = BoolVec4(z, x, z, x) val zxzy: BoolVec4 get() = BoolVec4(z, x, z, y) val zxzz: BoolVec4 get() = BoolVec4(z, x, z, z) val zyxx: BoolVec4 get() = BoolVec4(z, y, x, x) val zyxy: BoolVec4 get() = BoolVec4(z, y, x, y) val zyxz: BoolVec4 get() = BoolVec4(z, y, x, z) val zyyx: BoolVec4 get() = BoolVec4(z, y, y, x) val zyyy: BoolVec4 get() = BoolVec4(z, y, y, y) val zyyz: BoolVec4 get() = BoolVec4(z, y, y, z) val zyzx: BoolVec4 get() = BoolVec4(z, y, z, x) val zyzy: BoolVec4 get() = BoolVec4(z, y, z, y) val zyzz: BoolVec4 get() = BoolVec4(z, y, z, z) val zzxx: BoolVec4 get() = BoolVec4(z, z, x, x) val zzxy: BoolVec4 get() = BoolVec4(z, z, x, y) val zzxz: BoolVec4 get() = BoolVec4(z, z, x, z) val zzyx: BoolVec4 get() = BoolVec4(z, z, y, x) val zzyy: BoolVec4 get() = BoolVec4(z, z, y, y) val zzyz: BoolVec4 get() = BoolVec4(z, z, y, z) val zzzx: BoolVec4 get() = BoolVec4(z, z, z, x) val zzzy: BoolVec4 get() = BoolVec4(z, z, z, y) val zzzz: BoolVec4 get() = BoolVec4(z, z, z, z) } val swizzle: Swizzle get() = Swizzle() } fun vecOf(x: Boolean, y: Boolean, z: Boolean): BoolVec3 = BoolVec3(x, y, z) fun any(v: BoolVec3): Boolean = v.run { x || y || z } fun all(v: BoolVec3): Boolean = v.run { x && y && z }
mit
828d696f0f0aabb5dd971d1258c81592
71.061404
201
0.628606
3.131114
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuApi.kt
2
9948
package eu.kanade.tachiyomi.data.track.kitsu import androidx.core.net.toUri import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.await import eu.kanade.tachiyomi.network.jsonMime import eu.kanade.tachiyomi.network.parseAs import eu.kanade.tachiyomi.util.lang.withIOContext import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonObject import okhttp3.FormBody import okhttp3.Headers.Companion.headersOf import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import java.net.URLEncoder import java.nio.charset.StandardCharsets class KitsuApi(private val client: OkHttpClient, interceptor: KitsuInterceptor) { private val authClient = client.newBuilder().addInterceptor(interceptor).build() suspend fun addLibManga(track: Track, userId: String): Track { return withIOContext { val data = buildJsonObject { putJsonObject("data") { put("type", "libraryEntries") putJsonObject("attributes") { put("status", track.toKitsuStatus()) put("progress", track.last_chapter_read.toInt()) } putJsonObject("relationships") { putJsonObject("user") { putJsonObject("data") { put("id", userId) put("type", "users") } } putJsonObject("media") { putJsonObject("data") { put("id", track.media_id) put("type", "manga") } } } } } authClient.newCall( POST( "${baseUrl}library-entries", headers = headersOf( "Content-Type", "application/vnd.api+json" ), body = data.toString().toRequestBody("application/vnd.api+json".toMediaType()) ) ) .await() .parseAs<JsonObject>() .let { track.media_id = it["data"]!!.jsonObject["id"]!!.jsonPrimitive.int track } } } suspend fun updateLibManga(track: Track): Track { return withIOContext { val data = buildJsonObject { putJsonObject("data") { put("type", "libraryEntries") put("id", track.media_id) putJsonObject("attributes") { put("status", track.toKitsuStatus()) put("progress", track.last_chapter_read.toInt()) put("ratingTwenty", track.toKitsuScore()) put("startedAt", KitsuDateHelper.convert(track.started_reading_date)) put("finishedAt", KitsuDateHelper.convert(track.finished_reading_date)) } } } authClient.newCall( Request.Builder() .url("${baseUrl}library-entries/${track.media_id}") .headers( headersOf( "Content-Type", "application/vnd.api+json" ) ) .patch(data.toString().toRequestBody("application/vnd.api+json".toMediaType())) .build() ) .await() .parseAs<JsonObject>() .let { track } } } suspend fun search(query: String): List<TrackSearch> { return withIOContext { authClient.newCall(GET(algoliaKeyUrl)) .await() .parseAs<JsonObject>() .let { val key = it["media"]!!.jsonObject["key"]!!.jsonPrimitive.content algoliaSearch(key, query) } } } private suspend fun algoliaSearch(key: String, query: String): List<TrackSearch> { return withIOContext { val jsonObject = buildJsonObject { put("params", "query=${URLEncoder.encode(query, StandardCharsets.UTF_8.name())}$algoliaFilter") } client.newCall( POST( algoliaUrl, headers = headersOf( "X-Algolia-Application-Id", algoliaAppId, "X-Algolia-API-Key", key, ), body = jsonObject.toString().toRequestBody(jsonMime) ) ) .await() .parseAs<JsonObject>() .let { it["hits"]!!.jsonArray .map { KitsuSearchManga(it.jsonObject) } .filter { it.subType != "novel" } .map { it.toTrack() } } } } suspend fun findLibManga(track: Track, userId: String): Track? { return withIOContext { val url = "${baseUrl}library-entries".toUri().buildUpon() .encodedQuery("filter[manga_id]=${track.media_id}&filter[user_id]=$userId") .appendQueryParameter("include", "manga") .build() authClient.newCall(GET(url.toString())) .await() .parseAs<JsonObject>() .let { val data = it["data"]!!.jsonArray if (data.size > 0) { val manga = it["included"]!!.jsonArray[0].jsonObject KitsuLibManga(data[0].jsonObject, manga).toTrack() } else { null } } } } suspend fun getLibManga(track: Track): Track { return withIOContext { val url = "${baseUrl}library-entries".toUri().buildUpon() .encodedQuery("filter[id]=${track.media_id}") .appendQueryParameter("include", "manga") .build() authClient.newCall(GET(url.toString())) .await() .parseAs<JsonObject>() .let { val data = it["data"]!!.jsonArray if (data.size > 0) { val manga = it["included"]!!.jsonArray[0].jsonObject KitsuLibManga(data[0].jsonObject, manga).toTrack() } else { throw Exception("Could not find manga") } } } } suspend fun login(username: String, password: String): OAuth { return withIOContext { val formBody: RequestBody = FormBody.Builder() .add("username", username) .add("password", password) .add("grant_type", "password") .add("client_id", clientId) .add("client_secret", clientSecret) .build() client.newCall(POST(loginUrl, body = formBody)) .await() .parseAs() } } suspend fun getCurrentUser(): String { return withIOContext { val url = "${baseUrl}users".toUri().buildUpon() .encodedQuery("filter[self]=true") .build() authClient.newCall(GET(url.toString())) .await() .parseAs<JsonObject>() .let { it["data"]!!.jsonArray[0].jsonObject["id"]!!.jsonPrimitive.content } } } companion object { private const val clientId = "dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd" private const val clientSecret = "54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151" private const val baseUrl = "https://kitsu.io/api/edge/" private const val loginUrl = "https://kitsu.io/api/oauth/token" private const val baseMangaUrl = "https://kitsu.io/manga/" private const val algoliaKeyUrl = "https://kitsu.io/api/edge/algolia-keys/media/" private const val algoliaUrl = "https://AWQO5J657S-dsn.algolia.net/1/indexes/production_media/query/" private const val algoliaAppId = "AWQO5J657S" private const val algoliaFilter = "&facetFilters=%5B%22kind%3Amanga%22%5D&attributesToRetrieve=%5B%22synopsis%22%2C%22canonicalTitle%22%2C%22chapterCount%22%2C%22posterImage%22%2C%22startDate%22%2C%22subtype%22%2C%22endDate%22%2C%20%22id%22%5D" fun mangaUrl(remoteId: Int): String { return baseMangaUrl + remoteId } fun refreshTokenRequest(token: String) = POST( loginUrl, body = FormBody.Builder() .add("grant_type", "refresh_token") .add("refresh_token", token) .add("client_id", clientId) .add("client_secret", clientSecret) .build() ) } }
apache-2.0
897b67cc09074a96a9120acb13e9f716
37.55814
222
0.504926
4.890855
false
false
false
false
mdanielwork/intellij-community
platform/lang-impl/src/com/intellij/codeEditor/printing/HtmlStyleManager.kt
7
3606
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeEditor.printing import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.highlighter.HighlighterIterator import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.psi.PsiElement import com.intellij.ui.ColorUtil import com.intellij.ui.Gray import com.intellij.util.BitUtil import gnu.trove.THashMap import java.awt.Color import java.awt.Font import java.io.IOException import java.io.Writer class HtmlStyleManager(val isInline: Boolean) { private val styleMap = THashMap<TextAttributes, String>() private val separatorStyleMap = THashMap<Color, String>() private val buffer = StringBuilder() private val scheme = EditorColorsManager.getInstance().globalScheme fun ensureStyles(hIterator: HighlighterIterator, methodSeparators: List<LineMarkerInfo<PsiElement>>) { while (!hIterator.atEnd()) { val textAttributes = hIterator.textAttributes if (!styleMap.containsKey(textAttributes)) { val styleName = "s" + styleMap.size styleMap.put(textAttributes, styleName) buffer.append(".$styleName { ") writeTextAttributes(buffer, textAttributes) buffer.append("}\n") } hIterator.advance() } for (separator in methodSeparators) { val color = separator.separatorColor if (color != null && !separatorStyleMap.containsKey(color)) { val styleName = "ls${separatorStyleMap.size}" separatorStyleMap.put(color, styleName) val htmlColor = colorToHtml(color) buffer.append(".$styleName { height: 1px; border-width: 0; color: $htmlColor; background-color:$htmlColor}\n") } } } private fun writeTextAttributes(buffer: Appendable, attributes: TextAttributes) { val foreColor = attributes.foregroundColor ?: scheme.defaultForeground buffer.append("color: ${colorToHtml(foreColor)};") if (BitUtil.isSet(attributes.fontType, Font.BOLD)) { buffer.append(" font-weight: bold;") } if (BitUtil.isSet(attributes.fontType, Font.ITALIC)) { buffer.append(" font-style: italic;") } } @Throws(IOException::class) fun writeStyleTag(writer: Writer, isUseLineNumberStyle: Boolean) { writer.write("<style type=\"text/css\">\n") if (isUseLineNumberStyle) { val scheme = EditorColorsManager.getInstance().globalScheme val lineNumbers = scheme.getColor(EditorColors.LINE_NUMBERS_COLOR) buffer.append(String.format(".ln { color: #%s; font-weight: normal; font-style: normal; }\n", ColorUtil.toHex(lineNumbers ?: Gray.x00))) } writer.append(buffer) writer.write("</style>\n") } fun isDefaultAttributes(attributes: TextAttributes): Boolean { return (attributes.foregroundColor ?: scheme.defaultForeground).equals(Color.BLACK) && attributes.fontType == 0 } fun writeTextStyle(writer: Writer, attributes: TextAttributes) { writer.write("<span ") if (isInline) { writer.write("style=\"") writeTextAttributes(writer, attributes) writer.write("\">") } else { writer.write("class=\"") writer.write(styleMap.get(attributes)!!) writer.write("\">") } } fun getSeparatorClassName(color: Color): String { return separatorStyleMap.get(color)!! } } internal fun colorToHtml(color: Color) = "#${ColorUtil.toHex(color)}"
apache-2.0
003b9c02c5e242d1cf18419296a6800c
35.806122
142
0.714088
4.207701
false
false
false
false
cdietze/klay
klay-scene/src/main/kotlin/klay/scene/CanvasLayer.kt
1
3684
package klay.scene import euklid.f.IDimension import klay.core.Canvas import klay.core.Graphics import klay.core.Texture import klay.core.Tile import react.RFuture /** * Simplifies the process of displaying a [Canvas] which is updated after its initial * creation. When modifying the canvas, one must call [.begin] to obtain a reference to the * canvas, do the desired rendering, then call [.end] to upload the modified image data to * the GPU for display by this layer. */ class CanvasLayer : klay.scene.ImageLayer { private val gfx: Graphics private var canvas: Canvas? = null /** * Creates a canvas layer with a backing canvas of `size` (in display units). This layer * will display nothing until a [.begin]/[.end] pair is used to render something to * its backing canvas. */ constructor(gfx: Graphics, size: IDimension) : this(gfx, size.width, size.height) /** * Creates a canvas layer with a backing canvas of size `width x height` (in display * units). This layer will display nothing until a [.begin]/[.end] pair is used to * render something to its backing canvas. */ constructor(gfx: Graphics, width: Float, height: Float) { this.gfx = gfx resize(width, height) } /** * Creates a canvas layer with the supplied backing canvas. The canvas will immediately be * uploaded to the GPU for display. */ constructor(gfx: Graphics, canvas: Canvas) { this.gfx = gfx this.canvas = canvas super.setTile(canvas.image.createTexture(Texture.Config.DEFAULT)) } /** * Resizes the canvas that is displayed by this layer. * * Note: this throws away the old canvas and creates a new blank canvas with the desired size. * Thus this should immediately be followed by a [.begin]/[.end] pair which updates * the contents of the new canvas. Until then, it will display the old image data. */ fun resize(width: Float, height: Float) { if (canvas != null) canvas!!.close() canvas = gfx.createCanvas(width, height) } /** Starts a drawing operation on this layer's backing canvas. Thus must be followed by a call to * [.end] when the drawing is complete. */ fun begin(): Canvas { return canvas!! } /** Informs this layer that a drawing operation has just completed. The backing canvas image data * is uploaded to the GPU. */ fun end() { val tex = tile() as Texture? val image = canvas!!.image // if our texture is already the right size, just update it if (tex != null && tex.pixelWidth == image.pixelWidth && tex.pixelHeight == image.pixelHeight) tex.update(image) else super.setTile(canvas!!.image.createTexture(Texture.Config.DEFAULT))// otherwise we need to create a new texture (setTexture will unreference the old texture which // will cause it to be destroyed) } override fun setTile(tile: Tile?): ImageLayer { if (tile == null || tile is Texture) return super.setTile(tile) else throw UnsupportedOperationException() } override fun setTile(tile: RFuture<out Tile>): ImageLayer { throw UnsupportedOperationException() } override fun width(): Float { return if (forceWidth < 0) canvas!!.width else forceWidth } override fun height(): Float { return if (forceHeight < 0) canvas!!.height else forceHeight } override fun close() { super.close() if (canvas != null) { canvas!!.close() canvas = null } } }
apache-2.0
e844433f53b99eda7d9ef001027ab2dd
33.429907
174
0.64278
4.396181
false
false
false
false
dahlstrom-g/intellij-community
java/java-tests/testSrc/com/intellij/compiler/backwardRefs/CompilerReferencesMultiModuleTest.kt
9
4463
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.compiler.backwardRefs import com.intellij.compiler.CompilerReferenceService import com.intellij.java.compiler.CompilerReferencesTestBase import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.util.registry.Registry import com.intellij.pom.java.LanguageLevel import com.intellij.psi.PsiClassOwner import com.intellij.psi.PsiManager import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.testFramework.IdeaTestUtil import com.intellij.testFramework.PsiTestUtil import org.intellij.lang.annotations.Language class CompilerReferencesMultiModuleTest : CompilerReferencesTestBase() { private var moduleA: Module? = null private var moduleB: Module? = null override fun setUp() { super.setUp() addTwoModules() installCompiler() } override fun tearDown() { moduleA = null moduleB = null super.tearDown() } fun testNoChanges() { addClass("BaseClass.java", "public interface BaseClass{}") addClass("A/ClassA.java", "public class ClassA implements BaseClass{}") addClass("B/ClassB.java", "public class ClassB implements BaseClass{}") rebuildProject() assertEmpty(dirtyModules()) } @Throws(Exception::class) fun testDirtyScopeCachedResults() { val file1 = addClass("A/Foo.java", """public class Foo { static class Bar extends Foo {} }""") addClass("B/Unrelated.java", "public class Unrelated {}") rebuildProject() val foo = (file1 as PsiClassOwner).classes[0] assertOneElement(ClassInheritorsSearch.search(foo, foo.useScope, false).findAll()) val registryValue = Registry.get("compiler.ref.index") try { registryValue.setValue(false) assertOneElement(ClassInheritorsSearch.search(foo, foo.useScope, false).findAll()) } finally { registryValue.setValue(true) } } fun testLeafModuleTyping() { addClass("BaseClass.java", "public interface BaseClass{}") val classA = addClass("A/ClassA.java", "public class ClassA implements BaseClass{}") addClass("B/ClassB.java", "public class ClassB implements BaseClass{}") rebuildProject() myFixture.openFileInEditor(classA.virtualFile) myFixture.type("/*typing in module A*/") assertEquals("A", assertOneElement(dirtyModules())) FileDocumentManager.getInstance().saveAllDocuments() assertEquals("A", assertOneElement(dirtyModules())) } private fun addClass(relativePath: String, @Language("JAVA") text: String) = myFixture.addFileToProject(relativePath, text) fun testModulePathRename() { addClass("A/Foo.java", "class Foo { void m() {System.out.println(123);} }") rebuildProject() val moduleARoot = PsiManager.getInstance(myFixture.project).findDirectory(myFixture.findFileInTempDir("A"))!! myFixture.renameElement(moduleARoot, "XXX") assertTrue(dirtyModules().contains("A")) addClass("XXX/Bar.java", "class Bar { void m() {System.out.println(123);} }") rebuildProject() assertEmpty(dirtyModules()) val javaLangSystem = myFixture.javaFacade.findClass("java.lang.System")!! val referentFiles = (CompilerReferenceService.getInstance(myFixture.project) as CompilerReferenceServiceImpl).getReferentFilesForTests(javaLangSystem)!! assertEquals(setOf("Foo.java", "Bar.java"), referentFiles.map { it.name }.toSet()) } private fun addTwoModules() { moduleA = PsiTestUtil.addModule(project, JavaModuleType.getModuleType(), "A", myFixture.tempDirFixture.findOrCreateDir("A")) moduleB = PsiTestUtil.addModule(project, JavaModuleType.getModuleType(), "B", myFixture.tempDirFixture.findOrCreateDir("B")) IdeaTestUtil.setModuleLanguageLevel(moduleA!!, LanguageLevel.JDK_11) IdeaTestUtil.setModuleLanguageLevel(moduleB!!, LanguageLevel.JDK_11) ModuleRootModificationUtil.addDependency(moduleA!!, module) ModuleRootModificationUtil.addDependency(moduleB!!, module) } private fun dirtyModules(): Collection<String> = (CompilerReferenceService.getInstance(project) as CompilerReferenceServiceImpl).dirtyScopeHolder.allDirtyModules.map { module -> module.name } }
apache-2.0
3f1f87534300d5af6bfb577f29e6aa59
42.339806
156
0.741654
4.653806
false
true
false
false
dahlstrom-g/intellij-community
plugins/ide-features-trainer/src/training/actions/NextLessonAction.kt
4
1268
// 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.actions import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import training.learn.CourseManager import training.statistic.LessonStartingWay import training.statistic.StatisticBase import training.util.getLearnToolWindowForProject import training.util.getNextLessonForCurrent import training.util.lessonOpenedInProject private class NextLessonAction : AnAction(AllIcons.Actions.Forward) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return if (getLearnToolWindowForProject(project) == null) return val nextLesson = getNextLessonForCurrent() ?: return StatisticBase.logLessonStopped(StatisticBase.LessonStopReason.OPEN_NEXT_OR_PREV_LESSON) CourseManager.instance.openLesson(project, nextLesson, LessonStartingWay.NEXT_BUTTON) } override fun update(e: AnActionEvent) { val project = e.project val lesson = lessonOpenedInProject(project) e.presentation.isEnabled = lesson != null && CourseManager.instance.lessonsForModules.lastOrNull() != lesson } }
apache-2.0
dc1707a69628985711e9e2f6dcbbd98f
44.285714
140
0.806782
4.561151
false
false
false
false
google-developer-training/android-basics-kotlin-forage-app
app/src/main/java/com/example/forage/ui/AddForageableFragment.kt
1
4893
/* * Copyright (C) 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 com.example.forage.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.example.forage.R import com.example.forage.databinding.FragmentAddForageableBinding import com.example.forage.model.Forageable import com.example.forage.ui.viewmodel.ForageableViewModel /** * A fragment to enter data for a new [Forageable] or edit data for an existing [Forageable]. * [Forageable]s can be saved or deleted from this fragment. */ class AddForageableFragment : Fragment() { private val navigationArgs: AddForageableFragmentArgs by navArgs() private var _binding: FragmentAddForageableBinding? = null private lateinit var forageable: Forageable // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! // TODO: Refactor the creation of the view model to take an instance of // ForageableViewModelFactory. The factory should take an instance of the Database retrieved // from BaseApplication private val viewModel: ForageableViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentAddForageableBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val id = navigationArgs.id if (id > 0) { // TODO: Observe a Forageable that is retrieved by id, set the forageable variable, // and call the bindForageable method binding.deleteBtn.visibility = View.VISIBLE binding.deleteBtn.setOnClickListener { deleteForageable(forageable) } } else { binding.saveBtn.setOnClickListener { addForageable() } } } private fun deleteForageable(forageable: Forageable) { viewModel.deleteForageable(forageable) findNavController().navigate( R.id.action_addForageableFragment_to_forageableListFragment ) } private fun addForageable() { if (isValidEntry()) { viewModel.addForageable( binding.nameInput.text.toString(), binding.locationAddressInput.text.toString(), binding.inSeasonCheckbox.isChecked, binding.notesInput.text.toString() ) findNavController().navigate( R.id.action_addForageableFragment_to_forageableListFragment ) } } private fun updateForageable() { if (isValidEntry()) { viewModel.updateForageable( id = navigationArgs.id, name = binding.nameInput.text.toString(), address = binding.locationAddressInput.text.toString(), inSeason = binding.inSeasonCheckbox.isChecked, notes = binding.notesInput.text.toString() ) findNavController().navigate( R.id.action_addForageableFragment_to_forageableListFragment ) } } private fun bindForageable(forageable: Forageable) { binding.apply{ nameInput.setText(forageable.name, TextView.BufferType.SPANNABLE) locationAddressInput.setText(forageable.address, TextView.BufferType.SPANNABLE) inSeasonCheckbox.isChecked = forageable.inSeason notesInput.setText(forageable.notes, TextView.BufferType.SPANNABLE) saveBtn.setOnClickListener { updateForageable() } } } private fun isValidEntry() = viewModel.isValidEntry( binding.nameInput.text.toString(), binding.locationAddressInput.text.toString() ) override fun onDestroyView() { super.onDestroyView() _binding = null } }
apache-2.0
d5bf9f37d4538159e7064b88a79dc7b5
33.702128
97
0.674433
4.581461
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/to/bs3/Col.kt
2
2812
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.to.bs3 import org.w3c.dom.Node import org.w3c.dom.asList class Col(node: Node) { val rowList = mutableListOf<Row>() var domainObject: DomainObject? = null var actionList = mutableListOf<Action>() val tabGroupList = mutableListOf<TabGroup>() var fieldSetList = mutableListOf<FieldSet>() var collectionList = mutableListOf<Collection>() var span: Int = 0 init { val dyNode = node.asDynamic() span = dyNode.getAttribute("span") val nl = node.childNodes.asList() val rl = nl.filter { it.nodeName.equals("bs3:row") } for (n: Node in rl) { val row = Row(n) rowList.add(row) } val doNodes = nl.filter { it.nodeName.equals("cpt:domainObject") } if (!doNodes.isEmpty()) { domainObject = DomainObject(doNodes.first()) } val actNodes = nl.filter { it.nodeName.equals("cpt:action") } for (n: Node in actNodes) { val act = Action(n) actionList.add(act) } val tgNodes = nl.filter { it.nodeName.equals("bs3:tabGroup") } for (n: Node in tgNodes) { val tg = TabGroup(n) tabGroupList.add(tg) } val fsNodes = nl.filter { it.nodeName.equals("cpt:fieldSet") } for (n: Node in fsNodes) { val fs = FieldSet(n) fieldSetList.add(fs) } val collNodes = nl.filter { it.nodeName.equals("cpt:collection") } for (n: Node in collNodes) { val c = Collection(n) collectionList.add(c) } } fun getPropertyList(): List<Property> { val list = mutableListOf<Property>() fieldSetList.forEach { fs -> list.addAll(fs.propertyList) } tabGroupList.forEach { tg -> list.addAll(tg.getPropertyList()) } console.log("[CB.getPropertyList]") return list } }
apache-2.0
faff2c8a23eb36d3c66ca335f62c2fc3
31.321839
74
0.61522
3.949438
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/ui/popup/list/PopupInlineActionsSupportImpl.kt
1
4207
// 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.ui.popup.list import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.openapi.actionSystem.AnAction import com.intellij.ui.ExperimentalUI import com.intellij.ui.popup.ActionPopupStep import com.intellij.ui.popup.PopupFactoryImpl.ActionItem import com.intellij.ui.popup.PopupFactoryImpl.InlineActionItem import com.intellij.ui.popup.list.ListPopupImpl.ListWithInlineButtons import java.awt.Point import java.awt.event.InputEvent import javax.swing.JComponent import javax.swing.JList class PopupInlineActionsSupportImpl(private val myListPopup: ListPopupImpl) : PopupInlineActionsSupport { private val myStep = myListPopup.listStep as ActionPopupStep override fun hasExtraButtons(element: Any?): Boolean = calcExtraButtonsCount(element) > 0 override fun calcExtraButtonsCount(element: Any?): Int { if (!ExperimentalUI.isNewUI() || element !is ActionItem) return 0 var res = 0 res += myStep.getInlineActions(element).size if (hasMoreButton(element)) res++ return res } override fun calcButtonIndex(element: Any?, point: Point): Int? { if (element == null) return null val buttonsCount: Int = calcExtraButtonsCount(element) if (buttonsCount <= 0) return null return calcButtonIndex(myListPopup.list, buttonsCount, point) } override fun getInlineAction(element: Any?, index: Int, event: InputEvent?) : InlineActionDescriptor = getExtraButtonsActions(element, event)[index] private fun getExtraButtonsActions(element: Any?, event: InputEvent?): List<InlineActionDescriptor> { if (!ExperimentalUI.isNewUI() || element !is ActionItem) return emptyList() val res: MutableList<InlineActionDescriptor> = mutableListOf() res.addAll(myStep.getInlineActions(element).map { item: InlineActionItem -> InlineActionDescriptor(createInlineActionRunnable(item.action, event), true) }) if (hasMoreButton(element)) res.add(InlineActionDescriptor(createNextStepRunnable(element), false)) return res } override fun getExtraButtons(list: JList<*>, value: Any?, isSelected: Boolean): List<JComponent> { if (value !is ActionItem) return emptyList() val inlineActions = myStep.getInlineActions(value) val res: MutableList<JComponent> = java.util.ArrayList() val activeIndex = getActiveButtonIndex(list) for (i in 0 until inlineActions.size) res.add(createActionButton(inlineActions[i], i == activeIndex, isSelected)) if (hasMoreButton(value)) res.add(createSubmenuButton(value, res.size == activeIndex)) return res } override fun getActiveButtonIndex(list: JList<*>): Int? = (list as? ListWithInlineButtons)?.selectedButtonIndex private fun createSubmenuButton(value: ActionItem, active: Boolean): JComponent { val icon = if (myStep.isFinal(value)) AllIcons.Actions.More else AllIcons.Icons.Ide.MenuArrow return createExtraButton(icon, active) } private fun createActionButton(action: InlineActionItem, active: Boolean, isSelected: Boolean): JComponent = createExtraButton(action.getIcon(isSelected), active) override fun getActiveExtraButtonToolTipText(list: JList<*>, value: Any?): String? { if (value !is ActionItem) return null val inlineActions = myStep.getInlineActions(value) val activeButton = getActiveButtonIndex(list) ?: return null return if (activeButton == inlineActions.size) IdeBundle.message("inline.actions.more.actions.text") else inlineActions.getOrNull(activeButton)?.text } private fun createNextStepRunnable(element: ActionItem) = Runnable { myListPopup.showNextStepPopup(myStep.onChosen(element, false), element) } private fun createInlineActionRunnable(action: AnAction, inputEvent: InputEvent?) = Runnable { myStep.performAction(action, inputEvent) } private fun hasMoreButton(element: ActionItem) = myStep.hasSubstep(element) && !myListPopup.isShowSubmenuOnHover && myStep.isFinal(element) }
apache-2.0
0a5012b48f4e43037b284aad1bca1e65
43.294737
144
0.743523
4.451852
false
false
false
false
kibotu/AndroidBase
app/src/main/kotlin/net/kibotu/base/MainActivity.kt
1
10711
package net.kibotu.base import android.Manifest.permission.ACCESS_COARSE_LOCATION import android.Manifest.permission.ACCESS_FINE_LOCATION import android.app.Activity import android.content.Context import android.content.Intent import android.content.IntentSender import android.content.res.Configuration import android.location.LocationManager import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.text.TextUtils.isEmpty import android.view.MotionEvent import android.view.WindowManager import com.common.android.utils.ContextHelper.getActivity import com.common.android.utils.extensions.DeviceExtensions.hideKeyboard import com.common.android.utils.extensions.FragmentExtensions import com.common.android.utils.extensions.FragmentExtensions.currentFragment import com.common.android.utils.extensions.FragmentExtensions.replace import com.common.android.utils.extensions.JUnitExtensions.isJUnitTest import com.common.android.utils.extensions.KeyGuardExtensions.unlockScreen import com.common.android.utils.extensions.SnackbarExtensions import com.common.android.utils.interfaces.Backpress import com.common.android.utils.interfaces.DispatchTouchEvent import com.common.android.utils.logging.Logger import com.common.android.utils.misc.Bundler import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.location.LocationSettingsRequest import com.google.android.gms.location.LocationSettingsStatusCodes import com.robohorse.gpversionchecker.GPVersionChecker import com.robohorse.gpversionchecker.base.CheckingStrategy import io.nlopez.smartlocation.SmartLocation import io.nlopez.smartlocation.location.providers.LocationGooglePlayServicesProvider.REQUEST_CHECK_SETTINGS import net.kibotu.android.deviceinfo.library.services.SystemService.getLocationManager import net.kibotu.android.deviceinfo.library.services.SystemService.getWifiManager import net.kibotu.base.ui.debugMenu.DebugMenu import net.kibotu.base.ui.splash.SplashScreenFragment import net.kibotu.timebomb.TimeBomb import permissions.dispatcher.* import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper @RuntimePermissions class MainActivity : AppCompatActivity() { var debugMenu: DebugMenu? = null private var newIntent: Intent? = null private var locationControl: SmartLocation.LocationControl? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (isJUnitTest()) return newIntent = intent Logger.v(TAG, "[onCreate] savedInstanceState=$savedInstanceState intent=$newIntent") // Keep the screen always on if (resources.getBoolean(R.bool.flag_keep_screen_on)) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) // unlock screen if (resources.getBoolean(R.bool.unlock_screen_on_start)) unlockScreen(this) setContentView(R.layout.activity_main) debugMenu = DebugMenu() if (!consumeIntent()) replace(SplashScreenFragment()) GPVersionChecker.Builder(getActivity()) .setCheckingStrategy(CheckingStrategy.ALWAYS) .showDialog(true) .forceUpdate(resources.getBoolean(R.bool.force_update)) // .setCustomPackageName("net.kibotu.base") .setVersionInfoListener { version -> Logger.v(TAG, "version=" + version) } .create() } private fun consumeIntent(): Boolean { if (newIntent == null) return false val dataString = newIntent!!.dataString if (isEmpty(dataString)) return false Logger.v(TAG, "[consumeIntent] " + dataString) supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, Bundler() .putString(SplashScreenFragment::class.java.canonicalName, dataString) .into(SplashScreenFragment())) .commitNowAllowingStateLoss() newIntent = null return true } fun startLocationTracking() { if (locationControl != null) return locationControl = SmartLocation.with(this).location() locationControl!!.start { location -> Logger.v(TAG, "[onLocationUpdated] location=" + location) locationControl!!.stop() } } override fun onStart() { super.onStart() } override fun onResume() { super.onResume() TimeBomb.bombAfterDays(this, BuildConfig.BUILD_DATE, resources.getInteger(R.integer.time_bomb_delay)) } override fun onStop() { super.onPause() } override fun onBackPressed() { // hide keyboard hideKeyboard() // close menu if (debugMenu!!.isDrawerOpen) { debugMenu!!.closeDrawer() return } // let fragments handle back press val fragment = currentFragment() if (fragment is Backpress && fragment.onBackPressed()) return // pop back stack if (supportFragmentManager.backStackEntryCount > 0) { supportFragmentManager.popBackStack() FragmentExtensions.printBackStack() return } // quit app finish() } override fun attachBaseContext(newBase: Context) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)) } // region hide keyboard if raycast for specific view fails override fun dispatchTouchEvent(ev: MotionEvent): Boolean { val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container) if (fragment is DispatchTouchEvent) return fragment.dispatchTouchEvent(ev) || super.dispatchTouchEvent(ev) return super.dispatchTouchEvent(ev) } // endregion // region location permission @NeedsPermission(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION) fun scanWifi() { Logger.v(TAG, "[scanWifi]") startLocationTracking() displayLocationSettingsRequest(this) getWifiManager().startScan() } @OnShowRationale(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION) fun showRationaleForLocation(request: PermissionRequest) { AlertDialog.Builder(this) .setMessage(R.string.permission_location_rationale) .setPositiveButton(R.string.button_allow) { dialog, button -> request.proceed() } .setNegativeButton(R.string.button_deny) { dialog, button -> request.cancel() } .show() } @OnPermissionDenied(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION) fun showDeniedForLocation() { SnackbarExtensions.showWarningSnack(getString(R.string.permission_location_denied)) } @OnNeverAskAgain(ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION) fun showNeverAskForLocation() { SnackbarExtensions.showWarningSnack(getString(R.string.permission_location_neverask)) } // endregion // region external input override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) Logger.v(TAG, "[onConfigurationChanged] " + newConfig) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) Logger.v(TAG, "[onActivityResult] requestCode=$requestCode resultCode=$resultCode data=$data") } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Logger.v(TAG, "[onNewIntent] " + intent) this.newIntent = intent consumeIntent() } companion object { private val TAG = MainActivity::class.java.simpleName // endregion // region public global permission trigger fun startWifiScanning() { val activity = getActivity() if (activity is MainActivity) MainActivityPermissionsDispatcher.scanWifiWithCheck(activity as MainActivity?) } // endregion val isGPSProviderEnabled: Boolean get() = getLocationManager().isProviderEnabled(LocationManager.GPS_PROVIDER) fun displayLocationSettingsRequest(context: Activity) { if (isGPSProviderEnabled) return val googleApiClient = GoogleApiClient.Builder(context).addApi(LocationServices.API).build() googleApiClient.connect() val locationRequest = LocationRequest.create() locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY locationRequest.interval = 10000 locationRequest.fastestInterval = (10000 / 2).toLong() val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest) builder.setAlwaysShow(true) val result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()) result.setResultCallback { r -> val status = r.status when (status.statusCode) { LocationSettingsStatusCodes.SUCCESS -> { } LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> // Logger.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings "); try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS) } catch (e: IntentSender.SendIntentException) { // Logger.i(TAG, "PendingIntent unable to execute request."); } LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> { } }// Logger.i(TAG, "All location settings are satisfied."); // Logger.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created."); } } } }
apache-2.0
f2382c37147cb3f0e5f3c0704b492815
35.311864
134
0.681262
5.129789
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/view/course_content/ui/fragment/CourseContentFragment.kt
2
21828
package org.stepik.android.view.course_content.ui.fragment import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.StringRes import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.Observables.zip import io.reactivex.rxkotlin.plusAssign import io.reactivex.subjects.BehaviorSubject import kotlinx.android.synthetic.main.empty_default.* import kotlinx.android.synthetic.main.error_no_connection.* import kotlinx.android.synthetic.main.fragment_course_content.* import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.persistence.model.DownloadProgress import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.dialogs.VideoQualityDetailedDialog import org.stepic.droid.ui.util.PopupHelper import org.stepic.droid.ui.util.snackbar import org.stepic.droid.util.ProgressHelper import org.stepic.droid.util.checkSelfPermissions import org.stepic.droid.util.requestMultiplePermissions import org.stepic.droid.web.storage.model.StorageRecord import org.stepik.android.domain.calendar.model.CalendarItem import org.stepik.android.domain.personal_deadlines.model.Deadline import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper import org.stepik.android.domain.personal_deadlines.model.LearningRate import org.stepik.android.model.Course import org.stepik.android.model.Section import org.stepik.android.model.Unit import org.stepik.android.presentation.course_calendar.model.CalendarError import org.stepik.android.presentation.course_content.CourseContentPresenter import org.stepik.android.presentation.course_content.CourseContentView import org.stepik.android.view.course.routing.CourseDeepLinkBuilder import org.stepik.android.view.course_calendar.ui.ChooseCalendarDialog import org.stepik.android.view.course_calendar.ui.ExplainCalendarPermissionDialog import org.stepik.android.view.course_content.model.CourseContentItem import org.stepik.android.view.course_content.ui.adapter.CourseContentAdapter import org.stepik.android.view.course_content.ui.adapter.delegates.control_bar.CourseContentControlBarClickListener import org.stepik.android.view.course_content.ui.dialog.RemoveCachedContentDialog import org.stepik.android.view.course_content.ui.fragment.listener.CourseContentSectionClickListenerImpl import org.stepik.android.view.course_content.ui.fragment.listener.CourseContentUnitClickListenerImpl import org.stepik.android.view.personal_deadlines.ui.dialogs.EditDeadlinesDialog import org.stepik.android.view.personal_deadlines.ui.dialogs.LearningRateDialog import org.stepik.android.view.ui.delegate.ViewStateDelegate import org.stepik.android.view.ui.listener.FragmentViewPagerScrollStateListener import ru.nobird.android.view.base.ui.extension.argument import ru.nobird.android.view.base.ui.extension.showIfNotExists import ru.nobird.android.view.base.ui.extension.snackbar import javax.inject.Inject class CourseContentFragment : Fragment(), CourseContentView, FragmentViewPagerScrollStateListener, ExplainCalendarPermissionDialog.Callback, RemoveCachedContentDialog.Callback { companion object { fun newInstance(courseId: Long): Fragment = CourseContentFragment().apply { this.courseId = courseId } private val SCROLL_STATE_IDLE_STUB = RecyclerView.SCROLL_STATE_IDLE to 0 private val SCROLL_STATE_SCROLLING_STUB = RecyclerView.SCROLL_STATE_DRAGGING to -1 } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var courseDeepLinkBuilder: CourseDeepLinkBuilder @Inject internal lateinit var analytic: Analytic private lateinit var contentAdapter: CourseContentAdapter private var courseId: Long by argument() private val courseContentPresenter: CourseContentPresenter by viewModels { viewModelFactory } private lateinit var viewStateDelegate: ViewStateDelegate<CourseContentView.State> private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() private val fragmentVisibilitySubject = BehaviorSubject.create<FragmentViewPagerScrollStateListener.ScrollState>() private val contentRecyclerScrollStateSubject = BehaviorSubject.createDefault(SCROLL_STATE_IDLE_STUB) private val uiCompositeDisposable = CompositeDisposable() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent(courseId) savedInstanceState?.let(courseContentPresenter::onRestoreInstanceState) } private fun injectComponent(courseId: Long) { App.componentManager() .courseComponent(courseId) .inject(this) } private fun releaseComponent(courseId: Long) { App.componentManager() .releaseCourseComponent(courseId) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_course_content, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { with(courseContentRecycler) { contentAdapter = CourseContentAdapter( sectionClickListener = CourseContentSectionClickListenerImpl(courseContentPresenter, courseDeepLinkBuilder, childFragmentManager, analytic), unitClickListener = CourseContentUnitClickListenerImpl(activity, courseContentPresenter, screenManager, childFragmentManager, analytic), controlBarClickListener = object : CourseContentControlBarClickListener { override fun onCreateScheduleClicked() { showPersonalDeadlinesLearningRateDialog() } override fun onChangeScheduleClicked(record: StorageRecord<DeadlinesWrapper>) { showPersonalDeadlinesEditDialog(record) } override fun onRemoveScheduleClicked(record: StorageRecord<DeadlinesWrapper>) { courseContentPresenter.removeDeadlines() } override fun onExportScheduleClicked() { syncCalendarDates() } override fun onDownloadAllClicked(course: Course) { courseContentPresenter.addCourseDownloadTask(course) analytic.reportAmplitudeEvent( AmplitudeAnalytic.Downloads.STARTED, mapOf( AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.COURSE ) ) } override fun onRemoveAllClicked(course: Course) { val fragmentManager = childFragmentManager .takeIf { it.findFragmentByTag(RemoveCachedContentDialog.TAG) == null } ?: return RemoveCachedContentDialog .newInstance(course = course) .show(fragmentManager, RemoveCachedContentDialog.TAG) } } ) val linearLayoutManager = LinearLayoutManager(context) adapter = contentAdapter layoutManager = linearLayoutManager itemAnimator = null addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply { ContextCompat.getDrawable(context, R.drawable.bg_divider_vertical)?.let(::setDrawable) }) addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { if (newState == RecyclerView.SCROLL_STATE_IDLE) { contentRecyclerScrollStateSubject.onNext(newState to linearLayoutManager.findFirstCompletelyVisibleItemPosition()) } else { contentRecyclerScrollStateSubject.onNext(SCROLL_STATE_SCROLLING_STUB) } } }) } viewStateDelegate = ViewStateDelegate() viewStateDelegate.addState<CourseContentView.State.Idle>(courseContentPlaceholder) viewStateDelegate.addState<CourseContentView.State.Loading>(courseContentPlaceholder) viewStateDelegate.addState<CourseContentView.State.CourseContentLoaded>(courseContentRecycler) viewStateDelegate.addState<CourseContentView.State.NetworkError>(reportProblem) viewStateDelegate.addState<CourseContentView.State.EmptyContent>(report_empty) } override fun onStart() { super.onStart() courseContentPresenter.attachView(this) } override fun onStop() { courseContentPresenter.detachView(this) super.onStop() } override fun onViewPagerScrollStateChanged(scrollState: FragmentViewPagerScrollStateListener.ScrollState) { fragmentVisibilitySubject.onNext(scrollState) } /** * States */ override fun setState(state: CourseContentView.State) { viewStateDelegate.switchState(state) if (state is CourseContentView.State.CourseContentLoaded) { contentAdapter.items = state.courseContent contentAdapter.setControlBar(CourseContentItem.ControlBar(state.course.enrollment > 0, state.personalDeadlinesState, state.course, state.hasDates)) } } override fun setBlockingLoading(isLoading: Boolean) { if (isLoading) { ProgressHelper.activate(progressDialogFragment, activity?.supportFragmentManager, LoadingProgressDialogFragment.TAG) } else { ProgressHelper.dismiss(activity?.supportFragmentManager, LoadingProgressDialogFragment.TAG) } } /** * Downloads */ override fun updateSectionDownloadProgress(downloadProgress: DownloadProgress) { contentAdapter.updateSectionDownloadProgress(downloadProgress) } override fun updateUnitDownloadProgress(downloadProgress: DownloadProgress) { contentAdapter.updateUnitDownloadProgress(downloadProgress) } override fun updateCourseDownloadProgress(downloadProgress: DownloadProgress) { contentAdapter.updateCourseDownloadProgress(downloadProgress) } override fun showChangeDownloadNetworkType() { view?.snackbar(messageRes = R.string.allow_mobile_snack, length = Snackbar.LENGTH_LONG) { setAction(R.string.settings_title) { analytic.reportEvent(Analytic.DownloaderV2.CLICK_SETTINGS_SECTIONS) screenManager.showSettings(activity) } } } override fun showVideoQualityDialog(course: Course?, section: Section?, unit: Unit?) { val supportFragmentManager = activity ?.supportFragmentManager ?: return val dialog = VideoQualityDetailedDialog.newInstance(course, section, unit) dialog.setTargetFragment(this, VideoQualityDetailedDialog.VIDEO_QUALITY_REQUEST_CODE) dialog.showIfNotExists(supportFragmentManager, VideoQualityDetailedDialog.TAG) } /** * Personal deadlines */ override fun showPersonalDeadlinesBanner() { val visibilityObservable = fragmentVisibilitySubject .filter { it == FragmentViewPagerScrollStateListener.ScrollState.ACTIVE } val scrollObservable = contentRecyclerScrollStateSubject .filter { (state, firstVisiblePosition) -> state == RecyclerView.SCROLL_STATE_IDLE && firstVisiblePosition == 0 } uiCompositeDisposable += zip(visibilityObservable, scrollObservable) .firstElement() .ignoreElement() .subscribe { val anchorView = courseContentRecycler.findViewById<View>(R.id.course_control_schedule) val deadlinesDescription = getString(R.string.deadlines_banner_description) PopupHelper.showPopupAnchoredToView(requireContext(), anchorView, deadlinesDescription, cancelableOnTouchOutside = true, withArrow = true) } } override fun showPersonalDeadlinesError() { view?.snackbar(messageRes = R.string.deadlines_fetching_error) } private fun showPersonalDeadlinesLearningRateDialog() { val supportFragmentManager = activity ?.supportFragmentManager ?: return val dialog = LearningRateDialog.newInstance() dialog.setTargetFragment(this, LearningRateDialog.LEARNING_RATE_REQUEST_CODE) dialog.showIfNotExists(supportFragmentManager, LearningRateDialog.TAG) analytic.reportEvent(Analytic.Deadlines.PERSONAL_DEADLINE_MODE_OPENED, courseId.toString()) analytic.reportAmplitudeEvent(AmplitudeAnalytic.Deadlines.SCHEDULE_PRESSED) } private fun showPersonalDeadlinesEditDialog(record: StorageRecord<DeadlinesWrapper>) { val supportFragmentManager = activity ?.supportFragmentManager ?: return val sections = contentAdapter .items .mapNotNull { item -> (item as? CourseContentItem.SectionItem) ?.section } val dialog = EditDeadlinesDialog.newInstance(sections, record) dialog.setTargetFragment(this, EditDeadlinesDialog.EDIT_DEADLINES_REQUEST_CODE) dialog.showIfNotExists(supportFragmentManager, EditDeadlinesDialog.TAG) analytic.reportEvent(Analytic.Deadlines.PERSONAL_DEADLINE_CHANGE_PRESSED, courseId.toString()) } override fun showCalendarChoiceDialog(calendarItems: List<CalendarItem>) { val supportFragmentManager = activity ?.supportFragmentManager ?: return val dialog = ChooseCalendarDialog.newInstance(calendarItems) dialog.setTargetFragment(this, ChooseCalendarDialog.CHOOSE_CALENDAR_REQUEST_CODE) dialog.showIfNotExists(supportFragmentManager, ChooseCalendarDialog.TAG) } /** * Calendar permission related */ private fun showExplainPermissionsDialog() { val supportFragmentManager = activity ?.supportFragmentManager ?: return val dialog = ExplainCalendarPermissionDialog.newInstance() dialog.setTargetFragment(this@CourseContentFragment, 0) dialog.showIfNotExists(supportFragmentManager, ExplainCalendarPermissionDialog.TAG) } private fun syncCalendarDates() { val permissions = listOf(Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR) if (requireContext().checkSelfPermissions(permissions)) { courseContentPresenter.fetchCalendarPrimaryItems() } else { showExplainPermissionsDialog() } } override fun onCalendarPermissionChosen(isAgreed: Boolean) { if (!isAgreed) return val permissions = listOf(Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR) requestMultiplePermissions(permissions, ExplainCalendarPermissionDialog.REQUEST_CALENDAR_PERMISSION) } override fun showCalendarSyncSuccess() { view?.snackbar(messageRes = R.string.course_content_calendar_sync_success) } override fun showCalendarError(error: CalendarError) { @StringRes val errorMessage = when (error) { CalendarError.GENERIC_ERROR -> R.string.request_error CalendarError.NO_CALENDARS_ERROR -> R.string.course_content_calendar_no_calendars_error CalendarError.PERMISSION_ERROR -> R.string.course_content_calendar_permission_error } view?.snackbar(messageRes = errorMessage) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { when (requestCode) { ExplainCalendarPermissionDialog.REQUEST_CALENDAR_PERMISSION -> { val deniedPermissionIndex = grantResults .indexOf(PackageManager.PERMISSION_DENIED) if (deniedPermissionIndex != -1) { if (!ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), permissions[deniedPermissionIndex])) { showCalendarError(CalendarError.PERMISSION_ERROR) } } else { courseContentPresenter.fetchCalendarPrimaryItems() } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { LearningRateDialog.LEARNING_RATE_REQUEST_CODE -> data?.takeIf { resultCode == Activity.RESULT_OK } ?.getParcelableExtra<LearningRate>(LearningRateDialog.KEY_LEARNING_RATE) ?.let(courseContentPresenter::createPersonalDeadlines) EditDeadlinesDialog.EDIT_DEADLINES_REQUEST_CODE -> data?.takeIf { resultCode == Activity.RESULT_OK } ?.getParcelableArrayListExtra<Deadline>(EditDeadlinesDialog.KEY_DEADLINES) ?.let(courseContentPresenter::updatePersonalDeadlines) VideoQualityDetailedDialog.VIDEO_QUALITY_REQUEST_CODE -> data?.let { intent -> val videoQuality = intent .getStringExtra(VideoQualityDetailedDialog.VIDEO_QUALITY) ?: return val course: Course? = intent .getParcelableExtra(VideoQualityDetailedDialog.COURSE_KEY) if (course != null) { return courseContentPresenter.addCourseDownloadTask(course, videoQuality) } val section: Section? = intent .getParcelableExtra(VideoQualityDetailedDialog.SECTION_KEY) if (section != null) { return courseContentPresenter.addSectionDownloadTask(section, videoQuality) } val unit: Unit? = intent .getParcelableExtra(VideoQualityDetailedDialog.UNIT_KEY) if (unit != null) { return courseContentPresenter.addUnitDownloadTask(unit, videoQuality) } } ChooseCalendarDialog.CHOOSE_CALENDAR_REQUEST_CODE -> data?.takeIf { resultCode == Activity.RESULT_OK } ?.getParcelableExtra<CalendarItem>(ChooseCalendarDialog.KEY_CALENDAR_ITEM) ?.let(courseContentPresenter::exportScheduleToCalendar) else -> super.onActivityResult(requestCode, resultCode, data) } } /** * RemoveCachedContentDialog.Callback */ override fun onRemoveCourseDownloadConfirmed(course: Course) { analytic.reportAmplitudeEvent( AmplitudeAnalytic.Downloads.DELETED, mapOf( AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.COURSE, AmplitudeAnalytic.Downloads.PARAM_SOURCE to AmplitudeAnalytic.Downloads.Values.SYLLABUS ) ) courseContentPresenter.removeCourseDownloadTask(course) } override fun onRemoveSectionDownloadConfirmed(section: Section) { analytic.reportAmplitudeEvent( AmplitudeAnalytic.Downloads.DELETED, mapOf( AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.SECTION, AmplitudeAnalytic.Downloads.PARAM_SOURCE to AmplitudeAnalytic.Downloads.Values.SYLLABUS ) ) courseContentPresenter.removeSectionDownloadTask(section) } override fun onRemoveUnitDownloadConfirmed(unit: Unit) { analytic.reportAmplitudeEvent( AmplitudeAnalytic.Downloads.DELETED, mapOf( AmplitudeAnalytic.Downloads.PARAM_CONTENT to AmplitudeAnalytic.Downloads.Values.LESSON, AmplitudeAnalytic.Downloads.PARAM_SOURCE to AmplitudeAnalytic.Downloads.Values.SYLLABUS ) ) courseContentPresenter.removeUnitDownloadTask(unit) } override fun onDestroyView() { uiCompositeDisposable.clear() super.onDestroyView() } override fun onDestroy() { releaseComponent(courseId) super.onDestroy() } }
apache-2.0
86919e82e1e5617e25062d7c170f8ae0
42.13834
159
0.686962
5.631579
false
false
false
false
allotria/intellij-community
plugins/git4idea/src/git4idea/config/InlineErrorNotifier.kt
3
5623
// 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 git4idea.config import com.intellij.ide.plugins.newui.TwoLineProgressIndicator import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.text.HtmlBuilder import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.Alarm.ThreadToUse.SWING_THREAD import com.intellij.util.SingleAlarm import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.Nls import org.jetbrains.annotations.Nls.Capitalization.Sentence import org.jetbrains.annotations.Nls.Capitalization.Title import org.jetbrains.annotations.NotNull import javax.swing.JComponent import javax.swing.JPanel import javax.swing.SwingConstants internal interface InlineComponent { fun showProgress(@Nls(capitalization = Title) text: String): ProgressIndicator fun showError(@Nls(capitalization = Sentence) errorText: String, link: LinkLabel<*>? = null) fun showMessage(@Nls(capitalization = Sentence) text: String) fun hideProgress() } internal open class InlineErrorNotifier(private val inlineComponent: InlineComponent, private val modalityState: ModalityState, private val disposable: Disposable) : ErrorNotifier { var isTaskInProgress: Boolean = false // Check from EDT only private set override fun showError(@Nls(capitalization = Sentence) text: String, @Nls(capitalization = Sentence) description: String?, fixOption: ErrorNotifier.FixOption?) { invokeAndWaitIfNeeded(modalityState) { val linkLabel = fixOption?.let { LinkLabel<Any>(fixOption.text, null) { _, _ -> fixOption.fix() } } val message = if (description == null) text else HtmlBuilder().append(text).br().append(description).wrapWithHtmlBody().toString() inlineComponent.showError(message, linkLabel) } } override fun showError(@Nls(capitalization = Sentence) text: String) { invokeAndWaitIfNeeded(modalityState) { inlineComponent.showError(text) } } @RequiresEdt override fun executeTask(@Nls(capitalization = Title) title: String, cancellable: Boolean, action: () -> Unit) { val pi = inlineComponent.showProgress(title) isTaskInProgress = true Disposer.register(disposable, Disposable { pi.cancel() }) ApplicationManager.getApplication().executeOnPooledThread { try { ProgressManager.getInstance().runProcess(Runnable { action() }, pi) } finally { invokeAndWaitIfNeeded(modalityState) { isTaskInProgress = false } } } } override fun changeProgressTitle(@Nls(capitalization = Title) text: String) { invokeAndWaitIfNeeded(modalityState) { inlineComponent.showProgress(text) } } override fun showMessage(@NlsContexts.NotificationContent @NotNull message: String) { invokeAndWaitIfNeeded(modalityState) { inlineComponent.showMessage(message) } } override fun hideProgress() { invokeAndWaitIfNeeded(modalityState) { inlineComponent.hideProgress() } } } class GitExecutableInlineComponent(private val container: BorderLayoutPanel, private val modalityState: ModalityState, private val panelToValidate: JPanel?) : InlineComponent { private var progressShown = false override fun showProgress(@Nls(capitalization = Title) text: String): ProgressIndicator { container.removeAll() val pi = TwoLineProgressIndicator(true).apply { this.text = text } progressShown = true SingleAlarm(Runnable { if (progressShown) { container.addToLeft(pi.component) panelToValidate?.validate() } }, delay = DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS, threadToUse = SWING_THREAD).request(modalityState) return pi } override fun showError(@Nls(capitalization = Sentence) errorText: String, link: LinkLabel<*>?) { container.removeAll() progressShown = false val label = multilineLabel(errorText).apply { foreground = DialogWrapper.ERROR_FOREGROUND_COLOR } container.addToCenter(label) if (link != null) { link.verticalAlignment = SwingConstants.TOP container.addToRight(link) } panelToValidate?.validate() } override fun showMessage(@Nls(capitalization = Sentence) text: @NlsContexts.Label String) { container.removeAll() progressShown = false container.addToLeft(JBLabel(text)) panelToValidate?.validate() } override fun hideProgress() { container.removeAll() progressShown = false panelToValidate?.validate() } private fun multilineLabel(text: @NlsContexts.Label String): JComponent = JBLabel(text).apply { setAllowAutoWrapping(true) setCopyable(true) } }
apache-2.0
1777e52e10dffcf518c0ba158e1781e9
33.925466
140
0.72079
4.876843
false
false
false
false
allotria/intellij-community
platform/platform-util-io/src/org/jetbrains/io/bufferToChars.kt
4
1415
// 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.io import io.netty.buffer.ByteBuf import io.netty.buffer.ByteBufUtil import io.netty.util.CharsetUtil import java.nio.ByteBuffer import java.nio.CharBuffer import java.nio.charset.CharacterCodingException import java.nio.charset.CharsetDecoder fun ByteBuf.readIntoCharBuffer(byteCount: Int = readableBytes(), charBuffer: CharBuffer) { val decoder = CharsetUtil.decoder(Charsets.UTF_8) if (nioBufferCount() == 1) { decodeString(decoder, internalNioBuffer(readerIndex(), byteCount), charBuffer) } else { val buffer = alloc().heapBuffer(byteCount) try { buffer.writeBytes(this, readerIndex(), byteCount) decodeString(decoder, buffer.internalNioBuffer(0, byteCount), charBuffer) } finally { buffer.release() } } } private fun decodeString(decoder: CharsetDecoder, src: ByteBuffer, dst: CharBuffer) { try { var cr = decoder.decode(src, dst, true) if (!cr.isUnderflow) { cr.throwException() } cr = decoder.flush(dst) if (!cr.isUnderflow) { cr.throwException() } } catch (x: CharacterCodingException) { throw IllegalStateException(x) } } fun writeIntAsAscii(value: Int, buffer: ByteBuf) { ByteBufUtil.writeAscii(buffer, StringBuilder().append(value)) }
apache-2.0
d86c14f91947fe18f8d75eaa088a1b8c
28.5
140
0.721555
3.876712
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/api/util/GHGQLPagesLoader.kt
3
2367
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.api.util import com.intellij.openapi.progress.ProgressIndicator import org.jetbrains.plugins.github.api.GithubApiRequest import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.data.graphql.GHGQLPageInfo import org.jetbrains.plugins.github.api.data.graphql.GHGQLRequestPagination import org.jetbrains.plugins.github.api.data.request.GithubRequestPagination import java.util.* import java.util.concurrent.atomic.AtomicReference abstract class GHGQLPagesLoader<T, R>(private val executor: GithubApiRequestExecutor, private val requestProducer: (GHGQLRequestPagination) -> GithubApiRequest.Post<T>, private val supportsTimestampUpdates: Boolean = false, private val pageSize: Int = GithubRequestPagination.DEFAULT_PAGE_SIZE) { private val iterationDataRef = AtomicReference(IterationData(true)) val hasNext: Boolean get() = iterationDataRef.get().hasNext @Synchronized fun loadNext(progressIndicator: ProgressIndicator, update: Boolean = false): R? { val iterationData = iterationDataRef.get() val pagination: GHGQLRequestPagination = if (update) { if (hasNext || !supportsTimestampUpdates) return null GHGQLRequestPagination(iterationData.timestamp, pageSize) } else { if (!hasNext) return null GHGQLRequestPagination(iterationData.cursor, pageSize) } val executionDate = Date() val response = executor.execute(progressIndicator, requestProducer(pagination)) val page = extractPageInfo(response) iterationDataRef.compareAndSet(iterationData, IterationData(page, executionDate)) return extractResult(response) } fun reset() { iterationDataRef.set(IterationData(true)) } protected abstract fun extractPageInfo(result: T): GHGQLPageInfo protected abstract fun extractResult(result: T): R private class IterationData(val hasNext: Boolean, val timestamp: Date? = null, val cursor: String? = null) { constructor(page: GHGQLPageInfo, timestamp: Date) : this(page.hasNextPage, timestamp, page.endCursor) } }
apache-2.0
a0e9e86f07929309055f6a88b4891070
42.054545
140
0.738065
4.772177
false
false
false
false
anthonycr/Lightning-Browser
app/src/main/java/acr/browser/lightning/browser/di/AppModule.kt
1
8420
package acr.browser.lightning.browser.di import acr.browser.lightning.R import acr.browser.lightning.browser.tab.DefaultTabTitle import acr.browser.lightning.device.BuildInfo import acr.browser.lightning.device.BuildType import acr.browser.lightning.html.ListPageReader import acr.browser.lightning.html.bookmark.BookmarkPageReader import acr.browser.lightning.html.homepage.HomePageReader import acr.browser.lightning.js.InvertPage import acr.browser.lightning.js.TextReflow import acr.browser.lightning.js.ThemeColor import acr.browser.lightning.log.AndroidLogger import acr.browser.lightning.log.Logger import acr.browser.lightning.log.NoOpLogger import acr.browser.lightning.search.suggestions.RequestFactory import acr.browser.lightning.utils.FileUtils import android.app.Application import android.app.DownloadManager import android.app.NotificationManager import android.content.ClipboardManager import android.content.Context import android.content.SharedPreferences import android.content.pm.ShortcutManager import android.content.res.AssetManager import android.net.ConnectivityManager import android.os.Build import android.os.Handler import android.os.Looper import android.view.WindowManager import android.view.inputmethod.InputMethodManager import androidx.annotation.RequiresApi import androidx.core.content.getSystemService import com.anthonycr.mezzanine.MezzanineGenerator import dagger.Module import dagger.Provides import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import net.i2p.android.ui.I2PAndroidHelper import okhttp3.Cache import okhttp3.CacheControl import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import java.io.File import java.util.concurrent.Executors import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit import javax.inject.Qualifier import javax.inject.Singleton @Module class AppModule { @Provides @MainHandler fun provideMainHandler() = Handler(Looper.getMainLooper()) @Provides fun provideContext(application: Application): Context = application.applicationContext @Provides @UserPrefs fun provideUserPreferences(application: Application): SharedPreferences = application.getSharedPreferences("settings", 0) @Provides @DevPrefs fun provideDebugPreferences(application: Application): SharedPreferences = application.getSharedPreferences("developer_settings", 0) @Provides @AdBlockPrefs fun provideAdBlockPreferences(application: Application): SharedPreferences = application.getSharedPreferences("ad_block_settings", 0) @Provides fun providesAssetManager(application: Application): AssetManager = application.assets @Provides fun providesClipboardManager(application: Application) = application.getSystemService<ClipboardManager>()!! @Provides fun providesInputMethodManager(application: Application) = application.getSystemService<InputMethodManager>()!! @Provides fun providesDownloadManager(application: Application) = application.getSystemService<DownloadManager>()!! @Provides fun providesConnectivityManager(application: Application) = application.getSystemService<ConnectivityManager>()!! @Provides fun providesNotificationManager(application: Application) = application.getSystemService<NotificationManager>()!! @Provides fun providesWindowManager(application: Application) = application.getSystemService<WindowManager>()!! @RequiresApi(Build.VERSION_CODES.N_MR1) @Provides fun providesShortcutManager(application: Application) = application.getSystemService<ShortcutManager>()!! @Provides @DatabaseScheduler @Singleton fun providesIoThread(): Scheduler = Schedulers.from(Executors.newSingleThreadExecutor()) @Provides @DiskScheduler @Singleton fun providesDiskThread(): Scheduler = Schedulers.from(Executors.newSingleThreadExecutor()) @Provides @NetworkScheduler @Singleton fun providesNetworkThread(): Scheduler = Schedulers.from(ThreadPoolExecutor(0, 4, 60, TimeUnit.SECONDS, LinkedBlockingDeque())) @Provides @MainScheduler @Singleton fun providesMainThread(): Scheduler = AndroidSchedulers.mainThread() @Singleton @Provides fun providesSuggestionsCacheControl(): CacheControl = CacheControl.Builder().maxStale(1, TimeUnit.DAYS).build() @Singleton @Provides fun providesSuggestionsRequestFactory(cacheControl: CacheControl): RequestFactory = object : RequestFactory { override fun createSuggestionsRequest(httpUrl: HttpUrl, encoding: String): Request { return Request.Builder().url(httpUrl) .addHeader("Accept-Charset", encoding) .cacheControl(cacheControl) .build() } } private fun createInterceptorWithMaxCacheAge(maxCacheAgeSeconds: Long) = Interceptor { chain -> chain.proceed(chain.request()).newBuilder() .header("cache-control", "max-age=$maxCacheAgeSeconds, max-stale=$maxCacheAgeSeconds") .build() } @Singleton @Provides @SuggestionsClient fun providesSuggestionsHttpClient(application: Application): Single<OkHttpClient> = Single.fromCallable { val intervalDay = TimeUnit.DAYS.toSeconds(1) val suggestionsCache = File(application.cacheDir, "suggestion_responses") return@fromCallable OkHttpClient.Builder() .cache(Cache(suggestionsCache, FileUtils.megabytesToBytes(1))) .addNetworkInterceptor(createInterceptorWithMaxCacheAge(intervalDay)) .build() }.cache() @Singleton @Provides @HostsClient fun providesHostsHttpClient(application: Application): Single<OkHttpClient> = Single.fromCallable { val intervalYear = TimeUnit.DAYS.toSeconds(365) val suggestionsCache = File(application.cacheDir, "hosts_cache") return@fromCallable OkHttpClient.Builder() .cache(Cache(suggestionsCache, FileUtils.megabytesToBytes(5))) .addNetworkInterceptor(createInterceptorWithMaxCacheAge(intervalYear)) .build() }.cache() @Provides @Singleton fun provideLogger(buildInfo: BuildInfo): Logger = if (buildInfo.buildType == BuildType.DEBUG) { AndroidLogger() } else { NoOpLogger() } @Provides @Singleton fun provideI2PAndroidHelper(application: Application): I2PAndroidHelper = I2PAndroidHelper(application) @Provides fun providesListPageReader(): ListPageReader = MezzanineGenerator.ListPageReader() @Provides fun providesHomePageReader(): HomePageReader = MezzanineGenerator.HomePageReader() @Provides fun providesBookmarkPageReader(): BookmarkPageReader = MezzanineGenerator.BookmarkPageReader() @Provides fun providesTextReflow(): TextReflow = MezzanineGenerator.TextReflow() @Provides fun providesThemeColor(): ThemeColor = MezzanineGenerator.ThemeColor() @Provides fun providesInvertPage(): InvertPage = MezzanineGenerator.InvertPage() @DefaultTabTitle @Provides fun providesDefaultTabTitle(application: Application): String = application.getString(R.string.untitled) } @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class SuggestionsClient @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class HostsClient @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class MainHandler @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class UserPrefs @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class AdBlockPrefs @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class DevPrefs @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class MainScheduler @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class DiskScheduler @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class NetworkScheduler @Qualifier @Retention(AnnotationRetention.SOURCE) annotation class DatabaseScheduler
mpl-2.0
8fa2375e1e0dc7d69275d63686d46935
31.260536
99
0.760451
4.982249
false
false
false
false
AndroidX/androidx
compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/AnimatedVisibility.kt
3
43769
/* * 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.animation import androidx.compose.animation.EnterExitState.PostExit import androidx.compose.animation.EnterExitState.PreEnter import androidx.compose.animation.EnterExitState.Visible import androidx.compose.animation.core.ExperimentalTransitionApi import androidx.compose.animation.core.InternalAnimationApi import androidx.compose.animation.core.MutableTransitionState import androidx.compose.animation.core.Transition import androidx.compose.animation.core.createChildTransition import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.IntrinsicMeasureScope import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastMaxBy import kotlinx.coroutines.flow.collect import androidx.compose.animation.internal.JvmDefaultWithCompatibility /** * [AnimatedVisibility] composable animates the appearance and disappearance of its content, as * [visible] value changes. Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See the second sample code snippet below for example. * These custom animations will be running alongside of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish before * it considers itself idle. [content] will only be removed after all the (built-in and custom) * exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. If there's a need to observe the state change of the enter/exit * transition and follow up additional action (e.g. remove data, sequential animation, etc), * consider the AnimatedVisibility API variant that takes a [MutableTransitionState] parameter. * * By default, the enter transition will be a combination of [fadeIn] and [expandIn] of the * content from the bottom end. And the exit transition will be shrinking the content towards the * bottom end while fading out (i.e. [fadeOut] + [shrinkOut]). The expanding and shrinking will * likely also animate the parent and siblings if they rely on the size of appearing/disappearing * content. When the [AnimatedVisibility] composable is put in a [Row] or a [Column], the default * enter and exit transitions are tailored to that particular container. See * [RowScope.AnimatedVisibility] and [ColumnScope.AnimatedVisibility] for details. * * Here are two examples of [AnimatedVisibility]: one using the built-in enter/exit transition, the * other using a custom enter/exit animation. * * @sample androidx.compose.animation.samples.FullyLoadedTransition * * The example blow shows how a custom enter/exit animation can be created using the Transition * object (i.e. Transition<EnterExitState>) from [AnimatedVisibilityScope]. * * @sample androidx.compose.animation.samples.AnimatedVisibilityWithBooleanVisibleParamNoReceiver * * @param visible defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding by * default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking by default * @param content Content to appear or disappear based on the value of [visible] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibilityScope */ @Composable fun AnimatedVisibility( visible: Boolean, modifier: Modifier = Modifier, enter: EnterTransition = fadeIn() + expandIn(), exit: ExitTransition = shrinkOut() + fadeOut(), label: String = "AnimatedVisibility", content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visible, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * [RowScope.AnimatedVisibility] composable animates the appearance and disappearance of its * content when the [AnimatedVisibility] is in a [Row]. The default animations are tailored * specific to the [Row] layout. See more details below. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale, and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * The default [enter] and [exit] transition is configured based on the horizontal layout of a * [Row]. [enter] defaults to a combination of fading in and expanding the content horizontally. * (The end of the content will be the leading edge as the content expands to its * full width.) And [exit] defaults to shrinking the content horizontally with the end of the * content being the leading edge while fading out. The expanding and shrinking will likely also * animate the parent and siblings in the row since they rely on the size of appearing/disappearing * content. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. If there's a need to observe the state change of the enter/exit * transition and follow up additional action (e.g. remove data, sequential animation, etc), * consider the AnimatedVisibility API variant that takes a [MutableTransitionState] parameter. * * Here's an example of using [RowScope.AnimatedVisibility] in a [Row]: * @sample androidx.compose.animation.samples.AnimatedFloatingActionButton * * @param visible defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding * horizontally by default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking horizontally by default * @param content Content to appear or disappear based on the value of [visible] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibility * @see ColumnScope.AnimatedVisibility * @see AnimatedVisibilityScope */ @Composable fun RowScope.AnimatedVisibility( visible: Boolean, modifier: Modifier = Modifier, enter: EnterTransition = fadeIn() + expandHorizontally(), exit: ExitTransition = fadeOut() + shrinkHorizontally(), label: String = "AnimatedVisibility", content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visible, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * [ColumnScope.AnimatedVisibility] composable animates the appearance and disappearance of its * content when the [AnimatedVisibility] is in a [Column]. The default animations are tailored * specific to the [Column] layout. See more details below. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * The default [enter] and [exit] transition is configured based on the vertical layout of a * [Column]. [enter] defaults to a combination of fading in and expanding the content vertically. * (The bottom of the content will be the leading edge as the content expands to its full height.) * And the [exit] defaults to shrinking the content vertically with the bottom of the content being * the leading edge while fading out. The expanding and shrinking will likely also animate the * parent and siblings in the column since they rely on the size of appearing/disappearing content. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. If there's a need to observe the state change of the enter/exit * transition and follow up additional action (e.g. remove data, sequential animation, etc), * consider the AnimatedVisibility API variant that takes a [MutableTransitionState] parameter. * * Here's an example of using [ColumnScope.AnimatedVisibility] in a [Column]: * @sample androidx.compose.animation.samples.ColumnAnimatedVisibilitySample * * @param visible defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding * vertically by default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking vertically by default * @param content Content to appear or disappear based on the value of [visible] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibility * @see AnimatedVisibilityScope */ @Composable fun ColumnScope.AnimatedVisibility( visible: Boolean, modifier: Modifier = Modifier, enter: EnterTransition = fadeIn() + expandVertically(), exit: ExitTransition = fadeOut() + shrinkVertically(), label: String = "AnimatedVisibility", content: @Composable AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visible, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * [EnterExitState] contains the three states that are involved in the enter and exit transition * of [AnimatedVisibility]. More specifically, [PreEnter] and [Visible] defines the initial and * target state of an *enter* transition, whereas [Visible] and [PostExit] are the initial and * target state of an *exit* transition. * * See blow for an example of custom enter/exit animation in [AnimatedVisibility] using * `Transition<EnterExitState>` (i.e. [AnimatedVisibilityScope.transition]): * * @sample androidx.compose.animation.samples.AnimatedVisibilityWithBooleanVisibleParamNoReceiver * @see AnimatedVisibility */ @ExperimentalAnimationApi enum class EnterExitState { /** * The initial state of a custom enter animation in [AnimatedVisibility].. */ PreEnter, /** * The `Visible` state is the target state of a custom *enter* animation, also the initial * state of a custom *exit* animation in [AnimatedVisibility]. */ Visible, /** * Target state of a custom *exit* animation in [AnimatedVisibility]. */ PostExit } /** * [AnimatedVisibility] composable animates the appearance and disappearance of its content, as * [visibleState]'s [targetState][MutableTransitionState.targetState] changes. The [visibleState] * can also be used to observe the state of [AnimatedVisibility]. For example: * `visibleState.isIdle` indicates whether all the animations have finished in [AnimatedVisibility], * and `visibleState.currentState` returns the initial state of the current animations. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. Both `currentState` and `targetState` will be `false` for * [visibleState]. * * By default, the enter transition will be a combination of [fadeIn] and [expandIn] of the * content from the bottom end. And the exit transition will be shrinking the content towards the * bottom end while fading out (i.e. [fadeOut] + [shrinkOut]). The expanding and shrinking will * likely also animate the parent and siblings if they rely on the size of appearing/disappearing * content. When the [AnimatedVisibility] composable is put in a [Row] or a [Column], the default * enter and exit transitions are tailored to that particular container. See * [RowScope.AnimatedVisibility] and [ColumnScope.AnimatedVisibility] for details. * * @sample androidx.compose.animation.samples.AnimatedVisibilityLazyColumnSample * * @param visibleState defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding by * default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking by default * @param content Content to appear or disappear based on the value of [visibleState] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibility * @see Transition.AnimatedVisibility * @see AnimatedVisibilityScope */ @Composable fun AnimatedVisibility( visibleState: MutableTransitionState<Boolean>, modifier: Modifier = Modifier, enter: EnterTransition = fadeIn() + expandIn(), exit: ExitTransition = fadeOut() + shrinkOut(), label: String = "AnimatedVisibility", content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visibleState, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * [RowScope.AnimatedVisibility] composable animates the appearance and disappearance of its * content as [visibleState]'s [targetState][MutableTransitionState.targetState] changes. The * default [enter] and [exit] transitions are tailored specific to the [Row] layout. See more * details below. The [visibleState] can also be used to observe the state of [AnimatedVisibility]. * For example: `visibleState.isIdle` indicates whether all the animations have finished in * [AnimatedVisibility], and `visibleState.currentState` returns the initial state of the current * animations. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * The default [enter] and [exit] transition is configured based on the horizontal layout of a * [Row]. [enter] defaults to a combination of fading in and expanding the content horizontally. * (The end of the content will be the leading edge as the content expands to its * full width.) And [exit] defaults to shrinking the content horizontally with the end of the * content being the leading edge while fading out. The expanding and shrinking will likely also * animate the parent and siblings in the row since they rely on the size of appearing/disappearing * content. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. Both `currentState` and `targetState` will be `false` for * [visibleState]. * * @param visibleState defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding * vertically by default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking vertically by default * @param content Content to appear or disappear based on the value of [visibleState] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibility * @see Transition.AnimatedVisibility * @see AnimatedVisibilityScope */ @Composable fun RowScope.AnimatedVisibility( visibleState: MutableTransitionState<Boolean>, modifier: Modifier = Modifier, enter: EnterTransition = expandHorizontally() + fadeIn(), exit: ExitTransition = shrinkHorizontally() + fadeOut(), label: String = "AnimatedVisibility", content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visibleState, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * [ColumnScope.AnimatedVisibility] composable animates the appearance and disappearance of its * content as [visibleState]'s [targetState][MutableTransitionState.targetState] changes. The * default [enter] and [exit] transitions are tailored specific to the [Column] layout. See more * details below. The [visibleState] can also be used to observe the state of [AnimatedVisibility]. * For example: `visibleState.isIdle` indicates whether all the animations have finished in * [AnimatedVisibility], and `visibleState.currentState` returns the initial state of the current * animations. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * The default [enter] and [exit] transition is configured based on the vertical layout of a * [Column]. [enter] defaults to a combination of fading in and expanding the content vertically. * (The bottom of the content will be the leading edge as the content expands to its full height.) * And the [exit] defaults to shrinking the content vertically with the bottom of the content being * the leading edge while fading out. The expanding and shrinking will likely also animate the * parent and siblings in the column since they rely on the size of appearing/disappearing content. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. Both `currentState` and `targetState` will be `false` for * [visibleState]. * * @sample androidx.compose.animation.samples.AVColumnScopeWithMutableTransitionState * * @param visibleState defines whether the content should be visible * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding * vertically by default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking vertically by default * @param content Content to appear or disappear based on of [visibleState] * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibility * @see Transition.AnimatedVisibility * @see AnimatedVisibilityScope */ @Composable fun ColumnScope.AnimatedVisibility( visibleState: MutableTransitionState<Boolean>, modifier: Modifier = Modifier, enter: EnterTransition = expandVertically() + fadeIn(), exit: ExitTransition = shrinkVertically() + fadeOut(), label: String = "AnimatedVisibility", content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val transition = updateTransition(visibleState, label) AnimatedEnterExitImpl(transition, { it }, modifier, enter, exit, content) } /** * This extension function creates an [AnimatedVisibility] composable as a child Transition of * the given Transition. This means: 1) the enter/exit transition is now triggered by the provided * [Transition]'s [targetState][Transition.targetState] change. When the targetState changes, the * visibility will be derived using the [visible] lambda and [Transition.targetState]. 2) * The enter/exit transitions, as well as any custom enter/exit animations defined in * [AnimatedVisibility] are now hoisted to the parent Transition. The parent Transition will wait * for all of them to finish before it considers itself finished (i.e. [Transition.currentState] * = [Transition.targetState]), and subsequently removes the content in the exit case. * * Different [EnterTransition]s and [ExitTransition]s can be defined in * [enter] and [exit] for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * Aside from these three types of [EnterTransition] and [ExitTransition], [AnimatedVisibility] * also supports custom enter/exit animations. Some use cases may benefit from custom enter/exit * animations on shape, scale, color, etc. Custom enter/exit animations can be created using the * `Transition<EnterExitState>` object from the [AnimatedVisibilityScope] (i.e. * [AnimatedVisibilityScope.transition]). See [EnterExitState] for an example of custom animations. * These custom animations will be running along side of the built-in animations specified in * [enter] and [exit]. In cases where the enter/exit animation needs to be completely customized, * [enter] and/or [exit] can be specified as [EnterTransition.None] and/or [ExitTransition.None] * as needed. [AnimatedVisibility] will wait until *all* of enter/exit animations to finish * before it considers itself idle. [content] will only be removed after all the (built-in and * custom) exit animations have finished. * * [AnimatedVisibility] creates a custom [Layout] for its content. The size of the custom * layout is determined by the largest width and largest height of the children. All children * will be aligned to the top start of the [Layout]. * * __Note__: Once the exit transition is finished, the [content] composable will be removed * from the tree, and disposed. * * By default, the enter transition will be a combination of [fadeIn] and [expandIn] of the * content from the bottom end. And the exit transition will be shrinking the content towards the * bottom end while fading out (i.e. [fadeOut] + [shrinkOut]). The expanding and shrinking will * likely also animate the parent and siblings if they rely on the size of appearing/disappearing * content. * * @sample androidx.compose.animation.samples.AddAnimatedVisibilityToGenericTransitionSample * * @param visible defines whether the content should be visible based on transition state T * @param modifier modifier for the [Layout] created to contain the [content] * @param enter EnterTransition(s) used for the appearing animation, fading in while expanding * vertically by default * @param exit ExitTransition(s) used for the disappearing animation, fading out while * shrinking vertically by default * @param content Content to appear or disappear based on the visibility derived from the * [Transition.targetState] and the provided [visible] lambda * * @see EnterTransition * @see ExitTransition * @see fadeIn * @see expandIn * @see fadeOut * @see shrinkOut * @see AnimatedVisibilityScope * @see Transition.AnimatedVisibility */ @ExperimentalAnimationApi @Composable fun <T> Transition<T>.AnimatedVisibility( visible: (T) -> Boolean, modifier: Modifier = Modifier, enter: EnterTransition = fadeIn() + expandIn(), exit: ExitTransition = shrinkOut() + fadeOut(), content: @Composable() AnimatedVisibilityScope.() -> Unit ) = AnimatedEnterExitImpl(this, visible, modifier, enter, exit, content) /** * This is the scope for the content of [AnimatedVisibility]. In this scope, direct and * indirect children of [AnimatedVisibility] will be able to define their own enter/exit * transitions using the built-in options via [Modifier.animateEnterExit]. They will also be able * define custom enter/exit animations using the [transition] object. [AnimatedVisibility] will * ensure both custom and built-in enter/exit animations finish before it considers itself idle, * and subsequently removes its content in the case of exit. * * __Note:__ Custom enter/exit animations that are created *independent* of the * [AnimatedVisibilityScope.transition] will have no guarantee to finish when * exiting, as [AnimatedVisibility] would have no visibility of such animations. * * @sample androidx.compose.animation.samples.AVScopeAnimateEnterExit */ @JvmDefaultWithCompatibility interface AnimatedVisibilityScope { /** * [transition] allows custom enter/exit animations to be specified. It will run simultaneously * with the built-in enter/exit transitions specified in [AnimatedVisibility]. */ @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalAnimationApi @ExperimentalAnimationApi val transition: Transition<EnterExitState> /** * [animateEnterExit] modifier can be used for any direct or indirect children of * [AnimatedVisibility] to create a different enter/exit animation than what's specified in * [AnimatedVisibility]. The visual effect of these children will be a combination of the * [AnimatedVisibility]'s animation and their own enter/exit animations. * * [enter] and [exit] defines different [EnterTransition]s and [ExitTransition]s that will be * used for the appearance and disappearance animation. There are 4 types of * [EnterTransition] and [ExitTransition]: Fade, Expand/Shrink, Scale and Slide. The enter * transitions can be combined using `+`. Same for exit transitions. The order of the combination * does not matter, as the transition animations will start simultaneously. See [EnterTransition] * and [ExitTransition] for details on the three types of transition. * * By default, the enter transition will be a combination of [fadeIn] and [expandIn] of the * content from the bottom end. And the exit transition will be shrinking the content towards * the bottom end while fading out (i.e. [fadeOut] + [shrinkOut]). The expanding and shrinking * will likely also animate the parent and siblings if they rely on the size of * appearing/disappearing content. * * In some cases it may be desirable to have [AnimatedVisibility] apply no animation at all for * enter and/or exit, such that children of [AnimatedVisibility] can each have their distinct * animations. To achieve this, [EnterTransition.None] and/or [ExitTransition.None] can be * used for [AnimatedVisibility]. * * @sample androidx.compose.animation.samples.AnimateEnterExitPartialContent */ @ExperimentalAnimationApi fun Modifier.animateEnterExit( enter: EnterTransition = fadeIn() + expandIn(), exit: ExitTransition = fadeOut() + shrinkOut(), label: String = "animateEnterExit" ): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "animateEnterExit" properties["enter"] = enter properties["exit"] = exit properties["label"] = label } ) { this.then(transition.createModifier(enter, exit, label)) } } @ExperimentalAnimationApi internal class AnimatedVisibilityScopeImpl internal constructor( transition: Transition<EnterExitState> ) : AnimatedVisibilityScope { override var transition = transition internal val targetSize = mutableStateOf(IntSize.Zero) } @ExperimentalAnimationApi @Composable @Deprecated( "AnimatedVisibility no longer accepts initiallyVisible as a parameter, please use " + "AnimatedVisibility(MutableTransitionState, Modifier, ...) API instead", replaceWith = ReplaceWith( "AnimatedVisibility(" + "transitionState = remember { MutableTransitionState(initiallyVisible) }\n" + ".apply { targetState = visible },\n" + "modifier = modifier,\n" + "enter = enter,\n" + "exit = exit) {\n" + "content() \n" + "}", "androidx.compose.animation.core.MutableTransitionState" ) ) fun AnimatedVisibility( visible: Boolean, modifier: Modifier = Modifier, enter: EnterTransition, exit: ExitTransition, initiallyVisible: Boolean, content: @Composable () -> Unit ) = AnimatedVisibility( visibleState = remember { MutableTransitionState(initiallyVisible) } .apply { targetState = visible }, modifier = modifier, enter = enter, exit = exit ) { content() } // RowScope and ColumnScope AnimatedEnterExit extensions and AnimatedEnterExit without a receiver // converge here. @OptIn( ExperimentalTransitionApi::class, InternalAnimationApi::class, ExperimentalAnimationApi::class ) @Composable private fun <T> AnimatedEnterExitImpl( transition: Transition<T>, visible: (T) -> Boolean, modifier: Modifier, enter: EnterTransition, exit: ExitTransition, content: @Composable() AnimatedVisibilityScope.() -> Unit ) { val isAnimationVisible = remember(transition) { mutableStateOf(visible(transition.currentState)) } if (visible(transition.targetState) || isAnimationVisible.value || transition.isSeeking) { val childTransition = transition.createChildTransition(label = "EnterExitTransition") { transition.targetEnterExit(visible, it) } LaunchedEffect(childTransition) { snapshotFlow { childTransition.currentState == EnterExitState.Visible || childTransition.targetState == EnterExitState.Visible }.collect { isAnimationVisible.value = it } } AnimatedEnterExitImpl( childTransition, modifier, enter = enter, exit = exit, content = content ) } } @ExperimentalAnimationApi @Composable private inline fun AnimatedEnterExitImpl( transition: Transition<EnterExitState>, modifier: Modifier, enter: EnterTransition, exit: ExitTransition, content: @Composable AnimatedVisibilityScope.() -> Unit ) { // TODO: Get some feedback on whether there's a need to observe this state change in user // code. If there is, this if check will need to be moved to measure stage, along with some // structural changes. if (transition.currentState == EnterExitState.Visible || transition.targetState == EnterExitState.Visible ) { val scope = remember(transition) { AnimatedVisibilityScopeImpl(transition) } Layout( content = { scope.content() }, modifier = modifier.then(transition.createModifier(enter, exit, "Built-in")), measurePolicy = remember { AnimatedEnterExitMeasurePolicy(scope) } ) } } @OptIn(ExperimentalAnimationApi::class) private class AnimatedEnterExitMeasurePolicy( val scope: AnimatedVisibilityScopeImpl ) : MeasurePolicy { override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult { val placeables = measurables.map { it.measure(constraints) } val maxWidth: Int = placeables.fastMaxBy { it.width }?.width ?: 0 val maxHeight = placeables.fastMaxBy { it.height }?.height ?: 0 // Position the children. scope.targetSize.value = IntSize(maxWidth, maxHeight) return layout(maxWidth, maxHeight) { placeables.fastForEach { it.place(0, 0) } } } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = measurables.asSequence().map { it.minIntrinsicWidth(height) }.maxOrNull() ?: 0 override fun IntrinsicMeasureScope.minIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = measurables.asSequence().map { it.minIntrinsicHeight(width) }.maxOrNull() ?: 0 override fun IntrinsicMeasureScope.maxIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = measurables.asSequence().map { it.maxIntrinsicWidth(height) }.maxOrNull() ?: 0 override fun IntrinsicMeasureScope.maxIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = measurables.asSequence().map { it.maxIntrinsicHeight(width) }.maxOrNull() ?: 0 } // This converts Boolean visible to EnterExitState @OptIn(InternalAnimationApi::class, ExperimentalAnimationApi::class) @Composable private fun <T> Transition<T>.targetEnterExit( visible: (T) -> Boolean, targetState: T ): EnterExitState = key(this) { if (this.isSeeking) { if (visible(targetState)) { Visible } else { if (visible(this.currentState)) { PostExit } else { PreEnter } } } else { val hasBeenVisible = remember { mutableStateOf(false) } if (visible(currentState)) { hasBeenVisible.value = true } if (visible(targetState)) { EnterExitState.Visible } else { // If never been visible, visible = false means PreEnter, otherwise PostExit if (hasBeenVisible.value) { EnterExitState.PostExit } else { EnterExitState.PreEnter } } } }
apache-2.0
72417923c656b7ab91fbdd84367c0698
49.776102
101
0.744065
4.63213
false
false
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/model/TheWordContent.kt
1
1846
package de.reiss.bible2net.theword.model import android.os.Parcel import android.os.Parcelable data class TheWordContent( val book1: String, val chapter1: String, val verse1: String, val id1: String, val intro1: String, val text1: String, val ref1: String, val book2: String, val chapter2: String, val verse2: String, val id2: String, val intro2: String, val text2: String, val ref2: String ) : Parcelable { constructor(source: Parcel) : this( source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!!, source.readString()!! ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeString(book1) writeString(chapter1) writeString(verse1) writeString(id1) writeString(intro1) writeString(text1) writeString(ref1) writeString(book2) writeString(chapter2) writeString(verse2) writeString(id2) writeString(intro2) writeString(text2) writeString(ref2) } companion object { @JvmField val CREATOR: Parcelable.Creator<TheWordContent> = object : Parcelable.Creator<TheWordContent> { override fun createFromParcel(source: Parcel): TheWordContent = TheWordContent(source) override fun newArray(size: Int): Array<TheWordContent?> = arrayOfNulls(size) } } }
gpl-3.0
27a671e8ff6e5a808b5e2bf4678bc4a7
25.753623
93
0.599133
4.569307
false
true
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRSearchPanel.kt
3
3596
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.ui.toolwindow import com.intellij.codeInsight.AutoPopupController import com.intellij.icons.AllIcons import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.IconButton import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.InplaceButton import com.intellij.util.textCompletion.TextCompletionProvider import com.intellij.util.textCompletion.TextFieldWithCompletion import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import com.intellij.collaboration.ui.SingleValueModel import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.KeyStroke object GHPRSearchPanel { private const val SHOW_SEARCH_HISTORY_ACTION = "ShowSearchHistory" fun create(project: Project, model: SingleValueModel<String>, completionProvider: TextCompletionProvider, pullRequestUiSettings: GithubPullRequestsProjectUISettings): JComponent { var showSearchHistoryButton: JComponent? = null val showSearchHistoryAction = { JBPopupFactory.getInstance() .createListPopup(object : BaseListPopupStep<String>(null, pullRequestUiSettings.getRecentSearchFilters()) { override fun onChosen(selectedValue: String?, finalChoice: Boolean) = doFinalStep { selectedValue?.let { model.value = it } } }) .showUnderneathOf(showSearchHistoryButton!!) } showSearchHistoryButton = InplaceButton( IconButton( GithubBundle.message("pull.request.list.search.history", KeymapUtil.getFirstKeyboardShortcutText(SHOW_SEARCH_HISTORY_ACTION)), AllIcons.Actions.SearchWithHistory)) { showSearchHistoryAction() }.let { JBUI.Panels.simplePanel(it).withBorder(JBUI.Borders.emptyLeft(5)).withBackground(UIUtil.getListBackground()) } val searchField = object : TextFieldWithCompletion(project, completionProvider, "", true, true, false, false) { override fun setupBorder(editor: EditorEx) { editor.setBorder(JBUI.Borders.empty(6, 5)) } override fun processKeyBinding(ks: KeyStroke?, e: KeyEvent?, condition: Int, pressed: Boolean): Boolean { if (e?.keyCode == KeyEvent.VK_ENTER && pressed) { val query = text.trim() if (query.isNotEmpty()) { pullRequestUiSettings.addRecentSearchFilter(query) } model.value = query return true } return super.processKeyBinding(ks, e, condition, pressed) } }.apply { addSettingsProvider { it.putUserData(AutoPopupController.NO_ADS, true) UIUtil.setNotOpaqueRecursively(it.component) } DumbAwareAction.create { showSearchHistoryAction() } .registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts(SHOW_SEARCH_HISTORY_ACTION), this) } model.addAndInvokeListener { searchField.text = model.value } return JBUI.Panels.simplePanel(searchField).addToLeft(showSearchHistoryButton).withBackground(UIUtil.getListBackground()) } }
apache-2.0
3429276195bc76fa2a5a9baf37959aa0
40.344828
140
0.740545
4.762914
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/lang/KslIf.kt
1
1613
package de.fabmax.kool.modules.ksl.lang class KslIf(val condition: KslExpression<KslTypeBool1>, parentScope: KslScopeBuilder) : KslStatement("if", parentScope) { val body = KslScopeBuilder(this, parentScope, parentScope.parentStage) val elseIfs = mutableListOf<Pair<KslExpression<KslTypeBool1>, KslScopeBuilder>>() val elseBody = KslScopeBuilder(this, parentScope, parentScope.parentStage).apply { scopeName = "else" } private val parentBuilder = parentScope init { addExpressionDependencies(condition) childScopes += body childScopes += elseBody } fun elseIf(condition: KslExpression<KslTypeBool1>, block: KslScopeBuilder.() -> Unit): KslIf { addExpressionDependencies(condition) val body = KslScopeBuilder(this, parentBuilder, parentBuilder.parentStage).apply { scopeName = "elseif" block() } elseIfs += condition to body // insert else if block before else childScopes.add(childScopes.lastIndex, body) return this } fun `else`(block: KslScopeBuilder.() -> Unit) { elseBody.apply(block) } override fun toPseudoCode(): String { val str = StringBuilder("if (${condition.toPseudoCode()}) // ${dependenciesAndMutationsToString()}\n") str.append(body.toPseudoCode()) elseIfs.forEach { str.append(" else if (${it.first.toPseudoCode()}) ${it.second.toPseudoCode()}") } if (elseBody.isNotEmpty()) { str.append(" else ${elseBody.toPseudoCode()}") } return str.toString() } }
apache-2.0
bab7788e551ece9321337d8737bc4be7
36.534884
121
0.651581
4.371274
false
false
false
false