repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
ursjoss/scipamato
common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/model/InjectedLoadableDetachableModel.kt
2
493
package ch.difty.scipamato.common.web.model import org.apache.wicket.injection.Injector import org.apache.wicket.model.LoadableDetachableModel abstract class InjectedLoadableDetachableModel<T> : LoadableDetachableModel<List<T>>() { init { injectThis() } /** for overriding to get wicket-free test stubbing */ protected open fun injectThis() { Injector.get().inject(this) } companion object { private const val serialVersionUID = 1L } }
bsd-3-clause
ageery/kwicket
kwicket-wicket-webjars/src/main/kotlin/org/kwicket/agilecoders/wicket/webjars/Applications.kt
1
2592
package org.kwicket.agilecoders.wicket.webjars import de.agilecoders.wicket.webjars.WicketWebjars import de.agilecoders.wicket.webjars.collectors.AssetPathCollector import de.agilecoders.wicket.webjars.settings.ResourceStreamProvider import de.agilecoders.wicket.webjars.settings.WebjarsSettings import org.apache.wicket.protocol.http.WebApplication import org.apache.wicket.util.time.Duration import java.util.regex.Pattern /** * Extension method for enabling webjars in a [WebApplication]. * * @receiver the [WebApplication] to add the webjars functionality to * @param A type of [WebApplication] the webjar functionality is being added to * @param resourceStreamProvider [ResourceStreamProvider] to use to load resources * @param assetPathCollectors [AssetPathCollector instances to use to find resources * @param webjarsPackage webjars package path (e.g. "META-INF.resources.webjars") * @param webjarsPath the path where all webjars are stored (e.g. "META-INF/resources/webjars") * @param resourcePattern the pattern to filter accepted webjars resources * @param recentVersionPlaceHolder placeholder for recent version (e.g. current) * @param readFromCacheTimeout timeout which is used when reading from cache (Future.get(timeout)) * @param useCdnResources whether the resources for the webjars should be loaded from a CDN network * @param cdnUrl base URL of the webjars CDN * @return the [WebApplication] the webjar functionality was added to */ fun <A : WebApplication> A.enableWebjars( resourceStreamProvider: ResourceStreamProvider? = null, assetPathCollectors: Array<AssetPathCollector>? = null, webjarsPackage: String? = null, webjarsPath: String? = null, resourcePattern: Pattern? = null, recentVersionPlaceHolder: String? = null, readFromCacheTimeout: Duration? = null, useCdnResources: Boolean? = null, cdnUrl: String? = null ): A { val settings = WebjarsSettings() resourceStreamProvider?.let { settings.resourceStreamProvider(it) } assetPathCollectors?.let { settings.assetPathCollectors(*it) } webjarsPackage?.let { settings.webjarsPackage(it) } webjarsPath?.let { settings.webjarsPath(it) } resourcePattern?.let { settings.resourcePattern(it) } webjarsPath?.let { settings.webjarsPath(it) } recentVersionPlaceHolder?.let { settings.recentVersionPlaceHolder(it) } readFromCacheTimeout?.let { settings.readFromCacheTimeout(it) } useCdnResources?.let { settings.useCdnResources(it) } cdnUrl?.let { settings.cdnUrl(it) } WicketWebjars.install(this, settings) return this }
apache-2.0
SimonVT/cathode
trakt-api/src/main/java/net/simonvt/cathode/api/entity/RatingItem.kt
1
833
/* * Copyright (C) 2014 Simon Vig Therkildsen * * 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 net.simonvt.cathode.api.entity data class RatingItem( val rated_at: IsoTime, val rating: Int, val movie: Movie? = null, val show: Show? = null, val season: Season? = null, val episode: Episode? = null )
apache-2.0
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/dialog/AppLoginDialogFragment.kt
1
2633
package me.ykrank.s1next.view.dialog import android.os.Bundle import com.github.ykrank.androidtools.widget.RxBus import io.reactivex.Single import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.api.app.AppService import me.ykrank.s1next.data.api.app.model.AppDataWrapper import me.ykrank.s1next.data.api.app.model.AppLoginResult import me.ykrank.s1next.view.event.AppLoginEvent import javax.inject.Inject /** * A [ProgressDialogFragment] posts a request to login to server. */ class AppLoginDialogFragment : ProgressDialogFragment<AppDataWrapper<AppLoginResult>>() { @Inject internal lateinit var mAppService: AppService @Inject internal lateinit var mRxBus: RxBus override fun onCreate(savedInstanceState: Bundle?) { App.appComponent.inject(this) super.onCreate(savedInstanceState) } override fun getSourceObservable(): Single<AppDataWrapper<AppLoginResult>> { val username = arguments?.getString(ARG_USERNAME) val password = arguments?.getString(ARG_PASSWORD) val questionId = arguments?.getInt(ARG_QUESTION_ID) val answer = arguments?.getString(ARG_ANSWER) return mAppService.login(username, password, questionId, answer) } override fun onNext(data: AppDataWrapper<AppLoginResult>) { if (data.success) { if (mUserValidator.validateAppLoginInfo(data.data)) { showShortTextAndFinishCurrentActivity(data.message) mRxBus.post(AppLoginEvent()) } else { showToastText(getString(R.string.app_login_info_error)) } } else { showToastText(data.message) } } override fun getProgressMessage(): CharSequence? { return getText(R.string.dialog_progress_message_login) } companion object { val TAG: String = AppLoginDialogFragment::class.java.name private const val ARG_USERNAME = "username" private const val ARG_PASSWORD = "password" private const val ARG_QUESTION_ID = "question_id" private const val ARG_ANSWER = "answer" fun newInstance(username: String, password: String, questionId: Int, answer: String): AppLoginDialogFragment { val fragment = AppLoginDialogFragment() val bundle = Bundle() bundle.putString(ARG_USERNAME, username) bundle.putString(ARG_PASSWORD, password) bundle.putInt(ARG_QUESTION_ID, questionId) bundle.putString(ARG_ANSWER, answer) fragment.arguments = bundle return fragment } } }
apache-2.0
crunchersaspire/worshipsongs-android
app/src/main/java/org/worshipsongs/adapter/TitleAdapter.kt
2
2899
package org.worshipsongs.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import org.worshipsongs.CommonConstants import org.worshipsongs.R import java.util.* /** * Author : Madasamy * Version : 3.x.x */ class TitleAdapter<T>(context: AppCompatActivity, @LayoutRes resource: Int) : ArrayAdapter<T>(context, resource) { private var titleAdapterListener: TitleAdapterListener<T>? = null override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var view = convertView if (view == null) { val layoutInflater = LayoutInflater.from(context) view = layoutInflater.inflate(R.layout.title_row, null) } setViews(view!!, position) return view } private fun setViews(view: View, position: Int) { val maps = HashMap<String, Any>() maps[CommonConstants.TITLE_KEY] = getTitlesView(view) maps[CommonConstants.SUBTITLE_KEY] = getSubtitleTextView(view) maps[CommonConstants.COUNT_KEY] = getCountView(view) maps[CommonConstants.PLAY_IMAGE_KEy] = getPlayImageView(view) maps[CommonConstants.OPTIONS_IMAGE_KEY] = getOptionsImageView(view) maps[CommonConstants.POSITION_KEY] = position maps[CommonConstants.SONG_BOOK_NAME_KEY] = getSongBookNameTextView(view) titleAdapterListener!!.setViews(maps, getItem(position)) } private fun getTitlesView(view: View): TextView { return view.findViewById<View>(R.id.title_text_view) as TextView } private fun getCountView(view: View): TextView { return view.findViewById<View>(R.id.count_text_view) as TextView } private fun getSubtitleTextView(view: View): TextView { return view.findViewById<View>(R.id.subtitle_text_view) as TextView } private fun getPlayImageView(rowView: View): ImageView { return rowView.findViewById<View>(R.id.video_image_view) as ImageView } private fun getOptionsImageView(rowView: View): ImageView { return rowView.findViewById<View>(R.id.option_image_view) as ImageView } private fun getSongBookNameTextView(view: View): TextView { return view.findViewById<View>(R.id.songBookName_text_view) as TextView } fun addObjects(objects: List<T>) { clear() addAll(objects) notifyDataSetChanged() } fun setTitleAdapterListener(titleAdapterListener: TitleAdapterListener<T>) { this.titleAdapterListener = titleAdapterListener } interface TitleAdapterListener<T> { open fun setViews(objects: Map<String, Any>, t: T?) } }
gpl-3.0
PaulWoitaschek/Voice
settings/src/main/kotlin/voice/settings/views/TimeSettingDialog.kt
1
1879
package voice.settings.views import androidx.annotation.PluralsRes import androidx.compose.foundation.layout.Column import androidx.compose.material3.AlertDialog import androidx.compose.material3.Slider import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import voice.settings.R import kotlin.math.roundToInt @Composable // ktlint-disable twitter-compose:modifier-missing-check fun TimeSettingDialog( title: String, currentSeconds: Int, @PluralsRes textPluralRes: Int, minSeconds: Int, maxSeconds: Int, onSecondsConfirmed: (Int) -> Unit, onDismiss: () -> Unit, ) { val sliderValue = remember { mutableStateOf(currentSeconds.toFloat()) } AlertDialog( onDismissRequest = onDismiss, title = { Text(text = title) }, text = { Column { Text( LocalContext.current.resources.getQuantityString( textPluralRes, sliderValue.value.roundToInt(), sliderValue.value.roundToInt(), ), ) Slider( valueRange = minSeconds.toFloat()..maxSeconds.toFloat(), value = sliderValue.value, onValueChange = { sliderValue.value = it }, ) } }, confirmButton = { TextButton( onClick = { onSecondsConfirmed(sliderValue.value.roundToInt()) onDismiss() }, ) { Text(stringResource(R.string.dialog_confirm)) } }, dismissButton = { TextButton( onClick = { onDismiss() }, ) { Text(stringResource(R.string.dialog_cancel)) } }, ) }
gpl-3.0
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration48.kt
1
789
package voice.data.repo.internals.migrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import voice.common.AppScope import javax.inject.Inject @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) class Migration48 @Inject constructor() : IncrementalMigration(48) { override fun migrate(db: SupportSQLiteDatabase) { // there was a bug a in the chapter parsing, trigger a scan. val lastModifiedCv = ContentValues().apply { put("fileLastModified", 0) } db.update("chapters", SQLiteDatabase.CONFLICT_FAIL, lastModifiedCv, null, null) } }
gpl-3.0
borisf/classyshark-bytecode-viewer
src/IncrementalSearch.kt
1
2879
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.awt.Color import java.awt.event.ActionEvent import java.awt.event.ActionListener import java.util.regex.Matcher import java.util.regex.Pattern import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.text.BadLocationException import javax.swing.text.DefaultHighlighter import javax.swing.text.Document import javax.swing.text.JTextComponent class IncrementalSearch(private var content: JTextComponent) : DocumentListener, ActionListener { private var matcher: Matcher? = null override fun insertUpdate(evt: DocumentEvent) { runNewSearch(evt.document) } override fun removeUpdate(evt: DocumentEvent) { runNewSearch(evt.document) } override fun changedUpdate(evt: DocumentEvent) { runNewSearch(evt.document) } override fun actionPerformed(evt: ActionEvent) { continueSearch() } private fun runNewSearch(query_doc: Document) { try { val query = query_doc.getText(0, query_doc.length) val pattern = Pattern.compile(query) val content_doc = content.document val body = content_doc.getText(0, content_doc.length) matcher = pattern.matcher(body) continueSearch() } catch (ex: Exception) { ex.printStackTrace() } } private fun continueSearch() { if (matcher != null) { content.highlighter.removeAllHighlights() while (matcher!!.find()) { val group = matcher!!.group() if (group.length > 1) { content.caret.dot = matcher!!.start() content.caret.moveDot(matcher!!.end()) val highlightPainter = DefaultHighlighter.DefaultHighlightPainter(HIGHLIGHTER_COLOR) try { content.highlighter.addHighlight(matcher!!.start(), matcher!!.end(), highlightPainter) } catch (e: BadLocationException) { e.printStackTrace() } } } } } companion object { private val HIGHLIGHTER_COLOR = Color(71, 86, 89) } }
apache-2.0
clappr/clappr-android
clappr/src/test/kotlin/io/clappr/player/plugin/control/SeekbarPluginTest.kt
1
14103
package io.clappr.player.plugin.control import android.os.Bundle import android.view.MotionEvent import android.view.View import androidx.test.core.app.ApplicationProvider import io.clappr.player.base.* import io.clappr.player.components.Container import io.clappr.player.components.Core import io.clappr.player.components.Playback import io.clappr.player.components.PlaybackSupportCheck import io.clappr.player.plugin.assertHiddenView import io.clappr.player.plugin.assertVisibleView import io.clappr.player.plugin.setupViewVisible import io.clappr.player.shadows.ClapprShadowView import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadow.api.Shadow import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) @Config(sdk = [23], shadows = [ClapprShadowView::class]) class SeekbarPluginTest { private lateinit var core: Core private lateinit var container: Container private lateinit var seekbarPlugin: SeekbarPlugin @Before fun setup() { BaseObject.applicationContext = ApplicationProvider.getApplicationContext() container = Container(Options()) core = Core(Options()) seekbarPlugin = SeekbarPlugin(core) core.activeContainer = container container.playback = FakePlayback() } @Test fun `shouldHave a name`() { assertEquals("seekbar", SeekbarPlugin.name) } @Test fun shouldNotLoadItselfInChromelessMode() { core = Core(Options(options = hashMapOf(ClapprOption.CHROMELESS.value to true))) assertNull(SeekbarPlugin.entry.factory(core)) } @Test fun shouldSetViewTouchListenerWhenRender() { val didTouchSeekbar = performTouchActionOnSeekbar(MotionEvent.ACTION_UP) assertTrue(didTouchSeekbar) } @Test fun shouldUpdateViewVisibilityToGoneWhenRenderIsCalledAndPlaybackIsIdle() { assertViewVisibilityOnRender(Playback.MediaType.VOD, Playback.State.IDLE, View.GONE) } @Test fun shouldUpdateViewVisibilityToGoneWhenRenderIsCalledAndPlaybackIsNone() { assertViewVisibilityOnRender(Playback.MediaType.VOD, Playback.State.NONE, View.GONE) } @Test fun shouldUpdateViewVisibilityToGoneWhenRenderIsCalledAndVideoIsLive() { assertViewVisibilityOnRender(Playback.MediaType.LIVE, Playback.State.PLAYING, View.GONE) } @Test fun shouldUpdateViewVisibilityToGoneWhenRenderIsCalledAndVideoIsUnknown() { assertViewVisibilityOnRender(Playback.MediaType.UNKNOWN, Playback.State.PLAYING, View.GONE) } @Test fun shouldUpdateViewVisibilityToVisibleWhenRenderIsCalledAndVideoIsVOD() { seekbarPlugin.view.visibility = View.GONE assertViewVisibilityOnRender(Playback.MediaType.VOD, Playback.State.PLAYING, View.VISIBLE) } @Test fun shouldTriggerDidUpdateInteractingEventWhenTouchDownEventHappens() { var didUpdateInteractingCalled = false core.listenTo(core, InternalEvent.DID_UPDATE_INTERACTING.value) { didUpdateInteractingCalled = true } val didTouchSeekbar = performTouchActionOnSeekbar(MotionEvent.ACTION_DOWN) assertTrue(didTouchSeekbar) assertTrue(didUpdateInteractingCalled) } @Test fun shouldHideSeekbarWhenDidCompleteEventHappens() { setupViewVisible(seekbarPlugin) core.activePlayback?.trigger(Event.DID_COMPLETE.value) assertHiddenView(seekbarPlugin) } @Test fun shouldUpdatePositionBarViewAndScrubberViewWhenTouchActionDownHappens() { val expectedPositionBarWidth = 50 val expectedScrubberViewX = 46.0f setupViewWidth(500, 8) val didTouchSeekbar = performTouchActionOnSeekbar(MotionEvent.ACTION_DOWN, 50F) assertTrue(didTouchSeekbar) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } @Test fun shouldUpdatePositionBarViewAndScrubberViewWhenTouchActionMoveHappens() { val expectedPositionBarWidth = 100 val expectedScrubberViewX = 96.0f setupViewWidth(500, 8) val didTouchSeekbar = performTouchActionOnSeekbar(MotionEvent.ACTION_MOVE, 100F) assertTrue(didTouchSeekbar) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } @Test fun shouldNotUpdatePositionBarViewAndScrubberViewWhenTouchActionCancelHappens() { assertActionNotUpdateView(MotionEvent.ACTION_CANCEL) } @Test fun shouldNotUpdatePositionBarViewAndScrubberViewWhenTouchActionUpHappens() { assertActionNotUpdateView(MotionEvent.ACTION_UP) } @Test fun shouldUpdateViewVisibilityToGoneWhenUserTouchSeekbarAndPlaybackIsIdle() { assertViewVisibilityWhenTouchEventHappens(View.GONE, Playback.MediaType.VOD, Playback.State.IDLE) } @Test fun shouldUpdateViewVisibilityToGoneWhenUserTouchSeekbarAndPlaybackIsNone() { assertViewVisibilityWhenTouchEventHappens(View.GONE, Playback.MediaType.VOD, Playback.State.NONE) } @Test fun shouldUpdateViewVisibilityToGoneWhenUserTouchSeekbarAndVideoIsLive() { assertViewVisibilityWhenTouchEventHappens(View.GONE, Playback.MediaType.LIVE, Playback.State.PLAYING) } @Test fun shouldUpdateViewVisibilityToGoneWhenUserTouchSeekbarAndVideoIsUnknown() { assertViewVisibilityWhenTouchEventHappens(View.GONE, Playback.MediaType.UNKNOWN, Playback.State.PLAYING) } @Test fun shouldUpdateViewVisibilityToVisibleWhenUserTouchSeekbarAndVideoIsVOD() { assertViewVisibilityWhenTouchEventHappens( View.VISIBLE, Playback.MediaType.VOD, Playback.State.PLAYING, View.GONE) } @Test fun shouldStopListeningOldPlaybackAfterDestroy() { setupViewVisible(seekbarPlugin) val oldPlayback = container.playback seekbarPlugin.destroy() oldPlayback?.trigger(Event.DID_COMPLETE.value) assertVisibleView(seekbarPlugin) } @Test fun shouldRemoveTouchListenerWhenViewIsDestroyed() { val motionEvent = MotionEvent.obtain( 0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0) seekbarPlugin.render() assertTrue(seekbarPlugin.view.dispatchTouchEvent(motionEvent)) seekbarPlugin.destroy() assertFalse(seekbarPlugin.view.dispatchTouchEvent(motionEvent)) } @Test fun shouldUpdateBufferedBarWhenEventHappens() { val expectedBufferedBarWidth = 250 val expectedPercentage = 50.0 val bundle = Bundle().apply { putDouble("percentage", expectedPercentage) } setupViewWidth(500, 8) core.activePlayback?.trigger(Event.DID_UPDATE_BUFFER.value, bundle) assertEquals(expectedBufferedBarWidth, seekbarPlugin.bufferedBar.layoutParams.width) } @Test fun shouldUpdateBufferedBarWithoutBundleWhenEventHappens() { val expectedBufferedBarWidth = 0 setupViewWidth(500, 8) seekbarPlugin.bufferedBar.layoutParams.apply { width = 100 } core.activePlayback?.trigger(Event.DID_UPDATE_BUFFER.value) assertEquals(expectedBufferedBarWidth, seekbarPlugin.bufferedBar.layoutParams.width) } @Test fun shouldSeekWhenStopDrag() { val expectedSeekTime = 60 setupViewWidth(500, 8) setupFakePlayback(duration = 120.0, position = 10.0) performTouchActionOnSeekbar(MotionEvent.ACTION_UP, 250.0f) assertEquals(expectedSeekTime, (container.playback as FakePlayback).seekTime) } @Test fun shouldNotSeekWhenUserStopDragInTheOldPosition() { val expectedSeekTime = 0 setupViewWidth(500, 8) setupFakePlayback(duration = 120.0, position = 60.0) performTouchActionOnSeekbar(MotionEvent.ACTION_UP, 250.0f) assertEquals(expectedSeekTime, (container.playback as FakePlayback).seekTime) } @Test fun shouldUpdateViewsWhenUpdatePositionEventHappens() { val expectedPositionBarWidth = 250 val expectedScrubberViewX = 246.0f val expectedPercentage = 50.0 val bundle = Bundle().apply { putDouble("percentage", expectedPercentage) } setupViewWidth(500, 8) core.activePlayback?.trigger(Event.DID_UPDATE_POSITION.value, bundle) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } @Test fun shouldUpdateViewsWithoutBundleWhenUpdatePositionEventHappens() { val expectedPositionBarWidth = 0 val expectedScrubberViewX = 0f setupViewWidth(500, 8) seekbarPlugin.positionBar.layoutParams.width = 100 seekbarPlugin.scrubberView.x = 100f core.activePlayback?.trigger(Event.DID_UPDATE_POSITION.value) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } @Test fun shouldNotUpdateViewsWhenUpdatePositionEventHappensButUserIsDragging() { val expectedPositionBarWidth = 0 val expectedScrubberViewX = 0f val expectedPercentage = 50.0 val bundle = Bundle().apply { putDouble("percentage", expectedPercentage) } setupViewWidth(500, 8) seekbarPlugin.updateDrag(0.0f) core.activePlayback?.trigger(Event.DID_UPDATE_POSITION.value, bundle) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } @Test fun shouldStopListeningOldPlaybackWhenDidChangePlaybackEventIsTriggered() { val oldPlayback = container.playback assertEquals(View.VISIBLE, seekbarPlugin.view.visibility) container.playback = FakePlayback() oldPlayback?.trigger(Event.DID_COMPLETE.value) assertEquals(View.VISIBLE, seekbarPlugin.view.visibility) } private fun assertViewVisibilityWhenTouchEventHappens( expectedViewVisibility: Int, mediaType: Playback.MediaType, playbackState: Playback.State, currentViewVisibility: Int = View.VISIBLE) { val motionEvent = MotionEvent.obtain( 0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0) seekbarPlugin.render() seekbarPlugin.view.visibility = currentViewVisibility setupFakePlayback(mediaType, playbackState) seekbarPlugin.view.dispatchTouchEvent(motionEvent) assertEquals(expectedViewVisibility, seekbarPlugin.view.visibility) } private fun performTouchActionOnSeekbar(motionAction: Int, touchXPosition: Float = 0F): Boolean { val motionEvent = MotionEvent.obtain( 0, 0, motionAction, touchXPosition, 0.0f, 0) seekbarPlugin.render() return seekbarPlugin.view.dispatchTouchEvent(motionEvent) } private fun assertViewVisibilityOnRender( playbackMediaType: Playback.MediaType, playbackState: Playback.State, expectedViewVisibility: Int) { setupFakePlayback(playbackMediaType, playbackState) seekbarPlugin.render() assertEquals(expectedViewVisibility, seekbarPlugin.view.visibility) } private fun setupViewWidth(backgroundViewWidth: Int, scrubberViewWidth: Int) { (Shadow.extract(seekbarPlugin.backgroundView) as ClapprShadowView).viewWidth = backgroundViewWidth (Shadow.extract(seekbarPlugin.scrubberView) as ClapprShadowView).viewWidth = scrubberViewWidth } private fun assertActionNotUpdateView(event: Int) { val expectedPositionBarWidth = 100 val expectedScrubberViewX = 96.0f setupViewWidth(500, 8) seekbarPlugin.updatePosition(20.0, false) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) val didTouchSeekbar = performTouchActionOnSeekbar(event, 200F) assertTrue(didTouchSeekbar) assertEquals(expectedPositionBarWidth, seekbarPlugin.positionBar.layoutParams.width) assertEquals(expectedScrubberViewX, seekbarPlugin.scrubberView.x) } private fun setupFakePlayback( mediaType: Playback.MediaType = Playback.MediaType.VOD, state: Playback.State = Playback.State.PLAYING, duration: Double = 0.0, position: Double = 0.0) { (container.playback as FakePlayback).apply { currentMediaType = mediaType currentPlaybackState = state currentDuration = duration currentPosition = position } } class FakePlayback(source: String = "aSource", mimeType: String? = null, options: Options = Options()) : Playback(source, mimeType, options, name, supportsSource) { companion object { const val name = "fakePlayback" val supportsSource: PlaybackSupportCheck = { _, _ -> true } } var currentMediaType: MediaType = MediaType.VOD var currentPlaybackState: State = State.PLAYING var currentDuration: Double = 0.0 var currentPosition: Double = 0.0 var seekTime: Int = 0 override val state: State get() = currentPlaybackState override val mediaType: MediaType get() = currentMediaType override val duration: Double get() = currentDuration override val position: Double get() = currentPosition override fun seek(seconds: Int): Boolean { seekTime = seconds return super.seek(seconds) } } }
bsd-3-clause
AgileVentures/MetPlus_resumeCruncher
core/src/main/kotlin/org/metplus/cruncher/resume/ResumeNotFound.kt
1
124
package org.metplus.cruncher.resume import java.lang.Exception class ResumeNotFound(message: String) : Exception(message)
gpl-3.0
FHannes/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/PopupActions.kt
3
13689
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.hints import com.intellij.codeInsight.CodeInsightBundle import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.ParameterHintsPresentationManager import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.codeInsight.hints.settings.Diff import com.intellij.codeInsight.hints.settings.ParameterNameHintsConfigurable import com.intellij.codeInsight.hints.settings.ParameterNameHintsSettings import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.injected.editor.EditorWindow import com.intellij.lang.Language import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.PsiTreeUtil class ShowSettingsWithAddedPattern : AnAction() { init { templatePresentation.description = CodeInsightBundle.message("inlay.hints.show.settings.description") templatePresentation.text = CodeInsightBundle.message("inlay.hints.show.settings", "_") } override fun update(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) ?: return val text = when (info) { is HintInfo.OptionInfo -> "Show Hints Settings..." is HintInfo.MethodInfo -> CodeInsightBundle.message("inlay.hints.show.settings", info.getMethodName()) } e.presentation.setText(text, false) } override fun actionPerformed(e: AnActionEvent) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val language = file.language.baseLanguage ?: file.language InlayParameterHintsExtension.forLanguage(language) ?: return val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) ?: return val newPreselectedPattern = when (info) { is HintInfo.OptionInfo -> null is HintInfo.MethodInfo -> info.toPattern() } val dialog = ParameterNameHintsConfigurable(language, newPreselectedPattern) dialog.show() } } class BlacklistCurrentMethodIntention : IntentionAction, HighPriorityAction { companion object { private val presentableText = CodeInsightBundle.message("inlay.hints.blacklist.method") private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } override fun getText(): String = presentableText override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { val language = file.language val hintsProvider = InlayParameterHintsExtension.forLanguage(language) ?: return false return hintsProvider.isBlackListSupported && hasEditorParameterHintAtOffset(editor, file) && isMethodHintAtOffset(editor, file) } private fun isMethodHintAtOffset(editor: Editor, file: PsiFile): Boolean { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) is MethodInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val offset = editor.caretModel.offset val info = getHintInfoFromProvider(offset, file, editor) as? MethodInfo ?: return ParameterNameHintsSettings.getInstance().addIgnorePattern(file.language, info.toPattern()) refreshAllOpenEditors() showHint(project, file, info) } private fun showHint(project: Project, file: PsiFile, info: MethodInfo) { val methodName = info.getMethodName() val language = file.language val listener = NotificationListener { notification, event -> when (event.description) { "settings" -> showSettings(language) "undo" -> undo(language, info) } notification.expire() } val notification = Notification("Parameter Name Hints", "Method \"$methodName\" added to blacklist", "<html><a href='settings'>Show Parameter Hints Settings</a> or <a href='undo'>Undo</a></html>", NotificationType.INFORMATION, listener) notification.notify(project) } private fun showSettings(language: Language) { val dialog = ParameterNameHintsConfigurable(language, null) dialog.show() } private fun undo(language: Language, info: MethodInfo) { val settings = ParameterNameHintsSettings.getInstance() val diff = settings.getBlackListDiff(language) val updated = diff.added.toMutableSet().apply { remove(info.toPattern()) } settings.setBlackListDiff(language, Diff(updated, diff.removed)) refreshAllOpenEditors() } override fun startInWriteAction() = false } class DisableCustomHintsOption: IntentionAction, HighPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String = getIntentionText() private fun getIntentionText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return "Do not ${lastOptionName.toLowerCase()}" } return CodeInsightBundle.message("inlay.hints.disable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { InlayParameterHintsExtension.forLanguage(file.language) ?: return false if (!hasEditorParameterHintAtOffset(editor, file)) return false val option = getOptionHintAtOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getOptionHintAtOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset return getHintInfoFromProvider(offset, file, editor) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getOptionHintAtOffset(editor, file) ?: return option.disable() refreshAllOpenEditors() } override fun startInWriteAction() = false } class EnableCustomHintsOption: IntentionAction, HighPriorityAction { companion object { private val presentableFamilyName = CodeInsightBundle.message("inlay.hints.intention.family.name") } private var lastOptionName = "" override fun getText(): String { if (lastOptionName.startsWith("show", ignoreCase = true)) { return lastOptionName.capitalizeFirstLetter() } return CodeInsightBundle.message("inlay.hints.enable.custom.option", lastOptionName) } override fun getFamilyName(): String = presentableFamilyName override fun isAvailable(project: Project, editor: Editor, file: PsiFile): Boolean { if (!EditorSettingsExternalizable.getInstance().isShowParameterNameHints) return false if (editor !is EditorImpl) return false InlayParameterHintsExtension.forLanguage(file.language) ?: return false val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return false lastOptionName = option.optionName return true } private fun getDisabledOptionInfoAtCaretOffset(editor: Editor, file: PsiFile): HintInfo.OptionInfo? { val offset = editor.caretModel.offset val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val target = PsiTreeUtil.findFirstParent(element, { provider.hasDisabledOptionHintInfo(it) }) ?: return null return provider.getHintInfo(target) as? HintInfo.OptionInfo } override fun invoke(project: Project, editor: Editor, file: PsiFile) { val option = getDisabledOptionInfoAtCaretOffset(editor, file) ?: return option.enable() refreshAllOpenEditors() } override fun startInWriteAction() = false } private fun InlayParameterHintsProvider.hasDisabledOptionHintInfo(element: PsiElement): Boolean { val info = getHintInfo(element) return info is HintInfo.OptionInfo && !info.isOptionEnabled() } class ToggleInlineHintsAction : AnAction() { companion object { private val disableText = CodeInsightBundle.message("inlay.hints.disable.action.text").capitalize() private val enableText = CodeInsightBundle.message("inlay.hints.enable.action.text").capitalize() } override fun update(e: AnActionEvent) { if (!InlayParameterHintsExtension.hasAnyExtensions()) { e.presentation.isEnabledAndVisible = false return } val isHintsShownNow = EditorSettingsExternalizable.getInstance().isShowParameterNameHints e.presentation.text = if (isHintsShownNow) disableText else enableText e.presentation.isEnabledAndVisible = true if (isInMainEditorPopup(e)) { val file = CommonDataKeys.PSI_FILE.getData(e.dataContext) ?: return val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return val caretOffset = editor.caretModel.offset e.presentation.isEnabledAndVisible = !isHintsShownNow && isPossibleHintNearOffset(file, caretOffset) } } private fun isInMainEditorPopup(e: AnActionEvent): Boolean { if (e.place != ActionPlaces.EDITOR_POPUP) return false val editor = CommonDataKeys.EDITOR.getData(e.dataContext) ?: return false val offset = editor.caretModel.offset return !editor.inlayModel.hasInlineElementAt(offset) } override fun actionPerformed(e: AnActionEvent) { val settings = EditorSettingsExternalizable.getInstance() val before = settings.isShowParameterNameHints settings.isShowParameterNameHints = !before refreshAllOpenEditors() } } private fun hasEditorParameterHintAtOffset(editor: Editor, file: PsiFile): Boolean { if (editor is EditorWindow) return false val offset = editor.caretModel.offset val element = file.findElementAt(offset) val startOffset = element?.textRange?.startOffset ?: offset val endOffset = element?.textRange?.endOffset ?: offset return editor.inlayModel .getInlineElementsInRange(startOffset, endOffset) .find { ParameterHintsPresentationManager.getInstance().isParameterHint(it) } != null } private fun refreshAllOpenEditors() { ParameterHintsPassFactory.forceHintsUpdateOnNextPass(); ProjectManager.getInstance().openProjects.forEach { val psiManager = PsiManager.getInstance(it) val daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(it) val fileEditorManager = FileEditorManager.getInstance(it) fileEditorManager.selectedFiles.forEach { psiManager.findFile(it)?.let { daemonCodeAnalyzer.restart(it) } } } } private fun getHintInfoFromProvider(offset: Int, file: PsiFile, editor: Editor): HintInfo? { val element = file.findElementAt(offset) ?: return null val provider = InlayParameterHintsExtension.forLanguage(file.language) ?: return null val isHintOwnedByElement: (PsiElement) -> Boolean = { e -> provider.getHintInfo(e) != null && e.isOwnsInlayInEditor(editor) } val method = PsiTreeUtil.findFirstParent(element, isHintOwnedByElement) ?: return null return provider.getHintInfo(method) } fun PsiElement.isOwnsInlayInEditor(editor: Editor): Boolean { if (textRange == null) return false val start = if (textRange.isEmpty) textRange.startOffset else textRange.startOffset + 1 return !editor.inlayModel.getInlineElementsInRange(start, textRange.endOffset).isEmpty() } fun isPossibleHintNearOffset(file: PsiFile, offset: Int): Boolean { val hintProvider = InlayParameterHintsExtension.forLanguage(file.language) ?: return false var element = file.findElementAt(offset) for (i in 0..3) { if (element == null) return false val hints = hintProvider.getParameterHints(element) if (hints.isNotEmpty()) return true element = element.parent } return false } fun MethodInfo.toPattern() = this.fullyQualifiedName + '(' + this.paramNames.joinToString(",") + ')' private fun String.capitalize() = StringUtil.capitalizeWords(this, true) private fun String.capitalizeFirstLetter() = StringUtil.capitalize(this)
apache-2.0
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/video/VideoPlayerActivity.kt
1
114200
/***************************************************************************** * VideoPlayerActivity.java * * Copyright © 2011-2017 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.video import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Activity import android.app.KeyguardManager import android.app.PictureInPictureParams import android.bluetooth.BluetoothA2dp import android.bluetooth.BluetoothHeadset import android.content.* import android.content.pm.ActivityInfo import android.content.res.Configuration import android.media.AudioManager import android.net.Uri import android.os.* import android.support.v4.media.session.PlaybackStateCompat import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.util.DisplayMetrics import android.util.Log import android.util.Rational import android.view.* import android.view.View.OnClickListener import android.view.View.OnLongClickListener import android.view.ViewGroup.LayoutParams import android.view.animation.* import android.widget.* import android.widget.SeekBar.OnSeekBarChangeListener import androidx.annotation.StringRes import androidx.annotation.WorkerThread import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources import androidx.appcompat.widget.PopupMenu import androidx.appcompat.widget.ViewStubCompat import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.constraintlayout.widget.Guideline import androidx.databinding.BindingAdapter import androidx.databinding.DataBindingUtil import androidx.fragment.app.DialogFragment import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat import com.google.android.material.textfield.TextInputLayout import kotlinx.coroutines.* import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.videolan.libvlc.MediaPlayer import org.videolan.libvlc.RendererItem import org.videolan.libvlc.interfaces.IMedia import org.videolan.libvlc.util.AndroidUtil import org.videolan.libvlc.util.DisplayManager import org.videolan.libvlc.util.VLCVideoLayout import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.Tools import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.resources.* import org.videolan.tools.* import org.videolan.vlc.* import org.videolan.vlc.BuildConfig import org.videolan.vlc.R import org.videolan.vlc.databinding.PlayerHudBinding import org.videolan.vlc.databinding.PlayerHudRightBinding import org.videolan.vlc.gui.audio.EqualizerFragment import org.videolan.vlc.gui.audio.PlaylistAdapter import org.videolan.vlc.gui.browser.EXTRA_MRL import org.videolan.vlc.gui.browser.FilePickerActivity import org.videolan.vlc.gui.dialogs.RenderersDialog import org.videolan.vlc.gui.helpers.* import org.videolan.vlc.gui.helpers.hf.StoragePermissionsDelegate import org.videolan.vlc.interfaces.IPlaybackSettingsController import org.videolan.vlc.media.MediaUtils import org.videolan.vlc.repository.ExternalSubRepository import org.videolan.vlc.repository.SlaveRepository import org.videolan.vlc.util.FileUtils import org.videolan.vlc.util.Permissions import org.videolan.vlc.util.Util import org.videolan.vlc.viewmodels.PlaylistModel import java.lang.Runnable import kotlin.math.roundToInt @Suppress("DEPRECATION") @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi open class VideoPlayerActivity : AppCompatActivity(), PlaybackService.Callback, PlaylistAdapter.IPlayer, OnClickListener, OnLongClickListener, StoragePermissionsDelegate.CustomActionController, TextWatcher { private lateinit var startedScope : CoroutineScope private var wasPlaying = true var service: PlaybackService? = null private lateinit var medialibrary: Medialibrary private var videoLayout: VLCVideoLayout? = null lateinit var displayManager: DisplayManager private var rootView: View? = null private var videoUri: Uri? = null private var askResume = true private lateinit var closeButton: View private lateinit var playlistContainer: View private lateinit var playlist: RecyclerView private lateinit var playlistSearchText: TextInputLayout private lateinit var playlistAdapter: PlaylistAdapter private var playlistModel: PlaylistModel? = null private lateinit var abRepeatAddMarker: Button private lateinit var settings: SharedPreferences /** Overlay */ private var overlayBackground: View? = null private var isDragging: Boolean = false internal var isShowing: Boolean = false private set private var isShowingDialog: Boolean = false var info: TextView? = null var overlayInfo: View? = null var verticalBar: View? = null private lateinit var verticalBarProgress: View private lateinit var verticalBarBoostProgress: View internal var isLoading: Boolean = false private set private var isPlaying = false private var loadingImageView: ImageView? = null private var navMenu: ImageView? = null private var rendererBtn: ImageView? = null protected var enableCloneMode: Boolean = false private var screenOrientation: Int = 0 private var screenOrientationLock: Int = 0 private var currentScreenOrientation: Int = 0 private var currentAudioTrack = -2 private var currentSpuTrack = -2 internal var isLocked = false private set /* -1 is a valid track (Disable) */ private var lastAudioTrack = -2 private var lastSpuTrack = -2 private var overlayTimeout = 0 private var lockBackButton = false private var wasPaused = false private var savedTime: Long = -1 /** * For uninterrupted switching between audio and video mode */ private var switchingView: Boolean = false private var switchToPopup: Boolean = false //Volume internal lateinit var audiomanager: AudioManager private set internal var audioMax: Int = 0 private set internal var isAudioBoostEnabled: Boolean = false private set private var isMute = false private var volSave: Int = 0 internal var volume: Float = 0.toFloat() internal var originalVol: Float = 0.toFloat() private var warningToast: Toast? = null internal var fov: Float = 0.toFloat() lateinit var touchDelegate: VideoTouchDelegate private val statsDelegate: VideoStatsDelegate by lazy(LazyThreadSafetyMode.NONE) { VideoStatsDelegate(this, { showOverlayTimeout(OVERLAY_INFINITE) }, { showOverlay(true) }) } val delayDelegate: VideoDelayDelegate by lazy(LazyThreadSafetyMode.NONE) { VideoDelayDelegate(this@VideoPlayerActivity) } private var isTv: Boolean = false // Tracks & Subtitles private var audioTracksList: Array<MediaPlayer.TrackDescription>? = null private var videoTracksList: Array<MediaPlayer.TrackDescription>? = null private var subtitleTracksList: Array<MediaPlayer.TrackDescription>? = null /** * Flag to indicate whether the media should be paused once loaded * (e.g. lock screen, or to restore the pause state) */ private var playbackStarted = false // Tips private var overlayTips: View? = null // Navigation handling (DVD, Blu-Ray...) private var menuIdx = -1 private var isNavMenu = false /* for getTime and seek */ private var forcedTime: Long = -1 private var lastTime: Long = -1 private var alertDialog: AlertDialog? = null protected var isBenchmark = false private val addedExternalSubs = ArrayList<org.videolan.vlc.mediadb.models.ExternalSub>() private var downloadedSubtitleLiveData: LiveData<List<org.videolan.vlc.mediadb.models.ExternalSub>>? = null private var previousMediaPath: String? = null private val isInteractive: Boolean @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) get() { val pm = applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager return if (AndroidUtil.isLolliPopOrLater) pm.isInteractive else pm.isScreenOn } private val playlistObserver = Observer<List<MediaWrapper>> { mediaWrappers -> if (mediaWrappers != null) playlistAdapter.update(mediaWrappers) } private var addNextTrack = false private lateinit var playToPause: AnimatedVectorDrawableCompat private lateinit var pauseToPlay: AnimatedVectorDrawableCompat internal val isPlaybackSettingActive: Boolean get() = delayDelegate.playbackSetting != IPlaybackSettingsController.DelayState.OFF /** * Handle resize of the surface and the overlay */ val handler: Handler = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { service?.run { when (msg.what) { FADE_OUT -> hideOverlay(false) FADE_OUT_INFO -> fadeOutInfo() START_PLAYBACK -> startPlayback() AUDIO_SERVICE_CONNECTION_FAILED -> exit(RESULT_CONNECTION_FAILED) RESET_BACK_LOCK -> lockBackButton = true CHECK_VIDEO_TRACKS -> if (videoTracksCount < 1 && audioTracksCount > 0) { Log.i(TAG, "No video track, open in audio mode") switchToAudioMode(true) } else { } LOADING_ANIMATION -> startLoading() HIDE_INFO -> hideOverlay(true) SHOW_INFO -> showOverlay() HIDE_SEEK -> touchDelegate.hideSeekOverlay() HIDE_SETTINGS -> delayDelegate.endPlaybackSetting() else -> {} } } } } private val switchAudioRunnable = Runnable { if (displayManager.isPrimary && service?.hasMedia() == true && service?.videoTracksCount == 0) { Log.i(TAG, "Video track lost, switching to audio") switchingView = true exit(RESULT_VIDEO_TRACK_LOST) } } /** * handle changes of the seekbar (slicer) */ private val seekListener = object : OnSeekBarChangeListener { override fun onStartTrackingTouch(seekBar: SeekBar) { isDragging = true showOverlayTimeout(OVERLAY_INFINITE) } override fun onStopTrackingTouch(seekBar: SeekBar) { isDragging = false showOverlay(true) } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (!isFinishing && fromUser && service?.isSeekable == true) { seek(progress.toLong()) showInfo(Tools.millisToString(progress.toLong()), 1000) } if (fromUser) { showOverlay(true) } } } internal val isOnPrimaryDisplay: Boolean get() = displayManager.isPrimary val currentScaleType: MediaPlayer.ScaleType get() = service?.mediaplayer?.videoScale ?: MediaPlayer.ScaleType.SURFACE_BEST_FIT private val isOptionsListShowing: Boolean get() = optionsDelegate?.isShowing() == true /* XXX: After a seek, playbackService.getTime can return the position before or after * the seek position. Therefore we return forcedTime in order to avoid the seekBar * to move between seek position and the actual position. * We have to wait for a valid position (that is after the seek position). * to re-init lastTime and forcedTime to -1 and return the actual position. */ val time: Long get() { var time = service?.time ?: 0L if (forcedTime != -1L && lastTime != -1L) { if (lastTime > forcedTime) { if (time in (forcedTime + 1)..lastTime || time > lastTime) { forcedTime = -1 lastTime = forcedTime } } else { if (time > forcedTime) { forcedTime = -1 lastTime = forcedTime } } } else if (time == 0L) service?.currentMediaWrapper?.time?.let { time = it } return if (forcedTime == -1L) time else forcedTime } private lateinit var hudBinding: PlayerHudBinding private lateinit var hudRightBinding: PlayerHudRightBinding private var seekButtons: Boolean = false private var hasPlaylist: Boolean = false private var enableSubs = true private val downloadedSubtitleObserver = Observer<List<org.videolan.vlc.mediadb.models.ExternalSub>> { externalSubs -> for (externalSub in externalSubs) { if (!addedExternalSubs.contains(externalSub)) { service?.addSubtitleTrack(externalSub.subtitlePath, currentSpuTrack == -2) addedExternalSubs.add(externalSub) } } } private val screenRotation: Int get() { val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager return wm.defaultDisplay?.rotation ?: Surface.ROTATION_0 } private var optionsDelegate: PlayerOptionsDelegate? = null val isPlaylistVisible: Boolean get() = playlistContainer.visibility == View.VISIBLE private val btReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent?) { if (intent == null) return service?.let { service -> when (intent.action) { BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED, BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> { val savedDelay = settings.getLong(KEY_BLUETOOTH_DELAY, 0L) val currentDelay = service.audioDelay if (savedDelay != 0L) { val connected = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1) == BluetoothA2dp.STATE_CONNECTED if (connected && currentDelay == 0L) toggleBtDelay(true) else if (!connected && savedDelay == currentDelay) toggleBtDelay(false) } } } } } } private val serviceReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == PLAY_FROM_SERVICE) onNewIntent(intent) else if (intent.action == EXIT_PLAYER) exitOK() } } override fun attachBaseContext(newBase: Context?) { super.attachBaseContext(newBase?.getContextWithLocale(AppContextProvider.locale)) } override fun getApplicationContext(): Context { return super.getApplicationContext().getContextWithLocale(AppContextProvider.locale) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Util.checkCpuCompatibility(this) settings = Settings.getInstance(this) /* Services and miscellaneous */ audiomanager = applicationContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager audioMax = audiomanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) isAudioBoostEnabled = settings.getBoolean("audio_boost", true) enableCloneMode = clone ?: settings.getBoolean("enable_clone_mode", false) displayManager = DisplayManager(this, PlaybackService.renderer, false, enableCloneMode, isBenchmark) setContentView(if (displayManager.isPrimary) R.layout.player else R.layout.player_remote_control) rootView = findViewById(R.id.player_root) playlist = findViewById(R.id.video_playlist) playlistSearchText = findViewById(R.id.playlist_search_text) playlistContainer = findViewById(R.id.video_playlist_container) closeButton = findViewById(R.id.close_button) playlistSearchText.editText?.addTextChangedListener(this) screenOrientation = Integer.valueOf( settings.getString(SCREEN_ORIENTATION, "99" /*SCREEN ORIENTATION SENSOR*/)!!) videoLayout = findViewById(R.id.video_layout) /* Loading view */ loadingImageView = findViewById(R.id.player_overlay_loading) dimStatusBar(true) handler.sendEmptyMessageDelayed(LOADING_ANIMATION, LOADING_ANIMATION_DELAY.toLong()) switchingView = false askResume = settings.getString(KEY_VIDEO_CONFIRM_RESUME, "0") == "2" sDisplayRemainingTime = settings.getBoolean(KEY_REMAINING_TIME_DISPLAY, false) // Clear the resume time, since it is only used for resumes in external // videos. settings.putSingle(VIDEO_RESUME_TIME, -1L) // Paused flag - per session too, like the subs list. this.volumeControlStream = AudioManager.STREAM_MUSIC // 100 is the value for screen_orientation_start_lock try { requestedOrientation = getScreenOrientation(screenOrientation) } catch (ignored: IllegalStateException) { Log.w(TAG, "onCreate: failed to set orientation") } // Extra initialization when no secondary display is detected isTv = Settings.showTvUi if (displayManager.isPrimary) { // Orientation // Tips if (!BuildConfig.DEBUG && !isTv && !settings.getBoolean(PREF_TIPS_SHOWN, false) && !isBenchmark) { (findViewById<View>(R.id.player_overlay_tips) as ViewStubCompat).inflate() overlayTips = findViewById(R.id.overlay_tips_layout) } } medialibrary = Medialibrary.getInstance() val touch = if (!isTv) { val audioTouch = (!AndroidUtil.isLolliPopOrLater || !audiomanager.isVolumeFixed) && settings.getBoolean(ENABLE_VOLUME_GESTURE, true) val brightnessTouch = !AndroidDevices.isChromeBook && settings.getBoolean(ENABLE_BRIGHTNESS_GESTURE, true) ((if (audioTouch) TOUCH_FLAG_AUDIO_VOLUME else 0) + (if (brightnessTouch) TOUCH_FLAG_BRIGHTNESS else 0) + if (settings.getBoolean(ENABLE_DOUBLE_TAP_SEEK, true)) TOUCH_FLAG_SEEK else 0) } else 0 currentScreenOrientation = resources.configuration.orientation val dm = DisplayMetrics() windowManager.defaultDisplay.getMetrics(dm) val yRange = Math.min(dm.widthPixels, dm.heightPixels) val xRange = Math.max(dm.widthPixels, dm.heightPixels) val sc = ScreenConfig(dm, xRange, yRange, currentScreenOrientation) touchDelegate = VideoTouchDelegate(this, touch, sc, isTv) UiTools.setRotationAnimation(this) if (savedInstanceState != null) { savedTime = savedInstanceState.getLong(KEY_TIME) val list = savedInstanceState.getBoolean(KEY_LIST, false) if (list) { intent.removeExtra(PLAY_EXTRA_ITEM_LOCATION) } else { videoUri = savedInstanceState.getParcelable<Parcelable>(KEY_URI) as Uri? } } playToPause = AnimatedVectorDrawableCompat.create(this, R.drawable.anim_play_pause)!! pauseToPlay = AnimatedVectorDrawableCompat.create(this, R.drawable.anim_pause_play)!! } override fun afterTextChanged(s: Editable?) { } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s == null) return val length = s.length if (length > 0) { playlistModel?.filter(s) } else { playlistModel?.filter(null) } } private fun hideSearchField(): Boolean { if (playlistSearchText.visibility != View.VISIBLE) return false playlistSearchText.editText?.apply { removeTextChangedListener(this@VideoPlayerActivity) setText("") addTextChangedListener(this@VideoPlayerActivity) } UiTools.setKeyboardVisibility(playlistSearchText, false) return true } override fun onResume() { overridePendingTransition(0, 0) super.onResume() isShowingDialog = false /* * Set listeners here to avoid NPE when activity is closing */ setListeners(true) if (isLocked && screenOrientation == 99) requestedOrientation = screenOrientationLock } private fun setListeners(enabled: Boolean) { navMenu?.setOnClickListener(if (enabled) this else null) if (::hudBinding.isInitialized) { hudBinding.playerOverlaySeekbar.setOnSeekBarChangeListener(if (enabled) seekListener else null) hudBinding.orientationToggle.setOnClickListener(if (enabled) this else null) hudBinding.orientationToggle.setOnLongClickListener(if (enabled) this else null) abRepeatAddMarker.setOnClickListener(this) } if (::hudRightBinding.isInitialized) { hudRightBinding.abRepeatReset.setOnClickListener(this) hudRightBinding.abRepeatStop.setOnClickListener(this) } UiTools.setViewOnClickListener(rendererBtn, if (enabled) this else null) } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) if (playbackStarted) service?.run { if (::hudBinding.isInitialized) { hudRightBinding.playerOverlayTitle.text = currentMediaWrapper?.title ?: return@run } var uri: Uri? = if (intent.hasExtra(PLAY_EXTRA_ITEM_LOCATION)) { intent.extras?.getParcelable<Parcelable>(PLAY_EXTRA_ITEM_LOCATION) as Uri? } else intent.data if (uri == null || uri == videoUri) return if (TextUtils.equals("file", uri.scheme) && uri.path?.startsWith("/sdcard") == true) { val convertedUri = FileUtils.convertLocalUri(uri) if (convertedUri == videoUri) return else uri = convertedUri } videoUri = uri if (isPlaylistVisible) { playlistAdapter.currentIndex = currentMediaPosition playlistContainer.setGone() } if (settings.getBoolean("video_transition_show", true)) showTitle() initUI() lastTime = -1 forcedTime = lastTime enableSubs() } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) override fun onPause() { val finishing = isFinishing if (finishing) overridePendingTransition(0, 0) else hideOverlay(true) super.onPause() setListeners(false) /* Stop the earliest possible to avoid vout error */ if (!isInPictureInPictureMode && (finishing || (AndroidUtil.isNougatOrLater && !AndroidUtil.isOOrLater //Video on background on Nougat Android TVs && AndroidDevices.isAndroidTv && !requestVisibleBehind(true)))) stopPlayback() } @TargetApi(Build.VERSION_CODES.O) override fun onUserLeaveHint() { if (!isInPictureInPictureMode && displayManager.isPrimary && !isShowingDialog && "2" == settings.getString(KEY_VIDEO_APP_SWITCH, "0") && isInteractive && service?.hasRenderer() == false) switchToPopup() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (videoUri != null && "content" != videoUri?.scheme) { outState.putLong(KEY_TIME, savedTime) if (playlistModel == null) outState.putParcelable(KEY_URI, videoUri) } videoUri = null outState.putBoolean(KEY_LIST, hasPlaylist) } @TargetApi(Build.VERSION_CODES.O) fun switchToPopup() { if (isBenchmark) return optionsDelegate?.hide() //look for dialogs and close them supportFragmentManager.fragments.forEach { (it as? DialogFragment)?.dismiss() } val mw = service?.currentMediaWrapper if (mw == null || !AndroidDevices.pipAllowed || !isStarted()) return val forceLegacy = Settings.getInstance(this).getBoolean(POPUP_FORCE_LEGACY, false) if (AndroidDevices.hasPiP && !forceLegacy) { if (AndroidUtil.isOOrLater) try { val track = service?.playlistManager?.player?.mediaplayer?.currentVideoTrack ?: return val ar = Rational(track.width.coerceAtMost((track.height * 2.39f).toInt()), track.height) enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(ar).build()) } catch (e: IllegalArgumentException) { // Fallback with default parameters enterPictureInPictureMode() } else enterPictureInPictureMode() } else { if (Permissions.canDrawOverlays(this)) { switchingView = true switchToPopup = true if (service?.isPlaying != true) mw.addFlags(MediaWrapper.MEDIA_PAUSED) cleanUI() exitOK() } else Permissions.checkDrawOverlaysPermission(this) } } override fun onVisibleBehindCanceled() { super.onVisibleBehindCanceled() stopPlayback() exitOK() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) currentScreenOrientation = newConfig.orientation if (touchDelegate != null) { val dm = DisplayMetrics() windowManager.defaultDisplay.getMetrics(dm) val sc = ScreenConfig(dm, Math.max(dm.widthPixels, dm.heightPixels), Math.min(dm.widthPixels, dm.heightPixels), currentScreenOrientation) touchDelegate.screenConfig = sc } resetHudLayout() showControls(isShowing) statsDelegate.onConfigurationChanged() } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) fun resetHudLayout() { if (!::hudBinding.isInitialized) return if (!isTv && !AndroidDevices.isChromeBook) { hudBinding.orientationToggle.setVisible() hudBinding.lockOverlayButton.setVisible() } } override fun onStart() { medialibrary.pauseBackgroundOperations() super.onStart() startedScope = MainScope() PlaybackService.start(this) PlaybackService.serviceFlow.onEach { onServiceChanged(it) }.launchIn(startedScope) restoreBrightness() val filter = IntentFilter(PLAY_FROM_SERVICE) filter.addAction(EXIT_PLAYER) LocalBroadcastManager.getInstance(this).registerReceiver( serviceReceiver, filter) val btFilter = IntentFilter(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED) btFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED) registerReceiver(btReceiver, btFilter) overlayInfo.setInvisible() } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) override fun onStop() { super.onStop() startedScope.cancel() LocalBroadcastManager.getInstance(this).unregisterReceiver(serviceReceiver) unregisterReceiver(btReceiver) alertDialog?.dismiss() if (displayManager.isPrimary && !isFinishing && service?.isPlaying == true && "1" == settings.getString(KEY_VIDEO_APP_SWITCH, "0")) { switchToAudioMode(false) } cleanUI() stopPlayback() if (savedTime != -1L) settings.putSingle(VIDEO_RESUME_TIME, savedTime) saveBrightness() service?.removeCallback(this) service = null // Clear Intent to restore playlist on activity restart intent = Intent() handler.removeCallbacksAndMessages(null) removeDownloadedSubtitlesObserver() previousMediaPath = null addedExternalSubs.clear() medialibrary.resumeBackgroundOperations() service?.playlistManager?.videoStatsOn?.postValue(false) } private fun saveBrightness() { // Save brightness if user wants to if (settings.getBoolean(SAVE_BRIGHTNESS, false)) { val brightness = window.attributes.screenBrightness if (brightness != -1f) settings.putSingle(BRIGHTNESS_VALUE, brightness) } } private fun restoreBrightness() { if (settings.getBoolean(SAVE_BRIGHTNESS, false)) { val brightness = settings.getFloat(BRIGHTNESS_VALUE, -1f) if (brightness != -1f) setWindowBrightness(brightness) } } override fun onDestroy() { super.onDestroy() playlistModel?.run { dataset.removeObserver(playlistObserver) onCleared() } // Dismiss the presentation when the activity is not visible. displayManager.release() } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private fun startPlayback() { /* start playback only when audio service and both surfaces are ready */ if (playbackStarted) return service?.run { playbackStarted = true val vlcVout = vout if (vlcVout != null && vlcVout.areViewsAttached()) { if (isPlayingPopup) { stop(video = true) } else vlcVout.detachViews() } val mediaPlayer = mediaplayer if (!displayManager.isOnRenderer) videoLayout?.let { mediaPlayer.attachViews(it, displayManager, true, false) val size = if (isBenchmark) MediaPlayer.ScaleType.SURFACE_FILL else MediaPlayer.ScaleType.values()[settings.getInt(VIDEO_RATIO, MediaPlayer.ScaleType.SURFACE_BEST_FIT.ordinal)] mediaPlayer.videoScale = size } initUI() loadMedia() } } private fun initPlaylistUi() { if (service?.hasPlaylist() == true) { if (!::playlistAdapter.isInitialized) { playlistAdapter = PlaylistAdapter(this) val layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) playlist.layoutManager = layoutManager } if (playlistModel == null) { playlistModel = ViewModelProviders.of(this).get(PlaylistModel::class.java).apply { playlistAdapter.setModel(this) dataset.observe(this@VideoPlayerActivity, playlistObserver) } } hudRightBinding.playlistToggle.setVisible() if (::hudBinding.isInitialized) { hudBinding.playlistPrevious.setVisible() hudBinding.playlistNext.setVisible() } hudRightBinding.playlistToggle.setOnClickListener(this@VideoPlayerActivity) closeButton.setOnClickListener { togglePlaylist() } val callback = SwipeDragItemTouchHelperCallback(playlistAdapter, true) val touchHelper = ItemTouchHelper(callback) touchHelper.attachToRecyclerView(playlist) } } private fun initUI() { /* Listen for changes to media routes. */ if (!isBenchmark) displayManager.setMediaRouterCallback() rootView?.run { keepScreenOn = true } } private fun setPlaybackParameters() { service?.run { if (audioDelay != 0L && audioDelay != audioDelay) setAudioDelay(audioDelay) else if (audiomanager.isBluetoothA2dpOn || audiomanager.isBluetoothScoOn) toggleBtDelay(true) if (spuDelay != 0L && spuDelay != spuDelay) setSpuDelay(spuDelay) } } private fun stopPlayback() { if (!playbackStarted) return if (!displayManager.isPrimary && !isFinishing || service == null) { playbackStarted = false return } service?.run { val tv = Settings.showTvUi val interactive = isInteractive wasPaused = !isPlaying || (!tv && !interactive) if (wasPaused) settings.putSingle(VIDEO_PAUSED, true) if (!isFinishing) { currentAudioTrack = audioTrack currentSpuTrack = spuTrack if (tv) finish() // Leave player on TV, restauration can be difficult } if (isMute) mute(false) playbackStarted = false handler.removeCallbacksAndMessages(null) if (hasMedia() && switchingView) { if (BuildConfig.DEBUG) Log.d(TAG, "mLocation = \"$videoUri\"") if (switchToPopup) switchToPopup(currentMediaPosition) else { currentMediaWrapper?.addFlags(MediaWrapper.MEDIA_FORCE_AUDIO) showWithoutParse(currentMediaPosition) } return } if (isSeekable) { savedTime = time val length = length //remove saved position if in the last 5 seconds if (length - savedTime < 5000) savedTime = 0 else savedTime -= 2000 // go back 2 seconds, to compensate loading time } stop(video = true) } } private fun cleanUI() { rootView?.run { keepScreenOn = false } /* Stop listening for changes to media routes. */ if (!isBenchmark) displayManager.removeMediaRouterCallback() if (!displayManager.isSecondary) service?.mediaplayer?.detachViews() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data == null) return if (data.hasExtra(EXTRA_MRL)) { service?.addSubtitleTrack(Uri.parse(data.getStringExtra(EXTRA_MRL)), false) service?.currentMediaWrapper?.let { SlaveRepository.getInstance(this).saveSlave(it.location, IMedia.Slave.Type.Subtitle, 2, data.getStringExtra(EXTRA_MRL)) } addNextTrack = true } else if (BuildConfig.DEBUG) Log.d(TAG, "Subtitle selection dialog was cancelled") } open fun exit(resultCode: Int) { if (isFinishing) return val resultIntent = Intent(ACTION_RESULT) videoUri?.let { uri -> service?.run { if (AndroidUtil.isNougatOrLater) resultIntent.putExtra(EXTRA_URI, uri.toString()) else resultIntent.data = videoUri resultIntent.putExtra(EXTRA_POSITION, time) resultIntent.putExtra(EXTRA_DURATION, length) } setResult(resultCode, resultIntent) finish() } } private fun exitOK() { exit(Activity.RESULT_OK) } override fun onTrackballEvent(event: MotionEvent): Boolean { if (isLoading) return false showOverlay() return true } override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean { return !isLoading && ::touchDelegate.isInitialized && touchDelegate.dispatchGenericMotionEvent(event) } override fun onBackPressed() { if (optionsDelegate?.isShowing() == true) { optionsDelegate?.hide() } else if (lockBackButton) { lockBackButton = false handler.sendEmptyMessageDelayed(RESET_BACK_LOCK, 2000) Toast.makeText(applicationContext, getString(R.string.back_quit_lock), Toast.LENGTH_SHORT).show() } else if (isPlaylistVisible) { togglePlaylist() } else if (isPlaybackSettingActive) { delayDelegate.endPlaybackSetting() } else if (isTv && isShowing && !isLocked) { hideOverlay(true) } else { exitOK() super.onBackPressed() } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (service == null || keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_BUTTON_B) return super.onKeyDown(keyCode, event) if (isOptionsListShowing) return false if (isPlaybackSettingActive && keyCode != KeyEvent.KEYCODE_J && keyCode != KeyEvent.KEYCODE_K && keyCode != KeyEvent.KEYCODE_G && keyCode != KeyEvent.KEYCODE_H) return false if (isLoading) { when (keyCode) { KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_MEDIA_STOP -> { exitOK() return true } } return false } if (isShowing || fov == 0f && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && !playlistContainer.isVisible()) showOverlayTimeout(OVERLAY_TIMEOUT) when (keyCode) { KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> { touchDelegate.seekDelta(10000) return true } KeyEvent.KEYCODE_MEDIA_REWIND -> { touchDelegate.seekDelta(-10000) return true } KeyEvent.KEYCODE_BUTTON_R1 -> { touchDelegate.seekDelta(60000) return true } KeyEvent.KEYCODE_BUTTON_L1 -> { touchDelegate.seekDelta(-60000) return true } KeyEvent.KEYCODE_BUTTON_A -> { if (::hudBinding.isInitialized && hudBinding.progressOverlay.isVisible()) return false when { isNavMenu -> return navigateDvdMenu(keyCode) keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE //prevent conflict with remote control -> return super.onKeyDown(keyCode, event) else -> doPlayPause() } return true } KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE, KeyEvent.KEYCODE_SPACE -> { when { isNavMenu -> return navigateDvdMenu(keyCode) keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> return super.onKeyDown(keyCode, event) else -> doPlayPause() } return true } KeyEvent.KEYCODE_O, KeyEvent.KEYCODE_BUTTON_Y, KeyEvent.KEYCODE_MENU -> { showAdvancedOptions() return true } KeyEvent.KEYCODE_V, KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK, KeyEvent.KEYCODE_BUTTON_X -> { onAudioSubClick(if (::hudBinding.isInitialized) hudBinding.playerOverlayTracks else null) return true } KeyEvent.KEYCODE_A -> { resizeVideo() return true } KeyEvent.KEYCODE_M, KeyEvent.KEYCODE_VOLUME_MUTE -> { updateMute() return true } KeyEvent.KEYCODE_S, KeyEvent.KEYCODE_MEDIA_STOP -> { exitOK() return true } KeyEvent.KEYCODE_E -> { if (event.isCtrlPressed) { val newFragment = EqualizerFragment() newFragment.onDismissListener = DialogInterface.OnDismissListener { dimStatusBar(true) } newFragment.show(supportFragmentManager, "equalizer") } return true } KeyEvent.KEYCODE_DPAD_LEFT -> { if (isNavMenu) return navigateDvdMenu(keyCode) else if (!isShowing && !playlistContainer.isVisible()) { if (event.isAltPressed && event.isCtrlPressed) { touchDelegate.seekDelta(-300000) } else if (event.isCtrlPressed) { touchDelegate.seekDelta(-60000) } else if (fov == 0f) touchDelegate.seekDelta(-10000) else service?.updateViewpoint(-5f, 0f, 0f, 0f, false) return true } } KeyEvent.KEYCODE_DPAD_RIGHT -> { if (isNavMenu) return navigateDvdMenu(keyCode) else if (!isShowing && !playlistContainer.isVisible()) { if (event.isAltPressed && event.isCtrlPressed) { touchDelegate.seekDelta(300000) } else if (event.isCtrlPressed) { touchDelegate.seekDelta(60000) } else if (fov == 0f) touchDelegate.seekDelta(10000) else service?.updateViewpoint(5f, 0f, 0f, 0f, false) return true } } KeyEvent.KEYCODE_DPAD_UP -> { if (isNavMenu) return navigateDvdMenu(keyCode) else if (event.isCtrlPressed) { volumeUp() return true } else if (!isShowing && !playlistContainer.isVisible()) { if (fov == 0f) showAdvancedOptions() else service?.updateViewpoint(0f, -5f, 0f, 0f, false) return true } } KeyEvent.KEYCODE_DPAD_DOWN -> { if (isNavMenu) return navigateDvdMenu(keyCode) else if (event.isCtrlPressed) { volumeDown() return true } else if (!isShowing && fov != 0f) { service?.updateViewpoint(0f, 5f, 0f, 0f, false) return true } } KeyEvent.KEYCODE_DPAD_CENTER -> { if (isNavMenu) return navigateDvdMenu(keyCode) else if (!isShowing) { doPlayPause() return true } } KeyEvent.KEYCODE_ENTER -> return if (isNavMenu) navigateDvdMenu(keyCode) else super.onKeyDown(keyCode, event) KeyEvent.KEYCODE_J -> { delayDelegate.delayAudioOrSpu(delta = -50000L, delayState = IPlaybackSettingsController.DelayState.AUDIO) handler.removeMessages(HIDE_SETTINGS) handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L) return true } KeyEvent.KEYCODE_K -> { delayDelegate.delayAudioOrSpu(delta = 50000L, delayState = IPlaybackSettingsController.DelayState.AUDIO) handler.removeMessages(HIDE_SETTINGS) handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L) return true } KeyEvent.KEYCODE_G -> { delayDelegate.delayAudioOrSpu(delta = -50000L, delayState = IPlaybackSettingsController.DelayState.SUBS) handler.removeMessages(HIDE_SETTINGS) handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L) return true } KeyEvent.KEYCODE_T -> { showOverlay() } KeyEvent.KEYCODE_H -> { if (event.isCtrlPressed) { showOverlay() } else { delayDelegate.delayAudioOrSpu(delta = 50000L, delayState = IPlaybackSettingsController.DelayState.SUBS) handler.removeMessages(HIDE_SETTINGS) handler.sendEmptyMessageDelayed(HIDE_SETTINGS, 4000L) } return true } KeyEvent.KEYCODE_Z -> { resizeVideo() return true } KeyEvent.KEYCODE_N -> { next() return true } KeyEvent.KEYCODE_P -> { previous() return true } KeyEvent.KEYCODE_VOLUME_DOWN -> { volumeDown() return true } KeyEvent.KEYCODE_VOLUME_UP -> { volumeUp() return true } KeyEvent.KEYCODE_CAPTIONS -> { selectSubtitles() return true } KeyEvent.KEYCODE_PLUS -> { service?.run { setRate(rate * 1.2f, true) } return true } KeyEvent.KEYCODE_EQUALS -> { if (event.isShiftPressed) { service?.run { setRate(rate * 1.2f, true) } return true } else service?.run { setRate(1f, true) } return false } KeyEvent.KEYCODE_MINUS -> { service?.run { setRate(rate / 1.2f, true) } return true } KeyEvent.KEYCODE_C -> { resizeVideo() return true } } return super.onKeyDown(keyCode, event) } private fun volumeUp() { if (isMute) { updateMute() } else service?.let { service -> var volume = if (audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) < audioMax) audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) + 1 else Math.round(service.volume.toFloat() * audioMax / 100 + 1) volume = Math.min(Math.max(volume, 0), audioMax * if (isAudioBoostEnabled) 2 else 1) setAudioVolume(volume) } } private fun volumeDown() { service?.let { service -> var vol = if (service.volume > 100) Math.round(service.volume.toFloat() * audioMax / 100 - 1) else audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) - 1 vol = Math.min(Math.max(vol, 0), audioMax * if (isAudioBoostEnabled) 2 else 1) originalVol = vol.toFloat() setAudioVolume(vol) } } internal fun navigateDvdMenu(keyCode: Int): Boolean { when (keyCode) { KeyEvent.KEYCODE_DPAD_UP -> { service?.navigate(MediaPlayer.Navigate.Up) return true } KeyEvent.KEYCODE_DPAD_DOWN -> { service?.navigate(MediaPlayer.Navigate.Down) return true } KeyEvent.KEYCODE_DPAD_LEFT -> { service?.navigate(MediaPlayer.Navigate.Left) return true } KeyEvent.KEYCODE_DPAD_RIGHT -> { service?.navigate(MediaPlayer.Navigate.Right) return true } KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_BUTTON_X, KeyEvent.KEYCODE_BUTTON_A -> { service?.navigate(MediaPlayer.Navigate.Activate) return true } else -> return false } } fun focusPlayPause() { if (::hudBinding.isInitialized) hudBinding.playerOverlayPlay.requestFocus() } /** * Lock screen rotation */ private fun lockScreen() { if (screenOrientation != 100) { screenOrientationLock = requestedOrientation requestedOrientation = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) ActivityInfo.SCREEN_ORIENTATION_LOCKED else getScreenOrientation(100) } showInfo(R.string.locked, 1000) if (::hudBinding.isInitialized) { hudBinding.lockOverlayButton.setImageResource(R.drawable.ic_locked_player) hudBinding.playerOverlayTime.isEnabled = false hudBinding.playerOverlaySeekbar.isEnabled = false hudBinding.playerOverlayLength.isEnabled = false hudBinding.playlistNext.isEnabled = false hudBinding.playlistPrevious.isEnabled = false } hideOverlay(true) lockBackButton = true isLocked = true } /** * Remove screen lock */ private fun unlockScreen() { if (screenOrientation != 100) requestedOrientation = screenOrientationLock showInfo(R.string.unlocked, 1000) if (::hudBinding.isInitialized) { hudBinding.lockOverlayButton.setImageResource(R.drawable.ic_lock_player) hudBinding.playerOverlayTime.isEnabled = true hudBinding.playerOverlaySeekbar.isEnabled = service?.isSeekable != false hudBinding.playerOverlayLength.isEnabled = true hudBinding.playlistNext.isEnabled = true hudBinding.playlistPrevious.isEnabled = true } isShowing = false isLocked = false showOverlay() lockBackButton = false } /** * Show text in the info view and vertical progress bar for "duration" milliseconds * @param text * @param duration * @param barNewValue new volume/brightness value (range: 0 - 15) */ private fun showInfoWithVerticalBar(text: String, duration: Int, barNewValue: Int, max: Int) { showInfo(text, duration) if (!::verticalBarProgress.isInitialized) return var layoutParams: LinearLayout.LayoutParams if (barNewValue <= 100) { layoutParams = verticalBarProgress.layoutParams as LinearLayout.LayoutParams layoutParams.weight = barNewValue * 100 / max.toFloat() verticalBarProgress.layoutParams = layoutParams layoutParams = verticalBarBoostProgress.layoutParams as LinearLayout.LayoutParams layoutParams.weight = 0f verticalBarBoostProgress.layoutParams = layoutParams } else { layoutParams = verticalBarProgress.layoutParams as LinearLayout.LayoutParams layoutParams.weight = 100 * 100 / max.toFloat() verticalBarProgress.layoutParams = layoutParams layoutParams = verticalBarBoostProgress.layoutParams as LinearLayout.LayoutParams layoutParams.weight = (barNewValue - 100) * 100 / max.toFloat() verticalBarBoostProgress.layoutParams = layoutParams } verticalBar.setVisible() } /** * Show text in the info view for "duration" milliseconds * @param text * @param duration */ internal fun showInfo(text: String, duration: Int) { if (isInPictureInPictureMode) return initInfoOverlay() verticalBar.setGone() overlayInfo.setVisible() info.setVisible() info?.text = text handler.removeMessages(FADE_OUT_INFO) handler.sendEmptyMessageDelayed(FADE_OUT_INFO, duration.toLong()) } fun initInfoOverlay() { val vsc = findViewById<ViewStubCompat>(R.id.player_info_stub) if (vsc != null) { vsc.setVisible() // the info textView is not on the overlay info = findViewById(R.id.player_overlay_textinfo) overlayInfo = findViewById(R.id.player_overlay_info) verticalBar = findViewById(R.id.verticalbar) verticalBarProgress = findViewById(R.id.verticalbar_progress) verticalBarBoostProgress = findViewById(R.id.verticalbar_boost_progress) } } internal fun showInfo(textid: Int, duration: Int) { showInfo(getString(textid), duration) } /** * hide the info view with "delay" milliseconds delay * @param delay */ private fun hideInfo(delay: Int = 0) { handler.sendEmptyMessageDelayed(FADE_OUT_INFO, delay.toLong()) } private fun fadeOutInfo() { if (overlayInfo?.visibility == View.VISIBLE) { overlayInfo?.startAnimation(AnimationUtils.loadAnimation( this@VideoPlayerActivity, android.R.anim.fade_out)) overlayInfo.setInvisible() } } /* PlaybackService.Callback */ override fun update() { if (service == null || !::playlistAdapter.isInitialized) return playlistModel?.update() } override fun onMediaEvent(event: IMedia.Event) { when (event.type) { IMedia.Event.ParsedChanged -> updateNavStatus() IMedia.Event.MetaChanged -> { } } } override fun onMediaPlayerEvent(event: MediaPlayer.Event) { service?.let { service -> when (event.type) { MediaPlayer.Event.Playing -> onPlaying() MediaPlayer.Event.Paused -> updateOverlayPausePlay() MediaPlayer.Event.Opening -> forcedTime = -1 MediaPlayer.Event.Vout -> { updateNavStatus() if (event.voutCount > 0) service.mediaplayer.updateVideoSurfaces() if (menuIdx == -1) handleVout(event.voutCount) } MediaPlayer.Event.ESAdded -> { if (menuIdx == -1) { val mw = service.currentMediaWrapper ?: return if (event.esChangedType == IMedia.Track.Type.Audio) { setESTrackLists() lifecycleScope.launch(Dispatchers.IO) { val media = medialibrary.findMedia(mw) val audioTrack = media.getMetaLong(MediaWrapper.META_AUDIOTRACK).toInt() if (audioTrack != 0 || currentAudioTrack != -2) service.setAudioTrack(if (media.id == 0L) currentAudioTrack else audioTrack) } } else if (event.esChangedType == IMedia.Track.Type.Text) { setESTrackLists() lifecycleScope.launch(Dispatchers.IO) { val media = medialibrary.findMedia(mw) val spuTrack = media.getMetaLong(MediaWrapper.META_SUBTITLE_TRACK).toInt() if (addNextTrack) { val tracks = service.spuTracks if (!(tracks as Array<MediaPlayer.TrackDescription>).isNullOrEmpty()) service.setSpuTrack(tracks[tracks.size - 1].id) addNextTrack = false } else if (spuTrack != 0 || currentSpuTrack != -2) { service.setSpuTrack(if (media.id == 0L) currentSpuTrack else spuTrack) } } } } if (menuIdx == -1 && event.esChangedType == IMedia.Track.Type.Video) { handler.removeMessages(CHECK_VIDEO_TRACKS) handler.sendEmptyMessageDelayed(CHECK_VIDEO_TRACKS, 1000) } invalidateESTracks(event.esChangedType) } MediaPlayer.Event.ESDeleted -> { if (menuIdx == -1 && event.esChangedType == IMedia.Track.Type.Video) { handler.removeMessages(CHECK_VIDEO_TRACKS) handler.sendEmptyMessageDelayed(CHECK_VIDEO_TRACKS, 1000) } invalidateESTracks(event.esChangedType) } MediaPlayer.Event.ESSelected -> if (event.esChangedType == IMedia.Track.Type.Video) { val vt = service.currentVideoTrack if (vt != null) fov = if (vt.projection == IMedia.VideoTrack.Projection.Rectangular) 0f else DEFAULT_FOV } MediaPlayer.Event.SeekableChanged -> updateSeekable(event.seekable) MediaPlayer.Event.PausableChanged -> updatePausable(event.pausable) MediaPlayer.Event.Buffering -> { if (isPlaying) { if (event.buffering == 100f) stopLoading() else if (!handler.hasMessages(LOADING_ANIMATION) && !isLoading && (touchDelegate == null || !touchDelegate.isSeeking()) && !isDragging) handler.sendEmptyMessageDelayed(LOADING_ANIMATION, LOADING_ANIMATION_DELAY.toLong()) } } } } } private fun onPlaying() { val mw = service?.currentMediaWrapper ?: return isPlaying = true hasPlaylist = service?.hasPlaylist() == true setPlaybackParameters() stopLoading() updateOverlayPausePlay() updateNavStatus() if (!mw.hasFlag(MediaWrapper.MEDIA_PAUSED)) handler.sendEmptyMessageDelayed(FADE_OUT, OVERLAY_TIMEOUT.toLong()) else { mw.removeFlags(MediaWrapper.MEDIA_PAUSED) wasPaused = false } setESTracks() if (::hudBinding.isInitialized && hudRightBinding.playerOverlayTitle.length() == 0) hudRightBinding.playerOverlayTitle.text = mw.title // Get possible subtitles observeDownloadedSubtitles() optionsDelegate?.setup() settings.edit().remove(VIDEO_PAUSED).apply() if (isInPictureInPictureMode && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val track = service?.playlistManager?.player?.mediaplayer?.currentVideoTrack ?: return val ar = Rational(track.width.coerceAtMost((track.height * 2.39f).toInt()), track.height) if (ar.isFinite && !ar.isZero) { setPictureInPictureParams(PictureInPictureParams.Builder().setAspectRatio(ar).build()) } } } private fun encounteredError() { if (isFinishing || service?.hasNext() == true) return /* Encountered Error, exit player with a message */ alertDialog = AlertDialog.Builder(this@VideoPlayerActivity) .setOnCancelListener { exit(RESULT_PLAYBACK_ERROR) } .setPositiveButton(R.string.ok) { _, _ -> exit(RESULT_PLAYBACK_ERROR) } .setTitle(R.string.encountered_error_title) .setMessage(R.string.encountered_error_message) .create().apply { show() } } private fun handleVout(voutCount: Int) { handler.removeCallbacks(switchAudioRunnable) val vlcVout = service?.vout ?: return if (displayManager.isPrimary && vlcVout.areViewsAttached() && voutCount == 0) { handler.postDelayed(switchAudioRunnable, 4000) } } override fun recreate() { handler.removeCallbacks(switchAudioRunnable) super.recreate() } fun switchToAudioMode(showUI: Boolean) { if (service == null) return switchingView = true // Show the MainActivity if it is not in background. if (showUI) { val i = Intent().apply { setClassName(applicationContext, if (isTv) TV_AUDIOPLAYER_ACTIVITY else MOBILE_MAIN_ACTIVITY) } startActivity(i) } exitOK() } override fun isInPictureInPictureMode(): Boolean { return AndroidUtil.isNougatOrLater && super.isInPictureInPictureMode() } override fun setPictureInPictureParams(params: PictureInPictureParams) { try { super.setPictureInPictureParams(params) } catch (e: IllegalArgumentException) { if (BuildConfig.DEBUG) throw e } } override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) { super.onPictureInPictureModeChanged(isInPictureInPictureMode) service?.mediaplayer?.updateVideoSurfaces() } internal fun sendMouseEvent(action: Int, x: Int, y: Int) { service?.vout?.sendMouseEvent(action, 0, x, y) } /** * show/hide the overlay */ override fun onTouchEvent(event: MotionEvent): Boolean { return service != null && touchDelegate.onTouchEvent(event) } internal fun updateViewpoint(yaw: Float, pitch: Float, fov: Float): Boolean { return service?.updateViewpoint(yaw, pitch, 0f, fov, false) ?: false } internal fun initAudioVolume() = service?.let { service -> if (service.volume <= 100) { volume = audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() originalVol = audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC).toFloat() } else { volume = service.volume.toFloat() * audioMax / 100 } } fun toggleOverlay() { if (!isShowing) showOverlay() else hideOverlay(true) } //Toast that appears only once fun displayWarningToast() { warningToast?.cancel() warningToast = Toast.makeText(application, R.string.audio_boost_warning, Toast.LENGTH_SHORT).apply { show() } } internal fun setAudioVolume(vol: Int) { var vol = vol if (AndroidUtil.isNougatOrLater && (vol <= 0) xor isMute) { mute(!isMute) return //Android N+ throws "SecurityException: Not allowed to change Do Not Disturb state" } /* Since android 4.3, the safe volume warning dialog is displayed only with the FLAG_SHOW_UI flag. * We don't want to always show the default UI volume, so show it only when volume is not set. */ service?.let { service -> if (vol <= audioMax) { service.setVolume(100) if (vol != audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC)) { try { audiomanager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0) // High Volume warning can block volume setting if (audiomanager.getStreamVolume(AudioManager.STREAM_MUSIC) != vol) audiomanager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, AudioManager.FLAG_SHOW_UI) } catch (ignored: RuntimeException) { } //Some device won't allow us to change volume } vol = Math.round(vol * 100 / audioMax.toFloat()) } else { vol = Math.round(vol * 100 / audioMax.toFloat()) service.setVolume(Math.round(vol.toFloat())) } showInfoWithVerticalBar(getString(R.string.volume) + "\n" + Integer.toString(vol) + '%'.toString(), 1000, vol, if (isAudioBoostEnabled) 200 else 100) } } private fun mute(mute: Boolean) { service?.let { service -> isMute = mute if (isMute) volSave = service.volume service.setVolume(if (isMute) 0 else volSave) } } private fun updateMute() { mute(!isMute) showInfo(if (isMute) R.string.sound_off else R.string.sound_on, 1000) } internal fun changeBrightness(delta: Float) { // Estimate and adjust Brightness val lp = window.attributes var brightness = (lp.screenBrightness + delta).coerceIn(0.01f, 1f) setWindowBrightness(brightness) brightness = (brightness * 100).roundToInt().toFloat() showInfoWithVerticalBar("${getString(R.string.brightness)}\n${brightness.toInt()}%", 1000, brightness.toInt(), 100) } private fun setWindowBrightness(brightness: Float) { val lp = window.attributes lp.screenBrightness = brightness // Set Brightness window.attributes = lp } open fun onAudioSubClick(anchor: View?) { service?.let { service -> var flags = 0L if (enableSubs) { flags = flags or CTX_DOWNLOAD_SUBTITLES_PLAYER if (displayManager.isPrimary) flags = flags or CTX_PICK_SUBS } if (service.videoTracksCount > 2) flags = flags or CTX_VIDEO_TRACK if (service.audioTracksCount > 0) flags = flags or CTX_AUDIO_TRACK if (service.spuTracksCount > 0) flags = flags or CTX_SUBS_TRACK if (optionsDelegate == null) optionsDelegate = PlayerOptionsDelegate(this, service) optionsDelegate?.flags = flags optionsDelegate?.show(PlayerOptionType.MEDIA_TRACKS) hideOverlay(false) } } override fun onPopupMenu(view: View, position: Int, item: MediaWrapper?) { val popupMenu = PopupMenu(this, view) popupMenu.menuInflater.inflate(R.menu.audio_player, popupMenu.menu) popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item -> if (item.itemId == R.id.audio_player_mini_remove) service?.run { remove(position) return@OnMenuItemClickListener true } false }) popupMenu.show() } override fun onSelectionSet(position: Int) = playlist.scrollToPosition(position) override fun playItem(position: Int, item: MediaWrapper) { service?.playIndex(position) } override fun onClick(v: View) { when (v.id) { R.id.orientation_toggle -> toggleOrientation() R.id.playlist_toggle -> togglePlaylist() R.id.player_overlay_forward -> touchDelegate.seekDelta(10000) R.id.player_overlay_rewind -> touchDelegate.seekDelta(-10000) R.id.ab_repeat_add_marker -> service?.playlistManager?.setABRepeatValue(hudBinding.playerOverlaySeekbar.progress.toLong()) R.id.ab_repeat_reset -> service?.playlistManager?.resetABRepeatValues() R.id.ab_repeat_stop -> service?.playlistManager?.clearABRepeat() R.id.player_overlay_navmenu -> showNavMenu() R.id.player_overlay_length, R.id.player_overlay_time -> toggleTimeDisplay() R.id.video_renderer -> if (supportFragmentManager.findFragmentByTag("renderers") == null) RenderersDialog().show(supportFragmentManager, "renderers") R.id.video_secondary_display -> { clone = displayManager.isSecondary recreate() } } } override fun onLongClick(v: View): Boolean { when (v.id) { R.id.orientation_toggle -> return resetOrientation() } return false } fun toggleTimeDisplay() { sDisplayRemainingTime = !sDisplayRemainingTime showOverlay() settings.putSingle(KEY_REMAINING_TIME_DISPLAY, sDisplayRemainingTime) } fun toggleLock() { if (isLocked) unlockScreen() else lockScreen() } fun toggleLoop(v: View) = service?.run { if (repeatType == PlaybackStateCompat.REPEAT_MODE_ONE) { showInfo(getString(R.string.repeat), 1000) repeatType = PlaybackStateCompat.REPEAT_MODE_NONE } else { repeatType = PlaybackStateCompat.REPEAT_MODE_ONE showInfo(getString(R.string.repeat_single), 1000) } true } ?: false override fun onStorageAccessGranted() { handler.sendEmptyMessage(START_PLAYBACK) } fun hideOptions() { optionsDelegate?.hide() } private interface TrackSelectedListener { fun onTrackSelected(trackID: Int) } private fun selectTrack(tracks: Array<MediaPlayer.TrackDescription>?, currentTrack: Int, titleId: Int, listener: TrackSelectedListener?) { if (listener == null) throw IllegalArgumentException("listener must not be null") if (tracks == null) return val nameList = arrayOfNulls<String>(tracks.size) val idList = IntArray(tracks.size) var listPosition = 0 for ((i, track) in tracks.withIndex()) { idList[i] = track.id nameList[i] = track.name // map the track position to the list position if (track.id == currentTrack) listPosition = i } if (!isFinishing) alertDialog = AlertDialog.Builder(this@VideoPlayerActivity) .setTitle(titleId) .setSingleChoiceItems(nameList, listPosition) { dialog, listPosition -> var trackID = -1 // Reverse map search... for (track in tracks) { if (idList[listPosition] == track.id) { trackID = track.id break } } listener.onTrackSelected(trackID) dialog.dismiss() } .setOnDismissListener { this.dimStatusBar(true) } .create().apply { setCanceledOnTouchOutside(true) setOwnerActivity(this@VideoPlayerActivity) show() } } fun selectVideoTrack() { setESTrackLists() service?.let { selectTrack(videoTracksList, it.videoTrack, R.string.track_video, object : TrackSelectedListener { override fun onTrackSelected(trackID: Int) { if (trackID < -1) return service?.let { service -> service.setVideoTrack(trackID) seek(service.time) } } }) } } fun selectAudioTrack() { setESTrackLists() service?.let { selectTrack(audioTracksList, it.audioTrack, R.string.track_audio, object : TrackSelectedListener { override fun onTrackSelected(trackID: Int) { if (trackID < -1) return service?.let { service -> service.setAudioTrack(trackID) runIO(Runnable { val mw = medialibrary.findMedia(service.currentMediaWrapper) if (mw != null && mw.id != 0L) mw.setLongMeta(MediaWrapper.META_AUDIOTRACK, trackID.toLong()) }) } } }) } } fun selectSubtitles() { setESTrackLists() service?.let { selectTrack(subtitleTracksList, it.spuTrack, R.string.track_text, object : TrackSelectedListener { override fun onTrackSelected(trackID: Int) { if (trackID < -1 || service == null) return runIO(Runnable { setSpuTrack(trackID) }) } }) } } fun pickSubtitles() { val uri = videoUri?: return isShowingDialog = true val filePickerIntent = Intent(this, FilePickerActivity::class.java) filePickerIntent.data = Uri.parse(FileUtils.getParent(uri.toString())) startActivityForResult(filePickerIntent, 0) } fun downloadSubtitles() = service?.currentMediaWrapper?.let { MediaUtils.getSubs(this@VideoPlayerActivity, it) } @WorkerThread private fun setSpuTrack(trackID: Int) { runOnMainThread(Runnable { service?.setSpuTrack(trackID) }) val mw = medialibrary.findMedia(service?.currentMediaWrapper) ?: return if (mw.id != 0L) mw.setLongMeta(MediaWrapper.META_SUBTITLE_TRACK, trackID.toLong()) } private fun showNavMenu() { if (menuIdx >= 0) service?.titleIdx = menuIdx } private fun updateSeekable(seekable: Boolean) { if (!::hudBinding.isInitialized) return hudBinding.playerOverlayRewind.isEnabled = seekable hudBinding.playerOverlayRewind.setImageResource(if (seekable) R.drawable.ic_rewind_player else R.drawable.ic_rewind_player_disabled) hudBinding.playerOverlayForward.isEnabled = seekable hudBinding.playerOverlayForward.setImageResource(if (seekable) R.drawable.ic_forward_player else R.drawable.ic_forward_player_disabled) if (!isLocked) hudBinding.playerOverlaySeekbar.isEnabled = seekable } private fun updatePausable(pausable: Boolean) { if (!::hudBinding.isInitialized) return hudBinding.playerOverlayPlay.isEnabled = pausable if (!pausable) hudBinding.playerOverlayPlay.setImageResource(R.drawable.ic_play_player_disabled) } fun doPlayPause() { if (service?.isPausable != true) return if (service?.isPlaying == true) { showOverlayTimeout(OVERLAY_INFINITE) pause() } else { handler.sendEmptyMessageDelayed(FADE_OUT, 300L) play() } } fun seek(position: Long) { service?.let { seek(position, it.length) } } internal fun seek(position: Long, length: Long) { service?.let { service -> forcedTime = position lastTime = service.time service.seek(position, length.toDouble()) service.playlistManager.player.updateProgress(position) } } @SuppressLint("ClickableViewAccessibility") private fun initSeekButton() { if (!::hudBinding.isInitialized) return hudBinding.playerOverlayRewind.setOnClickListener(this) hudBinding.playerOverlayForward.setOnClickListener(this) hudBinding.playerOverlayRewind.setOnTouchListener(OnRepeatListener(this)) hudBinding.playerOverlayForward.setOnTouchListener(OnRepeatListener(this)) } fun resizeVideo() = service?.run { val next = (mediaplayer.videoScale.ordinal + 1) % MediaPlayer.SURFACE_SCALES_COUNT val scale = MediaPlayer.ScaleType.values()[next] setVideoScale(scale) } internal fun setVideoScale(scale: MediaPlayer.ScaleType) = service?.run { mediaplayer.videoScale = scale when (scale) { MediaPlayer.ScaleType.SURFACE_BEST_FIT -> showInfo(R.string.surface_best_fit, 1000) MediaPlayer.ScaleType.SURFACE_FIT_SCREEN -> showInfo(R.string.surface_fit_screen, 1000) MediaPlayer.ScaleType.SURFACE_FILL -> showInfo(R.string.surface_fill, 1000) MediaPlayer.ScaleType.SURFACE_16_9 -> showInfo("16:9", 1000) MediaPlayer.ScaleType.SURFACE_4_3 -> showInfo("4:3", 1000) MediaPlayer.ScaleType.SURFACE_ORIGINAL -> showInfo(R.string.surface_original, 1000) } settings.putSingle(VIDEO_RATIO, scale.ordinal) } /** * show overlay * @param forceCheck: adjust the timeout in function of playing state */ private fun showOverlay(forceCheck: Boolean = false) { if (forceCheck) overlayTimeout = 0 showOverlayTimeout(0) } /** * show overlay */ fun showOverlayTimeout(timeout: Int) { service?.let { service -> if (isInPictureInPictureMode) return initOverlay() if (!::hudBinding.isInitialized) return overlayTimeout = when { timeout != 0 -> timeout service.isPlaying -> OVERLAY_TIMEOUT else -> OVERLAY_INFINITE } if (isNavMenu) { isShowing = true return } if (!isShowing) { isShowing = true if (!isLocked) { showControls(true) } dimStatusBar(false) hudBinding.progressOverlay.setVisible() hudRightBinding.hudRightOverlay.setVisible() if (!displayManager.isPrimary) overlayBackground.setVisible() updateOverlayPausePlay(true) } handler.removeMessages(FADE_OUT) if (overlayTimeout != OVERLAY_INFINITE) handler.sendMessageDelayed(handler.obtainMessage(FADE_OUT), overlayTimeout.toLong()) } } private fun showControls(show: Boolean) { if (show && isInPictureInPictureMode) return if (::hudBinding.isInitialized) { hudBinding.playerOverlayPlay.visibility = if (show) View.VISIBLE else View.INVISIBLE if (seekButtons) { hudBinding.playerOverlayRewind.visibility = if (show) View.VISIBLE else View.INVISIBLE hudBinding.playerOverlayForward.visibility = if (show) View.VISIBLE else View.INVISIBLE } hudBinding.orientationToggle.visibility = if (isTv || AndroidDevices.isChromeBook) View.GONE else if (show) View.VISIBLE else View.INVISIBLE hudBinding.playerOverlayTracks.visibility = if (show) View.VISIBLE else View.INVISIBLE hudBinding.playerOverlayAdvFunction.visibility = if (show) View.VISIBLE else View.INVISIBLE if (hasPlaylist) { hudBinding.playlistPrevious.visibility = if (show) View.VISIBLE else View.INVISIBLE hudBinding.playlistNext.visibility = if (show) View.VISIBLE else View.INVISIBLE } } if (::hudRightBinding.isInitialized) { val secondary = displayManager.isSecondary if (secondary) hudRightBinding.videoSecondaryDisplay.setImageResource(R.drawable.ic_screenshare_stop_circle_player) hudRightBinding.videoSecondaryDisplay.visibility = if (!show) View.GONE else if (UiTools.hasSecondaryDisplay(applicationContext)) View.VISIBLE else View.GONE hudRightBinding.videoSecondaryDisplay.contentDescription = resources.getString(if (secondary) R.string.video_remote_disable else R.string.video_remote_enable) hudRightBinding.playlistToggle.visibility = if (show && service?.hasPlaylist() == true) View.VISIBLE else View.GONE } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private fun initOverlay() { service?.let { service -> val vscRight = findViewById<ViewStubCompat>(R.id.player_hud_right_stub) vscRight?.let { it.setVisible() hudRightBinding = DataBindingUtil.bind(findViewById(R.id.hud_right_overlay)) ?: return if (!isBenchmark && enableCloneMode && !settings.contains("enable_clone_mode")) { UiTools.snackerConfirm(hudRightBinding.videoSecondaryDisplay, getString(R.string.video_save_clone_mode), Runnable { settings.putSingle("enable_clone_mode", true) }) } } val vsc = findViewById<ViewStubCompat>(R.id.player_hud_stub) if (vsc != null) { seekButtons = settings.getBoolean(ENABLE_SEEK_BUTTONS, false) vsc.setVisible() hudBinding = DataBindingUtil.bind(findViewById(R.id.progress_overlay)) ?: return hudBinding.player = this hudBinding.progress = service.playlistManager.player.progress abRepeatAddMarker = hudBinding.abRepeatContainer.findViewById(R.id.ab_repeat_add_marker) service.playlistManager.abRepeat.observe(this, Observer { abvalues -> hudBinding.abRepeatA = if (abvalues.start == -1L) -1F else abvalues.start / service.playlistManager.player.getLength().toFloat() hudBinding.abRepeatB = if (abvalues.stop == -1L) -1F else abvalues.stop / service.playlistManager.player.getLength().toFloat() hudBinding.abRepeatMarkerA.visibility = if (abvalues.start == -1L) View.GONE else View.VISIBLE hudBinding.abRepeatMarkerB.visibility = if (abvalues.stop == -1L) View.GONE else View.VISIBLE service.manageAbRepeatStep(hudRightBinding.abRepeatReset, hudRightBinding.abRepeatStop, hudBinding.abRepeatContainer, abRepeatAddMarker) }) service.playlistManager.abRepeatOn.observe(this, Observer { hudBinding.abRepeatMarkerGuidelineContainer.visibility = if (it) View.VISIBLE else View.GONE if (it) showOverlay(true) if (it) { hudBinding.playerOverlayLength.nextFocusUpId = R.id.ab_repeat_add_marker hudBinding.playerOverlayTime.nextFocusUpId = R.id.ab_repeat_add_marker } service.manageAbRepeatStep(hudRightBinding.abRepeatReset, hudRightBinding.abRepeatStop, hudBinding.abRepeatContainer, abRepeatAddMarker) }) service.playlistManager.delayValue.observe(this, Observer { delayDelegate.delayChanged(it, service) }) service.playlistManager.videoStatsOn.observe(this, Observer { if (it) showOverlay(true) statsDelegate.container = hudBinding.statsContainer statsDelegate.initPlotView(hudBinding) if (it) statsDelegate.start() else statsDelegate.stop() }) hudBinding.statsClose.setOnClickListener { service.playlistManager.videoStatsOn.postValue(false) } hudBinding.lifecycleOwner = this val layoutParams = hudBinding.progressOverlay.layoutParams as RelativeLayout.LayoutParams if (AndroidDevices.isPhone || !AndroidDevices.hasNavBar) layoutParams.width = LayoutParams.MATCH_PARENT else layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE) hudBinding.progressOverlay.layoutParams = layoutParams overlayBackground = findViewById(R.id.player_overlay_background) navMenu = findViewById(R.id.player_overlay_navmenu) if (!AndroidDevices.isChromeBook && !isTv && Settings.getInstance(this).getBoolean("enable_casting", true)) { rendererBtn = findViewById(R.id.video_renderer) PlaybackService.renderer.observe(this, Observer { rendererItem -> rendererBtn?.setImageDrawable(AppCompatResources.getDrawable(this, if (rendererItem == null) R.drawable.ic_renderer_circle_player else R.drawable.ic_renderer_on_circle_player)) }) RendererDelegate.renderers.observe(this, Observer<List<RendererItem>> { rendererItems -> rendererBtn.setVisibility(if (rendererItems.isNullOrEmpty()) View.GONE else View.VISIBLE) }) } hudRightBinding.playerOverlayTitle.text = service.currentMediaWrapper?.title if (seekButtons) initSeekButton() //Set margins for TV overscan if (isTv) { val hm = resources.getDimensionPixelSize(R.dimen.tv_overscan_horizontal) val vm = resources.getDimensionPixelSize(R.dimen.tv_overscan_vertical) val lp = vsc.layoutParams as RelativeLayout.LayoutParams lp.setMargins(hm, 0, hm, vm) vsc.layoutParams = lp } resetHudLayout() updateOverlayPausePlay(true) updateSeekable(service.isSeekable) updatePausable(service.isPausable) updateNavStatus() setListeners(true) initPlaylistUi() if (!displayManager.isPrimary || isTv) hudBinding.lockOverlayButton.setGone() } else if (::hudBinding.isInitialized) { hudBinding.progress = service.playlistManager.player.progress hudBinding.lifecycleOwner = this } } } /** * hider overlay */ internal fun hideOverlay(fromUser: Boolean) { if (isShowing) { handler.removeMessages(FADE_OUT) Log.v(TAG, "remove View!") overlayTips.setInvisible() if (!displayManager.isPrimary) { overlayBackground?.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out)) overlayBackground.setInvisible() } if (::hudBinding.isInitialized) hudBinding.progressOverlay.setInvisible() if (::hudRightBinding.isInitialized) hudRightBinding.hudRightOverlay.setInvisible() showControls(false) isShowing = false dimStatusBar(true) playlistSearchText.editText?.setText("") } else if (!fromUser) { /* * Try to hide the Nav Bar again. * It seems that you can't hide the Nav Bar if you previously * showed it in the last 1-2 seconds. */ dimStatusBar(true) } } /** * Dim the status bar and/or navigation icons when needed on Android 3.x. * Hide it on Android 4.0 and later */ @TargetApi(Build.VERSION_CODES.KITKAT) fun dimStatusBar(dim: Boolean) { if (isNavMenu) return var visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN var navbar = 0 if (dim || isLocked) { window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) navbar = navbar or (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) if (AndroidUtil.isKitKatOrLater) visibility = visibility or View.SYSTEM_UI_FLAG_IMMERSIVE visibility = visibility or View.SYSTEM_UI_FLAG_FULLSCREEN } else { window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) visibility = visibility or View.SYSTEM_UI_FLAG_VISIBLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION } if (AndroidDevices.hasNavBar) visibility = visibility or navbar window.decorView.systemUiVisibility = visibility } private fun showTitle() { if (isNavMenu) return var visibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN var navbar = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION navbar = navbar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION if (AndroidDevices.hasNavBar) visibility = visibility or navbar window.decorView.systemUiVisibility = visibility } private fun updateOverlayPausePlay(skipAnim: Boolean = false) { if (!::hudBinding.isInitialized) return service?.let { service -> if (service.isPausable) { if (skipAnim) { hudBinding.playerOverlayPlay.setImageResource(if (service.isPlaying) R.drawable.ic_pause_player else R.drawable.ic_play_player) } else { val drawable = if (service.isPlaying) playToPause else pauseToPlay hudBinding.playerOverlayPlay.setImageDrawable(drawable) if (service.isPlaying != wasPlaying) drawable.start() } wasPlaying = service.isPlaying } hudBinding.playerOverlayPlay.requestFocus() if (::playlistAdapter.isInitialized) { playlistAdapter.setCurrentlyPlaying(service.isPlaying) } } } private fun invalidateESTracks(type: Int) { when (type) { IMedia.Track.Type.Audio -> audioTracksList = null IMedia.Track.Type.Text -> subtitleTracksList = null } } private fun setESTracks() { if (lastAudioTrack >= -1) { service?.setAudioTrack(lastAudioTrack) lastAudioTrack = -2 } if (lastSpuTrack >= -1) { service?.setSpuTrack(lastSpuTrack) lastSpuTrack = -2 } } @Suppress("UNCHECKED_CAST") private fun setESTrackLists() { service?.let { service -> if (audioTracksList == null && service.audioTracksCount > 0) audioTracksList = service.audioTracks as Array<MediaPlayer.TrackDescription>? if (subtitleTracksList == null && service.spuTracksCount > 0) subtitleTracksList = service.spuTracks as Array<MediaPlayer.TrackDescription>? if (videoTracksList == null && service.videoTracksCount > 0) videoTracksList = service.videoTracks as Array<MediaPlayer.TrackDescription>? } } /** * */ private fun play() { service?.play() rootView?.run { keepScreenOn = true } } /** * */ private fun pause() { service?.pause() rootView?.run { keepScreenOn = false } } fun next() { service?.next() } fun previous() { service?.previous(false) } /* * Additionnal method to prevent alert dialog to pop up */ private fun loadMedia(fromStart: Boolean) { askResume = false intent.putExtra(PLAY_EXTRA_FROM_START, fromStart) loadMedia() } /** * External extras: * - position (long) - position of the video to start with (in ms) * - subtitles_location (String) - location of a subtitles file to load * - from_start (boolean) - Whether playback should start from start or from resume point * - title (String) - video title, will be guessed from file if not set. */ @SuppressLint("SdCardPath") @TargetApi(12) protected open fun loadMedia() { service?.let { service -> isPlaying = false var title: String? = null var fromStart = settings.getString(KEY_VIDEO_CONFIRM_RESUME, "0") == "1" var itemTitle: String? = null var positionInPlaylist = -1 val intent = intent val extras = intent.extras var startTime = 0L val currentMedia = service.currentMediaWrapper val hasMedia = currentMedia != null val isPlaying = service.isPlaying /* * If the activity has been paused by pressing the power button, then * pressing it again will show the lock screen. * But onResume will also be called, even if vlc-android is still in * the background. * To workaround this, pause playback if the lockscreen is displayed. */ val km = applicationContext.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (km.inKeyguardRestrictedInputMode()) wasPaused = true if (wasPaused && BuildConfig.DEBUG) Log.d(TAG, "Video was previously paused, resuming in paused mode") if (intent.data != null) videoUri = intent.data if (extras != null) { if (intent.hasExtra(PLAY_EXTRA_ITEM_LOCATION)) { videoUri = extras.getParcelable(PLAY_EXTRA_ITEM_LOCATION) intent.removeExtra(PLAY_EXTRA_ITEM_LOCATION) } fromStart = fromStart or extras.getBoolean(PLAY_EXTRA_FROM_START, false) // Consume fromStart option after first use to prevent // restarting again when playback is paused. intent.putExtra(PLAY_EXTRA_FROM_START, false) askResume = askResume and !fromStart startTime = if (fromStart) 0L else extras.getLong(PLAY_EXTRA_START_TIME) // position passed in by intent (ms) if (!fromStart && startTime == 0L) { startTime = extras.getInt(PLAY_EXTRA_START_TIME).toLong() } positionInPlaylist = extras.getInt(PLAY_EXTRA_OPENED_POSITION, -1) val path = extras.getString(PLAY_EXTRA_SUBTITLES_LOCATION) if (!path.isNullOrEmpty()) service.addSubtitleTrack(path, true) if (intent.hasExtra(PLAY_EXTRA_ITEM_TITLE)) itemTitle = extras.getString(PLAY_EXTRA_ITEM_TITLE) } if (startTime == 0L && savedTime > 0L) startTime = savedTime val restorePlayback = hasMedia && currentMedia?.uri == videoUri var openedMedia: MediaWrapper? = null val resumePlaylist = service.isValidIndex(positionInPlaylist) val continueplayback = isPlaying && (restorePlayback || positionInPlaylist == service.currentMediaPosition) if (resumePlaylist) { // Provided externally from AudioService if (BuildConfig.DEBUG) Log.v(TAG, "Continuing playback from PlaybackService at index $positionInPlaylist") openedMedia = service.media[positionInPlaylist] itemTitle = openedMedia.title updateSeekable(service.isSeekable) updatePausable(service.isPausable) } if (videoUri != null) { var uri = videoUri ?:return var media: MediaWrapper? = null if (!continueplayback) { if (!resumePlaylist) { // restore last position media = medialibrary.getMedia(uri) if (media == null && TextUtils.equals(uri.scheme, "file") && uri.path?.startsWith("/sdcard") == true) { uri = FileUtils.convertLocalUri(uri) videoUri = uri media = medialibrary.getMedia(uri) } if (media != null && media.id != 0L && media.time == 0L) media.time = media.getMetaLong(MediaWrapper.META_PROGRESS) } else media = openedMedia if (media != null) { // in media library if (askResume && !fromStart && positionInPlaylist <= 0 && media.time > 0) { showConfirmResumeDialog() return } lastAudioTrack = media.audioTrack lastSpuTrack = media.spuTrack } else if (!fromStart) { // not in media library if (askResume && startTime > 0L) { showConfirmResumeDialog() return } else { val rTime = settings.getLong(VIDEO_RESUME_TIME, -1) if (rTime > 0) { if (askResume) { showConfirmResumeDialog() return } else { settings.putSingle(VIDEO_RESUME_TIME, -1L) startTime = rTime } } } } } // Start playback & seek /* prepare playback */ val medialoaded = media != null if (!medialoaded) media = if (hasMedia) currentMedia else MLServiceLocator.getAbstractMediaWrapper(uri) itemTitle?.let { media?.title = Uri.decode(it) } if (wasPaused) media?.addFlags(MediaWrapper.MEDIA_PAUSED) if (intent.hasExtra(PLAY_DISABLE_HARDWARE)) media?.addFlags(MediaWrapper.MEDIA_NO_HWACCEL) media!!.removeFlags(MediaWrapper.MEDIA_FORCE_AUDIO) media.addFlags(MediaWrapper.MEDIA_VIDEO) if (fromStart) media.addFlags(MediaWrapper.MEDIA_FROM_START) // Set resume point if (!continueplayback && !fromStart) { if (startTime <= 0L && media.time > 0L) startTime = media.time if (startTime > 0L) service.saveStartTime(startTime) } // Handle playback if (resumePlaylist) { if (continueplayback) { if (displayManager.isPrimary) service.flush() onPlaying() } else service.playIndex(positionInPlaylist) } else service.load(media) // Get the title if (itemTitle == null && "content" != uri.scheme) title = uri.lastPathSegment } else if (service.hasMedia() && !displayManager.isPrimary) { onPlaying() } else { service.loadLastPlaylist(PLAYLIST_TYPE_VIDEO) } if (itemTitle != null) title = itemTitle if (::hudBinding.isInitialized) { hudRightBinding.playerOverlayTitle.text = title } if (wasPaused) { // XXX: Workaround to update the seekbar position forcedTime = startTime forcedTime = -1 showOverlay(true) } enableSubs() } } private fun enableSubs() { videoUri?.let { val lastPath = it.lastPathSegment ?: return enableSubs = (!TextUtils.isEmpty(lastPath) && !lastPath.endsWith(".ts") && !lastPath.endsWith(".m2ts") && !lastPath.endsWith(".TS") && !lastPath.endsWith(".M2TS")) } } private fun removeDownloadedSubtitlesObserver() { downloadedSubtitleLiveData?.removeObserver(downloadedSubtitleObserver) downloadedSubtitleLiveData = null } private fun observeDownloadedSubtitles() { service?.let { service -> val uri = service.currentMediaWrapper?.uri ?: return val path = uri.path ?: return if (previousMediaPath == null || path != previousMediaPath) { previousMediaPath = path removeDownloadedSubtitlesObserver() downloadedSubtitleLiveData = ExternalSubRepository.getInstance(this).getDownloadedSubtitles(uri).apply { observe(this@VideoPlayerActivity, downloadedSubtitleObserver) } } } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private fun getScreenOrientation(mode: Int): Int { when (mode) { 98 //toggle button -> return if (currentScreenOrientation == Configuration.ORIENTATION_LANDSCAPE) ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE 99 //screen orientation user -> return if (AndroidUtil.isJellyBeanMR2OrLater) ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR else ActivityInfo.SCREEN_ORIENTATION_SENSOR 101 //screen orientation landscape -> return ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE 102 //screen orientation portrait -> return ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT } /* screenOrientation = 100, we lock screen at its current orientation */ val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager val display = wm.defaultDisplay val rot = screenRotation /* * Since getRotation() returns the screen's "natural" orientation, * which is not guaranteed to be SCREEN_ORIENTATION_PORTRAIT, * we have to invert the SCREEN_ORIENTATION value if it is "naturally" * landscape. */ var defaultWide = display.width > display.height if (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270) defaultWide = !defaultWide return if (defaultWide) { when (rot) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_180 -> // SCREEN_ORIENTATION_REVERSE_PORTRAIT only available since API // Level 9+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE Surface.ROTATION_270 -> // SCREEN_ORIENTATION_REVERSE_LANDSCAPE only available since API // Level 9+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT else -> 0 } } else { when (rot) { Surface.ROTATION_0 -> ActivityInfo.SCREEN_ORIENTATION_PORTRAIT Surface.ROTATION_90 -> ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE Surface.ROTATION_180 -> // SCREEN_ORIENTATION_REVERSE_PORTRAIT only available since API // Level 9+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT Surface.ROTATION_270 -> // SCREEN_ORIENTATION_REVERSE_LANDSCAPE only available since API // Level 9+ ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE else -> 0 } } } private fun showConfirmResumeDialog() { if (isFinishing) return service?.pause() /* Encountered Error, exit player with a message */ alertDialog = AlertDialog.Builder(this@VideoPlayerActivity) .setMessage(R.string.confirm_resume) .setPositiveButton(R.string.resume_from_position) { _, _ -> loadMedia(false) } .setNegativeButton(R.string.play_from_start) { _, _ -> loadMedia(true) } .create().apply { setCancelable(false) setOnKeyListener(DialogInterface.OnKeyListener { dialog, keyCode, _ -> if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.dismiss() finish() return@OnKeyListener true } false }) show() } } fun showAdvancedOptions() { if (optionsDelegate == null) service?.let { optionsDelegate = PlayerOptionsDelegate(this, it) } optionsDelegate?.show(PlayerOptionType.ADVANCED) hideOverlay(false) } private fun toggleOrientation() { //screen is not yet locked. We invert the rotation to force locking in the current orientation if (screenOrientation != 98) { currentScreenOrientation = if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) Configuration.ORIENTATION_LANDSCAPE else Configuration.ORIENTATION_PORTRAIT } screenOrientation = 98//Rotate button requestedOrientation = getScreenOrientation(screenOrientation) //As the current orientation may have been artificially changed above, we reset it to the real current orientation currentScreenOrientation = resources.configuration.orientation @StringRes val message = if (currentScreenOrientation == Configuration.ORIENTATION_LANDSCAPE) R.string.locked_in_landscape_mode else R.string.locked_in_portrait_mode rootView?.let { UiTools.snacker(it, message) } } private fun resetOrientation(): Boolean { if (screenOrientation == 98) { screenOrientation = Integer.valueOf( settings.getString(SCREEN_ORIENTATION, "99" /*SCREEN ORIENTATION SENSOR*/)!!) rootView?.let { UiTools.snacker(it, R.string.reset_orientation) } requestedOrientation = getScreenOrientation(screenOrientation) return true } return false } internal fun togglePlaylist() { if (isPlaylistVisible) { playlistContainer.setGone() playlist.setOnClickListener(null) return } hideOverlay(true) playlistContainer.setVisible() playlist.adapter = playlistAdapter update() } private fun toggleBtDelay(connected: Boolean) { service?.setAudioDelay(if (connected) settings.getLong(KEY_BLUETOOTH_DELAY, 0) else 0L) } /** * Start the video loading animation. */ private fun startLoading() { if (isLoading) return isLoading = true val anim = AnimationSet(true) val rotate = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) rotate.duration = 800 rotate.interpolator = DecelerateInterpolator() rotate.repeatCount = RotateAnimation.INFINITE anim.addAnimation(rotate) loadingImageView.setVisible() loadingImageView?.startAnimation(anim) } /** * Stop the video loading animation. */ private fun stopLoading() { handler.removeMessages(LOADING_ANIMATION) if (!isLoading) return isLoading = false loadingImageView.setInvisible() loadingImageView?.clearAnimation() } fun onClickOverlayTips(@Suppress("UNUSED_PARAMETER") v: View) { overlayTips.setGone() } fun onClickDismissTips(@Suppress("UNUSED_PARAMETER") v: View) { overlayTips.setGone() settings.putSingle(PREF_TIPS_SHOWN, true) } private fun updateNavStatus() { if (service == null) return menuIdx = -1 lifecycleScope.launchWhenStarted { val titles = withContext(Dispatchers.IO) { service?.titles } if (isFinishing) return@launchWhenStarted isNavMenu = false if (titles != null) { val currentIdx = service?.titleIdx ?: return@launchWhenStarted for (i in titles.indices) { val title = titles[i] if (title.isMenu) { menuIdx = i break } } val interactive = service?.mediaplayer?.let { it.titles[it.title].isInteractive } ?: false isNavMenu = menuIdx == currentIdx || interactive } if (isNavMenu) { /* * Keep the overlay hidden in order to have touch events directly * transmitted to navigation handling. */ hideOverlay(false) } else if (menuIdx != -1) setESTracks() navMenu.setVisibility(if (menuIdx >= 0 && navMenu != null) View.VISIBLE else View.GONE) supportInvalidateOptionsMenu() } } open fun onServiceChanged(service: PlaybackService?) { if (service != null) { this.service = service //We may not have the permission to access files if (Permissions.checkReadStoragePermission(this, true) && !switchingView) handler.sendEmptyMessage(START_PLAYBACK) switchingView = false handler.post { // delay mediaplayer loading, prevent ANR if (service.volume > 100 && !isAudioBoostEnabled) service.setVolume(100) } service.addCallback(this) } else if (this.service != null) { this.service?.removeCallback(this) this.service = null handler.sendEmptyMessage(AUDIO_SERVICE_CONNECTION_FAILED) removeDownloadedSubtitlesObserver() previousMediaPath = null } } companion object { private const val TAG = "VLC/VideoPlayerActivity" private val ACTION_RESULT = "player.result".buildPkgString() private const val EXTRA_POSITION = "extra_position" private const val EXTRA_DURATION = "extra_duration" private const val EXTRA_URI = "extra_uri" private const val RESULT_CONNECTION_FAILED = Activity.RESULT_FIRST_USER + 1 private const val RESULT_PLAYBACK_ERROR = Activity.RESULT_FIRST_USER + 2 private const val RESULT_VIDEO_TRACK_LOST = Activity.RESULT_FIRST_USER + 3 internal const val DEFAULT_FOV = 80f private const val KEY_TIME = "saved_time" private const val KEY_LIST = "saved_list" private const val KEY_URI = "saved_uri" private const val OVERLAY_TIMEOUT = 4000 const val OVERLAY_INFINITE = -1 private const val FADE_OUT = 1 private const val FADE_OUT_INFO = 2 private const val START_PLAYBACK = 3 private const val AUDIO_SERVICE_CONNECTION_FAILED = 4 private const val RESET_BACK_LOCK = 5 private const val CHECK_VIDEO_TRACKS = 6 private const val LOADING_ANIMATION = 7 internal const val SHOW_INFO = 8 internal const val HIDE_INFO = 9 internal const val HIDE_SEEK = 10 internal const val HIDE_SETTINGS = 11 private const val KEY_REMAINING_TIME_DISPLAY = "remaining_time_display" const val KEY_BLUETOOTH_DELAY = "key_bluetooth_delay" private const val LOADING_ANIMATION_DELAY = 1000 @Volatile internal var sDisplayRemainingTime: Boolean = false private const val PREF_TIPS_SHOWN = "video_player_tips_shown" private var clone: Boolean? = null fun start(context: Context, uri: Uri) { start(context, uri, null, false, -1) } fun start(context: Context, uri: Uri, fromStart: Boolean) { start(context, uri, null, fromStart, -1) } fun start(context: Context, uri: Uri, title: String) { start(context, uri, title, false, -1) } fun startOpened(context: Context, uri: Uri, openedPosition: Int) { start(context, uri, null, false, openedPosition) } private fun start(context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int) { val intent = getIntent(context, uri, title, fromStart, openedPosition) context.startActivity(intent) } fun getIntent(action: String, mw: MediaWrapper, fromStart: Boolean, openedPosition: Int): Intent { return getIntent(action, AppContextProvider.appContext, mw.uri, mw.title, fromStart, openedPosition) } fun getIntent(context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int): Intent { return getIntent(PLAY_FROM_VIDEOGRID, context, uri, title, fromStart, openedPosition) } fun getIntent(action: String, context: Context, uri: Uri, title: String?, fromStart: Boolean, openedPosition: Int): Intent { val intent = Intent(context, VideoPlayerActivity::class.java) intent.action = action intent.putExtra(PLAY_EXTRA_ITEM_LOCATION, uri) intent.putExtra(PLAY_EXTRA_ITEM_TITLE, title) intent.putExtra(PLAY_EXTRA_FROM_START, fromStart) if (openedPosition != -1 || context !is Activity) { if (openedPosition != -1) intent.putExtra(PLAY_EXTRA_OPENED_POSITION, openedPosition) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } return intent } } } @ExperimentalCoroutinesApi @ObsoleteCoroutinesApi @BindingAdapter("length", "time") fun setPlaybackTime(view: TextView, length: Long, time: Long) { view.text = if (VideoPlayerActivity.sDisplayRemainingTime && length > 0) "-" + '\u00A0'.toString() + Tools.millisToString(length - time) else Tools.millisToString(length) } @BindingAdapter("constraintPercent") fun setConstraintPercent(view: Guideline, percent: Float) { val constraintLayout = view.parent as ConstraintLayout val constraintSet = ConstraintSet() constraintSet.clone(constraintLayout) constraintSet.setGuidelinePercent(view.id, percent) constraintSet.applyTo(constraintLayout) } @BindingAdapter("mediamax") fun setProgressMax(view: SeekBar, length: Long) { view.max = length.toInt() } /** * hide the info view */ /** * show overlay with the previous timeout value */
gpl-2.0
coinbase/coinbase-java
app/src/main/java/com/coinbase/sample/MainApplication.kt
1
4474
/* * Copyright 2018 Coinbase, 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.coinbase.sample import android.app.Application import android.content.Context import android.content.Intent import android.util.Log import com.coinbase.Coinbase import com.coinbase.CoinbaseBuilder import com.coinbase.errors.CoinbaseOAuthException import com.coinbase.resources.auth.AccessToken import com.coinbase.resources.auth.RevokeTokenResponse import com.google.gson.Gson import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import okhttp3.logging.HttpLoggingInterceptor import java.util.* class MainApplication : Application() { lateinit var coinbase: Coinbase private set val savedExpireDate: Date? by lazy { val time = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getLong(KEY_EXPIRE_DATE, 0) if (time != 0L) { Date(time) } else { null } } var accessToken: AccessToken get() { val json = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE).getString(KEY_ACCESS_TOKEN, null) return if (json == null) AccessToken() else gson.fromJson(json, AccessToken::class.java) } set(value) { val json = gson.toJson(value) val expiresIn = Calendar.getInstance() expiresIn.add(Calendar.SECOND, value.expiresIn) getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) .edit() .putString(KEY_ACCESS_TOKEN, json) .putLong(KEY_EXPIRE_DATE, expiresIn.time.time) .apply() } private val gson = Gson() private val tokenUpdateListener = object : Coinbase.TokenListener { override fun onNewTokensAvailable(accessToken: AccessToken) { [email protected] = accessToken } override fun onRefreshFailed(cause: CoinbaseOAuthException) { Log.e("CoinbaseSample", "Access token autorefresh failed, logging out", cause) logout() } override fun onTokenRevoked() { logout() } } override fun onCreate() { super.onCreate() coinbase = buildCoinbase() } private fun buildCoinbase(): Coinbase { val builder = CoinbaseBuilder.withTokenAutoRefresh(this, BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET, accessToken.accessToken, accessToken.refreshToken, tokenUpdateListener ) builder.withLoggingLevel(HttpLoggingInterceptor.Level.BODY) return builder.withLoggingLevel(HttpLoggingInterceptor.Level.BODY).build() } fun revokeTokenRx(): Single<RevokeTokenResponse> { val savedAccessToken = accessToken return coinbase.authResource .revokeTokenRx(savedAccessToken.accessToken) .observeOn(AndroidSchedulers.mainThread()) .doOnSuccess { clearToken() } } fun refreshTokensRx(): Single<AccessToken> { return coinbase.authResource .refreshTokensRx(BuildConfig.CLIENT_ID, BuildConfig.CLIENT_SECRET, accessToken.refreshToken) .observeOn(AndroidSchedulers.mainThread()) } private fun clearToken() { getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) .edit() .clear() .apply() } fun logout() { clearToken() coinbase.logout() startActivity(Intent(this, LoginActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)) } companion object { const val PREF_NAME = "Sample App" private const val KEY_ACCESS_TOKEN = "access_token" private const val KEY_EXPIRE_DATE = "expireDate" } }
apache-2.0
ledao/chatbot
src/main/kotlin/com/davezhao/task/Skill.kt
1
83
package com.davezhao.task class Skill { lateinit var actions: List<Action> }
gpl-3.0
cout970/ComputerMod
src/main/kotlin/com/cout970/computer/gui/ContainerBase.kt
1
832
package com.cout970.computer.gui import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.InventoryPlayer import net.minecraft.inventory.Container import net.minecraft.inventory.Slot /** * Created by cout970 on 20/05/2016. */ open class ContainerBase : Container() { override fun canInteractWith(playerIn: EntityPlayer?): Boolean = true fun bindPlayerInventory(playerInventory: InventoryPlayer) { for (i in 0..2) { for (j in 0..8) { this.addSlotToContainer(Slot(playerInventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)) } } for (i in 0..8) { this.addSlotToContainer(Slot(playerInventory, i, 8 + i * 18, 142)) } } }
gpl-3.0
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/util/PCollectionExtensions.kt
1
474
package com.flexpoker.util import org.pcollections.HashTreePMap import org.pcollections.HashTreePSet import org.pcollections.PMap import org.pcollections.PSet import org.pcollections.PVector import org.pcollections.TreePVector fun <K, V> Map<K, V>.toPMap(): PMap<K, V> { return HashTreePMap.from(this) } fun <E> Collection<E>.toPSet(): PSet<E> { return HashTreePSet.from(this) } fun <E> Collection<E>.toPVector(): PVector<E> { return TreePVector.from(this) }
gpl-2.0
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/common/model/HttpFieldsExtension.kt
1
790
package com.fireflysource.net.http.common.model import com.fireflysource.net.http.common.model.HttpHeader.CONNECTION import com.fireflysource.net.http.common.model.HttpHeader.EXPECT import com.fireflysource.net.http.common.model.HttpHeaderValue.CLOSE import com.fireflysource.net.http.common.model.HttpHeaderValue.CONTINUE import com.fireflysource.net.http.common.model.HttpVersion.HTTP_0_9 import com.fireflysource.net.http.common.model.HttpVersion.HTTP_1_0 fun HttpFields.expectServerAcceptsContent(): Boolean { return this.contains(EXPECT, CONTINUE.value) } fun HttpFields.isCloseConnection(version: HttpVersion): Boolean = when (version) { HTTP_0_9, HTTP_1_0 -> !this.contains(CONNECTION, HttpHeaderValue.KEEP_ALIVE.value) else -> this.contains(CONNECTION, CLOSE.value) }
apache-2.0
nemerosa/ontrack
ontrack-extension-casc/src/test/java/net/nemerosa/ontrack/extension/casc/expressions/CascExpressionPreprocessorTest.kt
1
2144
package net.nemerosa.ontrack.extension.casc.expressions import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith internal class CascExpressionPreprocessorTest { private val mockExpressionContext = object : CascExpressionContext { override val name: String = "mock" override fun evaluate(value: String): String = value.uppercase() } private val multilineExpressionContext = object : CascExpressionContext { override val name: String = "multiline" private val expressions = mapOf( "test" to """ A clean multiline string """.trimIndent() ) override fun evaluate(value: String): String = expressions[value] ?: error("Cannot find multiline value for $value") } private val expressionPreprocessor = CascExpressionPreprocessor( listOf( mockExpressionContext, multilineExpressionContext, ) ) @Test fun `No change when no pattern`() { assertEquals( "value: no-pattern", expressionPreprocessor.process("value: no-pattern") ) } @Test fun `Error when no name`() { assertFailsWith<CascExpressionMissingNameException> { expressionPreprocessor.process("value: {{ }}") } } @Test fun `Error when no context`() { assertFailsWith<CascExpressionUnknownException> { expressionPreprocessor.process("value: {{ no-match }}") } } @Test fun `Matching a context`() { assertEquals( "value: TEST", expressionPreprocessor.process("value: {{ mock.test }}") ) } @Test fun `Multiline expression`() { assertEquals( """ value: |- A clean multiline string """.trimIndent(), expressionPreprocessor.process(""" value: |- {{ multiline.test }} """.trimIndent()) ) } }
mit
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GQLTypeValidationDataTypeConfig.kt
2
1263
package net.nemerosa.ontrack.graphql.schema import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.graphql.support.GQLScalarJSON import org.springframework.stereotype.Component /** * GraphQL type for [net.nemerosa.ontrack.model.structure.ValidationDataTypeConfig]. */ @Component class GQLTypeValidationDataTypeConfig( private val validationDataTypeDescriptor: GQLTypeValidationDataTypeDescriptor ) : GQLType { override fun getTypeName() = "ValidationDataTypeConfig" override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Configuration for the data type associated with a validation stamp") .field { it.name("descriptor") .description("Descriptor for the validation data type") .type(validationDataTypeDescriptor.typeRef) } .field { it.name("config") .description("Configuration object") .type(GQLScalarJSON.INSTANCE) } .build() }
mit
nemerosa/ontrack
ontrack-service/src/test/java/net/nemerosa/ontrack/service/security/SecuritySetupIT.kt
1
4565
package net.nemerosa.ontrack.service.security import net.nemerosa.ontrack.it.AbstractDSLTestJUnit4Support import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.structure.Project import org.junit.Test import org.springframework.security.access.AccessDeniedException import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue /** * Testing the basic security conditions. */ class SecuritySetupIT : AbstractDSLTestJUnit4Support() { @Test fun `Authentication is required to create a project`() { assertFailsWith<AccessDeniedException> { asAnonymous { structureService.newProject(Project.of(nameDescription())) } } } @Test fun `Admin user can create a project`() { val project = asAdmin { structureService.newProject(Project.of(nameDescription())) } assertTrue(project.id.isSet, "Project has been created") } @Test fun `Being authenticated is not enough to create a project`() { assertFailsWith<AccessDeniedException> { asUser().call { structureService.newProject(Project.of(nameDescription())) } } } @Test fun `Granting just enough rights`() { asUserWith<ProjectCreation> { structureService.newProject(Project.of(nameDescription())) } } @Test fun `Testing DSL to create a project`() { project { assertTrue(id.isSet, "Project has been created") } } @Test fun `Viewing projects is granted by default to all authenticated users`() { val project = project { branch() } val branches = asUser().call { structureService.getBranchesForProject(project.id) } assertTrue(branches.isNotEmpty(), "Could access the branches") } @Test fun `Viewing projects can be disabled for all authenticated users`() { val project = project { branch() } withNoGrantViewToAll { asUser().call { assertFailsWith<AccessDeniedException> { structureService.getBranchesForProject(project.id) } } } } @Test fun `Viewing projects needs to be granted explicitly when disabled globally`() { val project = project { branch() } withNoGrantViewToAll { val branches = asUser().withView(project).call { structureService.getBranchesForProject(project.id) } assertTrue(branches.isNotEmpty(), "Could access the branches") } } @Test fun `Participating into a project is granted to all by default`() { withGrantViewToAll { project { asUser { assertTrue(securityService.isProjectFunctionGranted(this, ProjectView::class.java)) assertTrue(securityService.isProjectFunctionGranted(this, ValidationRunStatusChange::class.java)) assertTrue(securityService.isProjectFunctionGranted(this, ValidationRunStatusCommentEditOwn::class.java)) } } } } @Test fun `Participating into a project can be disabled by default`() { withGrantViewAndNOParticipationToAll { project { asUser { assertTrue(securityService.isProjectFunctionGranted(this, ProjectView::class.java)) assertFalse(securityService.isProjectFunctionGranted(this, ValidationRunStatusChange::class.java)) assertFalse(securityService.isProjectFunctionGranted(this, ValidationRunStatusCommentEditOwn::class.java)) } } } } @Test fun `Participating into a project can be disabled by default and restored by project`() { withGrantViewAndNOParticipationToAll { project { val account = doCreateAccountWithProjectRole(this, Roles.PROJECT_PARTICIPANT) asFixedAccount(account) { assertTrue(securityService.isProjectFunctionGranted(this, ProjectView::class.java)) assertTrue(securityService.isProjectFunctionGranted(this, ValidationRunStatusChange::class.java)) assertTrue(securityService.isProjectFunctionGranted(this, ValidationRunStatusCommentEditOwn::class.java)) } } } } }
mit
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/forms/create/CreateTrainingSetBrowseButtonActionListener.kt
1
2539
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.forms.create import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Consumer import com.thomas.needham.neurophidea.Constants.TRAINING_SET_LOCATION_KEY import com.thomas.needham.neurophidea.actions.ShowCreateNetworkFormAction import com.thomas.needham.neurophidea.consumers.TrainingSetFileConsumer import java.awt.event.ActionEvent import java.awt.event.ActionListener /** * Created by Thomas Needham on 25/05/2016. */ class CreateTrainingSetBrowseButtonActionListener : ActionListener { var formInstance: CreateNetworkForm? = null companion object Data { val defaultPath = "" val allowedFileTypes = arrayOf("csv", "txt", "tset") val fileDescriptor = FileChooserDescriptor(true, false, false, false, false, false) val consumer: TrainingSetFileConsumer? = TrainingSetFileConsumer() val properties = PropertiesComponent.getInstance() var chosenPath = "" } override fun actionPerformed(e: ActionEvent?) { properties?.setValue(TRAINING_SET_LOCATION_KEY, defaultPath) FileChooser.chooseFile(fileDescriptor, ShowCreateNetworkFormAction.project, null, consumer as Consumer<VirtualFile?>) chosenPath = properties.getValue(TRAINING_SET_LOCATION_KEY, defaultPath) formInstance?.txtTrainingData?.text = chosenPath } }
mit
alpha-cross/ararat
library/src/main/java/org/akop/ararat/io/WSJFormatter.kt
1
8516
// Copyright (c) Akop Karapetyan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat.io import org.akop.ararat.core.Crossword import org.akop.ararat.core.buildWord import org.akop.ararat.util.SparseArray import org.akop.ararat.util.stripHtmlEntities import org.json.JSONArray import org.json.JSONObject import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.charset.Charset import java.text.SimpleDateFormat import java.util.* class WSJFormatter : CrosswordFormatter { private var encoding = Charset.forName(DEFAULT_ENCODING) override fun setEncoding(encoding: String) { this.encoding = Charset.forName(encoding) } @Throws(IOException::class) override fun read(builder: Crossword.Builder, inputStream: InputStream) { val json = inputStream.bufferedReader(encoding).use { it.readText() } val obj = JSONObject(json) val dataObj = obj.optJSONObject("data") ?: throw FormatException("Missing 'data'") val copyObj = dataObj.optJSONObject("copy") ?: throw FormatException("Missing 'data.copy'") val pubDate = copyObj.optString("date-publish") val gridObj = copyObj.optJSONObject("gridsize") ?: throw FormatException("Missing 'data.copy.gridsize'") builder.width = gridObj.optInt("cols") builder.height = gridObj.optInt("rows") builder.title = copyObj.optString("title") builder.description = copyObj.optString("description") builder.copyright = copyObj.optString("publisher") builder.author = copyObj.optString("byline") builder.date = PUBLISH_DATE_FORMAT.parse(pubDate)!!.time val grid = Grid(builder.width, builder.height, dataObj.getJSONArray("grid")) readClues(builder, copyObj, grid) } @Throws(IOException::class) override fun write(crossword: Crossword, outputStream: OutputStream) { throw UnsupportedOperationException("Writing not supported") } override fun canRead(): Boolean = true override fun canWrite(): Boolean = false private fun readClues(builder: Crossword.Builder, copyObj: JSONObject, grid: Grid) { val cluesArray = copyObj.optJSONArray("clues") when { cluesArray == null -> throw FormatException("Missing 'data.copy.clues[]'") cluesArray.length() != 2 -> throw FormatException("Unexpected clues length of '${cluesArray.length()}'") } val wordsArray = copyObj.optJSONArray("words") ?: throw FormatException("Missing 'data.copy.words[]'") // We'll need this to assign x/y locations to each clue val words = SparseArray<Word>() (0 until wordsArray.length()) .map { Word(wordsArray.optJSONObject(it)!!) } .forEach { words[it.id] = it } (0 until cluesArray.length()) .map { cluesArray.optJSONObject(it)!! } .forEach { val clueDir = it.optString("title") val dir = when (clueDir) { "Across" -> Crossword.Word.DIR_ACROSS "Down" -> Crossword.Word.DIR_DOWN else -> throw FormatException("Invalid direction: '$clueDir'") } val subcluesArray = it.optJSONArray("clues")!! (0 until subcluesArray.length()) .map { subcluesArray.optJSONObject(it)!! } .mapTo(builder.words) { buildWord { val word = words[it.optInt("word", -1)]!! direction = dir hint = it.optString("clue").stripHtmlEntities() number = it.optInt("number") startColumn = word.column startRow = word.row if (dir == Crossword.Word.DIR_ACROSS) { (startColumn until startColumn + word.length) .map { grid.squares[startRow][it]!! } .forEach { c -> addCell(c.char, c.attrFlags) } } else { (startRow until startRow + word.length) .map { grid.squares[it][startColumn]!! } .forEach { c -> addCell(c.char, c.attrFlags) } } } } } } private class Grid(width: Int, height: Int, gridArray: JSONArray) { val squares = Array<Array<Square?>>(height) { arrayOfNulls(width) } init { if (gridArray.length() != height) throw FormatException("Grid length mismatch (got: ${gridArray.length()}; exp.: $height)") for (i in 0 until height) { val rowArray = gridArray.optJSONArray(i) when { rowArray == null -> throw FormatException("Missing 'data.grid[$i]'") rowArray.length() != width -> throw FormatException("Grid row $i mismatch (got: ${rowArray.length()}); exp.: $width)") else -> (0 until width).forEach { j -> squares[i][j] = parseSquare(rowArray.optJSONObject(j)) } } } } private fun parseSquare(squareObj: JSONObject): Square? { val letter = squareObj.optString("Letter") val shapeBg = squareObj.optJSONObject("style")?.optString("shapebg") return when { letter.isNotEmpty() -> Square(letter, when (shapeBg) { "circle" -> Crossword.Cell.ATTR_CIRCLED else -> 0 }) else -> null } } } private class Square(val char: String, val attrFlags: Int = 0) private class Word(wordObj: JSONObject) { val id: Int = wordObj.optInt("id", -1) val row: Int val column: Int val length: Int init { if (id == -1) throw FormatException("Word missing identifier") val xStr: String = wordObj.optString("x") val xDashIdx: Int = xStr.indexOf('-') val yStr = wordObj.optString("y") val yDashIdx = yStr.indexOf('-') column = when { xDashIdx != -1 -> xStr.substring(0, xDashIdx).toInt() - 1 else -> xStr.toInt() - 1 } row = when { yDashIdx != -1 -> yStr.substring(0, yDashIdx).toInt() - 1 else -> yStr.toInt() - 1 } length = when { xDashIdx != -1 -> xStr.substring(xDashIdx + 1).toInt() - column yDashIdx != -1 -> yStr.substring(yDashIdx + 1).toInt() - row else -> 1 } } } companion object { private const val DEFAULT_ENCODING = "UTF-8" internal val PUBLISH_DATE_FORMAT = SimpleDateFormat("EEEE, d MMMM yyyy", Locale.US) } }
mit
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/feature/player/songlist/SelectPlaylistFragment.kt
1
6566
package be.florien.anyflow.feature.player.songlist import android.annotation.SuppressLint import android.content.DialogInterface import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import android.widget.EditText import androidx.appcompat.app.AlertDialog import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProvider import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import be.florien.anyflow.R import be.florien.anyflow.databinding.FragmentSelectPlaylistBinding import be.florien.anyflow.databinding.ItemSelectPlaylistBinding import be.florien.anyflow.extension.viewModelFactory import be.florien.anyflow.injection.ActivityScope import be.florien.anyflow.injection.UserScope import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView @ActivityScope @UserScope class SelectPlaylistFragment(private var songId: Long = 0L) : DialogFragment() { lateinit var viewModel: SelectPlaylistViewModel private lateinit var fragmentBinding: FragmentSelectPlaylistBinding init { arguments?.let { songId = it.getLong("SongId") } if (arguments == null) { arguments = Bundle().apply { putLong("SongId", songId) } } } @SuppressLint("NotifyDataSetChanged") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { viewModel = ViewModelProvider(this, requireActivity().viewModelFactory).get(SelectPlaylistViewModel::class.java) //todo change get viewmodel from attach to oncreateView in other fragments fragmentBinding = FragmentSelectPlaylistBinding.inflate(inflater, container, false) fragmentBinding.lifecycleOwner = viewLifecycleOwner fragmentBinding.viewModel = viewModel fragmentBinding.songId = songId fragmentBinding.filterList.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) fragmentBinding.filterList.adapter = FilterListAdapter() ResourcesCompat.getDrawable(resources, R.drawable.sh_divider, requireActivity().theme)?.let { fragmentBinding.filterList.addItemDecoration(DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL).apply { setDrawable(it) }) } viewModel.values.observe(viewLifecycleOwner) { if (it != null) (fragmentBinding.filterList.adapter as FilterListAdapter).submitData(lifecycle, it) } viewModel.currentSelectionLive.observe(viewLifecycleOwner) { (fragmentBinding.filterList.adapter as FilterListAdapter).notifyDataSetChanged() } viewModel.isCreating.observe(viewLifecycleOwner) { if (it) { val editText = EditText(requireActivity()) editText.inputType = EditorInfo.TYPE_CLASS_TEXT or EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES AlertDialog.Builder(requireActivity()) .setView(editText) .setTitle(R.string.info_action_new_playlist) .setPositiveButton(R.string.ok) { _: DialogInterface, _: Int -> viewModel.createPlaylist(editText.text.toString()) } .setNegativeButton(R.string.cancel) { dialog: DialogInterface, _: Int -> dialog.cancel() } .show() } } viewModel.isFinished.observe(viewLifecycleOwner) { if (it) { dismiss() } } return fragmentBinding.root } override fun onDismiss(dialog: DialogInterface) { val parentFragment = parentFragment if (parentFragment is DialogInterface.OnDismissListener) { parentFragment.onDismiss(dialog); } super.onDismiss(dialog) } inner class FilterListAdapter : PagingDataAdapter<SelectPlaylistViewModel.SelectionItem, PlaylistViewHolder>(object : DiffUtil.ItemCallback<SelectPlaylistViewModel.SelectionItem>() { override fun areItemsTheSame(oldItem: SelectPlaylistViewModel.SelectionItem, newItem: SelectPlaylistViewModel.SelectionItem) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: SelectPlaylistViewModel.SelectionItem, newItem: SelectPlaylistViewModel.SelectionItem): Boolean = oldItem.displayName == newItem.displayName && oldItem.isSelected == (viewModel.currentSelectionLive.value?.any { it.id == newItem.id }) }), FastScrollRecyclerView.SectionedAdapter { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaylistViewHolder = PlaylistViewHolder() override fun onBindViewHolder(holder: PlaylistViewHolder, position: Int) { val filter = getItem(position) ?: return filter.isSelected = viewModel.currentSelectionLive.value?.any { it.id == filter.id } ?: false holder.bind(filter) } override fun getSectionName(position: Int): String = snapshot()[position]?.displayName?.firstOrNull()?.uppercaseChar()?.toString() ?: "" } inner class PlaylistViewHolder( private val itemPlaylistBinding: ItemSelectPlaylistBinding = ItemSelectPlaylistBinding.inflate(layoutInflater, fragmentBinding.filterList, false) ) : RecyclerView.ViewHolder(itemPlaylistBinding.root) { fun bind(selection: SelectPlaylistViewModel.SelectionItem) { itemPlaylistBinding.vm = viewModel itemPlaylistBinding.lifecycleOwner = viewLifecycleOwner itemPlaylistBinding.item = selection setBackground(itemPlaylistBinding.root, selection) itemPlaylistBinding.root.setOnClickListener { viewModel.changeFilterSelection(selection) setBackground(itemPlaylistBinding.root, selection) } } private fun setBackground(view: View, selection: SelectPlaylistViewModel.SelectionItem?) { view.setBackgroundColor(ResourcesCompat.getColor(resources, if (selection?.isSelected == true) R.color.selected else R.color.unselected, requireActivity().theme)) } } }
gpl-3.0
nickbutcher/plaid
core/src/main/java/io/plaidapp/core/util/ImageUriProvider.kt
1
2058
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.plaidapp.core.util import android.content.Context import android.net.Uri import androidx.core.content.FileProvider import com.bumptech.glide.Glide import java.io.File import javax.inject.Inject /** * A class responsible for resolving an image as identified by Url into a sharable [Uri]. */ class ImageUriProvider @Inject constructor( context: Context, private val fileAuthority: FileAuthority ) { // Only hold the app context to avoid leaks private val appContext = context.applicationContext /** * Long running method! Making this a suspend function so it's only executed from a coroutine. * * Retrieve the image from Glide, as file, rename it, since Glide caches an unfriendly and * extension-less name, and then get the Uri. */ @Suppress("RedundantSuspendModifier") suspend operator fun invoke(url: String, width: Int, height: Int): Uri { // Retrieve the image from Glide (hopefully cached) as a File val file = Glide.with(appContext) .asFile() .load(url) .submit(width, height) .get() // Glide cache uses an unfriendly & extension-less name. Massage it based on the original. val fileName = url.substring(url.lastIndexOf('/') + 1) val renamed = File(file.parent, fileName) file.renameTo(renamed) return FileProvider.getUriForFile(appContext, fileAuthority.authority, renamed) } }
apache-2.0
deadpixelsociety/twodee
src/main/kotlin/com/thedeadpixelsociety/twodee/scripts/Duration.kt
1
266
package com.thedeadpixelsociety.twodee.scripts /** * Defines script durations. */ object Duration { /** * The duration lasts forever. */ const val INFINITE = -1f /** * The duration is instantaneous. */ const val INSTANT = 0f }
mit
mockk/mockk
modules/mockk/src/jvmTest/kotlin/io/mockk/it/JavaClassParamTest.kt
1
528
package io.mockk.it import io.mockk.every import io.mockk.mockk import io.mockk.verify import org.junit.Test import kotlin.test.assertFalse /** * Test related to github issue #29 */ @Suppress("UNUSED_PARAMETER") class JavaClassParamTest { class MockCls { fun op(klass: Class<*>): Boolean = true } @Test fun matchingAnyClass() { val mock = mockk<MockCls>() every { mock.op(any()) } returns false assertFalse(mock.op(Long::class.java)) verify { mock.op(any()) } } }
apache-2.0
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/reference/UnresolvedReferenceInspection.kt
1
2940
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.reference import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection import com.demonwav.mcdev.platform.mixin.reference.DescReference import com.demonwav.mcdev.platform.mixin.reference.InjectionPointReference import com.demonwav.mcdev.platform.mixin.reference.MethodReference import com.demonwav.mcdev.platform.mixin.reference.MixinReference import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference import com.demonwav.mcdev.platform.mixin.util.isWithinDynamicMixin import com.demonwav.mcdev.util.annotationFromNameValuePair import com.demonwav.mcdev.util.constantStringValue import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiAnnotationMemberValue import com.intellij.psi.PsiArrayInitializerMemberValue import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameValuePair class UnresolvedReferenceInspection : MixinInspection() { override fun getStaticDescription() = "Reports unresolved references in Mixin annotations" override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitNameValuePair(pair: PsiNameValuePair) { val name = pair.name ?: PsiAnnotation.DEFAULT_REFERENCED_METHOD_NAME val resolvers: Array<MixinReference> = when (name) { "method" -> arrayOf(MethodReference) "target" -> arrayOf(TargetReference) "value" -> arrayOf(InjectionPointReference, DescReference) else -> return } // Check if valid annotation val qualifiedName = pair.annotationFromNameValuePair?.qualifiedName ?: return val resolver = resolvers.firstOrNull { it.isValidAnnotation(qualifiedName) } ?: return val value = pair.value ?: return if (value is PsiArrayInitializerMemberValue) { for (initializer in value.initializers) { checkResolved(resolver, initializer) } } else { checkResolved(resolver, value) } } private fun checkResolved(resolver: MixinReference, value: PsiAnnotationMemberValue) { if (resolver.isUnresolved(value) && !value.isWithinDynamicMixin) { holder.registerProblem( value, "Cannot resolve ${resolver.description}".format(value.constantStringValue), ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } } }
mit
Orchextra/orchextra-android-sdk
geofence/src/main/java/com/gigigo/orchextra/geofence/GeofenceErrorMessages.kt
1
1806
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.geofence import android.content.Context import com.google.android.gms.common.api.ApiException import com.google.android.gms.location.GeofenceStatusCodes object GeofenceErrorMessages { fun getErrorString(context: Context, e: Exception?): String { return if (e is ApiException) { getErrorString(context, e.statusCode) } else { context.resources.getString(R.string.unknown_geofence_error) } } fun getErrorString(context: Context, errorCode: Int): String { val mResources = context.resources return when (errorCode) { GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE -> mResources.getString(R.string.geofence_not_available) GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES -> mResources.getString(R.string.geofence_too_many_geofences) GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS -> mResources.getString( R.string.geofence_too_many_pending_intents ) else -> mResources.getString(R.string.unknown_geofence_error) } } }
apache-2.0
dewarder/Android-Kotlin-Commons
akommons-bindings/src/androidTest/java/com/dewarder/akommons/binding/view/TestViewViewFinderProvider.kt
1
3087
/* * Copyright (C) 2017 Artem Hluhovskyi * * 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.dewarder.akommons.binding.view import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.dewarder.akommons.binding.* import com.dewarder.akommons.binding.common.NO_VIEW1 import com.dewarder.akommons.binding.common.NO_VIEW2 import com.dewarder.akommons.binding.common.view.TestableView import com.dewarder.akommons.binding.common.R class TestViewViewFinderProvider(val view: View) : ViewFinderProvider, TestableView { override val viewRequiredExist: View by view(R.id.test_view1) override val viewRequiredAbsent: View by view(NO_VIEW1) override val viewOptionalExist: View? by viewOptional(R.id.test_view1) override val viewOptionalAbsent: View? by viewOptional(NO_VIEW1) override val textViewRequiredCorrect: TextView by view(R.id.test_text_view1) override val textViewRequiredIncorrect: LinearLayout by view(R.id.test_text_view1) override val textViewOptionalCorrect: TextView? by viewOptional(R.id.test_text_view1) override val textViewOptionalIncorrect: LinearLayout? by viewOptional(R.id.test_text_view1) override val viewsRequiredExist: List<View> by views(R.id.test_view1, R.id.test_view2) override val viewsRequiredAbsent: List<View> by views(NO_VIEW1, NO_VIEW2) override val viewsOptionalExist: List<View?> by viewsOptional(R.id.test_view1, R.id.test_view2) override val viewsOptionalAbsent: List<View?> by viewsOptional(NO_VIEW1, NO_VIEW2) override val viewsRequiredFirstExistSecondAbsent: List<View> by views(R.id.test_view1, NO_VIEW1) override val viewsOptionalFirstExistSecondAbsent: List<View?> by viewsOptional(R.id.test_view1, NO_VIEW1) override val viewsRequiredExistCorrect: List<TextView> by views(R.id.test_text_view1, R.id.test_text_view2) override val viewsRequiredExistIncorrect: List<TextView> by views(R.id.test_text_view1, R.id.test_view1) override val viewsRequiredExistFirstViewSecondTextViewCorrect: List<View> by views(R.id.test_view1, R.id.test_text_view1) override val viewsOptionalExistCorrect: List<TextView?> by viewsOptional(R.id.test_text_view1, R.id.test_text_view2) override val viewsOptionalExistIncorrect: List<TextView?> by viewsOptional(R.id.test_text_view1, R.id.test_view1) override val viewsOptionalExistFirstViewSecondTextViewCorrect: List<View?> by viewsOptional(R.id.test_view1, R.id.test_text_view1) override fun provideViewFinder(): ViewFinder<View> = view::findViewById }
apache-2.0
apixandru/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/module/impl/ModulePointerManagerImpl.kt
10
3789
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.module.impl import com.intellij.ProjectTopics import com.intellij.openapi.Disposable import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.module.ModulePointer import com.intellij.openapi.module.ModulePointerManager import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.util.Function import gnu.trove.THashMap import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write /** * @author nik */ class ModulePointerManagerImpl(private val project: Project) : ModulePointerManager() { private val unresolved = THashMap<String, ModulePointerImpl>() private val pointers = THashMap<Module, ModulePointerImpl>() private val lock = ReentrantReadWriteLock() init { project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener { override fun beforeModuleRemoved(project: Project, module: Module) { unregisterPointer(module) } override fun moduleAdded(project: Project, module: Module) { moduleAppears(module) } override fun modulesRenamed(project: Project, modules: List<Module>, oldNameProvider: Function<Module, String>) { for (module in modules) { moduleAppears(module) } } }) } private fun moduleAppears(module: Module) { lock.write { unresolved.remove(module.name)?.let { it.moduleAdded(module) registerPointer(module, it) } } } private fun registerPointer(module: Module, pointer: ModulePointerImpl) { pointers.put(module, pointer) Disposer.register(module, Disposable { unregisterPointer(module) }) } private fun unregisterPointer(module: Module) { lock.write { pointers.remove(module)?.let { it.moduleRemoved(module) unresolved.put(it.moduleName, it) } } } @Suppress("UNNECESSARY_NOT_NULL_ASSERTION") override fun create(module: Module): ModulePointer { return lock.read { pointers.get(module) } ?: lock.write { pointers.get(module)?.let { return it } var pointer = unresolved.remove(module.name) if (pointer == null) { pointer = ModulePointerImpl(module, lock) } else { pointer.moduleAdded(module) } registerPointer(module, pointer) pointer!! } } override fun create(moduleName: String): ModulePointer { ModuleManager.getInstance(project).findModuleByName(moduleName)?.let { return create(it) } return lock.read { unresolved.get(moduleName) ?: lock.write { unresolved.get(moduleName)?.let { return it } // let's find in the pointers (if model not committed, see testDisposePointerFromUncommittedModifiableModel) pointers.keys.firstOrNull { it.name == moduleName }?.let { return create(it) } val pointer = ModulePointerImpl(moduleName, lock) unresolved.put(moduleName, pointer) pointer } } } }
apache-2.0
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/listenerList/ListenerListAnnotationChecker.kt
19
1907
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.transformations.listenerList import com.intellij.lang.annotation.AnnotationHolder import com.intellij.psi.PsiWildcardType import org.jetbrains.plugins.groovy.annotator.checkers.CustomAnnotationChecker import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration class ListenerListAnnotationChecker : CustomAnnotationChecker() { override fun checkApplicability(holder: AnnotationHolder, annotation: GrAnnotation): Boolean { if (annotation.qualifiedName != listenerListFqn) return false val modifierList = annotation.owner as? GrModifierList val parent = modifierList?.parent as? GrVariableDeclaration val field = parent?.variables?.singleOrNull() as? GrField ?: return true when (field.getListenerType()) { null -> holder.createErrorAnnotation(annotation, "@ListenerList field must have a generic Collection type") is PsiWildcardType -> holder.createErrorAnnotation(annotation, "@ListenerList field with generic wildcards not supported") } return true } }
apache-2.0
cashapp/sqldelight
sqldelight-compiler/src/test/kotlin/app/cash/sqldelight/core/queries/JavadocTest.kt
1
9951
package app.cash.sqldelight.core.queries import app.cash.sqldelight.core.TestDialect import app.cash.sqldelight.core.TestDialect.SQLITE_3_18 import app.cash.sqldelight.core.compiler.MutatorQueryGenerator import app.cash.sqldelight.core.compiler.SelectQueryGenerator import app.cash.sqldelight.core.dialects.binderCheck import app.cash.sqldelight.core.dialects.cursorCheck import app.cash.sqldelight.core.dialects.intKotlinType import app.cash.sqldelight.core.dialects.textType import app.cash.sqldelight.test.util.FixtureCompiler import com.google.common.truth.Truth.assertThat import com.squareup.burst.BurstJUnit4 import com.squareup.kotlinpoet.INT import com.squareup.kotlinpoet.LONG import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith @RunWith(BurstJUnit4::class) class JavadocTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun `select - properly formatted javadoc`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Queries all values. | */ |selectAll: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) } @Test fun `select - properly formatted javadoc when there are two`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Queries all values. | */ |selectAll: |SELECT * |FROM test; | |/** | * Queries all values. | */ |selectAll2: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) } @Test fun `select - multiline javadoc`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Queries all values. | * Returns values as a List. | * | * @deprecated Don't use it! | */ |selectAll: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | * Returns values as a List. | * | * @deprecated Don't use it! | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) } @Test fun `select - javadoc containing star symbols`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Queries all values. ** | * Returns values as a * List. | * | * ** @deprecated Don't use it! | */ |selectAll: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. ** | * Returns values as a * List. | * | * ** @deprecated Don't use it! | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) } @Test fun `select - single line javadoc`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** Queries all values. */ |selectAll: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) val int = testDialect.intKotlinType val toInt = when (int) { LONG -> "" INT -> ".toInt()" else -> error("Unknown kotlinType $int") } assertThat(selectGenerator.customResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | */ |public fun <T : kotlin.Any> selectAll(mapper: (_id: $int, value_: kotlin.String) -> T): app.cash.sqldelight.Query<T> = app.cash.sqldelight.Query(-585795480, arrayOf("test"), driver, "Test.sq", "selectAll", ""${'"'} ||SELECT * ||FROM test |""${'"'}.trimMargin()) { cursor -> | ${testDialect.cursorCheck(2)}mapper( | cursor.getLong(0)!!$toInt, | cursor.getString(1)!! | ) |} | """.trimMargin(), ) } @Test fun `select - misformatted javadoc`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** |Queries all values. |*/ |selectAll: |SELECT * |FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val selectGenerator = SelectQueryGenerator(file.namedQueries.first()) assertThat(selectGenerator.defaultResultTypeFunction().toString()).isEqualTo( """ |/** | * Queries all values. | */ |public fun selectAll(): app.cash.sqldelight.Query<com.example.Test> = selectAll { _id, value_ -> | com.example.Test( | _id, | value_ | ) |} | """.trimMargin(), ) } @Test fun `insert`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Insert new value. | */ |insertValue: |INSERT INTO test(value) |VALUES (?); | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val insert = file.namedMutators.first() val insertGenerator = MutatorQueryGenerator(insert) assertThat(insertGenerator.function().toString()).isEqualTo( """ |/** | * Insert new value. | */ |public fun insertValue(value_: kotlin.String): kotlin.Unit { | driver.execute(${insert.id}, ""${'"'} | |INSERT INTO test(value) | |VALUES (?) | ""${'"'}.trimMargin(), 1) { | ${testDialect.binderCheck}bindString(0, value_) | } | notifyQueries(${insert.id}) { emit -> | emit("test") | } |} | """.trimMargin(), ) } @Test fun `update`() { val file = FixtureCompiler.parseSql( createTable() + """ |/** | * Update value by id. | */ |updateById: |UPDATE test |SET value = ? |WHERE _id = ?; | """.trimMargin(), tempFolder, ) val update = file.namedMutators.first() val updateGenerator = MutatorQueryGenerator(update) assertThat(updateGenerator.function().toString()).isEqualTo( """ |/** | * Update value by id. | */ |public fun updateById(value_: kotlin.String, _id: kotlin.Long): kotlin.Unit { | driver.execute(${update.id}, ""${'"'} | |UPDATE test | |SET value = ? | |WHERE _id = ? | ""${'"'}.trimMargin(), 2) { | bindString(0, value_) | bindLong(1, _id) | } | notifyQueries(${update.id}) { emit -> | emit("test") | } |} | """.trimMargin(), ) } @Test fun `delete`(testDialect: TestDialect) { val file = FixtureCompiler.parseSql( createTable(testDialect) + """ |/** | * Delete all. | */ |deleteAll: |DELETE FROM test; | """.trimMargin(), tempFolder, dialect = testDialect.dialect, ) val delete = file.namedMutators.first() val deleteGenerator = MutatorQueryGenerator(delete) assertThat(deleteGenerator.function().toString()).isEqualTo( """ |/** | * Delete all. | */ |public fun deleteAll(): kotlin.Unit { | driver.execute(${delete.id}, ""${'"'}DELETE FROM test""${'"'}, 0) | notifyQueries(${delete.id}) { emit -> | emit("test") | } |} | """.trimMargin(), ) } companion object { private fun createTable(testDialect: TestDialect = SQLITE_3_18) = """ |CREATE TABLE test ( | _id INTEGER NOT NULL PRIMARY KEY DEFAULT 0, | value ${testDialect.textType} NOT NULL |); | """.trimMargin() } }
apache-2.0
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/psiUtil.kt
7
2648
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.util import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kIN import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod /** * @param owner modifier list owner * * @return * * `true` when owner has explicit type or it's not required for owner to have explicit type * * `false` when doesn't have explicit type and it's required to have a type or modifier * * `defaultValue` for the other owners * */ fun modifierListMayBeEmpty(owner: PsiElement?): Boolean = when (owner) { is GrParameter -> owner.parent.let { if (it is GrParameterList) return true if (it is GrForClause && it.declaredVariable != owner) return true if (it is GrForInClause && it.delimiter.node.elementType == kIN) return true return owner.typeElementGroovy != null } is GrMethod -> owner.isConstructor || owner.returnTypeElementGroovy != null && !owner.hasTypeParameters() is GrVariable -> owner.typeElementGroovy != null is GrVariableDeclaration -> owner.typeElementGroovy != null else -> true } fun GrExpression?.isSuperExpression(): Boolean { val referenceExpression = this as? GrReferenceExpression return referenceExpression?.referenceNameElement?.node?.elementType == GroovyTokenTypes.kSUPER }
apache-2.0
Jire/Abendigo
src/main/kotlin/org/abendigo/cached/InitializedCache.kt
2
290
package org.abendigo.cached class InitializedCached<T>(init: () -> T, lazy: T.() -> Any, private val initialized: T = init()) : Cached<T>({ lazy(initialized) initialized }) {} fun <T> initializedCache(initializer: () -> T, updater: T.() -> Any) = InitializedCached(initializer, updater)
gpl-3.0
nicolacimmino/playground
Spring/kotlin/expensesdemo/src/main/kotlin/com/nicolacimmino/expensesdemo/Extensions.kt
1
761
package com.nicolacimmino.expensesdemo import java.time.LocalDateTime import java.time.format.DateTimeFormatterBuilder import java.time.temporal.ChronoField import java.util.* fun LocalDateTime.format(): String = this.format(englishDateFormatter) private val daysLookup = (1..31).associate { it.toLong() to getOrdinal(it) } private val englishDateFormatter = DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd") .appendLiteral(" ") .appendText(ChronoField.DAY_OF_MONTH, daysLookup) .appendLiteral(" ") .appendPattern("yyyy") .toFormatter(Locale.ENGLISH) private fun getOrdinal(n: Int) = when { n in 11..13 -> "${n}th" n % 10 == 1 -> "${n}st" n % 10 == 2 -> "${n}nd" n % 10 == 3 -> "${n}rd" else -> "${n}th" }
gpl-3.0
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/photo/asymmetric/ImageItem.kt
1
1370
package ffc.app.photo.asymmetric import android.os.Parcel import android.os.Parcelable import com.felipecsl.asymmetricgridview.AsymmetricItem /** * Modified from ItemImage at abhisheklunagaria/FacebookTypeImageGrid */ class ImageItem( var urls: String, var _columnSpan: Int = 1, var _rowSpan: Int = 1 ) : AsymmetricItem { override fun getColumnSpan(): Int = _columnSpan override fun getRowSpan(): Int = _rowSpan fun setColumnSpan(span: Int) { _columnSpan = span } fun setRowSpan(span: Int) { _rowSpan = span } protected constructor(parcel: Parcel) : this( urls = parcel.readString()!!, _columnSpan = parcel.readInt(), _rowSpan = parcel.readInt() ) override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(urls) dest.writeInt(_columnSpan) dest.writeInt(_rowSpan) } companion object { @JvmField val CREATOR: Parcelable.Creator<ImageItem> = object : Parcelable.Creator<ImageItem> { override fun createFromParcel(parcel: Parcel): ImageItem { return ImageItem(parcel) } override fun newArray(size: Int): Array<ImageItem> { return newArray(size) } } } }
apache-2.0
Cleverdesk/cleverdesk
src/main/java/net/cleverdesk/cleverdesk/ui/Alert.kt
1
1069
/** * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.cleverdesk.cleverdesk.ui import net.cleverdesk.cleverdesk.plugin.Response /** * An alert only contains [text] that will be displayed to the user. * This should be use for Errors other short messages. */ class Alert(text: String) : Response { override val name: String = "Alert" var text: String = text /* override fun toJson(): String { return Gson().toJson(this) }*/ }
gpl-3.0
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/models/untis/timetable/PeriodMessengerChannel.kt
1
163
package com.sapuseven.untis.models.untis.timetable import kotlinx.serialization.Serializable @Serializable data class PeriodMessengerChannel( val id: String )
gpl-3.0
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/holder/StatusViewHolder.kt
1
32388
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.view.holder import android.support.annotation.DrawableRes import android.support.v4.content.ContextCompat import android.support.v4.widget.TextViewCompat import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView.ViewHolder import android.text.SpannableString import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.ForegroundColorSpan import android.view.View import android.view.View.OnClickListener import android.view.View.OnLongClickListener import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.RequestManager import kotlinx.android.synthetic.main.list_item_status.view.* import org.mariotaku.ktextension.* import de.vanita5.microblog.library.mastodon.annotation.StatusVisibility import de.vanita5.twittnuker.Constants.* import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.USER_TYPE_FANFOU_COM import de.vanita5.twittnuker.adapter.iface.IStatusesAdapter import de.vanita5.twittnuker.constant.SharedPreferenceConstants.VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.extension.model.applyTo import de.vanita5.twittnuker.extension.model.quoted_user_acct import de.vanita5.twittnuker.extension.model.retweeted_by_user_acct import de.vanita5.twittnuker.extension.model.user_acct import de.vanita5.twittnuker.extension.setVisible import de.vanita5.twittnuker.graphic.like.LikeAnimationDrawable import de.vanita5.twittnuker.model.ParcelableLocation import de.vanita5.twittnuker.model.ParcelableMedia import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.task.CreateFavoriteTask import de.vanita5.twittnuker.task.DestroyFavoriteTask import de.vanita5.twittnuker.task.RetweetStatusTask import de.vanita5.twittnuker.text.TwidereClickableSpan import de.vanita5.twittnuker.util.HtmlEscapeHelper.toPlainText import de.vanita5.twittnuker.util.HtmlSpanBuilder import de.vanita5.twittnuker.util.ThemeUtils import de.vanita5.twittnuker.util.UnitConvertUtils import de.vanita5.twittnuker.util.Utils import de.vanita5.twittnuker.util.Utils.getUserTypeIconRes import de.vanita5.twittnuker.view.ShapedImageView import de.vanita5.twittnuker.view.holder.iface.IStatusViewHolder import java.lang.ref.WeakReference class StatusViewHolder(private val adapter: IStatusesAdapter<*>, itemView: View) : ViewHolder(itemView), IStatusViewHolder { override val profileImageView: ShapedImageView by lazy { itemView.profileImage } override val profileTypeView: ImageView by lazy { itemView.profileType } private val itemContent by lazy { itemView.itemContent } private val mediaPreview by lazy { itemView.mediaPreview } private val statusContentUpperSpace by lazy { itemView.statusContentUpperSpace } private val summaryView by lazy { itemView.summary } private val textView by lazy { itemView.text } private val nameView by lazy { itemView.name } private val itemMenu by lazy { itemView.itemMenu } private val statusInfoLabel by lazy { itemView.statusInfoLabel } private val statusInfoIcon by lazy { itemView.statusInfoIcon } private val quotedNameView by lazy { itemView.quotedName } private val timeView by lazy { itemView.time } private val replyCountView by lazy { itemView.replyCount } private val retweetCountView by lazy { itemView.retweetCount } private val quotedView by lazy { itemView.quotedView } private val quotedTextView by lazy { itemView.quotedText } private val actionButtons by lazy { itemView.actionButtons } private val mediaLabel by lazy { itemView.mediaLabel } private val quotedMediaLabel by lazy { itemView.quotedMediaLabel } private val statusContentLowerSpace by lazy { itemView.statusContentLowerSpace } private val quotedMediaPreview by lazy { itemView.quotedMediaPreview } private val favoriteIcon by lazy { itemView.favoriteIcon } private val retweetIcon by lazy { itemView.retweetIcon } private val favoriteCountView by lazy { itemView.favoriteCount } private val replyButton by lazy { itemView.reply } private val retweetButton by lazy { itemView.retweet } private val favoriteButton by lazy { itemView.favorite } private val eventListener: EventListener private var statusClickListener: IStatusViewHolder.StatusClickListener? = null init { this.eventListener = EventListener(this) if (adapter.mediaPreviewEnabled) { View.inflate(mediaPreview.context, R.layout.layout_card_media_preview, itemView.mediaPreview) View.inflate(quotedMediaPreview.context, R.layout.layout_card_media_preview, itemView.quotedMediaPreview) } } fun displaySampleStatus() { val profileImageEnabled = adapter.profileImageEnabled profileImageView.visibility = if (profileImageEnabled) View.VISIBLE else View.GONE statusContentUpperSpace.visibility = View.VISIBLE adapter.requestManager.loadProfileImage(itemView.context, R.drawable.ic_account_logo_twitter, adapter.profileImageStyle, profileImageView.cornerRadius, profileImageView.cornerRadiusRatio).into(profileImageView) nameView.name = TWITTNUKER_PREVIEW_NAME nameView.screenName = "@$TWITTNUKER_PREVIEW_SCREEN_NAME" nameView.updateText(adapter.bidiFormatter) summaryView.hideIfEmpty() if (adapter.linkHighlightingStyle == VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) { textView.spannable = toPlainText(TWITTNUKER_PREVIEW_TEXT_HTML) } else { val linkify = adapter.twidereLinkify val text = HtmlSpanBuilder.fromHtml(TWITTNUKER_PREVIEW_TEXT_HTML) linkify.applyAllLinks(text, null, -1, false, adapter.linkHighlightingStyle, true) textView.spannable = text } timeView.time = System.currentTimeMillis() val showCardActions = isCardActionsShown if (adapter.mediaPreviewEnabled) { mediaPreview.visibility = View.VISIBLE mediaLabel.visibility = View.GONE } else { mediaPreview.visibility = View.GONE mediaLabel.visibility = View.VISIBLE } actionButtons.visibility = if (showCardActions) View.VISIBLE else View.GONE itemMenu.visibility = if (showCardActions) View.VISIBLE else View.GONE statusContentLowerSpace.visibility = if (showCardActions) View.GONE else View.VISIBLE quotedMediaPreview.visibility = View.GONE quotedMediaLabel.visibility = View.GONE mediaPreview.displayMedia(R.drawable.twittnuker_feature_graphic) } override fun display(status: ParcelableStatus, displayInReplyTo: Boolean, displayPinned: Boolean) { val context = itemView.context val requestManager = adapter.requestManager val twitter = adapter.twitterWrapper val linkify = adapter.twidereLinkify val formatter = adapter.bidiFormatter val colorNameManager = adapter.userColorNameManager val nameFirst = adapter.nameFirst val showCardActions = isCardActionsShown actionButtons.visibility = if (showCardActions) View.VISIBLE else View.GONE itemMenu.visibility = if (showCardActions) View.VISIBLE else View.GONE statusContentLowerSpace.visibility = if (showCardActions) View.GONE else View.VISIBLE val replyCount = status.reply_count val retweetCount = status.retweet_count val favoriteCount = status.favorite_count if (displayPinned && status.is_pinned_status) { statusInfoLabel.setText(R.string.pinned_status) statusInfoIcon.setImageResource(R.drawable.ic_activity_action_pinned) statusInfoLabel.visibility = View.VISIBLE statusInfoIcon.visibility = View.VISIBLE statusContentUpperSpace.visibility = View.GONE } else if (status.retweet_id != null) { val retweetedBy = colorNameManager.getDisplayName(status.retweeted_by_user_key!!, status.retweeted_by_user_name, status.retweeted_by_user_acct!!, nameFirst) statusInfoLabel.spannable = context.getString(R.string.name_retweeted, formatter.unicodeWrap(retweetedBy)) statusInfoIcon.setImageResource(R.drawable.ic_activity_action_retweet) statusInfoLabel.visibility = View.VISIBLE statusInfoIcon.visibility = View.VISIBLE statusContentUpperSpace.visibility = View.GONE } else if (status.in_reply_to_status_id != null && status.in_reply_to_user_key != null && displayInReplyTo) { if (status.in_reply_to_name != null && status.in_reply_to_screen_name != null) { val inReplyTo = colorNameManager.getDisplayName(status.in_reply_to_user_key!!, status.in_reply_to_name, status.in_reply_to_screen_name, nameFirst) statusInfoLabel.spannable = context.getString(R.string.in_reply_to_name, formatter.unicodeWrap(inReplyTo)) } else { statusInfoLabel.spannable = context.getString(R.string.label_status_type_reply) } statusInfoIcon.setImageResource(R.drawable.ic_activity_action_reply) statusInfoLabel.visibility = View.VISIBLE statusInfoIcon.visibility = View.VISIBLE statusContentUpperSpace.visibility = View.GONE } else { statusInfoLabel.visibility = View.GONE statusInfoIcon.visibility = View.GONE statusContentUpperSpace.visibility = View.VISIBLE } val skipLinksInText = status.extras?.support_entities ?: false if (status.is_quote) { quotedView.visibility = View.VISIBLE val quoteContentAvailable = status.quoted_text_plain != null && status.quoted_text_unescaped != null val isFanfouStatus = status.account_key.host == USER_TYPE_FANFOU_COM if (quoteContentAvailable && !isFanfouStatus) { quotedNameView.visibility = View.VISIBLE quotedTextView.visibility = View.VISIBLE val quoted_user_key = status.quoted_user_key!! quotedNameView.name = status.quoted_user_name quotedNameView.screenName = "@${status.quoted_user_acct}" val quotedDisplayEnd = status.extras?.quoted_display_text_range?.getOrNull(1) ?: -1 val quotedText: CharSequence if (adapter.linkHighlightingStyle != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) { quotedText = SpannableStringBuilder.valueOf(status.quoted_text_unescaped) status.quoted_spans?.applyTo(quotedText) linkify.applyAllLinks(quotedText, status.account_key, layoutPosition.toLong(), status.is_possibly_sensitive, adapter.linkHighlightingStyle, skipLinksInText) } else { quotedText = status.quoted_text_unescaped } if (quotedDisplayEnd != -1 && quotedDisplayEnd <= quotedText.length) { quotedTextView.spannable = quotedText.subSequence(0, quotedDisplayEnd) } else { quotedTextView.spannable = quotedText } quotedTextView.hideIfEmpty() val quoted_user_color = colorNameManager.getUserColor(quoted_user_key) if (quoted_user_color != 0) { quotedView.drawStart(quoted_user_color) } else { quotedView.drawStart(ThemeUtils.getColorFromAttribute(context, R.attr.quoteIndicatorBackgroundColor)) } displayQuotedMedia(requestManager, status) } else { quotedNameView.visibility = View.GONE quotedTextView.visibility = View.VISIBLE if (quoteContentAvailable) { displayQuotedMedia(requestManager, status) } else { quotedMediaPreview.visibility = View.GONE quotedMediaLabel.visibility = View.GONE } quotedTextView.spannable = if (!quoteContentAvailable) { // Display 'not available' label SpannableString.valueOf(context.getString(R.string.label_status_not_available)).apply { setSpan(ForegroundColorSpan(ThemeUtils.getColorFromAttribute(context, android.R.attr.textColorTertiary, textView.currentTextColor)), 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } else { // Display 'original status' label context.getString(R.string.label_original_status) } quotedView.drawStart(ThemeUtils.getColorFromAttribute(context, R.attr.quoteIndicatorBackgroundColor)) } itemContent.drawStart(colorNameManager.getUserColor(status.user_key)) } else { quotedView.visibility = View.GONE val userColor = colorNameManager.getUserColor(status.user_key) if (status.is_retweet) { val retweetUserColor = colorNameManager.getUserColor(status.retweeted_by_user_key!!) if (retweetUserColor == 0) { itemContent.drawStart(userColor) } else if (userColor == 0) { itemContent.drawStart(retweetUserColor) } else { itemContent.drawStart(retweetUserColor, userColor) } } else { itemContent.drawStart(userColor) } } timeView.time = if (status.is_retweet) { status.retweet_timestamp } else { status.timestamp } nameView.name = status.user_name nameView.screenName = "@${status.user_acct}" if (adapter.profileImageEnabled) { profileImageView.visibility = View.VISIBLE requestManager.loadProfileImage(context, status, adapter.profileImageStyle, profileImageView.cornerRadius, profileImageView.cornerRadiusRatio, adapter.profileImageSize).into(profileImageView) profileTypeView.setImageResource(getUserTypeIconRes(status.user_is_verified, status.user_is_protected)) profileTypeView.visibility = View.VISIBLE } else { profileImageView.visibility = View.GONE profileTypeView.setImageDrawable(null) profileTypeView.visibility = View.GONE } if (adapter.showAccountsColor) { itemContent.drawEnd(status.account_color) } else { itemContent.drawEnd() } val hasMediaLabel = mediaLabel.displayMediaLabel(status.card_name, status.media, status.location, status.place_full_name, status.is_possibly_sensitive) if (status.media.isNotNullOrEmpty()) { if (!adapter.sensitiveContentEnabled && status.is_possibly_sensitive) { // Sensitive content, show label instead of media view mediaLabel.contentDescription = status.media?.firstOrNull()?.alt_text mediaLabel.setVisible(hasMediaLabel) mediaPreview.visibility = View.GONE } else if (!adapter.mediaPreviewEnabled) { // Media preview disabled, just show label mediaLabel.contentDescription = status.media?.firstOrNull()?.alt_text mediaLabel.setVisible(hasMediaLabel) mediaPreview.visibility = View.GONE } else { // Show media mediaLabel.visibility = View.GONE mediaPreview.visibility = View.VISIBLE mediaPreview.displayMedia(requestManager = requestManager, media = status.media, accountKey = status.account_key, mediaClickListener = this) } } else { // No media, hide media preview mediaLabel.setVisible(hasMediaLabel) mediaPreview.visibility = View.GONE } summaryView.spannable = status.extras?.summary_text summaryView.hideIfEmpty() val text: CharSequence val displayEnd: Int if (!summaryView.empty && !isFullTextVisible) { text = SpannableStringBuilder.valueOf(context.getString(R.string.label_status_show_more)).apply { setSpan(object : TwidereClickableSpan(adapter.linkHighlightingStyle) { override fun onClick(widget: View?) { showFullText() } }, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } displayEnd = -1 } else if (adapter.linkHighlightingStyle != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) { text = SpannableStringBuilder.valueOf(status.text_unescaped).apply { status.spans?.applyTo(this) linkify.applyAllLinks(this, status.account_key, layoutPosition.toLong(), status.is_possibly_sensitive, adapter.linkHighlightingStyle, skipLinksInText) } displayEnd = status.extras?.display_text_range?.getOrNull(1) ?: -1 } else { text = status.text_unescaped displayEnd = status.extras?.display_text_range?.getOrNull(1) ?: -1 } if (displayEnd != -1 && displayEnd <= text.length) { textView.spannable = text.subSequence(0, displayEnd) } else { textView.spannable = text } textView.hideIfEmpty() if (replyCount > 0) { replyCountView.spannable = UnitConvertUtils.calculateProperCount(replyCount) } else { replyCountView.spannable = null } replyCountView.hideIfEmpty() when (status.extras?.visibility) { StatusVisibility.PRIVATE -> { retweetIcon.setImageResource(R.drawable.ic_action_lock) } StatusVisibility.DIRECT -> { retweetIcon.setImageResource(R.drawable.ic_action_message) } else -> { retweetIcon.setImageResource(R.drawable.ic_action_retweet) } } if (twitter.isDestroyingStatus(status.account_key, status.my_retweet_id)) { retweetIcon.isActivated = false } else { val creatingRetweet = RetweetStatusTask.isCreatingRetweet(status.account_key, status.id) retweetIcon.isActivated = creatingRetweet || status.retweeted || Utils.isMyRetweet(status.account_key, status.retweeted_by_user_key, status.my_retweet_id) } if (retweetCount > 0) { retweetCountView.spannable = UnitConvertUtils.calculateProperCount(retweetCount) } else { retweetCountView.spannable = null } retweetCountView.hideIfEmpty() if (DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id)) { favoriteIcon.isActivated = false } else { val creatingFavorite = CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id) favoriteIcon.isActivated = creatingFavorite || status.is_favorite } if (favoriteCount > 0) { favoriteCountView.spannable = UnitConvertUtils.calculateProperCount(favoriteCount) } else { favoriteCountView.spannable = null } favoriteCountView.hideIfEmpty() nameView.updateText(formatter) quotedNameView.updateText(formatter) } private fun displayQuotedMedia(requestManager: RequestManager, status: ParcelableStatus) { val hasMediaLabel = quotedMediaLabel.displayMediaLabel(null, status.quoted_media, null, null, status.is_possibly_sensitive) if (status.quoted_media.isNotNullOrEmpty()) { if (!adapter.sensitiveContentEnabled && status.is_possibly_sensitive) { quotedMediaLabel.setVisible(hasMediaLabel) // Sensitive content, show label instead of media view quotedMediaPreview.visibility = View.GONE } else if (!adapter.mediaPreviewEnabled) { quotedMediaLabel.setVisible(hasMediaLabel) // Media preview disabled, just show label quotedMediaPreview.visibility = View.GONE } else if (status.media.isNotNullOrEmpty()) { quotedMediaLabel.setVisible(hasMediaLabel) // Already displaying media, show label only quotedMediaPreview.visibility = View.GONE } else { quotedMediaLabel.visibility = View.GONE // Show media quotedMediaPreview.visibility = View.VISIBLE quotedMediaPreview.displayMedia(requestManager = requestManager, media = status.quoted_media, accountKey = status.account_key, mediaClickListener = this) } } else { quotedMediaLabel.setVisible(hasMediaLabel) // No media, hide all related views quotedMediaPreview.visibility = View.GONE } } override fun onMediaClick(view: View, current: ParcelableMedia, accountKey: UserKey?, id: Long) { if (view.parent == quotedMediaPreview) { statusClickListener?.onQuotedMediaClick(this, view, current, layoutPosition) } else { statusClickListener?.onMediaClick(this, view, current, layoutPosition) } } fun setOnClickListeners() { setStatusClickListener(adapter.statusClickListener) } override fun setStatusClickListener(listener: IStatusViewHolder.StatusClickListener?) { statusClickListener = listener itemContent.setOnClickListener(eventListener) itemContent.setOnLongClickListener(eventListener) itemMenu.setOnClickListener(eventListener) profileImageView.setOnClickListener(eventListener) replyButton.setOnClickListener(eventListener) retweetButton.setOnClickListener(eventListener) favoriteButton.setOnClickListener(eventListener) retweetButton.setOnLongClickListener(eventListener) favoriteButton.setOnLongClickListener(eventListener) mediaLabel.setOnClickListener(eventListener) quotedView.setOnClickListener(eventListener) } override fun setTextSize(textSize: Float) { nameView.setPrimaryTextSize(textSize) quotedNameView.setPrimaryTextSize(textSize) summaryView.textSize = textSize textView.textSize = textSize quotedTextView.textSize = textSize nameView.setSecondaryTextSize(textSize * 0.85f) quotedNameView.setSecondaryTextSize(textSize * 0.85f) timeView.textSize = textSize * 0.85f statusInfoLabel.textSize = textSize * 0.75f mediaLabel.textSize = textSize * 0.95f quotedMediaLabel.textSize = textSize * 0.95f replyCountView.textSize = textSize retweetCountView.textSize = textSize favoriteCountView.textSize = textSize } fun setupViewOptions() { setTextSize(adapter.textSize) profileImageView.style = adapter.profileImageStyle mediaPreview.style = adapter.mediaPreviewStyle quotedMediaPreview.style = adapter.mediaPreviewStyle // profileImageView.setStyle(adapter.getProfileImageStyle()); val nameFirst = adapter.nameFirst nameView.nameFirst = nameFirst quotedNameView.nameFirst = nameFirst val favIcon: Int val favStyle: Int val favColor: Int val context = itemView.context if (adapter.useStarsForLikes) { favIcon = R.drawable.ic_action_star favStyle = LikeAnimationDrawable.Style.FAVORITE favColor = ContextCompat.getColor(context, R.color.highlight_favorite) } else { favIcon = R.drawable.ic_action_heart favStyle = LikeAnimationDrawable.Style.LIKE favColor = ContextCompat.getColor(context, R.color.highlight_like) } val icon = ContextCompat.getDrawable(context, favIcon) val drawable = LikeAnimationDrawable(icon, favoriteCountView.textColors.defaultColor, favColor, favStyle) drawable.mutate() favoriteIcon.setImageDrawable(drawable) timeView.showAbsoluteTime = adapter.showAbsoluteTime favoriteIcon.activatedColor = favColor nameView.applyFontFamily(adapter.lightFont) timeView.applyFontFamily(adapter.lightFont) summaryView.applyFontFamily(adapter.lightFont) textView.applyFontFamily(adapter.lightFont) mediaLabel.applyFontFamily(adapter.lightFont) quotedNameView.applyFontFamily(adapter.lightFont) quotedTextView.applyFontFamily(adapter.lightFont) quotedMediaLabel.applyFontFamily(adapter.lightFont) } override fun playLikeAnimation(listener: LikeAnimationDrawable.OnLikedListener) { var handled = false val drawable = favoriteIcon.drawable if (drawable is LikeAnimationDrawable) { drawable.setOnLikedListener(listener) drawable.start() handled = true } if (!handled) { listener.onLiked() } } private val isCardActionsShown: Boolean get() = adapter.isCardActionsShown(layoutPosition) private val isFullTextVisible: Boolean get() = adapter.isFullTextVisible(layoutPosition) private fun showCardActions() { adapter.showCardActions(layoutPosition) } private fun hideTempCardActions(): Boolean { adapter.showCardActions(RecyclerView.NO_POSITION) return !adapter.isCardActionsShown(RecyclerView.NO_POSITION) } private fun showFullText() { adapter.setFullTextVisible(layoutPosition, true) } private fun hideFullText(): Boolean { adapter.setFullTextVisible(layoutPosition, false) return !adapter.isFullTextVisible(RecyclerView.NO_POSITION) } private fun TextView.displayMediaLabel(cardName: String?, media: Array<ParcelableMedia?>?, location: ParcelableLocation?, placeFullName: String?, sensitive: Boolean): Boolean { var result = false if (media != null && media.isNotEmpty()) { if (sensitive) { setLabelIcon(R.drawable.ic_label_warning) setText(R.string.label_sensitive_content) } else when { media.type in videoTypes -> { setLabelIcon(R.drawable.ic_label_video) setText(R.string.label_video) } media.size > 1 -> { setLabelIcon(R.drawable.ic_label_gallery) setText(R.string.label_photos) } else -> { setLabelIcon(R.drawable.ic_label_gallery) setText(R.string.label_photo) } } result = true } else if (cardName != null) { if (cardName.startsWith("poll")) { setLabelIcon(R.drawable.ic_label_poll) setText(R.string.label_poll) result = true } } refreshDrawableState() return result } private fun TextView.setLabelIcon(@DrawableRes icon: Int) { TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(this, icon, 0, 0, 0) } private val Array<ParcelableMedia?>.type: Int get() { forEach { if (it != null) return it.type } return 0 } private fun hasVideo(media: Array<ParcelableMedia?>?): Boolean { if (media == null) return false return media.any { item -> if (item == null) return@any false return@any videoTypes.contains(item.type) } } internal class EventListener(holder: StatusViewHolder) : OnClickListener, OnLongClickListener { private val holderRef = WeakReference(holder) override fun onClick(v: View) { val holder = holderRef.get() ?: return val listener = holder.statusClickListener ?: return val position = holder.layoutPosition when (v) { holder.itemContent -> { listener.onStatusClick(holder, position) } holder.quotedView -> { listener.onQuotedStatusClick(holder, position) } holder.itemMenu -> { listener.onItemMenuClick(holder, v, position) } holder.profileImageView -> { listener.onUserProfileClick(holder, position) } holder.replyButton -> { listener.onItemActionClick(holder, R.id.reply, position) } holder.retweetButton -> { listener.onItemActionClick(holder, R.id.retweet, position) } holder.favoriteButton -> { listener.onItemActionClick(holder, R.id.favorite, position) } holder.mediaLabel -> { val firstMedia = holder.adapter.getStatus(position).media?.firstOrNull() if (firstMedia != null) { listener.onMediaClick(holder, v, firstMedia, position) } else { listener.onStatusClick(holder, position) } } } } override fun onLongClick(v: View): Boolean { val holder = holderRef.get() ?: return false val listener = holder.statusClickListener ?: return false val position = holder.layoutPosition when (v) { holder.itemContent -> { if (!holder.isCardActionsShown) { holder.showCardActions() return true } else if (holder.hideTempCardActions()) { return true } return listener.onStatusLongClick(holder, position) } holder.favoriteButton -> { return listener.onItemActionLongClick(holder, R.id.favorite, position) } holder.retweetButton -> { return listener.onItemActionLongClick(holder, R.id.retweet, position) } } return false } } companion object { const val layoutResource = R.layout.list_item_status private val videoTypes = intArrayOf(ParcelableMedia.Type.VIDEO, ParcelableMedia.Type.ANIMATED_GIF, ParcelableMedia.Type.EXTERNAL_PLAYER) } }
gpl-3.0
ham1/jmeter
src/core/src/test/kotlin/org/apache/jmeter/threads/openmodel/ThreadScheduleTest.kt
3
2622
/* * 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.jmeter.threads.openmodel import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource import kotlin.test.assertEquals class ThreadScheduleTest { class Case(val input: String, val expected: String) { override fun toString() = input } companion object { @JvmStatic fun data() = listOf( Case("rate(0/min)", "[Rate(0)]"), Case("rate(36000/hour)", "[Rate(10)]"), Case("random_arrivals(0) /* 0 does not require time unit */", "[Arrivals(type=RANDOM, duration=0)]"), Case( "rate(1/sec) random_arrivals(2 min) pause(3 min) random_arrivals(4 sec)", "[Rate(1), Arrivals(type=RANDOM, duration=120), Rate(1), Rate(0), Arrivals(type=EVEN, duration=180), Rate(0), Rate(1), Arrivals(type=RANDOM, duration=4)]" ), Case("rate(50.1/sec)", "[Rate(50.1)]"), Case("even_arrivals(50 min)", "[Arrivals(type=EVEN, duration=3000)]"), Case("even_arrivals(2d 1m 30s)", "[Arrivals(type=EVEN, duration=${2 * 86400 + 60 + 30})]"), Case( "rate(50/min) even_arrivals(2 hour) rate(60/min)", "[Rate(0.8), Arrivals(type=EVEN, duration=7200), Rate(1)]" ), Case( "rate(0 per min) even_arrivals(30 min) rate(50 per min) random_arrivals(4 min) rate(200 per min) random_arrivals(10 sec)", "[Rate(0), Arrivals(type=EVEN, duration=1800), Rate(0.8), Arrivals(type=RANDOM, duration=240), Rate(3.3), Arrivals(type=RANDOM, duration=10)]" ) ) } @ParameterizedTest @MethodSource("data") fun test(case: Case) { assertEquals(case.expected, ThreadSchedule(case.input).toString(), case.input) } }
apache-2.0
slartus/4pdaClient-plus
forum/forum-data/src/main/java/org/softeg/slartus/forpdaplus/forum/data/LocalForumDataSource.kt
1
733
package org.softeg.slartus.forpdaplus.forum.data import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.softeg.slartus.forpdaplus.forum.data.db.ForumDao import org.softeg.slartus.forpdaplus.forum.data.db.mapToDb import org.softeg.slartus.forpdaplus.forum.data.db.mapToItem import ru.softeg.slartus.forum.api.ForumItem import javax.inject.Inject class LocalForumDataSource @Inject constructor(private val forumDao: ForumDao) { suspend fun getAll(): List<ForumItem> = withContext(Dispatchers.IO) { forumDao.getAll().map { it.mapToItem() } } suspend fun merge(forums: List<ForumItem>) = withContext(Dispatchers.IO) { forumDao.replaceAll(forums.map { it.mapToDb() }) } }
apache-2.0
stripe/stripe-android
link/src/test/java/com/stripe/android/link/repositories/LinkApiRepositoryTest.kt
1
25256
package com.stripe.android.link.repositories import com.google.common.truth.Truth.assertThat import com.stripe.android.core.networking.ApiRequest import com.stripe.android.link.model.PaymentDetailsFixtures import com.stripe.android.link.ui.paymentmethod.SupportedPaymentMethod import com.stripe.android.model.ConsumerPaymentDetails import com.stripe.android.model.ConsumerPaymentDetailsCreateParams import com.stripe.android.model.ConsumerPaymentDetailsUpdateParams import com.stripe.android.model.ConsumerSession import com.stripe.android.model.ConsumerSessionLookup import com.stripe.android.model.ConsumerSignUpConsentAction import com.stripe.android.model.FinancialConnectionsSession import com.stripe.android.model.PaymentIntent import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.android.networking.StripeRepository import com.stripe.android.ui.core.FieldValuesToParamsMapConverter import com.stripe.android.ui.core.elements.IdentifierSpec import com.stripe.android.ui.core.forms.FormFieldEntry import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import java.util.Locale @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) class LinkApiRepositoryTest { private val stripeRepository = mock<StripeRepository>() private val paymentIntent = mock<PaymentIntent>().apply { whenever(clientSecret).thenReturn("secret") } private val linkRepository = LinkApiRepository( publishableKeyProvider = { PUBLISHABLE_KEY }, stripeAccountIdProvider = { STRIPE_ACCOUNT_ID }, stripeRepository = stripeRepository, workContext = Dispatchers.IO, locale = Locale.US ) @Test fun `lookupConsumer sends correct parameters`() = runTest { val email = "[email protected]" val cookie = "cookie1" linkRepository.lookupConsumer(email, cookie) verify(stripeRepository).lookupConsumerSession( eq(email), eq(cookie), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `lookupConsumer returns successful result`() = runTest { val consumerSessionLookup = mock<ConsumerSessionLookup>() whenever(stripeRepository.lookupConsumerSession(any(), any(), any())) .thenReturn(consumerSessionLookup) val result = linkRepository.lookupConsumer("email", "cookie") assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerSessionLookup) } @Test fun `lookupConsumer catches exception and returns failure`() = runTest { whenever(stripeRepository.lookupConsumerSession(any(), any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.lookupConsumer("email", "cookie") assertThat(result.isFailure).isTrue() } @Test fun `consumerSignUp sends correct parameters`() = runTest { val email = "[email protected]" val phone = "phone" val country = "US" val name = "name" val cookie = "cookie2" linkRepository.consumerSignUp( email, phone, country, name, cookie, ConsumerSignUpConsentAction.Checkbox ) verify(stripeRepository).consumerSignUp( eq(email), eq(phone), eq(country), eq(name), eq(Locale.US), eq(cookie), eq(ConsumerSignUpConsentAction.Checkbox), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `consumerSignUp returns successful result`() = runTest { val consumerSession = mock<ConsumerSession>() whenever( stripeRepository.consumerSignUp( email = any(), phoneNumber = any(), country = any(), name = anyOrNull(), locale = anyOrNull(), authSessionCookie = anyOrNull(), consentAction = any(), requestOptions = any() ) ).thenReturn(consumerSession) val result = linkRepository.consumerSignUp( "email", "phone", "country", "name", "cookie", ConsumerSignUpConsentAction.Checkbox ) assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerSession) } @Test fun `consumerSignUp catches exception and returns failure`() = runTest { whenever( stripeRepository.consumerSignUp( email = any(), phoneNumber = any(), country = any(), name = anyOrNull(), locale = anyOrNull(), authSessionCookie = anyOrNull(), consentAction = any(), requestOptions = any() ) ).thenThrow(RuntimeException("error")) val result = linkRepository.consumerSignUp( "email", "phone", "country", "name", "cookie", ConsumerSignUpConsentAction.Button ) assertThat(result.isFailure).isTrue() } @Test fun `startVerification sends correct parameters`() = runTest { val secret = "secret" val cookie = "cookie1" val consumerKey = "key" linkRepository.startVerification(secret, consumerKey, cookie) verify(stripeRepository).startConsumerVerification( eq(secret), eq(Locale.US), eq(cookie), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `startVerification without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val cookie = "cookie1" linkRepository.startVerification(secret, null, cookie) verify(stripeRepository).startConsumerVerification( eq(secret), eq(Locale.US), eq(cookie), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `startVerification returns successful result`() = runTest { val consumerSession = mock<ConsumerSession>() whenever(stripeRepository.startConsumerVerification(any(), any(), anyOrNull(), any())) .thenReturn(consumerSession) val result = linkRepository.startVerification("secret", "key", "cookie") assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerSession) } @Test fun `startVerification catches exception and returns failure`() = runTest { whenever(stripeRepository.startConsumerVerification(any(), any(), anyOrNull(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.startVerification("secret", "key", "cookie") assertThat(result.isFailure).isTrue() } @Test fun `confirmVerification sends correct parameters`() = runTest { val secret = "secret" val code = "code" val cookie = "cookie2" val consumerKey = "key2" linkRepository.confirmVerification(code, secret, consumerKey, cookie) verify(stripeRepository).confirmConsumerVerification( eq(secret), eq(code), eq(cookie), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `confirmVerification without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val code = "code" val cookie = "cookie2" linkRepository.confirmVerification(code, secret, null, cookie) verify(stripeRepository).confirmConsumerVerification( eq(secret), eq(code), eq(cookie), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `confirmVerification returns successful result`() = runTest { val consumerSession = mock<ConsumerSession>() whenever(stripeRepository.confirmConsumerVerification(any(), any(), anyOrNull(), any())) .thenReturn(consumerSession) val result = linkRepository.confirmVerification("code", "secret", "key", "cookie") assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerSession) } @Test fun `confirmVerification catches exception and returns failure`() = runTest { whenever(stripeRepository.confirmConsumerVerification(any(), any(), anyOrNull(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.confirmVerification("code", "secret", "key", "cookie") assertThat(result.isFailure).isTrue() } @Test fun `logout sends correct parameters`() = runTest { val secret = "secret" val cookie = "cookie2" val consumerKey = "key2" linkRepository.logout(secret, consumerKey, cookie) verify(stripeRepository).logoutConsumer( eq(secret), eq(cookie), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `logout without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val cookie = "cookie2" linkRepository.logout(secret, null, cookie) verify(stripeRepository).logoutConsumer( eq(secret), eq(cookie), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `logout returns successful result`() = runTest { val consumerSession = mock<ConsumerSession>() whenever(stripeRepository.logoutConsumer(any(), any(), any())) .thenReturn(consumerSession) val result = linkRepository.logout("secret", "key", "cookie") assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerSession) } @Test fun `logout catches exception and returns failure`() = runTest { whenever(stripeRepository.logoutConsumer(any(), any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.logout("secret", "key", "cookie") assertThat(result.isFailure).isTrue() } @Test fun `listPaymentDetails sends correct parameters`() = runTest { val secret = "secret" val consumerKey = "key" linkRepository.listPaymentDetails(secret, consumerKey) verify(stripeRepository).listPaymentDetails( eq(secret), eq(SupportedPaymentMethod.allTypes), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `listPaymentDetails without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" linkRepository.listPaymentDetails(secret, null) verify(stripeRepository).listPaymentDetails( eq(secret), eq(SupportedPaymentMethod.allTypes), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `listPaymentDetails returns successful result`() = runTest { val paymentDetails = mock<ConsumerPaymentDetails>() whenever(stripeRepository.listPaymentDetails(any(), any(), any())) .thenReturn(paymentDetails) val result = linkRepository.listPaymentDetails("secret", "key") assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(paymentDetails) } @Test fun `listPaymentDetails catches exception and returns failure`() = runTest { whenever(stripeRepository.listPaymentDetails(any(), any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.listPaymentDetails("secret", "key") assertThat(result.isFailure).isTrue() } @Test fun `deletePaymentDetails sends correct parameters`() = runTest { val secret = "secret" val id = "payment_details_id" val consumerKey = "key" linkRepository.deletePaymentDetails(id, secret, consumerKey) verify(stripeRepository).deletePaymentDetails( eq(secret), eq(id), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `deletePaymentDetails without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val id = "payment_details_id" linkRepository.deletePaymentDetails(id, secret, null) verify(stripeRepository).deletePaymentDetails( eq(secret), eq(id), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `deletePaymentDetails returns successful result`() = runTest { whenever(stripeRepository.deletePaymentDetails(any(), any(), any())).thenReturn(Unit) val result = linkRepository.deletePaymentDetails("id", "secret", "key") assertThat(result.isSuccess).isTrue() } @Test fun `deletePaymentDetails catches exception and returns failure`() = runTest { whenever(stripeRepository.deletePaymentDetails(any(), any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.deletePaymentDetails("id", "secret", "key") assertThat(result.isFailure).isTrue() } @Test fun `createFinancialConnectionsSession sends correct parameters`() = runTest { val secret = "secret" val consumerKey = "key" linkRepository.createFinancialConnectionsSession(secret, consumerKey) verify(stripeRepository).createLinkFinancialConnectionsSession( eq(secret), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `createFinancialConnectionsSession returns successful result`() = runTest { val session = FinancialConnectionsSession("client_secret", "id") whenever(stripeRepository.createLinkFinancialConnectionsSession(any(), any())).thenReturn( session ) val result = linkRepository.createFinancialConnectionsSession("secret", "key") assertThat(result.isSuccess).isTrue() } @Test fun `createFinancialConnectionsSession catches exception and returns failure`() = runTest { whenever(stripeRepository.createLinkFinancialConnectionsSession(any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.createFinancialConnectionsSession("secret", "key") assertThat(result.isFailure).isTrue() } @Test fun `createPaymentDetails for financial connections sends correct parameters`() = runTest { val accountId = "id" val secret = "secret" val consumerKey = "key" linkRepository.createBankAccountPaymentDetails( financialConnectionsAccountId = accountId, consumerSessionClientSecret = secret, consumerPublishableKey = consumerKey ) verify(stripeRepository).createPaymentDetails( eq(secret), eq(accountId), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `createPaymentDetails for financial connections returns new LinkPaymentDetails when successful`() = runTest { val accountId = "id" val secret = "secret" val consumerKey = "key" val paymentDetails = PaymentDetailsFixtures.CONSUMER_SINGLE_BANK_ACCOUNT_PAYMENT_DETAILS whenever(stripeRepository.createPaymentDetails(any(), any<String>(), any())) .thenReturn(paymentDetails) val result = linkRepository.createBankAccountPaymentDetails( financialConnectionsAccountId = accountId, consumerSessionClientSecret = secret, consumerPublishableKey = consumerKey ) assertThat(result.isSuccess).isTrue() } @Test fun `createPaymentDetails for financial connections catches exception and returns failure`() = runTest { val accountId = "id" val secret = "secret" val consumerKey = "key" whenever(stripeRepository.createPaymentDetails(any(), any<String>(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.createBankAccountPaymentDetails( financialConnectionsAccountId = accountId, consumerSessionClientSecret = secret, consumerPublishableKey = consumerKey ) assertThat(result.isFailure).isTrue() } @Test fun `createPaymentDetails for card sends correct parameters`() = runTest { val secret = "secret" val email = "[email protected]" val consumerKey = "key" linkRepository.createCardPaymentDetails( paymentMethodCreateParams = cardPaymentMethodCreateParams, userEmail = email, stripeIntent = paymentIntent, consumerSessionClientSecret = secret, consumerPublishableKey = consumerKey ) verify(stripeRepository).createPaymentDetails( eq(secret), argThat<ConsumerPaymentDetailsCreateParams> { toParamMap() == mapOf( "type" to "card", "billing_email_address" to "[email protected]", "card" to mapOf( "number" to "5555555555554444", "exp_month" to "12", "exp_year" to "2050" ), "billing_address" to mapOf( "country_code" to "US", "postal_code" to "12345" ) ) }, eq(ApiRequest.Options(consumerKey)) ) } @Test fun `createPaymentDetails for card without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val email = "[email protected]" linkRepository.createCardPaymentDetails( paymentMethodCreateParams = cardPaymentMethodCreateParams, userEmail = email, stripeIntent = paymentIntent, consumerSessionClientSecret = secret, consumerPublishableKey = null ) verify(stripeRepository).createPaymentDetails( eq(secret), argThat<ConsumerPaymentDetailsCreateParams> { toParamMap() == mapOf( "type" to "card", "billing_email_address" to "[email protected]", "card" to mapOf( "number" to "5555555555554444", "exp_month" to "12", "exp_year" to "2050" ), "billing_address" to mapOf( "country_code" to "US", "postal_code" to "12345" ) ) }, eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `createPaymentDetails for card returns new LinkPaymentDetails when successful`() = runTest { val consumerSessionSecret = "consumer_session_secret" val email = "[email protected]" val paymentDetails = PaymentDetailsFixtures.CONSUMER_SINGLE_PAYMENT_DETAILS whenever( stripeRepository.createPaymentDetails( any(), any<ConsumerPaymentDetailsCreateParams>(), any() ) ) .thenReturn(paymentDetails) val result = linkRepository.createCardPaymentDetails( paymentMethodCreateParams = cardPaymentMethodCreateParams, userEmail = email, stripeIntent = paymentIntent, consumerSessionClientSecret = consumerSessionSecret, consumerPublishableKey = null ) assertThat(result.isSuccess).isTrue() val newLinkPaymentDetails = result.getOrThrow() assertThat(newLinkPaymentDetails.paymentDetails) .isEqualTo(paymentDetails.paymentDetails.first()) assertThat(newLinkPaymentDetails.paymentMethodCreateParams) .isEqualTo( PaymentMethodCreateParams.createLink( paymentDetails.paymentDetails.first().id, consumerSessionSecret, mapOf("card" to mapOf("cvc" to "123")) ) ) assertThat(newLinkPaymentDetails.buildFormValues()).isEqualTo( mapOf( IdentifierSpec.get("type") to "card", IdentifierSpec.CardNumber to "5555555555554444", IdentifierSpec.CardCvc to "123", IdentifierSpec.CardExpMonth to "12", IdentifierSpec.CardExpYear to "2050", IdentifierSpec.Country to "US", IdentifierSpec.PostalCode to "12345" ) ) } @Test fun `createPaymentDetails for card catches exception and returns failure`() = runTest { whenever( stripeRepository.createPaymentDetails( any(), any<ConsumerPaymentDetailsCreateParams>(), any() ) ) .thenThrow(RuntimeException("error")) val result = linkRepository.createCardPaymentDetails( paymentMethodCreateParams = cardPaymentMethodCreateParams, userEmail = "[email protected]", stripeIntent = paymentIntent, consumerSessionClientSecret = "secret", consumerPublishableKey = null ) assertThat(result.isFailure).isTrue() } @Test fun `updatePaymentDetails sends correct parameters`() = runTest { val secret = "secret" val params = ConsumerPaymentDetailsUpdateParams("id") val consumerKey = "key" linkRepository.updatePaymentDetails( params, secret, consumerKey ) verify(stripeRepository).updatePaymentDetails( eq(secret), eq(params), eq(ApiRequest.Options(consumerKey)) ) } @Test fun `updatePaymentDetails without consumerPublishableKey sends correct parameters`() = runTest { val secret = "secret" val params = ConsumerPaymentDetailsUpdateParams("id") linkRepository.updatePaymentDetails( params, secret, null ) verify(stripeRepository).updatePaymentDetails( eq(secret), eq(params), eq(ApiRequest.Options(PUBLISHABLE_KEY, STRIPE_ACCOUNT_ID)) ) } @Test fun `updatePaymentDetails returns successful result`() = runTest { val consumerPaymentDetails = mock<ConsumerPaymentDetails>() whenever(stripeRepository.updatePaymentDetails(any(), any(), any())) .thenReturn(consumerPaymentDetails) val result = linkRepository.updatePaymentDetails( ConsumerPaymentDetailsUpdateParams("id"), "secret", "key" ) assertThat(result.isSuccess).isTrue() assertThat(result.getOrNull()).isEqualTo(consumerPaymentDetails) } @Test fun `updatePaymentDetails catches exception and returns failure`() = runTest { whenever(stripeRepository.updatePaymentDetails(any(), any(), any())) .thenThrow(RuntimeException("error")) val result = linkRepository.updatePaymentDetails( ConsumerPaymentDetailsUpdateParams("id"), "secret", "key" ) assertThat(result.isFailure).isTrue() } private val cardPaymentMethodCreateParams = FieldValuesToParamsMapConverter.transformToPaymentMethodCreateParams( mapOf( IdentifierSpec.CardNumber to FormFieldEntry("5555555555554444", true), IdentifierSpec.CardCvc to FormFieldEntry("123", true), IdentifierSpec.CardExpMonth to FormFieldEntry("12", true), IdentifierSpec.CardExpYear to FormFieldEntry("2050", true), IdentifierSpec.Country to FormFieldEntry("US", true), IdentifierSpec.PostalCode to FormFieldEntry("12345", true) ), "card", false ) companion object { const val PUBLISHABLE_KEY = "publishableKey" const val STRIPE_ACCOUNT_ID = "stripeAccountId" } }
mit
slartus/4pdaClient-plus
qms/qms-api/src/main/java/ru/softeg/slartus/qms/api/models/QmsThread.kt
1
267
package ru.softeg.slartus.qms.api.models interface QmsThread { val id: String? val title: String? val messagesCount: Int? val newMessagesCount: Int? val lastMessageDate: String? } class QmsThreads(list: List<QmsThread>) : List<QmsThread> by list
apache-2.0
AndroidX/androidx
glance/glance-appwidget/src/test/kotlin/androidx/glance/appwidget/SizeBoxTest.kt
3
11266
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.appwidget import android.os.Bundle import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.glance.LocalSize import androidx.glance.text.EmittableText import androidx.glance.text.Text import com.google.common.truth.Truth.assertThat import kotlin.test.assertIs import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) class SizeBoxTest { private val minSize = DpSize(50.dp, 100.dp) @Test fun sizeModeSingle() = runTest { val root = runTestingComposition { ForEachSize(SizeMode.Single, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } val sizeBox = assertIs<EmittableSizeBox>(root.children.single()) assertThat(sizeBox.size).isEqualTo(minSize) assertThat(sizeBox.sizeMode).isEqualTo(SizeMode.Single) val text = assertIs<EmittableText>(sizeBox.children.single()) assertThat(text.text).isEqualTo("50.0.dp x 100.0.dp") } @Config(sdk = [30]) @Test fun sizeModeExactPreS() = runTest { val options = optionsBundleOf( listOf( DpSize(100.dp, 50.dp), DpSize(50.dp, 100.dp), DpSize(75.dp, 75.dp), ) ) val root = runTestingComposition { CompositionLocalProvider(LocalAppWidgetOptions provides options) { ForEachSize(SizeMode.Exact, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } } // On Pre-S, since AppWidgetManager.OPTION_APPWIDGET_SIZES isn't available, we use // AppWidgetManager.OPTION_APPWIDGET_{MIN,MAX}_{HEIGHT,WIDTH} to find the landscape and // portrait sizes. assertThat(root.children).hasSize(2) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(DpSize(100.dp, 50.dp)) assertThat(sizeBox1.sizeMode).isEqualTo(SizeMode.Exact) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("100.0.dp x 50.0.dp") val sizeBox2 = assertIs<EmittableSizeBox>(root.children[1]) assertThat(sizeBox2.size).isEqualTo(DpSize(50.dp, 100.dp)) assertThat(sizeBox2.sizeMode).isEqualTo(SizeMode.Exact) val text2 = assertIs<EmittableText>(sizeBox2.children.single()) assertThat(text2.text).isEqualTo("50.0.dp x 100.0.dp") } @Config(sdk = [31]) @Test fun sizeModeExactS() = runTest { val options = optionsBundleOf( listOf( DpSize(100.dp, 50.dp), DpSize(50.dp, 100.dp), DpSize(75.dp, 75.dp), ) ) val root = runTestingComposition { CompositionLocalProvider(LocalAppWidgetOptions provides options) { ForEachSize(SizeMode.Exact, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } } // On S+, AppWidgetManager.OPTION_APPWIDGET_SIZES is available so we create a SizeBox for // each size. assertThat(root.children).hasSize(3) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(DpSize(100.dp, 50.dp)) assertThat(sizeBox1.sizeMode).isEqualTo(SizeMode.Exact) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("100.0.dp x 50.0.dp") val sizeBox2 = assertIs<EmittableSizeBox>(root.children[1]) assertThat(sizeBox2.size).isEqualTo(DpSize(50.dp, 100.dp)) assertThat(sizeBox2.sizeMode).isEqualTo(SizeMode.Exact) val text2 = assertIs<EmittableText>(sizeBox2.children.single()) assertThat(text2.text).isEqualTo("50.0.dp x 100.0.dp") val sizeBox3 = assertIs<EmittableSizeBox>(root.children[2]) assertThat(sizeBox3.size).isEqualTo(DpSize(75.dp, 75.dp)) assertThat(sizeBox3.sizeMode).isEqualTo(SizeMode.Exact) val text3 = assertIs<EmittableText>(sizeBox3.children.single()) assertThat(text3.text).isEqualTo("75.0.dp x 75.0.dp") } @Test fun sizeModeExactEmptySizes() = runTest { val options = Bundle() val root = runTestingComposition { CompositionLocalProvider(LocalAppWidgetOptions provides options) { ForEachSize(SizeMode.Exact, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } } // When no sizes are available, a single SizeBox for minSize should be created assertThat(root.children).hasSize(1) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(minSize) assertThat(sizeBox1.sizeMode).isEqualTo(SizeMode.Exact) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("50.0.dp x 100.0.dp") } @Config(sdk = [30]) @Test fun sizeModeResponsivePreS() = runTest { val options = optionsBundleOf( listOf( DpSize(100.dp, 50.dp), DpSize(50.dp, 100.dp), DpSize(75.dp, 75.dp), ) ) val sizeMode = SizeMode.Responsive( setOf( DpSize(99.dp, 49.dp), DpSize(49.dp, 99.dp), DpSize(75.dp, 75.dp), ) ) val root = runTestingComposition { CompositionLocalProvider(LocalAppWidgetOptions provides options) { ForEachSize(sizeMode, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } } // On Pre-S, we extract orientation sizes from // AppWidgetManager.OPTION_APPWIDGET_{MIN,MAX}_{HEIGHT,WIDTH} to find the landscape and // portrait sizes, then find which responsive size fits best for each. assertThat(root.children).hasSize(2) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(DpSize(99.dp, 49.dp)) assertThat(sizeBox1.sizeMode).isEqualTo(sizeMode) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("99.0.dp x 49.0.dp") val sizeBox2 = assertIs<EmittableSizeBox>(root.children[1]) assertThat(sizeBox2.size).isEqualTo(DpSize(49.dp, 99.dp)) assertThat(sizeBox2.sizeMode).isEqualTo(sizeMode) val text2 = assertIs<EmittableText>(sizeBox2.children.single()) assertThat(text2.text).isEqualTo("49.0.dp x 99.0.dp") } @Config(sdk = [30]) @Test fun sizeModeResponsiveUseSmallestSize() = runTest { val options = optionsBundleOf( listOf( DpSize(100.dp, 50.dp), DpSize(50.dp, 100.dp), ) ) val sizeMode = SizeMode.Responsive( setOf( DpSize(200.dp, 200.dp), DpSize(300.dp, 300.dp), DpSize(75.dp, 75.dp), ) ) val root = runTestingComposition { CompositionLocalProvider(LocalAppWidgetOptions provides options) { ForEachSize(sizeMode, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } } // On Pre-S, we extract orientation sizes from // AppWidgetManager.OPTION_APPWIDGET_{MIN,MAX}_{HEIGHT,WIDTH} to find the landscape and // portrait sizes, then find which responsive size fits best for each. If none fits, then we // use the smallest size for both landscape and portrait. assertThat(root.children).hasSize(2) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(DpSize(75.dp, 75.dp)) assertThat(sizeBox1.sizeMode).isEqualTo(sizeMode) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("75.0.dp x 75.0.dp") val sizeBox2 = assertIs<EmittableSizeBox>(root.children[1]) assertThat(sizeBox2.size).isEqualTo(DpSize(75.dp, 75.dp)) assertThat(sizeBox2.sizeMode).isEqualTo(sizeMode) val text2 = assertIs<EmittableText>(sizeBox2.children.single()) assertThat(text2.text).isEqualTo("75.0.dp x 75.0.dp") } @Config(sdk = [31]) @Test fun sizeModeResponsiveS() = runTest { val sizeMode = SizeMode.Responsive( setOf( DpSize(100.dp, 50.dp), DpSize(50.dp, 100.dp), DpSize(75.dp, 75.dp), ) ) val root = runTestingComposition { ForEachSize(sizeMode, minSize) { val size = LocalSize.current Text("${size.width} x ${size.height}") } } // On S, we create a SizeBox for each given size. assertThat(root.children).hasSize(3) val sizeBox1 = assertIs<EmittableSizeBox>(root.children[0]) assertThat(sizeBox1.size).isEqualTo(DpSize(100.dp, 50.dp)) assertThat(sizeBox1.sizeMode).isEqualTo(sizeMode) val text1 = assertIs<EmittableText>(sizeBox1.children.single()) assertThat(text1.text).isEqualTo("100.0.dp x 50.0.dp") val sizeBox2 = assertIs<EmittableSizeBox>(root.children[1]) assertThat(sizeBox2.size).isEqualTo(DpSize(50.dp, 100.dp)) assertThat(sizeBox2.sizeMode).isEqualTo(sizeMode) val text2 = assertIs<EmittableText>(sizeBox2.children.single()) assertThat(text2.text).isEqualTo("50.0.dp x 100.0.dp") val sizeBox3 = assertIs<EmittableSizeBox>(root.children[2]) assertThat(sizeBox3.size).isEqualTo(DpSize(75.dp, 75.dp)) assertThat(sizeBox3.sizeMode).isEqualTo(sizeMode) val text3 = assertIs<EmittableText>(sizeBox3.children.single()) assertThat(text3.text).isEqualTo("75.0.dp x 75.0.dp") } }
apache-2.0
exponent/exponent
packages/expo-dev-launcher/android/src/testDebug/java/expo/modules/devlauncher/modules/DevLauncherModuleTest.kt
2
1265
package expo.modules.devlauncher.modules import android.net.Uri import com.facebook.react.bridge.ReactApplicationContext import com.google.common.truth.Truth import expo.modules.devlauncher.koin.DevLauncherKoinContext import expo.modules.devlauncher.launcher.DevLauncherControllerInterface import io.mockk.every import io.mockk.mockk import org.junit.Test import org.junit.runner.RunWith import org.koin.dsl.module import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class DevLauncherModuleTest { @Test fun `exports manifestURL for currently loaded app`() { // used by snack val urlString = "https://exp.host/@test/test?query=param" val manifestURL = Uri.parse(urlString) val devLauncherController = mockk<DevLauncherControllerInterface>(relaxed = true) DevLauncherKoinContext.app.koin.loadModules(listOf( module { single { devLauncherController } } )) every { devLauncherController.manifestURL } returns manifestURL val reactApplicationContext = mockk<ReactApplicationContext>(relaxed = true) val module = DevLauncherModule(reactApplicationContext) val constants = module.constants Truth.assertThat(constants["manifestURL"]).isEqualTo(urlString) } }
bsd-3-clause
Undin/intellij-rust
src/main/kotlin/org/rust/ide/annotator/RsLiteralAnnotator.kt
2
2755
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.annotator import com.intellij.lang.ASTNode import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.HighlightSeverity import com.intellij.psi.PsiElement import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsElementTypes.* class RsLiteralAnnotator : AnnotatorBase() { override fun annotateInternal(element: PsiElement, holder: AnnotationHolder) { if (element !is RsLitExpr) return val literal = element.kind // Check suffix when (literal) { is RsLiteralKind.Integer, is RsLiteralKind.Float, is RsLiteralKind.String, is RsLiteralKind.Char -> { literal as RsLiteralWithSuffix val suffix = literal.suffix val validSuffixes = literal.validSuffixes if (!suffix.isNullOrEmpty() && suffix !in validSuffixes) { val message = if (validSuffixes.isNotEmpty()) { val validSuffixesStr = validSuffixes.joinToString { "'$it'" } "invalid suffix '$suffix' for ${literal.node.displayName}; " + "the suffix must be one of: $validSuffixesStr" } else { "${literal.node.displayName} with a suffix is invalid" } holder.newAnnotation(HighlightSeverity.ERROR, message).create() } } else -> Unit } // Check char literal length if (literal is RsLiteralKind.Char) { val value = literal.value when { value == null || value.isEmpty() -> "empty ${literal.node.displayName}" value.codePointCount(0, value.length) > 1 -> "too many characters in ${literal.node.displayName}" else -> null }?.let { holder.newAnnotation(HighlightSeverity.ERROR, it).create() } } // Check delimiters if (literal is RsTextLiteral && literal.hasUnpairedQuotes) { holder.newAnnotation(HighlightSeverity.ERROR, "unclosed ${literal.node.displayName}").create() } } } private val ASTNode.displayName: String get() = when (elementType) { INTEGER_LITERAL -> "integer literal" FLOAT_LITERAL -> "float literal" CHAR_LITERAL -> "char literal" BYTE_LITERAL -> "byte literal" STRING_LITERAL -> "string literal" BYTE_STRING_LITERAL -> "byte string literal" RAW_STRING_LITERAL -> "raw string literal" RAW_BYTE_STRING_LITERAL -> "raw byte string literal" else -> toString() }
mit
Undin/intellij-rust
src/test/kotlin/org/rust/ide/inspections/typecheck/ConvertToTyWithDerefsRefsFixTest.kt
3
4529
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.typecheck import org.rust.ide.inspections.RsInspectionsTestBase import org.rust.ide.inspections.RsTypeCheckInspection class ConvertToTyWithDerefsRefsFixTest : RsInspectionsTestBase(RsTypeCheckInspection::class) { fun `test &T to T `() = checkFixByText("Convert to i32 using *", """ fn main () { let a: &i32 = &42; let b: i32 = <error>a<caret></error>; } """, """ fn main () { let a: &i32 = &42; let b: i32 = *a; } """) fun `test &mut T to T `() = checkFixByText("Convert to i32 using *", """ fn main () { let a: &mut i32 = &mut 42; let b: i32 = <error>a<caret></error>; } """, """ fn main () { let a: &mut i32 = &mut 42; let b: i32 = *a; } """) fun `test &&mut T to T`() = checkFixByText("Convert to i32 using **", """ fn main () { let a: &&mut i32 = &&mut 42; let b: i32 = <error>a<caret></error>; } """, """ fn main () { let a: &&mut i32 = &&mut 42; let b: i32 = **a; } """) fun `test T to &T `() = checkFixByText("Convert to &i32 using &", """ fn main () { let a: i32 = 42; let b: &i32 = <error>a<caret></error>; } """, """ fn main () { let a: i32 = 42; let b: &i32 = &a; } """) fun `test mut T to &mut T `() = checkFixByText("Convert to &mut i32 using &mut", """ fn main () { let mut a: i32 = 42; let b: &mut i32 = <error>a<caret></error>; } """, """ fn main () { let mut a: i32 = 42; let b: &mut i32 = &mut a; } """) fun `test T to &mut T `() = checkFixIsUnavailable("Convert to &mut i32", """ fn main () { let a: i32 = 42; let b: &mut i32 = <error>a<caret></error>; } """) fun `test T to &mut &T `() = checkFixByText("Convert to &mut &i32 using &mut &", """ fn main () { let a: i32 = 42; let b: &mut &i32 = <error>a<caret></error>; } """, """ fn main () { let a: i32 = 42; let b: &mut &i32 = &mut &a; } """) fun `test &T to &mut T`() = checkFixIsUnavailable("Convert to &mut i32", """ fn main () { let a: &i32 = &42; let b: &mut i32 = <error>a<caret></error>; } """) fun `test mut &T to &mut T`() = checkFixIsUnavailable("Convert to &mut i32", """ fn main () { let mut a: &i32 = &42; let b: &mut i32 = <error>a<caret></error>; } """) fun `test &mut&&mut T to &mut T`() = checkFixIsUnavailable("Convert to &mut i32", """ fn main () { let a: &i32 = &42; let b: &mut i32 = <error>a<caret></error>; } """) fun `test &mut&&mut T to &mut& T `() = checkFixByText("Convert to &mut &i32 using &mut &***", """ fn main () { let a: &mut &&mut i32 = &mut &&mut 42; let b: &mut &i32 = <error>a<caret></error>; } """, """ fn main () { let a: &mut &&mut i32 = &mut &&mut 42; let b: &mut &i32 = &mut &***a; } """) fun `test B to &mut A when Deref for A with target B exists`() = checkFixIsUnavailable("Convert to &mut B", """ #[lang = "deref"] trait Deref { type Target; } struct A; struct B; impl Deref for A { type Target = B; } fn main () { let a: A = A; let b: &mut B = <error>a<caret></error>; } """) fun `test mut B to &mut A when Deref for A with target B exists`() = checkFixByText("Convert to &mut B using &mut *", """ #[lang = "deref"] trait Deref { type Target; } struct A; struct B; impl Deref for A { type Target = B; } fn main () { let mut a: A = A; let b: &mut B = <error>a<caret></error>; } """, """ #[lang = "deref"] trait Deref { type Target; } struct A; struct B; impl Deref for A { type Target = B; } fn main () { let mut a: A = A; let b: &mut B = &mut *a; } """) }
mit
riaektiv/fdp
fdp-common/src/main/java/com/riaektiv/fdp/common/messages/Message.kt
1
145
package com.riaektiv.fdp.common.messages /** * Created: 3/24/2018, 5:05 PM Eastern Time * * @author Sergey Chuykov */ interface Message { }
apache-2.0
google/dokka
core/src/test/kotlin/model/CommentTest.kt
2
6780
package org.jetbrains.dokka.tests import org.junit.Test import org.junit.Assert.* import org.jetbrains.dokka.* public class CommentTest { @Test fun codeBlockComment() { verifyModel("testdata/comments/codeBlockComment.kt") { model -> with(model.members.single().members.first()) { assertEqualsIgnoringSeparators("""[code lang=brainfuck] | |++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. | |[/code] |""".trimMargin(), content.toTestString()) } with(model.members.single().members.last()) { assertEqualsIgnoringSeparators("""[code] | |a + b - c | |[/code] |""".trimMargin(), content.toTestString()) } } } @Test fun emptyDoc() { verifyModel("testdata/comments/emptyDoc.kt") { model -> with(model.members.single().members.single()) { assertEquals(Content.Empty, content) } } } @Test fun emptyDocButComment() { verifyModel("testdata/comments/emptyDocButComment.kt") { model -> with(model.members.single().members.single()) { assertEquals(Content.Empty, content) } } } @Test fun multilineDoc() { verifyModel("testdata/comments/multilineDoc.kt") { model -> with(model.members.single().members.single()) { assertEquals("doc1", content.summary.toTestString()) assertEquals("doc2\ndoc3", content.description.toTestString()) } } } @Test fun multilineDocWithComment() { verifyModel("testdata/comments/multilineDocWithComment.kt") { model -> with(model.members.single().members.single()) { assertEquals("doc1", content.summary.toTestString()) assertEquals("doc2\ndoc3", content.description.toTestString()) } } } @Test fun oneLineDoc() { verifyModel("testdata/comments/oneLineDoc.kt") { model -> with(model.members.single().members.single()) { assertEquals("doc", content.summary.toTestString()) } } } @Test fun oneLineDocWithComment() { verifyModel("testdata/comments/oneLineDocWithComment.kt") { model -> with(model.members.single().members.single()) { assertEquals("doc", content.summary.toTestString()) } } } @Test fun oneLineDocWithEmptyLine() { verifyModel("testdata/comments/oneLineDocWithEmptyLine.kt") { model -> with(model.members.single().members.single()) { assertEquals("doc", content.summary.toTestString()) } } } @Test fun emptySection() { verifyModel("testdata/comments/emptySection.kt") { model -> with(model.members.single().members.single()) { assertEquals("Summary", content.summary.toTestString()) assertEquals(1, content.sections.count()) with (content.findSectionByTag("one")!!) { assertEquals("One", tag) assertEquals("", toTestString()) } } } } @Test fun quotes() { verifyModel("testdata/comments/quotes.kt") { model -> with(model.members.single().members.single()) { assertEquals("it's \"useful\"", content.summary.toTestString()) } } } @Test fun section1() { verifyModel("testdata/comments/section1.kt") { model -> with(model.members.single().members.single()) { assertEquals("Summary", content.summary.toTestString()) assertEquals(1, content.sections.count()) with (content.findSectionByTag("one")!!) { assertEquals("One", tag) assertEquals("section one", toTestString()) } } } } @Test fun section2() { verifyModel("testdata/comments/section2.kt") { model -> with(model.members.single().members.single()) { assertEquals("Summary", content.summary.toTestString()) assertEquals(2, content.sections.count()) with (content.findSectionByTag("one")!!) { assertEquals("One", tag) assertEquals("section one", toTestString()) } with (content.findSectionByTag("two")!!) { assertEquals("Two", tag) assertEquals("section two", toTestString()) } } } } @Test fun multilineSection() { verifyModel("testdata/comments/multilineSection.kt") { model -> with(model.members.single().members.single()) { assertEquals("Summary", content.summary.toTestString()) assertEquals(1, content.sections.count()) with (content.findSectionByTag("one")!!) { assertEquals("One", tag) assertEquals("""line one line two""", toTestString()) } } } } @Test fun directive() { verifyModel("testdata/comments/directive.kt") { model -> with(model.members.single().members[3]) { assertEquals("Summary", content.summary.toTestString()) with (content.description) { assertEqualsIgnoringSeparators(""" |[code lang=kotlin] |if (true) { | println(property) |} |[/code] |[code lang=kotlin] |if (true) { | println(property) |} |[/code] |[code lang=kotlin] |if (true) { | println(property) |} |[/code] |[code lang=kotlin] |if (true) { | println(property) |} |[/code] |""".trimMargin(), toTestString()) } } } } }
apache-2.0
androidx/androidx
benchmark/benchmark-common/src/androidTest/java/androidx/benchmark/ArgumentInjectingApplication.kt
3
2366
/* * Copyright 2019 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.benchmark import android.app.Application import android.os.Bundle import androidx.test.platform.app.InstrumentationRegistry /** * Hack to enable overriding benchmark arguments (since we can't easily do this in CI, per apk) * * The *correct* way to do this would be to put the following in benchmark/build.gradle: * * ``` * android { * defaultConfig { * testInstrumentationRunnerArguments["androidx.benchmark.suppressErrors"] = * "CODE-COVERAGE,DEBUGGABLE,EMULATOR,LOW-BATTERY,UNLOCKED" * } * } * ``` */ class ArgumentInjectingApplication : Application() { override fun onCreate() { super.onCreate() argumentSource = Bundle().apply { // allow cli args to pass through putAll(InstrumentationRegistry.getArguments()) // Since these benchmark correctness tests run as part of the regular // (non-performance-test) suite, they will have debuggable=true, won't be clock-locked, // can run with low-battery or on an emulator, and code coverage enabled. // We also don't have the activity up for these correctness tests, instead // leaving testing that behavior to the junit4 module. putString( "androidx.benchmark.suppressErrors", "ACTIVITY-MISSING,CODE-COVERAGE,DEBUGGABLE,EMULATOR,LOW-BATTERY,UNLOCKED," + "UNSUSTAINED-ACTIVITY-MISSING,ENG-BUILD" ) // TODO: consider moving default directory to files dir. putString( "additionalTestOutputDir", InstrumentationRegistry.getInstrumentation().targetContext.filesDir.absolutePath ) } } }
apache-2.0
klazuka/intellij-elm
src/test/kotlin/org/elm/ide/test/core/ElmPluginHelperTest.kt
1
3563
package org.elm.ide.test.core import com.intellij.psi.PsiElement import com.intellij.testFramework.ParsingTestCase import org.elm.ide.test.core.ElmPluginHelper.getPsiElement import org.elm.ide.test.core.LabelUtils.toPath import org.elm.lang.core.parser.ElmParserDefinition class ElmPluginHelperTest : ParsingTestCase("elmPluginHelper", "elm", ElmParserDefinition()) { override fun getTestDataPath(): String { return "src/test/resources" } override// see file resources/elmPluginHelper/Navigation fun getTestName(lowercaseFirstLetter: Boolean): String { return "Navigation" } fun testTopLevelSuite() { doTest(false) assertSuite(27, "suite1") } fun testTestInSuite() { doTest(false) assertTest(55, "suite1", "test1") } fun testTopLevelTest() { doTest(false) assertTest(137, "test1") } fun testNestedSuitesAndTests() { doTest(false) assertSuite(207, "suite2") assertTest(235, "suite2", "test1") assertSuite(291, "suite2", "nested1") assertTest(324, "suite2", "nested1", "test1") } fun testMissingTopLevelSuite() { doTest(false) assertMissing("suiteMissing") } fun testMissingTopLevelTest() { doTest(false) assertMissing("testMissing") } fun testMissingNestedSuitesAndTests() { doTest(false) assertSuite(207, "suite2") assertMissing("suite2", "testMissing") assertFallback("suite2", "suite2", "nestedMissing") assertFallback("nested1", "suite2", "nested1", "testMissing") } fun testFuzzTest() { doTest(false) assertFuzz(495, "fuzz1") assertFuzz(388, "suite2", "fuzz1") } private fun assertSuite(offset: Int, vararg labels: String) { val path = toPath(*labels) val element = getPsiElement(true, path.toString(), myFile) val expected = String.format("describe \"%s\"", labels[labels.size - 1]) assertEquals(expected, firstLine(text(element))) assertEquals(offset, element.node.startOffset) } private fun assertTest(offset: Int, vararg labels: String) { val path = toPath(*labels) val element = getPsiElement(false, path.toString(), myFile) val expected = String.format("test \"%s\"", labels[labels.size - 1]) assertEquals(expected, text(element)) assertEquals(offset, element.node.startOffset) } private fun assertFuzz(offset: Int, vararg labels: String) { val path = toPath(*labels) val element = getPsiElement(false, path.toString(), myFile) val expected = String.format("fuzz fuzzer \"%s\"", labels[labels.size - 1]) assertEquals(expected, text(element)) assertEquals(offset, element.node.startOffset) } private fun assertMissing(vararg labels: String) { val path = toPath(*labels) val element = getPsiElement(false, path.toString(), myFile) assertSame(myFile, element) } private fun assertFallback(fallback: String, vararg labels: String) { val path = toPath(*labels) val element = getPsiElement(true, path.toString(), myFile) val expected = String.format("describe \"%s\"", fallback) assertEquals(expected, firstLine(text(element))) } private fun text(element: PsiElement): String { return element.text.trim { it <= ' ' } } private fun firstLine(text: String): String { return text.substringBefore("\n"); } }
mit
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/nuklear/templates/nuklear.kt
1
72700
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.nuklear.templates import org.lwjgl.generator.* import org.lwjgl.nuklear.* val nuklear = "Nuklear".nativeClass(packageName = NUKLEAR_PACKAGE, prefix = "NK", prefixMethod = "nk_", library = "lwjgl_nuklear") { nativeDirective("""#ifdef LWJGL_LINUX #pragma GCC diagnostic ignored "-Wunused-function" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #endif""", beforeIncludes = true) nativeDirective( """DISABLE_WARNINGS() #ifdef LWJGL_WINDOWS __pragma(warning(disable : 4711 4738)) #endif #define NK_PRIVATE #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_COMMAND_USERDATA #ifdef LWJGL_WINDOWS #define NK_BUTTON_TRIGGER_ON_RELEASE #endif #define NK_ASSERT(expr) #define NK_IMPLEMENTATION #define NK_MEMSET memset #define NK_MEMCOPY memcpy #define NK_SQRT sqrt #define NK_SIN sinf #define NK_COS cosf #include <math.h> #include <string.h> #include "nuklear.h" typedef float(*nk_value_getter)(void* user, int index); typedef void(*nk_item_getter)(void*, int, const char**); ENABLE_WARNINGS()""") documentation = """ This is a minimal state immediate mode graphical user interface single header toolkit written in ANSI C and licensed under public domain. It was designed as a simple embeddable user interface for application and does not have any dependencies, a default renderbackend or OS window and input handling but instead provides a very modular library approach by using simple input state for input and draw commands describing primitive shapes as output. So instead of providing a layered library that tries to abstract over a number of platform and render backends it only focuses on the actual UI. <h3>VALUES</h3> ${ul( "Immediate mode graphical user interface toolkit", "Single header library", "Written in C89 (ANSI C)", "Small codebase (~15kLOC)", "Focus on portability, efficiency and simplicity", "No dependencies (not even the standard library if not wanted)", "Fully skinnable and customizable", "Low memory footprint with total memory control if needed or wanted", "UTF-8 support", "No global or hidden state", "Customizable library modules (you can compile and use only what you need)", "Optional font baker and vertex buffer output" )} <h3>FEATURES</h3> ${ul( "Absolutely no platform dependent code", "Memory management control ranging from/to", "Ease of use by allocating everything from the standard library", "Control every byte of memory inside the library", "Font handling control ranging from/to", "Use your own font implementation for everything", "Use this libraries internal font baking and handling API", "Drawing output control ranging from/to", "Simple shapes for more high level APIs which already having drawing capabilities", "Hardware accessible anti-aliased vertex buffer output", "Customizable colors and properties ranging from/to", "Simple changes to color by filling a simple color table", "Complete control with ability to use skinning to decorate widgets", "Bendable UI library with widget ranging from/to", "Basic widgets like buttons, checkboxes, slider, ...", "Advanced widget like abstract comboboxes, contextual menus,...", "Compile time configuration to only compile what you need", "Subset which can be used if you do not want to link or use the standard library", "Can be easily modified to only update on user input instead of frame updates" )} """ IntConstant( "Constants.", "UTF_INVALID"..0xFFFD, "UTF_SIZE".."$NK_UTF_SIZE", "INPUT_MAX".."16", "MAX_NUMBER_BUFFER".."64" ) FloatConstant( "Constants.", "UNDEFINED"..-1.0f, "SCROLLBAR_HIDING_TIMEOUT"..4.0f ) EnumConstant( "Boolean values.", "nk_false".enum, "nk_true".enum ).noPrefix() val Headings = EnumConstant( "nk_heading", "UP".enum, "RIGHT".enum, "DOWN".enum, "LEFT".enum ).javaDocLinks val ButtonBehaviors = EnumConstant( "nk_button_behavior", "BUTTON_DEFAULT".enum, "BUTTON_REPEATER".enum ).javaDocLinks EnumConstant( "nk_modify", "FIXED".enum("", "nk_false"), "MODIFIABLE".enum("", "nk_true") ) EnumConstant( "nk_orientation", "VERTICAL".enum, "HORIZONTAL".enum ) val CollapseStates = EnumConstant( "nk_collapse_states", "MINIMIZED".enum("", "nk_false"), "MAXIMIZED".enum("", "nk_true") ).javaDocLinks val ShowStates = EnumConstant( "nk_show_states", "HIDDEN".enum("", "nk_false"), "SHOWN".enum("", "nk_true") ).javaDocLinks val ChartTypes = EnumConstant( "nk_chart_type", "CHART_LINES".enum, "CHART_COLUMN".enum, "CHART_MAX".enum ).javaDocLinks EnumConstant( "nk_chart_event", "CHART_HOVERING".enum(0x01), "CHART_CLICKED".enum(0x02) ) val ColorFormats = EnumConstant( "nk_color_format", "RGB".enum, "RGBA".enum ).javaDocLinks val PopupTypes = EnumConstant( "nk_popup_type", "POPUP_STATIC".enum, "POPUP_DYNAMIC".enum ).javaDocLinks val LayoutFormats = EnumConstant( "nk_layout_format", "DYNAMIC".enum, "STATIC".enum ).javaDocLinks val TreeTypes = EnumConstant( "nk_tree_type", "TREE_NODE".enum, "TREE_TAB".enum ).javaDocLinks val Antialiasing = EnumConstant( "nk_anti_aliasing", "ANTI_ALIASING_OFF".enum, "ANTI_ALIASING_ON".enum ).javaDocLinks val SymbolTypes = EnumConstant( "nk_symbol_type", "SYMBOL_NONE".enum, "SYMBOL_X".enum, "SYMBOL_UNDERSCORE".enum, "SYMBOL_CIRCLE_SOLID".enum, "SYMBOL_CIRCLE_OUTLINE".enum, "SYMBOL_RECT_SOLID".enum, "SYMBOL_RECT_OUTLINE".enum, "SYMBOL_TRIANGLE_UP".enum, "SYMBOL_TRIANGLE_DOWN".enum, "SYMBOL_TRIANGLE_LEFT".enum, "SYMBOL_TRIANGLE_RIGHT".enum, "SYMBOL_PLUS".enum, "SYMBOL_MINUS".enum, "SYMBOL_MAX".enum ).javaDocLinks val Keys = EnumConstant( "nk_keys", "KEY_NONE".enum, "KEY_SHIFT".enum, "KEY_CTRL".enum, "KEY_DEL".enum, "KEY_ENTER".enum, "KEY_TAB".enum, "KEY_BACKSPACE".enum, "KEY_COPY".enum, "KEY_CUT".enum, "KEY_PASTE".enum, "KEY_UP".enum, "KEY_DOWN".enum, "KEY_LEFT".enum, "KEY_RIGHT".enum, "KEY_TEXT_INSERT_MODE".enum, "KEY_TEXT_REPLACE_MODE".enum, "KEY_TEXT_RESET_MODE".enum, "KEY_TEXT_LINE_START".enum, "KEY_TEXT_LINE_END".enum, "KEY_TEXT_START".enum, "KEY_TEXT_END".enum, "KEY_TEXT_UNDO".enum, "KEY_TEXT_REDO".enum, "KEY_TEXT_WORD_LEFT".enum, "KEY_TEXT_WORD_RIGHT".enum, "KEY_SCROLL_START".enum, "KEY_SCROLL_END".enum, "KEY_SCROLL_DOWN".enum, "KEY_SCROLL_UP".enum, "KEY_MAX".enum ).javaDocLinks { !it.name.endsWith("MAX") } val Buttons = EnumConstant( "nk_buttons", "BUTTON_LEFT".enum, "BUTTON_MIDDLE".enum, "BUTTON_RIGHT".enum, "BUTTON_MAX".enum ).javaDocLinks { !it.name.endsWith("MAX") } val StyleColors = EnumConstant( "nk_style_colors", "COLOR_TEXT".enum, "COLOR_WINDOW".enum, "COLOR_HEADER".enum, "COLOR_BORDER".enum, "COLOR_BUTTON".enum, "COLOR_BUTTON_HOVER".enum, "COLOR_BUTTON_ACTIVE".enum, "COLOR_TOGGLE".enum, "COLOR_TOGGLE_HOVER".enum, "COLOR_TOGGLE_CURSOR".enum, "COLOR_SELECT".enum, "COLOR_SELECT_ACTIVE".enum, "COLOR_SLIDER".enum, "COLOR_SLIDER_CURSOR".enum, "COLOR_SLIDER_CURSOR_HOVER".enum, "COLOR_SLIDER_CURSOR_ACTIVE".enum, "COLOR_PROPERTY".enum, "COLOR_EDIT".enum, "COLOR_EDIT_CURSOR".enum, "COLOR_COMBO".enum, "COLOR_CHART".enum, "COLOR_CHART_COLOR".enum, "COLOR_CHART_COLOR_HIGHLIGHT".enum, "COLOR_SCROLLBAR".enum, "COLOR_SCROLLBAR_CURSOR".enum, "COLOR_SCROLLBAR_CURSOR_HOVER".enum, "COLOR_SCROLLBAR_CURSOR_ACTIVE".enum, "COLOR_TAB_HEADER".enum, "COLOR_COUNT".enum ).javaDocLinksSkipCount val StyleCursor = EnumConstant( "nk_style_cursor", "CURSOR_ARROW".enum, "CURSOR_TEXT".enum, "CURSOR_MOVE".enum, "CURSOR_RESIZE_VERTICAL".enum, "CURSOR_RESIZE_HORIZONTAL".enum, "CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT".enum, "CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT".enum, "CURSOR_COUNT".enum ).javaDocLinksSkipCount EnumConstant( "nk_widget_layout_states", "WIDGET_INVALID".enum("The widget cannot be seen and is completely out of view"), "WIDGET_VALID".enum("The widget is completely inside the window and can be updated and drawn"), "WIDGET_ROM".enum("The widget is partially visible and cannot be updated") ) EnumConstant( "nk_widget_states", "WIDGET_STATE_MODIFIED".enum("", 1.NK_FLAG), "WIDGET_STATE_INACTIVE".enum("widget is neither active nor hovered", 2.NK_FLAG), "WIDGET_STATE_ENTERED".enum("widget has been hovered on the current frame", 3.NK_FLAG), "WIDGET_STATE_HOVER".enum("widget is being hovered", 4.NK_FLAG), "WIDGET_STATE_ACTIVED".enum("widget is currently activated", 5.NK_FLAG), "WIDGET_STATE_LEFT".enum("widget is from this frame on not hovered anymore", 6.NK_FLAG), "WIDGET_STATE_HOVERED".enum("widget is being hovered", "NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED"), "WIDGET_STATE_ACTIVE".enum("widget is currently activated", "NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED") ) EnumConstant( "nk_text_align", "TEXT_ALIGN_LEFT".enum(0x01), "TEXT_ALIGN_CENTERED".enum(0x02), "TEXT_ALIGN_RIGHT".enum(0x04), "TEXT_ALIGN_TOP".enum(0x08), "TEXT_ALIGN_MIDDLE".enum(0x10), "TEXT_ALIGN_BOTTOM".enum(0x20) ) val TextAlignments = EnumConstant( "nk_text_alignment", "TEXT_LEFT".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT"), "TEXT_CENTERED".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED"), "TEXT_RIGHT".enum("", "NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT") ).javaDocLinks val EditFlags = EnumConstant( "nk_edit_flags", "EDIT_DEFAULT".enum(0), "EDIT_READ_ONLY".enum("", 0.NK_FLAG), "EDIT_AUTO_SELECT".enum("", 1.NK_FLAG), "EDIT_SIG_ENTER".enum("", 2.NK_FLAG), "EDIT_ALLOW_TAB".enum("", 3.NK_FLAG), "EDIT_NO_CURSOR".enum("", 4.NK_FLAG), "EDIT_SELECTABLE".enum("", 5.NK_FLAG), "EDIT_CLIPBOARD".enum("", 6.NK_FLAG), "EDIT_CTRL_ENTER_NEWLINE".enum("", 7.NK_FLAG), "EDIT_NO_HORIZONTAL_SCROLL".enum("", 8.NK_FLAG), "EDIT_ALWAYS_INSERT_MODE".enum("", 9.NK_FLAG), "EDIT_MULTILINE".enum("", 11.NK_FLAG), "EDIT_GOTO_END_ON_ACTIVATE".enum("", 12.NK_FLAG) ).javaDocLinks EnumConstant( "nk_edit_types", "EDIT_SIMPLE".enum("", "NK_EDIT_ALWAYS_INSERT_MODE"), "EDIT_FIELD".enum("", "NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD"), "EDIT_BOX".enum("", "NK_EDIT_ALWAYS_INSERT_MODE|NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD"), "EDIT_EDITOR".enum("", "NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD") ) EnumConstant( "nk_edit_events", "EDIT_ACTIVE".enum("edit widget is currently being modified", 0.NK_FLAG), "EDIT_INACTIVE".enum("edit widget is not active and is not being modified", 1.NK_FLAG), "EDIT_ACTIVATED".enum("edit widget went from state inactive to state active", 2.NK_FLAG), "EDIT_DEACTIVATED".enum("edit widget went from state active to state inactive", 3.NK_FLAG), "EDIT_COMMITED".enum("edit widget has received an enter and lost focus", 4.NK_FLAG) ) val PanelFlags = EnumConstant( "nk_panel_flags", "WINDOW_BORDER".enum("Draws a border around the window to visually separate the window * from the background", 0.NK_FLAG), "WINDOW_MOVABLE".enum("The movable flag indicates that a window can be moved by user input or * by dragging the window header", 1.NK_FLAG), "WINDOW_SCALABLE".enum("The scalable flag indicates that a window can be scaled by user input * by dragging a scaler icon at the button of the window", 2.NK_FLAG), "WINDOW_CLOSABLE".enum("adds a closable icon into the header", 3.NK_FLAG), "WINDOW_MINIMIZABLE".enum("adds a minimize icon into the header", 4.NK_FLAG), "WINDOW_NO_SCROLLBAR".enum("Removes the scrollbar from the window", 5.NK_FLAG), "WINDOW_TITLE".enum("Forces a header at the top at the window showing the title", 6.NK_FLAG), "WINDOW_SCROLL_AUTO_HIDE".enum("Automatically hides the window scrollbar if no user interaction", 7.NK_FLAG), "WINDOW_BACKGROUND".enum("Keep window always in the background", 8.NK_FLAG) ).javaDocLinks EnumConstant( "nk_allocation_type", "BUFFER_FIXED".enum, "BUFFER_DYNAMIC".enum ) val BufferAllocationTypes = EnumConstant( "nk_buffer_allocation_type", "BUFFER_FRONT".enum, "BUFFER_BACK".enum, "BUFFER_MAX".enum ).javaDocLinks EnumConstant( "nk_text_edit_type", "TEXT_EDIT_SINGLE_LINE".enum, "TEXT_EDIT_MULTI_LINE".enum ) EnumConstant( "nk_text_edit_mode", "TEXT_EDIT_MODE_VIEW".enum, "TEXT_EDIT_MODE_INSERT".enum, "TEXT_EDIT_MODE_REPLACE".enum ) EnumConstant( "nk_font_coord_type", "COORD_UV".enum("texture coordinates inside font glyphs are clamped between 0-1"), "COORD_PIXEL".enum("texture coordinates inside font glyphs are in absolute pixel") ) EnumConstant( "nk_font_atlas_format", "FONT_ATLAS_ALPHA8".enum, "FONT_ATLAS_RGBA32".enum ) EnumConstant( "nk_command_type", "COMMAND_NOP".enum, "COMMAND_SCISSOR".enum, "COMMAND_LINE".enum, "COMMAND_CURVE".enum, "COMMAND_RECT".enum, "COMMAND_RECT_FILLED".enum, "COMMAND_RECT_MULTI_COLOR".enum, "COMMAND_CIRCLE".enum, "COMMAND_CIRCLE_FILLED".enum, "COMMAND_ARC".enum, "COMMAND_ARC_FILLED".enum, "COMMAND_TRIANGLE".enum, "COMMAND_TRIANGLE_FILLED".enum, "COMMAND_POLYGON".enum, "COMMAND_POLYGON_FILLED".enum, "COMMAND_POLYLINE".enum, "COMMAND_TEXT".enum, "COMMAND_IMAGE".enum ) EnumConstant( "nk_command_clipping", "CLIPPING_OFF".enum("", "nk_false"), "CLIPPING_ON".enum("", "nk_true") ) val DrawListStrokes = EnumConstant( "nk_draw_list_stroke", "STROKE_OPEN".enum("build up path has no connection back to the beginning", "nk_false"), "STROKE_CLOSED".enum("build up path has a connection back to the beginning", "nk_true") ).javaDocLinks EnumConstant( "nk_draw_vertex_layout_attribute", "VERTEX_POSITION".enum, "VERTEX_COLOR".enum, "VERTEX_TEXCOORD".enum, "VERTEX_ATTRIBUTE_COUNT".enum ) EnumConstant( "nk_draw_vertex_layout_format", "FORMAT_SCHAR".enum, "FORMAT_SSHORT".enum, "FORMAT_SINT".enum, "FORMAT_UCHAR".enum, "FORMAT_USHORT".enum, "FORMAT_UINT".enum, "FORMAT_FLOAT".enum, "FORMAT_DOUBLE".enum, "FORMAT_R8G8B8".enum, "FORMAT_R16G15B16".enum, "FORMAT_R32G32B32".enum, "FORMAT_R8G8B8A8".enum, "FORMAT_R16G15B16A16".enum, "FORMAT_R32G32B32A32".enum, "FORMAT_R32G32B32A32_FLOAT".enum, "FORMAT_R32G32B32A32_DOUBLE".enum, "FORMAT_RGB32".enum, "FORMAT_RGBA32".enum, "FORMAT_COUNT".enum ) EnumConstant( "nk_style_item_type", "STYLE_ITEM_COLOR".enum, "STYLE_ITEM_IMAGE".enum ) EnumConstant( "nk_style_header_align", "HEADER_LEFT".enum, "HEADER_RIGHT".enum ) val PanelTypes = EnumConstant( "nk_panel_type", "PANEL_WINDOW".enum("", 0.NK_FLAG), "PANEL_GROUP".enum("", 1.NK_FLAG), "PANEL_POPUP".enum("", 2.NK_FLAG), "PANEL_CONTEXTUAL".enum("", 4.NK_FLAG), "PANEL_COMBO".enum("", 5.NK_FLAG), "PANEL_MENU".enum("", 6.NK_FLAG), "PANEL_TOOLTIP".enum("", 7.NK_FLAG) ) val PanelSet = EnumConstant( "nk_panel_set", "PANEL_SET_NONBLOCK".enum("", "NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP"), "PANEL_SET_POPUP".enum("", "NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP"), "PANEL_SET_SUB".enum("", "NK_PANEL_SET_POPUP|NK_PANEL_GROUP") ) val WindowFlags = EnumConstant( "nk_window_flags", "WINDOW_PRIVATE".enum("", 10.NK_FLAG), "WINDOW_DYNAMIC".enum("special window type growing up in height while being filled to a certain maximum height", "NK_WINDOW_PRIVATE"), "WINDOW_ROM".enum("sets the window into a read only mode and does not allow input changes", 11.NK_FLAG), "WINDOW_HIDDEN".enum("Hides the window and stops any window interaction and drawing can be set by user input or by closing the window", 12.NK_FLAG), "WINDOW_CLOSED".enum("Directly closes and frees the window at the end of the frame", 13.NK_FLAG), "WINDOW_MINIMIZED".enum("marks the window as minimized", 14.NK_FLAG), "WINDOW_REMOVE_ROM".enum("Removes the read only mode at the end of the window", 15.NK_FLAG) ).javaDocLinks val ctx = nk_context_p.IN("ctx", "the nuklear context"); val cctx = const..nk_context_p.IN("ctx", "the nuklear context"); { intb( "init_fixed", "", ctx, void_p.IN("memory", ""), AutoSize("memory")..nk_size.IN("size", ""), nullable..const..nk_user_font_p.IN("font", "") ) intb( "init_custom", "", ctx, nk_buffer_p.IN("cmds", ""), nk_buffer_p.IN("pool", ""), nullable..const..nk_user_font_p.IN("font", "") ) intb( "init", "", ctx, nk_allocator_p.IN("allocator", ""), nullable..const..nk_user_font_p.IN("font", "") ) void("clear", "", ctx) void("free", "", ctx) void( "set_user_data", "", ctx, nullable..nk_handle.IN("handle", "") ) intb( "begin", "", ctx, nk_panel_p.OUT("panel", ""), const..charUTF8_p.IN("title", ""), nk_rect.IN("bounds", ""), nk_flags.IN("flags", "", WindowFlags, LinkMode.BITFIELD) ) intb( "begin_titled", "", ctx, nk_panel_p.OUT("panel", ""), const..charUTF8_p.IN("name", ""), const..charUTF8_p.IN("title", ""), nk_rect.IN("bounds", ""), nk_flags.IN("flags", "", WindowFlags, LinkMode.BITFIELD) ) void("end", "", ctx) nk_window_p( "window_find", "", ctx, const..charUTF8_p.IN("name", "") ) nk_rect("window_get_bounds", "", cctx) nk_vec2("window_get_position", "", cctx) nk_vec2("window_get_size", "", cctx) float("window_get_width", "", cctx) float("window_get_height", "", cctx) nk_panel_p("window_get_panel", "", ctx) nk_rect("window_get_content_region", "", ctx) nk_vec2("window_get_content_region_min", "", ctx) nk_vec2("window_get_content_region_max", "", ctx) nk_vec2("window_get_content_region_size", "", ctx) nk_command_buffer_p("window_get_canvas", "", ctx) intb("window_has_focus", "", cctx) intb( "window_is_collapsed", "", ctx, const..charUTF8_p.IN("name", "") ) intb( "window_is_closed", "", ctx, const..charUTF8_p.IN("name", "") ) intb( "window_is_hidden", "", ctx, const..charUTF8_p.IN("name", "") ) intb( "window_is_active", "", ctx, const..charUTF8_p.IN("name", "") ) intb("window_is_hovered", "", ctx) intb("window_is_any_hovered", "", ctx) intb("item_is_any_active", "", ctx) void( "window_set_bounds", "", ctx, nk_rect.IN("bounds", "") ) void( "window_set_position", "", ctx, nk_vec2.IN("position", "") ) void( "window_set_size", "", ctx, nk_vec2.IN("size", "") ) void( "window_set_focus", "", ctx, const..charUTF8_p.IN("name", "") ) void( "window_close", "", ctx, const..charUTF8_p.IN("name", "") ) void( "window_collapse", "", ctx, const..charUTF8_p.IN("name", ""), nk_collapse_states.IN("c", "", CollapseStates) ) void( "window_show", "", ctx, const..charUTF8_p.IN("name", ""), nk_show_states.IN("s", "", ShowStates) ) void( "layout_row_dynamic", "", ctx, float.IN("height", ""), nk_int.IN("cols", "") ) void( "layout_row_static", "", ctx, float.IN("height", ""), nk_int.IN("item_width", ""), nk_int.IN("cols", "") ) void( "layout_row_begin", "", ctx, nk_layout_format.IN("fmt", "", LayoutFormats), float.IN("row_height", ""), nk_int.IN("cols", "") ) void( "layout_row_push", "", ctx, float.IN("value", "") ) void("layout_row_end", "", ctx) void( "layout_row", "", ctx, nk_layout_format.IN("fmt", "", LayoutFormats), float.IN("height", ""), nk_int.IN("cols", ""), const..float_p.IN("ratio", "") ) void( "layout_space_begin", "", ctx, nk_layout_format.IN("fmt", "", LayoutFormats), float.IN("height", ""), nk_int.IN("widget_count", "") ) void( "layout_space_push", "", ctx, nk_rect.IN("rect", "") ) void("layout_space_end", "", ctx) nk_rect("layout_space_bounds", "", ctx) nk_vec2( "layout_space_to_screen", "", ctx, ReturnParam..nk_vec2.IN("ret", "") ) nk_vec2( "layout_space_to_local", "", ctx, ReturnParam..nk_vec2.IN("ret", "") ) nk_rect( "layout_space_rect_to_screen", "", ctx, ReturnParam..nk_rect.IN("ret", "") ) nk_rect( "layout_space_rect_to_local", "", ctx, ReturnParam..nk_rect.IN("ret", "") ) float( "layout_ratio_from_pixel", "", ctx, float.IN("pixel_width", "") ) intb( "group_begin", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("title", ""), nk_flags.IN("flags", "") ) void("group_end", "", ctx) intb( "tree_push_hashed", "", ctx, nk_tree_type.IN("type", "", TreeTypes), const..charUTF8_p.IN("title", ""), nk_collapse_states.IN("initial_state", "", CollapseStates), const..char_p.IN("hash", ""), AutoSize("hash")..nk_int.IN("len", ""), nk_int.IN("seed", "") ) intb( "tree_image_push_hashed", "", ctx, nk_tree_type.IN("type", "", TreeTypes), nk_image.IN("img", ""), const..charUTF8_p.IN("title", ""), nk_collapse_states.IN("initial_state", "", CollapseStates), const..charUTF8_p.IN("hash", ""), AutoSize("hash")..nk_int.IN("len", ""), nk_int.IN("seed", "") ) void("tree_pop", "", ctx) void( "text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..nk_int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) void( "text_colored", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..nk_int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments), nk_color.IN("color", "") ) void( "text_wrap", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..nk_int.IN("len", "") ) void( "text_wrap_colored", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..nk_int.IN("len", ""), nk_color.IN("color", "") ) void( "label", "", ctx, const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments) ) void( "label_colored", "", ctx, const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments), nk_color.IN("color", "") ) void( "label_wrap", "", ctx, const..charUTF8_p.IN("str", "") ) void( "label_colored_wrap", "", ctx, const..charUTF8_p.IN("str", ""), nk_color.IN("color", "") ) void( "image", "", ctx, nk_image.IN("img", "") ) intb( "button_text", "", ctx, const..charUTF8_p.IN("title", ""), AutoSize("title")..nk_int.IN("len", "") ) intb( "button_label", "", ctx, const..charUTF8_p.IN("title", "") ) intb( "button_color", "", ctx, nk_color.IN("color", "") ) intb( "button_symbol", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes) ) intb( "button_image", "", ctx, nk_image.IN("img", "") ) intb( "button_symbol_label", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), nk_flags.IN("text_alignment", "", TextAlignments) ) intb( "button_symbol_text", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), AutoSize("text")..nk_int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "button_image_label", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("text_alignment", "", TextAlignments) ) intb( "button_image_text", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..nk_int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) void( "button_set_behavior", "", ctx, nk_button_behavior.IN("behavior", "", ButtonBehaviors) ) int( "button_push_behavior", "", ctx, nk_button_behavior.IN("behavior", "", ButtonBehaviors) ) int( "button_pop_behavior", "", ctx ) intb( "check_label", "", ctx, const..charUTF8_p.IN("str", ""), intb.IN("active", "") ) intb( "check_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), intb.IN("active", "") ) unsigned_int( "check_flags_label", "", ctx, const..charUTF8_p.IN("str", ""), unsigned_int.IN("flags", ""), unsigned_int.IN("value", "") ) unsigned_int( "check_flags_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), unsigned_int.IN("flags", ""), unsigned_int.IN("value", "") ) intb( "checkbox_label", "", ctx, const..charUTF8_p.IN("str", ""), Check(1)..int_p.INOUT("active", "") ) intb( "checkbox_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), Check(1)..int_p.INOUT("active", "") ) intb( "checkbox_flags_label", "", ctx, const..charUTF8_p.IN("str", ""), Check(1)..unsigned_int_p.INOUT("flags", ""), unsigned_int.IN("value", "") ) intb( "checkbox_flags_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), Check(1)..unsigned_int_p.INOUT("flags", ""), unsigned_int.IN("value", "") ) intb( "radio_label", "", ctx, const..charUTF8_p.IN("str", ""), Check(1)..int_p.INOUT("active", "") ) intb( "radio_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), Check(1)..int_p.INOUT("active", "") ) intb( "option_label", "", ctx, const..charUTF8_p.IN("str", ""), intb.IN("active", "") ) intb( "option_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), intb.IN("active", "") ) intb( "selectable_label", "", ctx, const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments), Check(1)..int_p.INOUT("value", "") ) intb( "selectable_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), Check(1)..int_p.INOUT("value", "") ) intb( "selectable_image_label", "", ctx, nullable..nk_image.IN("img", ""), const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments), Check(1)..int_p.INOUT("value", "") ) intb( "selectable_image_text", "", ctx, nullable..nk_image.IN("img", ""), const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), Check(1)..int_p.INOUT("value", "") ) intb( "select_label", "", ctx, const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments), intb.IN("value", "") ) intb( "select_text", "", ctx, const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), intb.IN("value", "") ) intb( "select_image_label", "", ctx, nullable..nk_image.IN("img", ""), const..charUTF8_p.IN("str", ""), nk_flags.IN("align", "", TextAlignments), intb.IN("value", "") ) intb( "select_image_text", "", ctx, nullable..nk_image.IN("img", ""), const..charUTF8_p.IN("str", ""), AutoSize("str")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), intb.IN("value", "") ) float( "slide_float", "", ctx, float.IN("min", ""), float.IN("val", ""), float.IN("max", ""), float.IN("step", "") ) int( "slide_int", "", ctx, int.IN("min", ""), int.IN("val", ""), int.IN("max", ""), int.IN("step", "") ) int( "slider_float", "", ctx, float.IN("min", ""), float_p.OUT("val", ""), float.IN("max", ""), float.IN("step", "") ) int( "slider_int", "", ctx, int.IN("min", ""), int_p.OUT("val", ""), int.IN("max", ""), int.IN("step", "") ) intb( "progress", "", ctx, nk_size.p.INOUT("cur", ""), nk_size.IN("max", ""), intb.IN("modifyable", "") ) nk_size( "prog", "", ctx, nk_size.IN("cur", ""), nk_size.IN("max", ""), intb.IN("modifyable", "") ) nk_color( "color_picker", "", ctx, ReturnParam..nk_color.IN("color", ""), nk_color_format.IN("fmt", "", ColorFormats) ) intb( "color_pick", "", ctx, nk_color.p.INOUT("color", ""), nk_color_format.IN("fmt", "", ColorFormats) ) void( "property_int", "", ctx, const..charUTF8_p.IN("name", ""), int.IN("min", ""), Check(1)..int_p.INOUT("val", ""), int.IN("max", ""), int.IN("step", ""), float.IN("inc_per_pixel", "") ) void( "property_float", "", ctx, const..charUTF8_p.IN("name", ""), float.IN("min", ""), Check(1)..float_p.INOUT("val", ""), float.IN("max", ""), float.IN("step", ""), float.IN("inc_per_pixel", "") ) void( "property_double", "", ctx, const..charUTF8_p.IN("name", ""), double.IN("min", ""), Check(1)..double_p.INOUT("val", ""), double.IN("max", ""), double.IN("step", ""), float.IN("inc_per_pixel", "") ) int( "propertyi", "", ctx, const..charUTF8_p.IN("name", ""), int.IN("min", ""), int.IN("val", ""), int.IN("max", ""), int.IN("step", ""), float.IN("inc_per_pixel", "") ) float( "propertyf", "", ctx, const..charUTF8_p.IN("name", ""), float.IN("min", ""), float.IN("val", ""), float.IN("max", ""), float.IN("step", ""), float.IN("inc_per_pixel", "") ) double( "propertyd", "", ctx, const..charUTF8_p.IN("name", ""), double.IN("min", ""), double.IN("val", ""), double.IN("max", ""), double.IN("step", ""), float.IN("inc_per_pixel", "") ) nk_flags( "edit_string", "", ctx, nk_flags.IN("flags", "", EditFlags), charUTF8_p.IN("memory", ""), Check(1)..int_p.OUT("len", ""), int.IN("max", ""), nullable..nk_plugin_filter.IN("filter", "") ) nk_flags( "edit_buffer", "", ctx, nk_flags.IN("flags", "", EditFlags), nk_text_edit_p.IN("edit", ""), nullable..nk_plugin_filter.IN("filter", "") ) nk_flags( "edit_string_zero_terminated", "", ctx, nk_flags.IN("flags", "", EditFlags), charUTF8_p.IN("buffer", ""), int.IN("max", ""), nullable..nk_plugin_filter.IN("filter", "") ) }(); { intb( "chart_begin", "", ctx, nk_chart_type.IN("type", "", ChartTypes), int.IN("num", ""), float.IN("min", ""), float.IN("max", "") ) intb( "chart_begin_colored", "", ctx, nk_chart_type.IN("type", "", ChartTypes), nk_color.IN("color", ""), nk_color.IN("active", ""), int.IN("num", ""), float.IN("min", ""), float.IN("max", "") ) void( "chart_add_slot", "", ctx, nk_chart_type.IN("type", "", ChartTypes), int.IN("count", ""), float.IN("min_value", ""), float.IN("max_value", "") ) void( "chart_add_slot_colored", "", ctx, nk_chart_type.IN("type", "", ChartTypes), nk_color.IN("color", ""), nk_color.IN("active", ""), int.IN("count", ""), float.IN("min_value", ""), float.IN("max_value", "") ) nk_flags( "chart_push", "", ctx, float.IN("value", "") ) nk_flags( "chart_push_slot", "", ctx, float.IN("value", ""), int.IN("slot", "") ) void("chart_end", "", ctx) void( "plot", "", ctx, nk_chart_type.IN("type", "", ChartTypes), Check("offset + count")..const..float_p.IN("values", ""), int.IN("count", ""), int.IN("offset", "") ) void( "plot_function", "", ctx, nk_chart_type.IN("type", "", ChartTypes), voidptr.IN("userdata", ""), nk_value_getter.IN("value_getter", ""), int.IN("count", ""), int.IN("offset", "") ) intb( "popup_begin", "", ctx, nk_panel_p.IN("layout", ""), nk_popup_type.IN("type", "", PopupTypes), const..charUTF8_p.IN("title", ""), nk_flags.IN("flags", "", PanelFlags), nk_rect.IN("rect", "") ) void("popup_close", "", ctx) void("popup_end", "", ctx) intb( "combo", "", ctx, const..charUTF8_pp.IN("items", ""), AutoSize("items")..int.IN("count", ""), intb.IN("selected", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) intb( "combo_separator", "", ctx, const..charUTF8_p.IN("items_separated_by_separator", ""), int.IN("separator", ""), intb.IN("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) intb( "combo_string", "", ctx, const..charUTF8_p.IN("items_separated_by_zeros", ""), intb.IN("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) intb( "combo_callback", "", ctx, nk_item_getter.IN("item_getter", ""), voidptr.IN("userdata", ""), intb.IN("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) void( "combobox", "", ctx, const..charUTF8_pp.IN("items", ""), AutoSize("items")..int.IN("count", ""), Check(1)..int_p.INOUT("selected", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) void( "combobox_string", "", ctx, const..charUTF8_p.IN("items_separated_by_zeros", ""), Check(1)..int_p.INOUT("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) void( "combobox_separator", "", ctx, const..charUTF8_p.IN("items_separated_by_separator", ""), int.IN("separator", ""), Check(1)..int_p.INOUT("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) void( "combobox_callback", "", ctx, nk_item_getter.IN("item_getter", ""), voidptr.IN("userdata", ""), Check(1)..int_p.INOUT("selected", ""), int.IN("count", ""), int.IN("item_height", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), AutoSize("selected")..int.IN("len", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_color", "", ctx, nk_panel_p.IN("layout", ""), nk_color.IN("color", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_symbol", "", ctx, nk_panel_p.IN("layout", ""), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "combo_begin_symbol_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "combo_begin_symbol_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), AutoSize("selected")..int.IN("len", ""), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "combo_begin_image", "", ctx, nk_panel_p.IN("layout", ""), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_image_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "combo_begin_image_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("selected", ""), AutoSize("selected")..int.IN("len", ""), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "combo_item_label", "", ctx, const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "combo_item_text", "", ctx, const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "combo_item_image_label", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "combo_item_image_text", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "combo_item_symbol_label", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "combo_item_symbol_text", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) void("combo_close", "", ctx) void("combo_end", "", ctx) intb( "contextual_begin", "", ctx, nk_panel_p.IN("layout", ""), nk_flags.IN("flags", "", WindowFlags), nk_vec2.IN("size", ""), nk_rect.IN("trigger_bounds", "") ) intb( "contextual_item_text", "", ctx, const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments) ) intb( "contextual_item_label", "", ctx, const..charUTF8_p.IN("text", ""), nk_flags.IN("align", "", TextAlignments) ) intb( "contextual_item_image_label", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "contextual_item_image_text", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "contextual_item_symbol_label", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "contextual_item_symbol_text", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) void("contextual_close", "", ctx) void("contextual_end", "", ctx) void( "tooltip", "", ctx, const..charUTF8_p.IN("text", "") ) intb( "tooltip_begin", "", ctx, nk_panel_p.IN("layout", ""), float.IN("width", "") ) void("tooltip_end", "", ctx) void("menubar_begin", "", ctx) void("menubar_end", "", ctx) intb( "menu_begin_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), nk_vec2.IN("size", "") ) intb( "menu_begin_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("align", "", TextAlignments), nk_vec2.IN("size", "") ) intb( "menu_begin_image", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "menu_begin_image_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "menu_begin_image_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("align", "", TextAlignments), nk_image.IN("img", ""), nk_vec2.IN("size", "") ) intb( "menu_begin_symbol", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "menu_begin_symbol_text", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "menu_begin_symbol_label", "", ctx, nk_panel_p.IN("layout", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("align", "", TextAlignments), nk_symbol_type.IN("symbol", "", SymbolTypes), nk_vec2.IN("size", "") ) intb( "menu_item_text", "", ctx, const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("align", "", TextAlignments) ) intb( "menu_item_label", "", ctx, const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "menu_item_image_label", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "menu_item_image_text", "", ctx, nk_image.IN("img", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "menu_item_symbol_text", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), nk_flags.IN("alignment", "", TextAlignments) ) intb( "menu_item_symbol_label", "", ctx, nk_symbol_type.IN("symbol", "", SymbolTypes), const..charUTF8_p.IN("text", ""), nk_flags.IN("alignment", "", TextAlignments) ) void("menu_close", "", ctx) void("menu_end", "", ctx) }(); { void( "convert", "", ctx, nk_buffer_p.IN("cmds", ""), nk_buffer_p.IN("vertices", ""), nk_buffer_p.IN("elements", ""), const..nk_convert_config.p.IN("config", "") ) void("input_begin", "", ctx) void( "input_motion", "", ctx, int.IN("x", ""), int.IN("y", "") ) void( "input_key", "", ctx, nk_keys.IN("key", "", Keys), intb.IN("down", "") ) void( "input_button", "", ctx, nk_buttons.IN("id", "", Buttons), int.IN("x", ""), int.IN("y", ""), intb.IN("down", "") ) void( "input_scroll", "", ctx, float.IN("y", "") ) void( "input_glyph", "", ctx, Check(NK_UTF_SIZE)..nk_glyph.IN("glyph", "") ) void( "input_unicode", "", ctx, nk_rune.IN("unicode", "") ) void("input_end", "", ctx) void("style_default", "", ctx) void( "style_from_table", "", ctx, Check("NK_COLOR_COUNT")..const..nk_color.p.IN("table", "") ) void( "style_load_cursor", "", ctx, nk_style_cursor.IN("style", "", StyleCursor), nk_cursor_p.IN("cursor", "") ) void( "style_load_all_cursors", "", ctx, Check("NK_CURSOR_COUNT")..nk_cursor_p.IN("cursors", "") ) (const..charUTF8_p)( "style_get_color_by_name", "", nk_style_colors.IN("c", "", StyleColors) ) void( "style_set_font", "", ctx, const..nk_user_font_p.IN("font", "") ) int( "style_set_cursor", "", ctx, nk_style_cursor.IN("style", "", StyleCursor) ) void("style_show_cursor", "", ctx) void("style_hide_cursor", "", ctx) int( "style_push_font", "", ctx, nk_user_font_p.IN("font", "") ) int( "style_push_float", "", ctx, float_p.IN("address", ""), float.IN("value", "") ) int( "style_push_vec2", "", ctx, nk_vec2.p.IN("address", ""), nk_vec2.IN("value", "") ) int( "style_push_style_item", "", ctx, nk_style_item.p.IN("address", ""), nk_style_item.IN("value", "") ) int( "style_push_flags", "", ctx, nk_flags.p.IN("address", ""), nk_flags.IN("value", "") ) int( "style_push_color", "", ctx, nk_color.p.IN("address", ""), nk_color.IN("value", "") ) int("style_pop_font", "", ctx) int("style_pop_float", "", ctx) int("style_pop_vec2", "", ctx) int("style_pop_style_item", "", ctx) int("style_pop_flags", "", ctx) int("style_pop_color", "", ctx) nk_rect("widget_bounds", "", ctx) nk_vec2("widget_position", "", ctx) nk_vec2("widget_size", "", ctx) float("widget_width", "", ctx) float("widget_height", "", ctx) intb("widget_is_hovered", "", ctx) intb( "widget_is_mouse_clicked", "", ctx, nk_buttons.IN("btn", "") ) intb( "widget_has_mouse_click_down", "", ctx, nk_buttons.IN("btn", "", Buttons), intb.IN("down", "") ) void( "spacing", "", ctx, int.IN("cols", "") ) nk_widget_layout_states( "widget", "", nk_rect.p.IN("bounds", ""), cctx ) nk_widget_layout_states( "widget_fitting", "", nk_rect.p.IN("bounds", ""), ctx, nk_vec2.IN("item_padding", "") ) nk_color( "rgb", "", int.IN("r", ""), int.IN("g", ""), int.IN("b", "") ) nk_color( "rgb_iv", "", Check(3)..const..int_p.IN("rgb", "") ) nk_color( "rgb_bv", "", Check(3)..const..nk_byte_p.IN("rgb", "") ) nk_color( "rgb_f", "", float.IN("r", ""), float.IN("g", ""), float.IN("b", "") ) nk_color( "rgb_fv", "", Check(3)..const..float_p.IN("rgb", "") ) nk_color( "rgb_hex", "", Check(6)..const..charASCII_p.IN("rgb", "") ) nk_color( "rgba", "", int.IN("r", ""), int.IN("g", ""), int.IN("b", ""), int.IN("a", "") ) nk_color( "rgba_u32", "", nk_uint.IN("in", "") ) nk_color( "rgba_iv", "", Check(4)..const..int_p.IN("rgba", "") ) nk_color( "rgba_bv", "", Check(4)..const..nk_byte_p.IN("rgba", "") ) nk_color( "rgba_f", "", float.IN("r", ""), float.IN("g", ""), float.IN("b", ""), float.IN("a", "") ) nk_color( "rgba_fv", "", Check(4)..const..float_p.IN("rgba", "") ) nk_color( "rgba_hex", "", Check(8)..const..charASCII_p.IN("rgba", "") ) nk_color( "hsv", "", int.IN("h", ""), int.IN("s", ""), int.IN("v", "") ) nk_color( "hsv_iv", "", Check(3)..const..int_p.IN("hsv", "") ) nk_color( "hsv_bv", "", Check(3)..const..nk_byte_p.IN("hsv", "") ) nk_color( "hsv_f", "", float.IN("h", ""), float.IN("s", ""), float.IN("v", "") ) nk_color( "hsv_fv", "", Check(3)..const..float_p.IN("hsv", "") ) nk_color( "hsva", "", int.IN("h", ""), int.IN("s", ""), int.IN("v", ""), int.IN("a", "") ) nk_color( "hsva_iv", "", Check(4)..const..int_p.IN("hsva", "") ) nk_color( "hsva_bv", "", Check(4)..const..nk_byte_p.IN("hsva", "") ) nk_color( "hsva_f", "", float.IN("h", ""), float.IN("s", ""), float.IN("v", ""), float.IN("a", "") ) nk_color( "hsva_fv", "", Check(4)..const..float_p.IN("hsva", "") ) void( "color_f", "", Check(1)..float_p.OUT("r", ""), Check(1)..float_p.OUT("g", ""), Check(1)..float_p.OUT("b", ""), Check(1)..float_p.OUT("a", ""), nk_color.IN("color", "") ) void( "color_fv", "", Check(4)..float_p.OUT("rgba_out", ""), nk_color.IN("color", "") ) void( "color_d", "", Check(1)..double_p.OUT("r", ""), Check(1)..double_p.OUT("g", ""), Check(1)..double_p.OUT("b", ""), Check(1)..double_p.OUT("a", ""), nk_color.IN("color", "") ) void( "color_dv", "", Check(4)..double_p.OUT("rgba_out", ""), nk_color.IN("color", "") ) nk_uint( "color_u32", "", nk_color.IN("color", "") ) void( "color_hex_rgba", "", Check(8)..char_p.OUT("output", ""), nk_color.IN("color", "") ) void( "color_hex_rgb", "", Check(6)..char_p.OUT("output", ""), nk_color.IN("color", "") ) void( "color_hsv_i", "", Check(1)..int_p.OUT("out_h", ""), Check(1)..int_p.OUT("out_s", ""), Check(1)..int_p.OUT("out_v", ""), nk_color.IN("color", "") ) void( "color_hsv_b", "", Check(1)..nk_byte_p.OUT("out_h", ""), Check(1)..nk_byte_p.OUT("out_s", ""), Check(1)..nk_byte_p.OUT("out_v", ""), nk_color.IN("color", "") ) void( "color_hsv_iv", "", Check(3)..int_p.OUT("hsv_out", ""), nk_color.IN("color", "") ) void( "color_hsv_bv", "", Check(3)..nk_byte_p.OUT("hsv_out", ""), nk_color.IN("color", "") ) void( "color_hsv_f", "", Check(1)..float_p.OUT("out_h", ""), Check(1)..float_p.OUT("out_s", ""), Check(1)..float_p.OUT("out_v", ""), nk_color.IN("color", "") ) void( "color_hsv_fv", "", Check(3)..float_p.OUT("hsv_out", ""), nk_color.IN("color", "") ) void( "color_hsva_i", "", Check(1)..int_p.OUT("h", ""), Check(1)..int_p.OUT("s", ""), Check(1)..int_p.OUT("v", ""), Check(1)..int_p.OUT("a", ""), nk_color.IN("color", "") ) void( "color_hsva_b", "", Check(1)..nk_byte_p.OUT("h", ""), Check(1)..nk_byte_p.OUT("s", ""), Check(1)..nk_byte_p.OUT("v", ""), Check(1)..nk_byte_p.OUT("a", ""), nk_color.IN("color", "") ) void( "color_hsva_iv", "", Check(4)..int_p.OUT("hsva_out", ""), nk_color.IN("color", "") ) void( "color_hsva_bv", "", Check(4)..nk_byte_p.OUT("hsva_out", ""), nk_color.IN("color", "") ) void( "color_hsva_f", "", Check(1)..float_p.OUT("out_h", ""), Check(1)..float_p.OUT("out_s", ""), Check(1)..float_p.OUT("out_v", ""), Check(1)..float_p.OUT("out_a", ""), nk_color.IN("color", "") ) void( "color_hsva_fv", "", Check(4)..float_p.OUT("hsva_out", ""), nk_color.IN("color", "") ) nk_handle( "handle_ptr", "", voidptr.IN("ptr", "") ) nk_handle( "handle_id", "", int.IN("id", "") ) nk_image( "image_handle", "", nk_handle.IN("handle", "") ) nk_image( "image_ptr", "", voidptr.IN("ptr", "") ) nk_image( "image_id", "", int.IN("id", "") ) intb( "image_is_subimage", "", const..nk_image.p.IN("img", "") ) nk_image( "subimage_ptr", "", voidptr.IN("ptr", ""), unsigned_short.IN("w", ""), unsigned_short.IN("h", ""), nk_rect.IN("sub_region", "") ) nk_image( "subimage_id", "", int.IN("id", ""), unsigned_short.IN("w", ""), unsigned_short.IN("h", ""), nk_rect.IN("sub_region", "") ) nk_image( "subimage_handle", "", nk_handle.IN("handle", ""), unsigned_short.IN("w", ""), unsigned_short.IN("h", ""), nk_rect.IN("sub_region", "") ) nk_hash( "murmur_hash", "", const..void_p.IN("key", ""), AutoSize("key")..int.IN("len", ""), nk_hash.IN("seed", "") ) void( "triangle_from_direction", "", nk_vec2.p.OUT("result", ""), nk_rect.IN("r", ""), float.IN("pad_x", ""), float.IN("pad_y", ""), nk_heading.IN("direction", "", Headings) ) nk_vec2( "vec2", "", float.IN("x", ""), float.IN("y", "") ) nk_vec2( "vec2i", "", int.IN("x", ""), int.IN("y", "") ) nk_vec2( "vec2v", "", Check(2)..const..float_p.IN("xy", "") ) nk_vec2( "vec2iv", "", Check(2)..const..int_p.IN("xy", "") ) nk_rect( "get_null_rect", "" ) nk_rect( "rect", "", float.IN("x", ""), float.IN("y", ""), float.IN("w", ""), float.IN("h", "") ) nk_rect( "recti", "", int.IN("x", ""), int.IN("y", ""), int.IN("w", ""), int.IN("h", "") ) nk_rect( "recta", "", nk_vec2.IN("pos", ""), nk_vec2.IN("size", "") ) nk_rect( "rectv", "", Check(4)..const..float_p.IN("xywh", "") ) nk_rect( "rectiv", "", Check(4)..const..int_p.IN("xywh", "") ) nk_vec2( "rect_pos", "", nk_rect.IN("r", "") ) nk_vec2( "rect_size", "", nk_rect.IN("r", "") ) }(); { int( "strlen", "", const..charUTF8_p.IN("str", "") ) int( "stricmp", "", const..charUTF8_p.IN("s1", ""), const..charUTF8_p.IN("s2", "") ) int( "stricmpn", "", const..charUTF8_p.IN("s1", ""), const..charUTF8_p.IN("s2", ""), int.IN("n", "") ) int( "strtoi", "", const..charUTF8_p.IN("str", ""), charUTF8_pp.OUT("endptr", "") ) float( "strtof", "", const..charUTF8_p.IN("str", ""), charUTF8_pp.OUT("endptr", "") ) double( "strtod", "", const..charUTF8_p.IN("str", ""), charUTF8_pp.OUT("endptr", "") ) intb( "strfilter", """ ${ul( "c - matches any literal character c", ". - matches any single character", "^ - matches the beginning of the input string", "$ - matches the end of the input string", "* - matches zero or more occurrences of the previous character" )} """, const..charUTF8_p.IN("str", ""), const..charUTF8_p.IN("regexp", "") ) intb( "strmatch_fuzzy_string", """ Returns true if each character in {@code pattern} is found sequentially within {@code str} if found then {@code out_score} is also set. Score value has no intrinsic meaning. Range varies with {@code pattern}. Can only compare scores with same search pattern. """, const..charUTF8_p.IN("str", ""), const..charUTF8_p.IN("pattern", ""), Check(1)..int_p.OUT("out_score", "") ) int( "strmatch_fuzzy_text", "", const..charUTF8_p.IN("txt", ""), AutoSize("txt")..int.IN("txt_len", ""), const..charUTF8_p.IN("pattern", ""), Check(1)..int_p.OUT("out_score", "") ) int( "utf_decode", "", const..char_p.IN("c", ""), Check(1)..nk_rune_p.OUT("u", ""), AutoSize("c")..int.IN("clen", "") ) int( "utf_encode", "", nk_rune.IN("u", ""), char_p.IN("c", ""), AutoSize("c")..int.IN("clen", "") ) int( "utf_len", "", const..char_p.IN("str", ""), AutoSize("str")..int.IN("byte_len", "") ) (const..char_p)( "utf_at", "", const..char_p.IN("buffer", ""), AutoSize("buffer")..int.IN("length", ""), int.IN("index", ""), Check(1)..nk_rune_p.OUT("unicode", ""), AutoSizeResult..int_p.OUT("len", "") ) void( "buffer_init", "", nk_buffer_p.IN("buffer", ""), const..nk_allocator_p.IN("allocator", ""), nk_size.IN("size", "") ) void( "buffer_init_fixed", "", nk_buffer_p.IN("buffer", ""), void_p.IN("memory", ""), AutoSize("memory")..nk_size.IN("size", "") ) void( "buffer_info", "", nk_memory_status.p.OUT("status", ""), nk_buffer_p.IN("buffer", "") ) void( "buffer_push", "", nk_buffer_p.IN("buffer", ""), nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes), const..void_p.IN("memory", ""), AutoSize("memory")..nk_size.IN("size", ""), nk_size.IN("align", "") ) void( "buffer_mark", "", nk_buffer_p.IN("buffer", ""), nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes) ) void( "buffer_reset", "", nk_buffer_p.IN("buffer", ""), nk_buffer_allocation_type.IN("type", "", BufferAllocationTypes) ) void( "buffer_clear", "", nk_buffer_p.IN("buffer", "") ) void( "buffer_free", "", nk_buffer_p.IN("buffer", "") ) voidptr( "buffer_memory", "", nk_buffer_p.IN("buffer", "") ) (const..voidptr)( "buffer_memory_const", "", const..nk_buffer_p.IN("buffer", "") ) nk_size( "buffer_total", "", nk_buffer_p.IN("buffer", "") ) void( "str_init", "", nk_str_p.IN("str", ""), const..nk_allocator_p.IN("allocator", ""), nk_size.IN("size", "") ) void( "str_init_fixed", "", nk_str_p.IN("str", ""), void_p.IN("memory", ""), AutoSize("memory")..nk_size.IN("size", "") ) void( "str_clear", "", nk_str_p.IN("str", "") ) void( "str_free", "", nk_str_p.IN("str", "") ) int( "str_append_text_char", "", nk_str_p.IN("s", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_append_str_char", "", nk_str_p.IN("s", ""), NullTerminated..const..char_p.IN("str", "") ) int( "str_append_text_utf8", "", nk_str_p.IN("s", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_append_str_utf8", "", nk_str_p.IN("s", ""), NullTerminated..const..char_p.IN("str", "") ) int( "str_append_text_runes", "", nk_str_p.IN("s", ""), const..nk_rune_p.IN("runes", ""), AutoSize("runes")..int.IN("len", "") ) int( "str_append_str_runes", "", nk_str_p.IN("s", ""), NullTerminated..const..nk_rune_p.IN("runes", "") ) int( "str_insert_at_char", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_insert_at_rune", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_insert_text_char", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_insert_str_char", "", nk_str_p.IN("s", ""), int.IN("pos", ""), NullTerminated..const..char_p.IN("str", "") ) int( "str_insert_text_utf8", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..char_p.IN("str", ""), AutoSize("str")..int.IN("len", "") ) int( "str_insert_str_utf8", "", nk_str_p.IN("s", ""), int.IN("pos", ""), NullTerminated..const..char_p.IN("str", "") ) int( "str_insert_text_runes", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..nk_rune_p.IN("runes", ""), AutoSize("runes")..int.IN("len", "") ) int( "str_insert_str_runes", "", nk_str_p.IN("s", ""), int.IN("pos", ""), const..nk_rune_p.IN("runes", "") ) void( "str_remove_chars", "", nk_str_p.IN("s", ""), int.IN("len", "") ) void( "str_remove_runes", "", nk_str_p.IN("str", ""), int.IN("len", "") ) void( "str_delete_chars", "", nk_str_p.IN("s", ""), int.IN("pos", ""), int.IN("len", "") ) void( "str_delete_runes", "", nk_str_p.IN("s", ""), int.IN("pos", ""), int.IN("len", "") ) charUTF8_p( "str_at_char", "", nk_str_p.IN("s", ""), int.IN("pos", "") ) char_p( "str_at_rune", "", nk_str_p.IN("s", ""), int.IN("pos", ""), Check(1)..nk_rune_p.OUT("unicode", ""), AutoSizeResult..int_p.OUT("len", "") ) nk_rune( "str_rune_at", "", const..nk_str_p.IN("s", ""), int.IN("pos", "") ) (const..charUTF8_p)( "str_at_char_const", "", const..nk_str_p.IN("s", ""), int.IN("pos", "") ) (const..char_p)( "str_at_const", "", const..nk_str_p.IN("s", ""), int.IN("pos", ""), Check(1)..nk_rune_p.OUT("unicode", ""), AutoSizeResult..int_p.OUT("len", "") ) charUTF8_p( "str_get", "", nk_str_p.IN("s", "") ) (const..charUTF8_p)( "str_get_const", "", const..nk_str_p.IN("s", "") ) int( "str_len", "", nk_str_p.IN("s", "") ) int( "str_len_char", "", nk_str_p.IN("s", "") ) intb( "filter_default", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_ascii", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_float", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_decimal", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_hex", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_oct", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) intb( "filter_binary", "", const..nk_text_edit_p.IN("edit", ""), nk_rune.IN("unicode", "") ) void( "textedit_init", "", nk_text_edit_p.IN("box", ""), nk_allocator_p.IN("allocator", ""), nk_size.IN("size", "") ) void( "textedit_init_fixed", "", nk_text_edit_p.IN("box", ""), void_p.IN("memory", ""), AutoSize("memory")..nk_size.IN("size", "") ) void( "textedit_free", "", nk_text_edit_p.IN("box", "") ) void( "textedit_text", "", nk_text_edit_p.IN("box", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("total_len", "") ) void( "textedit_delete", "", nk_text_edit_p.IN("box", ""), int.IN("where", ""), int.IN("len", "") ) void( "textedit_delete_selection", "", nk_text_edit_p.IN("box", "") ) void( "textedit_select_all", "", nk_text_edit_p.IN("box", "") ) intb( "textedit_cut", "", nk_text_edit_p.IN("box", "") ) intb( "textedit_paste", "", nk_text_edit_p.IN("box", ""), const..charUTF8_p.IN("ctext", ""), AutoSize("ctext")..int.IN("len", "") ) void( "textedit_undo", "", nk_text_edit_p.IN("box", "") ) void( "textedit_redo", "", nk_text_edit_p.IN("box", "") ) }(); { void( "stroke_line", "", nk_command_buffer_p.IN("b", ""), float.IN("x0", ""), float.IN("y0", ""), float.IN("x1", ""), float.IN("y1", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "stroke_curve", "", nk_command_buffer_p.IN("b", ""), float.IN("ax", ""), float.IN("ay", ""), float.IN("ctrl0x", ""), float.IN("ctrl0y", ""), float.IN("ctrl1x", ""), float.IN("ctrl1y", ""), float.IN("bx", ""), float.IN("by", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "stroke_rect", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), float.IN("rounding", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "stroke_circle", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "stroke_arc", "", nk_command_buffer_p.IN("b", ""), float.IN("cx", ""), float.IN("cy", ""), float.IN("radius", ""), float.IN("a_min", ""), float.IN("a_max", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "stroke_triangle", "", nk_command_buffer_p.IN("b", ""), float.IN("x0", ""), float.IN("y0", ""), float.IN("x1", ""), float.IN("y1", ""), float.IN("x2", ""), float.IN("y2", ""), float.IN("line_thichness", ""), nk_color.IN("color", "") ) void( "stroke_polyline", "", nk_command_buffer_p.IN("b", ""), float_p.IN("points", ""), AutoSize("points")..int.IN("point_count", ""), float.IN("line_thickness", ""), nk_color.IN("col", "") ) void( "stroke_polygon", "", nk_command_buffer_p.IN("b", ""), float_p.IN("points", ""), AutoSize("points")..int.IN("point_count", ""), float.IN("line_thickness", ""), nk_color.IN("color", "") ) void( "fill_rect", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), float.IN("rounding", ""), nk_color.IN("color", "") ) void( "fill_rect_multi_color", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), nk_color.IN("left", ""), nk_color.IN("top", ""), nk_color.IN("right", ""), nk_color.IN("bottom", "") ) void( "fill_circle", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), nk_color.IN("color", "") ) void( "fill_arc", "", nk_command_buffer_p.IN("b", ""), float.IN("cx", ""), float.IN("cy", ""), float.IN("radius", ""), float.IN("a_min", ""), float.IN("a_max", ""), nk_color.IN("color", "") ) void( "fill_triangle", "", nk_command_buffer_p.IN("b", ""), float.IN("x0", ""), float.IN("y0", ""), float.IN("x1", ""), float.IN("y1", ""), float.IN("x2", ""), float.IN("y2", ""), nk_color.IN("color", "") ) void( "fill_polygon", "", nk_command_buffer_p.IN("b", ""), float_p.IN("points", ""), AutoSize("points")..int.IN("point_count", ""), nk_color.IN("color", "") ) void( "push_scissor", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", "") ) void( "draw_image", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), const..nk_image.p.IN("img", ""), nk_color.IN("color", "") ) void( "draw_text", "", nk_command_buffer_p.IN("b", ""), nk_rect.IN("rect", ""), const..charUTF8_p.IN("string", ""), AutoSize("string")..int.IN("length", ""), const..nk_user_font_p.IN("font", ""), nk_color.IN("bg", ""), nk_color.IN("fg", "") ) (const..nk_command.p)( "_next", "", ctx, const..nk_command.p.IN("cmd", "") ) (const..nk_command.p)( "_begin", "", ctx ) intb( "input_has_mouse_click", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons) ) intb( "input_has_mouse_click_in_rect", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons), nk_rect.IN("rect", "") ) intb( "input_has_mouse_click_down_in_rect", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons), nk_rect.IN("rect", ""), int.IN("down", "") ) intb( "input_is_mouse_click_in_rect", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons), nk_rect.IN("rect", "") ) intb( "input_is_mouse_click_down_in_rect", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons), nk_rect.IN("b", ""), int.IN("down", "") ) intb( "input_any_mouse_click_in_rect", "", const..nk_input_p.IN("i", ""), nk_rect.IN("rect", "") ) intb( "input_is_mouse_prev_hovering_rect", "", const..nk_input_p.IN("i", ""), nk_rect.IN("rect", "") ) intb( "input_is_mouse_hovering_rect", "", const..nk_input_p.IN("i", ""), nk_rect.IN("rect", "") ) intb( "input_mouse_clicked", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons), nk_rect.IN("rect", "") ) intb( "input_is_mouse_down", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons) ) intb( "input_is_mouse_pressed", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons) ) intb( "input_is_mouse_released", "", const..nk_input_p.IN("i", ""), nk_buttons.IN("id", "", Buttons) ) intb( "input_is_key_pressed", "", const..nk_input_p.IN("i", ""), nk_keys.IN("key", "", Keys) ) intb( "input_is_key_released", "", const..nk_input_p.IN("i", ""), nk_keys.IN("key", "", Keys) ) intb( "input_is_key_down", "", const..nk_input_p.IN("i", ""), nk_keys.IN("key", "", Keys) ) }(); { void( "draw_list_init", "", nk_draw_list_p.IN("list", "") ) void( "draw_list_setup", "", nk_draw_list_p.IN("canvas", ""), const..nk_convert_config.p.IN("config", ""), nk_buffer_p.IN("cmds", ""), nk_buffer_p.IN("vertices", ""), nk_buffer_p.IN("elements", "") ) void( "draw_list_clear", "", nk_draw_list_p.IN("list", "") ) (const..nk_draw_command_p)( "_draw_list_begin", "", const..nk_draw_list_p.IN("list", ""), const..nk_buffer_p.IN("buffer", "") ) (const..nk_draw_command_p)( "_draw_list_next", "", const..nk_draw_command_p.IN("cmd", ""), const..nk_buffer_p.IN("buffer", ""), const..nk_draw_list_p.IN("list", "") ) (const..nk_draw_command_p)( "_draw_begin", "", cctx, const..nk_buffer_p.IN("buffer", "") ) (const..nk_draw_command_p)( "_draw_end", "", cctx, const..nk_buffer_p.IN("buffer", "") ) (const..nk_draw_command_p)( "_draw_next", "", const..nk_draw_command_p.IN("cmd", ""), const..nk_buffer_p.IN("buffer", ""), cctx ) void( "draw_list_path_clear", "", nk_draw_list_p.IN("list", "") ) void( "draw_list_path_line_to", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("pos", "") ) void( "draw_list_path_arc_to_fast", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("center", ""), float.IN("radius", ""), int.IN("a_min", ""), int.IN("a_max", "") ) void( "draw_list_path_arc_to", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("center", ""), float.IN("radius", ""), float.IN("a_min", ""), float.IN("a_max", ""), unsigned_int.IN("segments", "") ) void( "draw_list_path_rect_to", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("a", ""), nk_vec2.IN("b", ""), float.IN("rounding", "") ) void( "draw_list_path_curve_to", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("p2", ""), nk_vec2.IN("p3", ""), nk_vec2.IN("p4", ""), unsigned_int.IN("num_segments", "") ) void( "draw_list_path_fill", "", nk_draw_list_p.IN("list", ""), nk_color.IN("color", "") ) void( "draw_list_path_stroke", "", nk_draw_list_p.IN("list", ""), nk_color.IN("color", ""), nk_draw_list_stroke.IN("closed", "", DrawListStrokes), float.IN("thickness", "") ) void( "draw_list_stroke_line", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("a", ""), nk_vec2.IN("b", ""), nk_color.IN("color", ""), float.IN("thickness", "") ) void( "draw_list_stroke_rect", "", nk_draw_list_p.IN("list", ""), nk_rect.IN("rect", ""), nk_color.IN("color", ""), float.IN("rounding", ""), float.IN("thickness", "") ) void( "draw_list_stroke_triangle", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("a", ""), nk_vec2.IN("b", ""), nk_vec2.IN("c", ""), nk_color.IN("color", ""), float.IN("thickness", "") ) void( "draw_list_stroke_circle", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("center", ""), float.IN("radius", ""), nk_color.IN("color", ""), unsigned_int.IN("segs", ""), float.IN("thickness", "") ) void( "draw_list_stroke_curve", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("p0", ""), nk_vec2.IN("cp0", ""), nk_vec2.IN("cp1", ""), nk_vec2.IN("p1", ""), nk_color.IN("color", ""), unsigned_int.IN("segments", ""), float.IN("thickness", "") ) void( "draw_list_stroke_poly_line", "", nk_draw_list_p.IN("list", ""), const..nk_vec2.p.IN("pnts", ""), unsigned_int.IN("cnt", ""), nk_color.IN("color", ""), nk_draw_list_stroke.IN("closed", "", DrawListStrokes), float.IN("thickness", ""), nk_anti_aliasing.IN("aliasing", "", Antialiasing) ) void( "draw_list_fill_rect", "", nk_draw_list_p.IN("list", ""), nk_rect.IN("rect", ""), nk_color.IN("color", ""), float.IN("rounding", "") ) void( "draw_list_fill_rect_multi_color", "", nk_draw_list_p.IN("list", ""), nk_rect.IN("rect", ""), nk_color.IN("left", ""), nk_color.IN("top", ""), nk_color.IN("right", ""), nk_color.IN("bottom", "") ) void( "draw_list_fill_triangle", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("a", ""), nk_vec2.IN("b", ""), nk_vec2.IN("c", ""), nk_color.IN("color", "") ) void( "draw_list_fill_circle", "", nk_draw_list_p.IN("list", ""), nk_vec2.IN("center", ""), float.IN("radius", ""), nk_color.IN("col", ""), unsigned_int.IN("segs", "") ) void( "draw_list_fill_poly_convex", "", nk_draw_list_p.IN("list", ""), const..nk_vec2.p.IN("points", ""), AutoSize("points")..unsigned_int.IN("count", ""), nk_color.IN("color", ""), nk_anti_aliasing.IN("aliasing", "", Antialiasing) ) void( "draw_list_add_image", "", nk_draw_list_p.IN("list", ""), nk_image.IN("texture", ""), nk_rect.IN("rect", ""), nk_color.IN("color", "") ) void( "draw_list_add_text", "", nk_draw_list_p.IN("list", ""), const..nk_user_font_p.IN("font", ""), nk_rect.IN("rect", ""), const..charUTF8_p.IN("text", ""), AutoSize("text")..int.IN("len", ""), float.IN("font_height", ""), nk_color.IN("color", "") ) void( "draw_list_push_userdata", "", nk_draw_list_p.IN("list", ""), nk_handle.IN("userdata", "") ) nk_style_item( "style_item_image", "", nk_image.IN("img", "") ) nk_style_item( "style_item_color", "", nk_color.IN("color", "") ) nk_style_item( "style_item_hide", "" ) }(); }
bsd-3-clause
klazuka/intellij-elm
src/test/kotlin/org/elm/ide/lineMarkers/ElmExposureLineMarkerProviderTest.kt
1
1519
package org.elm.ide.lineMarkers class ElmExposureLineMarkerProviderTest : ElmLineMarkerProviderTestBase() { fun `test module that exposes all`() = doTestByText( """ module Main exposing (..) n = 0 --> Exposed f x = 0 --> Exposed type Foo = Foo --> Exposed (including variants) type alias Bar = () --> Exposed """) fun `test module that exposes a single function`() = doTestByText( """ module Main exposing (f) f x = 0 --> Exposed g x = 0 """) fun `test module that exposes a single value`() = doTestByText( """ module Main exposing (a) a = 0 --> Exposed b = 0 """) fun `test functions declared in a let-in do NOT get a line marker`() = doTestByText( """ module Main exposing (..) f x = --> Exposed let y = 0 in y """) fun `test module that exposes a union type`() = doTestByText( """ module Main exposing (Foo) type Foo = Foo --> Exposed type Bar = Bar """) fun `test module that exposes a union type and its constructors`() = doTestByText( """ module Main exposing (Foo(..)) type Foo = Foo --> Exposed (including variants) """) fun `test module that exposes a type alias`() = doTestByText( """ module Main exposing (Foo) type alias Foo = () --> Exposed type alias Bar = () """ ) fun `test module that exposes a port`() = doTestByText( """ port module Main exposing (foo) port foo : a -> () --> Exposed port bar : a -> () """) }
mit
rosenpin/QuickDrawEverywhere
app/src/main/java/com/tomer/draw/windows/drawings/QuickDrawView.kt
1
8555
package com.tomer.draw.windows.drawings import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.Color import android.net.Uri import android.os.Environment import android.os.Handler import android.support.v4.view.ViewCompat import android.support.v7.widget.AppCompatImageView import android.view.Gravity import android.view.KeyEvent import android.view.LayoutInflater import android.view.WindowManager import android.widget.FrameLayout import com.byox.drawview.enums.BackgroundScale import com.byox.drawview.enums.BackgroundType import com.byox.drawview.enums.DrawingCapture import com.byox.drawview.enums.DrawingMode import com.byox.drawview.views.DrawView import com.tomer.draw.R import com.tomer.draw.gallery.MainActivity import com.tomer.draw.utils.circularRevealHide import com.tomer.draw.utils.circularRevealShow import com.tomer.draw.utils.hasPermissions import com.tomer.draw.utils.helpers.DisplaySize import com.tomer.draw.windows.FloatingView import com.tomer.draw.windows.OnWindowStateChangedListener import com.tomer.draw.windows.WindowsManager import kotlinx.android.synthetic.main.quick_draw_view.view.* import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* import kotlin.collections.ArrayList /** * DrawEverywhere * Created by Tomer Rosenfeld on 7/27/17. */ class QuickDrawView(context: Context) : FrameLayout(context), FloatingView { override val listeners: ArrayList<OnWindowStateChangedListener> = ArrayList() private val displaySize = DisplaySize(context) override var currentX: Int = 0 override var currentY: Int = 0 private var fullScreen = false var isAttached = false var accessibleDrawView: DrawView? = null var onDrawingFinished: OnDrawingFinished? = null override fun removeFromWindow(x: Int, y: Int, onWindowRemoved: Runnable?, listener: OnWindowStateChangedListener?) { if (isAttached) { isAttached = false this.circularRevealHide(cx = x + if (x == 0) 50 else -50, cy = y + 50, radius = Math.hypot(displaySize.getWidth().toDouble(), displaySize.getHeight().toDouble()).toFloat(), action = Runnable { if (tapBarMenu != null) tapBarMenu.close() WindowsManager.getInstance(context).removeView(this) onWindowRemoved?.run() triggerListeners(false) }) } } override fun addToWindow(x: Int, y: Int, onWindowAdded: Runnable?, listener: OnWindowStateChangedListener?) { if (!isAttached) { isAttached = true this.circularRevealShow(x + if (x == 0) 50 else -50, y + 50, Math.hypot(displaySize.getWidth().toDouble(), displaySize.getHeight().toDouble()).toFloat()) WindowsManager.getInstance(context).addView(this) Handler().postDelayed({ onWindowAdded?.run() triggerListeners(true) }, 100) } } fun triggerListeners(added: Boolean) { for (l in listeners) { if (added) l.onWindowAdded() else if (!added) l.onWindowRemoved() } } override fun origHeight(): Int = (displaySize.getHeight() * (if (!fullScreen) 0.8f else 0.95f)).toInt() override fun origWidth(): Int = WindowManager.LayoutParams.MATCH_PARENT override fun gravity() = Gravity.CENTER init { val drawView = LayoutInflater.from(context).inflate(R.layout.quick_draw_view, this).draw_view drawView.setBackgroundDrawColor(Color.WHITE) drawView.backgroundColor = Color.WHITE drawView.setDrawViewBackgroundColor(Color.WHITE) drawView.drawWidth = 8 drawView.drawColor = Color.GRAY cancel.setOnClickListener { drawView.restartDrawing(); onDrawingFinished?.OnDrawingClosed() } minimize.setOnClickListener { onDrawingFinished?.OnDrawingClosed() } undo.setOnClickListener { if (drawView.canUndo()) drawView.undo(); refreshRedoUndoButtons(drawView) } redo.setOnClickListener { if (drawView.canRedo()) drawView.redo(); refreshRedoUndoButtons(drawView) } maximize.setOnClickListener { fullScreen = !fullScreen removeFromWindow(x = displaySize.getWidth() / 2, onWindowRemoved = Runnable { addToWindow(x = displaySize.getWidth() / 2) }) } save.setOnClickListener { save(drawView) } eraser.setOnClickListener { v -> drawView.drawingMode = if (drawView.drawingMode == DrawingMode.DRAW) DrawingMode.ERASER else DrawingMode.DRAW drawView.drawWidth = if (drawView.drawingMode == DrawingMode.DRAW) 8 else 28 (v as AppCompatImageView).setImageResource( if (drawView.drawingMode == DrawingMode.DRAW) R.drawable.ic_erase else R.drawable.ic_pencil) } gallery.setOnClickListener { removeFromWindow(displaySize.getWidth() / 2, 0, Runnable { context.startActivity(Intent(context, MainActivity::class.java)) }) } tapBarMenu.setOnClickListener({ tapBarMenu.toggle() }) tapBarMenu.moveDownOnClose = false refreshRedoUndoButtons(drawView) drawView.setOnDrawViewListener(object : DrawView.OnDrawViewListener { override fun onStartDrawing() { refreshRedoUndoButtons(drawView) } override fun onEndDrawing() { refreshRedoUndoButtons(drawView) } override fun onClearDrawing() { refreshRedoUndoButtons(drawView) } override fun onRequestText() { } override fun onAllMovesPainted() { } }) ViewCompat.setElevation(toolbar, context.resources?.getDimension(R.dimen.qda_design_appbar_elevation) ?: 6f) ViewCompat.setElevation(tapBarMenu, context.resources?.getDimension(R.dimen.standard_elevation) ?: 8f) accessibleDrawView = drawView } private fun refreshRedoUndoButtons(drawView: DrawView) { redo.alpha = if (drawView.canRedo()) 1f else 0.4f undo.alpha = if (drawView.canUndo()) 1f else 0.4f } internal fun setImage(file: File) { accessibleDrawView?.setBackgroundImage(file, BackgroundType.FILE, BackgroundScale.CENTER_INSIDE) } override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (event.keyCode == KeyEvent.KEYCODE_VOLUME_UP || event .keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { return super.dispatchKeyEvent(event) } removeFromWindow() return super.dispatchKeyEvent(event) } fun undo(v: DrawView) { v.undo() } fun save(v: DrawView) { val createCaptureResponse = v.createCapture(DrawingCapture.BITMAP) if (!context.hasPermissions(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { context.startActivity(Intent(context, AskPermissionActivity::class.java)) return } saveFile(createCaptureResponse[0] as Bitmap) } fun saveFile(bitmap: Bitmap) { paintBitmapToBlack(bitmap) var fileName = Calendar.getInstance().timeInMillis.toString() try { fileName = "drawing-$fileName.jpg" val imageDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), context.getString(R.string.app_name)) imageDir.mkdirs() val image = File(imageDir, fileName) val result = image.createNewFile() val fileOutputStream = FileOutputStream(image) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream) onDrawingFinished?.onDrawingSaved() showNotification(bitmap, image) } catch (e: IOException) { e.printStackTrace() onDrawingFinished?.OnDrawingSaveFailed() } } private fun paintBitmapToBlack(bitmap: Bitmap) { val allpixels = IntArray(bitmap.height * bitmap.width) bitmap.getPixels(allpixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) (0..allpixels.size - 1) .filter { allpixels[it] == Color.TRANSPARENT } .forEach { allpixels[it] = Color.WHITE } bitmap.setPixels(allpixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height) } fun clear(v: DrawView) { v.restartDrawing() } fun showNotification(drawing: Bitmap, file: File) { val notificationManager = context .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val intent = Intent() intent.action = Intent.ACTION_VIEW intent.setDataAndType(Uri.fromFile(file), "image/*") val pendingIntent = PendingIntent.getActivity(context, 100, intent, PendingIntent.FLAG_ONE_SHOT) val notification = Notification.Builder(context) .setContentTitle(context.resources.getString(R.string.drawing_drawing_saved)) .setContentText(context.resources.getString(R.string.drawing_view_drawing)) .setStyle(Notification.BigPictureStyle().bigPicture(drawing)) .setSmallIcon(R.drawable.ic_gallery_compat) .setContentIntent(pendingIntent).build() notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL notificationManager.notify(1689, notification) } }
gpl-3.0
auth0/Lock.Android
app/src/main/java/com/auth0/android/lock/app/DemoActivity.kt
1
11714
/* * DemoActivity.java * * Copyright (c) 2016 Auth0 (http://auth0.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.auth0.android.lock.app import android.os.Bundle import android.view.View import android.widget.Button import android.widget.CheckBox import android.widget.LinearLayout import android.widget.RadioGroup import androidx.appcompat.app.AppCompatActivity import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationException import com.auth0.android.callback.Callback import com.auth0.android.lock.* import com.auth0.android.provider.WebAuthProvider.login import com.auth0.android.provider.WebAuthProvider.logout import com.auth0.android.result.Credentials import com.google.android.material.snackbar.Snackbar class DemoActivity : AppCompatActivity() { // Configured instances private var lock: Lock? = null private var passwordlessLock: PasswordlessLock? = null // Views private lateinit var rootLayout: View private lateinit var groupSubmitMode: RadioGroup private lateinit var checkboxClosable: CheckBox private lateinit var groupPasswordlessChannel: RadioGroup private lateinit var groupPasswordlessMode: RadioGroup private lateinit var checkboxConnectionsDB: CheckBox private lateinit var checkboxConnectionsEnterprise: CheckBox private lateinit var checkboxConnectionsSocial: CheckBox private lateinit var checkboxConnectionsPasswordless: CheckBox private lateinit var checkboxHideMainScreenTitle: CheckBox private lateinit var groupDefaultDB: RadioGroup private lateinit var groupUsernameStyle: RadioGroup private lateinit var checkboxLoginAfterSignUp: CheckBox private lateinit var checkboxScreenLogIn: CheckBox private lateinit var checkboxScreenSignUp: CheckBox private lateinit var checkboxScreenReset: CheckBox private lateinit var groupInitialScreen: RadioGroup override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.demo_activity) rootLayout = findViewById(R.id.scrollView) //Basic groupSubmitMode = findViewById(R.id.group_submitmode) checkboxClosable = findViewById(R.id.checkbox_closable) checkboxHideMainScreenTitle = findViewById(R.id.checkbox_hide_title) checkboxConnectionsDB = findViewById(R.id.checkbox_connections_db) checkboxConnectionsEnterprise = findViewById(R.id.checkbox_connections_enterprise) checkboxConnectionsSocial = findViewById(R.id.checkbox_connections_social) checkboxConnectionsPasswordless = findViewById(R.id.checkbox_connections_Passwordless) groupPasswordlessChannel = findViewById(R.id.group_passwordless_channel) groupPasswordlessMode = findViewById(R.id.group_passwordless_mode) //Advanced groupDefaultDB = findViewById(R.id.group_default_db) groupUsernameStyle = findViewById(R.id.group_username_style) checkboxLoginAfterSignUp = findViewById(R.id.checkbox_login_after_signup) checkboxScreenLogIn = findViewById(R.id.checkbox_enable_login) checkboxScreenSignUp = findViewById(R.id.checkbox_enable_signup) checkboxScreenReset = findViewById(R.id.checkbox_enable_reset) groupInitialScreen = findViewById(R.id.group_initial_screen) //Buttons val advancedContainer = findViewById<LinearLayout>(R.id.advanced_container) val checkboxShowAdvanced = findViewById<CheckBox>(R.id.checkbox_show_advanced) checkboxShowAdvanced.setOnCheckedChangeListener { _, b -> advancedContainer.visibility = if (b) View.VISIBLE else View.GONE } val btnShowLockClassic = findViewById<Button>(R.id.btn_show_lock_classic) btnShowLockClassic.setOnClickListener { showClassicLock() } val btnShowLockPasswordless = findViewById<Button>(R.id.btn_show_lock_passwordless) btnShowLockPasswordless.setOnClickListener { showPasswordlessLock() } val btnShowUniversalLogin = findViewById<Button>(R.id.btn_show_universal_login) btnShowUniversalLogin.setOnClickListener { showWebAuth() } val btnClearSession = findViewById<Button>(R.id.btn_clear_session) btnClearSession.setOnClickListener { clearSession() } } private fun showWebAuth() { login(account) .withScheme("demo") .withAudience(String.format("https://%s/userinfo", getString(R.string.com_auth0_domain))) .start(this, loginCallback) } private fun clearSession() { logout(account) .withScheme("demo") .start(this, logoutCallback) } private fun showClassicLock() { val builder = Lock.newBuilder(account, callback) .withScheme("demo") .closable(checkboxClosable.isChecked) .useLabeledSubmitButton(groupSubmitMode.checkedRadioButtonId == R.id.radio_use_label) .loginAfterSignUp(checkboxLoginAfterSignUp.isChecked) .allowLogIn(checkboxScreenLogIn.isChecked) .allowSignUp(checkboxScreenSignUp.isChecked) .allowForgotPassword(checkboxScreenReset.isChecked) .allowedConnections(generateConnections()) .hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked) when (groupUsernameStyle.checkedRadioButtonId) { R.id.radio_username_style_email -> { builder.withUsernameStyle(UsernameStyle.EMAIL) } R.id.radio_username_style_username -> { builder.withUsernameStyle(UsernameStyle.USERNAME) } } when (groupInitialScreen.checkedRadioButtonId) { R.id.radio_initial_reset -> { builder.initialScreen(InitialScreen.FORGOT_PASSWORD) } R.id.radio_initial_signup -> { builder.initialScreen(InitialScreen.SIGN_UP) } else -> { builder.initialScreen(InitialScreen.LOG_IN) } } if (checkboxConnectionsDB.isChecked) { when (groupDefaultDB.checkedRadioButtonId) { R.id.radio_default_db_policy -> { builder.setDefaultDatabaseConnection("with-strength") } R.id.radio_default_db_mfa -> { builder.setDefaultDatabaseConnection("mfa-connection") } else -> { builder.setDefaultDatabaseConnection("Username-Password-Authentication") } } } // For demo purposes because options change dynamically, we release the resources of Lock here. // In a real app, you will have a single instance and release its resources in Activity#OnDestroy. lock?.onDestroy(this) // Create a new instance with the updated configuration lock = builder.build(this) startActivity(lock!!.newIntent(this)) } private fun showPasswordlessLock() { val builder = PasswordlessLock.newBuilder(account, callback) .withScheme("demo") .closable(checkboxClosable.isChecked) .allowedConnections(generateConnections()) .hideMainScreenTitle(checkboxHideMainScreenTitle.isChecked) if (groupPasswordlessMode.checkedRadioButtonId == R.id.radio_use_link) { builder.useLink() } else { builder.useCode() } // For demo purposes because options change dynamically, we release the resources of Lock here. // In a real app, you will have a single instance and release its resources in Activity#OnDestroy. passwordlessLock?.onDestroy(this) // Create a new instance with the updated configuration passwordlessLock = builder.build(this) startActivity(passwordlessLock!!.newIntent(this)) } private val account: Auth0 by lazy { Auth0(getString(R.string.com_auth0_client_id), getString(R.string.com_auth0_domain)) } private fun generateConnections(): List<String> { val connections: MutableList<String> = ArrayList() if (checkboxConnectionsDB.isChecked) { connections.add("Username-Password-Authentication") connections.add("mfa-connection") connections.add("with-strength") } if (checkboxConnectionsEnterprise.isChecked) { connections.add("ad") connections.add("another") connections.add("fake-saml") connections.add("contoso-ad") } if (checkboxConnectionsSocial.isChecked) { connections.add("google-oauth2") connections.add("twitter") connections.add("facebook") connections.add("paypal-sandbox") } if (checkboxConnectionsPasswordless.isChecked) { connections.add(if (groupPasswordlessChannel.checkedRadioButtonId == R.id.radio_use_sms) "sms" else "email") } if (connections.isEmpty()) { connections.add("no-connection") } return connections } public override fun onDestroy() { super.onDestroy() lock?.onDestroy(this) passwordlessLock?.onDestroy(this) } internal fun showResult(message: String) { Snackbar.make(rootLayout, message, Snackbar.LENGTH_LONG).show() } private val callback: LockCallback = object : AuthenticationCallback() { override fun onAuthentication(credentials: Credentials) { showResult("OK > " + credentials.accessToken) } override fun onError(error: AuthenticationException) { if (error.isCanceled) { showResult("User pressed back.") } else { showResult(error.getDescription()) } } } private val loginCallback: Callback<Credentials, AuthenticationException> = object : Callback<Credentials, AuthenticationException> { override fun onFailure(error: AuthenticationException) { showResult("Failed > " + error.getDescription()) } override fun onSuccess(result: Credentials) { showResult("OK > " + result.accessToken) } } private val logoutCallback: Callback<Void?, AuthenticationException> = object : Callback<Void?, AuthenticationException> { override fun onFailure(error: AuthenticationException) { showResult("Log out cancelled") } override fun onSuccess(result: Void?) { showResult("Logged out!") } } }
mit
CruGlobal/android-gto-support
gto-support-okta/src/main/kotlin/com/okta/authfoundation/claims/DefaultClaimsProviderInternals.kt
1
246
package com.okta.authfoundation.claims import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject internal fun DefaultClaimsProvider(claims: JsonObject, json: Json) = DefaultClaimsProviderInternals.create(claims, json)
mit
CruGlobal/android-gto-support
gto-support-picasso/src/test/kotlin/org/ccci/gto/android/common/picasso/view/SimplePicassoImageViewTest.kt
1
1746
package org.ccci.gto.android.common.picasso.view import android.content.Context import android.util.AttributeSet import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import org.ccci.gto.android.common.picasso.R import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith import org.robolectric.Robolectric @RunWith(AndroidJUnit4::class) class SimplePicassoImageViewTest { private val context get() = ApplicationProvider.getApplicationContext<Context>() @Test fun `testConstructor - attribute - placeholder resource`() { val attrs = Robolectric.buildAttributeSet() .addAttribute(R.attr.placeholder, "@android:drawable/btn_default") .build() val view = TestSimplePicassoImageView(context, attrs) assertEquals(android.R.drawable.btn_default, view.helper.placeholderResId) assertNull(view.helper.placeholder) } @Test fun `testConstructor - scaleType Attribute`() { val attrs = Robolectric.buildAttributeSet().addAttribute(android.R.attr.scaleType, "center").build() SimplePicassoImageView(context, attrs) } @Test fun `testConstructor - scaleType Attribute - Subclass`() { val attrs = Robolectric.buildAttributeSet().addAttribute(android.R.attr.scaleType, "center").build() object : SimplePicassoImageView(context, attrs) { override val helper by lazy { PicassoImageView.Helper(this, attrs) } } } class TestSimplePicassoImageView(context: Context, attrs: AttributeSet?) : SimplePicassoImageView(context, attrs) { public override val helper get() = super.helper } }
mit
CruGlobal/android-gto-support
gto-support-androidx-compose/src/main/kotlin/org/ccci/gto/android/common/androidx/compose/ui/draw/InvisibleIfModifier.kt
1
368
package org.ccci.gto.android.common.androidx.compose.ui.draw import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent fun Modifier.invisibleIf(invisible: Boolean) = if (invisible) drawWithContent { } else this inline fun Modifier.invisibleIf(crossinline invisible: () -> Boolean) = drawWithContent { if (!invisible()) drawContent() }
mit
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/orders/dto/OrdersAmount.kt
1
1757
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.orders.dto import com.google.gson.annotations.SerializedName import kotlin.String import kotlin.collections.List /** * @param amounts * @param currency - Currency name */ data class OrdersAmount( @SerializedName("amounts") val amounts: List<OrdersAmountItem>? = null, @SerializedName("currency") val currency: String? = null )
mit
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/market/dto/MarketSearchExtendedStatus.kt
1
1637
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.market.dto import com.google.gson.annotations.SerializedName import kotlin.Int enum class MarketSearchExtendedStatus( val value: Int ) { @SerializedName("0") ACTIVE(0), @SerializedName("2") DISABLED(2); }
mit
spamdr/astroants
src/main/kotlin/cz/richter/david/astroants/model/InputMapSettings.kt
1
189
package cz.richter.david.astroants.model import com.fasterxml.jackson.annotation.JsonProperty data class InputMapSettings( @JsonProperty("areas") val areas: List<String> )
mit
BoD/CineToday
app/src/main/kotlin/org/jraf/android/cinetoday/glide/GlideHelper.kt
1
3492
/* * This source is part of the * _____ ___ ____ * __ / / _ \/ _ | / __/___ _______ _ * / // / , _/ __ |/ _/_/ _ \/ __/ _ `/ * \___/_/|_/_/ |_/_/ (_)___/_/ \_, / * /___/ * repository. * * Copyright (C) 2017-present Benoit 'BoD' Lubek ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jraf.android.cinetoday.glide import android.graphics.drawable.Drawable import android.widget.ImageView import com.bumptech.glide.load.DataSource import com.bumptech.glide.load.engine.GlideException import com.bumptech.glide.request.RequestListener import com.bumptech.glide.request.target.Target import org.jraf.android.util.log.Log object GlideHelper { private val requestListener = object : RequestListener<Drawable> { override fun onResourceReady( resource: Drawable, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { return false } override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { Log.w(e, "Could not load image $model") return false } } private fun getRequestBuilder(path: String?, imageView: ImageView): GlideRequest<Drawable> { return GlideApp.with(imageView.context) .load(path) .centerCrop() } fun load(path: String?, imageView: ImageView) { getRequestBuilder(path, imageView) .listener(requestListener) .into(imageView) } fun load(path: String?, imageView: ImageView, listener: RequestListener<Drawable>) { getRequestBuilder(path, imageView) .listener(object : RequestListener<Drawable> { override fun onLoadFailed( e: GlideException?, model: Any?, target: Target<Drawable>?, isFirstResource: Boolean ): Boolean { requestListener.onLoadFailed(e, model, target, isFirstResource) return listener.onLoadFailed(e, model, target, isFirstResource) } override fun onResourceReady( resource: Drawable, model: Any?, target: Target<Drawable>?, dataSource: DataSource?, isFirstResource: Boolean ): Boolean { requestListener.onResourceReady(resource, model, target, dataSource, isFirstResource) return listener.onResourceReady(resource, model, target, dataSource, isFirstResource) } }) .into(imageView) } }
gpl-3.0
Schlangguru/paperless-uploader
app/src/main/java/de/schlangguru/paperlessuploader/ui/settings/AppCompatPreferenceActivity.kt
1
2536
package de.schlangguru.paperlessuploader.ui.settings import android.content.res.Configuration import android.os.Bundle import android.preference.PreferenceActivity import android.support.annotation.LayoutRes import android.support.v7.app.ActionBar import android.support.v7.app.AppCompatDelegate import android.support.v7.widget.Toolbar import android.view.MenuInflater import android.view.View import android.view.ViewGroup /** * A [android.preference.PreferenceActivity] which implements and proxies the necessary calls * to be used with AppCompat. */ abstract class AppCompatPreferenceActivity : PreferenceActivity() { private lateinit var delegate: AppCompatDelegate override fun onCreate(savedInstanceState: Bundle?) { delegate = AppCompatDelegate.create(this, null) delegate.installViewFactory() delegate.onCreate(savedInstanceState) super.onCreate(savedInstanceState) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) delegate.onPostCreate(savedInstanceState) } val supportActionBar: ActionBar? get() = delegate.supportActionBar fun setSupportActionBar(toolbar: Toolbar?) { delegate.setSupportActionBar(toolbar) } override fun getMenuInflater(): MenuInflater { return delegate.menuInflater } override fun setContentView(@LayoutRes layoutResID: Int) { delegate.setContentView(layoutResID) } override fun setContentView(view: View) { delegate.setContentView(view) } override fun setContentView(view: View, params: ViewGroup.LayoutParams) { delegate.setContentView(view, params) } override fun addContentView(view: View, params: ViewGroup.LayoutParams) { delegate.addContentView(view, params) } override fun onPostResume() { super.onPostResume() delegate.onPostResume() } override fun onTitleChanged(title: CharSequence, color: Int) { super.onTitleChanged(title, color) delegate.setTitle(title) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) delegate.onConfigurationChanged(newConfig) } override fun onStop() { super.onStop() delegate.onStop() } override fun onDestroy() { super.onDestroy() delegate.onDestroy() } override fun invalidateOptionsMenu() { delegate.invalidateOptionsMenu() } }
mit
Instagram/ig-json-parser
processor/src/test/java/com/instagram/common/json/annotation/processor/JavaLargeObjectSupportTest.kt
1
11891
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.instagram.common.json.annotation.processor import org.junit.Assert.assertEquals import org.junit.Test /** * Testing whether the [JsonAnnotationProcessor] generates valid Java code when reading annotations * of larger models */ class JavaLargeObjectSupportTest { val json = """{"field1":"field1","field2":"field2","field3":"field3","field4":"field4","field5":"field5","field6":"field6","field7":"field7","field8":"field8","field9":"field9","field10":"field10","field11":"field11","field12":"field12","field13":"field13","field14":"field14","field15":"field15","field16":"field16","field17":"field17","field18":"field18","field19":"field19","field20":"field20","field21":"field21","field22":"field22","field23":"field23","field24":"field24","field25":"field25","field26":"field26","field27":"field27","field28":"field28","field29":"field29","field30":"field30","field31":"field31","field32":"field32","field33":"field33","field34":"field34","field35":"field35","field36":"field36","field37":"field37","field38":"field38","field39":"field39","field40":"field40","field41":"field41","field42":"field42","field43":"field43","field44":"field44","field45":"field45","field46":"field46","field47":"field47","field48":"field48","field49":"field49","field50":"field50","field51":"field51","field52":"field52","field53":"field53","field54":"field54","field55":"field55","field56":"field56","field57":"field57","field58":"field58","field59":"field59","field60":"field60","field61":"field61","field62":"field62","field63":"field63","field64":"field64","field65":"field65","field66":"field66","field67":"field67","field68":"field68","field69":"field69","field70":"field70","field71":"field71","field72":"field72","field73":"field73","field74":"field74","field75":"field75","field76":"field76","field77":"field77","field78":"field78","field79":"field79","field80":"field80","field81":"field81","field82":"field82","field83":"field83","field84":"field84","field85":"field85","field86":"field86","field87":"field87","field88":"field88","field89":"field89","field90":"field90","field91":"field91","field92":"field92","field93":"field93","field94":"field94","field95":"field95","field96":"field96","field97":"field97","field98":"field98","field99":"field99","field100":"field100","field101":"field101","field102":"field102","field103":"field103","field104":"field104","field105":"field105","field106":"field106","field107":"field107","field108":"field108","field109":"field109","field110":"field110","field111":"field111","field112":"field112","field113":"field113","field114":"field114","field115":"field115","field116":"field116","field117":"field117","field118":"field118","field119":"field119","field120":"field120","field121":"field121","field122":"field122","field123":"field123","field124":"field124","field125":"field125","field126":"field126","field127":"field127","field128":"field128","field129":"field129","field130":"field130","field131":"field131","field132":"field132","field133":"field133","field134":"field134","field135":"field135","field136":"field136","field137":"field137","field138":"field138","field139":"field139","field140":"field140","field141":"field141","field142":"field142","field143":"field143","field144":"field144","field145":"field145","field146":"field146","field147":"field147","field148":"field148","field149":"field149","field150":"field150","field151":"field151","field152":"field152","field153":"field153","field154":"field154","field155":"field155","field156":"field156","field157":"field157","field158":"field158","field159":"field159","field160":"field160","field161":"field161","field162":"field162","field163":"field163","field164":"field164","field165":"field165","field166":"field166","field167":"field167","field168":"field168","field169":"field169","field170":"field170","field171":"field171","field172":"field172","field173":"field173","field174":"field174","field175":"field175","field176":"field176","field177":"field177","field178":"field178","field179":"field179","field180":"field180","field181":"field181","field182":"field182","field183":"field183","field184":"field184","field185":"field185","field186":"field186","field187":"field187","field188":"field188","field189":"field189","field190":"field190","field191":"field191","field192":"field192","field193":"field193","field194":"field194","field195":"field195","field196":"field196","field197":"field197","field198":"field198","field199":"field199","field200":"field200","field201":"field201","field202":"field202","field203":"field203","field204":"field204","field205":"field205","field206":"field206","field207":"field207","field208":"field208","field209":"field209","field210":"field210","field211":"field211","field212":"field212","field213":"field213","field214":"field214","field215":"field215","field216":"field216","field217":"field217","field218":"field218","field219":"field219","field220":"field220","field221":"field221","field222":"field222","field223":"field223","field224":"field224","field225":"field225","field226":"field226","field227":"field227","field228":"field228","field229":"field229","field230":"field230","field231":"field231","field232":"field232","field233":"field233","field234":"field234","field235":"field235","field236":"field236","field237":"field237","field238":"field238","field239":"field239","field240":"field240","field241":"field241","field242":"field242","field243":"field243","field244":"field244","field245":"field245","field246":"field246","field247":"field247","field248":"field248","field249":"field249","field250":"field250","field251":"field251","field252":"field252","field253":"field253","field254":"field254","field255":"field255","field256":"field256","field257":"field257","field258":"field258","field259":"field259","field260":"field260","field261":"field261","field262":"field262","field263":"field263","field264":"field264","field265":"field265","field266":"field266","field267":"field267","field268":"field268","field269":"field269","field270":"field270","field271":"field271","field272":"field272","field273":"field273","field274":"field274","field275":"field275","field276":"field276","field277":"field277","field278":"field278","field279":"field279","field280":"field280","field281":"field281","field282":"field282","field283":"field283","field284":"field284","field285":"field285","field286":"field286","field287":"field287","field288":"field288","field289":"field289","field290":"field290","field291":"field291","field292":"field292","field293":"field293","field294":"field294","field295":"field295","field296":"field296","field297":"field297","field298":"field298","field299":"field299","field300":"field300","field301":"field301","field302":"field302","field303":"field303","field304":"field304","field305":"field305","field306":"field306","field307":"field307","field308":"field308","field309":"field309","field310":"field310","field311":"field311","field312":"field312","field313":"field313","field314":"field314","field315":"field315","field316":"field316","field317":"field317","field318":"field318","field319":"field319","field320":"field320","field321":"field321","field322":"field322","field323":"field323","field324":"field324","field325":"field325","field326":"field326","field327":"field327","field328":"field328","field329":"field329","field330":"field330","field331":"field331","field332":"field332","field333":"field333","field334":"field334","field335":"field335","field336":"field336","field337":"field337","field338":"field338","field339":"field339","field340":"field340","field341":"field341","field342":"field342","field343":"field343","field344":"field344","field345":"field345","field346":"field346","field347":"field347","field348":"field348","field349":"field349","field350":"field350","field351":"field351","field352":"field352","field353":"field353","field354":"field354","field355":"field355","field356":"field356","field357":"field357","field358":"field358","field359":"field359","field360":"field360","field361":"field361","field362":"field362","field363":"field363","field364":"field364","field365":"field365","field366":"field366","field367":"field367","field368":"field368","field369":"field369","field370":"field370","field371":"field371","field372":"field372","field373":"field373","field374":"field374","field375":"field375","field376":"field376","field377":"field377","field378":"field378","field379":"field379","field380":"field380","field381":"field381","field382":"field382","field383":"field383","field384":"field384","field385":"field385","field386":"field386","field387":"field387","field388":"field388","field389":"field389","field390":"field390","field391":"field391","field392":"field392","field393":"field393","field394":"field394","field395":"field395","field396":"field396","field397":"field397","field398":"field398","field399":"field399","field400":"field400","field401":"field401","field402":"field402","field403":"field403","field404":"field404","field405":"field405","field406":"field406","field407":"field407","field408":"field408","field409":"field409","field410":"field410","field411":"field411","field412":"field412","field413":"field413","field414":"field414","field415":"field415","field416":"field416","field417":"field417","field418":"field418","field419":"field419","field420":"field420","field421":"field421","field422":"field422","field423":"field423","field424":"field424","field425":"field425","field426":"field426","field427":"field427","field428":"field428","field429":"field429","field430":"field430","field431":"field431","field432":"field432","field433":"field433","field434":"field434","field435":"field435","field436":"field436","field437":"field437","field438":"field438","field439":"field439","field440":"field440","field441":"field441","field442":"field442","field443":"field443","field444":"field444","field445":"field445","field446":"field446","field447":"field447","field448":"field448","field449":"field449","field450":"field450","field451":"field451","field452":"field452","field453":"field453","field454":"field454","field455":"field455","field456":"field456","field457":"field457","field458":"field458","field459":"field459","field460":"field460","field461":"field461","field462":"field462","field463":"field463","field464":"field464","field465":"field465","field466":"field466","field467":"field467","field468":"field468","field469":"field469","field470":"field470","field471":"field471","field472":"field472","field473":"field473","field474":"field474","field475":"field475","field476":"field476","field477":"field477","field478":"field478","field479":"field479","field480":"field480","field481":"field481","field482":"field482","field483":"field483","field484":"field484","field485":"field485","field486":"field486","field487":"field487","field488":"field488","field489":"field489","field490":"field490","field491":"field491","field492":"field492","field493":"field493","field494":"field494","field495":"field495","field496":"field496","field497":"field497","field498":"field498","field499":"field499","field500":"field500","field501":"field501","field502":"field502","field503":"field503","field504":"field504","field505":"field505","field506":"field506","field507":"field507","field508":"field508"}""" @Test fun handlesJavaImmutableClassFromJson() { val actual = LargeObject__JsonHelper.parseFromJson(json) assertEquals("field1", actual.field1) assertEquals("field508", actual.field508) } @Test fun deserializeThenSerializeIsSymmetric() { val actual = LargeObject__JsonHelper.parseFromJson(json) val actualJson = LargeObject__JsonHelper.serializeToJson(actual) assertEquals(actualJson, json) } }
mit
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/callableReference/property/privateSetterOutsideClass.kt
4
675
// See KT-12337 Reference to property with invisible setter should not be a KMutableProperty import kotlin.reflect.KProperty1 import kotlin.reflect.KMutableProperty open class Bar(name: String) { var foo: String = name private set } class Baz : Bar("") { fun ref() = Bar::foo } fun box(): String { val p1: KProperty1<Bar, String> = Bar::foo if (p1 is KMutableProperty<*>) return "Fail: p1 is a KMutableProperty" val p2 = Baz().ref() if (p2 is KMutableProperty<*>) return "Fail: p2 is a KMutableProperty" val p3 = Bar("")::foo if (p3 is KMutableProperty<*>) return "Fail: p3 is a KMutableProperty" return p1.get(Bar("OK")) }
apache-2.0
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/StaticData.kt
1
6451
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.llvm import llvm.* import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.types.KotlinType /** * Provides utilities to create static data. */ internal class StaticData(override val context: Context): ContextUtils { /** * Represents the LLVM global variable. */ class Global private constructor(val staticData: StaticData, val llvmGlobal: LLVMValueRef) { companion object { private fun createLlvmGlobal(module: LLVMModuleRef, type: LLVMTypeRef, name: String, isExported: Boolean ): LLVMValueRef { if (isExported && LLVMGetNamedGlobal(module, name) != null) { throw IllegalArgumentException("Global '$name' already exists") } // Globals created with this API are *not* thread local. val llvmGlobal = LLVMAddGlobal(module, type, name)!! if (!isExported) { LLVMSetLinkage(llvmGlobal, LLVMLinkage.LLVMInternalLinkage) } return llvmGlobal } fun create(staticData: StaticData, type: LLVMTypeRef, name: String, isExported: Boolean): Global { val module = staticData.context.llvmModule val isUnnamed = (name == "") // LLVM will select the unique index and represent the global as `@idx`. if (isUnnamed && isExported) { throw IllegalArgumentException("unnamed global can't be exported") } val llvmGlobal = createLlvmGlobal(module!!, type, name, isExported) return Global(staticData, llvmGlobal) } } fun setInitializer(value: ConstValue) { LLVMSetInitializer(llvmGlobal, value.llvm) } fun setConstant(value: Boolean) { LLVMSetGlobalConstant(llvmGlobal, if (value) 1 else 0) } val pointer = Pointer.to(this) } /** * Represents the pointer to static data. * It can be a pointer to either a global or any its element. * * TODO: this class is probably should be implemented more optimally */ class Pointer private constructor(val global: Global, private val delegate: ConstPointer, val offsetInGlobal: Long) : ConstPointer by delegate { companion object { fun to(global: Global) = Pointer(global, constPointer(global.llvmGlobal), 0L) } private fun getElementOffset(index: Int): Long { val llvmTargetData = global.staticData.llvmTargetData val type = LLVMGetElementType(delegate.llvmType) return when (LLVMGetTypeKind(type)) { LLVMTypeKind.LLVMStructTypeKind -> LLVMOffsetOfElement(llvmTargetData, type, index) LLVMTypeKind.LLVMArrayTypeKind -> LLVMABISizeOfType(llvmTargetData, LLVMGetElementType(type)) * index else -> TODO() } } override fun getElementPtr(index: Int): Pointer { return Pointer(global, delegate.getElementPtr(index), offsetInGlobal + this.getElementOffset(index)) } /** * @return the distance from other pointer to this. * * @throws UnsupportedOperationException if it is not possible to represent the distance as [Int] value */ fun sub(other: Pointer): Int { if (this.global != other.global) { throw UnsupportedOperationException("pointers must belong to the same global") } val res = this.offsetInGlobal - other.offsetInGlobal if (res.toInt().toLong() != res) { throw UnsupportedOperationException("result doesn't fit into Int") } return res.toInt() } } /** * Creates [Global] with given type and name. * * It is external until explicitly initialized with [Global.setInitializer]. */ fun createGlobal(type: LLVMTypeRef, name: String, isExported: Boolean = false): Global { return Global.create(this, type, name, isExported) } /** * Creates [Global] with given name and value. */ fun placeGlobal(name: String, initializer: ConstValue, isExported: Boolean = false): Global { val global = createGlobal(initializer.llvmType, name, isExported) global.setInitializer(initializer) return global } /** * Creates array-typed global with given name and value. */ fun placeGlobalArray(name: String, elemType: LLVMTypeRef?, elements: List<ConstValue>): Global { val initializer = ConstArray(elemType, elements) val global = placeGlobal(name, initializer) return global } private val stringLiterals = mutableMapOf<String, ConstPointer>() private val cStringLiterals = mutableMapOf<String, ConstPointer>() fun cStringLiteral(value: String) = cStringLiterals.getOrPut(value) { placeCStringLiteral(value) } fun kotlinStringLiteral(type: KotlinType, value: IrConst<String>) = stringLiterals.getOrPut(value.value) { createKotlinStringLiteral(type, value) } } /** * Creates static instance of `konan.ImmutableByteArray` with given values of elements. * * @param args data for constant creation. */ internal fun StaticData.createImmutableBinaryBlob(value: IrConst<String>): LLVMValueRef { val args = value.value.map { Int8(it.toByte()).llvm } return createKotlinArray(context.ir.symbols.immutableBinaryBlob.descriptor.defaultType, args) }
apache-2.0
robfletcher/orca
keiko-sql/src/main/kotlin/com/netflix/spinnaker/q/sql/util/Util.kt
4
1467
/* * Copyright 2020 Apple, 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.netflix.spinnaker.q.sql.util import org.jooq.DSLContext import org.jooq.Field import org.jooq.SQLDialect import org.jooq.impl.DSL fun currentSchema(context: DSLContext): String { return context.fetch("select current_schema()") .getValue(0, DSL.field("current_schema")).toString() } fun createTableLike(newTable: String, templateTable: String, context: DSLContext) { var sql = "CREATE TABLE IF NOT EXISTS " sql += when (context.dialect()) { SQLDialect.POSTGRES -> { val cs = currentSchema(context) "$cs.$newTable ( LIKE $cs.$templateTable INCLUDING ALL )" } else -> "$newTable LIKE $templateTable" } context.execute(sql) } // Allows insertion of virtual Postgres values on conflict, similar to MySQLDSL.values fun <T> excluded(values: Field<T>): Field<T> { return DSL.field("excluded.{0}", values.dataType, values) }
apache-2.0
WhosNickDoglio/Aww-Gallery
app/src/main/java/com/nicholasdoglio/eyebleach/data/util/DataExtensions.kt
1
1879
/* * MIT License * * Copyright (c) 2019. Nicholas Doglio * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.nicholasdoglio.eyebleach.data.util import com.nicholasdoglio.eyebleach.data.ChildData import com.nicholasdoglio.eyebleach.data.ListingResponse import com.nicholasdoglio.eyebleach.data.RedditPost fun ListingResponse.toRedditPosts(): List<RedditPost> = this.data.children.asSequence() .filter { !it.data.over18 } .filter { it.data.url.contains(".jpg") || it.data.url.contains(".png") } .map { it.data.toRedditPost() } .toList() fun ChildData.toRedditPost(): RedditPost = RedditPost( url = url, name = name, thumbnail = thumbnail, permalink = permalink ) inline val RedditPost.redditUrl: String get() = "https://reddit.com$permalink"
mit
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/ui/catalogue/browse/ProgressItem.kt
1
1647
package eu.kanade.tachiyomi.ui.catalogue.browse import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ProgressBar import android.widget.TextView import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractFlexibleItem import eu.davidea.flexibleadapter.items.IFlexible import eu.davidea.viewholders.FlexibleViewHolder import eu.kanade.tachiyomi.R class ProgressItem : AbstractFlexibleItem<ProgressItem.Holder>() { private var loadMore = true override fun getLayoutRes(): Int { return R.layout.catalogue_progress_item } override fun createViewHolder(view: View, adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>): Holder { return Holder(view, adapter) } override fun bindViewHolder(adapter: FlexibleAdapter<IFlexible<RecyclerView.ViewHolder>>, holder: Holder, position: Int, payloads: List<Any?>) { holder.progressBar.visibility = View.GONE holder.progressMessage.visibility = View.GONE if (!adapter.isEndlessScrollEnabled) { loadMore = false } if (loadMore) { holder.progressBar.visibility = View.VISIBLE } else { holder.progressMessage.visibility = View.VISIBLE } } override fun equals(other: Any?): Boolean { return this === other } class Holder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter) { val progressBar: ProgressBar = view.findViewById(R.id.progress_bar) val progressMessage: TextView = view.findViewById(R.id.progress_message) } }
apache-2.0
K0zka/wikistat
src/main/kotlin/org/dictat/wikistat/servlets/LanguageServlet.kt
1
552
package org.dictat.wikistat.servlets import javax.servlet.http.HttpServlet import org.dictat.wikistat.services.PageDao import org.springframework.web.context.support.WebApplicationContextUtils import javax.servlet.ServletConfig import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import com.fasterxml.jackson.databind.ObjectMapper public final class LanguageServlet : PageDaoServlet<List<String>>() { override fun getData(req: HttpServletRequest): List<String> { return getBean().getLangs(); } }
apache-2.0
olivierperez/crapp
feature-summary/src/main/java/fr/o80/featuresummary/usecase/MonthSummary.kt
1
2135
package fr.o80.featuresummary.usecase import fr.o80.crapp.data.ProjectRepository import fr.o80.crapp.data.TimesheetRepository import fr.o80.crapp.data.entity.Project import fr.o80.crapp.data.entity.TimeEntry import fr.o80.featuresummary.usecase.model.ProjectSummary import fr.o80.sample.lib.dagger.FeatureScope import fr.o80.sample.lib.utils.firstDayOfMonth import fr.o80.sample.lib.utils.lastDayOfMonth import io.reactivex.Observable import io.reactivex.Single import io.reactivex.functions.BiFunction import io.reactivex.schedulers.Schedulers import java.util.Date import javax.inject.Inject /** * @author Olivier Perez */ @FeatureScope class MonthSummary @Inject constructor(private val timesheetRepository: TimesheetRepository, private val projectRepository: ProjectRepository) { fun getMonth(startDate: Date): Single<List<ProjectSummary>> { val start = firstDayOfMonth(startDate) val end = lastDayOfMonth(startDate) val projectsSingle = projectRepository.all() val entriesSingle = timesheetRepository .findByDateRange(start, end) .flatMapObservable { Observable.fromIterable(it) } .toMultimap { it.project!!.id } return Single.zip<List<Project>, MutableMap<Long, MutableCollection<TimeEntry>>, List<ProjectSummary>>( projectsSingle, entriesSingle, BiFunction { projects, entries -> projects .filter { (id) -> entries.containsKey(id) } .map { (id, label, code) -> ProjectSummary( label!!, code!!, entries[id] ?.map(TimeEntry::hours) ?.fold(0) { acc, item -> acc + item } ?: 0 ) } }) .subscribeOn(Schedulers.io()) } }
apache-2.0
FelixKlauke/mercantor
commons/src/main/kotlin/de/d3adspace/mercantor/commons/model/HeartbeatModel.kt
1
222
package de.d3adspace.mercantor.commons.model import java.util.* /** * @author Felix Klauke <[email protected]> */ data class HeartbeatModel(val status: ServiceStatus, val instanceId: UUID)
mit
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/more/NewUpdateDialogController.kt
1
2517
package eu.kanade.tachiyomi.ui.more import android.app.Dialog import android.os.Bundle import android.text.method.LinkMovementMethod import android.view.View import android.widget.TextView import androidx.core.os.bundleOf import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.updater.AppUpdateResult import eu.kanade.tachiyomi.data.updater.AppUpdateService import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.openInBrowser import io.noties.markwon.Markwon class NewUpdateDialogController(bundle: Bundle? = null) : DialogController(bundle) { constructor(update: AppUpdateResult.NewUpdate) : this( bundleOf( BODY_KEY to update.release.info, VERSION_KEY to update.release.version, RELEASE_URL_KEY to update.release.releaseLink, DOWNLOAD_URL_KEY to update.release.getDownloadLink(), ), ) override fun onCreateDialog(savedViewState: Bundle?): Dialog { val releaseBody = args.getString(BODY_KEY)!! .replace("""---(\R|.)*Checksums(\R|.)*""".toRegex(), "") val info = Markwon.create(activity!!).toMarkdown(releaseBody) return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.update_check_notification_update_available) .setMessage(info) .setPositiveButton(R.string.update_check_confirm) { _, _ -> applicationContext?.let { context -> // Start download val url = args.getString(DOWNLOAD_URL_KEY)!! val version = args.getString(VERSION_KEY) AppUpdateService.start(context, url, version) } } .setNeutralButton(R.string.update_check_open) { _, _ -> openInBrowser(args.getString(RELEASE_URL_KEY)!!) } .create() } override fun onAttach(view: View) { super.onAttach(view) // Make links in Markdown text clickable (dialog?.findViewById(android.R.id.message) as? TextView)?.movementMethod = LinkMovementMethod.getInstance() } } private const val BODY_KEY = "NewUpdateDialogController.body" private const val VERSION_KEY = "NewUpdateDialogController.version" private const val RELEASE_URL_KEY = "NewUpdateDialogController.release_url" private const val DOWNLOAD_URL_KEY = "NewUpdateDialogController.download_url"
apache-2.0
deltaDNA/android-sdk
library-notifications/src/test/java/com/deltadna/android/sdk/notifications/NotificationInfoTest.kt
1
1301
/* * Copyright (c) 2017 deltaDNA Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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.deltadna.android.sdk.notifications import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class NotificationInfoTest { @Test fun construction() { val id = 1 val message = PushMessage( RuntimeEnvironment.application, "from", emptyMap()) NotificationInfo(id, message).apply { assertThat(this.id).isEqualTo(id) assertThat(this.message).isEqualTo(message) } } }
apache-2.0
monarezio/Takuzu
app/src/main/java/net/zdendukmonarezio/takuzu/domain/score/ScoreManager.kt
1
711
package net.zdendukmonarezio.takuzu.domain.score import android.content.Context import net.zdendukmonarezio.takuzu.data.score.ScoreData import rx.Observable /** * Created by monarezio on 08/04/2017. */ class ScoreManager private constructor(private val score: Score) { /** * return a observable with the score */ fun getScore(): Observable<Int> = this.score.getScore() /** * set the score */ fun setScore(score: Int) = this.score.setScore(score) /** * adds the score */ fun addScore(score: Int) = this.score.addScore(score) companion object { @JvmStatic fun createScoreManager(context: Context) = ScoreManager(ScoreData(context)) } }
mit
russhwolf/Code-Computer
src/test/kotlin/codecomputer/AccumulatorTest.kt
1
2283
package codecomputer import org.junit.Test class AccumulatorTest { private val A = 27 private val B = 16 private val C = 62 @Test fun accumulatorTest() { val input = 0.toSignals(8) val add = Relay() val clear = Relay() val accumulator = Accumulator(input, add, clear) accumulator.readAndAssert(0, "accumulator 1") input.write(A) accumulator.readAndAssert(0, "accumulator 2") add.write(true) add.write(false) accumulator.readAndAssert(A, "accumulator 3") input.write(B) accumulator.readAndAssert(A, "accumulator 4") add.write(true) add.write(false) accumulator.readAndAssert(A + B, "accumulator 5") input.write(C) add.write(true) add.write(false) accumulator.readAndAssert(A + B + C, "accumulator 6") add.write(true) add.write(false) accumulator.readAndAssert(A + B + C + C, "accumulator 7") clear.write(true) clear.write(false) accumulator.readAndAssert(0, "accumulator 8") } @Test fun ramAccumulatorTest() { val oscillator = Oscillator() val address = 0.toSignals(4) val data = 0.toSignals(8) val write = Relay() val clear = Relay() val takeover = Relay() val accumulator = RamAccumulator(oscillator, address, data, write, clear, takeover) accumulator.readAndAssert(0, "ram accumulator 1") takeover.write(true) address.write(0) data.write(A) write.write(true) write.write(false) address.write(1) data.write(B) write.write(true) write.write(false) address.write(2) data.write(C) write.write(true) write.write(false) takeover.write(false) accumulator.readAndAssert(0, "ram accumulator 2") oscillator.run(2) accumulator.readAndAssert(A, "ram accumulator 3") oscillator.run(2) accumulator.readAndAssert(A + B, "ram accumulator 4") oscillator.run(2) accumulator.readAndAssert(A + B + C, "ram accumulator 5") clear.write(true) clear.write(false) accumulator.readAndAssert(0, "ram accumulator 6") } }
mit
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt
1
1372
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * LanguageInquireResponsePacket */ class LanguageInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump init { msgType = 0xA0.toByte() aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket init") } override fun handleMessage(data: ByteArray?) { val result = defect(data) if (result != 0) { aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket Got some Error") failed = true return } else failed = false val bufferData = prefixDecode(data) val result2 = getByteToInt(bufferData) if(!isSuccInquireResponseResult(result2)) { failed = true return } diaconnG8Pump.selectedLanguage = getByteToInt(bufferData) aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage --> ${diaconnG8Pump.selectedLanguage}") } override fun getFriendlyName(): String { return "PUMP_LANGUAGE_INQUIRE_RESPONSE" } }
agpl-3.0
Heiner1/AndroidAPS
danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAlarmTest.kt
1
340
package info.nightscout.androidaps.plugins.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MsgHistoryAlarm import org.junit.Test class MsgHistoryAlarmTest : DanaRTestBase() { @Test fun runTest() { @Suppress("UNUSED_VARIABLE") val packet = MsgHistoryAlarm(injector) // nothing left to test } }
agpl-3.0
szaboa/ShowTrackerMVP
app/src/main/java/com/cdev/showtracker/BasePresenter.kt
1
123
package com.cdev.showtracker interface BasePresenter<in T : BaseView> { fun attachView(view: T) fun detachView() }
mit
onoderis/failchat
src/main/kotlin/failchat/chat/OriginStatusManager.kt
2
1531
package failchat.chat import failchat.Origin import failchat.chat.OriginStatus.DISCONNECTED import failchat.chatOrigins import failchat.util.enumMap import java.util.EnumMap import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write class OriginStatusManager( private val messageSender: ChatMessageSender ) { private companion object { val allDisconnected: Map<Origin, OriginStatus> = enumMap<Origin, OriginStatus>().also { map -> chatOrigins.forEach { origin -> map[origin] = DISCONNECTED } } } private val statuses: EnumMap<Origin, OriginStatus> = enumMap() private val lock = ReentrantReadWriteLock() init { chatOrigins.forEach { statuses[it] = DISCONNECTED } } fun getStatuses(): Map<Origin, OriginStatus> { return lock.read { cloneStatuses() } } fun setStatus(origin: Origin, status: OriginStatus) { val afterMap = lock.write { statuses[origin] = status cloneStatuses() } messageSender.sendConnectedOriginsMessage(afterMap) } fun reset() { lock.write { statuses.entries.forEach { it.setValue(DISCONNECTED) } } messageSender.sendConnectedOriginsMessage(allDisconnected) } private fun cloneStatuses(): EnumMap<Origin, OriginStatus> { return EnumMap(statuses) } }
gpl-3.0
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/ide/projectView/impl/ProjectViewState.kt
3
3814
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.projectView.impl import com.intellij.ide.projectView.ProjectViewSettings import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.components.* import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.registry.Registry import com.intellij.ui.ExperimentalUI import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "ProjectViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))]) class ProjectViewState : PersistentStateComponent<ProjectViewState> { companion object { @JvmStatic fun getInstance(project: Project): ProjectViewState = project.service() @JvmStatic fun getDefaultInstance(): ProjectViewState = ProjectManager.getInstance().defaultProject.service() } var abbreviatePackageNames = ProjectViewSettings.Immutable.DEFAULT.isAbbreviatePackageNames var autoscrollFromSource = ExperimentalUI.isNewUI() var autoscrollToSource = UISettings.getInstance().state.defaultAutoScrollToSource var compactDirectories = ProjectViewSettings.Immutable.DEFAULT.isCompactDirectories var flattenModules = ProjectViewSettings.Immutable.DEFAULT.isFlattenModules var flattenPackages = ProjectViewSettings.Immutable.DEFAULT.isFlattenPackages var foldersAlwaysOnTop = ProjectViewSettings.Immutable.DEFAULT.isFoldersAlwaysOnTop var hideEmptyMiddlePackages = ProjectViewSettings.Immutable.DEFAULT.isHideEmptyMiddlePackages var manualOrder = false var showExcludedFiles = ProjectViewSettings.Immutable.DEFAULT.isShowExcludedFiles var showLibraryContents = ProjectViewSettings.Immutable.DEFAULT.isShowLibraryContents var showMembers = ProjectViewSettings.Immutable.DEFAULT.isShowMembers var showModules = ProjectViewSettings.Immutable.DEFAULT.isShowModules var showURL = ProjectViewSettings.Immutable.DEFAULT.isShowURL var showVisibilityIcons = ProjectViewSettings.Immutable.DEFAULT.isShowVisibilityIcons var sortByType = false var useFileNestingRules = ProjectViewSettings.Immutable.DEFAULT.isUseFileNestingRules override fun noStateLoaded() { val application = getApplication() if (application == null || application.isUnitTestMode) return // for backward compatibility abbreviatePackageNames = ProjectViewSharedSettings.instance.abbreviatePackages autoscrollFromSource = ProjectViewSharedSettings.instance.autoscrollFromSource autoscrollToSource = ProjectViewSharedSettings.instance.autoscrollToSource compactDirectories = ProjectViewSharedSettings.instance.compactDirectories flattenModules = ProjectViewSharedSettings.instance.flattenModules flattenPackages = ProjectViewSharedSettings.instance.flattenPackages foldersAlwaysOnTop = ProjectViewSharedSettings.instance.foldersAlwaysOnTop hideEmptyMiddlePackages = ProjectViewSharedSettings.instance.hideEmptyPackages manualOrder = ProjectViewSharedSettings.instance.manualOrder showExcludedFiles = ProjectViewSharedSettings.instance.showExcludedFiles showLibraryContents = ProjectViewSharedSettings.instance.showLibraryContents showMembers = ProjectViewSharedSettings.instance.showMembers showModules = ProjectViewSharedSettings.instance.showModules showURL = Registry.`is`("project.tree.structure.show.url") showVisibilityIcons = ProjectViewSharedSettings.instance.showVisibilityIcons sortByType = ProjectViewSharedSettings.instance.sortByType } override fun loadState(state: ProjectViewState) { XmlSerializerUtil.copyBean(state, this) } override fun getState(): ProjectViewState { return this } }
apache-2.0
PolymerLabs/arcs
src/tools/tests/goldens/generated-schemas.jvm.kt
1
22543
/* ktlint-disable */ @file:Suppress("PackageName", "TopLevelName") package arcs.golden // // GENERATED CODE -- DO NOT EDIT // import arcs.core.data.Annotation import arcs.core.data.expression.* import arcs.core.data.expression.Expression.* import arcs.core.data.expression.Expression.BinaryOp.* import arcs.core.data.util.toReferencable import arcs.sdk.ArcsDuration import arcs.sdk.ArcsInstant import arcs.sdk.BigInt import arcs.sdk.Entity import arcs.sdk.toBigInt import javax.annotation.Generated typealias Gold_Data_Ref = AbstractGold.GoldInternal1 typealias Gold_Data_Ref_Slice = AbstractGold.GoldInternal1Slice typealias Gold_Alias = AbstractGold.GoldInternal1 typealias Gold_Alias_Slice = AbstractGold.GoldInternal1Slice typealias Gold_AllPeople = AbstractGold.Gold_AllPeople typealias Gold_AllPeople_Slice = AbstractGold.Gold_AllPeople_Slice typealias Gold_Collection = AbstractGold.Foo typealias Gold_Collection_Slice = AbstractGold.FooSlice typealias Gold_Data = AbstractGold.Gold_Data typealias Gold_Data_Slice = AbstractGold.Gold_Data_Slice typealias Gold_QCollection = AbstractGold.Gold_QCollection typealias Gold_QCollection_Slice = AbstractGold.Gold_QCollection_Slice @Generated("src/tools/schema2kotlin.ts") abstract class AbstractGold : arcs.sdk.BaseParticle() { override val handles: Handles = Handles() interface GoldInternal1Slice : arcs.sdk.Entity { val val_: String } @Suppress("UNCHECKED_CAST") class GoldInternal1( val_: String = "", entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "GoldInternal1", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), GoldInternal1Slice { override var val_: String get() = super.getSingletonValue("val") as String? ?: "" private set(_value) = super.setSingletonValue("val", _value) init { this.val_ = val_ } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy(val_: String = this.val_) = GoldInternal1(val_ = val_) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate(val_: String = this.val_) = GoldInternal1( val_ = val_, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<GoldInternal1> { override val SCHEMA = arcs.core.data.Schema( setOf(), arcs.core.data.SchemaFields( singletons = mapOf("val" to arcs.core.data.FieldType.Text), collections = emptyMap() ), "a90c278182b80e5275b076240966fde836108a5b", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = GoldInternal1().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_AllPeople_Slice : arcs.sdk.Entity { val name: String val age: Double val lastCall: Double val address: String val favoriteColor: String val birthDayMonth: Double val birthDayDOM: Double } @Suppress("UNCHECKED_CAST") class Gold_AllPeople( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "Gold_AllPeople", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), Gold_AllPeople_Slice { override var name: String get() = super.getSingletonValue("name") as String? ?: "" private set(_value) = super.setSingletonValue("name", _value) override var age: Double get() = super.getSingletonValue("age") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("age", _value) override var lastCall: Double get() = super.getSingletonValue("lastCall") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("lastCall", _value) override var address: String get() = super.getSingletonValue("address") as String? ?: "" private set(_value) = super.setSingletonValue("address", _value) override var favoriteColor: String get() = super.getSingletonValue("favoriteColor") as String? ?: "" private set(_value) = super.setSingletonValue("favoriteColor", _value) override var birthDayMonth: Double get() = super.getSingletonValue("birthDayMonth") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayMonth", _value) override var birthDayDOM: Double get() = super.getSingletonValue("birthDayDOM") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayDOM", _value) init { this.name = name this.age = age this.lastCall = lastCall this.address = address this.favoriteColor = favoriteColor this.birthDayMonth = birthDayMonth this.birthDayDOM = birthDayDOM } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_AllPeople( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_AllPeople( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_AllPeople> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("People")), arcs.core.data.SchemaFields( singletons = mapOf( "name" to arcs.core.data.FieldType.Text, "age" to arcs.core.data.FieldType.Number, "lastCall" to arcs.core.data.FieldType.Number, "address" to arcs.core.data.FieldType.Text, "favoriteColor" to arcs.core.data.FieldType.Text, "birthDayMonth" to arcs.core.data.FieldType.Number, "birthDayDOM" to arcs.core.data.FieldType.Number ), collections = emptyMap() ), "430781483d522f87f27b5cc3d40fd28aa02ca8fd", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_AllPeople().apply { deserialize(data, nestedEntitySpecs) } } } interface FooSlice : arcs.sdk.Entity { val num: Double } @Suppress("UNCHECKED_CAST") class Foo( num: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase("Foo", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), FooSlice { override var num: Double get() = super.getSingletonValue("num") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("num", _value) init { this.num = num } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy(num: Double = this.num) = Foo(num = num) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate(num: Double = this.num) = Foo( num = num, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Foo> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("Foo")), arcs.core.data.SchemaFields( singletons = mapOf("num" to arcs.core.data.FieldType.Number), collections = emptyMap() ), "b73fa6f39c1a582996bec8776857fc24341b533c", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Foo().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_Data_Slice : arcs.sdk.Entity { val num: Double val txt: String val lnk: String val flg: Boolean val ref: arcs.sdk.Reference<GoldInternal1>? } @Suppress("UNCHECKED_CAST") class Gold_Data( num: Double = 0.0, txt: String = "", lnk: String = "", flg: Boolean = false, ref: arcs.sdk.Reference<GoldInternal1>? = null, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase("Gold_Data", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false), Gold_Data_Slice { override var num: Double get() = super.getSingletonValue("num") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("num", _value) override var txt: String get() = super.getSingletonValue("txt") as String? ?: "" private set(_value) = super.setSingletonValue("txt", _value) override var lnk: String get() = super.getSingletonValue("lnk") as String? ?: "" private set(_value) = super.setSingletonValue("lnk", _value) override var flg: Boolean get() = super.getSingletonValue("flg") as Boolean? ?: false private set(_value) = super.setSingletonValue("flg", _value) override var ref: arcs.sdk.Reference<GoldInternal1>? get() = super.getSingletonValue("ref") as arcs.sdk.Reference<GoldInternal1>? private set(_value) = super.setSingletonValue("ref", _value) init { this.num = num this.txt = txt this.lnk = lnk this.flg = flg this.ref = ref } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( num: Double = this.num, txt: String = this.txt, lnk: String = this.lnk, flg: Boolean = this.flg, ref: arcs.sdk.Reference<GoldInternal1>? = this.ref ) = Gold_Data(num = num, txt = txt, lnk = lnk, flg = flg, ref = ref) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( num: Double = this.num, txt: String = this.txt, lnk: String = this.lnk, flg: Boolean = this.flg, ref: arcs.sdk.Reference<GoldInternal1>? = this.ref ) = Gold_Data( num = num, txt = txt, lnk = lnk, flg = flg, ref = ref, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_Data> { override val SCHEMA = arcs.core.data.Schema( setOf(), arcs.core.data.SchemaFields( singletons = mapOf( "num" to arcs.core.data.FieldType.Number, "txt" to arcs.core.data.FieldType.Text, "lnk" to arcs.core.data.FieldType.Text, "flg" to arcs.core.data.FieldType.Boolean, "ref" to arcs.core.data.FieldType.EntityRef("a90c278182b80e5275b076240966fde836108a5b") ), collections = emptyMap() ), "ac9a319922d90e47a2f2a271fd9da3eda9aebd92", refinementExpression = true.asExpr(), queryExpression = true.asExpr() ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = mapOf("a90c278182b80e5275b076240966fde836108a5b" to GoldInternal1) init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_Data().apply { deserialize(data, nestedEntitySpecs) } } } interface Gold_QCollection_Slice : Gold_AllPeople_Slice { } @Suppress("UNCHECKED_CAST") class Gold_QCollection( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0, entityId: String? = null, creationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP, expirationTimestamp: Long = arcs.core.data.RawEntity.UNINITIALIZED_TIMESTAMP ) : arcs.sdk.EntityBase( "Gold_QCollection", SCHEMA, entityId, creationTimestamp, expirationTimestamp, false ), Gold_QCollection_Slice { override var name: String get() = super.getSingletonValue("name") as String? ?: "" private set(_value) = super.setSingletonValue("name", _value) override var age: Double get() = super.getSingletonValue("age") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("age", _value) override var lastCall: Double get() = super.getSingletonValue("lastCall") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("lastCall", _value) override var address: String get() = super.getSingletonValue("address") as String? ?: "" private set(_value) = super.setSingletonValue("address", _value) override var favoriteColor: String get() = super.getSingletonValue("favoriteColor") as String? ?: "" private set(_value) = super.setSingletonValue("favoriteColor", _value) override var birthDayMonth: Double get() = super.getSingletonValue("birthDayMonth") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayMonth", _value) override var birthDayDOM: Double get() = super.getSingletonValue("birthDayDOM") as Double? ?: 0.0 private set(_value) = super.setSingletonValue("birthDayDOM", _value) init { this.name = name this.age = age this.lastCall = lastCall this.address = address this.favoriteColor = favoriteColor this.birthDayMonth = birthDayMonth this.birthDayDOM = birthDayDOM } /** * Use this method to create a new, distinctly identified copy of the entity. * Storing the copy will result in a new copy of the data being stored. */ fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_QCollection( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) /** * Use this method to create a new version of an existing entity. * Storing the mutation will overwrite the existing entity in the set, if it exists. */ fun mutate( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_QCollection( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM, entityId = entityId, creationTimestamp = creationTimestamp, expirationTimestamp = expirationTimestamp ) companion object : arcs.sdk.EntitySpec<Gold_QCollection> { override val SCHEMA = arcs.core.data.Schema( setOf(arcs.core.data.SchemaName("People")), arcs.core.data.SchemaFields( singletons = mapOf( "name" to arcs.core.data.FieldType.Text, "age" to arcs.core.data.FieldType.Number, "lastCall" to arcs.core.data.FieldType.Number, "address" to arcs.core.data.FieldType.Text, "favoriteColor" to arcs.core.data.FieldType.Text, "birthDayMonth" to arcs.core.data.FieldType.Number, "birthDayDOM" to arcs.core.data.FieldType.Number ), collections = emptyMap() ), "430781483d522f87f27b5cc3d40fd28aa02ca8fd", refinementExpression = true.asExpr(), queryExpression = ((lookup<String>("name") eq query<String>("queryArgument")) and (lookup<Number>("lastCall") lt 259200.asExpr())) ) private val nestedEntitySpecs: Map<String, arcs.sdk.EntitySpec<out arcs.sdk.Entity>> = emptyMap() init { arcs.core.data.SchemaRegistry.register(SCHEMA) } override fun deserialize(data: arcs.core.data.RawEntity) = Gold_QCollection().apply { deserialize(data, nestedEntitySpecs) } } } class Handles : arcs.sdk.HandleHolderBase( "Gold", mapOf( "data" to setOf(Gold_Data), "allPeople" to setOf(Gold_AllPeople), "qCollection" to setOf(Gold_QCollection), "alias" to setOf(Gold_Alias), "collection" to setOf(Foo) ) ) { val data: arcs.sdk.ReadSingletonHandle<Gold_Data> by handles val allPeople: arcs.sdk.ReadCollectionHandle<Gold_AllPeople> by handles val qCollection: arcs.sdk.ReadQueryCollectionHandle<Gold_QCollection, String> by handles val alias: arcs.sdk.WriteSingletonHandle<Gold_Alias_Slice> by handles val collection: arcs.sdk.ReadCollectionHandle<Foo> by handles } }
bsd-3-clause
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/syntax/exp/TokenExp.kt
1
944
package com.bajdcc.LALR1.syntax.exp import com.bajdcc.LALR1.syntax.ISyntaxComponent import com.bajdcc.LALR1.syntax.ISyntaxComponentVisitor import com.bajdcc.util.VisitBag import com.bajdcc.util.lexer.token.TokenType /** * 文法规则(终结符) * [id] 终结符ID * [name] 终结符名称 * [type] 终结符对应的正则表达式 * [obj] 终结符对应的正则表达式解析组件(用于语义分析中的单词流解析) * @author bajdcc */ class TokenExp(var id: Int, var name: String, var type: TokenType, var obj: Any?) : ISyntaxComponent { override fun visit(visitor: ISyntaxComponentVisitor) { val bag = VisitBag() visitor.visitBegin(this, bag) if (bag.visitEnd) { visitor.visitEnd(this) } } override fun toString(): String { return "$id: `$name`,${type.desc},${obj?.toString() ?: "(null)"}" } }
mit
grpc/grpc-kotlin
compiler/src/main/java/io/grpc/kotlin/generator/TopLevelConstantsGenerator.kt
1
2051
package io.grpc.kotlin.generator import com.google.protobuf.Descriptors import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.asTypeName import io.grpc.MethodDescriptor import io.grpc.ServiceDescriptor import io.grpc.kotlin.generator.protoc.Declarations import io.grpc.kotlin.generator.protoc.GeneratorConfig import io.grpc.kotlin.generator.protoc.builder import io.grpc.kotlin.generator.protoc.declarations import io.grpc.kotlin.generator.protoc.methodName /** * Generates top-level properties for the service descriptor and method descriptors. */ class TopLevelConstantsGenerator(config: GeneratorConfig): ServiceCodeGenerator(config) { override fun generate(service: Descriptors.ServiceDescriptor): Declarations = declarations { addProperty( PropertySpec.builder("serviceDescriptor", ServiceDescriptor::class) .addAnnotation(JvmStatic::class) .getter( FunSpec.getterBuilder() .addStatement("return %T.getServiceDescriptor()", service.grpcClass) .build() ) .build() ) with(config) { for (method in service.methods) { addProperty( PropertySpec .builder( method.methodName.toMemberSimpleName().withSuffix("Method"), MethodDescriptor::class.asTypeName().parameterizedBy( method.inputType.messageClass(), method.outputType.messageClass() ) ) .getter( FunSpec.getterBuilder() .addAnnotation(JvmStatic::class) .addStatement("return %T.%L()", service.grpcClass, method.methodName .toMemberSimpleName() .withPrefix("get") .withSuffix("Method") ) .build() ) .build() ) } } } }
apache-2.0
Hexworks/zircon
zircon.jvm.swing/src/test/kotlin/org/hexworks/zircon/internal/tileset/impl/Java2DCP437TilesetTest.kt
1
605
package org.hexworks.zircon.internal.tileset.impl import org.assertj.core.api.Assertions.assertThat import org.hexworks.zircon.api.CP437TilesetResources import org.hexworks.zircon.api.SwingApplications import org.junit.Ignore import org.junit.Test @Ignore class Java2DCP437TilesetTest { val target = SwingApplications.createTilesetLoader().loadTilesetFrom(CP437TilesetResources.wanderlust16x16()) @Test fun shouldProperlyReportSize() { val expectedSize = 16 assertThat(target.width).isEqualTo(expectedSize) assertThat(target.height).isEqualTo(expectedSize) } }
apache-2.0
firebase/FirebaseUI-Android
lint/src/main/java/com/firebaseui/lint/FirestoreRecyclerAdapterLifecycleDetector.kt
2
4497
package com.firebaseui.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity.WARNING import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UClass import org.jetbrains.uast.UField import org.jetbrains.uast.visitor.AbstractUastVisitor import java.util.EnumSet class FirestoreRecyclerAdapterLifecycleDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UClass::class.java) override fun createUastHandler(context: JavaContext) = MissingLifecycleMethodsVisitor(context) class MissingLifecycleMethodsVisitor( private val context: JavaContext ) : UElementHandler() { private val FIRESTORE_RECYCLER_ADAPTER_TYPE = "FirestoreRecyclerAdapter" override fun visitClass(node: UClass) { val adapterReferences = node .fields .filter { FIRESTORE_RECYCLER_ADAPTER_TYPE == it.type.canonicalText } .map { AdapterReference(it) } node.accept(AdapterStartListeningMethodVisitor(adapterReferences)) node.accept(AdapterStopListeningMethodVisitor(adapterReferences)) adapterReferences.forEach { if (it.hasCalledStart && !it.hasCalledStop) { context.report( ISSUE_MISSING_LISTENING_STOP_METHOD, it.uField, context.getLocation(it.uField), "Have called .startListening() without .stopListening()." ) } else if (!it.hasCalledStart) { context.report( ISSUE_MISSING_LISTENING_START_METHOD, it.uField, context.getLocation(it.uField), "Have not called .startListening()." ) } } } } class AdapterStartListeningMethodVisitor( private val adapterReferences: List<AdapterReference> ) : AbstractUastVisitor() { private val START_LISTENING_METHOD_NAME = "startListening" override fun visitCallExpression(node: UCallExpression): Boolean = if (START_LISTENING_METHOD_NAME == node.methodName) { adapterReferences .find { it.uField.name == node.receiver?.asRenderString() } ?.let { it.hasCalledStart = true } true } else { super.visitCallExpression(node) } } class AdapterStopListeningMethodVisitor( private val adapterReferences: List<AdapterReference> ) : AbstractUastVisitor() { private val STOP_LISTENING_METHOD_NAME = "stopListening" override fun visitCallExpression(node: UCallExpression): Boolean = if (STOP_LISTENING_METHOD_NAME == node.methodName) { adapterReferences .find { it.uField.name == node.receiver?.asRenderString() } ?.let { it.hasCalledStop = true } true } else { super.visitCallExpression(node) } } companion object { val ISSUE_MISSING_LISTENING_START_METHOD = Issue.create( "FirestoreAdapterMissingStartListeningMethod", "Checks if FirestoreAdapter has called .startListening() method.", "If a class is using a FirestoreAdapter and does not call startListening it won't be " + "notified on changes.", CORRECTNESS, 10, WARNING, Implementation( FirestoreRecyclerAdapterLifecycleDetector::class.java, EnumSet.of(Scope.JAVA_FILE) ) ) val ISSUE_MISSING_LISTENING_STOP_METHOD = Issue.create( "FirestoreAdapterMissingStopListeningMethod", "Checks if FirestoreAdapter has called .stopListening() method.", "If a class is using a FirestoreAdapter and has called .startListening() but missing " + " .stopListening() might cause issues with RecyclerView data changes.", CORRECTNESS, 10, WARNING, Implementation( FirestoreRecyclerAdapterLifecycleDetector::class.java, EnumSet.of(Scope.JAVA_FILE) ) ) } } data class AdapterReference( val uField: UField, var hasCalledStart: Boolean = false, var hasCalledStop: Boolean = false )
apache-2.0
fcostaa/kotlin-rxjava-android
library/cache/src/main/kotlin/com/github/felipehjcosta/marvelapp/cache/data/ThumbnailEntity.kt
1
646
package com.github.felipehjcosta.marvelapp.cache.data import androidx.room.* @Entity( tableName = "thumbnail", indices = [Index(value = ["thumbnail_character_id"], name = "thumbnail_character_index")], foreignKeys = [ForeignKey( entity = CharacterEntity::class, parentColumns = ["id"], childColumns = ["thumbnail_character_id"] )] ) data class ThumbnailEntity( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "thumbnail_id") var id: Long = 0L, var path: String = "", var extension: String = "", @ColumnInfo(name = "thumbnail_character_id") var characterId: Long = 0L )
mit
wordpress-mobile/WordPress-Android
libs/processors/src/main/java/org/wordpress/android/processor/RemoteConfigProcessor.kt
1
4421
package org.wordpress.android.processor import com.google.auto.service.AutoService import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.asTypeName import org.wordpress.android.annotation.Experiment import org.wordpress.android.annotation.Feature import org.wordpress.android.annotation.FeatureInDevelopment import java.io.File import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.annotation.processing.SupportedAnnotationTypes import javax.annotation.processing.SupportedSourceVersion import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import javax.tools.Diagnostic.Kind @AutoService(Processor::class) // For registering the service @SupportedSourceVersion(SourceVersion.RELEASE_8) // to support Java 8 @SupportedAnnotationTypes( "org.wordpress.android.annotation.Experiment", "org.wordpress.android.annotation.Feature", "org.wordpress.android.annotation.FeatureInDevelopment" ) class RemoteConfigProcessor : AbstractProcessor() { @Suppress("DEPRECATION") override fun process(p0: MutableSet<out TypeElement>?, roundEnvironment: RoundEnvironment?): Boolean { val experiments = roundEnvironment?.getElementsAnnotatedWith(Experiment::class.java)?.map { element -> val annotation = element.getAnnotation(Experiment::class.java) annotation.remoteField to annotation.defaultVariant } ?: listOf() val remoteFeatureNames = mutableListOf<TypeName>() val features = roundEnvironment?.getElementsAnnotatedWith(Feature::class.java)?.map { element -> val annotation = element.getAnnotation(Feature::class.java) remoteFeatureNames.add(element.asType().asTypeName()) annotation.remoteField to annotation.defaultValue.toString() } ?: listOf() val featuresInDevelopment = roundEnvironment?.getElementsAnnotatedWith(FeatureInDevelopment::class.java) ?.map { element -> element.asType().toString() } ?: listOf() return if (experiments.isNotEmpty() || features.isNotEmpty()) { generateRemoteConfigDefaults((experiments + features).toMap()) generateRemoteConfigCheck(remoteFeatureNames) generateFeaturesInDevelopment(featuresInDevelopment) true } else { false } } @Suppress("TooGenericExceptionCaught", "SwallowedException") private fun generateRemoteConfigDefaults( remoteConfigDefaults: Map<String, String> ) { try { val fileContent = RemoteConfigDefaultsBuilder(remoteConfigDefaults).getContent() val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] fileContent.writeTo(File(kaptKotlinGeneratedDir)) } catch (e: Exception) { processingEnv.messager.printMessage(Kind.ERROR, "Failed to generate remote config defaults") } } @Suppress("TooGenericExceptionCaught") private fun generateRemoteConfigCheck( remoteFeatureNames: List<TypeName> ) { try { val fileContent = RemoteConfigCheckBuilder(remoteFeatureNames).getContent() val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] fileContent.writeTo(File(kaptKotlinGeneratedDir)) } catch (e: Exception) { processingEnv.messager.printMessage( Kind.ERROR, "Failed to generate remote config check: $e" ) } } @Suppress("TooGenericExceptionCaught") private fun generateFeaturesInDevelopment( remoteFeatureNames: List<String> ) { try { val fileContent = FeaturesInDevelopmentDefaultsBuilder(remoteFeatureNames).getContent() val kaptKotlinGeneratedDir = processingEnv.options[KAPT_KOTLIN_GENERATED_OPTION_NAME] fileContent.writeTo(File(kaptKotlinGeneratedDir)) } catch (e: Exception) { processingEnv.messager.printMessage( Kind.ERROR, "Failed to generate remote config check: $e" ) } } companion object { const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated" } }
gpl-2.0
wordpress-mobile/WordPress-Android
WordPress/src/test/java/org/wordpress/android/sharedlogin/WordPressPublicDataTest.kt
1
3187
package org.wordpress.android.sharedlogin import android.content.pm.PackageInfo import org.assertj.core.api.Assertions import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.wordpress.android.util.publicdata.PackageManagerWrapper import org.wordpress.android.util.publicdata.WordPressPublicData class WordPressPublicDataTest { private val packageManagerWrapper: PackageManagerWrapper = mock() private val classToTest = WordPressPublicData(packageManagerWrapper) @Test fun `Should return correct current package ID`() { val actual = classToTest.currentPackageId() val expected = "org.wordpress.android" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Should return correct current package version`() { mockVersion("21.2-rc-3") val actual = classToTest.currentPackageVersion() val expected = "21.2-rc-3" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Versions without semantic information should be equal to the non semantic version`() { mockVersion("21.2") val actual = classToTest.nonSemanticPackageVersion() val expected = "21.2" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Release candidate versions should be stripped from the non semantic version`() { mockVersion("21.2-rc-3") val actual = classToTest.nonSemanticPackageVersion() val expected = "21.2" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Alpha versions should be stripped from the non semantic version`() { mockVersion("21.2-alpha-3") val actual = classToTest.nonSemanticPackageVersion() val expected = "21.2" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Invalid versions should return a null non semantic version`() { mockVersion("21.a2...-rc2") val actual = classToTest.nonSemanticPackageVersion() val expected = null Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Empty versions should return a null non semantic version`() { mockVersion("") val actual = classToTest.nonSemanticPackageVersion() val expected = null Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `Only the major-minor version information is returned`() { mockVersion("21.3.1") val actual = classToTest.nonSemanticPackageVersion() val expected = "21.3" Assertions.assertThat(actual).isEqualTo(expected) } @Test fun `When only the major is provided a null non semantic version is returned`() { mockVersion("21") val actual = classToTest.nonSemanticPackageVersion() val expected = null Assertions.assertThat(actual).isEqualTo(expected) } private fun mockVersion(version: String) { val packageInfo = PackageInfo().apply { versionName = version } whenever(packageManagerWrapper.getPackageInfo(any(), any())).thenReturn(packageInfo) } }
gpl-2.0
DiUS/pact-jvm
core/model/src/main/kotlin/au/com/dius/pact/core/model/BaseRequest.kt
1
2450
package au.com.dius.pact.core.model import au.com.dius.pact.core.support.Json import au.com.dius.pact.core.support.json.JsonValue import java.io.ByteArrayOutputStream import javax.mail.internet.InternetHeaders import javax.mail.internet.MimeBodyPart import javax.mail.internet.MimeMultipart abstract class BaseRequest : HttpPart() { /** * Sets up the request as a multipart file upload * @param partName The attribute name in the multipart upload that the file is included in * @param contentType The content type of the file data * @param contents File contents */ fun withMultipartFileUpload(partName: String, filename: String, contentType: ContentType, contents: String) = withMultipartFileUpload(partName, filename, contentType.toString(), contents) /** * Sets up the request as a multipart file upload * @param partName The attribute name in the multipart upload that the file is included in * @param contentType The content type of the file data * @param contents File contents */ fun withMultipartFileUpload(partName: String, filename: String, contentType: String, contents: String): BaseRequest { val multipart = MimeMultipart("form-data") val internetHeaders = InternetHeaders() internetHeaders.setHeader("Content-Disposition", "form-data; name=\"$partName\"; filename=\"$filename\"") internetHeaders.setHeader("Content-Type", contentType) multipart.addBodyPart(MimeBodyPart(internetHeaders, contents.toByteArray())) val stream = ByteArrayOutputStream() multipart.writeTo(stream) body = OptionalBody.body(stream.toByteArray(), ContentType(contentType)) headers["Content-Type"] = listOf(multipart.contentType) return this } /** * If this request represents a multipart file upload */ fun isMultipartFileUpload() = contentType().equals("multipart/form-data", ignoreCase = true) companion object { fun parseQueryParametersToMap(query: JsonValue?): Map<String, List<String>> { return when (query) { null -> emptyMap() is JsonValue.Object -> query.entries.entries.associate { entry -> val list = when (entry.value) { is JsonValue.Array -> entry.value.asArray().values.map { Json.toString(it) } else -> emptyList() } entry.key to list } is JsonValue.StringValue -> queryStringToMap(query.asString()) else -> emptyMap() } } } }
apache-2.0
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/quickfix/modifiers/illegalEnumAnnotation1.kt
8
64
// "Remove 'enum' modifier" "true" <caret>enum interface A { }
apache-2.0
mdaniel/intellij-community
plugins/kotlin/completion/tests/testData/smart/functionLiterals/OutsideCallParenthesis7.kt
13
215
fun foo(optional: Int = 0, handler: (String, Char) -> Unit){} fun bar(handler: (String, Char) -> Unit) { foo() <caret> } // EXIST: "{ s, c -> ... }" // EXIST: "{ s: String, c: Char -> ... }" // ABSENT: handler
apache-2.0
ingokegel/intellij-community
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/runner/TestContextInitializedEvent.kt
2
307
package com.intellij.ide.starter.runner import com.intellij.ide.starter.bus.Event import com.intellij.ide.starter.bus.EventState import com.intellij.ide.starter.ide.IDETestContext class TestContextInitializedEvent(state: EventState, testContext: IDETestContext) : Event<IDETestContext>(state, testContext)
apache-2.0
byu-oit-appdev/android-byu-suite-v2
app/src/main/java/edu/byu/suite/features/myFinancialCenter/controller/MfcPaymentAccountsActivity.kt
1
1374
package edu.byu.suite.features.myFinancialCenter.controller import android.content.Intent import edu.byu.suite.features.myFinancialCenter.service.MfcClient import edu.byu.support.payment.controller.PaymentAccountsActivity import edu.byu.support.payment.controller.PaymentReviewActivity import edu.byu.support.payment.model.PaymentAccount import retrofit2.Response /** * Created by geogor37 on 2/16/18 */ class MfcPaymentAccountsActivity: PaymentAccountsActivity() { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == UnpaidChargesFragment.CHECKOUT_REQUEST) { setResult(resultCode) finish() } super.onActivityResult(requestCode, resultCode, data) } override fun loadPaymentMethods() { enqueueCall(MfcClient().getApi(this).getPaymentTypes(), object: PaymentAccountsCallback<List<PaymentAccount>>(this, pathToReadableError = MfcClient.PATH_TO_READABLE_ERROR) { override fun parseResponse(response: Response<List<PaymentAccount>>?): List<PaymentAccount>? { return response?.body() } }) } override fun continuePaymentProcess(selectedPaymentAccount: PaymentAccount) { startActivityForResult(Intent(this, MfcPaymentReviewActivity::class.java) .putExtra(PaymentReviewActivity.PAYMENT_ACCOUNT_TAG, selectedPaymentAccount) .putExtras(intent), UnpaidChargesFragment.CHECKOUT_REQUEST) } }
apache-2.0
ingokegel/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/writer/apiCode.kt
1
5235
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.codegen import com.intellij.workspaceModel.codegen.classes.* import com.intellij.workspaceModel.codegen.deft.meta.ObjClass import com.intellij.workspaceModel.codegen.deft.meta.ObjProperty import com.intellij.workspaceModel.codegen.deft.meta.OwnProperty import com.intellij.workspaceModel.codegen.deft.meta.ValueType import com.intellij.workspaceModel.codegen.fields.javaMutableType import com.intellij.workspaceModel.codegen.fields.javaType import com.intellij.workspaceModel.codegen.fields.wsCode import com.intellij.workspaceModel.codegen.utils.fqn import com.intellij.workspaceModel.codegen.utils.fqn7 import com.intellij.workspaceModel.codegen.utils.lines import com.intellij.workspaceModel.codegen.writer.allFields import com.intellij.workspaceModel.codegen.writer.isStandardInterface import com.intellij.workspaceModel.codegen.writer.javaName import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceSet import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type val SKIPPED_TYPES: Set<String> = setOfNotNull(WorkspaceEntity::class.simpleName, ReferableWorkspaceEntity::class.simpleName, ModifiableWorkspaceEntity::class.simpleName, ModifiableReferableWorkspaceEntity::class.simpleName, WorkspaceEntityWithPersistentId::class.simpleName) fun ObjClass<*>.generateBuilderCode(): String = lines { line("@${GeneratedCodeApiVersion::class.fqn}(${CodeGeneratorVersions.API_VERSION})") val (typeParameter, typeDeclaration) = if (openness.extendable) "T" to "<T: $javaFullName>" else javaFullName to "" val superBuilders = superTypes.filterIsInstance<ObjClass<*>>().filter { !it.isStandardInterface }.joinToString { ", ${it.name}.Builder<$typeParameter>" } val header = "interface Builder$typeDeclaration: $javaFullName$superBuilders, ${ModifiableWorkspaceEntity::class.fqn}<$typeParameter>, ${ObjBuilder::class.fqn}<$typeParameter>" section(header) { list(allFields.noPersistentId()) { wsBuilderApi } } } fun ObjClass<*>.generateCompanionObject(): String = lines { val builderGeneric = if (openness.extendable) "<$javaFullName>" else "" val companionObjectHeader = buildString { append("companion object: ${Type::class.fqn}<$javaFullName, Builder$builderGeneric>(") val base = superTypes.filterIsInstance<ObjClass<*>>().firstOrNull() if (base != null && base.name !in SKIPPED_TYPES) append(base.javaFullName) append(")") } val mandatoryFields = allFields.mandatoryFields() if (mandatoryFields.isNotEmpty()) { val fields = mandatoryFields.joinToString { "${it.name}: ${it.valueType.javaType}" } section(companionObjectHeader) { section("operator fun invoke($fields, init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") list(mandatoryFields) { if (this.valueType is ValueType.Set<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceSet)}()" } else if (this.valueType is ValueType.List<*> && !this.valueType.isRefType()) { "builder.$name = $name.${fqn7(Collection<*>::toMutableWorkspaceList)}()" } else { "builder.$name = $name" } } line("init?.invoke(builder)") line("return builder") } } } else { section(companionObjectHeader) { section("operator fun invoke(init: (Builder$builderGeneric.() -> Unit)? = null): $javaFullName") { line("val builder = builder()") line("init?.invoke(builder)") line("return builder") } } } } fun List<OwnProperty<*, *>>.mandatoryFields(): List<ObjProperty<*, *>> { var fields = this.noRefs().noOptional().noPersistentId().noDefaultValue() if (fields.isNotEmpty()) { fields = fields.noEntitySource() + fields.single { it.name == "entitySource" } } return fields } fun ObjClass<*>.generateExtensionCode(): String? { val fields = module.extensions.filter { it.receiver == this || it.receiver.module != module && it.valueType.isRefType() && it.valueType.getRefType().target == this } if (openness.extendable && fields.isEmpty()) return null return lines { if (!openness.extendable) { line("fun ${MutableEntityStorage::class.fqn}.modifyEntity(entity: $name, modification: $name.Builder.() -> Unit) = modifyEntity($name.Builder::class.java, entity, modification)") } fields.sortedWith(compareBy({ it.receiver.name }, { it.name })).forEach { line(it.wsCode) } } } val ObjProperty<*, *>.wsBuilderApi: String get() { val returnType = if (valueType is ValueType.Collection<*, *> && !valueType.isRefType()) valueType.javaMutableType else valueType.javaType return "override var $javaName: $returnType" }
apache-2.0
hermantai/samples
android/AndroidProgramming3e-master/02_MVC/kotlin/GeoQuiz/app/src/main/java/com/bignerdranch/android/geoquiz/Question.kt
2
110
package com.bignerdranch.android.geoquiz data class Question(val textResId : Int, val isAnswerTrue : Boolean)
apache-2.0
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/store/avatar/usecase/BuyAvatarUseCase.kt
1
1167
package io.ipoli.android.store.avatar.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.player.data.Avatar import io.ipoli.android.player.data.Player import io.ipoli.android.player.persistence.PlayerRepository /** * Created by Venelin Valkov <[email protected]> * on 03/25/2018. */ class BuyAvatarUseCase(private val playerRepository: PlayerRepository) : UseCase<BuyAvatarUseCase.Params, BuyAvatarUseCase.Result> { override fun execute(parameters: Params): Result { val player = playerRepository.find() requireNotNull(player) val avatar = parameters.avatar require(!player!!.inventory.hasAvatar(avatar)) if (player.gems < avatar.gemPrice) { return Result.TooExpensive } val newPlayer = player.copy( gems = player.gems - avatar.gemPrice, inventory = player.inventory.addAvatar(avatar) ) return Result.Bought(playerRepository.save(newPlayer)) } data class Params(val avatar: Avatar) sealed class Result { data class Bought(val player: Player) : Result() object TooExpensive : Result() } }
gpl-3.0
nonylene/MackerelAgentAndroid
app/src/main/java/net/nonylene/mackerelagent/utils/CronUtils.kt
1
980
package net.nonylene.mackerelagent.utils import android.app.ActivityManager import android.content.Context import android.content.Intent import net.nonylene.mackerelagent.service.GatherMetricsService fun startGatherMetricsService(context: Context) { context.startService(createGatherMetricsServiceIntent(context)) realmLog("Starting monitoring service", false) } fun stopGatherMetricsService(context: Context) { context.stopService(createGatherMetricsServiceIntent(context)) realmLog("Stopping monitoring service", false) } fun createGatherMetricsServiceIntent(context: Context): Intent { return Intent(context, GatherMetricsService::class.java) } fun isGatherMetricsServiceRunning(context: Context): Boolean { val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager return manager.getRunningServices(Integer.MAX_VALUE).any { service -> GatherMetricsService::class.java.name == service.service.className } }
mit
GunoH/intellij-community
plugins/kotlin/completion/testData/basic/common/extensionMethodInObject/InheritedExtensionGenericType.kt
3
610
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. open class A { fun <T> T.fooExtension() {} val <T> T.fooProperty get() = 10 } object AOBject : A() class B fun usage(arg: B) { arg.foo<caret> } // EXIST: { lookupString: "fooExtension", itemText: "fooExtension", icon: "Function"} // EXIST: { lookupString: "fooProperty", itemText: "fooProperty", icon: "org/jetbrains/kotlin/idea/icons/field_value.svg"}
apache-2.0
GunoH/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/annotations/AllGradleVersionsSource.kt
7
732
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.gradle.testFramework.annotations import org.jetbrains.plugins.gradle.testFramework.annotations.processors.AllGradleVersionArgumentsProcessor import org.junit.jupiter.params.provider.ArgumentsSource /** * Alias for [GradleTestSource] where [GradleTestSource.value] are predefined with * [org.jetbrains.plugins.gradle.tooling.VersionMatcherRule.SUPPORTED_GRADLE_VERSIONS]. */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION) @ArgumentsSource(AllGradleVersionArgumentsProcessor::class) annotation class AllGradleVersionsSource(vararg val value: String)
apache-2.0