repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Undin/intellij-rust
src/test/kotlin/org/rust/ide/hints/parameter/RsParameterInfoHandlerTest.kt
2
6354
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.hints.parameter import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor import org.rust.lang.core.psi.RsValueArgumentList /** * Tests for RustParameterInfoHandler */ class RsParameterInfoHandlerTest : RsParameterInfoHandlerTestBase<RsValueArgumentList, RsArgumentsDescription>(RsParameterInfoHandler()) { fun `test fn no args`() = checkByText(""" fn foo() {} fn main() { foo(<caret>); } """, "<no arguments>", 0) fun `test fn no args before args`() = checkByText(""" fn foo() {} fn main() { foo<caret>(); } """, "<no arguments>", -1) fun `test fn one arg`() = checkByText(""" fn foo(arg: u32) {} fn main() { foo(<caret>); } """, "arg: u32", 0) fun `test tuple struct one arg`() = checkByText(""" struct Foo(u32); fn main() { Foo(<caret>); } """, "u32", 0) fun `test enum one arg`() = checkByText(""" enum E { Foo(u32) } fn main() { E::Foo(<caret>); } """, "u32", 0) fun `test fn one arg end`() = checkByText(""" fn foo(arg: u32) {} fn main() { foo(42<caret>); } """, "arg: u32", 0) fun `test fn many args`() = checkByText(""" fn foo(id: u32, name: &'static str, mut year: &u16) {} fn main() { foo(<caret>); } """, "id: u32, name: &'static str, year: &u16", 0) fun `test fn poorly formatted args`() = checkByText(""" fn foo( id : u32 , name: &'static str , mut year : &u16 ) {} fn main() { foo(<caret>); } """, "id: u32, name: &'static str, year: &u16", 0) fun `test fn arg index0`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(a1<caret>); } """, "a1: u32, a2: u32", 0) fun `test fn arg index0 with comma`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(a1<caret>,); } """, "a1: u32, a2: u32", 0) fun `test fn arg index1`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(16,<caret>); } """, "a1: u32, a2: u32", 1) fun `test fn arg index1 value start`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(12, <caret>32); } """, "a1: u32, a2: u32", 1) fun `test fn arg index1 value end`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(5, 32<caret>); } """, "a1: u32, a2: u32", 1) fun `test fn arg too many args`() = checkByText(""" fn foo(a1: u32, a2: u32) {} fn main() { foo(0, 32,<caret>); } """, "a1: u32, a2: u32", 2) @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test fn closure`() = checkByText(""" fn foo(fun: &dyn Fn(u32) -> u32) {} fn main() { foo(|x| x + <caret>); } """, "fun: &dyn Fn(u32) -> u32", 0) fun `test fn nested inner`() = checkByText(""" fn add(v1: u32, v2: u32) -> u32 { v1 + v2 } fn display(v: u32, format: &'static str) {} fn main() { display(add(4, <caret>), "0.00"); } """, "v1: u32, v2: u32", 1) fun `test fn nested outer`() = checkByText(""" fn add(v1: u32, v2: u32) -> u32 { v1 + v2 } fn display(v: u32, indent: bool, format: &'static str) {} fn main() { display(add(4, 7), false, <caret>"); } """, "v: u32, indent: bool, format: &'static str", 2) fun `test multiline`() = checkByText(""" fn sum(v1: u32, v2: u32, v3: u32) -> u32 { v1 + v2 + v3 } fn main() { sum( 10, <caret> ); } """, "v1: u32, v2: u32, v3: u32", 1) fun `test assoc fn`() = checkByText(""" struct Foo; impl Foo { fn new(id: u32, val: f64) {} } fn main() { Foo::new(10, <caret>); } """, "id: u32, val: f64", 1) fun `test method`() = checkByText(""" struct Foo; impl Foo { fn bar(&self, id: u32, name: &'static str, year: u16) {} } fn main() { let foo = Foo{}; foo.bar(10, "Bo<caret>b", 1987); } """, "id: u32, name: &'static str, year: u16", 1) fun `test trait method`() = checkByText(""" trait Named { fn greet(&self, text: &'static str, count: u16, l: f64); } struct Person; impl Named for Person { fn greet(&self, text: &'static str, count: u16, l: f64) {} } fn main() { let p = Person {}; p.greet("Hello", 19, 10.21<caret>); } """, "text: &'static str, count: u16, l: f64", 2) fun `test method with explicit self`() = checkByText(""" struct S; impl S { fn foo(self, arg: u32) {} } fn main() { let s = S; S::foo(s, 0<caret>); } """, "self, arg: u32", 1) fun `test not args 1`() = checkByText(""" fn foo() {} fn main() { fo<caret>o(); } """, "", -1) fun `test not args 2`() = checkByText(""" fn foo() {} fn main() { foo()<caret>; } """, "", -1) fun `test not applied within declaration`() = checkByText(""" fn foo(v<caret>: u32) {} """, "", -1) fun `test generic function parameter`() = checkByText(""" fn foo<T1>(x: T1) {} fn main() { foo::<i32>(/*caret*/); } """, "x: i32", 0) fun `test generic method parameter`() = checkByText(""" struct S<T1>(); impl <T2> S<T2> { fn foo(&self, x: T2) -> T2 { x } } fn main() { let s = S::<i32>(); s.foo(/*caret*/); } """, "x: i32", 0) fun `test generic parameter unknown type`() = checkByText(""" fn foo<T1>(x: T1) {} fn main() { foo::<S>(/*caret*/); } """, "x: T1", 0) fun `test generic parameter with lifetime`() = checkByText(""" fn foo<'a, T1>(x: &'a T1) {} fn main() { let a = 5; foo(&a/*caret*/); } """, "x: &'a i32", 0) fun `test closure`() = checkByText(""" fn main() { let foo = |a: usize, b| { a + b }; foo(0/*caret*/, 1); } """, "a: usize, b: i32", 0) }
mit
3e25f6a4be3b160b173a07bd4741e25e
28.691589
109
0.469783
3.282025
false
true
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/activity/ServerRowAdapter.kt
1
6959
package org.moire.ultrasonic.activity import android.content.Context import android.graphics.Color import android.os.Build import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageButton import android.widget.ImageView import android.widget.PopupMenu import android.widget.RelativeLayout import android.widget.TextView import androidx.core.content.ContextCompat import org.moire.ultrasonic.R import org.moire.ultrasonic.data.ActiveServerProvider import org.moire.ultrasonic.data.ServerSetting import org.moire.ultrasonic.util.Util /** * Row Adapter to be used in the Server List * Converts a Server Setting into a displayable Row, and sets up the Row's context menu * @param manageMode: set to True if the default action by clicking the row is to edit the server * In Manage Mode the "Offline" setting is not visible, and the servers can be edited by * clicking the row. */ internal class ServerRowAdapter( private var context: Context, private var data: Array<ServerSetting>, private val model: ServerSettingsModel, private val activeServerProvider: ActiveServerProvider, private val manageMode: Boolean, private val serverDeletedCallback: ((Int) -> Unit), private val serverEditRequestedCallback: ((Int) -> Unit) ) : BaseAdapter() { companion object { private const val MENU_ID_EDIT = 1 private const val MENU_ID_DELETE = 2 private const val MENU_ID_UP = 3 private const val MENU_ID_DOWN = 4 } var inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater fun setData(data: Array<ServerSetting>) { this.data = data notifyDataSetChanged() } override fun getCount(): Int { return if (manageMode) data.size else data.size + 1 } override fun getItem(position: Int): Any { return data[position] } override fun getItemId(position: Int): Long { return position.toLong() } /** * Creates the Row representation of a Server Setting */ override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var index = position // Skip "Offline" in manage mode if (manageMode) index++ var vi: View? = convertView if (vi == null) vi = inflater.inflate(R.layout.server_row, parent, false) val text = vi?.findViewById<TextView>(R.id.server_name) val description = vi?.findViewById<TextView>(R.id.server_description) val layout = vi?.findViewById<RelativeLayout>(R.id.server_layout) val image = vi?.findViewById<ImageView>(R.id.server_image) val serverMenu = vi?.findViewById<ImageButton>(R.id.server_menu) if (index == 0) { text?.text = context.getString(R.string.main_offline) description?.text = "" } else { val setting = data.singleOrNull { t -> t.index == index } text?.text = setting?.name ?: "" description?.text = setting?.url ?: "" if (setting == null) serverMenu?.visibility = View.INVISIBLE } // Provide icons for the row if (index == 0) { serverMenu?.visibility = View.INVISIBLE image?.setImageDrawable(Util.getDrawableFromAttribute(context, R.attr.screen_on_off)) } else { image?.setImageDrawable(Util.getDrawableFromAttribute(context, R.attr.server)) } // Highlight the Active Server's row by changing its background if (index == activeServerProvider.getActiveServer().index) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { layout?.background = ContextCompat.getDrawable(context, R.drawable.select_ripple) } else { layout?.setBackgroundResource( Util.getResourceFromAttribute(context, R.attr.list_selector_holo_selected) ) } } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { layout?.background = ContextCompat.getDrawable(context, R.drawable.default_ripple) } else { layout?.setBackgroundResource( Util.getResourceFromAttribute(context, R.attr.list_selector_holo) ) } } // Add the context menu for the row if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { serverMenu?.background = ContextCompat.getDrawable( context, R.drawable.select_ripple_circle ) } else { serverMenu?.setBackgroundColor(Color.TRANSPARENT) } serverMenu?.setOnClickListener { view -> serverMenuClick(view, index) } return vi } /** * Builds the Context Menu of a row when the "more" icon is clicked */ private fun serverMenuClick(view: View, position: Int) { val menu = PopupMenu(context, view) val firstServer = 1 var lastServer = count - 1 if (!manageMode) { menu.menu.add( Menu.NONE, MENU_ID_EDIT, Menu.NONE, context.getString(R.string.server_menu_edit) ) } else { lastServer++ } menu.menu.add( Menu.NONE, MENU_ID_DELETE, Menu.NONE, context.getString(R.string.server_menu_delete) ) if (position != firstServer) { menu.menu.add( Menu.NONE, MENU_ID_UP, Menu.NONE, context.getString(R.string.server_menu_move_up) ) } if (position != lastServer) { menu.menu.add( Menu.NONE, MENU_ID_DOWN, Menu.NONE, context.getString(R.string.server_menu_move_down) ) } menu.show() menu.setOnMenuItemClickListener { menuItem -> popupMenuItemClick(menuItem, position) } } /** * Handles the click on a context menu item */ private fun popupMenuItemClick(menuItem: MenuItem, position: Int): Boolean { when (menuItem.itemId) { MENU_ID_EDIT -> { serverEditRequestedCallback.invoke(position) return true } MENU_ID_DELETE -> { serverDeletedCallback.invoke(position) return true } MENU_ID_UP -> { model.moveItemUp(position) return true } MENU_ID_DOWN -> { model.moveItemDown(position) return true } else -> return false } } }
gpl-3.0
dffda8ff3d316995f573217814d41d30
32.296651
98
0.59908
4.575279
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/ui/overview/CardsRepository.kt
1
3623
package de.tum.`in`.tumcampusapp.component.ui.overview import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.content.Context import com.crashlytics.android.Crashlytics import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.TuitionFeeManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.controller.CafeteriaManager import de.tum.`in`.tumcampusapp.component.ui.chat.ChatRoomController import de.tum.`in`.tumcampusapp.component.ui.eduroam.EduroamCard import de.tum.`in`.tumcampusapp.component.ui.eduroam.EduroamFixCard import de.tum.`in`.tumcampusapp.component.ui.news.NewsController import de.tum.`in`.tumcampusapp.component.ui.news.TopNewsCard import de.tum.`in`.tumcampusapp.component.ui.onboarding.LoginPromptCard import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card import de.tum.`in`.tumcampusapp.component.ui.overview.card.ProvidesCard import de.tum.`in`.tumcampusapp.component.ui.ticket.EventsController import de.tum.`in`.tumcampusapp.component.ui.transportation.TransportController import de.tum.`in`.tumcampusapp.utils.Utils import org.jetbrains.anko.doAsync class CardsRepository(private val context: Context) { private var cards = MutableLiveData<List<Card>>() /** * Starts refresh of [Card]s and returns the corresponding [LiveData] * through which the result can be received. * * @return The [LiveData] of [Card]s */ fun getCards(): LiveData<List<Card>> { refreshCards(CacheControl.USE_CACHE) return cards } /** * Refreshes the [LiveData] of [Card]s and updates its value. */ fun refreshCards(cacheControl: CacheControl) { doAsync { val results = getCardsNow(cacheControl) cards.postValue(results) } } /** * Returns the list of [Card]s synchronously. * * @return The list of [Card]s */ private fun getCardsNow(cacheControl: CacheControl): List<Card> { val results = ArrayList<Card?>().apply { add(NoInternetCard(context).getIfShowOnStart()) add(TopNewsCard(context).getIfShowOnStart()) add(LoginPromptCard(context).getIfShowOnStart()) add(SupportCard(context).getIfShowOnStart()) add(EduroamCard(context).getIfShowOnStart()) add(EduroamFixCard(context).getIfShowOnStart()) } val providers = ArrayList<ProvidesCard>().apply { if (AccessTokenManager.hasValidAccessToken(context)) { add(CalendarController(context)) add(TuitionFeeManager(context)) add(ChatRoomController(context)) } add(CafeteriaManager(context)) add(TransportController(context)) add(NewsController(context)) add(EventsController(context)) } providers.forEach { provider -> // Don't prevent a single card exception to block other cards from being displayed. try { val cards = provider.getCards(cacheControl) results.addAll(cards) } catch (e: Exception) { // We still want to know about it though Utils.log(e) Crashlytics.logException(e) } } results.add(RestoreCard(context).getIfShowOnStart()) return results.filterNotNull() } }
gpl-3.0
fcc611d77f86744e93d86c6ff853a9e3
37.147368
95
0.682307
4.318236
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/util/views/CircularProgressMaterialButton.kt
1
5115
package org.thoughtcrime.securesms.util.views import android.animation.Animator import android.content.Context import android.os.Build import android.os.Bundle import android.os.Parcelable import android.util.AttributeSet import android.view.ViewAnimationUtils import android.widget.FrameLayout import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import androidx.core.animation.doOnEnd import androidx.core.content.withStyledAttributes import com.google.android.material.button.MaterialButton import com.google.android.material.progressindicator.CircularProgressIndicator import com.google.android.material.theme.overlay.MaterialThemeOverlay import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.util.visible import kotlin.math.max /** * Drop-In replacement for CircularProgressButton that better supports material design. */ class CircularProgressMaterialButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : FrameLayout(MaterialThemeOverlay.wrap(context, attrs, 0, 0), attrs, 0) { init { inflate(getContext(), R.layout.circular_progress_material_button, this) } private var currentState: State = State.BUTTON private var requestedState: State = State.BUTTON private var animator: Animator? = null private val materialButton: MaterialButton = findViewById(R.id.button) private val progressIndicator: CircularProgressIndicator = findViewById(R.id.progress_indicator) var text: CharSequence? get() = materialButton.text set(value) { materialButton.text = value } init { getContext().withStyledAttributes(attrs, R.styleable.CircularProgressMaterialButton) { val label = getString(R.styleable.CircularProgressMaterialButton_circularProgressMaterialButton__label) materialButton.text = label } } fun setText(@StringRes resId: Int) { materialButton.setText(resId) } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) materialButton.isEnabled = enabled progressIndicator.visible = enabled } override fun setClickable(clickable: Boolean) { super.setClickable(clickable) materialButton.isClickable = clickable progressIndicator.visible = clickable } override fun onSaveInstanceState(): Parcelable { return Bundle().apply { putParcelable(SUPER_STATE, super.onSaveInstanceState()) putInt(STATE, if (requestedState != currentState) requestedState.code else currentState.code) } } override fun onRestoreInstanceState(state: Parcelable) { val stateBundle = state as Bundle val superState: Parcelable? = stateBundle.getParcelable(SUPER_STATE) super.onRestoreInstanceState(superState) currentState = if (materialButton.visibility == INVISIBLE) State.PROGRESS else State.BUTTON requestedState = State.fromCode(stateBundle.getInt(STATE)) ensureRequestedState(false) } override fun setOnClickListener(onClickListener: OnClickListener?) { materialButton.setOnClickListener(onClickListener) } @VisibleForTesting fun getRequestedState(): State { return requestedState } fun setSpinning() { transformTo(State.PROGRESS, true) } fun cancelSpinning() { transformTo(State.BUTTON, true) } private fun transformTo(state: State, animate: Boolean) { if (!isAttachedToWindow) { return } if (state == currentState && state == requestedState) { return } requestedState = state if (animator?.isRunning == true) { return } if (!animate || Build.VERSION.SDK_INT < 21) { materialButton.visibility = state.materialButtonVisibility currentState = state return } currentState = state if (state == State.BUTTON) { materialButton.visibility = VISIBLE } val buttonShrunkRadius = 0f val buttonExpandedRadius = max(measuredWidth, measuredHeight).toFloat() animator = ViewAnimationUtils.createCircularReveal( materialButton, materialButton.measuredWidth / 2, materialButton.measuredHeight / 2, if (state == State.BUTTON) buttonShrunkRadius else buttonExpandedRadius, if (state == State.PROGRESS) buttonShrunkRadius else buttonExpandedRadius ).apply { duration = ANIMATION_DURATION doOnEnd { materialButton.visibility = state.materialButtonVisibility ensureRequestedState(true) } start() } } private fun ensureRequestedState(animate: Boolean) { if (requestedState == currentState || !isAttachedToWindow) { return } transformTo(requestedState, animate) } enum class State(val code: Int, val materialButtonVisibility: Int) { BUTTON(0, VISIBLE), PROGRESS(1, INVISIBLE); companion object { fun fromCode(code: Int): State { return when (code) { 0 -> BUTTON 1 -> PROGRESS else -> error("Unexpected code $code") } } } } companion object { private val ANIMATION_DURATION = 300L private val SUPER_STATE = "super_state" private val STATE = "state" } }
gpl-3.0
044b54bcc7037a2a27d7e1faa1c7d551
27.735955
109
0.727273
4.718635
false
false
false
false
androidx/androidx
slice/slice-builders-ktx/src/androidTest/java/androidx/slice/builders/SliceBuildersKtxTest.kt
3
8519
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.slice.builders import android.app.PendingIntent import android.app.PendingIntent.FLAG_IMMUTABLE import android.content.Intent import android.net.Uri import androidx.core.graphics.drawable.IconCompat import androidx.slice.SliceProvider import androidx.slice.SliceSpecs import androidx.slice.builders.ListBuilder.ICON_IMAGE import androidx.slice.builders.ktx.test.R import androidx.test.core.app.ApplicationProvider import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import org.junit.Assert.assertEquals import org.junit.Test @SdkSuppress(minSdkVersion = 19) @MediumTest class SliceBuildersKtxTest { private val testUri = Uri.parse("content://com.example.android.sliceuri") private val context = ApplicationProvider.getApplicationContext() as android.content.Context init { SliceProvider.setSpecs(setOf(SliceSpecs.LIST)) SliceProvider.setClock { 0 } } private fun pendingIntentToTestActivity() = PendingIntent.getActivity( context, 0, Intent(context, TestActivity::class.java), FLAG_IMMUTABLE ) private val accentColor = 0xff3949 private fun createIcon(id: Int) = IconCompat.createWithResource(context, id) @Test fun helloWorldSlice() { val sliceKtx = list(context = context, uri = testUri, ttl = ListBuilder.INFINITY) { header { setTitle("Hello World") } } val slice = ListBuilder(context, testUri, ListBuilder.INFINITY).setHeader( ListBuilder.HeaderBuilder().apply { setTitle("Hello World") } ).build() // Compare toString()s because Slice.equals is not implemented. assertEquals(sliceKtx.toString(), slice.toString()) } // Temporarily disabled due to b/116146018. // @Test fun allBuildersTogether() { val pendingIntent = pendingIntentToTestActivity() val tapAction = tapSliceAction( pendingIntentToTestActivity(), createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE, "Title" ) val sliceKtx = list(context = context, uri = testUri, ttl = ListBuilder.INFINITY) { header { setPrimaryAction(tapAction) } row { } gridRow { cell { } } inputRange { setInputAction(pendingIntent) } range { } } val slice = ListBuilder(context, testUri, ListBuilder.INFINITY).apply { setHeader(ListBuilder.HeaderBuilder().setPrimaryAction(tapAction)) addRow(ListBuilder.RowBuilder()) addGridRow(GridRowBuilder().addCell(GridRowBuilder.CellBuilder())) addInputRange(ListBuilder.InputRangeBuilder().setInputAction(pendingIntent)) addRange(ListBuilder.RangeBuilder()) }.build() assertEquals(slice.toString(), sliceKtx.toString()) } // Temporarily disabled due to b/116146018. // @Test fun sanity_withGridRow() { val tapAction = tapSliceAction( pendingIntentToTestActivity(), createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE, "Title" ) val toggleAction = toggleSliceAction( pendingIntentToTestActivity(), createIcon(R.drawable.ic_android_black_24dp), "Title", false ) val titleText1 = "cell title text 1" val titleText2 = "cell title text 2" val text1 = "cell text 1" val text2 = "cell text 2" val sliceKtx = list(context = context, uri = testUri, ttl = ListBuilder.INFINITY) { gridRow { setPrimaryAction(tapAction) cell { addTitleText(titleText1) addImage(createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE) addText(text1) } cell { addTitleText(titleText2) addImage(createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE) addText(text2) } } addAction(toggleAction) } val slice = ListBuilder(context, testUri, ListBuilder.INFINITY).addGridRow( GridRowBuilder().apply { setPrimaryAction(tapAction) addCell( GridRowBuilder.CellBuilder().apply { addTitleText(titleText1) addImage( createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE ) addText(text1) } ) addCell( GridRowBuilder.CellBuilder().apply { addTitleText(titleText2) addImage( createIcon(R.drawable.ic_android_black_24dp), ListBuilder.SMALL_IMAGE ) addText(text2) } ) } ).addAction(toggleAction).build() // Compare toString()s because Slice.equals is not implemented. assertEquals(sliceKtx.toString(), slice.toString()) } @Test fun sanity_withMixedGridRowAndRow() { val resIds = intArrayOf( R.drawable.ic_all_out_black_24dp, R.drawable.ic_android_black_24dp, R.drawable.ic_attach_money_black_24dp ) val pendingIntent = pendingIntentToTestActivity() val rowPrimaryAction = tapSliceAction( pendingIntent, createIcon(R.drawable.ic_android_black_24dp), ListBuilder.LARGE_IMAGE, "Droid" ) val sliceAction1 = SliceAction( pendingIntent, createIcon(R.drawable.ic_all_out_black_24dp), ListBuilder.LARGE_IMAGE, "Action1" ) val sliceAction2 = SliceAction( pendingIntent, createIcon(R.drawable.ic_all_out_black_24dp), "Action2", false ) val icons = (resIds + resIds).map { createIcon(it) } val sliceKtx = list(context = context, uri = testUri, ttl = ListBuilder.INFINITY) { setAccentColor(accentColor) row { setTitle("Title") setSubtitle("Subtitle") setPrimaryAction(rowPrimaryAction) } addAction(sliceAction1) addAction(sliceAction2) gridRow { icons.forEach { cell { addImage(it, ICON_IMAGE) } } } } val slice = ListBuilder(context, testUri, ListBuilder.INFINITY).apply { setAccentColor(accentColor) addRow( ListBuilder.RowBuilder() .setTitle("Title") .setSubtitle("Subtitle") .setPrimaryAction(rowPrimaryAction) ) addAction(sliceAction1) addAction(sliceAction2) addGridRow( GridRowBuilder().apply { icons.forEach { icon -> GridRowBuilder.CellBuilder().addImage(icon, ICON_IMAGE) addCell( GridRowBuilder.CellBuilder().apply { addImage(icon, ICON_IMAGE) } ) } } ) }.build() // Compare toString()s because Slice.equals is not implemented. assertEquals(slice.toString(), sliceKtx.toString()) } }
apache-2.0
33ae8a9b63249bb12586d5fa196c5b2d
33.771429
99
0.568494
4.976051
false
true
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/glfw/templates/GLFWNativeEGL.kt
1
1506
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.glfw.templates import org.lwjgl.generator.* import org.lwjgl.glfw.* import org.lwjgl.egl.* val GLFWNativeEGL = "GLFWNativeEGL".nativeClass(packageName = GLFW_PACKAGE, nativeSubPath = "egl", prefix = "GLFW", binding = GLFW_BINDING_DELEGATE) { javaImport( "org.lwjgl.egl.EGL10" ) documentation = "Native bindings to the GLFW library's EGL native access functions." EGLDisplay( "GetEGLDisplay", """ Returns the {@code EGLDisplay} used by GLFW. This function may be called from any thread. Access is not synchronized. """, returnDoc = "the {@code EGLDisplay} used by GLFW, or EGL10##EGL_NO_DISPLAY if an error occured", since = "version 3.0" ) EGLContext( "GetEGLContext", """ Returns the {@code EGLContext} of the specified window. This function may be called from any thread. Access is not synchronized. """, GLFWwindow.IN("window", "a GLFW window"), returnDoc = "the {@code EGLContext} of the specified window, or EGL10##EGL_NO_CONTEXT if an error occurred", since = "version 3.0" ) EGLSurface( "GetEGLSurface", """ Returns the {@code EGLSurface} of the specified window. This function may be called from any thread. Access is not synchronized. """, GLFWwindow.IN("window", ""), returnDoc = "the {@code EGLSurface} of the specified window, or EGL10##EGL_NO_SURFACE if an error occurred", since = "version 3.0" ) }
bsd-3-clause
012dcbd68cb1489cb9a55bb0a739402b
25.438596
150
0.698539
3.585714
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/mcp/gradle/McpDataService.kt
1
1609
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.mcp.McpModuleType import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.Key import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project class McpDataService : AbstractProjectDataService<McpModelData, Module>() { override fun getTargetDataKey(): Key<McpModelData> = McpModelData.KEY override fun importData( toImport: Collection<DataNode<McpModelData>>, projectData: ProjectData?, project: Project, modelsProvider: IdeModifiableModelsProvider ) { if (projectData == null || toImport.isEmpty()) { return } for (node in toImport) { val data = node.data val module = modelsProvider.findIdeModule(data.module) ?: continue val mcpModule = MinecraftFacet.getInstance(module, McpModuleType) if (mcpModule != null) { // Update the local settings and recompute the SRG map mcpModule.updateSettings(data.settings) continue } } } }
mit
e1b9257a1d171bc970345bd43c645d66
31.836735
92
0.707272
4.890578
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/platform/sponge/SpongeModuleType.kt
1
1685
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.sponge import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.sponge.generation.SpongeEventGenerationPanel import com.demonwav.mcdev.platform.sponge.util.SpongeConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object SpongeModuleType : AbstractModuleType<SpongeModule>("org.spongepowered", "spongeapi") { private const val ID = "SPONGE_MODULE_TYPE" private val IGNORED_ANNOTATIONS = listOf( SpongeConstants.LISTENER_ANNOTATION, SpongeConstants.PLUGIN_ANNOTATION, SpongeConstants.JVM_PLUGIN_ANNOTATION ) private val LISTENER_ANNOTATIONS = listOf(SpongeConstants.LISTENER_ANNOTATION) init { CommonColors.applyStandardColors(colorMap, SpongeConstants.TEXT_COLORS) } override val platformType = PlatformType.SPONGE override val icon = PlatformAssets.SPONGE_ICON override val id = ID override val ignoredAnnotations = IGNORED_ANNOTATIONS override val listenerAnnotations = LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet) = SpongeModule(facet) override fun getDefaultListenerName(psiClass: PsiClass): String = defaultNameForSubClassEvents(psiClass) override fun getEventGenerationPanel(chosenClass: PsiClass) = SpongeEventGenerationPanel(chosenClass) }
mit
535fc9c3ed60ffc914335f36502f9c98
34.851064
108
0.786944
4.541779
false
false
false
false
EddieVanHalen98/vision-kt
main/out/production/core/com/evh98/vision/ui/GamePane.kt
2
1587
package com.evh98.vision.ui import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.evh98.vision.Vision import com.evh98.vision.models.Game import com.evh98.vision.util.Graphics import com.evh98.vision.util.Palette class GamePane(val game: Game, val xPos: Int, val yPos: Int) { val Vision = Vision() val WIDTH = 920F val HEIGHT = 430F var x = 0 var y = 0 init { x = 320 + (xPos * 1140) y = 278 + (yPos * 557) } fun renderUnselect(sprite_batch: SpriteBatch) { renderIcon(sprite_batch) } fun renderSelect(sprite_batch: SpriteBatch, shape_renderer: ShapeRenderer) { renderIcon(sprite_batch) renderIndicator(shape_renderer) } private fun renderIcon(sprite_batch: SpriteBatch) { sprite_batch.begin() Graphics.drawSprite(sprite_batch, game.icon!!, x.toFloat(), y.toFloat(), WIDTH, HEIGHT) sprite_batch.end() } private fun renderIndicator(shape_renderer: ShapeRenderer) { Gdx.gl.glEnable(GL20.GL_BLEND) Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA) shape_renderer.begin(ShapeRenderer.ShapeType.Filled) val red = Palette.RED shape_renderer.color = Color(red.r, red.g, red.b, 0.6F) Graphics.drawRect(shape_renderer, x.toFloat(), y + HEIGHT - 32, WIDTH, 32F) shape_renderer.end() Gdx.gl.glDisable(GL20.GL_BLEND) } }
mit
b7b4ad298c0cbe98ddca6e499e20b14c
29.538462
95
0.674858
3.45
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/main/kotlin/org/wfanet/panelmatch/client/exchangetasks/DecryptPrivateMembershipResults.kt
1
3996
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.exchangetasks import com.google.protobuf.Any import org.apache.beam.sdk.values.PCollection import org.wfanet.panelmatch.client.privatemembership.EncryptedQueryResult import org.wfanet.panelmatch.client.privatemembership.JoinKeyIdentifierCollection import org.wfanet.panelmatch.client.privatemembership.KeyedDecryptedEventDataSet import org.wfanet.panelmatch.client.privatemembership.QueryResultsDecryptor import org.wfanet.panelmatch.client.privatemembership.decryptQueryResults import org.wfanet.panelmatch.client.privatemembership.encryptedQueryResult import org.wfanet.panelmatch.client.privatemembership.queryIdAndId import org.wfanet.panelmatch.client.privatemembership.removeDiscardedJoinKeys import org.wfanet.panelmatch.common.beam.flatMap import org.wfanet.panelmatch.common.beam.map import org.wfanet.panelmatch.common.beam.mapWithSideInput import org.wfanet.panelmatch.common.beam.toSingletonView import org.wfanet.panelmatch.common.compression.CompressionParameters import org.wfanet.panelmatch.common.crypto.AsymmetricKeyPair /** Decrypts private membership results given serialized parameters. */ suspend fun ApacheBeamContext.decryptPrivateMembershipResults( parameters: Any, queryResultsDecryptor: QueryResultsDecryptor, ) { val encryptedQueryResults: PCollection<EncryptedQueryResult> = readShardedPCollection("encrypted-results", encryptedQueryResult {}) val queryAndIds = readShardedPCollection("query-to-ids-map", queryIdAndId {}) // TODO: remove this functionality v2.0.0 // For backwards compatibility for workflows without discarded-join-keys val discardedJoinKeys: List<JoinKeyIdentifier> = if ("discarded-join-keys" in inputLabels) { JoinKeyIdentifierCollection.parseFrom(readBlob("discarded-join-keys")).joinKeyIdentifiersList } else { emptyList() } val plaintextJoinKeyAndIds: PCollection<JoinKeyAndId> = readBlobAsPCollection("plaintext-join-keys-to-id-map").flatMap { JoinKeyAndIdCollection.parseFrom(it) .joinKeyAndIdsList .removeDiscardedJoinKeys(discardedJoinKeys) } val decryptedJoinKeyAndIds: PCollection<JoinKeyAndId> = readBlobAsPCollection("decrypted-join-keys-to-id-map").flatMap { JoinKeyAndIdCollection.parseFrom(it) .joinKeyAndIdsList .removeDiscardedJoinKeys(discardedJoinKeys) } val compressionParameters = readBlobAsPCollection("compression-parameters") .map("Parse as CompressionParameters") { CompressionParameters.parseFrom(it) } .toSingletonView() val hkdfPepper = readBlob("pepper") val publicKeyView = readBlobAsView("serialized-rlwe-public-key") val privateKeysView = readBlobAsPCollection("serialized-rlwe-private-key") .mapWithSideInput(publicKeyView, "Make Private Membership Keys") { privateKey, publicKey -> AsymmetricKeyPair(serializedPublicKey = publicKey, serializedPrivateKey = privateKey) } .toSingletonView() val keyedDecryptedEventDataSet: PCollection<KeyedDecryptedEventDataSet> = decryptQueryResults( encryptedQueryResults, plaintextJoinKeyAndIds, decryptedJoinKeyAndIds, queryAndIds, compressionParameters, privateKeysView, parameters, queryResultsDecryptor, hkdfPepper, ) keyedDecryptedEventDataSet.writeShardedFiles("decrypted-event-data") }
apache-2.0
06a89f31a3f376eaa0c42b42c63016ba
41.510638
99
0.789289
4.273797
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/user/domain/SimpleRole.kt
3
1929
/** * Copyright ยฉ MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.module.user.domain import com.mycollab.core.arguments.NotBindable import com.mycollab.core.reporting.NotInReport import com.mycollab.core.utils.StringUtils import com.mycollab.security.PermissionMap import org.slf4j.LoggerFactory /** * @author MyCollab Ltd. * @since 1.0 */ class SimpleRole : Role() { var permissionVal: String? = null var numMembers: Int? = null @NotBindable @NotInReport var permissionMap: PermissionMap? = null get() = if (field == null) { if (StringUtils.isBlank(permissionVal)) { PermissionMap() } else { try { PermissionMap.fromJsonString(permissionVal!!) } catch (e: Exception) { LOG.error("Error while get permission", e) PermissionMap() } } } else field val isSystemRole: Boolean get() = java.lang.Boolean.TRUE == issystemrole companion object { private val LOG = LoggerFactory.getLogger(SimpleRole::class.java) const val ADMIN = "Administrator" const val EMPLOYEE = "Employee" const val GUEST = "Guest" } }
agpl-3.0
92c298f042216b295ab81942940f1624
29.125
81
0.651452
4.381818
false
false
false
false
TUWien/DocScan
app/src/main/java/at/ac/tuwien/caa/docscan/ui/start/StartActivity.kt
1
7159
package at.ac.tuwien.caa.docscan.ui.start import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.activity.result.contract.ActivityResultContracts import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import at.ac.tuwien.caa.docscan.R import at.ac.tuwien.caa.docscan.databinding.MainContainerViewBinding import at.ac.tuwien.caa.docscan.db.model.error.IOErrorCode import at.ac.tuwien.caa.docscan.extensions.shareFileAsEmailLog import at.ac.tuwien.caa.docscan.extensions.showAppSettings import at.ac.tuwien.caa.docscan.logic.* import at.ac.tuwien.caa.docscan.ui.base.BaseActivity import at.ac.tuwien.caa.docscan.ui.camera.CameraActivity import at.ac.tuwien.caa.docscan.ui.dialog.* import at.ac.tuwien.caa.docscan.ui.info.LogViewModel import at.ac.tuwien.caa.docscan.ui.intro.IntroActivity import org.koin.android.ext.android.inject import org.koin.androidx.viewmodel.ext.android.viewModel import timber.log.Timber class StartActivity : BaseActivity() { private val viewModel: StartViewModel by viewModel() private val logViewModel: LogViewModel by viewModel() private val dialogViewModel: DialogViewModel by viewModel() private val preferenceHandler: PreferencesHandler by inject() private lateinit var binding: MainContainerViewBinding private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { map: Map<String, Boolean> -> if (map.filter { entry -> !entry.value }.isEmpty()) { viewModel.checkStartUpConditions(Bundle()) } else { showDialog(ADialog.DialogAction.RATIONALE_MIGRATION_PERMISSION) } } companion object { fun newInstance(context: Context): Intent { return Intent(context, StartActivity::class.java) } } override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) // Keep the splash screen visible for this Activity val shouldPerformDBMigration = preferenceHandler.shouldPerformDBMigration splashScreen.setKeepOnScreenCondition { !shouldPerformDBMigration } binding = MainContainerViewBinding.inflate(layoutInflater) setContentView(binding.root) observe() } override fun onStart() { super.onStart() viewModel.checkStartUpConditions(Bundle()) } override fun onBackPressed() { if (viewModel.loadingProgress.value == true) { showDialog(ADialog.DialogAction.MIGRATION_ABORT) } else { super.onBackPressed() } } private fun observe() { viewModel.loadingProgress.observe(this) { binding.progress.visibility = if (it) View.VISIBLE else View.GONE } logViewModel.observableShareUris.observe(this, ConsumableEvent { uri -> if (!shareFileAsEmailLog(this, PageFileType.ZIP, uri)) { showDialog(ADialog.DialogAction.ACTIVITY_NOT_FOUND_EMAIL) } }) viewModel.destination.observe(this, ConsumableEvent { pair -> when (pair.first) { StartDestination.CAMERA -> { startCameraIntent() } StartDestination.INTRO -> { startActivity(IntroActivity.newInstance(this)) } StartDestination.PERMISSIONS -> { requestPermissionLauncher.launch(PermissionHandler.requiredMandatoryPermissions) } StartDestination.MIGRATION_DIALOG_1 -> { showDialog(ADialog.DialogAction.MIGRATION_DIALOG_ONE, pair.second) } StartDestination.MIGRATION_DIALOG_2 -> { showDialog(ADialog.DialogAction.MIGRATION_DIALOG_TWO, pair.second) } } }) viewModel.migrationError.observe(this, ConsumableEvent { throwable -> Timber.e(throwable, "Migration error occurred") val hasIOErrorHappenedDueToMissingSpace = when (throwable.getDocScanIOError()?.ioErrorCode) { // it is very likely that these errors have happened due to missing storage IOErrorCode.FILE_COPY_ERROR, IOErrorCode.NOT_ENOUGH_DISK_SPACE -> { true } else -> { false } } val dialogModel = DialogModel( ADialog.DialogAction.MIGRATION_FAILED, customMessage = getString(if (hasIOErrorHappenedDueToMissingSpace) R.string.migration_failed_missing_space_text else R.string.migration_failed_text) ) showDialog(dialogModel) }) dialogViewModel.observableDialogAction.observe(this, ConsumableEvent { dialogResult -> when (dialogResult.dialogAction) { ADialog.DialogAction.RATIONALE_MIGRATION_PERMISSION -> { when { dialogResult.isPositive() -> { requestPermissionLauncher.launch(PermissionHandler.requiredMandatoryPermissions) } dialogResult.isNegative() -> { finish() } dialogResult.isNeutral() -> { showAppSettings(this) } } } ADialog.DialogAction.MIGRATION_DIALOG_ONE -> { if (dialogResult.isPositive()) { viewModel.checkStartUpConditions(dialogResult.arguments.appendMigrationDialogOne()) } else if (dialogResult.isNegative()) { finish() } } ADialog.DialogAction.MIGRATION_DIALOG_TWO -> { if (dialogResult.isPositive()) { viewModel.checkStartUpConditions(dialogResult.arguments.appendMigrationDialogTwo()) } else if (dialogResult.isNegative()) { finish() } } ADialog.DialogAction.MIGRATION_FAILED -> { if (dialogResult.isPositive()) { finish() } else if (dialogResult.isNegative()) { logViewModel.shareLog() } } ADialog.DialogAction.MIGRATION_ABORT -> { if (dialogResult.isPositive()) { Timber.w("User aborted migration!") finish() } } else -> { // ignore } } }) } private fun startCameraIntent() { startActivity(CameraActivity.newInstance(this, false)) finish() } }
lgpl-3.0
ebb35b0bcc663fb9995c9e84e3026b40
40.143678
164
0.585417
5.350523
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/common/service/impl/CustomViewStoreServiceImpl.kt
3
2562
/** * Copyright ยฉ MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.common.service.impl import com.mycollab.common.dao.CustomViewStoreMapper import com.mycollab.common.domain.CustomViewStore import com.mycollab.common.domain.CustomViewStoreExample import com.mycollab.common.domain.NullCustomViewStore import com.mycollab.common.service.CustomViewStoreService import com.mycollab.db.persistence.ICrudGenericDAO import com.mycollab.db.persistence.service.DefaultCrudService import org.springframework.stereotype.Service import java.time.LocalDateTime /** * @author MyCollab Ltd. * @since 2.0 */ @Service class CustomViewStoreServiceImpl(private val customViewStoreMapper: CustomViewStoreMapper) : DefaultCrudService<Int, CustomViewStore>(), CustomViewStoreService { override val crudMapper: ICrudGenericDAO<Int, CustomViewStore> get() = customViewStoreMapper as ICrudGenericDAO<Int, CustomViewStore> override fun getViewLayoutDef(accountId: Int?, username: String, viewId: String): CustomViewStore { val ex = CustomViewStoreExample() ex.createCriteria().andCreateduserEqualTo(username).andViewidEqualTo(viewId).andSaccountidEqualTo(accountId) val views = customViewStoreMapper.selectByExampleWithBLOBs(ex) return if (views.isNotEmpty()) { views[0] } else NullCustomViewStore() } override fun saveOrUpdateViewLayoutDef(viewStore: CustomViewStore) { val viewLayoutDef = getViewLayoutDef(viewStore.saccountid, viewStore.createduser, viewStore.viewid) viewStore.createdtime = LocalDateTime.now() when (viewLayoutDef) { !is NullCustomViewStore -> { viewStore.id = viewLayoutDef.id updateWithSession(viewStore, viewStore.createduser) } else -> saveWithSession(viewStore, viewStore.createduser) } } }
agpl-3.0
f2146e363923a9f1e01a4dfc2f359eb1
41.683333
161
0.74385
4.370307
false
false
false
false
esofthead/mycollab
mycollab-services/src/main/java/com/mycollab/module/project/ProjectTypeConstants.kt
3
1640
/** * Copyright ยฉ MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project /** * @author MyCollab Ltd. * @since 4.0 */ object ProjectTypeConstants { const val PROJECT = "Project" const val PROJECT_ROLE = "Project-Role" const val CLIENT = "Project-Client" const val TICKET = "Project-Assignment" const val TASK = "Project-Task" const val MESSAGE = "Project-Message" const val MILESTONE = "Project-Milestone" const val RISK = "Project-Risk" const val BUG = "Project-Bug" const val SPIKE = "Project-Spike" const val FILE = "Project-File" const val COMPONENT = "Project-Component" const val VERSION = "Project-Version" const val STANDUP = "Project-StandUp" const val PAGE = "Project-Page" const val DASHBOARD = "Project-Dashboard" const val TIME = "Project-Time" const val INVOICE = "Project-Invoice" const val FINANCE = "Project-Finance" const val MEMBER = "Project-Member" }
agpl-3.0
0d408d954a131403c22dacac75154740
25.015873
78
0.697987
4.007335
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/util/PageLinkManage.kt
1
17857
package com.intfocus.template.util import android.app.AlertDialog import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.net.Uri import com.alibaba.fastjson.TypeReference import com.intfocus.template.ConfigConstants import com.intfocus.template.constant.Params.ACTION import com.intfocus.template.constant.Params.BANNER_NAME import com.intfocus.template.constant.Params.GROUP_ID import com.intfocus.template.constant.Params.LINK import com.intfocus.template.constant.Params.OBJECT_ID import com.intfocus.template.constant.Params.OBJECT_TITLE import com.intfocus.template.constant.Params.OBJECT_TYPE import com.intfocus.template.constant.Params.TEMPLATE_ID import com.intfocus.template.constant.Params.TIME_STAMP import com.intfocus.template.constant.Params.USER_BEAN import com.intfocus.template.constant.Params.USER_NUM import com.intfocus.template.dashboard.DashboardActivity import com.intfocus.template.dashboard.feedback.FeedbackActivity import com.intfocus.template.dashboard.mine.activity.ShowPushMessageActivity import com.intfocus.template.model.entity.DashboardItem import com.intfocus.template.model.entity.PushMsgBean import com.intfocus.template.scanner.BarCodeScannerActivity import com.intfocus.template.subject.nine.CollectionActivity import com.intfocus.template.subject.one.NativeReportActivity import com.intfocus.template.subject.seven.MyConcernActivity import com.intfocus.template.subject.three.MultiIndexActivity import com.intfocus.template.subject.two.WebPageActivity import org.json.JSONException import org.json.JSONObject /** * **************************************************** * author jameswong * created on: 17/11/08 ไธŠๅˆ10:51 * e-mail: [email protected] * name: * desc: * **************************************************** */ object PageLinkManage { private val PUSH_MESSAGE_LIST = "-4" private val FEEDBACK = "-3" private val SCANNER = "-2" private val EXTERNAL_LINK = "-1" private val TEMPLATE_ONE = "1" private val TEMPLATE_TWO = "2" private val TEMPLATE_THREE = "3" private val TEMPLATE_FOUR = "4" private val TEMPLATE_FIVE = "5" private val TEMPLATE_SIX = "6" private val TEMPLATE_SEVEN = "7" private val TEMPLATE_NINE = "9" private val TEMPLATE_TEN = "10" private var objectTypeName = arrayOf("็”Ÿๆ„ๆฆ‚ๅ†ต", "ๆŠฅ่กจ", "ๅทฅๅ…ท็ฎฑ", "ๆŽจ้€้€š็Ÿฅ") private var mClickTemplateName = "" /** * ๅ›พ่กจ็‚นๅ‡ปไบ‹ไปถ็ปŸไธ€ๅค„็†ๆ–นๆณ• */ fun pageLink(context: Context, items: DashboardItem?) { if (items != null) { val link = items.obj_link ?: "" val objTitle = items.obj_title ?: "" val objectId = items.obj_id ?: "-1" val templateId = items.template_id ?: "-1" val objectType = items.objectType ?: "-1" val paramsMappingBean = items.paramsMappingBean ?: HashMap() PageLinkManage.pageLink(context, objTitle, link, objectId, templateId, objectType, paramsMappingBean) } else { ToastUtils.show(context, "ๆฒกๆœ‰ๆŒ‡ๅฎš้“พๆŽฅ") } } fun pageLink(context: Context, pushMsg: PushMsgBean) { val paramsMappingBean = com.alibaba.fastjson.JSONObject.parseObject(pushMsg.params_mapping, object : TypeReference<java.util.HashMap<String, String>>() { }) var templateId = "" if (pushMsg.template_id == null || "" == pushMsg.template_id) { val temp = pushMsg.url.split("/") for (i in 0..temp.size) { if ("template" == temp[i] && i + 1 < temp.size) { templateId = temp[i + 1] break } } } else { templateId = pushMsg.template_id } if (templateId == "") { return } val userSP = context.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE) val userNum = userSP.getString(USER_NUM, "") if (userNum != "") { pageLink(context, pushMsg.title ?: "ๆ ‡้ข˜", pushMsg.url ?: "", pushMsg.obj_id ?: "-1", templateId, "4", paramsMappingBean ?: HashMap(), true) } else { ToastUtils.show(context, "่ฏทๅ…ˆ็™ปๅฝ•") } } /** * ้กต้ข่ทณ่ฝฌไบ‹ไปถ */ fun pageLink(context: Context, objTitle: String, link: String) { pageLink(context, objTitle, link, "-1", "-1", "-1") } // fun pageLink(context: Context, objTitle: String, link: String, objectId: String, templateId: String, objectType: String) { // pageLink(context, objTitle, link, objectId, templateId, objectType, HashMap()) // } // fun pageLink(context: Context, objTitle: String, link: String, objectId: String, templateId: String, objectType: String, paramsMappingBean: HashMap<String, String>) { // pageLink(context, objTitle, link, objectId, templateId, objectType, paramsMappingBean, false) // } fun pageLink(context: Context, objTitle: String = "ๆ ‡้ข˜", link: String = "http://shengyiplus.com/", objectId: String = "-1", templateId: String = "-1", objectType: String = "-1", paramsMappingBean: HashMap<String, String> = HashMap(), fromPushMsg: Boolean = false) { try { val userSP = context.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE) val groupID = userSP.getString(GROUP_ID, "0") userSP.edit().putString(TIME_STAMP, "" + System.currentTimeMillis()).commit() //ๆ›ดๆ–ฐๆœฌๅœฐๅฎšไฝไฟกๆฏ MapUtil.getInstance(context).updateSPLocation() var urlString: String val intent: Intent when (templateId) { // TEMPLATE_TWO -> { TEMPLATE_SEVEN -> { mClickTemplateName = "ๆจกๆฟไธƒ" intent = Intent(context, MyConcernActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_ONE -> { mClickTemplateName = "ๆจกๆฟไธ€" savePageLink(context, objTitle, link, objectId, templateId, objectType) intent = Intent(context, NativeReportActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_TEN -> { mClickTemplateName = "ๆจกๆฟๅ" savePageLink(context, objTitle, link, objectId, templateId, objectType) intent = Intent(context, NativeReportActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_TWO -> { mClickTemplateName = "ๆจกๆฟไบŒ" savePageLink(context, objTitle, link, objectId, templateId, objectType) intent = Intent(context, WebPageActivity::class.java) if (fromPushMsg) { intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_FOUR -> { mClickTemplateName = "ๆจกๆฟๅ››" intent = Intent(context, WebPageActivity::class.java) if (fromPushMsg) { intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_THREE -> { mClickTemplateName = "ๆจกๆฟไธ‰" intent = Intent(context, MultiIndexActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } TEMPLATE_NINE -> { mClickTemplateName = "ๆจกๆฟไน" intent = Intent(context, CollectionActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, link) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } EXTERNAL_LINK, TEMPLATE_SIX -> { mClickTemplateName = "ๅค–้ƒจ้“พๆŽฅ" urlString = link // urlString = "https://datav.aliyun.com/share/31ae546cd064046699a979b24607a9d5" for ((key, value) in paramsMappingBean) { urlString = splitUrl(userSP, urlString, key, value) } savePageLink(context, objTitle, urlString, objectId, templateId, objectType) intent = Intent(context, WebPageActivity::class.java) if (fromPushMsg) { intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK } intent.putExtra(GROUP_ID, groupID) intent.putExtra(TEMPLATE_ID, templateId) intent.putExtra(BANNER_NAME, objTitle) intent.putExtra(LINK, urlString) intent.putExtra(OBJECT_ID, objectId) intent.putExtra(OBJECT_TYPE, objectType) context.startActivity(intent) } SCANNER -> { mClickTemplateName = "ๆ‰ซไธ€ๆ‰ซ" urlString = link for ((key, value) in paramsMappingBean) { urlString = splitUrl(userSP, urlString, key, value) } savePageLink(context, objTitle, urlString, objectId, templateId, objectType) intent = Intent(context, BarCodeScannerActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { Intent.FLAG_ACTIVITY_SINGLE_TOP } intent.putExtra(BarCodeScannerActivity.INTENT_FOR_RESULT, false) intent.putExtra(LINK, urlString) context.startActivity(intent) } PUSH_MESSAGE_LIST -> { mClickTemplateName = "ๆถˆๆฏๅˆ—่กจ" intent = Intent(context, ShowPushMessageActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) Intent.FLAG_ACTIVITY_SINGLE_TOP } context.startActivity(intent) } FEEDBACK -> { mClickTemplateName = "้—ฎ้ข˜ๅ้ฆˆ" intent = Intent(context, FeedbackActivity::class.java) intent.flags = if (fromPushMsg) { Intent.FLAG_ACTIVITY_NEW_TASK } else { savePageLink(context, objTitle, link, objectId, templateId, objectType) Intent.FLAG_ACTIVITY_SINGLE_TOP } context.startActivity(intent) } else -> showTemplateErrorDialog(context) } } catch (e: JSONException) { e.printStackTrace() } val logParams = JSONObject() if ("-1" == templateId && "-1" != objectType) { logParams.put(ACTION, "็‚นๅ‡ป/" + objectTypeName[objectType.toInt() - 1] + "/" + mClickTemplateName) } else if ("-1" != objectType) { logParams.put(ACTION, "็‚นๅ‡ป/" + objectTypeName[objectType.toInt() - 1] + "/" + mClickTemplateName) } logParams.put(OBJECT_TITLE, objTitle) logParams.put(OBJECT_ID, objectId) logParams.put(LINK, link) logParams.put(OBJECT_TYPE, objectType) ActionLogUtil.actionLog(logParams) } private fun showTemplateErrorDialog(context: Context) { val builder = AlertDialog.Builder(context) builder.setTitle("ๆธฉ้ฆจๆ็คบ") .setMessage("ๅฝ“ๅ‰็‰ˆๆœฌๆš‚ไธๆ”ฏๆŒ่ฏฅๆจกๆฟ, ่ฏทๅ‡็บงๅบ”็”จๅŽๆŸฅ็œ‹") .setPositiveButton("ๅ‰ๅŽปๅ‡็บง") { _, _ -> val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(TempHost.getHost())) context.startActivity(browserIntent) } .setNegativeButton("็จๅŽๅ‡็บง") { _, _ -> // ่ฟ”ๅ›ž LoginActivity } builder.show() } private fun savePageLink(context: Context, objTitle: String, link: String, objectId: String, templateId: String, objectType: String) { if (ConfigConstants.REVIEW_LAST_PAGE) { val pageLinkManagerSP = context.getSharedPreferences("PageLinkManager", Context.MODE_PRIVATE) val pageLinkManagerSPED = pageLinkManagerSP.edit() pageLinkManagerSPED.putBoolean("pageSaved", true) pageLinkManagerSPED.putString("objTitle", objTitle) pageLinkManagerSPED.putString("link", link) pageLinkManagerSPED.putString("objectId", objectId) pageLinkManagerSPED.putString("templateId", templateId) pageLinkManagerSPED.putString("objectType", objectType).apply() } } fun pageBackIntent(context: Context) { val pageLinkManager = context.getSharedPreferences("PageLinkManager", Context.MODE_PRIVATE) val pageSaved = pageLinkManager.getBoolean("pageSaved", false) if (pageSaved) { pageLinkManager.edit().putBoolean("pageSaved", false).apply() context.startActivity(Intent(context, DashboardActivity::class.java)) } } private fun splitUrl(userSP: SharedPreferences, urlString: String, paramsKey: String, paramsValue: String): String { val params = paramsValue + "=" + userSP.getString(paramsKey, "null") val splitString = if (urlString.contains("?")) "&" else "?" return String.format("%s%s%s", urlString, splitString, params) } }
gpl-3.0
5a9aa59859b3ff3e94973c51e71d0077
45.075916
172
0.556502
4.727639
false
false
false
false
naosim/RPGSample
rpglib/src/main/kotlin/com/naosim/rpglib/model/value/field/Position.kt
1
581
package com.naosim.rpglib.model.value.field class Position(val fieldName: FieldName, val x: X, val y: Y) { fun isSame(fieldName: FieldName, x: X, y: Y): Boolean { return isSame(Position(fieldName, x, y)) } fun isSame(fieldName: FieldName, x: Int, y: Int): Boolean { return isSame(fieldName, X(x), Y(y)) } fun isSame(otherPosition: Position): Boolean { return this.fieldName.value == otherPosition.fieldName.value && this.x.value == otherPosition.x.value && this.y.value == otherPosition.y.value } }
mit
c70d465a14c86b552eec047ef277a606
33.235294
68
0.624785
3.724359
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/LastPickedValuesStore.kt
1
3462
package de.westnordost.streetcomplete.quests import android.content.SharedPreferences import androidx.core.content.edit import java.util.LinkedList import javax.inject.Inject import de.westnordost.streetcomplete.Prefs import de.westnordost.streetcomplete.view.image_select.DisplayItem import de.westnordost.streetcomplete.view.image_select.GroupableDisplayItem import kotlin.math.min /** T must be a string or enum - something that distinctly converts toString. */ class LastPickedValuesStore<T> @Inject constructor(private val prefs: SharedPreferences) { fun add(key: String, newValues: Iterable<T>, max: Int = -1) { val values = get(key) for (value in newValues.map { it.toString() }) { values.remove(value) values.addFirst(value) } val lastValues = if (max != -1) values.subList(0, min(values.size, max)) else values prefs.edit { putString(getKey(key), lastValues.joinToString(",")) } } fun add(key: String, value: T, max: Int = -1) { add(key, listOf(value), max) } fun get(key: String): LinkedList<String> { val result = LinkedList<String>() val values = prefs.getString(getKey(key), null) if(values != null) result.addAll(values.split(",")) return result } private fun getKey(key: String) = Prefs.LAST_PICKED_PREFIX + key } fun <T> LastPickedValuesStore<T>.moveLastPickedGroupableDisplayItemToFront( key: String, items: LinkedList<GroupableDisplayItem<T>>, itemPool: List<GroupableDisplayItem<T>>) { val lastPickedItems = find(get(key), itemPool) val reverseIt = lastPickedItems.descendingIterator() while (reverseIt.hasNext()) { val lastPicked = reverseIt.next() if (!items.remove(lastPicked)) items.removeLast() items.addFirst(lastPicked) } } private fun <T> find(values: List<String>, itemPool: Iterable<GroupableDisplayItem<T>>): LinkedList<GroupableDisplayItem<T>> { val result = LinkedList<GroupableDisplayItem<T>>() for (value in values) { val item = find(value, itemPool) if(item != null) result.add(item) } return result } private fun <T> find(value: String, itemPool: Iterable<GroupableDisplayItem<T>>): GroupableDisplayItem<T>? { for (item in itemPool) { val subItems = item.items // returns only items which are not groups themselves if (subItems != null) { val subItem = find(value, subItems.asIterable()) if (subItem != null) return subItem } else if (value == item.value.toString()) { return item } } return null } fun <T> LastPickedValuesStore<T>.moveLastPickedDisplayItemsToFront( key: String, items: LinkedList<DisplayItem<T>>, itemPool: List<DisplayItem<T>>) { val lastPickedItems = findDisplayItems(get(key), itemPool) val reverseIt = lastPickedItems.descendingIterator() while (reverseIt.hasNext()) { val lastPicked = reverseIt.next() if (!items.remove(lastPicked)) items.removeLast() items.addFirst(lastPicked) } } private fun <T> findDisplayItems(values: List<String>, itemPool: Iterable<DisplayItem<T>>): LinkedList<DisplayItem<T>> { val result = LinkedList<DisplayItem<T>>() for (value in values) { val item = itemPool.find { it.value.toString() == value } if (item != null) result.add(item) } return result }
gpl-3.0
a27269556ffb2e010dd8c039dd2a7632
32.941176
126
0.667244
3.87682
false
false
false
false
anrelic/Anci-OSS
test/src/main/kotlin/su/jfdev/test/history/EventHistory.kt
1
698
@file:Suppress("unused") package su.jfdev.test.history import su.jfdev.anci.util.syntax.* import java.util.concurrent.* class EventHistory<T>(register: ((T) -> Unit) -> Unit, private val delegate: MutableCollection<T>): Collection<T> by delegate { constructor(register: ((T) -> Unit) -> Unit): this(register, delegate = CopyOnWriteArrayList()) var active = true init { register { if (active) delegate += it } } inline infix fun <R> temporary(using: EventCatcher<T>.() -> R) = then(using) finally { active = false } inline infix fun <R> then(using: EventCatcher<T>.() -> R) = EventCatcher(this).run(using) companion object }
mit
5decd56b3305fb48f9e08c1df5ce373b
26.96
127
0.636103
3.814208
false
false
false
false
Nhemesy/DDS-PatternsApplication
src/main/kotlin/Window.kt
1
1828
import Styles.Companion.loginScreen import javafx.animation.KeyFrame import javafx.animation.Timeline import javafx.event.EventHandler import javafx.scene.control.TextField import javafx.scene.layout.GridPane import javafx.util.Duration import tornadofx.* class Window : View() { override val root = GridPane() val loginController: WindowController by inject() var nombre: TextField by singleAssign() var direccion: TextField by singleAssign() var codpostal: TextField by singleAssign() var telefono: TextField by singleAssign() var direcciondest: TextField by singleAssign() var codpostaldest: TextField by singleAssign() var peso: TextField by singleAssign() init { title = "Envia tu mierda" with(root) { addClass(loginScreen) row("Nombre") { nombre = textfield() } row("Direccion") { direccion = textfield() } row("Codigo postal") { codpostal = textfield() } row("Telefono") { telefono = textfield() } row("Direccion destino") { direcciondest = textfield() } row("Codigo postal destino") { codpostaldest = textfield() } row("Peso") { peso = textfield() } row { button("Enviar") { isDefaultButton = true setOnAction{ loginController.send(Cliente(nombre.text, direccion.text, codpostal.text.toInt(), telefono.text.toInt()), EnvioFactory().envioPorPeso(peso.text.toDouble())!!) } } } } } }
apache-2.0
9c8395ad6b4929d2a47cdc9e122f571a
28.967213
108
0.538293
4.604534
false
false
false
false
jkcclemens/khttp
src/test/kotlin/khttp/structures/cookie/CookieJarSpec.kt
1
8063
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package khttp.structures.cookie import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue class CookieJarSpec : Spek({ describe("a CookieJar constructed with Cookies") { val cookie1 = Cookie("test1", "value1") val cookie2 = Cookie("test2", "value2", mapOf("attr1" to "attrv1")) val cookies = listOf(cookie1, cookie2) val cookieJar = CookieJar(*cookies.toTypedArray()) context("inspecting the cookie jar") { val size = cookieJar.size it("should have two cookies") { assertEquals(2, size) } } context("accessing a cookie by name") { val cookie = cookieJar.getCookie("test1") it("should not be null") { assertNotNull(cookie) } it("should have the same name") { assertEquals("test1", cookie!!.key) } it("should have the same value") { assertEquals("value1", cookie!!.value) } it("should have the no attributes") { assertEquals(0, cookie!!.attributes.size) } } context("checking if a cookie exists by name") { it("should exist") { assertTrue("test1" in cookieJar) } it("should not exist") { assertFalse("test3" in cookieJar) } it("should not exist") { assertFalse(cookieJar.containsKey(null as String?)) } } context("checking if a cookie exists by value") { it("should exist") { assertTrue(cookieJar.containsValue(cookie1.valueWithAttributes)) } it("should not exist") { assertFalse(cookieJar.containsValue("")) } it("should not exist") { assertFalse(cookieJar.containsValue(null as String?)) } } context("accessing another cookie by name") { val cookie = cookieJar.getCookie("test2") it("should not be null") { assertNotNull(cookie) } it("should have the same name") { assertEquals("test2", cookie!!.key) } it("should have the same value") { assertEquals("value2", cookie!!.value) } it("should have the same attributes") { assertEquals(mapOf("attr1" to "attrv1"), cookie!!.attributes) } } context("accessing a cookie that doesn't exist") { val cookie = cookieJar.getCookie("test3") val cookieRaw: Any? = cookieJar.get(null as String?) it("should be null") { assertNull(cookie) } it("should be null") { assertNull(cookieRaw) } } context("accessing a cookie with Map methods") { val cookieValue = cookieJar["test1"] it("should exist") { assertNotNull(cookieValue) } it("should have the value of the first cookie") { assertEquals(cookie1.valueWithAttributes, cookieValue) } } context("accessing a cookie that doesn't exist with Map methods") { val cookieValue = cookieJar["test3"] it("should not exist") { assertNull(cookieValue) } } context("adding a cookie to the cookie jar") { val cookie = Cookie("delicious", "cookie", mapOf("edible" to "damn straight")) cookieJar.setCookie(cookie) val size = cookieJar.size val added = cookieJar.getCookie("delicious") it("should have three cookies") { assertEquals(3, size) } it("should have the same cookie as was added") { assertEquals(added, cookie) } } } describe("a CookieJar constructed with a map") { val cookies = mapOf("test1" to "value1", "test2" to "value2; attr1=attrv1") val cookieJar = CookieJar(cookies) context("inspecting the cookie jar") { val size = cookieJar.size it("should have two cookies") { assertEquals(2, size) } } context("accessing a cookie by name") { val cookie = cookieJar.getCookie("test1") it("should not be null") { assertNotNull(cookie) } it("should have the same name") { assertEquals("test1", cookie!!.key) } it("should have the same value") { assertEquals("value1", cookie!!.value) } it("should have the no attributes") { assertEquals(0, cookie!!.attributes.size) } } context("accessing another cookie by name") { val cookie = cookieJar.getCookie("test2") it("should not be null") { assertNotNull(cookie) } it("should have the same name") { assertEquals("test2", cookie!!.key) } it("should have the same value") { assertEquals("value2", cookie!!.value) } it("should have the same attributes") { assertEquals(mapOf("attr1" to "attrv1"), cookie!!.attributes) } } context("accessing a cookie that doesn't exist") { val cookie = cookieJar.getCookie("test3") it("should be null") { assertNull(cookie) } } context("adding a cookie to the cookie jar") { val cookie = Cookie("delicious", "cookie", mapOf("edible" to "damn straight")) cookieJar.setCookie(cookie) val size = cookieJar.size val added = cookieJar.getCookie("delicious") it("should have three cookies") { assertEquals(3, size) } it("should have the same cookie as was added") { assertEquals(added, cookie) } } context("adding a cookie to the cookie jar with Map methods") { val cookie = Cookie("tasty", "cookie", mapOf("edible" to "damn straight")) cookieJar[cookie.key] = cookie.valueWithAttributes val size = cookieJar.size val added = cookieJar.getCookie("tasty") it("should have four cookies") { assertEquals(4, size) } it("should have the same cookie as was added") { assertEquals(added, cookie) } } context("removing a cookie with Map methods") { val originalSize = cookieJar.size cookieJar.remove("tasty") val cookieValue = cookieJar["tasty"] val size = cookieJar.size it("should have one less cookie") { assertEquals(originalSize - 1, size) } it("should not be accessible by name") { assertNull(cookieValue) } } context("removing an object that is not a string") { val originalSize = cookieJar.size val removed: Any? = (cookieJar as MutableMap<*, *>).remove(null) val size = cookieJar.size it("should be the same size") { assertTrue(originalSize == size) } it("should not have removed anything") { assertNull(removed) } } } })
mpl-2.0
41c03de797d8371e53b23d5ff1109063
37.21327
90
0.523999
4.952703
false
true
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt
1
13100
package info.nightscout.androidaps.plugins.source import android.content.Context import android.content.Intent import android.content.pm.PackageManager import androidx.core.content.ContextCompat import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.transactions.CgmSourceTransaction import info.nightscout.androidaps.database.transactions.InvalidateGlucoseValueTransaction import info.nightscout.androidaps.extensions.fromConstant import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton import kotlin.math.abs @Singleton class DexcomPlugin @Inject constructor( injector: HasAndroidInjector, rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP, private val dexcomMediator: DexcomMediator, config: Config ) : PluginBase( PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginIcon(R.drawable.ic_dexcom_g6) .pluginName(R.string.dexcom_app_patched) .shortName(R.string.dexcom_short) .preferencesId(R.xml.pref_bgsourcedexcom) .description(R.string.description_source_dexcom), aapsLogger, rh, injector ), BgSource { init { if (!config.NSCLIENT) { pluginDescription.setDefault() } } override fun advancedFilteringSupported(): Boolean { return true } override fun shouldUploadToNs(glucoseValue: GlucoseValue): Boolean = (glucoseValue.sourceSensor == GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE || glucoseValue.sourceSensor == GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE || glucoseValue.sourceSensor == GlucoseValue.SourceSensor.DEXCOM_NATIVE_UNKNOWN) && sp.getBoolean(R.string.key_dexcomg5_nsupload, false) override fun onStart() { super.onStart() dexcomMediator.requestPermissionIfNeeded() } // cannot be inner class because of needed injection class DexcomWorker( context: Context, params: WorkerParameters ) : Worker(context, params) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker @Inject lateinit var xDripBroadcast: XDripBroadcast @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) } override fun doWork(): Result { var ret = Result.success() if (!dexcomPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val bundle = dataWorker.pickupBundle(inputData.getLong(DataWorker.STORE_KEY, -1)) ?: return Result.failure(workDataOf("Error" to "missing input data")) try { val sourceSensor = when (bundle.getString("sensorType") ?: "") { "G6" -> GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE "G5" -> GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE else -> GlucoseValue.SourceSensor.DEXCOM_NATIVE_UNKNOWN } val calibrations = mutableListOf<CgmSourceTransaction.Calibration>() bundle.getBundle("meters")?.let { meters -> for (i in 0 until meters.size()) { meters.getBundle(i.toString())?.let { val timestamp = it.getLong("timestamp") * 1000 val now = dateUtil.now() val value = it.getInt("meterValue").toDouble() if (timestamp > now - T.months(1).msecs() && timestamp < now) { calibrations.add( CgmSourceTransaction.Calibration( timestamp = it.getLong("timestamp") * 1000, value = value, glucoseUnit = TherapyEvent.GlucoseUnit.fromConstant(Profile.unit(value)) ) ) } } } } val now = dateUtil.now() val glucoseValuesBundle = bundle.getBundle("glucoseValues") ?: return Result.failure(workDataOf("Error" to "missing glucoseValues")) val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>() for (i in 0 until glucoseValuesBundle.size()) { val glucoseValueBundle = glucoseValuesBundle.getBundle(i.toString())!! val timestamp = glucoseValueBundle.getLong("timestamp") * 1000 // G5 calibration bug workaround (calibration is sent as glucoseValue too) var valid = true if (sourceSensor == GlucoseValue.SourceSensor.DEXCOM_G5_NATIVE) calibrations.forEach { calibration -> if (calibration.timestamp == timestamp) valid = false } // G6 is sending one 24h old changed value causing recalculation. Ignore if (sourceSensor == GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE) if ((now - timestamp) > T.hours(20).msecs()) valid = false if (valid) glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( timestamp = timestamp, value = glucoseValueBundle.getInt("glucoseValue").toDouble(), noise = null, raw = null, trendArrow = GlucoseValue.TrendArrow.fromString(glucoseValueBundle.getString("trendArrow")!!), sourceSensor = sourceSensor ) } var sensorStartTime = if (sp.getBoolean(R.string.key_dexcom_lognssensorchange, false) && bundle.containsKey("sensorInsertionTime")) { bundle.getLong("sensorInsertionTime", 0) * 1000 } else { null } // check start time validity sensorStartTime?.let { if (abs(it - now) > T.months(1).msecs() || it > now) sensorStartTime = null } repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, calibrations, sensorStartTime)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while saving values from Dexcom App", it) ret = Result.failure(workDataOf("Error" to it.toString())) } .blockingGet() .also { result -> // G6 calibration bug workaround (2 additional GVs are created within 1 minute) for (i in result.inserted.indices) { if (sourceSensor == GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE) { if (i < result.inserted.size - 1) { if (abs(result.inserted[i].timestamp - result.inserted[i + 1].timestamp) < T.mins(1).msecs()) { repository.runTransactionForResult(InvalidateGlucoseValueTransaction(result.inserted[i].id)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating BG value", it) } .blockingGet() .also { result1 -> result1.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted and invalidated bg $it") } } repository.runTransactionForResult(InvalidateGlucoseValueTransaction(result.inserted[i + 1].id)) .doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating BG value", it) } .blockingGet() .also { result1 -> result1.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted and invalidated bg $it") } } result.inserted.removeAt(i + 1) result.inserted.removeAt(i) continue } } } xDripBroadcast.send(result.inserted[i]) aapsLogger.debug(LTag.DATABASE, "Inserted bg ${result.inserted[i]}") } result.updated.forEach { xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Updated bg $it") } result.sensorInsertionsInserted.forEach { uel.log( Action.CAREPORTAL, Sources.Dexcom, ValueWithUnit.Timestamp(it.timestamp), ValueWithUnit.TherapyEventType(it.type) ) aapsLogger.debug(LTag.DATABASE, "Inserted sensor insertion $it") } result.calibrationsInserted.forEach { calibration -> calibration.glucose?.let { glucoseValue -> uel.log( Action.CALIBRATION, Sources.Dexcom, ValueWithUnit.Timestamp(calibration.timestamp), ValueWithUnit.TherapyEventType(calibration.type), ValueWithUnit.fromGlucoseUnit(glucoseValue, calibration.glucoseUnit.toString) ) } aapsLogger.debug(LTag.DATABASE, "Inserted calibration $calibration") } } } catch (e: Exception) { aapsLogger.error("Error while processing intent from Dexcom App", e) ret = Result.failure(workDataOf("Error" to e.toString())) } return ret } } companion object { private val PACKAGE_NAMES = arrayOf( "com.dexcom.cgm.region1.mgdl", "com.dexcom.cgm.region1.mmol", "com.dexcom.cgm.region2.mgdl", "com.dexcom.cgm.region2.mmol", "com.dexcom.g6.region1.mmol", "com.dexcom.g6.region2.mgdl", "com.dexcom.g6.region3.mgdl", "com.dexcom.g6.region3.mmol", "com.dexcom.g6" ) const val PERMISSION = "com.dexcom.cgm.EXTERNAL_PERMISSION" } class DexcomMediator @Inject constructor(val context: Context) { fun requestPermissionIfNeeded() { if (ContextCompat.checkSelfPermission(context, PERMISSION) != PackageManager.PERMISSION_GRANTED) { val intent = Intent(context, RequestDexcomPermissionActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(intent) } } fun findDexcomPackageName(): String? { val packageManager = context.packageManager for (packageInfo in packageManager.getInstalledPackages(0)) { if (PACKAGE_NAMES.contains(packageInfo.packageName)) return packageInfo.packageName } return null } } }
agpl-3.0
80fcddced75196fa4c4a17a5b4ee02d8
50.778656
163
0.571298
5.305792
false
false
false
false
abigpotostew/easypolitics
ui/src/main/kotlin/bz/stew/bracken/ui/common/index/NumericDoubleAbstractMappedIndex.kt
1
2204
package bz.stew.bracken.ui.common.index import bz.stew.bracken.ui.util.log.Log /** * Created by stew on 2/10/17. */ abstract class NumericDoubleAbstractMappedIndex<I> : AbstractMappedIndex<Double, I>(null) { private var minKeyCached: Double? = null private var maxKeyCached: Double? = null fun instancesByOperator(operator: IndexOperation, c: Double): Collection<I> { Log.debug({ "$operator comparing $c in map \n\t[[[$forwardMap]]]" }) val out = when (operator) { IndexOperation.GreaterThanOrEqual -> //forwardMap.filterKeys { compareTo(it,instancesWith(c))>=0 }.flattenValueSets() forwardMap.flatMap { Log.debug { ("Comparing $c to ${it.key}") }; if (it.key-c>=0.0) { Log.debug({ "--> PASSED @ ${it.key}" }) it.value } else { Log.debug { "--> FAILED @ ${it.key}" } val emptyList: List<I> = emptyList() emptyList } } IndexOperation.LessThanOrEqual -> //forwardMap.filterKeys { compareTo(it,instancesWith(c))>=0 }.flattenValueSets() forwardMap.flatMap { Log.debug { ("Comparing $c to ${it.key}") }; if (it.key-c<=0.0) { Log.debug({ "--> PASSED @ ${it.key}" }) it.value } else { Log.debug { "--> FAILED @ ${it.key}" } emptyList<I>() //emptyListTyped<I>() } } } Log.debug({ "OUT == [[[\n\t$out]]]" }) return out } /** * 0 is equal */ fun compareTo(key: Double, other: I): Double { return key - map(other) } fun maxKey(): Double { if (this.maxKeyCached == null) { this.maxKeyCached = forwardMap.keys.max() ?: Double.NaN } return this.maxKeyCached ?: Double.NaN } fun minKey(): Double { if (this.minKeyCached == null) { this.minKeyCached = forwardMap.keys.min() ?: Double.NaN } return this.minKeyCached ?: Double.NaN } }
apache-2.0
55a019e3123c9478921171f31720d84a
33.453125
102
0.497731
4.066421
false
false
false
false
Maccimo/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/suggesters/IntroduceVariableSuggester.kt
6
5764
package training.featuresSuggester.suggesters import com.intellij.openapi.ide.CopyPasteManager import com.intellij.psi.PsiElement import training.featuresSuggester.FeatureSuggesterBundle import training.featuresSuggester.NoSuggestion import training.featuresSuggester.SuggesterSupport import training.featuresSuggester.SuggestingUtils.asString import training.featuresSuggester.Suggestion import training.featuresSuggester.actions.* import training.util.WeakReferenceDelegator import java.awt.datatransfer.DataFlavor class IntroduceVariableSuggester : AbstractFeatureSuggester() { override val id: String = "Introduce variable" override val suggestingActionDisplayName: String = FeatureSuggesterBundle.message("introduce.variable.name") override val message = FeatureSuggesterBundle.message("introduce.variable.message") override val suggestingActionId = "IntroduceVariable" override val suggestingTipFileName = "IntroduceVariable.html" override val minSuggestingIntervalDays = 14 override val languages = listOf("JAVA", "kotlin", "Python", "ECMAScript 6") private class ExtractedExpressionData(var exprText: String, changedStatement: PsiElement) { var changedStatement: PsiElement? by WeakReferenceDelegator(changedStatement) val changedStatementText: String var declaration: PsiElement? by WeakReferenceDelegator(null) var variableEditingFinished: Boolean = false init { val text = changedStatement.text changedStatementText = text.replaceFirst(exprText, "").trim() exprText = exprText.trim() } fun getDeclarationText(): String? { return declaration?.let { if (it.isValid) it.text else null } } } private var extractedExprData: ExtractedExpressionData? = null override fun getSuggestion(action: Action): Suggestion { val language = action.language ?: return NoSuggestion val langSupport = SuggesterSupport.getForLanguage(language) ?: return NoSuggestion when (action) { is BeforeEditorTextRemovedAction -> { with(action) { val deletedText = getCopiedContent(textFragment.text) ?: return NoSuggestion val psiFile = this.psiFile ?: return NoSuggestion val contentOffset = caretOffset + textFragment.text.indexOfFirst { it != ' ' && it != '\n' } val curElement = psiFile.findElementAt(contentOffset) ?: return NoSuggestion if (langSupport.isPartOfExpression(curElement)) { val changedStatement = langSupport.getTopmostStatementWithText(curElement, deletedText) ?: return NoSuggestion extractedExprData = ExtractedExpressionData(textFragment.text, changedStatement) } } } is ChildReplacedAction -> { if (extractedExprData == null) return NoSuggestion with(action) { when { langSupport.isVariableDeclarationAdded(this) -> { extractedExprData!!.declaration = newChild } newChild.text.trim() == extractedExprData!!.changedStatementText -> { extractedExprData!!.changedStatement = newChild } langSupport.isVariableInserted(this) -> { extractedExprData = null return createSuggestion() } } } } is ChildAddedAction -> { if (extractedExprData == null) return NoSuggestion with(action) { if (langSupport.isVariableDeclarationAdded(this)) { extractedExprData!!.declaration = newChild } else if (newChild.text.trim() == extractedExprData!!.changedStatementText) { extractedExprData!!.changedStatement = newChild } else if (!extractedExprData!!.variableEditingFinished && isVariableEditingFinished()) { extractedExprData!!.variableEditingFinished = true } } } is ChildrenChangedAction -> { if (extractedExprData == null) return NoSuggestion if (action.parent === extractedExprData!!.declaration && !extractedExprData!!.variableEditingFinished && isVariableEditingFinished() ) { extractedExprData!!.variableEditingFinished = true } } else -> NoSuggestion } return NoSuggestion } private fun getCopiedContent(text: String): String? { if (text.isBlank()) return null val content = text.trim() val copyPasteManager = CopyPasteManager.getInstance() return if (copyPasteManager.areDataFlavorsAvailable(DataFlavor.stringFlavor) && content == copyPasteManager.contents?.asString()?.trim() ) { content } else { null } } private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildReplacedAction): Boolean { return isExpressionStatement(action.oldChild) && isVariableDeclaration(action.newChild) } private fun SuggesterSupport.isVariableDeclarationAdded(action: ChildAddedAction): Boolean { return isCodeBlock(action.parent) && isVariableDeclaration(action.newChild) } private fun isVariableEditingFinished(): Boolean { if (extractedExprData == null) return false with(extractedExprData!!) { val declarationText = getDeclarationText() ?: return false return declarationText.trim().endsWith(exprText) } } private fun SuggesterSupport.isVariableInserted(action: ChildReplacedAction): Boolean { if (extractedExprData == null) return false with(extractedExprData!!) { return variableEditingFinished && declaration.let { it != null && it.isValid && action.newChild.text == getVariableName(it) } && changedStatement === getTopmostStatementWithText(action.newChild, "") } } }
apache-2.0
38004ba18bdb762b2afbdbae1b8abda3
38.479452
110
0.695871
5.521073
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddForLoopIndicesIntention.kt
2
4648
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInsight.template.TemplateBuilderImpl import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class AddForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>( KtForExpression::class.java, KotlinBundle.lazyMessage("add.indices.to.for.loop"), ), LowPriorityAction { override fun applicabilityRange(element: KtForExpression): TextRange? { if (element.loopParameter == null) return null if (element.loopParameter?.destructuringDeclaration != null) return null val loopRange = element.loopRange ?: return null val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA) val resolvedCall = loopRange.getResolvedCall(bindingContext) if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() in WITH_INDEX_FQ_NAMES) return null // already withIndex() call val potentialExpression = createWithIndexExpression(loopRange, reformat = false) val newBindingContext = potentialExpression.analyzeAsReplacement(loopRange, bindingContext) val newResolvedCall = potentialExpression.getResolvedCall(newBindingContext) ?: return null if (newResolvedCall.resultingDescriptor.fqNameUnsafe.asString() !in WITH_INDEX_FQ_NAMES) return null return TextRange(element.startOffset, element.body?.startOffset ?: element.endOffset) } override fun applyTo(element: KtForExpression, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val loopRange = element.loopRange!! val loopParameter = element.loopParameter!! val psiFactory = KtPsiFactory(element) loopRange.replace(createWithIndexExpression(loopRange, reformat = true)) var multiParameter = (psiFactory.createExpressionByPattern( "for((index, $0) in x){}", loopParameter.text ) as KtForExpression).destructuringDeclaration!! multiParameter = loopParameter.replaced(multiParameter) val indexVariable = multiParameter.entries[0] editor.caretModel.moveToOffset(indexVariable.startOffset) runTemplate(editor, element, indexVariable) } private fun runTemplate(editor: Editor, forExpression: KtForExpression, indexVariable: KtDestructuringDeclarationEntry) { PsiDocumentManager.getInstance(forExpression.project).doPostponedOperationsAndUnblockDocument(editor.document) val templateBuilder = TemplateBuilderImpl(forExpression) templateBuilder.replaceElement(indexVariable, ChooseStringExpression(listOf("index", "i"))) when (val body = forExpression.body) { is KtBlockExpression -> { val statement = body.statements.firstOrNull() if (statement != null) { templateBuilder.setEndVariableBefore(statement) } else { templateBuilder.setEndVariableAfter(body.lBrace) } } null -> forExpression.rightParenthesis.let { templateBuilder.setEndVariableAfter(it) } else -> templateBuilder.setEndVariableBefore(body) } templateBuilder.run(editor, true) } private fun createWithIndexExpression(originalExpression: KtExpression, reformat: Boolean): KtExpression = KtPsiFactory(originalExpression).createExpressionByPattern( "$0.$WITH_INDEX_NAME()", originalExpression, reformat = reformat ) companion object { private val WITH_INDEX_NAME = "withIndex" private val WITH_INDEX_FQ_NAMES: Set<String> by lazy { sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet() } } }
apache-2.0
c661ff8f6f1345b2ca95b3441bf7dff4
45.019802
158
0.730852
5.204927
false
false
false
false
livefront/bridge
bridgesample/src/main/java/com/livefront/bridgesample/scenario/fragment/LargeDataFragment.kt
1
3387
package com.livefront.bridgesample.scenario.fragment import android.content.Context import android.graphics.Bitmap import android.os.Bundle import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.evernote.android.state.State import com.livefront.bridgesample.R import com.livefront.bridgesample.base.BridgeBaseFragment import com.livefront.bridgesample.scenario.activity.FragmentData import com.livefront.bridgesample.util.FragmentNavigationManager import kotlinx.android.parcel.Parcelize import kotlinx.android.synthetic.main.activity_large_data.bitmapGeneratorView class LargeDataFragment : BridgeBaseFragment() { override val shouldClearOnDestroy: Boolean get() = getArguments(this).shouldClearOnDestroy @State var savedBitmap: Bitmap? = null private lateinit var fragmentNavigationManager: FragmentNavigationManager override fun onAttach(context: Context) { super.onAttach(context) fragmentNavigationManager = context as FragmentNavigationManager } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.fragment_large_data, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) bitmapGeneratorView.apply { setHeaderText(R.string.large_data_header) generatedBitmap = savedBitmap onBitmapGeneratedListener = { savedBitmap = it } if (getArguments(this@LargeDataFragment).infiniteBackstack) { onNavigateButtonClickListener = { fragmentNavigationManager.navigateTo( newInstance( LargeDataArguments( getArguments(this@LargeDataFragment).shouldClearOnDestroy, infiniteBackstack = true ) ), addToBackstack = true ) } } } } companion object { private const val ARGUMENTS_KEY = "arguments" fun getArguments( fragment: LargeDataFragment ): LargeDataArguments = fragment .requireArguments() .getParcelable(ARGUMENTS_KEY)!! fun getFragmentData( largeDataArguments: LargeDataArguments = LargeDataArguments() ) = FragmentData( R.string.large_data_screen_title, LargeDataFragment::class.java, getInitialArguments(largeDataArguments) ) fun getInitialArguments( largeDataArguments: LargeDataArguments = LargeDataArguments() ) = Bundle().apply { putParcelable(ARGUMENTS_KEY, largeDataArguments) } fun newInstance( largeDataArguments: LargeDataArguments = LargeDataArguments() ) = LargeDataFragment().apply { arguments = getInitialArguments(largeDataArguments) } } } @Parcelize data class LargeDataArguments( val shouldClearOnDestroy: Boolean = true, val infiniteBackstack: Boolean = false ) : Parcelable
apache-2.0
6bffb6c4666579a179e732183d678678
35.031915
102
0.649247
5.543372
false
false
false
false
Hexworks/zircon
zircon.jvm.swing/src/main/kotlin/org/hexworks/zircon/internal/renderer/SwingCanvasRenderer.kt
1
13437
package org.hexworks.zircon.internal.renderer import org.hexworks.cobalt.databinding.api.extension.toProperty import org.hexworks.cobalt.databinding.api.property.Property import org.hexworks.cobalt.events.api.Subscription import org.hexworks.zircon.api.application.Application import org.hexworks.zircon.api.application.CloseBehavior import org.hexworks.zircon.api.application.CursorStyle import org.hexworks.zircon.api.behavior.TilesetHolder import org.hexworks.zircon.api.data.CharacterTile import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.StackedTile import org.hexworks.zircon.api.data.Tile import org.hexworks.zircon.api.graphics.TileGraphics import org.hexworks.zircon.api.modifier.TileTransformModifier import org.hexworks.zircon.api.resource.TilesetResource import org.hexworks.zircon.api.tileset.Tileset import org.hexworks.zircon.api.tileset.TilesetLoader import org.hexworks.zircon.internal.behavior.Observable import org.hexworks.zircon.internal.behavior.impl.DefaultObservable import org.hexworks.zircon.internal.graphics.FastTileGraphics import org.hexworks.zircon.internal.grid.InternalTileGrid import org.hexworks.zircon.internal.tileset.transformer.toAWTColor import org.hexworks.zircon.internal.uievent.KeyboardEventListener import org.hexworks.zircon.internal.uievent.MouseEventListener import org.hexworks.zircon.platform.util.SystemUtils import java.awt.* import java.awt.event.* import java.awt.image.BufferStrategy import javax.swing.JFrame @Suppress("UNCHECKED_CAST") class SwingCanvasRenderer private constructor( val tileGrid: InternalTileGrid, val tilesetLoader: TilesetLoader<Graphics2D>, val canvas: Canvas, val frame: JFrame, val shouldInitializeSwingComponents: Boolean ) : SwingRenderer, Observable<SwingCanvasRenderer> by DefaultObservable() { override val closedValue: Property<Boolean> = false.toProperty() private var blinkOn = true private var lastRender: Long = SystemUtils.getCurrentTimeMs() private var lastBlink: Long = lastRender private val config = tileGrid.config private val keyboardEventListener = KeyboardEventListener() private val mouseEventListener = object : MouseEventListener( fontWidth = tileGrid.tileset.width, fontHeight = tileGrid.tileset.height ) { override fun mouseClicked(e: MouseEvent) { super.mouseClicked(e) canvas.requestFocusInWindow() } } private val gridPositions = tileGrid.size.fetchPositions().toList() /** * Adds a callback [fn] that will be called whenever the frame where the contents * of the [tileGrid] are rendered is closed. */ override fun onFrameClosed(fn: (SwingRenderer) -> Unit): Subscription { return addObserver(fn) } override fun create() { if (closed.not()) { // display settings if (config.fullScreen) { frame.extendedState = JFrame.MAXIMIZED_BOTH } if (config.borderless) { frame.isUndecorated = true } // no resize frame.isResizable = false // rendering frame.addWindowStateListener { if (it.newState == Frame.NORMAL) { render() } } // dimensions canvas.preferredSize = Dimension( tileGrid.widthInPixels, tileGrid.heightInPixels ) canvas.minimumSize = Dimension(tileGrid.tileset.width, tileGrid.tileset.height) // input listeners canvas.addKeyListener(keyboardEventListener) canvas.addMouseListener(mouseEventListener) canvas.addMouseMotionListener(mouseEventListener) canvas.addMouseWheelListener(mouseEventListener) // window closed canvas.addHierarchyListener { e -> if (e.changeFlags == HierarchyEvent.DISPLAYABILITY_CHANGED.toLong()) { if (!e.changed.isDisplayable) { close() } } } // close behavior frame.defaultCloseOperation = when (config.closeBehavior) { CloseBehavior.DO_NOTHING_ON_CLOSE -> JFrame.DO_NOTHING_ON_CLOSE CloseBehavior.EXIT_ON_CLOSE -> JFrame.EXIT_ON_CLOSE } // app stop callback frame.addWindowListener(object : WindowAdapter() { override fun windowClosing(windowEvent: WindowEvent?) { notifyObservers(this@SwingCanvasRenderer) } }) // focus settings canvas.isFocusable = true if (shouldInitializeSwingComponents) { initializeSwingComponents() } // buffering canvas.createBufferStrategy(2) initializeBufferStrategy() } } override fun render() { if (closed.not()) { val now = SystemUtils.getCurrentTimeMs() processInputEvents() tileGrid.updateAnimations(now, tileGrid) val bs: BufferStrategy = canvas.bufferStrategy // this is a regular Swing Canvas object handleBlink(now) canvas.bufferStrategy.drawGraphics.configure().apply { color = Color.BLACK fillRect(0, 0, tileGrid.widthInPixels, tileGrid.heightInPixels) drawTiles(this) if (shouldDrawCursor()) { val tile = tileGrid.getTileAtOrElse(tileGrid.cursorPosition) { Tile.empty() } drawCursor(this, tile, tileGrid.cursorPosition) } dispose() } bs.show() lastRender = now } } override fun close() { if (!closed) { closedValue.value = true tileGrid.close() frame.dispose() } } private fun drawTiles(graphics: Graphics2D) { val layers = fetchLayers() val tiles = mutableListOf<Pair<Tile, TilesetResource>>() gridPositions.forEach { pos -> tiles@ for (i in layers.size - 1 downTo 0) { val (layerPos, layer) = layers[i] val toRender = layer.getTileAtOrNull(pos - layerPos)?.tiles() ?: listOf() for (j in toRender.size - 1 downTo 0) { val tile = toRender[j] val tileset = tile.finalTileset(layer) tiles.add(0, tile to tileset) if (tile.isOpaque) { break@tiles } } } for ((tile, tileset) in tiles) { renderTile( graphics = graphics, position = pos, tile = tile, tileset = tilesetLoader.loadTilesetFrom(tileset) ) } tiles.clear() } } private fun Tile.tiles(): List<Tile> = if (this is StackedTile) { tiles.flatMap { it.tiles() } } else listOf(this) private fun fetchLayers(): List<Pair<Position, TileGraphics>> { return tileGrid.renderables.map { renderable -> val tg = FastTileGraphics( initialSize = renderable.size, initialTileset = renderable.tileset, ) if (!renderable.isHidden) { renderable.render(tg) } renderable.position to tg } } private fun Graphics.configure(): Graphics2D { val gc = this as Graphics2D gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF) gc.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED) gc.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE) gc.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) gc.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF) gc.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED) gc.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY) return gc } private fun renderTile( graphics: Graphics2D, position: Position, tile: Tile, tileset: Tileset<Graphics2D> ) { if (tile.isNotEmpty) { var finalTile = tile finalTile.modifiers.filterIsInstance<TileTransformModifier<CharacterTile>>().forEach { modifier -> if (modifier.canTransform(finalTile)) { (finalTile as? CharacterTile)?.let { finalTile = modifier.transform(it) } } } finalTile = if (tile.isBlinking && blinkOn) { tile.withBackgroundColor(tile.foregroundColor) .withForegroundColor(tile.backgroundColor) } else { tile } ( (finalTile as? TilesetHolder)?.let { tilesetLoader.loadTilesetFrom(it.tileset) } ?: tileset ).drawTile( tile = finalTile, surface = graphics, position = position ) } } private fun processInputEvents() { keyboardEventListener.drainEvents().forEach { (event, phase) -> tileGrid.process(event, phase) } mouseEventListener.drainEvents().forEach { (event, phase) -> tileGrid.process(event, phase) } } private fun handleBlink(now: Long) { if (now > lastBlink + config.blinkLengthInMilliSeconds) { blinkOn = !blinkOn lastBlink = now } } private fun drawCursor(graphics: Graphics, character: Tile, position: Position) { val tileWidth = tileGrid.tileset.width val tileHeight = tileGrid.tileset.height val x = position.x * tileWidth val y = position.y * tileHeight val cursorColor = config.cursorColor.toAWTColor() graphics.color = cursorColor when (config.cursorStyle) { CursorStyle.USE_CHARACTER_FOREGROUND -> { if (blinkOn) { graphics.color = character.foregroundColor.toAWTColor() graphics.fillRect(x, y, tileWidth, tileHeight) } } CursorStyle.FIXED_BACKGROUND -> graphics.fillRect(x, y, tileWidth, tileHeight) CursorStyle.UNDER_BAR -> graphics.fillRect(x, y + tileHeight - 3, tileWidth, 2) CursorStyle.VERTICAL_BAR -> graphics.fillRect(x, y + 1, 2, tileHeight - 2) } } private fun shouldDrawCursor(): Boolean { return tileGrid.isCursorVisible && (config.isCursorBlinking.not() || config.isCursorBlinking && blinkOn) } private tailrec fun initializeBufferStrategy() { val bs = canvas.bufferStrategy var failed = false try { bs.drawGraphics as Graphics2D } catch (e: NullPointerException) { failed = true } if (failed) { initializeBufferStrategy() } } private fun initializeSwingComponents() { canvas.requestFocusInWindow() canvas.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, emptySet<AWTKeyStroke>()) canvas.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, emptySet<AWTKeyStroke>()) frame.pack() frame.isVisible = true frame.setLocationRelativeTo(null) } companion object { /** * Creates a [SwingCanvasRenderer]. */ internal fun create( tileGrid: InternalTileGrid, tilesetLoader: TilesetLoader<Graphics2D>, /** * The grid will be drawn on this [Canvas]. Use this parameter * if you want to provide your own. */ canvas: Canvas, /** * The [JFrame] that will display the [canvas]. Use this parameter * if you want to provide your own. */ frame: JFrame, /** * If set to `false` initializations won't be run on [canvas] and [frame]. * This includes disabling focus traversal (between Swing components) and * displaying and packing the [frame] itself. * Set this to `false` if you want to handle these yourself. A typical example * of this would be the case when you're using multiple [Application]s. */ shouldInitializeSwingComponents: Boolean ): SwingCanvasRenderer = SwingCanvasRenderer( tileGrid = tileGrid, tilesetLoader = tilesetLoader, canvas = canvas, frame = frame, shouldInitializeSwingComponents = shouldInitializeSwingComponents ) } } private fun Tile.finalTileset(graphics: TileGraphics): TilesetResource { return if (this is TilesetHolder) { tileset } else graphics.tileset }
apache-2.0
f6b6bc493b15854991cf981d2cbf52d9
35.914835
115
0.604004
5.025056
false
false
false
false
Tiofx/semester_6
TRPSV/src/main/kotlin/task2/main.kt
1
2489
package task2 import mpi.MPI import task2.test.GenerateValues import task2.test.parallelBellmanFord import task2.test.sequentialBellmanFord fun task2(args: Array<String>) { val vertexNumber = 999 val edgeProbability = 0.9 val iterationNumber = 22 val parallelResult = parallelBellmanFord(args, GenerateValues(vertexNumber, edgeProbability), iterationNumber) if (MPI.COMM_WORLD.Rank() == 0) { val sequentialResult = sequentialBellmanFord(GenerateValues(vertexNumber, edgeProbability), iterationNumber) //TODO: delete println(parallelResult.map { it / 1e6 }) println(sequentialResult.map { it / 1e6 }) println(""" |ะšะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะพั†ะตััะพะฒ: ${MPI.COMM_WORLD.Size()} |ะšะพะปะธั‡ะตัั‚ะฒะพ ะธั‚ะตั€ะฐั†ะธะน: $iterationNumber |============================================= |ะŸะฐั€ะฐะปะปะตะปัŒะฝั‹ะน ะฐะปะณะพั€ะธั‚ะผ: |${parallelResult.drop((iterationNumber * 0.1).toInt()).average() / 1e6} ะผั |==== |ะŸะพัะปะตะดะพะฒะฐั‚ะตะปัŒะฝั‹ะน ะฐะปะณะพั€ะธั‚ะผ: |${sequentialResult.average() / 1e6} ะผั """.trimMargin()) } } //fun sequentialBellmanFord(inputGraph: InputGraph, iterationNumber: Int): MutableList<Long> { // val result = mutableListOf<Long>() // val (adjacencyMatrix, sourceVertex, vertexNumber) = inputGraph // val plainAdjacencyList = adjacencyMatrix.toPlainAdjacencyList() // // repeat(iterationNumber) { // val nanoTime = measureNanoTime { // bellmanFord(plainAdjacencyList, sourceVertex, vertexNumber) // } // result.add(nanoTime) // } // // return result //} // //fun parallelBellmanFord(args: Array<String>, inputGraph: InputGraph, iterationNumber: Int): // MutableList<Long> { // MPI.Init(args) // // val comm = MPI.COMM_WORLD // val rank = comm.Rank() // // val process = if (rank == 0) WorkMaster(inputGraph) else Work() // val result = mutableListOf<Long>() // // repeat(iterationNumber) { // comm.Barrier() // // val nanoTime = measureNanoTime { // process.task1.parallelTask1() // } // //// if (rank == 0) { //// println(process.distance contentEquals bellmanFord(inputGraph)) //// } // // // if (rank == 0) result.add(nanoTime) // // process.reset() // comm.Barrier() // } // // MPI.Finalize() // return result //}
gpl-3.0
8d75c8c81a42ef239e33618384043ab8
28.317073
116
0.605657
3.535294
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/ui/AbstractParameterTablePanel.kt
1
7945
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.introduce.ui import com.intellij.ui.BooleanTableCellRenderer import com.intellij.ui.TableUtil import com.intellij.ui.ToolbarDecorator import com.intellij.ui.table.JBTable import com.intellij.util.ui.EditableModel import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.psi.psiUtil.isIdentifier import java.awt.BorderLayout import java.awt.Component import java.awt.Dimension import java.awt.event.ActionEvent import java.awt.event.KeyEvent import javax.swing.* import javax.swing.table.AbstractTableModel import kotlin.math.max import kotlin.math.min abstract class AbstractParameterTablePanel<Param, UIParam : AbstractParameterTablePanel.AbstractParameterInfo<Param>> : JPanel(BorderLayout()) { companion object { val CHECKMARK_COLUMN = 0 val PARAMETER_NAME_COLUMN = 1 } abstract class AbstractParameterInfo<out Param>(val originalParameter: Param) { var isEnabled = true lateinit var name: String abstract fun toParameter(): Param } protected lateinit var parameterInfos: MutableList<UIParam> lateinit var table: JBTable private set protected lateinit var tableModel: TableModelBase private set protected open fun createTableModel() = TableModelBase() protected open fun createAdditionalColumns() { } fun init() { tableModel = createTableModel() table = JBTable(tableModel) val defaultEditor = table.getDefaultEditor(Any::class.java) as DefaultCellEditor defaultEditor.clickCountToStart = 1 table.selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION table.cellSelectionEnabled = true with(table.columnModel.getColumn(CHECKMARK_COLUMN)) { TableUtil.setupCheckboxColumn(this) headerValue = "" cellRenderer = object : BooleanTableCellRenderer() { override fun getTableCellRendererComponent( table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int ): Component { val rendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) rendererComponent.isEnabled = [email protected] (rendererComponent as JCheckBox).addActionListener { updateSignature() } return rendererComponent } } } table.columnModel.getColumn(PARAMETER_NAME_COLUMN).headerValue = KotlinBundle.message("text.Name") createAdditionalColumns() table.preferredScrollableViewportSize = Dimension(250, table.rowHeight * 5) table.setShowGrid(false) table.intercellSpacing = Dimension(0, 0) @NonNls val inputMap = table.inputMap @NonNls val actionMap = table.actionMap // SPACE: toggle enable/disable inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "enable_disable") actionMap.put("enable_disable", object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { if (table.isEditing) return val rows = table.selectedRows if (rows.size > 0) { var valueToBeSet = false for (row in rows) { if (!parameterInfos[row].isEnabled) { valueToBeSet = true break } } for (row in rows) { parameterInfos[row].isEnabled = valueToBeSet } tableModel.fireTableRowsUpdated(rows[0], rows[rows.size - 1]) TableUtil.selectRows(table, rows) updateSignature() } } }) // make ENTER work when the table has focus inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "invoke_impl") actionMap.put("invoke_impl", object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { table.cellEditor?.stopCellEditing() ?: onEnterAction() } }) // make ESCAPE work when the table has focus actionMap.put("doCancel", object : AbstractAction() { override fun actionPerformed(e: ActionEvent) { table.cellEditor?.stopCellEditing() ?: onCancelAction() } }) val listPanel = ToolbarDecorator.createDecorator(table).disableAddAction().disableRemoveAction().createPanel() add(listPanel, BorderLayout.CENTER) } protected open fun updateSignature() { } protected open fun onEnterAction() { } protected open fun onCancelAction() { } protected open fun isCheckMarkColumnEditable() = true protected open inner class TableModelBase : AbstractTableModel(), EditableModel { override fun addRow() = throw IllegalAccessError("Not implemented") override fun removeRow(index: Int) = throw IllegalAccessError("Not implemented") override fun exchangeRows(oldIndex: Int, newIndex: Int) { if (oldIndex < 0 || newIndex < 0) return if (oldIndex >= parameterInfos.size || newIndex >= parameterInfos.size) return val old = parameterInfos[oldIndex] parameterInfos[oldIndex] = parameterInfos[newIndex] parameterInfos[newIndex] = old fireTableRowsUpdated(min(oldIndex, newIndex), max(oldIndex, newIndex)) updateSignature() } override fun canExchangeRows(oldIndex: Int, newIndex: Int): Boolean { return when { oldIndex < 0 || newIndex < 0 -> false oldIndex >= parameterInfos.size || newIndex >= parameterInfos.size -> false else -> true } } override fun getColumnCount() = 2 override fun getRowCount() = parameterInfos.size override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { return when (columnIndex) { CHECKMARK_COLUMN -> parameterInfos[rowIndex].isEnabled PARAMETER_NAME_COLUMN -> parameterInfos[rowIndex].name else -> null } } override fun setValueAt(aValue: Any?, rowIndex: Int, columnIndex: Int) { val info = parameterInfos[rowIndex] when (columnIndex) { CHECKMARK_COLUMN -> { info.isEnabled = aValue as Boolean fireTableRowsUpdated(rowIndex, rowIndex) table.selectionModel.setSelectionInterval(rowIndex, rowIndex) updateSignature() } PARAMETER_NAME_COLUMN -> { val name = aValue as String if (name.isIdentifier()) { info.name = name } updateSignature() } } } override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { val info = parameterInfos[rowIndex] return when (columnIndex) { CHECKMARK_COLUMN -> isEnabled && isCheckMarkColumnEditable() PARAMETER_NAME_COLUMN -> isEnabled && info.isEnabled else -> false } } override fun getColumnClass(columnIndex: Int): Class<*> { if (columnIndex == CHECKMARK_COLUMN) return Boolean::class.java return super.getColumnClass(columnIndex) } } }
apache-2.0
841a43d3a381db0bb39bd8ce5bd0283b
35.953488
158
0.612838
5.382791
false
false
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/notification/impl/NotificationsToolWindow.kt
1
53042
// 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.notification.impl import com.intellij.UtilBundle import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.ide.IdeBundle import com.intellij.ide.ui.LafManagerListener import com.intellij.idea.ActionsBundle import com.intellij.notification.ActionCenter import com.intellij.notification.EventLog import com.intellij.notification.LogModel import com.intellij.notification.Notification import com.intellij.notification.impl.ui.NotificationsUtil import com.intellij.notification.impl.widget.IdeNotificationArea import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Divider import com.intellij.openapi.ui.NullableComponent import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Clock import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.ToolWindowEx import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.ui.* import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBOptionButton import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.content.ContentFactory import com.intellij.ui.scale.JBUIScale import com.intellij.util.Alarm import com.intellij.util.text.DateFormatUtil import com.intellij.util.ui.* import org.jetbrains.annotations.Nls import java.awt.* import java.awt.event.* import java.util.* import java.util.function.Consumer import javax.accessibility.AccessibleContext import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.HyperlinkEvent import javax.swing.event.PopupMenuEvent import javax.swing.text.JTextComponent internal class NotificationsToolWindowFactory : ToolWindowFactory, DumbAware { companion object { const val ID = "Notifications" internal const val CLEAR_ACTION_ID = "ClearAllNotifications" internal val myModel = ApplicationNotificationModel() fun addNotification(project: Project?, notification: Notification) { if (ActionCenter.isEnabled() && notification.canShowFor(project)) { myModel.addNotification(project, notification) } } fun expire(notification: Notification) { myModel.expire(notification) } fun expireAll() { myModel.expireAll() } fun clearAll(project: Project?) { myModel.clearAll(project) } fun getStateNotifications(project: Project) = myModel.getStateNotifications(project) fun getNotifications(project: Project?) = myModel.getNotifications(project) } override fun isApplicable(project: Project) = ActionCenter.isEnabled() override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { NotificationContent(project, toolWindow) } } internal class NotificationContent(val project: Project, private val toolWindow: ToolWindow) : Disposable, ToolWindowManagerListener { private val myMainPanel = JBPanelWithEmptyText(BorderLayout()) private val myNotifications = ArrayList<Notification>() private val myIconNotifications = ArrayList<Notification>() private val suggestions: NotificationGroupComponent private val timeline: NotificationGroupComponent private val searchController: SearchController private val singleSelectionHandler = SingleTextSelectionHandler() private var myVisible = true private val mySearchUpdateAlarm = Alarm() init { myMainPanel.background = NotificationComponent.BG_COLOR setEmptyState() handleFocus() suggestions = NotificationGroupComponent(this, true, project) timeline = NotificationGroupComponent(this, false, project) searchController = SearchController(this, suggestions, timeline) myMainPanel.add(createSearchComponent(toolWindow), BorderLayout.NORTH) createGearActions() val splitter = MySplitter() splitter.firstComponent = suggestions splitter.secondComponent = timeline myMainPanel.add(splitter) suggestions.setRemoveCallback(Consumer(::remove)) timeline.setClearCallback(::clear) Disposer.register(toolWindow.disposable, this) val content = ContentFactory.getInstance().createContent(myMainPanel, "", false) content.preferredFocusableComponent = myMainPanel val contentManager = toolWindow.contentManager contentManager.addContent(content) contentManager.setSelectedContent(content) project.messageBus.connect(toolWindow.disposable).subscribe(ToolWindowManagerListener.TOPIC, this) ApplicationManager.getApplication().messageBus.connect(toolWindow.disposable).subscribe(LafManagerListener.TOPIC, LafManagerListener { suggestions.updateLaf() timeline.updateLaf() }) val newNotifications = ArrayList<Notification>() NotificationsToolWindowFactory.myModel.registerAndGetInitNotifications(this, newNotifications) for (notification in newNotifications) { add(notification) } } private fun createSearchComponent(toolWindow: ToolWindow): SearchTextField { val searchField = object : SearchTextField() { override fun updateUI() { super.updateUI() textEditor?.border = null } override fun preprocessEventForTextField(event: KeyEvent): Boolean { if (event.keyCode == KeyEvent.VK_ESCAPE && event.id == KeyEvent.KEY_PRESSED) { isVisible = false searchController.cancelSearch() return true } return super.preprocessEventForTextField(event) } } searchField.textEditor.border = null searchField.border = JBUI.Borders.customLineBottom(JBColor.border()) searchField.isVisible = false if (ExperimentalUI.isNewUI()) { searchController.background = JBUI.CurrentTheme.ToolWindow.background() searchField.textEditor.background = searchController.background } else { searchController.background = UIUtil.getTextFieldBackground() } searchController.searchField = searchField searchField.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { mySearchUpdateAlarm.cancelAllRequests() mySearchUpdateAlarm.addRequest(searchController::doSearch, 100, ModalityState.stateForComponent(searchField)) } }) return searchField } private fun createGearActions() { val gearAction = object : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { searchController.startSearch() } } val actionManager = ActionManager.getInstance() val findAction = actionManager.getAction(IdeActions.ACTION_FIND) if (findAction == null) { gearAction.templatePresentation.text = ActionsBundle.actionText(IdeActions.ACTION_FIND) } else { gearAction.copyFrom(findAction) gearAction.registerCustomShortcutSet(findAction.shortcutSet, myMainPanel) } val group = DefaultActionGroup() group.add(gearAction) group.addSeparator() val clearAction = actionManager.getAction(NotificationsToolWindowFactory.CLEAR_ACTION_ID) if (clearAction != null) { group.add(clearAction) } val markAction = actionManager.getAction("MarkNotificationsAsRead") if (markAction != null) { group.add(markAction) } (toolWindow as ToolWindowEx).setAdditionalGearActions(group) } fun setEmptyState() { myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.first.line")) @Suppress("DialogTitleCapitalization") myMainPanel.emptyText.appendLine(IdeBundle.message("notifications.toolwindow.empty.text.second.line")) } fun clearEmptyState() { myMainPanel.emptyText.clear() } private fun handleFocus() { val listener = AWTEventListener { if (it is MouseEvent && it.id == MouseEvent.MOUSE_PRESSED && !toolWindow.isActive && UIUtil.isAncestor(myMainPanel, it.component)) { it.component.requestFocus() } } Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.MOUSE_EVENT_MASK) Disposer.register(toolWindow.disposable, Disposable { Toolkit.getDefaultToolkit().removeAWTEventListener(listener) }) } fun add(notification: Notification) { if (!NotificationsConfigurationImpl.getSettings(notification.groupId).isShouldLog) { return } if (notification.isSuggestionType) { suggestions.add(notification, singleSelectionHandler) } else { timeline.add(notification, singleSelectionHandler) } myNotifications.add(notification) myIconNotifications.add(notification) searchController.update() setStatusMessage(notification) updateIcon() } fun getStateNotifications() = ArrayList(myIconNotifications) fun getNotifications() = ArrayList(myNotifications) fun isEmpty() = suggestions.isEmpty() && timeline.isEmpty() fun expire(notification: Notification?) { if (notification == null) { val notifications = ArrayList(myNotifications) myNotifications.clear() myIconNotifications.clear() suggestions.expireAll() timeline.expireAll() searchController.update() setStatusMessage(null) updateIcon() for (n in notifications) { n.expire() } } else { remove(notification) } } private fun remove(notification: Notification) { if (notification.isSuggestionType) { suggestions.remove(notification) } else { timeline.remove(notification) } myNotifications.remove(notification) myIconNotifications.remove(notification) searchController.update() setStatusMessage() updateIcon() } private fun clear(notifications: List<Notification>) { myNotifications.removeAll(notifications) myIconNotifications.removeAll(notifications) searchController.update() setStatusMessage() updateIcon() } fun clearAll() { project.closeAllBalloons() myNotifications.clear() myIconNotifications.clear() suggestions.clear() timeline.clear() searchController.update() setStatusMessage(null) updateIcon() } override fun stateChanged(toolWindowManager: ToolWindowManager) { val visible = toolWindow.isVisible if (myVisible != visible) { myVisible = visible if (visible) { project.closeAllBalloons() suggestions.updateComponents() timeline.updateComponents() } else { suggestions.clearNewState() timeline.clearNewState() myIconNotifications.clear() updateIcon() } } } private fun updateIcon() { toolWindow.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(myIconNotifications)) LogModel.fireModelChanged() } private fun setStatusMessage() { setStatusMessage(myNotifications.findLast { it.isImportant || it.isImportantSuggestion }) } private fun setStatusMessage(notification: Notification?) { EventLog.getLogModel(project).setStatusMessage(notification) } override fun dispose() { NotificationsToolWindowFactory.myModel.unregister(this) Disposer.dispose(mySearchUpdateAlarm) } fun fullRepaint() { myMainPanel.doLayout() myMainPanel.revalidate() myMainPanel.repaint() } } private class MySplitter : OnePixelSplitter(true, .5f) { override fun createDivider(): Divider { return object : OnePixelDivider(true, this) { override fun setVisible(aFlag: Boolean) { super.setVisible(aFlag) setResizeEnabled(aFlag) if (!aFlag) { setBounds(0, 0, 0, 0) } } override fun setBackground(bg: Color?) { super.setBackground(JBColor.border()) } } } } private fun JComponent.mediumFontFunction() { font = JBFont.medium() val f: (JComponent) -> Unit = { it.font = JBFont.medium() } putClientProperty(NotificationGroupComponent.FONT_KEY, f) } private fun JComponent.smallFontFunction() { font = JBFont.small() val f: (JComponent) -> Unit = { it.font = JBFont.small() } putClientProperty(NotificationGroupComponent.FONT_KEY, f) } private class SearchController(private val mainContent: NotificationContent, private val suggestions: NotificationGroupComponent, private val timeline: NotificationGroupComponent) { lateinit var searchField: SearchTextField lateinit var background: Color fun startSearch() { searchField.isVisible = true searchField.selectText() searchField.requestFocus() mainContent.clearEmptyState() if (searchField.text.isNotEmpty()) { doSearch() } } fun doSearch() { val query = searchField.text if (query.isEmpty()) { searchField.textEditor.background = background clearSearch() return } var result = false val function: (NotificationComponent) -> Unit = { if (it.applySearchQuery(query)) { result = true } } suggestions.iterateComponents(function) timeline.iterateComponents(function) searchField.textEditor.background = if (result) background else LightColors.RED mainContent.fullRepaint() } fun update() { if (searchField.isVisible && searchField.text.isNotEmpty()) { doSearch() } } fun cancelSearch() { mainContent.setEmptyState() clearSearch() } private fun clearSearch() { val function: (NotificationComponent) -> Unit = { it.applySearchQuery(null) } suggestions.iterateComponents(function) timeline.iterateComponents(function) mainContent.fullRepaint() } } private class NotificationGroupComponent(private val myMainContent: NotificationContent, private val mySuggestionType: Boolean, private val myProject: Project) : JBPanel<NotificationGroupComponent>(BorderLayout()), NullableComponent { companion object { const val FONT_KEY = "FontFunction" } private val myTitle = JBLabel( IdeBundle.message(if (mySuggestionType) "notifications.toolwindow.suggestions" else "notifications.toolwindow.timeline")) private val myList = JPanel(VerticalLayout(JBUI.scale(10))) private val myScrollPane = object : JBScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) { override fun setupCorners() { super.setupCorners() border = null } override fun updateUI() { super.updateUI() border = null } } private var myScrollValue = 0 private val myEventHandler = ComponentEventHandler() private val myTimeComponents = ArrayList<JLabel>() private val myTimeAlarm = Alarm(myProject) private lateinit var myClearCallback: (List<Notification>) -> Unit private lateinit var myRemoveCallback: Consumer<Notification> init { background = NotificationComponent.BG_COLOR val mainPanel = JPanel(BorderLayout(0, JBUI.scale(8))) mainPanel.isOpaque = false mainPanel.border = JBUI.Borders.empty(8, 8, 0, 0) add(mainPanel) myTitle.mediumFontFunction() myTitle.foreground = NotificationComponent.INFO_COLOR if (mySuggestionType) { myTitle.border = JBUI.Borders.emptyLeft(10) mainPanel.add(myTitle, BorderLayout.NORTH) } else { val panel = JPanel(BorderLayout()) panel.isOpaque = false panel.border = JBUI.Borders.emptyLeft(10) panel.add(myTitle, BorderLayout.WEST) val clearAll = LinkLabel(IdeBundle.message("notifications.toolwindow.timeline.clear.all"), null) { _: LinkLabel<Unit>, _: Unit? -> clearAll() } clearAll.mediumFontFunction() clearAll.border = JBUI.Borders.emptyRight(20) panel.add(clearAll, BorderLayout.EAST) mainPanel.add(panel, BorderLayout.NORTH) } myList.isOpaque = true myList.background = NotificationComponent.BG_COLOR myList.border = JBUI.Borders.emptyRight(10) myScrollPane.border = null mainPanel.add(myScrollPane) myScrollPane.verticalScrollBar.addAdjustmentListener { val value = it.value if (myScrollValue == 0 && value > 0 || myScrollValue > 0 && value == 0) { myScrollValue = value repaint() } else { myScrollValue = value } } myEventHandler.add(this) } fun updateLaf() { updateComponents() iterateComponents { it.updateLaf() } } override fun paintComponent(g: Graphics) { super.paintComponent(g) if (myScrollValue > 0) { g.color = JBColor.border() val y = myScrollPane.y - 1 g.drawLine(0, y, width, y) } } fun add(notification: Notification, singleSelectionHandler: SingleTextSelectionHandler) { val component = NotificationComponent(myProject, notification, myTimeComponents, singleSelectionHandler) component.setNew(true) myList.add(component, 0) updateLayout() myEventHandler.add(component) updateContent() if (mySuggestionType) { component.setDoNotAskHandler { forProject -> component.myNotificationWrapper.notification!! .setDoNotAskFor(if (forProject) myProject else null) .also { myRemoveCallback.accept(it) } .hideBalloon() } component.setRemoveCallback(myRemoveCallback) } } private fun updateLayout() { val layout = myList.layout iterateComponents { component -> layout.removeLayoutComponent(component) layout.addLayoutComponent(null, component) } } fun isEmpty(): Boolean { val count = myList.componentCount for (i in 0 until count) { if (myList.getComponent(i) is NotificationComponent) { return false } } return true } fun setRemoveCallback(callback: Consumer<Notification>) { myRemoveCallback = callback } fun remove(notification: Notification) { val count = myList.componentCount for (i in 0 until count) { val component = myList.getComponent(i) as NotificationComponent if (component.myNotificationWrapper.notification === notification) { if (notification.isSuggestionType) { component.removeFromParent() myList.remove(i) } else { component.expire() } break } } updateContent() } fun setClearCallback(callback: (List<Notification>) -> Unit) { myClearCallback = callback } private fun clearAll() { myProject.closeAllBalloons() val notifications = ArrayList<Notification>() iterateComponents { val notification = it.myNotificationWrapper.notification if (notification != null) { notifications.add(notification) } } clear() myClearCallback.invoke(notifications) } fun expireAll() { if (mySuggestionType) { clear() } else { iterateComponents { if (it.myNotificationWrapper.notification != null) { it.expire() } } updateContent() } } fun clear() { iterateComponents { it.removeFromParent() } myList.removeAll() updateContent() } fun clearNewState() { iterateComponents { it.setNew(false) } } fun updateComponents() { UIUtil.uiTraverser(this).filter(JComponent::class.java).forEach { val value = it.getClientProperty(FONT_KEY) if (value != null) { (value as (JComponent) -> Unit).invoke(it) } } myMainContent.fullRepaint() } inline fun iterateComponents(f: (NotificationComponent) -> Unit) { val count = myList.componentCount for (i in 0 until count) { f.invoke(myList.getComponent(i) as NotificationComponent) } } private fun updateContent() { if (!mySuggestionType && !myTimeAlarm.isDisposed) { myTimeAlarm.cancelAllRequests() object : Runnable { override fun run() { for (timeComponent in myTimeComponents) { timeComponent.text = formatPrettyDateTime(timeComponent.getClientProperty(NotificationComponent.TIME_KEY) as Long) } if (myTimeComponents.isNotEmpty() && !myTimeAlarm.isDisposed) { myTimeAlarm.addRequest(this, 30000) } } }.run() } myMainContent.fullRepaint() } private fun formatPrettyDateTime(time: Long): @NlsSafe String { val c = Calendar.getInstance() c.timeInMillis = Clock.getTime() val currentYear = c[Calendar.YEAR] val currentDayOfYear = c[Calendar.DAY_OF_YEAR] c.timeInMillis = time val year = c[Calendar.YEAR] val dayOfYear = c[Calendar.DAY_OF_YEAR] if (currentYear == year && currentDayOfYear == dayOfYear) { return DateFormatUtil.formatTime(time) } val isYesterdayOnPreviousYear = currentYear == year + 1 && currentDayOfYear == 1 && dayOfYear == c.getActualMaximum( Calendar.DAY_OF_YEAR) val isYesterday = isYesterdayOnPreviousYear || currentYear == year && currentDayOfYear == dayOfYear + 1 if (isYesterday) { return UtilBundle.message("date.format.yesterday") } return DateFormatUtil.formatDate(time) } override fun isVisible(): Boolean { if (super.isVisible()) { val count = myList.componentCount for (i in 0 until count) { if (myList.getComponent(i).isVisible) { return true } } } return false } override fun isNull(): Boolean = !isVisible } private class NotificationComponent(val project: Project, notification: Notification, timeComponents: ArrayList<JLabel>, val singleSelectionHandler: SingleTextSelectionHandler) : JBPanel<NotificationComponent>() { companion object { val BG_COLOR: Color get() { if (ExperimentalUI.isNewUI()) { return JBUI.CurrentTheme.ToolWindow.background() } return UIUtil.getListBackground() } val INFO_COLOR = JBColor.namedColor("Label.infoForeground", JBColor(Gray.x80, Gray.x8C)) internal const val NEW_COLOR_NAME = "NotificationsToolwindow.newNotification.background" internal val NEW_DEFAULT_COLOR = JBColor(0xE6EEF7, 0x45494A) val NEW_COLOR = JBColor.namedColor(NEW_COLOR_NAME, NEW_DEFAULT_COLOR) val NEW_HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.newNotification.hoverBackground", JBColor(0xE6EEF7, 0x45494A)) val HOVER_COLOR = JBColor.namedColor("NotificationsToolwindow.Notification.hoverBackground", BG_COLOR) const val TIME_KEY = "TimestampKey" } val myNotificationWrapper = NotificationWrapper(notification) private var myIsNew = false private var myHoverState = false private val myMoreButton: Component? private var myMorePopupVisible = false private var myRoundColor = BG_COLOR private lateinit var myDoNotAskHandler: (Boolean) -> Unit private lateinit var myRemoveCallback: Consumer<Notification> private var myMorePopup: JBPopup? = null var myMoreAwtPopup: JPopupMenu? = null var myDropDownPopup: JPopupMenu? = null private var myLafUpdater: Runnable? = null init { isOpaque = true background = BG_COLOR border = JBUI.Borders.empty(10, 10, 10, 0) layout = object : BorderLayout(JBUI.scale(7), 0) { private var myEastComponent: Component? = null override fun addLayoutComponent(name: String?, comp: Component) { if (EAST == name) { myEastComponent = comp } else { super.addLayoutComponent(name, comp) } } override fun layoutContainer(target: Container) { super.layoutContainer(target) if (myEastComponent != null && myEastComponent!!.isVisible) { val insets = target.insets val height = target.height - insets.bottom - insets.top val component = myEastComponent!! component.setSize(component.width, height) val d = component.preferredSize component.setBounds(target.width - insets.right - d.width, insets.top, d.width, height) } } } val iconPanel = JPanel(BorderLayout()) iconPanel.isOpaque = false iconPanel.add(JBLabel(NotificationsUtil.getIcon(notification)), BorderLayout.NORTH) add(iconPanel, BorderLayout.WEST) val centerPanel = JPanel(VerticalLayout(JBUI.scale(8))) centerPanel.isOpaque = false centerPanel.border = JBUI.Borders.emptyRight(10) var titlePanel: JPanel? = null if (notification.hasTitle()) { val titleContent = NotificationsUtil.buildHtml(notification, null, false, null, null) val title = object : JBLabel(titleContent) { override fun updateUI() { val oldEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java) if (oldEditor != null) { singleSelectionHandler.remove(oldEditor) } super.updateUI() val newEditor = UIUtil.findComponentOfType(this, JEditorPane::class.java) if (newEditor != null) { singleSelectionHandler.add(newEditor, true) } } } try { title.setCopyable(true) } catch (_: Exception) { } NotificationsManagerImpl.setTextAccessibleName(title, titleContent) val editor = UIUtil.findComponentOfType(title, JEditorPane::class.java) if (editor != null) { singleSelectionHandler.add(editor, true) } if (notification.isSuggestionType) { centerPanel.add(title) } else { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false titlePanel.add(title) centerPanel.add(titlePanel) } } if (notification.hasContent()) { val textContent = NotificationsUtil.buildFullContent(notification) val textComponent = createTextComponent(textContent) NotificationsManagerImpl.setTextAccessibleName(textComponent, textContent) singleSelectionHandler.add(textComponent, true) if (!notification.hasTitle() && !notification.isSuggestionType) { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false titlePanel.add(textComponent) centerPanel.add(titlePanel) } else { centerPanel.add(textComponent) } } val actions = notification.actions val actionsSize = actions.size val helpAction = notification.contextHelpAction if (actionsSize > 0 || helpAction != null) { val layout = HorizontalLayout(JBUIScale.scale(16)) val actionPanel = JPanel(if (!notification.isSuggestionType && actions.size > 1) DropDownActionLayout(layout) else layout) actionPanel.isOpaque = false if (notification.isSuggestionType) { if (actionsSize > 0) { val button = JButton(actions[0].templateText) button.isOpaque = false button.addActionListener { runAction(actions[0], it.source) } actionPanel.add(button) if (actionsSize == 2) { actionPanel.add(createAction(actions[1])) } else if (actionsSize > 2) { actionPanel.add(MoreAction(this, actions)) } } } else { if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST) { actionPanel.add(MyDropDownAction(this)) } for (action in actions) { actionPanel.add(createAction(action)) } if (actionsSize > 1 && notification.collapseDirection == Notification.CollapseActionsDirection.KEEP_LEFTMOST) { actionPanel.add(MyDropDownAction(this)) } } if (helpAction != null) { val presentation = helpAction.templatePresentation val helpLabel = ContextHelpLabel.create(StringUtil.defaultIfEmpty(presentation.text, ""), presentation.description) helpLabel.foreground = UIUtil.getLabelDisabledForeground() actionPanel.add(helpLabel) } if (!notification.hasTitle() && !notification.hasContent() && !notification.isSuggestionType) { titlePanel = JPanel(BorderLayout()) titlePanel.isOpaque = false actionPanel.add(titlePanel, HorizontalLayout.RIGHT) } centerPanel.add(actionPanel) } add(centerPanel) if (notification.isSuggestionType) { val group = DefaultActionGroup() group.isPopup = true if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) { group.add(object : DumbAwareAction(IdeBundle.message("action.text.settings")) { override fun actionPerformed(e: AnActionEvent) { doShowSettings() } }) group.addSeparator() } val remindAction = RemindLaterManager.createAction(notification, DateFormatUtil.DAY) if (remindAction != null) { @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.remind.tomorrow")) { override fun actionPerformed(e: AnActionEvent) { remindAction.run() myRemoveCallback.accept(myNotificationWrapper.notification!!) myNotificationWrapper.notification!!.hideBalloon() } }) } @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again.for.this.project")) { override fun actionPerformed(e: AnActionEvent) { myDoNotAskHandler.invoke(true) } }) @Suppress("DialogTitleCapitalization") group.add(object : DumbAwareAction(IdeBundle.message("notifications.toolwindow.dont.show.again")) { override fun actionPerformed(e: AnActionEvent) { myDoNotAskHandler.invoke(false) } }) val presentation = Presentation() presentation.icon = AllIcons.Actions.More presentation.putClientProperty(ActionButton.HIDE_DROPDOWN_ICON, java.lang.Boolean.TRUE) val button = object : ActionButton(group, presentation, ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) { override fun createAndShowActionGroupPopup(actionGroup: ActionGroup, event: AnActionEvent): JBPopup { myMorePopupVisible = true val popup = super.createAndShowActionGroupPopup(actionGroup, event) myMorePopup = popup popup.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { myMorePopup = null ApplicationManager.getApplication().invokeLater { myMorePopupVisible = false isVisible = myHoverState } } }) return popup } } button.border = JBUI.Borders.emptyRight(5) button.isVisible = false myMoreButton = button val eastPanel = JPanel(BorderLayout()) eastPanel.isOpaque = false eastPanel.add(button, BorderLayout.NORTH) add(eastPanel, BorderLayout.EAST) setComponentZOrder(eastPanel, 0) } else { val timeComponent = JBLabel(DateFormatUtil.formatPrettyDateTime(notification.timestamp)) timeComponent.putClientProperty(TIME_KEY, notification.timestamp) timeComponent.verticalAlignment = SwingConstants.TOP timeComponent.verticalTextPosition = SwingConstants.TOP timeComponent.toolTipText = DateFormatUtil.formatDateTime(notification.timestamp) timeComponent.border = JBUI.Borders.emptyRight(10) timeComponent.smallFontFunction() timeComponent.foreground = INFO_COLOR timeComponents.add(timeComponent) if (NotificationsConfigurationImpl.getInstanceImpl().isRegistered(notification.groupId)) { val button = object: InplaceButton(IdeBundle.message("tooltip.turn.notification.off"), AllIcons.Ide.Notification.Gear, ActionListener { doShowSettings() }) { override fun setBounds(x: Int, y: Int, width: Int, height: Int) { super.setBounds(x, y - 1, width, height) } } button.setIcons(AllIcons.Ide.Notification.Gear, null, AllIcons.Ide.Notification.GearHover) myMoreButton = button val buttonWrapper = JPanel(BorderLayout()) buttonWrapper.isOpaque = false buttonWrapper.border = JBUI.Borders.emptyRight(10) buttonWrapper.add(button, BorderLayout.NORTH) buttonWrapper.preferredSize = buttonWrapper.preferredSize button.isVisible = false val eastPanel = JPanel(BorderLayout()) eastPanel.isOpaque = false eastPanel.add(buttonWrapper, BorderLayout.WEST) eastPanel.add(timeComponent, BorderLayout.EAST) titlePanel!!.add(eastPanel, BorderLayout.EAST) } else { titlePanel!!.add(timeComponent, BorderLayout.EAST) myMoreButton = null } } } private fun createAction(action: AnAction): JComponent { return object : LinkLabel<AnAction>(action.templateText, action.templatePresentation.icon, { link, _action -> runAction(_action, link) }, action) { override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } } private fun doShowSettings() { NotificationCollector.getInstance().logNotificationSettingsClicked(myNotificationWrapper.id, myNotificationWrapper.displayId, myNotificationWrapper.groupId) val configurable = NotificationsConfigurable() ShowSettingsUtil.getInstance().editConfigurable(project, configurable, Runnable { val runnable = configurable.enableSearch(myNotificationWrapper.groupId) runnable?.run() }) } private fun runAction(action: AnAction, component: Any) { setNew(false) NotificationCollector.getInstance().logNotificationActionInvoked(null, myNotificationWrapper.notification!!, action, NotificationCollector.NotificationPlace.ACTION_CENTER) Notification.fire(myNotificationWrapper.notification!!, action, DataManager.getInstance().getDataContext(component as Component)) } fun expire() { closePopups() myNotificationWrapper.notification = null setNew(false) for (component in UIUtil.findComponentsOfType(this, LinkLabel::class.java)) { component.isEnabled = false } val dropDownAction = UIUtil.findComponentOfType(this, MyDropDownAction::class.java) if (dropDownAction != null) { DataManager.removeDataProvider(dropDownAction) } } fun removeFromParent() { closePopups() for (component in UIUtil.findComponentsOfType(this, JTextComponent::class.java)) { singleSelectionHandler.remove(component) } } private fun closePopups() { myMorePopup?.cancel() myMoreAwtPopup?.isVisible = false myDropDownPopup?.isVisible = false } private fun createTextComponent(text: @Nls String): JEditorPane { val component = JEditorPane() component.isEditable = false component.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, java.lang.Boolean.TRUE) component.contentType = "text/html" component.isOpaque = false component.border = null NotificationsUtil.configureHtmlEditorKit(component, false) if (myNotificationWrapper.notification!!.listener != null) { component.addHyperlinkListener { e -> val notification = myNotificationWrapper.notification if (notification != null && e.eventType == HyperlinkEvent.EventType.ACTIVATED) { val listener = notification.listener if (listener != null) { NotificationCollector.getInstance().logHyperlinkClicked(notification) listener.hyperlinkUpdate(notification, e) } } } } component.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, StringUtil.unescapeXmlEntities(StringUtil.stripHtml(text, " "))) component.text = text component.isEditable = false if (component.caret != null) { component.caretPosition = 0 } myLafUpdater = Runnable { NotificationsUtil.configureHtmlEditorKit(component, false) component.text = text component.revalidate() component.repaint() } return component } fun updateLaf() { myLafUpdater?.run() updateColor() } fun setDoNotAskHandler(handler: (Boolean) -> Unit) { myDoNotAskHandler = handler } fun setRemoveCallback(callback: Consumer<Notification>) { myRemoveCallback = callback } fun isHover(): Boolean = myHoverState fun setNew(state: Boolean) { if (myIsNew != state) { myIsNew = state updateColor() } } fun setHover(state: Boolean) { myHoverState = state if (myMoreButton != null) { if (!myMorePopupVisible) { myMoreButton.isVisible = state } } updateColor() } private fun updateColor() { if (myHoverState) { if (myIsNew) { setColor(NEW_HOVER_COLOR) } else { setColor(HOVER_COLOR) } } else if (myIsNew) { if (UIManager.getColor(NEW_COLOR_NAME) != null) { setColor(NEW_COLOR) } else { setColor(NEW_DEFAULT_COLOR) } } else { setColor(BG_COLOR) } } private fun setColor(color: Color) { myRoundColor = color repaint() } override fun paintComponent(g: Graphics) { super.paintComponent(g) if (myRoundColor !== BG_COLOR) { g.color = myRoundColor val config = GraphicsUtil.setupAAPainting(g) val cornerRadius = NotificationBalloonRoundShadowBorderProvider.CORNER_RADIUS.get() g.fillRoundRect(0, 0, width, height, cornerRadius, cornerRadius) config.restore() } } fun applySearchQuery(query: String?): Boolean { if (query == null) { isVisible = true return true } val result = matchQuery(query) isVisible = result return result } private fun matchQuery(query: @NlsSafe String): Boolean { if (myNotificationWrapper.title.contains(query, true)) { return true } val subtitle = myNotificationWrapper.subtitle if (subtitle != null && subtitle.contains(query, true)) { return true } if (myNotificationWrapper.content.contains(query, true)) { return true } for (action in myNotificationWrapper.actions) { if (action != null && action.contains(query, true)) { return true } } return false } } private class MoreAction(val notificationComponent: NotificationComponent, actions: List<AnAction>) : NotificationsManagerImpl.DropDownAction(null, null) { val group = DefaultActionGroup() init { val size = actions.size for (i in 1..size - 1) { group.add(actions[i]) } setListener(LinkListener { link, _ -> val popup = NotificationsManagerImpl.showPopup(link, group) notificationComponent.myMoreAwtPopup = popup popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { notificationComponent.myMoreAwtPopup = null } }) }, null) text = IdeBundle.message("notifications.action.more") Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this) } override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } private class MyDropDownAction(val notificationComponent: NotificationComponent) : NotificationsManagerImpl.DropDownAction(null, null) { var collapseActionsDirection: Notification.CollapseActionsDirection = notificationComponent.myNotificationWrapper.notification!!.collapseDirection init { setListener(LinkListener { link, _ -> val group = DefaultActionGroup() val layout = link.parent.layout as DropDownActionLayout for (action in layout.actions) { if (!action.isVisible) { group.add(action.linkData) } } val popup = NotificationsManagerImpl.showPopup(link, group) notificationComponent.myDropDownPopup = popup popup?.addPopupMenuListener(object: PopupMenuListenerAdapter() { override fun popupMenuWillBecomeInvisible(e: PopupMenuEvent?) { notificationComponent.myDropDownPopup = null } }) }, null) text = notificationComponent.myNotificationWrapper.notification!!.dropDownText isVisible = false Notification.setDataProvider(notificationComponent.myNotificationWrapper.notification!!, this) } override fun getTextColor() = JBUI.CurrentTheme.Link.Foreground.ENABLED } private class NotificationWrapper(notification: Notification) { val title = notification.title val subtitle = notification.subtitle val content = notification.content val id = notification.id val displayId = notification.displayId val groupId = notification.groupId val actions: List<String?> = notification.actions.stream().map { it.templateText }.toList() var notification: Notification? = notification } private class DropDownActionLayout(layout: LayoutManager2) : FinalLayoutWrapper(layout) { val actions = ArrayList<LinkLabel<AnAction>>() private lateinit var myDropDownAction: MyDropDownAction override fun addLayoutComponent(comp: Component, constraints: Any?) { super.addLayoutComponent(comp, constraints) add(comp) } override fun addLayoutComponent(name: String?, comp: Component) { super.addLayoutComponent(name, comp) add(comp) } private fun add(component: Component) { if (component is MyDropDownAction) { myDropDownAction = component } else if (component is LinkLabel<*>) { @Suppress("UNCHECKED_CAST") actions.add(component as LinkLabel<AnAction>) } } override fun layoutContainer(parent: Container) { val width = parent.width myDropDownAction.isVisible = false for (action in actions) { action.isVisible = true } layout.layoutContainer(parent) val keepRightmost = myDropDownAction.collapseActionsDirection == Notification.CollapseActionsDirection.KEEP_RIGHTMOST val collapseStart = if (keepRightmost) 0 else actions.size - 1 val collapseDelta = if (keepRightmost) 1 else -1 var collapseIndex = collapseStart if (parent.preferredSize.width > width) { myDropDownAction.isVisible = true actions[collapseIndex].isVisible = false collapseIndex += collapseDelta actions[collapseIndex].isVisible = false collapseIndex += collapseDelta layout.layoutContainer(parent) while (parent.preferredSize.width > width && collapseIndex >= 0 && collapseIndex < actions.size) { actions[collapseIndex].isVisible = false collapseIndex += collapseDelta layout.layoutContainer(parent) } } } } private class ComponentEventHandler { private var myHoverComponent: NotificationComponent? = null private val myMouseHandler = object : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { if (myHoverComponent == null) { val component = ComponentUtil.getParentOfType(NotificationComponent::class.java, e.component) if (component != null) { if (!component.isHover()) { component.setHover(true) } myHoverComponent = component } } } override fun mouseExited(e: MouseEvent) { if (myHoverComponent != null) { val component = myHoverComponent!! if (component.isHover()) { component.setHover(false) } myHoverComponent = null } } } fun add(component: Component) { addAll(component) { c -> c.addMouseListener(myMouseHandler) c.addMouseMotionListener(myMouseHandler) } } private fun addAll(component: Component, listener: (Component) -> Unit) { listener.invoke(component) if (component is JBOptionButton) { component.addContainerListener(object : ContainerAdapter() { override fun componentAdded(e: ContainerEvent) { addAll(e.child, listener) } }) } for (child in UIUtil.uiChildren(component)) { addAll(child, listener) } } } internal class ApplicationNotificationModel { private val myNotifications = ArrayList<Notification>() private val myProjectToModel = HashMap<Project, ProjectNotificationModel>() private val myLock = Object() internal fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) { synchronized(myLock) { notifications.addAll(myNotifications) myNotifications.clear() val model = myProjectToModel.getOrPut(content.project) { ProjectNotificationModel() } model.registerAndGetInitNotifications(content, notifications) } } internal fun unregister(content: NotificationContent) { synchronized(myLock) { myProjectToModel.remove(content.project) } } fun addNotification(project: Project?, notification: Notification) { val runnables = ArrayList<Runnable>() synchronized(myLock) { if (project == null) { if (myProjectToModel.isEmpty()) { myNotifications.add(notification) } else { for ((_project, model) in myProjectToModel.entries) { model.addNotification(_project, notification, myNotifications, runnables) } } } else { val model = myProjectToModel.getOrPut(project) { Disposer.register(project) { synchronized(myLock) { myProjectToModel.remove(project) } } ProjectNotificationModel() } model.addNotification(project, notification, myNotifications, runnables) } } for (runnable in runnables) { runnable.run() } } fun getStateNotifications(project: Project): List<Notification> { synchronized(myLock) { val model = myProjectToModel[project] if (model != null) { return model.getStateNotifications() } } return emptyList() } fun getNotifications(project: Project?): List<Notification> { synchronized(myLock) { if (project == null) { return ArrayList(myNotifications) } val model = myProjectToModel[project] if (model == null) { return ArrayList(myNotifications) } return model.getNotifications(myNotifications) } } fun isEmptyContent(project: Project): Boolean { val model = myProjectToModel[project] return model == null || model.isEmptyContent() } fun expire(notification: Notification) { val runnables = ArrayList<Runnable>() synchronized(myLock) { myNotifications.remove(notification) for ((project , model) in myProjectToModel) { model.expire(project, notification, runnables) } } for (runnable in runnables) { runnable.run() } } fun expireAll() { val notifications = ArrayList<Notification>() val runnables = ArrayList<Runnable>() synchronized(myLock) { notifications.addAll(myNotifications) myNotifications.clear() for ((project, model) in myProjectToModel) { model.expireAll(project, notifications, runnables) } } for (runnable in runnables) { runnable.run() } for (notification in notifications) { notification.expire() } } fun clearAll(project: Project?) { synchronized(myLock) { myNotifications.clear() if (project != null) { myProjectToModel[project]?.clearAll(project) } } } } private class ProjectNotificationModel { private val myNotifications = ArrayList<Notification>() private var myContent: NotificationContent? = null fun registerAndGetInitNotifications(content: NotificationContent, notifications: MutableList<Notification>) { notifications.addAll(myNotifications) myNotifications.clear() myContent = content } fun addNotification(project: Project, notification: Notification, appNotifications: List<Notification>, runnables: MutableList<Runnable>) { if (myContent == null) { myNotifications.add(notification) val notifications = ArrayList(appNotifications) notifications.addAll(myNotifications) runnables.add(Runnable { updateToolWindow(project, notification, notifications, false) }) } else { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.add(notification) } }) } } fun getStateNotifications(): List<Notification> { if (myContent == null) { return emptyList() } return myContent!!.getStateNotifications() } fun isEmptyContent(): Boolean { return myContent == null || myContent!!.isEmpty() } fun getNotifications(appNotifications: List<Notification>): List<Notification> { if (myContent == null) { val notifications = ArrayList(appNotifications) notifications.addAll(myNotifications) return notifications } return myContent!!.getNotifications() } fun expire(project: Project, notification: Notification, runnables: MutableList<Runnable>) { myNotifications.remove(notification) if (myContent == null) { runnables.add(Runnable { updateToolWindow(project, null, myNotifications, false) }) } else { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(notification) } }) } } fun expireAll(project: Project, notifications: MutableList<Notification>, runnables: MutableList<Runnable>) { notifications.addAll(myNotifications) myNotifications.clear() if (myContent == null) { updateToolWindow(project, null, emptyList(), false) } else { runnables.add(Runnable { UIUtil.invokeLaterIfNeeded { myContent!!.expire(null) } }) } } fun clearAll(project: Project) { myNotifications.clear() if (myContent == null) { updateToolWindow(project, null, emptyList(), true) } else { UIUtil.invokeLaterIfNeeded { myContent!!.clearAll() } } } private fun updateToolWindow(project: Project, stateNotification: Notification?, notifications: List<Notification>, closeBalloons: Boolean) { UIUtil.invokeLaterIfNeeded { if (project.isDisposed) { return@invokeLaterIfNeeded } EventLog.getLogModel(project).setStatusMessage(stateNotification) if (closeBalloons) { project.closeAllBalloons() } val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(NotificationsToolWindowFactory.ID) toolWindow?.setIcon(IdeNotificationArea.getActionCenterNotificationIcon(notifications)) } } } fun Project.closeAllBalloons() { val ideFrame = WindowManager.getInstance().getIdeFrame(this) val balloonLayout = ideFrame!!.balloonLayout as BalloonLayoutImpl balloonLayout.closeAll() } class ClearAllNotificationsAction : DumbAwareAction(IdeBundle.message("clear.all.notifications"), null, AllIcons.Actions.GC) { override fun update(e: AnActionEvent) { val project = e.project e.presentation.isEnabled = NotificationsToolWindowFactory.getNotifications(project).isNotEmpty() || (project != null && !NotificationsToolWindowFactory.myModel.isEmptyContent(project)) } override fun getActionUpdateThread() = ActionUpdateThread.EDT override fun actionPerformed(e: AnActionEvent) { NotificationsToolWindowFactory.clearAll(e.project) } }
apache-2.0
b8945512eeac01e2b6b70d3f4b9e59f3
30.386391
148
0.687323
4.975331
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/avatar/picker/AvatarPickerRepository.kt
1
7235
package org.thoughtcrime.securesms.avatar.picker import android.content.Context import android.net.Uri import android.widget.Toast import io.reactivex.rxjava3.core.Single import org.signal.core.util.StreamUtil import org.signal.core.util.ThreadUtil import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.avatar.Avatar import org.thoughtcrime.securesms.avatar.AvatarPickerStorage import org.thoughtcrime.securesms.avatar.AvatarRenderer import org.thoughtcrime.securesms.avatar.Avatars import org.thoughtcrime.securesms.conversation.colors.AvatarColor import org.thoughtcrime.securesms.database.DatabaseFactory import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.mediasend.Media import org.thoughtcrime.securesms.profiles.AvatarHelper import org.thoughtcrime.securesms.providers.BlobProvider import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.NameUtil import org.whispersystems.signalservice.api.util.StreamDetails import java.io.IOException private val TAG = Log.tag(AvatarPickerRepository::class.java) class AvatarPickerRepository(context: Context) { private val applicationContext = context.applicationContext fun getAvatarForSelf(): Single<Avatar> = Single.fromCallable { val details: StreamDetails? = AvatarHelper.getSelfProfileAvatarStream(applicationContext) if (details != null) { try { val bytes = StreamUtil.readFully(details.stream) Avatar.Photo( BlobProvider.getInstance().forData(bytes).createForSingleSessionInMemory(), details.length, Avatar.DatabaseId.DoNotPersist ) } catch (e: IOException) { Log.w(TAG, "Failed to read avatar!") getDefaultAvatarForSelf() } } else { getDefaultAvatarForSelf() } } fun getAvatarForGroup(groupId: GroupId): Single<Avatar> = Single.fromCallable { val recipient = Recipient.externalGroupExact(applicationContext, groupId) if (AvatarHelper.hasAvatar(applicationContext, recipient.id)) { try { val bytes = AvatarHelper.getAvatarBytes(applicationContext, recipient.id) Avatar.Photo( BlobProvider.getInstance().forData(bytes).createForSingleSessionInMemory(), AvatarHelper.getAvatarLength(applicationContext, recipient.id), Avatar.DatabaseId.DoNotPersist ) } catch (e: IOException) { Log.w(TAG, "Failed to read group avatar!") getDefaultAvatarForGroup(recipient.avatarColor) } } else { getDefaultAvatarForGroup(recipient.avatarColor) } } fun getPersistedAvatarsForSelf(): Single<List<Avatar>> = Single.fromCallable { DatabaseFactory.getAvatarPickerDatabase(applicationContext).getAvatarsForSelf() } fun getPersistedAvatarsForGroup(groupId: GroupId): Single<List<Avatar>> = Single.fromCallable { DatabaseFactory.getAvatarPickerDatabase(applicationContext).getAvatarsForGroup(groupId) } fun getDefaultAvatarsForSelf(): Single<List<Avatar>> = Single.fromCallable { Avatars.defaultAvatarsForSelf.entries.mapIndexed { index, entry -> Avatar.Vector(entry.key, color = Avatars.colors[index % Avatars.colors.size], Avatar.DatabaseId.NotSet) } } fun getDefaultAvatarsForGroup(): Single<List<Avatar>> = Single.fromCallable { Avatars.defaultAvatarsForGroup.entries.mapIndexed { index, entry -> Avatar.Vector(entry.key, color = Avatars.colors[index % Avatars.colors.size], Avatar.DatabaseId.NotSet) } } fun writeMediaToMultiSessionStorage(media: Media, onMediaWrittenToMultiSessionStorage: (Uri) -> Unit) { SignalExecutors.BOUNDED.execute { onMediaWrittenToMultiSessionStorage(AvatarPickerStorage.save(applicationContext, media)) } } fun persistAvatarForSelf(avatar: Avatar, onPersisted: (Avatar) -> Unit) { SignalExecutors.BOUNDED.execute { val avatarDatabase = DatabaseFactory.getAvatarPickerDatabase(applicationContext) val savedAvatar = avatarDatabase.saveAvatarForSelf(avatar) avatarDatabase.markUsage(savedAvatar) onPersisted(savedAvatar) } } fun persistAvatarForGroup(avatar: Avatar, groupId: GroupId, onPersisted: (Avatar) -> Unit) { SignalExecutors.BOUNDED.execute { val avatarDatabase = DatabaseFactory.getAvatarPickerDatabase(applicationContext) val savedAvatar = avatarDatabase.saveAvatarForGroup(avatar, groupId) avatarDatabase.markUsage(savedAvatar) onPersisted(savedAvatar) } } fun persistAndCreateMediaForSelf(avatar: Avatar, onSaved: (Media) -> Unit) { SignalExecutors.BOUNDED.execute { if (avatar.databaseId !is Avatar.DatabaseId.DoNotPersist) { persistAvatarForSelf(avatar) { AvatarRenderer.renderAvatar(applicationContext, avatar, onSaved, this::handleRenderFailure) } } else { AvatarRenderer.renderAvatar(applicationContext, avatar, onSaved, this::handleRenderFailure) } } } fun persistAndCreateMediaForGroup(avatar: Avatar, groupId: GroupId, onSaved: (Media) -> Unit) { SignalExecutors.BOUNDED.execute { if (avatar.databaseId !is Avatar.DatabaseId.DoNotPersist) { persistAvatarForGroup(avatar, groupId) { AvatarRenderer.renderAvatar(applicationContext, avatar, onSaved, this::handleRenderFailure) } } else { AvatarRenderer.renderAvatar(applicationContext, avatar, onSaved, this::handleRenderFailure) } } } fun createMediaForNewGroup(avatar: Avatar, onSaved: (Media) -> Unit) { SignalExecutors.BOUNDED.execute { AvatarRenderer.renderAvatar(applicationContext, avatar, onSaved, this::handleRenderFailure) } } fun handleRenderFailure(throwable: Throwable?) { Log.w(TAG, "Failed to render avatar.", throwable) ThreadUtil.postToMain { Toast.makeText(applicationContext, R.string.AvatarPickerRepository__failed_to_save_avatar, Toast.LENGTH_SHORT).show() } } fun getDefaultAvatarForSelf(): Avatar { val initials = NameUtil.getAbbreviation(Recipient.self().getDisplayName(applicationContext)) return if (initials.isNullOrBlank()) { Avatar.getDefaultForSelf() } else { Avatar.Text(initials, requireNotNull(Avatars.colorMap[Recipient.self().avatarColor.serialize()]), Avatar.DatabaseId.DoNotPersist) } } fun getDefaultAvatarForGroup(groupId: GroupId): Avatar { val recipient = Recipient.externalGroupExact(applicationContext, groupId) return getDefaultAvatarForGroup(recipient.avatarColor) } fun getDefaultAvatarForGroup(color: AvatarColor?): Avatar { val colorPair = Avatars.colorMap[color?.serialize()] val defaultColor = Avatar.getDefaultForGroup() return if (colorPair != null) { defaultColor.copy(color = colorPair) } else { defaultColor } } fun delete(avatar: Avatar, onDelete: () -> Unit) { SignalExecutors.BOUNDED.execute { if (avatar.databaseId is Avatar.DatabaseId.Saved) { val avatarDatabase = DatabaseFactory.getAvatarPickerDatabase(applicationContext) avatarDatabase.deleteAvatar(avatar) } onDelete() } } }
gpl-3.0
5849b2e1c8b286e206d24beec19ece76
37.280423
135
0.744713
4.449569
false
false
false
false
elpassion/cloud-timer-android
app/src/main/java/pl/elpassion/cloudtimer/timer/TimerActivity.kt
1
3259
package pl.elpassion.cloudtimer.timer import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.widget.Button import android.widget.EditText import android.widget.TextView import com.triggertrap.seekarc.SeekArc import pl.elpassion.cloudtimer.R import pl.elpassion.cloudtimer.TimeConverter.formatFromMilliToMinutes import pl.elpassion.cloudtimer.TimeConverter.formatFromMilliToTime import pl.elpassion.cloudtimer.alarm.scheduleAlarm import pl.elpassion.cloudtimer.base.CloudTimerActivity import pl.elpassion.cloudtimer.dao.TimerDaoProvider import pl.elpassion.cloudtimer.domain.Timer import pl.elpassion.cloudtimer.login.authtoken.AuthTokenSharedPreferences.isLoggedIn class TimerActivity : CloudTimerActivity() { companion object { fun start(activity: Activity, timerActivityResultCode: Int) { val intent = Intent(activity, TimerActivity::class.java) activity.startActivityForResult(intent, timerActivityResultCode) } } val seekArcWrapper by lazy { val seekArc = findViewById(R.id.timer_seekArc) as SeekArc SeekArcWrapper(seekArc) { timerEndTime.text = formatFromMilliToTime(it.endTime) timerDuration.text = formatFromMilliToMinutes(it.timerDurationInMillis) } } val timerDuration by lazy { findViewById(R.id.timer_duration) as TextView } private val timerEndTime by lazy { findViewById(R.id.timer_time_to_end) as TextView } private val startTimerButton by lazy { findViewById(R.id.start_timer_button) as Button } private val timerTitle by lazy { findViewById(R.id.new_timer_title) as EditText } private val handler = Handler() private val timerRefreshRunnable = TimerEndTimeRefresher() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_timer) timerDuration.text = formatFromMilliToMinutes(seekArcWrapper.timerDurationInMillis) refreshTimerEndTime() startTimerButton.setOnClickListener { startNewTimer() } } private fun refreshTimerEndTime() { timerEndTime.text = formatFromMilliToTime(seekArcWrapper.endTime) } private fun startNewTimer() { val newTimer = Timer(timerTitle.text.toString(), seekArcWrapper.timerDurationInMillis) scheduleAlarm(newTimer, this) TimerDaoProvider.getInstance().save(newTimer) if (isLoggedIn()) sendTimerService.sendTimer(TimerToSend(newTimer)).subscribe(onSendTimerSuccess) else finish() } private val onSendTimerSuccess = { receivedTimer: ReceivedTimer -> TimerDaoProvider.getInstance().changeTimerToSynced(receivedTimer.uuid) finish() } override fun onResume() { handler.postDelayed(timerRefreshRunnable, 1000) refreshTimerEndTime() super.onResume() } override fun onPause() { handler.removeCallbacks(timerRefreshRunnable) super.onPause() } inner class TimerEndTimeRefresher : Runnable { override fun run() { refreshTimerEndTime() handler.postDelayed(this, 1000) } } }
apache-2.0
e3685087c1614124d781f02f005290bb
35.629213
94
0.725683
4.603107
false
false
false
false
micolous/metrodroid
src/jvmCliMain/kotlin/au/id/micolous/metrodroid/card/Atr.kt
1
5408
/* * Atr.kt * * Copyright 2019 Michael Farrell <[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 au.id.micolous.metrodroid.card import au.id.micolous.metrodroid.card.iso7816.ISO7816TLV import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.util.ImmutableByteArray /** * ATR (Answer To Reset) parser for PC/SC and standard compact-TLV. * * Reference: https://en.wikipedia.org/wiki/Answer_to_reset#ATR_in_asynchronous_transmission */ data class Atr( /** A list of supported protocols, eg: T=0, T=1... */ val protocols: List<Int>, /** PC/SC-specific ATR data, null if not present */ val pcscAtr: PCSCAtr? = null, val cardServiceDataByte: Int? = null, val preIssuingData: ImmutableByteArray? = null, val statusIndicator: ImmutableByteArray? = null, /** Checksum; null if not present. Omitted if only T=0 supported. */ val checksumByte: Int? = null ) { companion object { val RID_PCSC_WORKGROUP = ImmutableByteArray.fromHex("a000000306") val PCSC_RESPONSE_LEN = 3 /* header */ + RID_PCSC_WORKGROUP.count() + 3 /* PIX, excluding RFU bytes */ /** * Parses an ATR. Returns null if the data could not be handled. */ fun parseAtr(atr: ImmutableByteArray) : Atr? { // println("ATR: ${atr.getHexString()}") // Initial character TS if (atr[0] != 0x3b.toByte()) return null var p = 1 val nibbles = mutableListOf<Int>() do { val y = atr[p].toInt() and 0xf0 nibbles.add(atr[p].toInt() and 0xf) val ta = y and 0x10 != 0 val tb = y and 0x20 != 0 val tc = y and 0x40 != 0 val td = y and 0x80 != 0 // println("$ta, $tb, $tc, $td") p++ // TODO: implement t_(n) if (ta) p++ if (tb) p++ if (tc) p++ } while (td) val historicalByteCount = nibbles[0] val protocols = if (nibbles.size > 1) { nibbles.slice(1 until nibbles.size) } else { // No protocols specified; T=0 listOf(0) } val t1 = atr.sliceOffLenSafe(p, historicalByteCount) ?: return null val checksum = if (protocols != listOf(0)) atr[atr.lastIndex].toInt() and 0xff else null if (t1.isEmpty()) { // No historical bytes return null } // Category indicator byte if (t1[0] != 0.toByte() && t1[0] != 0x80.toByte()) { Log.w("Atr", "can't handle t1=${t1.getHexString()}") return null } // PC/SC Specification treats this as Simple TLV, rather than Compact TLV. // Check for its fingerprints... if (t1.count() > PCSC_RESPONSE_LEN && t1[1] == 0x4f.toByte()) { // PC/SC T1: 80(category byte) 4f(tag) [length] a000000306(PC/SC RID) ... // PC/SC calls everything after from the RID bytes the AID val aid = t1.sliceOffLenSafe(3, t1[2].toInt() and 0xff) if (aid?.startsWith(RID_PCSC_WORKGROUP) == true) { // This is PC/SC! val i = RID_PCSC_WORKGROUP.count() // ... [standard] [cardName(high)] [cardName(low)] val standard = aid.byteArrayToInt(i, 1) val cardName = aid.byteArrayToInt(i + 1, 2) return Atr( protocols = protocols, pcscAtr = PCSCAtr(standard, cardName), checksumByte = checksum) } } // Handle Compact-TLV tag type var cardServiceDataByte: Int? = null var preIssuingData: ImmutableByteArray? = null var statusIndicator: ImmutableByteArray? = null if (t1.count() > 2) { ISO7816TLV.compactTlvIterate(t1.sliceOffLen(1, t1.count() - 1)).forEach { when { it.first == 0x3 -> cardServiceDataByte = it.second.byteArrayToInt() and 0xff it.first == 0x6 -> preIssuingData = it.second it.first == 0x8 -> statusIndicator = it.second } } } return Atr( protocols = protocols, cardServiceDataByte = cardServiceDataByte, preIssuingData = preIssuingData, statusIndicator = statusIndicator, checksumByte = checksum ) } } }
gpl-3.0
5a6a806979f23273c7267c56ab2897ab
36.555556
100
0.539571
4.144061
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/kazan/KazanTransitData.kt
1
5914
/* * KazanTransitData.kt * * Copyright 2018 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.kazan import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.classic.ClassicCard import au.id.micolous.metrodroid.card.classic.ClassicCardTransitFactory import au.id.micolous.metrodroid.card.classic.ClassicSector import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.time.Daystamp import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.time.TimestampFull import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.util.HashUtils import au.id.micolous.metrodroid.util.ImmutableByteArray import au.id.micolous.metrodroid.util.NumberUtils private fun name() = Localizer.localizeString(R.string.card_name_kazan) private val CARD_INFO = CardInfo( name = R.string.card_name_kazan, locationId = R.string.location_kazan, cardType = CardType.MifareClassic, keysRequired = true, imageId = R.drawable.kazan, imageAlphaId = R.drawable.iso7810_id1_alpha, keyBundle = "kazan", region = TransitRegion.RUSSIA, preview = true) private fun formatSerial(serial: Long) = NumberUtils.zeroPad(serial, 10) private fun getSerial(card: ClassicCard) = card.tagId.byteArrayToLongReversed() private fun parseDate(raw: ImmutableByteArray, off: Int) = if (raw.byteArrayToInt(off, 3) == 0) null else Daystamp( year = raw[off].toInt() + 2000, month = raw[off+1].toInt() - 1, day = raw[off+2].toInt() ) private fun parseTime(raw: ImmutableByteArray, off: Int) = TimestampFull( year = raw[off].toInt() + 2000, month = raw[off+1].toInt() - 1, day = raw[off+2].toInt(), hour = raw[off+3].toInt(), min = raw[off+4].toInt(), tz = MetroTimeZone.MOSCOW ) @Parcelize data class KazanTrip(override val startTimestamp: TimestampFull): Trip() { override val mode: Mode get() = Mode.OTHER override val fare: TransitCurrency? get() = null companion object { fun parse(raw: ImmutableByteArray): KazanTrip? { if (raw.byteArrayToInt(1, 3) == 0) return null return KazanTrip(parseTime(raw, 1)) } } } @Parcelize data class KazanSubscription(override val validFrom: Daystamp?, override val validTo: Daystamp?, private val mType: Int, private val mCounter: Int): Subscription() { val isPurse: Boolean get () = mType == 0x53 val isUnlimited: Boolean get() = mType in listOf(0, 0x60) val balance: TransitBalance? get() = if (!isPurse) null else TransitBalanceStored(TransitCurrency.RUB(mCounter * 100), name = null, validFrom = validFrom, validTo = validTo) override val remainingTripCount: Int? get() = if (isUnlimited) null else mCounter override val subscriptionName: String? get() = when (mType) { 0 -> Localizer.localizeString(R.string.kazan_blank) // Could be unlimited buses, unlimited tram, unlimited trolleybus or unlimited tram+trolleybus 0x60 -> "Unknown unlimited (0x60)" else -> Localizer.localizeString(R.string.unknown_format, mType) } } @Parcelize data class KazanTransitData(private val mSerial: Long, private val mSub: KazanSubscription, private val mTrip: KazanTrip? ) : TransitData() { override val serialNumber get() = formatSerial(mSerial) override val balance: TransitBalance? get() = mSub.balance override val subscriptions get() = if (!mSub.isPurse) listOf(mSub) else null // Apparently subscriptions do not record trips override val trips: List<Trip>? get() = mTrip?.let { listOf(it) } override val cardName get() = name() companion object { fun parse(card: ClassicCard): KazanTransitData { return KazanTransitData( mSerial = getSerial(card), mSub = KazanSubscription( mType = card[8, 0].data[6].toInt() and 0xff, validFrom = parseDate(card[8,0].data, 7), validTo = parseDate(card[8,0].data, 10), mCounter = card[9, 0].data.byteArrayToIntReversed(0, 4) ), mTrip = KazanTrip.parse(card[8,2].data) ) } } } object KazanTransitFactory : ClassicCardTransitFactory { override val allCards get() = listOf(CARD_INFO) override fun parseTransitIdentity(card: ClassicCard) = TransitIdentity( name(), formatSerial(getSerial(card))) override fun parseTransitData(card: ClassicCard) = KazanTransitData.parse(card) override val earlySectors get() = 9 override fun earlyCheck(sectors: List<ClassicSector>) = HashUtils.checkKeyHash(sectors[8], "kazan", "0f30386921b6558b133f0f49081b932d", "ec1b1988a2021019074d4304b4aea772") >= 0 }
gpl-3.0
c3137175c68179862a3573f0744ee158
37.907895
115
0.653365
4.0674
false
false
false
false
phase/lang-kotlin-antlr-compiler
src/test/kotlin/xyz/jadonfowler/compiler/ConstantFoldTest.kt
1
1103
package xyz.jadonfowler.compiler import org.junit.Test import xyz.jadonfowler.compiler.ast.IntegerLiteral import xyz.jadonfowler.compiler.pass.ConstantFoldPass import xyz.jadonfowler.compiler.pass.PrintPass import xyz.jadonfowler.compiler.pass.TypePass import kotlin.test.assertEquals class ConstantFoldTest { @Test fun additionConstantFolding() { val code = """ let a = 10 + 24 """ val module = compileString("additionConstantFolding", code) TypePass(module) ConstantFoldPass(module) assertEquals(34, (module.globalVariables[0].initialExpression as IntegerLiteral).value) println(PrintPass(module).output) } @Test fun complexConstantFolding() { val code = """ let a = 1234 * 12 + 8767 + 3453 - 57347 + 73457 + 7457 """ val module = compileString("complexConstantFolding", code) TypePass(module) ConstantFoldPass(module) assertEquals(50595, (module.globalVariables[0].initialExpression as IntegerLiteral).value) println(PrintPass(module).output) } }
mpl-2.0
0d435ae60ae459f0981da0ede17c0565
28.026316
98
0.688123
3.967626
false
true
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/cli/src/org/jetbrains/kotlin/tools/projectWizard/wizard/YamlWizard.kt
4
2602
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard import org.jetbrains.kotlin.tools.projectWizard.YamlSettingsParser import org.jetbrains.kotlin.tools.projectWizard.core.* import org.jetbrains.kotlin.tools.projectWizard.core.entity.PipelineTask import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.PluginSetting import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.core.service.IdeaIndependentWizardService import org.jetbrains.kotlin.tools.projectWizard.core.service.Services import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService import org.jetbrains.kotlin.tools.projectWizard.phases.GenerationPhase import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.templates.TemplatesPlugin import java.nio.file.Path class YamlWizard( private val yaml: String, private val projectPath: Path, createPlugins: (Context) -> List<Plugin>, servicesManager: ServicesManager = CLI_SERVICES_MANAGER, isUnitTestMode: Boolean ) : Wizard(createPlugins, servicesManager, isUnitTestMode) { override fun apply( services: List<WizardService>, phases: Set<GenerationPhase>, onTaskExecuting: (PipelineTask) -> Unit ): TaskResult<Unit> = computeM { val (settingsValuesFromYaml) = context.read { parseYaml(yaml, pluginSettings) } context.writeSettings { settingsValuesFromYaml.forEach { (reference, value) -> reference.setValue(value) } StructurePlugin.projectPath.reference.setValue(projectPath) } super.apply(services, phases, onTaskExecuting) } companion object { val CLI_SERVICES_MANAGER = ServicesManager(Services.IDEA_INDEPENDENT_SERVICES) { services -> services.firstOrNull { it is IdeaIndependentWizardService } } } } fun Reader.parseYaml( yaml: String, pluginSettings: List<PluginSetting<*, *>> ): TaskResult<Map<SettingReference<*, *>, Any>> { val parsingData = ParsingState(TemplatesPlugin.templates.propertyValue, emptyMap()) val yamlParser = YamlSettingsParser(pluginSettings, parsingData) return yamlParser.parseYamlText(yaml) }
apache-2.0
c767d2ee45296777bc940a88d2e11a08
45.464286
158
0.774404
4.517361
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHintsTest.kt
2
4853
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.parameterInfo import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class ArgumentNameHintsTest : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.getInstance() fun check(text: String) { myFixture.configureByText("A.kt", text) myFixture.testInlays() } fun `test insert literal arguments`() { check( """ fun test(file: File) { val testNow = System.currentTimeMillis() > 34000 val times = 1 val pi = 4.0f val title = "Testing..." val ch = 'q'; configure(<hint text="testNow:" />true, <hint text="times:" />555, <hint text="pii:" />3.141f, <hint text="title:" />"Huge Title", <hint text="terminate:" />'c', <hint text="file:" />null) configure(testNow, shouldIgnoreRoots(), fourteen, pi, title, c, file) } fun configure(testNow: Boolean, times: Int, pii: Float, title: String, terminate: Char, file: File) { System.out.println() System.out.println() }""" ) } fun `test do not show for Exceptions`() { check( """ fun test() { val t = IllegalStateException("crime"); }""" ) } fun `test single varargs hint`() { check( """ fun main() { testBooleanVarargs(<hint text="test:" />13, <hint text="...booleans:" />false) } fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean { return false } } """ ) } fun `test no hint if varargs null`() { check( """ fun main() { testBooleanVarargs(<hint text="test:" />13) } fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean { return false } """ ) } fun `test multiple vararg hint`() { check( """ fun main() { testBooleanVarargs(<hint text="test:" />13, <hint text="...booleans:" />false, true, false) } fun testBooleanVarargs(test: Int, vararg booleans: Boolean): Boolean { return false } """ ) } fun `test inline positive and negative numbers`() { check( """ fun main() { val obj = Any() count(<hint text="test:"/>-1, obj); count(<hint text="test:"/>+1, obj); } fun count(test: Int, obj: Any) { } } """ ) } fun `test show ambiguous`() { check( """ fun main() { test(<hint text="a:"/>10, x); } fun test(a: Int, bS: String) {} fun test(a: Int, bI: Int) {} """ ) } fun `test show non-ambiguous overload`() { check( """ fun main() { test(<hint text="a:"/>10, <hint text="bI:"/>15); } fun test() {} fun test(a: Int, bS: String) {} fun test(a: Int, bI: Int) {} """ ) } fun `test show ambiguous constructor`() { check( """ fun main() { X(<hint text="a:"/>10, x); } } class X { constructor(a: Int, bI: Int) {} constructor(a: Int, bS: String) {} } """ ) } fun `test invoke`() { check( """ fun main() { val x = X() x(<hint text="a:"/>10, x); } } class X { operator fun invoke(a: Int, bI: Int) {} } """ ) } fun `test annotation`() { check( """ annotation class ManyArgs(val name: String, val surname: String) @ManyArgs(<hint text="name:"/>"Ilya", <hint text="surname:"/>"Sergey") class AnnotatedMuch """ ) } fun `test functional type`() { check( """ fun <T> T.test(block: (T) -> Unit) = block(this) """ ) } fun `test functional type with parameter name`() { check( """ fun <T> T.test(block: (receiver: T, Int) -> Unit) = block(<hint text="receiver:"/>this, 0) """ ) } fun `test dynamic`() { check( """fun foo(x: dynamic) { x.foo("123") }""" ) } fun `test spread`() { check( """fun foo(vararg x: Int) { intArrayOf(1, 0).apply { foo(<hint text="...x:" />*this) } }""" ) } fun `test line break`() { check( """fun foo(vararg x: Int) { foo(<hint text="...x:" /> 1, 2, 3 ) } }""" ) } fun `test incomplete Pair call`() { check("val x = Pair(1, )") } }
apache-2.0
52a20557c84b4ca906e2dd8d92e4857f
20.86036
190
0.525242
3.863854
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/execution/console/ConsolePromptDecorator.kt
7
3358
// 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.execution.console import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorLinePainter import com.intellij.openapi.editor.LineExtensionInfo import com.intellij.openapi.editor.TextAnnotationGutterProvider import com.intellij.openapi.editor.colors.ColorKey import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ui.UIUtil import java.awt.Color /** * Created by Yuli Fiterman on 9/16/2016. */ class ConsolePromptDecorator(private val myEditorEx: EditorEx) : EditorLinePainter(), TextAnnotationGutterProvider { var mainPrompt: String = "> " get() = if (myEditorEx.isRendererMode) "" else field set(mainPrompt) { val mainPromptWrapped = wrapPrompt(mainPrompt) if (this.mainPrompt != mainPromptWrapped) { // to be compatible with LanguageConsoleView we should reset the indent prompt indentPrompt = "" field = mainPromptWrapped update() } } var promptAttributes: ConsoleViewContentType = ConsoleViewContentType.USER_INPUT set(promptAttributes) { field = promptAttributes myEditorEx.colorsScheme.setColor(promptColor, promptAttributes.attributes.foregroundColor) update() } var indentPrompt: String = "" get() = if (myEditorEx.isRendererMode) "" else field set(indentPrompt) { val indentPromptWrapped = wrapPrompt(indentPrompt) field = indentPromptWrapped update() } init { myEditorEx.colorsScheme.setColor(promptColor, this.promptAttributes.attributes.foregroundColor) } // always add space to the prompt otherwise it may look ugly private fun wrapPrompt(prompt: String) = if (!prompt.endsWith(" ")) "$prompt " else prompt override fun getLineExtensions(project: Project, file: VirtualFile, lineNumber: Int): Collection<LineExtensionInfo>? = null override fun getLineText(line: Int, editor: Editor): String? { when { line == 0 -> return mainPrompt line > 0 -> return indentPrompt else -> return null } } override fun getToolTip(line: Int, editor: Editor): String? = null override fun getStyle(line: Int, editor: Editor): EditorFontType = EditorFontType.CONSOLE_PLAIN override fun getColor(line: Int, editor: Editor): ColorKey = promptColor override fun getBgColor(line: Int, editor: Editor): Color { var backgroundColor: Color? = this.promptAttributes.attributes.backgroundColor if (backgroundColor == null) { backgroundColor = myEditorEx.backgroundColor } return backgroundColor } override fun getPopupActions(line: Int, editor: Editor): List<AnAction>? = null override fun gutterClosed() {} override fun useMargin(): Boolean = false fun update() { UIUtil.invokeLaterIfNeeded { if (!myEditorEx.isDisposed) { myEditorEx.gutterComponentEx.revalidateMarkup() } } } companion object { private val promptColor = ColorKey.createColorKey("CONSOLE_PROMPT_COLOR") } }
apache-2.0
122f4485777cd2a2540dd3a8983be910
32.919192
125
0.736748
4.36671
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database-tests/src/main/kotlin/entities/partition/ManyToOnePartitionEntity.kt
1
881
package entities.partition import com.onyx.persistence.IManagedEntity import com.onyx.persistence.ManagedEntity import com.onyx.persistence.annotations.* import com.onyx.persistence.annotations.values.FetchPolicy import com.onyx.persistence.annotations.values.IdentifierGenerator import com.onyx.persistence.annotations.values.RelationshipType /** * Created by timothy.osborn on 3/5/15. */ @Entity(fileName = "web/partition") class ManyToOnePartitionEntity : ManagedEntity(), IManagedEntity { @Identifier(generator = IdentifierGenerator.SEQUENCE) @Attribute var id: Long? = null @Attribute @Partition var partitionId: Long? = null @Relationship(type = RelationshipType.ONE_TO_MANY, inverse = "child", inverseClass = OneToManyPartitionEntity::class, fetchPolicy = FetchPolicy.EAGER) var parents: MutableList<OneToManyPartitionEntity>? = null }
agpl-3.0
fbc649a31a9e9528d8dfce1492c45b58
34.24
154
0.784336
4.472081
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-reference-index/src/org/jetbrains/kotlin/idea/search/refIndex/JavaCompilerClassRefWithSearchId.kt
4
2599
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.search.refIndex import com.intellij.compiler.backwardRefs.SearchId import com.intellij.compiler.backwardRefs.SearchIdHolder import org.jetbrains.jps.backwardRefs.CompilerRef import org.jetbrains.jps.backwardRefs.NameEnumerator import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.psi.KtClassOrObject class JavaCompilerClassRefWithSearchId private constructor( override val jvmClassName: String, qualifierId: Int, ) : CompilerRef.JavaCompilerClassRef(qualifierId), CompilerClassHierarchyElementDefWithSearchId { override val searchId: SearchId get() = SearchId(jvmClassName) override fun createMethod(name: Int, parameterCount: Int): CompilerRef.CompilerMember = JavaCompilerMethodRefWithSearchIdOwner( owner = this, name = name, parameterCount = parameterCount, ) override fun createField(name: Int): CompilerRef.CompilerMember = JavaCompilerFieldRefWithSearchIdOwner(owner = this, name = name) companion object { fun create(classOrObject: KtClassOrObject, names: NameEnumerator): JavaCompilerClassRefWithSearchId? { val qualifier = KotlinPsiHeuristics.getJvmName(classOrObject) ?: return null return JavaCompilerClassRefWithSearchId(qualifier, names.tryEnumerate(qualifier)) } fun create(jvmClassName: String, names: NameEnumerator): JavaCompilerClassRefWithSearchId = JavaCompilerClassRefWithSearchId(jvmClassName, names.tryEnumerate(jvmClassName)) } } private class JavaCompilerFieldRefWithSearchIdOwner( private val owner: CompilerClassHierarchyElementDefWithSearchId, name: Int, ) : CompilerRef.JavaCompilerFieldRef(owner.name, name) { override fun getOwner(): CompilerRef.CompilerClassHierarchyElementDef = owner } private class JavaCompilerMethodRefWithSearchIdOwner( private val owner: CompilerClassHierarchyElementDefWithSearchId, name: Int, parameterCount: Int, ) : CompilerRef.JavaCompilerMethodRef(owner.name, name, parameterCount) { override fun getOwner(): CompilerRef.CompilerClassHierarchyElementDef = owner } interface CompilerClassHierarchyElementDefWithSearchId : CompilerRef.CompilerClassHierarchyElementDef, SearchIdHolder { fun createMethod(name: Int, parameterCount: Int): CompilerRef.CompilerMember fun createField(name: Int): CompilerRef.CompilerMember val jvmClassName: String }
apache-2.0
c81b7f88d7928d64a08f441fb09b59c4
46.272727
158
0.793767
5.177291
false
false
false
false
GunoH/intellij-community
platform/util/ui/src/com/intellij/ui/svg/SvgPrebuiltCacheManager.kt
4
3316
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.svg import com.intellij.diagnostic.StartUpMeasurer import com.intellij.ui.icons.IconLoadMeasurer import com.intellij.util.ImageLoader import org.jetbrains.annotations.ApiStatus import org.jetbrains.ikv.Ikv import org.jetbrains.ikv.UniversalHash import java.awt.Image import java.nio.ByteBuffer import java.nio.file.Path private val intKeyHash = UniversalHash.IntHash() @ApiStatus.Internal class SvgPrebuiltCacheManager(private val dbDir: Path) { private val lightStores = Stores("") private val darkStores = Stores("-d") @Suppress("PropertyName") private inner class Stores(classifier: String) { val s1 = StoreContainer(1f, classifier) val s1_25 = StoreContainer(1.25f, classifier) val s1_5 = StoreContainer(1.5f, classifier) val s2 = StoreContainer(2f, classifier) val s2_5 = StoreContainer(2.5f, classifier) } private inner class StoreContainer(private val scale: Float, private val classifier: String) { @Volatile private var store: Ikv.SizeUnawareIkv<Int>? = null fun getOrCreate() = store ?: getSynchronized() @Synchronized private fun getSynchronized(): Ikv.SizeUnawareIkv<Int> { var store = store if (store == null) { store = Ikv.loadSizeUnawareIkv(dbDir.resolve("icons-v2-$scale$classifier.db"), intKeyHash) this.store = store } return store } } fun loadFromCache(key: Int, scale: Float, isDark: Boolean, docSize: ImageLoader.Dimension2DDouble? = null): Image? { val start = StartUpMeasurer.getCurrentTimeIfEnabled() val list = if (isDark) darkStores else lightStores // not supported scale val store = when (scale) { 1f -> list.s1.getOrCreate() 1.25f -> list.s1_25.getOrCreate() 1.5f -> list.s1_5.getOrCreate() 2f -> list.s2.getOrCreate() 2.5f -> list.s2_5.getOrCreate() else -> return null } val data = store.getUnboundedValue(key) ?: return null val storedKey = readVar(data) if (storedKey != key) return null val actualWidth: Int val actualHeight: Int val format = data.get().toInt() and 0xff if (format < 254) { actualWidth = format actualHeight = format } else if (format == 255) { actualWidth = readVar(data) actualHeight = actualWidth } else { actualWidth = readVar(data) actualHeight = readVar(data) } docSize?.setSize((actualWidth / scale).toDouble(), (actualHeight / scale).toDouble()) val image = SvgCacheManager.readImage(data, actualWidth, actualHeight) IconLoadMeasurer.svgPreBuiltLoad.end(start) return image } } private fun readVar(buf: ByteBuffer): Int { var aByte = buf.get().toInt() var value: Int = aByte and 127 if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 7) if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 14) if (aByte and 128 != 0) { aByte = buf.get().toInt() value = value or (aByte and 127 shl 21) if (aByte and 128 != 0) { value = value or (buf.get().toInt() shl 28) } } } } return value }
apache-2.0
4c96840e797c1e0e05540a4005382118
30.292453
120
0.666164
3.789714
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/model/CodeVisionVisualVerticalPositionKeeper.kt
8
1932
package com.intellij.codeInsight.codeVision.ui.model import com.intellij.openapi.Disposable import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.util.Disposer import java.awt.Point class CodeVisionVisualVerticalPositionKeeper(vararg editors: Editor) { private val map = HashMap<Editor, RangeMarkerWithOffset>() init { for (editor in editors) { map[editor] = keep(editor) } } private fun keep(editor: Editor): RangeMarkerWithOffset { val visibleArea = editor.scrollingModel.visibleAreaOnScrollingFinished val cursorPosition = editor.visualPositionToXY(editor.caretModel.visualPosition) val offset = if (visibleArea.height > 0 && (cursorPosition.y < visibleArea.y || cursorPosition.y > (visibleArea.y + visibleArea.height))) { val pos = Point(visibleArea.x + (visibleArea.width / 2), visibleArea.y + (visibleArea.height / 2)) editor.logicalPositionToOffset(editor.xyToLogicalPosition(pos)) } else { editor.caretModel.offset } val rangeMarker = editor.document.createRangeMarker(offset, offset) val offsetToXY = editor.offsetToXY(offset) val shift = offsetToXY.y - visibleArea.y return RangeMarkerWithOffset(rangeMarker, shift) } fun restoreOriginalLocation() { map.forEach { (editor, value) -> restoreOriginalLocation(editor, value) } map.clear() } private fun restoreOriginalLocation(editor: Editor, pair: RangeMarkerWithOffset) { val newLocation = editor.offsetToXY(pair.range.startOffset) editor.scrollingModel.disableAnimation() editor.scrollingModel.scrollVertically(newLocation.y - pair.shift) editor.scrollingModel.enableAnimation() pair.dispose() } class RangeMarkerWithOffset(val range: RangeMarker, val shift: Int) : Disposable { override fun dispose() { Disposer.dispose { range } } } }
apache-2.0
d06c4f66ab40aa15a31a3eda7c53cb2a
32.912281
132
0.731884
4.341573
false
false
false
false
rejasupotaro/onesky-gradle-plugin
plugin/src/main/java/com/cookpad/android/onesky/plugin/tasks/UploadTranslationAndMarkAsDeprecatedTask.kt
1
907
package com.cookpad.android.onesky.plugin.tasks import com.github.kittinunf.result.Result import org.gradle.api.tasks.TaskAction import java.io.File open class uploadTranslationAndMarkAsDeprecated : OneskyTask() { init { group = "Translation" description = "Upload the default translation file (values/strings.xml) and deprecate old translation" } @TaskAction fun uploadTranslationAndMarkAsDeprecated() { val file = File("${project.projectDir.absolutePath}/src/main/res/values/strings.xml") print("Uploading ${file.absolutePath} ... ") val result = oneskyClient.upload(file, isKeepingAllStrings = false) when (result) { is Result.Success -> { println("Done!") } is Result.Failure -> { println("Failed!") throw result.error } } } }
mit
61ae8eeecf13de835ffc88f651891926
30.275862
110
0.622933
4.381643
false
false
false
false
infotech-group/android-drawable-dsl
src/androidTest/kotlin/group/infotech/drawable/dsl/SnapshotTest.kt
1
4010
package group.infotech.drawable.dsl import android.content.Context import android.graphics.Color import android.graphics.drawable.Drawable import android.graphics.drawable.GradientDrawable import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import group.infotech.drawable.dsl.test.R import io.kotlintest.matchers.should import org.jetbrains.anko.dip import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SnapshotTest { val ctx: Context = InstrumentationRegistry.getTargetContext() @Test fun redCircle() { val dsl = shapeDrawable { shape = GradientDrawable.OVAL solidColor = Color.parseColor("#666666") size = ctx.dip(120) } dsl should drawPixelsLike(ctx.drawable(R.drawable.redcircle)) } @Test fun blueStroke() { val dsl = shapeDrawable { shape = GradientDrawable.OVAL stroke { width = ctx.dip(2F) color = Color.parseColor("#78d9ff") } } dsl should drawPixelsLike(ctx.drawable(R.drawable.bluestroke)) } @Test fun solidStroke() { val dsl = shapeDrawable { shape = GradientDrawable.OVAL solidColor = Color.parseColor("#199fff") stroke { width = ctx.dip(2) color = Color.parseColor("#444444") } } dsl should drawPixelsLike(ctx.drawable(R.drawable.solidstroke)) } @Test fun states() { val check = { d: Drawable -> d.state = ViewStates.checked() } val uncheck = { d: Drawable -> d.state = ViewStates.unchecked() } val dsl = stateListDrawable { checkedState { shapeDrawable { solidColor = Color.BLACK } } pressedState { shapeDrawable { solidColor = Color.RED } } defaultState { shapeDrawable { solidColor = Color.WHITE } } } val xml = ctx.drawable(R.drawable.states) dsl.also(check) should drawPixelsLike(xml.also(check)) dsl.also(uncheck) should drawPixelsLike(xml.also(uncheck)) } @Test fun sizes() { val dsl = shapeDrawable { shape = GradientDrawable.OVAL solidColor = Color.parseColor("#666666") size { width = ctx.dip(120) height = ctx.dip(240) } } val xml = ctx.drawable(R.drawable.sizes) dsl should drawPixelsLike(xml) } @Test fun layers() { val dsl = layerDrawable( shapeDrawable { shape = GradientDrawable.OVAL stroke { width = 50 color = Color.parseColor("#000000") } }, shapeDrawable { shape = GradientDrawable.OVAL stroke { width = 20 color = Color.parseColor("#ffffff") } } ) dsl should drawPixelsLike(ctx.drawable(R.drawable.layers)) } @Test fun corners() { val dsl = shapeDrawable { shapeEnum = Shape.RECTANGLE corners { bottomRight = 5f radius = 10f topLeft = 15f } solidColor = Color.parseColor("#666666") } dsl should drawPixelsLike(ctx.drawable(R.drawable.corners)) } }
apache-2.0
79aeb35af5a7e2281aa303e89e242eec
23.156627
73
0.488279
5.141026
false
true
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotatorPre30.kt
5
5269
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.psi.PsiModifier import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.GroovyBundle.message import org.jetbrains.plugins.groovy.annotator.intentions.ReplaceDotFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.* import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.* import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrTraditionalForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrBinaryExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrInstanceOfExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty internal class GroovyAnnotatorPre30(private val holder: AnnotationHolder) : GroovyElementVisitor() { override fun visitModifierList(modifierList: GrModifierList) { val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return holder.createErrorAnnotation(modifier, GroovyBundle.message("default.modifier.in.old.versions")) } override fun visitDoWhileStatement(statement: GrDoWhileStatement) { super.visitDoWhileStatement(statement) holder.createErrorAnnotation(statement.doKeyword, message("unsupported.do.while.statement")) } override fun visitVariableDeclaration(variableDeclaration: GrVariableDeclaration) { super.visitVariableDeclaration(variableDeclaration) if (variableDeclaration.parent is GrTraditionalForClause) { if (variableDeclaration.isTuple) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.tuple.declaration.in.for")) } else if (variableDeclaration.variables.size > 1) { holder.createErrorAnnotation(variableDeclaration, message("unsupported.multiple.variables.in.for")) } } } override fun visitExpressionList(expressionList: GrExpressionList) { super.visitExpressionList(expressionList) if (expressionList.expressions.size > 1) { holder.createErrorAnnotation(expressionList, message("unsupported.expression.list.in.for.update")) } } override fun visitTryResourceList(resourceList: GrTryResourceList) { super.visitTryResourceList(resourceList) holder.createErrorAnnotation(resourceList.firstChild, message("unsupported.resource.list")) } override fun visitBinaryExpression(expression: GrBinaryExpression) { super.visitBinaryExpression(expression) val operator = expression.operationToken val tokenType = operator.node.elementType if (tokenType === T_ID || tokenType === T_NID) { holder.createErrorAnnotation(operator, message("operator.is.not.supported.in", tokenType)) } } override fun visitInExpression(expression: GrInExpression) { super.visitInExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.in")) } } override fun visitInstanceofExpression(expression: GrInstanceOfExpression) { super.visitInstanceofExpression(expression) val negation = expression.negationToken if (negation != null) { holder.createErrorAnnotation(negation, message("unsupported.negated.instanceof")) } } override fun visitAssignmentExpression(expression: GrAssignmentExpression) { super.visitAssignmentExpression(expression) val operator = expression.operationToken if (operator.node.elementType === T_ELVIS_ASSIGN) { holder.createErrorAnnotation(operator, message("unsupported.elvis.assignment")) } } override fun visitIndexProperty(expression: GrIndexProperty) { super.visitIndexProperty(expression) val safeAccessToken = expression.safeAccessToken if (safeAccessToken != null) { holder.createErrorAnnotation(safeAccessToken, message("unsupported.safe.index.access")) } } override fun visitReferenceExpression(expression: GrReferenceExpression) { super.visitReferenceExpression(expression) val dot = expression.dotToken ?: return val tokenType = dot.node.elementType if (tokenType === T_METHOD_REFERENCE) { holder.createErrorAnnotation(dot, message("operator.is.not.supported.in", tokenType)).apply { val descriptor = createDescriptor(dot) val fix = ReplaceDotFix(tokenType, T_METHOD_CLOSURE) registerFix(fix, descriptor) } } } override fun visitArrayInitializer(arrayInitializer: GrArrayInitializer) { super.visitArrayInitializer(arrayInitializer) holder.createErrorAnnotation(arrayInitializer, message("unsupported.array.initializers")) } }
apache-2.0
105cbca245bbb2213ae596168ddcc864
44.817391
140
0.786107
4.768326
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/utils.kt
1
5483
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.ui.RawCommandLineEditor import com.intellij.ui.SearchTextField import com.intellij.ui.TitledSeparator import com.intellij.ui.ToolbarDecorator import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.DslComponentProperty import com.intellij.ui.dsl.builder.HyperlinkEventAction import com.intellij.ui.dsl.builder.SpacingConfiguration import com.intellij.ui.dsl.builder.components.DslLabel import com.intellij.ui.dsl.builder.components.DslLabelType import com.intellij.ui.dsl.builder.components.SegmentedButtonComponent import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.GridLayoutComponentProperty import com.intellij.ui.dsl.gridLayout.toGaps import org.jetbrains.annotations.ApiStatus import javax.swing.* import javax.swing.text.JTextComponent /** * Internal component properties for UI DSL */ @ApiStatus.Internal internal enum class DslComponentPropertyInternal { /** * Removes standard bottom gap from label */ LABEL_NO_BOTTOM_GAP, /** * A mark that component is a cell label, see [Cell.label] * * Value: true */ CELL_LABEL } /** * [JPanel] descendants that should use default vertical gaps around similar to other standard components like labels, text fields etc */ private val DEFAULT_VERTICAL_GAP_COMPONENTS = setOf( RawCommandLineEditor::class, SearchTextField::class, SegmentedButtonComponent::class, SegmentedButtonToolbar::class, TextFieldWithBrowseButton::class, TitledSeparator::class ) /** * Throws exception instead of logging warning. Useful while forms building to avoid layout mistakes */ private const val FAIL_ON_WARN = false private val LOG = Logger.getInstance("Jetbrains UI DSL") /** * Components that can have assigned labels */ private val ALLOWED_LABEL_COMPONENTS = listOf( JComboBox::class, JSlider::class, JSpinner::class, JTable::class, JTextComponent::class, JTree::class, SegmentedButtonComponent::class, SegmentedButtonToolbar::class ) internal val JComponent.origin: JComponent get() { return when (this) { is TextFieldWithBrowseButton -> textField is ComponentWithBrowseButton<*> -> childComponent else -> this } } internal fun prepareVisualPaddings(component: JComponent): Gaps { var customVisualPaddings = component.getClientProperty(DslComponentProperty.VISUAL_PADDINGS) as? Gaps if (customVisualPaddings == null) { // todo Move into components implementation // Patch visual paddings for known components customVisualPaddings = when (component) { is RawCommandLineEditor -> component.editorField.insets.toGaps() is SearchTextField -> component.textEditor.insets.toGaps() is JScrollPane -> Gaps.EMPTY is ComponentWithBrowseButton<*> -> component.childComponent.insets.toGaps() else -> { if (component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) != null) { Gaps.EMPTY } else { null } } } } if (customVisualPaddings == null) { return component.insets.toGaps() } component.putClientProperty(GridLayoutComponentProperty.SUB_GRID_AUTO_VISUAL_PADDINGS, false) return customVisualPaddings } internal fun getComponentGaps(left: Int, right: Int, component: JComponent, spacing: SpacingConfiguration): Gaps { val top = getDefaultVerticalGap(component, spacing) var bottom = top if (component is JLabel && component.getClientProperty(DslComponentPropertyInternal.LABEL_NO_BOTTOM_GAP) == true) { bottom = 0 } return Gaps(top = top, left = left, bottom = bottom, right = right) } /** * Returns default top and bottom gap for [component]. All non [JPanel] components or * [DEFAULT_VERTICAL_GAP_COMPONENTS] have default vertical gap, zero otherwise */ internal fun getDefaultVerticalGap(component: JComponent, spacing: SpacingConfiguration): Int { val noDefaultVerticalGap = component is JPanel && component.getClientProperty(ToolbarDecorator.DECORATOR_KEY) == null && !DEFAULT_VERTICAL_GAP_COMPONENTS.any { clazz -> clazz.isInstance(component) } return if (noDefaultVerticalGap) 0 else spacing.verticalComponentGap } internal fun createComment(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): DslLabel { val result = DslLabel(DslLabelType.COMMENT) result.action = action result.maxLineLength = maxLineLength result.text = text return result } internal fun isAllowedLabel(cell: CellBaseImpl<*>?): Boolean { return cell is CellImpl<*> && ALLOWED_LABEL_COMPONENTS.any { clazz -> clazz.isInstance(cell.component.origin) } } internal fun labelCell(label: JLabel, cell: CellBaseImpl<*>?) { if (isAllowedLabel(cell)) { label.labelFor = (cell as CellImpl<*>).component.origin } } internal fun warn(message: String) { if (FAIL_ON_WARN) { throw UiDslException(message) } else { LOG.warn(message) } }
apache-2.0
4f1ab813ecfeefad4d89d08637dff85c
32.638037
158
0.750502
4.494262
false
false
false
false
ogarcia/ultrasonic
core/domain/src/main/kotlin/org/moire/ultrasonic/domain/MusicDirectory.kt
2
2228
package org.moire.ultrasonic.domain import java.io.Serializable import java.util.Date class MusicDirectory { var name: String? = null private val children = mutableListOf<Entry>() fun addAll(entries: Collection<Entry>) { children.addAll(entries) } fun addFirst(child: Entry) { children.add(0, child) } fun addChild(child: Entry) { children.add(child) } fun findChild(id: String): Entry? = children.lastOrNull { it.id == id } fun getAllChild(): List<Entry> = children.toList() @JvmOverloads fun getChildren( includeDirs: Boolean = true, includeFiles: Boolean = true ): List<Entry> { if (includeDirs && includeFiles) { return children } return children.filter { it.isDirectory && includeDirs || !it.isDirectory && includeFiles } } data class Entry( var id: String? = null, var parent: String? = null, var isDirectory: Boolean = false, var title: String? = null, var album: String? = null, var albumId: String? = null, var artist: String? = null, var artistId: String? = null, var track: Int? = 0, var year: Int? = 0, var genre: String? = null, var contentType: String? = null, var suffix: String? = null, var transcodedContentType: String? = null, var transcodedSuffix: String? = null, var coverArt: String? = null, var size: Long? = null, var songCount: Long? = null, var duration: Int? = null, var bitRate: Int? = null, var path: String? = null, var isVideo: Boolean = false, var starred: Boolean = false, var discNumber: Int? = null, var type: String? = null, var created: Date? = null, var closeness: Int = 0, var bookmarkPosition: Int = 0, var userRating: Int? = null, var averageRating: Float? = null ) : Serializable { fun setDuration(duration: Long) { this.duration = duration.toInt() } companion object { private const val serialVersionUID = -3339106650010798108L } } }
gpl-3.0
44e438761c3ae19f396a76560f426f30
27.564103
99
0.575853
4.164486
false
false
false
false
MGaetan89/ShowsRage
app/src/test/kotlin/com/mgaetan89/showsrage/fragment/AddShowOptionsFragment_GetAllowedQualityTest.kt
1
2693
package com.mgaetan89.showsrage.fragment import android.content.res.Resources import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.widget.Spinner import com.mgaetan89.showsrage.EmptyFragmentHostCallback import com.mgaetan89.showsrage.R import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.spy @RunWith(Parameterized::class) class AddShowOptionsFragment_GetAllowedQualityTest(val spinner: Spinner?, val allowedQuality: String?) { private lateinit var fragment: AddShowOptionsFragment @Before fun before() { val resources = mock(Resources::class.java) `when`(resources.getStringArray(R.array.allowed_qualities_keys)).thenReturn(arrayOf("sdtv", "sddvd", "hdtv", "rawhdtv", "fullhdtv", "hdwebdl", "fullhdwebdl", "hdbluray", "fullhdbluray", "unknown")) val activity = mock(FragmentActivity::class.java) `when`(activity.resources).thenReturn(resources) this.fragment = spy(AddShowOptionsFragment()) try { val fragmentHostField = Fragment::class.java.getDeclaredField("mHost") fragmentHostField.isAccessible = true fragmentHostField.set(this.fragment, EmptyFragmentHostCallback(activity)) } catch (ignored: IllegalAccessException) { } catch (ignored: NoSuchFieldException) { } `when`(this.fragment.resources).thenReturn(resources) } @Test fun getAllowedQuality() { assertThat(this.fragment.getAllowedQuality(this.spinner)).isEqualTo(this.allowedQuality) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any?>> { return listOf( arrayOf<Any?>(null, "sdtv"), arrayOf<Any?>(getMockedSpinner(-1), null), arrayOf<Any?>(getMockedSpinner(0), null), arrayOf<Any?>(getMockedSpinner(1), "sdtv"), arrayOf<Any?>(getMockedSpinner(2), "sddvd"), arrayOf<Any?>(getMockedSpinner(3), "hdtv"), arrayOf<Any?>(getMockedSpinner(4), "rawhdtv"), arrayOf<Any?>(getMockedSpinner(5), "fullhdtv"), arrayOf<Any?>(getMockedSpinner(6), "hdwebdl"), arrayOf<Any?>(getMockedSpinner(7), "fullhdwebdl"), arrayOf<Any?>(getMockedSpinner(8), "hdbluray"), arrayOf<Any?>(getMockedSpinner(9), "fullhdbluray"), arrayOf<Any?>(getMockedSpinner(10), "unknown"), arrayOf<Any?>(getMockedSpinner(11), null) ) } private fun getMockedSpinner(selectedItemPosition: Int): Spinner { val spinner = mock(Spinner::class.java) `when`(spinner.selectedItemPosition).thenReturn(selectedItemPosition) return spinner } } }
apache-2.0
de3e45ad0d93ad4a9ed7611f16e38ef6
33.974026
199
0.74638
3.488342
false
false
false
false
paplorinc/intellij-community
plugins/stats-collector/log-events/test/com/intellij/stats/completion/RealDataValidation.kt
2
2344
/* * 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.stats.completion import com.intellij.stats.validation.EventLine import com.intellij.stats.validation.InputSessionValidator import com.intellij.stats.validation.SessionValidationResult import org.junit.Assert import org.junit.Before import org.junit.Test import java.io.File class RealDataValidation { private lateinit var separator: InputSessionValidator val sessionStatuses = hashMapOf<String, Boolean>() @Before fun setup() { sessionStatuses.clear() val result = object : SessionValidationResult { override fun addErrorSession(errorSession: List<EventLine>) { val sessionUid = errorSession.first().sessionUid ?: return sessionStatuses[sessionUid] = false } override fun addValidSession(validSession: List<EventLine>) { val sessionUid = validSession.first().sessionUid ?: return sessionStatuses[sessionUid] = true } } separator = InputSessionValidator(result) } @Test fun testRealData() { val file = file("real_data") val files = file.list().sortedBy { it.substringAfter("_").toInt() } val chunkFiles = files.map { "real_data/$it" } val totalLines = chunkFiles.map { file(it) }.map { it.reader().readLines() }.flatten() separator.validate(totalLines) val invalidSessions = sessionStatuses.count { !it.value } val validSessions = sessionStatuses.count { it.value } Assert.assertEquals(7, validSessions) Assert.assertEquals(6, invalidSessions) } private fun file(path: String): File { return File(javaClass.classLoader.getResource(path).file) } }
apache-2.0
ce18a6ced75a37482ce7fbddd37f1378
32.5
94
0.6843
4.542636
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/sequentialparsers/impl/ImageParser.kt
1
2114
package org.intellij.markdown.parser.sequentialparsers.impl import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.sequentialparsers.SequentialParser import org.intellij.markdown.parser.sequentialparsers.SequentialParserUtil import org.intellij.markdown.parser.sequentialparsers.TokensCache import java.util.ArrayList public class ImageParser : SequentialParser { override fun parse(tokens: TokensCache, rangesToGlue: Collection<Range<Int>>): SequentialParser.ParsingResult { var result = SequentialParser.ParsingResult() val delegateIndices = ArrayList<Int>() val indices = SequentialParserUtil.textRangesToIndices(rangesToGlue) var iterator: TokensCache.Iterator = tokens.ListIterator(indices, 0) while (iterator.type != null) { if (iterator.type == MarkdownTokenTypes.EXCLAMATION_MARK && iterator.rawLookup(1) == MarkdownTokenTypes.LBRACKET) { val localDelegates = ArrayList<Int>() val resultNodes = ArrayList<SequentialParser.Node>() val afterLink = InlineLinkParser.parseInlineLink(resultNodes, localDelegates, iterator.advance()) ?: run { resultNodes.clear() localDelegates.clear() ReferenceLinkParser.parseReferenceLink(resultNodes, localDelegates, iterator.advance()) } if (afterLink != null) { resultNodes.add(SequentialParser.Node(iterator.index..afterLink.index + 1, MarkdownElementTypes.IMAGE)) iterator = afterLink.advance() result = result.withNodes(resultNodes).withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(localDelegates)) continue } } delegateIndices.add(iterator.index) iterator = iterator.advance() } return result.withFurtherProcessing(SequentialParserUtil.indicesToTextRanges(delegateIndices)) } }
apache-2.0
4b4d7ea092ff2741e330216d81651dba
47.068182
138
0.677862
5.62234
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/LookaheadText.kt
1
3818
package org.intellij.markdown.parser public class LookaheadText(public val text: String) { private val lines: List<String> = text.split('\n') public val startPosition: Position? = if (text.isNotEmpty()) Position(0, -1, -1).nextPosition() else null public inner class Position internal constructor(private val lineN: Int, private val localPos: Int, // -1 if on newline before private val globalPos: Int) { init { assert(lineN < lines.size()) assert(localPos >= -1 && localPos < lines.get(lineN).length()) } override fun toString(): String { return "Position: '${ if (localPos == -1) { "\\n" + currentLine } else { currentLine.substring(localPos) } }'" } public val offset: Int get() = globalPos public val offsetInCurrentLine: Int get() = localPos public val nextLineOffset: Int? get() = if (lineN + 1 < lines.size()) { globalPos + (currentLine.length() - localPos) } else { null } public val nextLineOrEofOffset: Int get() = globalPos + (currentLine.length() - localPos) public val textFromPosition: CharSequence get() = text.subSequence(globalPos, text.length()) public val currentLine: String get() = lines.get(lineN) public val currentLineFromPosition: CharSequence get() = currentLine.subSequence(offsetInCurrentLine, currentLine.length()) public val nextLine: String? get() = if (lineN + 1 < lines.size()) { lines.get(lineN + 1) } else { null } public val prevLine: String? get() = if (lineN > 0) { lines.get(lineN - 1) } else { null } public val char: Char get() = text.charAt(globalPos) public fun nextPosition(delta: Int = 1): Position? { var remaining = delta var currentPosition = this while (true) { if (currentPosition.localPos + remaining < currentPosition.currentLine.length()) { return Position(currentPosition.lineN, currentPosition.localPos + remaining, currentPosition.globalPos + remaining) } else { val nextLine = currentPosition.nextLineOffset if (nextLine == null) { return null } else { val payload = currentPosition.currentLine.length() - currentPosition.localPos currentPosition = Position(currentPosition.lineN + 1, -1, currentPosition.globalPos + payload) remaining -= payload } } } } public fun nextLinePosition(): Position? { val nextLine = nextLineOffset ?: return null return nextPosition(nextLine - offset) } public fun charsToNonWhitespace(): Int? { val line = currentLine var offset = localPos while (offset < line.length()) { if (offset >= 0) { val c = line[offset] if (c != ' ' && c != '\t') { return offset - localPos } } offset++ } return null } } }
apache-2.0
f55f5497adf643f8d433fd2547f66919
31.641026
118
0.47407
5.415603
false
false
false
false
google/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookIntervalPointerImpl.kt
1
8546
package org.jetbrains.plugins.notebooks.visualization import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.editor.Editor import com.intellij.util.EventDispatcher import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.OnEdited import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.OnInserted import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.OnRemoved import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.OnSwapped import org.jetbrains.plugins.notebooks.visualization.NotebookIntervalPointersEvent.Change class NotebookIntervalPointerFactoryImplProvider : NotebookIntervalPointerFactoryProvider { override fun create(editor: Editor): NotebookIntervalPointerFactory = NotebookIntervalPointerFactoryImpl(NotebookCellLines.get(editor)) } private class NotebookIntervalPointerImpl(var interval: NotebookCellLines.Interval?) : NotebookIntervalPointer { override fun get(): NotebookCellLines.Interval? = interval override fun toString(): String = "NotebookIntervalPointerImpl($interval)" } class NotebookIntervalPointerFactoryImpl(private val notebookCellLines: NotebookCellLines) : NotebookIntervalPointerFactory, NotebookCellLines.IntervalListener { private val pointers = ArrayList<NotebookIntervalPointerImpl>() private var mySavedChanges: Iterable<NotebookIntervalPointerFactory.Change>? = null override val changeListeners: EventDispatcher<NotebookIntervalPointerFactory.ChangeListener> = EventDispatcher.create(NotebookIntervalPointerFactory.ChangeListener::class.java) init { pointers.addAll(notebookCellLines.intervals.asSequence().map { NotebookIntervalPointerImpl(it) }) notebookCellLines.intervalListeners.addListener(this) } override fun create(interval: NotebookCellLines.Interval): NotebookIntervalPointer = pointers[interval.ordinal].also { require(it.interval == interval) } override fun <T> modifyingPointers(changes: Iterable<NotebookIntervalPointerFactory.Change>, modifyDocumentAction: () -> T): T { try { require(mySavedChanges == null) { "NotebookIntervalPointerFactory hints already added somewhere" } mySavedChanges = changes return modifyDocumentAction().also { mySavedChanges?.let { val eventBuilder = NotebookIntervalPointersEventBuilder() applyChanges(it, eventBuilder) eventBuilder.applyEvent(changeListeners, cellLinesEvent = null) } } } finally { mySavedChanges = null } } override fun documentChanged(event: NotebookCellLinesEvent) { val eventBuilder = NotebookIntervalPointersEventBuilder() updateIntervals(event, eventBuilder) mySavedChanges?.let { applyChanges(it, eventBuilder) mySavedChanges = null } eventBuilder.applyEvent(changeListeners, event) } private fun updateIntervals(e: NotebookCellLinesEvent, eventBuilder: NotebookIntervalPointersEventBuilder) { when { !e.isIntervalsChanged() -> { // content edited without affecting intervals values eventBuilder.onEdited((e.oldAffectedIntervals + e.newAffectedIntervals).distinct().sortedBy { it.ordinal }) } e.oldIntervals.size == 1 && e.newIntervals.size == 1 && e.oldIntervals.first().type == e.newIntervals.first().type -> { // only one interval changed size pointers[e.newIntervals.first().ordinal].interval = e.newIntervals.first() eventBuilder.onEdited(e.newAffectedIntervals) if (e.newIntervals.first() !in e.newAffectedIntervals) { eventBuilder.onEdited(e.newIntervals.first()) } } else -> { for (old in e.oldIntervals.asReversed()) { pointers[old.ordinal].interval = null pointers.removeAt(old.ordinal) } eventBuilder.onRemoved(e.oldIntervals) e.newIntervals.firstOrNull()?.also { firstNew -> pointers.addAll(firstNew.ordinal, e.newIntervals.map { NotebookIntervalPointerImpl(it) }) } eventBuilder.onInserted(e.newIntervals) eventBuilder.onEdited(e.newAffectedIntervals, excluded = e.newIntervals) } } val invalidPointersStart = e.newIntervals.firstOrNull()?.let { it.ordinal + e.newIntervals.size } ?: e.oldIntervals.firstOrNull()?.ordinal ?: pointers.size updatePointersFrom(invalidPointersStart) } private fun applyChanges(changes: Iterable<NotebookIntervalPointerFactory.Change>, eventBuilder: NotebookIntervalPointersEventBuilder) { for(hint in changes) { when (hint) { is NotebookIntervalPointerFactory.Invalidate -> applyChange(eventBuilder, hint) is NotebookIntervalPointerFactory.Swap -> applyChange(eventBuilder, hint) } } } private fun applyChange(eventBuilder: NotebookIntervalPointersEventBuilder, hint: NotebookIntervalPointerFactory.Invalidate) { val ptr = hint.ptr as NotebookIntervalPointerImpl val interval = ptr.interval if (interval == null) return invalidate(ptr) eventBuilder.onRemoved(interval) eventBuilder.onInserted(interval) } private fun applyChange(eventBuilder: NotebookIntervalPointersEventBuilder, hint: NotebookIntervalPointerFactory.Swap) { val success = trySwapPointers(eventBuilder, hint) } private fun trySwapPointers(eventBuilder: NotebookIntervalPointersEventBuilder, hint: NotebookIntervalPointerFactory.Swap): Boolean { val firstPtr = pointers.getOrNull(hint.firstOrdinal) val secondPtr = pointers.getOrNull(hint.secondOrdinal) if (firstPtr == null || secondPtr == null) { thisLogger().error("cannot swap invalid NotebookIntervalPointers: ${hint.firstOrdinal} and ${hint.secondOrdinal}") return false } if (hint.firstOrdinal == hint.secondOrdinal) return false // nothing to do val interval = firstPtr.interval!! firstPtr.interval = secondPtr.interval secondPtr.interval = interval pointers[hint.firstOrdinal] = secondPtr pointers[hint.secondOrdinal] = firstPtr eventBuilder.onSwapped(hint.firstOrdinal, hint.secondOrdinal) return true } private fun invalidate(ptr: NotebookIntervalPointerImpl) { ptr.interval?.let { interval -> pointers[interval.ordinal] = NotebookIntervalPointerImpl(interval) ptr.interval = null } } private fun updatePointersFrom(pos: Int) { for (i in pos until pointers.size) { pointers[i].interval = notebookCellLines.intervals[i] } } } @JvmInline private value class NotebookIntervalPointersEventBuilder(val accumulatedChanges: MutableList<Change> = mutableListOf<Change>()) { fun applyEvent(eventDispatcher: EventDispatcher<NotebookIntervalPointerFactory.ChangeListener>, cellLinesEvent: NotebookCellLinesEvent?) { val event = NotebookIntervalPointersEvent(accumulatedChanges, cellLinesEvent) eventDispatcher.multicaster.onUpdated(event) } fun onEdited(interval: NotebookCellLines.Interval) { accumulatedChanges.add(OnEdited(interval.ordinal)) } fun onEdited(intervals: List<NotebookCellLines.Interval>, excluded: List<NotebookCellLines.Interval> = emptyList()) { if (intervals.isEmpty()) return val overLast = intervals.last().ordinal + 1 val excludedRange = (excluded.firstOrNull()?.ordinal ?: overLast)..(excluded.lastOrNull()?.ordinal ?: overLast) for (interval in intervals) { if (interval.ordinal !in excludedRange) { accumulatedChanges.add(OnEdited(interval.ordinal)) } } } fun onRemoved(interval: NotebookCellLines.Interval) { accumulatedChanges.add(OnRemoved(interval.ordinal..interval.ordinal)) } fun onRemoved(sequentialIntervals: List<NotebookCellLines.Interval>) { if (sequentialIntervals.isNotEmpty()) { accumulatedChanges.add(OnRemoved(sequentialIntervals.first().ordinal..sequentialIntervals.last().ordinal)) } } fun onInserted(interval: NotebookCellLines.Interval) { accumulatedChanges.add(OnInserted(interval.ordinal..interval.ordinal)) } fun onInserted(sequentialIntervals: List<NotebookCellLines.Interval>) { if (sequentialIntervals.isNotEmpty()) { accumulatedChanges.add(OnInserted(sequentialIntervals.first().ordinal..sequentialIntervals.last().ordinal)) } } fun onSwapped(fromOrdinal: Int, toOrdinal: Int) { accumulatedChanges.add(OnSwapped(fromOrdinal, toOrdinal)) } }
apache-2.0
f6a4de698a68c702b2514fd6972b817c
38.027397
161
0.743272
4.844671
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/IfToWhenIntention.kt
1
10582
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getSubjectToIntroduce import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceSubject import org.jetbrains.kotlin.idea.intentions.branchedTransformations.unwrapBlockOrParenthesis import org.jetbrains.kotlin.idea.quickfix.AddLoopLabelFix import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* class IfToWhenIntention : SelfTargetingRangeIntention<KtIfExpression>( KtIfExpression::class.java, KotlinBundle.lazyMessage("replace.if.with.when") ) { override fun applicabilityRange(element: KtIfExpression): TextRange? { if (element.then == null) return null return element.ifKeyword.textRange } private fun canPassThrough(expression: KtExpression?): Boolean = when (expression) { is KtReturnExpression, is KtThrowExpression -> false is KtBlockExpression -> expression.statements.all { canPassThrough(it) } is KtIfExpression -> canPassThrough(expression.then) || canPassThrough(expression.`else`) else -> true } private fun buildNextBranch(ifExpression: KtIfExpression): KtExpression? { var nextSibling = ifExpression.getNextSiblingIgnoringWhitespaceAndComments() ?: return null return when (nextSibling) { is KtIfExpression -> if (nextSibling.then == null) null else nextSibling else -> { val builder = StringBuilder() while (true) { builder.append(nextSibling.text) nextSibling = nextSibling.nextSibling ?: break } KtPsiFactory(ifExpression.project).createBlock(builder.toString()).takeIf { it.statements.isNotEmpty() } } } } private fun KtIfExpression.siblingsUpTo(other: KtExpression): List<PsiElement> { val result = ArrayList<PsiElement>() var nextSibling = nextSibling // We delete elements up to the next if (or up to the end of the surrounding block) while (nextSibling != null && nextSibling != other) { // RBRACE closes the surrounding block, so it should not be copied / deleted if (nextSibling !is PsiWhiteSpace && nextSibling.node.elementType != KtTokens.RBRACE) { result.add(nextSibling) } nextSibling = nextSibling.nextSibling } return result } private class LabelLoopJumpVisitor(private val nearestLoopIfAny: KtLoopExpression?) : KtVisitorVoid() { val labelName: String? by lazy { nearestLoopIfAny?.let { loop -> (loop.parent as? KtLabeledExpression)?.getLabelName() ?: AddLoopLabelFix.getUniqueLabelName(loop) } } var labelRequired = false fun KtExpressionWithLabel.addLabelIfNecessary(): KtExpressionWithLabel { if (this.getLabelName() != null) { // Label is already present, no need to add return this } if (this.getStrictParentOfType<KtLoopExpression>() != nearestLoopIfAny) { // 'for' inside 'if' return this } if (!languageVersionSettings.supportsFeature(LanguageFeature.AllowBreakAndContinueInsideWhen) && labelName != null) { val jumpWithLabel = KtPsiFactory(project).createExpression("$text@$labelName") as KtExpressionWithLabel labelRequired = true return replaced(jumpWithLabel) } return this } override fun visitBreakExpression(expression: KtBreakExpression) { expression.addLabelIfNecessary() } override fun visitContinueExpression(expression: KtContinueExpression) { expression.addLabelIfNecessary() } override fun visitKtElement(element: KtElement) { element.acceptChildren(this) } } private fun BuilderByPattern<*>.appendElseBlock(block: KtExpression?, unwrapBlockOrParenthesis: Boolean = false) { appendFixedText("else->") appendExpression(if (unwrapBlockOrParenthesis) block?.unwrapBlockOrParenthesis() else block) appendFixedText("\n") } private fun KtIfExpression.topmostIfExpression(): KtIfExpression { var target = this while (true) { val container = target.parent as? KtContainerNodeForControlStructureBody ?: break val parent = container.parent as? KtIfExpression ?: break if (parent.`else` != target) break target = parent } return target } override fun applyTo(element: KtIfExpression, editor: Editor?) { val ifExpression = element.topmostIfExpression() val siblings = ifExpression.siblings() val elementCommentSaver = CommentSaver(ifExpression) val fullCommentSaver = CommentSaver(PsiChildRange(ifExpression, siblings.last()), saveLineBreaks = true) val toDelete = ArrayList<PsiElement>() var applyFullCommentSaver = true val loop = ifExpression.getStrictParentOfType<KtLoopExpression>() val loopJumpVisitor = LabelLoopJumpVisitor(loop) var whenExpression = KtPsiFactory(ifExpression.project).buildExpression { appendFixedText("when {\n") var currentIfExpression = ifExpression var baseIfExpressionForSyntheticBranch = currentIfExpression var canPassThrough = false while (true) { val condition = currentIfExpression.condition val orBranches = ArrayList<KtExpression>() if (condition != null) { orBranches.addOrBranches(condition) } appendExpressions(orBranches, separator = "||") appendFixedText("->") val currentThenBranch = currentIfExpression.then appendExpression(currentThenBranch) appendFixedText("\n") canPassThrough = canPassThrough || canPassThrough(currentThenBranch) val currentElseBranch = currentIfExpression.`else` if (currentElseBranch == null) { // Try to build synthetic if / else according to KT-10750 val syntheticElseBranch = if (canPassThrough) null else buildNextBranch(baseIfExpressionForSyntheticBranch) if (syntheticElseBranch == null) { applyFullCommentSaver = false break } toDelete.addAll(baseIfExpressionForSyntheticBranch.siblingsUpTo(syntheticElseBranch)) if (syntheticElseBranch is KtIfExpression) { baseIfExpressionForSyntheticBranch = syntheticElseBranch currentIfExpression = syntheticElseBranch toDelete.add(syntheticElseBranch) } else { appendElseBlock(syntheticElseBranch, unwrapBlockOrParenthesis = true) break } } else if (currentElseBranch is KtIfExpression) { currentIfExpression = currentElseBranch } else { appendElseBlock(currentElseBranch) applyFullCommentSaver = false break } } appendFixedText("}") } as KtWhenExpression if (whenExpression.getSubjectToIntroduce(checkConstants = false) != null) { whenExpression = whenExpression.introduceSubject(checkConstants = false) ?: return } val result = ifExpression.replaced(whenExpression) editor?.caretModel?.moveToOffset(result.startOffset) (if (applyFullCommentSaver) fullCommentSaver else elementCommentSaver).restore(result) toDelete.forEach(PsiElement::delete) result.accept(loopJumpVisitor) val labelName = loopJumpVisitor.labelName if (loop != null && loopJumpVisitor.labelRequired && labelName != null && loop.parent !is KtLabeledExpression) { val labeledLoopExpression = KtPsiFactory(result.project).createLabeledExpression(labelName) labeledLoopExpression.baseExpression!!.replace(loop) val replacedLabeledLoopExpression = loop.replace(labeledLoopExpression) // For some reason previous operation can break adjustments val project = loop.project if (editor != null) { val documentManager = PsiDocumentManager.getInstance(project) documentManager.commitDocument(editor.document) documentManager.doPostponedOperationsAndUnblockDocument(editor.document) val psiFile = documentManager.getPsiFile(editor.document)!! CodeStyleManager.getInstance(project).adjustLineIndent(psiFile, replacedLabeledLoopExpression.textRange) } } } private fun MutableList<KtExpression>.addOrBranches(expression: KtExpression): List<KtExpression> { if (expression is KtBinaryExpression && expression.operationToken == KtTokens.OROR) { val left = expression.left val right = expression.right if (left != null && right != null) { addOrBranches(left) addOrBranches(right) return this } } add(KtPsiUtil.safeDeparenthesize(expression, true)) return this } }
apache-2.0
3c94a221e07c216762537267a1b99871
43.091667
158
0.650161
5.78884
false
false
false
false
vanniktech/RxBinding
buildSrc/src/main/kotlin/com/jakewharton/rxbinding/project/ValidateBindingsTask.kt
1
5296
package com.jakewharton.rxbinding.project import com.github.javaparser.JavaParser import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration import com.github.javaparser.ast.body.MethodDeclaration import com.github.javaparser.ast.body.Parameter import com.github.javaparser.ast.type.ClassOrInterfaceType import com.github.javaparser.ast.type.ReferenceType import com.github.javaparser.ast.type.WildcardType import com.github.javaparser.ast.visitor.VoidVisitorAdapter import org.gradle.api.tasks.SourceTask import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.incremental.IncrementalTaskInputs import java.io.File open class ValidateBindingsTask : SourceTask() { @TaskAction @Suppress("unused", "UNUSED_PARAMETER") fun validate(inputs: IncrementalTaskInputs) { getSource().forEach { verifyJavaFile(it) } } private fun verifyJavaFile(javaFile: File) { val cu = JavaParser.parse(javaFile) cu.accept(object : VoidVisitorAdapter<Any>() { override fun visit(n: MethodDeclaration, arg: Any?) { verifyMethodAnnotations(n) verifyParameters(n) verifyReturnType(n) verifyNullChecks(n) // Explicitly avoid going deeper, we only care about top level methods. Otherwise // we'd hit anonymous inner classes and whatnot } }, null) } /** Validates that method signatures have @CheckResult and @NonNull annotations */ fun verifyMethodAnnotations(method: MethodDeclaration) { val annotationNames = method.annotations.map { it.name.toString() } METHOD_ANNOTATIONS.forEach { annotation: String -> if (!annotationNames.contains(annotation)) { throw IllegalStateException("Missing required @$annotation method annotation on ${(method.getEnclosingClass()).name}#${method.name}") } } } /** * Validates that: * - reference type parameters have @NonNull annotations * - Second parameters that are instances of Func1 have a wildcard first parameterized type */ fun verifyParameters(method: MethodDeclaration) { val params = method.parameters // Validate annotations params.forEach { p -> if (p.type is ReferenceType) { if (p.annotations == null || !p.annotations.map { it.name.toString() }.contains("NonNull")) { throw IllegalStateException("Missing required @NonNull annotation on ${method.getEnclosingClass().name}#${method.name} parameter: \"${p.id.name}\"") } } } // Validate Func1 params if (params.size >= 2 && params[1].type is ReferenceType && params[1].coerceClassType().name == "Func1") { val func1Param: Parameter = params[1] if (!func1Param.typeHasTypeArgs() || func1Param.coerceClassType().typeArgs[0] !is WildcardType) { throw IllegalStateException("Missing wildcard type parameter declaration on ${method.getEnclosingClass().name}#${method.name} Func1 parameter: \"${func1Param.id.name}\"") } } } /** Validates that Action1 return types have proper wildcard bounds */ fun verifyReturnType(method: MethodDeclaration) { if (method.returnTypeAsType().name == "Action1") { if (!method.returnTypeHasTypeArgs() || method.returnTypeAsType().typeArgs[0] !is WildcardType) { throw IllegalStateException("Missing wildcard type parameter declaration on ${method.getEnclosingClass().name}#${method.name}'s Action1 return type") } } } /** Validates that reference type parameters have corresponding checkNotNull calls at the beginning of the body */ fun verifyNullChecks(method: MethodDeclaration) { val parameters = method.parameters val statements = method.body.stmts parameters .filter { it.type is ReferenceType } .map { it.id.name } .zip(statements, { param, stmt -> Pair(param, stmt) }) .forEach { val pName = it.first val expected = "checkNotNull($pName, \"$pName == null\");" val found = it.second.toString() if (expected != found) { throw IllegalStateException("Missing proper checkNotNull call on parameter " + pName + " in " + prettyMethodSignature(method) + "\nExpected:\t" + expected + "\nFound:\t" + found ) } } } /** Generates a nice String representation of the method signature (e.g. RxView#clicks(View)) */ private fun prettyMethodSignature(method: MethodDeclaration): String { val parameterTypeNames = method.parameters.joinToString { it.type.toString() } return "${(method.getEnclosingClass()).name}#${method.name}($parameterTypeNames)" } private fun Parameter.coerceClassType() = (this.type as ReferenceType).type as ClassOrInterfaceType private fun Parameter.typeHasTypeArgs() = coerceClassType().typeArgs?.isNotEmpty() ?: false private fun MethodDeclaration.getEnclosingClass() = this.parentNode as ClassOrInterfaceDeclaration private fun MethodDeclaration.returnTypeAsType() = (this.type as ReferenceType).type as ClassOrInterfaceType private fun MethodDeclaration.returnTypeHasTypeArgs() = returnTypeAsType().typeArgs?.isNotEmpty() ?: false } private val METHOD_ANNOTATIONS = listOf( "CheckResult", "NonNull" )
apache-2.0
a5eacb3383468c23fa256df8494dba68
37.941176
178
0.695242
4.573402
false
false
false
false
StepicOrg/stepik-android
app/src/debug/java/org/stepik/android/view/debug/ui/adapter/delegate/InAppPurchaseAdapterDelegate.kt
1
1900
package org.stepik.android.view.debug.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import com.android.billingclient.api.Purchase import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.debug.item_in_app_purchase.* import org.stepic.droid.R import org.stepic.droid.util.DateTimeHelper import org.stepic.droid.util.toObject import org.stepik.android.domain.course.model.CoursePurchasePayload import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder import java.util.Date import java.util.TimeZone class InAppPurchaseAdapterDelegate( private val onItemClick: (Purchase) -> Unit ) : AdapterDelegate<Purchase, DelegateViewHolder<Purchase>>() { override fun isForViewType(position: Int, data: Purchase): Boolean = true override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<Purchase> = ViewHolder(createView(parent, R.layout.item_in_app_purchase)) private inner class ViewHolder(override val containerView: View) : DelegateViewHolder<Purchase>(containerView), LayoutContainer { init { inAppPurchaseConsumeAction.setOnClickListener { itemData?.let(onItemClick) } } override fun onBind(data: Purchase) { inAppPurchaseSku.text = data.skus.first() inAppPurchaseTime.text = context.getString(R.string.debug_purchase_date, DateTimeHelper.getPrintableDate(Date(data.purchaseTime), DateTimeHelper.DISPLAY_DATETIME_PATTERN, TimeZone.getDefault())) inAppPurchaseStatus.text = context.getString(R.string.debug_purchase_status, data.purchaseState.toString()) inAppPurchaseCourse.isVisible = data.developerPayload.isNotEmpty() inAppPurchaseUser.isVisible = data.developerPayload.isNotEmpty() } } }
apache-2.0
9f036c696571995bfe2e04df1ed6b839
46.525
206
0.772632
4.545455
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitLegendPanel.kt
3
2725
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.ui import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.ui.JBColor import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import kotlin.math.max import kotlin.properties.Delegates.observable private val FileStatus.attributes get() = SimpleTextAttributes( SimpleTextAttributes.STYLE_PLAIN, JBColor { color ?: UIUtil.getLabelForeground() }) private fun Int.formatInt(): String = "%,d".format(this) // NON-NLS open class CommitLegendPanel(private val myInfoCalculator: InfoCalculator) { private val myRootPanel = SimpleColoredComponent() private val isPanelEmpty get() = !myRootPanel.iterator().hasNext() val component get() = myRootPanel var isCompact: Boolean by observable(false) { _, oldValue, newValue -> if (oldValue != newValue) update() } open fun update() { myRootPanel.clear() appendLegend() myRootPanel.isVisible = !isPanelEmpty } private fun appendLegend() = with(myInfoCalculator) { appendAdded(includedNew, includedUnversioned) append(includedModified, FileStatus.MODIFIED, message("commit.legend.modified"), "*") append(includedDeleted, FileStatus.DELETED, message("commit.legend.deleted"), "-") } @JvmOverloads protected fun append(included: Int, fileStatus: FileStatus, label: String, compactLabel: @Nls String? = null) { if (included > 0) { if (!isPanelEmpty) { appendSpace() } myRootPanel.append(format(included.formatInt(), label, compactLabel), fileStatus.attributes) } } private fun appendAdded(new: Int, unversioned: Int) { if (new > 0 || unversioned > 0) { if (!isPanelEmpty) { appendSpace() } val value = if (new > 0 && unversioned > 0) "${new.formatInt()}+${unversioned.formatInt()}" else max(new, unversioned).formatInt() myRootPanel.append(format(value, message("commit.legend.new"), "+"), FileStatus.ADDED.attributes) } } protected fun appendSpace() { myRootPanel.append(" ") } @Nls private fun format(value: Any, label: String, compactLabel: @Nls String?): String = if (isCompact && compactLabel != null) "$compactLabel$value" else "$value $label" interface InfoCalculator { val new: Int val modified: Int val deleted: Int val unversioned: Int val includedNew: Int val includedModified: Int val includedDeleted: Int val includedUnversioned: Int } }
apache-2.0
8e1cc41fd91060e4cea2d395405a6dcb
33.0625
140
0.714128
4.085457
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/ide/htl/HtlColorsAndFontsPage.kt
1
5051
package com.aemtools.ide.htl import com.aemtools.common.constant.const.DOLLAR import com.aemtools.lang.htl.colorscheme.HtlColors import com.aemtools.lang.htl.highlight.HtlHighlighter import com.aemtools.lang.htl.icons.HtlIcons import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighter import com.intellij.openapi.options.colors.AttributesDescriptor import com.intellij.openapi.options.colors.ColorDescriptor import com.intellij.openapi.options.colors.ColorSettingsPage import javax.swing.Icon /** * @author Dmytro Troynikov */ class HtlColorsAndFontsPage : ColorSettingsPage { private val previewTags: MutableMap<String, TextAttributesKey> = mutableMapOf( "HTL_EL_BOOLEAN" to HtlColors.BOOLEAN, "HTL_EL_STRING" to HtlColors.STRING, "HTL_EL_INTEGER" to HtlColors.INTEGER, "HTL_El_VARIABLE" to HtlColors.VARIABLE, "HTL_El_AT" to HtlColors.DELIMITER, "HTL_EL_BRACKET" to HtlColors.BRACKET, "HTL_EL_OPERATOR" to HtlColors.OPERATOR, "HTL_EL_IDENTIFIER" to HtlColors.IDENTIFIER, "HTL_EL_TEMPLATE_ARGUMENT" to HtlColors.TEMPLATE_ARGUMENT, "HTL_EL_TEMPLATE_PARAMETER" to HtlColors.TEMPLATE_PARAMETER, "HTL_EL_STANDARD_OPTION" to HtlColors.STANDARD_OPTION, "HTL_EL_OPTION" to HtlColors.OPTION, "HTL_EL_NULL" to HtlColors.NULL, "HTL_EL_PARENTHESES" to HtlColors.PARENTHESES, "HTL_ATTRIBUTE" to HtlColors.HTL_ATTRIBUTE, "HTL_VARIABLE_DECLARATION" to HtlColors.HTL_VARIABLE_DECLARATION, "HTL_VARIABLE_UNUSED" to HtlColors.HTL_VARIABLE_UNUSED, "HTL_EL_GLOBAL_VARIABLE" to HtlColors.HTL_EL_GLOBAL_VARIABLE, "HTL_EL_LOCAL_VARIABLE" to HtlColors.HTL_EL_LOCAL_VARIABLE, "HTL_EL_UNRESOLVED_VARIABLE" to HtlColors.HTL_EL_UNRESOLVED_VARIABLE ) private val attributes: Array<AttributesDescriptor> = arrayOf( AttributesDescriptor("Boolean", HtlColors.BOOLEAN), AttributesDescriptor("String", HtlColors.STRING), AttributesDescriptor("Integer", HtlColors.INTEGER), AttributesDescriptor("Variable", HtlColors.VARIABLE), AttributesDescriptor("Delimiter", HtlColors.DELIMITER), AttributesDescriptor("Bracket", HtlColors.BRACKET), AttributesDescriptor("Operator", HtlColors.OPERATOR), AttributesDescriptor("Identifier", HtlColors.IDENTIFIER), AttributesDescriptor("Template Argument", HtlColors.TEMPLATE_ARGUMENT), AttributesDescriptor("Template Parameter", HtlColors.TEMPLATE_PARAMETER), AttributesDescriptor("Standard Option", HtlColors.STANDARD_OPTION), AttributesDescriptor("Option", HtlColors.OPTION), AttributesDescriptor("Null", HtlColors.NULL), AttributesDescriptor("Parentheses", HtlColors.PARENTHESES), AttributesDescriptor("HTL Attribute", HtlColors.HTL_ATTRIBUTE), AttributesDescriptor("Variable Declaration", HtlColors.HTL_VARIABLE_DECLARATION), AttributesDescriptor("Unused Variable", HtlColors.HTL_VARIABLE_UNUSED), AttributesDescriptor("Global Variable", HtlColors.HTL_EL_GLOBAL_VARIABLE), AttributesDescriptor("Local Variable", HtlColors.HTL_EL_LOCAL_VARIABLE), AttributesDescriptor("Unresolved Variable", HtlColors.HTL_EL_UNRESOLVED_VARIABLE) ) override fun getHighlighter(): SyntaxHighlighter = HtlHighlighter() override fun getAdditionalHighlightingTagToDescriptorMap(): MutableMap<String, TextAttributesKey> = previewTags override fun getIcon(): Icon? = HtlIcons.HTL_FILE_ICON override fun getAttributeDescriptors(): Array<AttributesDescriptor> = attributes override fun getColorDescriptors(): Array<ColorDescriptor> = ColorDescriptor.EMPTY_ARRAY override fun getDisplayName(): String = "HTML Markup Language (HTL)" override fun getDemoText(): String = buildString { append("<div") append(" <HTL_ATTRIBUTE>data-sly-use.</HTL_ATTRIBUTE><HTL_VARIABLE_DECLARATION>bean</HTL_VARIABLE_DECLARATION>") append("$DOLLAR{'com.test.Bean' @ <HTL_EL_OPTION>option</HTL_EL_OPTION>=true}\"") append(">\n") append("$DOLLAR{<HTL_EL_LOCAL_VARIABLE>bean</HTL_EL_LOCAL_VARIABLE>.field @ ") append("<HTL_EL_STANDARD_OPTION>context</HTL_EL_STANDARD_OPTION>='html'}\n") append("$DOLLAR{true || false || null || (100 < 200)}\n") append("$DOLLAR{<HTL_EL_GLOBAL_VARIABLE>properties</HTL_EL_GLOBAL_VARIABLE>[jcr:title]}\n") append("$DOLLAR{<HTL_EL_UNRESOLVED_VARIABLE>unresolved</HTL_EL_UNRESOLVED_VARIABLE>}\n") append("<div <HTL_ATTRIBUTE>data-sly-test.</HTL_ATTRIBUTE>") append("<HTL_VARIABLE_UNUSED>unused</HTL_VARIABLE_UNUSED>=\"\">\n") append("<div <HTL_ATTRIBUTE>data-sly-template.</HTL_ATTRIBUTE>") append("<HTL_VARIABLE_DECLARATION>template</HTL_VARIABLE_DECLARATION>=\"") append("$DOLLAR{@ <HTL_EL_TEMPLATE_PARAMETER>param1</HTL_EL_TEMPLATE_PARAMETER>}\"></div>\n") append("<div <HTL_ATTRIBUTE>data-sly-call</HTL_ATTRIBUTE>=\"") append("$DOLLAR{template @ <HTL_EL_TEMPLATE_ARGUMENT>param1</HTL_EL_TEMPLATE_ARGUMENT>=true}\"\n") } }
gpl-3.0
5e974c257e369a00891e40435d76d444
45.33945
116
0.736488
4.167492
false
false
false
false
DmytroTroynikov/aemtools
common/src/main/kotlin/com/aemtools/common/util/ObjectSerializer.kt
1
2391
package com.aemtools.common.util import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.io.Serializable /** * @author Dmytro_Troynikov */ object ObjectSerializer { /** * Serialize given object into [String] using [ObjectOutputStream]. * @param obj object to serialize * @see ObjectInputStream * @return the serialization result, empty string for _null_ input */ fun <T : Serializable> serialize(obj: T?): String { if (obj == null) { return "" } return obj.serializeToByteArray().toString(charset("ISO-8859-1")) } /** * Serialize given [Serializable] object into [ByteArray] using [ObjectOutputStream]. * @param obj object to serialize * @return byte array */ fun <T : Serializable> serializeToByteArray(obj: T?): ByteArray { if (obj == null) { return ByteArray(0) } val baos = ByteArrayOutputStream() val oos = ObjectOutputStream(baos) oos.writeObject(obj) oos.close() return baos.toByteArray() } /** * Deserialize given [String] using [ObjectInputStream]. * @param string the string to deserialize * @return deserialized object, _null_ in case of error. */ @Suppress("UNCHECKED_CAST") fun <T : Serializable> deserialize(string: String): T? = deserialize(string.toByteArray(charset("ISO-8859-1"))) /** * Deserialize given [ByteArray] using [ObjectInputStream]. * @param byteArray the array to deserialize * @return deserialized object, _null_ in case of error. */ fun <T : Serializable> deserialize(byteArray: ByteArray): T? { if (byteArray.isEmpty()) { return null } var bais = ByteArrayInputStream(byteArray) var ois = ObjectInputStream(bais) return ois.readObject() as T } } /** * Serialize current [Serializable]. * The shortcut for [ObjectSerializer.serialize] method. * @receiver [Serializable] * @see ObjectSerializer.serialize */ fun Serializable.serialize(): String = ObjectSerializer.serialize(this) /** * Serialize current [Serializable] into [ByteArray]. * The shortcut for [ObjectSerializer.serializeToByteArray] method. * @receiver [Serializable] * @see ObjectSerializer.serializeToByteArray */ fun Serializable.serializeToByteArray(): ByteArray = ObjectSerializer.serializeToByteArray(this)
gpl-3.0
849bba823aff333f07c9aa28d960594f
26.482759
96
0.701798
4.355191
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/CommitProjectPanelAdapter.kt
3
2629
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.commit import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentContainer import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vfs.VirtualFile import java.io.File import javax.swing.JComponent open class CommitProjectPanelAdapter(private val handler: AbstractCommitWorkflowHandler<*, *>) : CheckinProjectPanel { private val workflow get() = handler.workflow private val ui get() = handler.ui private val vcsManager get() = ProjectLevelVcsManager.getInstance(workflow.project) override fun getCommitWorkflowHandler(): CommitWorkflowHandler = handler override fun getProject(): Project = workflow.project // NOTE: Seems it is better to remove getComponent()/getPreferredFocusedComponent() usages. And provide more specific methods instead. // So corresponding methods are not added to workflow ui interface explicitly. override fun getComponent(): JComponent? = (ui as? ComponentContainer)?.component override fun getPreferredFocusedComponent(): JComponent? = (ui as? ComponentContainer)?.preferredFocusableComponent override fun hasDiffs(): Boolean = !handler.isCommitEmpty() override fun getVirtualFiles(): Collection<VirtualFile> = ui.getIncludedPaths().mapNotNull { it.virtualFile } override fun getSelectedChanges(): Collection<Change> = ui.getIncludedChanges() override fun getFiles(): Collection<File> = ui.getIncludedPaths().map { it.ioFile } override fun getRoots(): Collection<VirtualFile> = ui.getDisplayedPaths().mapNotNullTo(hashSetOf()) { vcsManager.getVcsRootFor(it) } override fun vcsIsAffected(name: String): Boolean = vcsManager.checkVcsIsActive(name) && workflow.vcses.any { it.name == name } override fun getCommitActionName(): String = ui.defaultCommitActionName override fun getCommitMessage(): String = ui.commitMessageUi.text override fun setCommitMessage(currentDescription: String?) { ui.commitMessageUi.setText(currentDescription) ui.commitMessageUi.focus() } override fun refresh() = ChangeListManager.getInstance(workflow.project).invokeAfterUpdate(true) { ui.refreshData() workflow.commitOptions.refresh() } override fun saveState() = workflow.commitOptions.saveState() override fun restoreState() = workflow.commitOptions.restoreState() }
apache-2.0
3282a874c2f5eb5fd75245312e36c7e1
50.568627
140
0.789654
4.841621
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/coroutines.kt
1
7057
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:ApiStatus.Experimental package com.intellij.openapi.application import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.progress.util.ProgressIndicatorUtils.runActionAndCancelBeforeWrite import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import kotlinx.coroutines.* import org.jetbrains.annotations.ApiStatus import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext import kotlin.coroutines.resume /** * Runs given [action] under [read lock][com.intellij.openapi.application.Application.runReadAction] * except it doesn't affect any write actions. * * The function suspends if at the moment of calling it's not possible to acquire the read lock. * If the write action happens while the [action] is running, then the [action] is canceled, * and the function suspends until its possible to acquire the read lock, and then the [action] is tried again. * * Since the [action] might me executed several times, it must be idempotent. * The function returns when given [action] was completed fully. * [CoroutineContext] passed to the action must be used to check for cancellation inside the [action]. */ suspend fun <T> readAction(action: (ctx: CoroutineContext) -> T): T { return constrainedReadAction(ReadConstraints.unconstrained(), action) } /** * Suspends until it's possible to obtain the read lock in smart mode and then runs the [action] holding the lock. * @see readAction */ suspend fun <T> smartReadAction(project: Project, action: (ctx: CoroutineContext) -> T): T { return constrainedReadAction(ReadConstraints.inSmartMode(project), action) } /** * Suspends until it's possible to obtain the read lock with all [constraints] [satisfied][ContextConstraint.isCorrectContext] * and then runs the [action] holding the lock. * @see readAction */ suspend fun <T> constrainedReadAction(constraints: ReadConstraints, action: (ctx: CoroutineContext) -> T): T { val application: ApplicationEx = ApplicationManager.getApplication() as ApplicationEx check(!application.isDispatchThread) { "Must not call from EDT" } if (application.isReadAccessAllowed) { val unsatisfiedConstraint = constraints.findUnsatisfiedConstraint() check(unsatisfiedConstraint == null) { "Cannot suspend until constraints are satisfied while holding read lock: $unsatisfiedConstraint" } return action(coroutineContext) } return supervisorScope { readLoop(application, constraints, action) } } private suspend fun <T> readLoop(application: ApplicationEx, constraints: ReadConstraints, action: (ctx: CoroutineContext) -> T): T { while (true) { coroutineContext.ensureActive() if (application.isWriteActionPending || application.isWriteActionInProgress) { yieldToPendingWriteActions() // Write actions are executed on the write thread => wait until write action is processed. } try { when (val readResult = tryReadAction(application, constraints, action)) { is ReadResult.Successful -> return readResult.value is ReadResult.UnsatisfiedConstraint -> readResult.waitForConstraint.join() } } catch (e: CancellationException) { continue // retry } } } private suspend fun <T> tryReadAction(application: ApplicationEx, constraints: ReadConstraints, action: (ctx: CoroutineContext) -> T): ReadResult<T> { val loopContext = coroutineContext return withContext(CoroutineName("read action")) { val readCtx: CoroutineContext = [email protected] val readJob: Job = requireNotNull(readCtx[Job]) val cancellation = { readJob.cancel() } lateinit var result: ReadResult<T> runActionAndCancelBeforeWrite(application, cancellation) { readJob.ensureActive() application.tryRunReadAction { val unsatisfiedConstraint = constraints.findUnsatisfiedConstraint() result = if (unsatisfiedConstraint == null) { ReadResult.Successful(action(readCtx)) } else { ReadResult.UnsatisfiedConstraint(waitForConstraint(loopContext, unsatisfiedConstraint)) } } } readJob.ensureActive() result } } private sealed class ReadResult<T> { class Successful<T>(val value: T) : ReadResult<T>() class UnsatisfiedConstraint<T>(val waitForConstraint: Job) : ReadResult<T>() } /** * Suspends the execution until the write thread queue is processed. */ private suspend fun yieldToPendingWriteActions() { // the runnable is executed on the write thread _after_ the current or pending write action yieldUntilRun(ApplicationManager.getApplication()::invokeLater) } private fun waitForConstraint(ctx: CoroutineContext, constraint: ContextConstraint): Job { return CoroutineScope(ctx).launch(Dispatchers.Unconfined + CoroutineName("waiting for constraint '$constraint'")) { check(ApplicationManager.getApplication().isReadAccessAllowed) // schedule while holding read lock yieldUntilRun(constraint::schedule) check(constraint.isCorrectContext()) // Job is finished, readLoop may continue the next attempt } } private suspend fun yieldUntilRun(schedule: (Runnable) -> Unit) { suspendCancellableCoroutine<Unit> { continuation -> schedule(ResumeContinuationRunnable(continuation)) } } private class ResumeContinuationRunnable(continuation: CancellableContinuation<Unit>) : Runnable { @Volatile private var myContinuation: CancellableContinuation<Unit>? = continuation init { continuation.invokeOnCancellation { myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { myContinuation?.resume(Unit) } } /** * Suspends until dumb mode is over and runs [action] in Smart Mode on EDT */ suspend fun <T> smartAction(project: Project, action: (ctx: CoroutineContext) -> T): T { return suspendCancellableCoroutine { continuation -> DumbService.getInstance(project).runWhenSmart(SmartRunnable(action, continuation)) } } private class SmartRunnable<T>(action: (ctx: CoroutineContext) -> T, continuation: CancellableContinuation<T>) : Runnable { @Volatile private var myAction: ((ctx: CoroutineContext) -> T)? = action @Volatile private var myContinuation: CancellableContinuation<T>? = continuation init { continuation.invokeOnCancellation { myAction = null myContinuation = null // it's not possible to unschedule the runnable, so we make it do nothing instead } } override fun run() { val continuation = myContinuation ?: return val action = myAction ?: return continuation.resumeWith(kotlin.runCatching { action.invoke(continuation.context) }) } }
apache-2.0
32c4233a868ebea24f20758ff191f7f3
37.78022
140
0.740825
4.748991
false
false
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/util/GameSettings.kt
1
4988
package au.com.codeka.warworlds.client.util import android.annotation.SuppressLint import android.content.SharedPreferences import androidx.preference.PreferenceManager import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.BuildConfig import com.google.common.base.Preconditions import java.util.* import kotlin.collections.ArrayList /** Wrapper class around our {@link SharedPreferences} instance. */ object GameSettings { enum class ValueType { BOOLEAN, INT, STRING, ENUM } enum class ChatProfanityFilter { AllowAll, AllowMild, AllowNone, } enum class Key( val valueType: ValueType, val defValue: Any, val enumType: Class<out Enum<*>>? = null) { /** If true, we'll automatically translate chat messages to English. */ CHAT_AUTO_TRANSLATE(ValueType.BOOLEAN, false), /** How much we should filter chat message which contain profanity. */ CHAT_PROFANITY_FILTER( ValueType.ENUM, ChatProfanityFilter.AllowAll, ChatProfanityFilter::class.java), /** The cookie used to authenicate with the server. */ COOKIE(ValueType.STRING, ""), /** If you've associated with an email address, this is it. */ EMAIL_ADDR(ValueType.STRING, ""), /** A unique ID that's guaranteed to not change (as long as the user doesn't clear app data) */ INSTANCE_ID(ValueType.STRING, ""), /** The base URL of the server. */ SERVER(ValueType.STRING, BuildConfig.DEFAULT_SERVER), /** Set to true after you've seen the warm welcome, so we don't show it again. */ WARM_WELCOME_SEEN(ValueType.BOOLEAN, false) } interface SettingChangeHandler { fun onSettingChanged(key: Key) } class Editor(sharedPreferences: SharedPreferences) { private var editor: SharedPreferences.Editor private var committed: Boolean init { @SuppressLint("CommitPrefEdits") // we have our own commit() method. editor = sharedPreferences.edit() committed = false } fun setBoolean(key: Key, value: Boolean): Editor { Preconditions.checkState(key.valueType == ValueType.BOOLEAN) editor.putBoolean(key.toString(), value) return this } fun <T : Enum<*>> setEnum(key: Key, value: T): Editor { Preconditions.checkArgument(key.valueType == ValueType.ENUM) Preconditions.checkArgument(key.enumType == value::class.java) editor.putString(key.toString(), value.toString()) return this } fun setString(key: Key, value: String): Editor { Preconditions.checkState(key.valueType == ValueType.STRING) editor.putString(key.toString(), value) return this } fun commit() { editor.apply() committed = true } protected fun finalize() { if (!committed) { // TODO: log, or something? commit() } } } private var sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App) private val settingChangeHandlers = ArrayList<(Key) -> Unit>() private val onPrefChangedListener = object : SharedPreferences.OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, keyName: String) { val key: Key try { key = Key.valueOf(keyName) } catch (e: IllegalArgumentException) { // This will happen if the setting isn't one of ours. Ignore. return } for (handler in settingChangeHandlers) { handler(key) } } } init { sharedPreferences.registerOnSharedPreferenceChangeListener(onPrefChangedListener) if (getString(Key.INSTANCE_ID) == "") { edit().setString(Key.INSTANCE_ID, UUID.randomUUID().toString()).commit() } } fun addSettingChangedHandler(handler: (Key) -> Unit) { settingChangeHandlers.add(handler) } fun removeSettingChangedHandler(handler: (Key) -> Unit) { settingChangeHandlers.remove(handler) } fun getBoolean(key: Key): Boolean { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(App) Preconditions.checkArgument(key.valueType == ValueType.BOOLEAN) return sharedPreferences.getBoolean(key.toString(), key.defValue as Boolean) } fun <T : Enum<*>> getEnum(key: Key, enumType: Class<T>): T { Preconditions.checkArgument(key.valueType == ValueType.ENUM) Preconditions.checkArgument(key.enumType == enumType) val strValue = sharedPreferences.getString(key.toString(), key.defValue.toString()) return (enumType.enumConstants as Array<out T>).first { it.name == strValue } } fun getInt(key: Key): Int { Preconditions.checkArgument(key.valueType == ValueType.INT) return sharedPreferences.getInt(key.toString(), key.defValue as Int) } fun getString(key: Key): String { Preconditions.checkArgument(key.valueType == ValueType.STRING) return sharedPreferences.getString(key.toString(), key.defValue as String)!! } fun edit(): Editor { return Editor(sharedPreferences) } }
mit
6ce19831ecc2e9581ca110bfcd30a22d
30.175
99
0.695269
4.433778
false
false
false
false
AndroidX/androidx
fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentFinishEarlyTest.kt
3
2478
/* * 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.fragment.app import android.os.Bundle import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.test.filters.SdkSuppress import com.google.common.truth.Truth.assertThat import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import leakcanary.DetectLeaksAfterTestSuccess import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @LargeTest class FragmentFinishEarlyTest { @Suppress("DEPRECATION") val activityRule = androidx.test.rule.ActivityTestRule( FragmentFinishEarlyTestActivity::class.java, false, false ) // Detect leaks BEFORE and AFTER activity is destroyed @get:Rule val ruleChain: RuleChain = RuleChain.outerRule(DetectLeaksAfterTestSuccess()) .around(activityRule) /** * FragmentActivity should not raise the state of a Fragment while it is being destroyed. */ @SdkSuppress(minSdkVersion = 24) // this is failing remotely for API 23 devices b/178692379 @Test fun fragmentActivityFinishEarly() { val activity = activityRule.launchActivity(null) assertThat(activity.onDestroyLatch.await(1000, TimeUnit.MILLISECONDS)).isTrue() } } /** * A simple activity used for testing an Early Finishing Activity */ class FragmentFinishEarlyTestActivity : FragmentActivity() { val onDestroyLatch = CountDownLatch(1) val fragment = StrictFragment() public override fun onCreate(icicle: Bundle?) { super.onCreate(icicle) finish() supportFragmentManager.beginTransaction() .add(fragment, "not destroyed") .commit() } override fun onDestroy() { super.onDestroy() onDestroyLatch.countDown() } }
apache-2.0
f29bec33b0f758a4b1c01fb33a97815c
30.367089
95
0.730831
4.530165
false
true
false
false
smmribeiro/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleTargetPathsConverter.kt
9
1721
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.project import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.externalSystem.service.execution.ExternalSystemExecutionAware.Companion.getEnvironmentConfigurationProvider import org.jetbrains.plugins.gradle.model.ProjectImportAction.AllModels import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings import org.jetbrains.plugins.gradle.util.ReflectionTraverser import java.io.Closeable import java.io.File internal class GradleTargetPathsConverter(private val executionSettings: GradleExecutionSettings) : Closeable { private val traverser = ReflectionTraverser() fun mayBeApplyTo(allModels: AllModels) { val pathMapper = executionSettings.getEnvironmentConfigurationProvider()?.pathMapper ?: return allModels.applyPathsConverter { rootObject -> traverser.walk(rootObject!!, listOf(String::class.java), listOf(File::class.java)) { if (it !is File) return@walk val remotePath = it.path if (!pathMapper.canReplaceRemote(remotePath)) return@walk val localPath = pathMapper.convertToLocal(remotePath) try { val field = File::class.java.getDeclaredField("path") field.isAccessible = true field[it] = localPath } catch (reflectionError: Throwable) { LOG.error("Failed to update mapped file", reflectionError) } } } } override fun close() { traverser.close() } companion object { private val LOG = logger<GradleTargetPathsConverter>() } }
apache-2.0
ad350ef9adc0e62b781d3fa41dc71585
40
158
0.745497
4.626344
false
false
false
false
macoscope/KetchupLunch
app/src/main/java/com/macoscope/ketchuplunch/view/lunch/WeekToolbarItemUI.kt
1
852
package com.macoscope.ketchuplunch.view.lunch import android.graphics.Color import android.text.TextUtils import android.view.Gravity import android.view.View import android.view.ViewGroup import com.macoscope.ketchuplunch.R import org.jetbrains.anko.AnkoComponent import org.jetbrains.anko.AnkoContext import org.jetbrains.anko.singleLine import org.jetbrains.anko.textColor import org.jetbrains.anko.textView class WeekToolbarItemUI : AnkoComponent<ViewGroup> { override fun createView(ui: AnkoContext<ViewGroup>): View { return with(ui) { textView { id = R.id.week_toolbar_name singleLine = true ellipsize = TextUtils.TruncateAt.END textSize = 18f gravity = Gravity.RIGHT textColor = Color.WHITE } } } }
apache-2.0
d94256abaf68af199cca4db758da8942
29.464286
63
0.680751
4.605405
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddLabeledReturnInLambdaIntention.kt
1
2571
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression class AddLabeledReturnInLambdaIntention : SelfTargetingRangeIntention<KtBlockExpression>( KtBlockExpression::class.java, KotlinBundle.lazyMessage("add.labeled.return.to.last.expression.in.a.lambda") ), LowPriorityAction { override fun applicabilityRange(element: KtBlockExpression): TextRange? { if (!isApplicableTo(element)) return null val labelName = element.getParentLambdaLabelName() ?: return null if (labelName == KtTokens.SUSPEND_KEYWORD.value) return null setTextGetter(KotlinBundle.lazyMessage("add.return.at.0", labelName)) return element.statements.lastOrNull()?.textRange } override fun applyTo(element: KtBlockExpression, editor: Editor?) { val labelName = element.getParentLambdaLabelName() ?: return val lastStatement = element.statements.lastOrNull() ?: return val newExpression = KtPsiFactory(element.project).createExpressionByPattern("return@$labelName $0", lastStatement) lastStatement.replace(newExpression) } private fun isApplicableTo(block: KtBlockExpression): Boolean { val lastStatement = block.statements.lastOrNull().takeIf { it !is KtReturnExpression } ?: return false if (block.getNonStrictParentOfType<KtLambdaExpression>() == null) return false val bindingContext = lastStatement.safeAnalyzeNonSourceRootCode().takeIf { it != BindingContext.EMPTY } ?: return false return lastStatement.isUsedAsExpression(bindingContext) } }
apache-2.0
5f201e94da79a35fbbf042f42a58febb
53.702128
158
0.792688
5.131737
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/authentication/ui/AddGHAccountAction.kt
1
1890
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.authentication.ui import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.util.ui.JBUI.Panels.simplePanel import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.i18n.GithubBundle.message import java.awt.Component import javax.swing.Action import javax.swing.JComponent class AddGHAccountAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.getData(GHAccountsHost.KEY) != null } override fun actionPerformed(e: AnActionEvent) { val accountsHost = e.getData(GHAccountsHost.KEY)!! val dialog = GHOAuthLoginDialog(e.project, e.getData(CONTEXT_COMPONENT), accountsHost::isAccountUnique) dialog.setServer(GithubServerPath.DEFAULT_HOST, false) if (dialog.showAndGet()) { accountsHost.addAccount(dialog.server, dialog.login, dialog.token) } } } internal class GHOAuthLoginDialog(project: Project?, parent: Component?, isAccountUnique: UniqueLoginPredicate) : BaseLoginDialog(project, parent, GithubApiRequestExecutor.Factory.getInstance(), isAccountUnique) { init { title = message("login.to.github") loginPanel.setOAuthUi() init() } override fun createActions(): Array<Action> = arrayOf(cancelAction) override fun show() { doOKAction() super.show() } override fun createCenterPanel(): JComponent = simplePanel(loginPanel) .withPreferredWidth(200) .setPaddingCompensated() }
apache-2.0
fa7b03ece73b62f7adb5f77283bae28b
35.365385
140
0.778836
4.305239
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt
2
5300
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.codeInsight.TargetElementUtil import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.jsonUtils.getNullableString import org.jetbrains.kotlin.idea.refactoring.rename.loadTestConfiguration import org.jetbrains.kotlin.idea.test.* import org.jetbrains.kotlin.test.KotlinTestUtils import org.jetbrains.kotlin.util.prefixIfNot import java.io.File abstract class AbstractMultifileRefactoringTest : KotlinLightCodeInsightFixtureTestCase() { interface RefactoringAction { fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject) } override fun getProjectDescriptor(): LightProjectDescriptor { val testConfigurationFile = File(super.getTestDataPath(), fileName()) val config = loadTestConfiguration(testConfigurationFile) val withRuntime = config["withRuntime"]?.asBoolean ?: false if (withRuntime) { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } return KotlinLightProjectDescriptor.INSTANCE } protected abstract fun runRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project) protected fun doTest(unused: String) { val testFile = testDataFile() val config = JsonParser.parseString(FileUtil.loadFile(testFile, true)) as JsonObject doTestCommittingDocuments(testFile) { rootDir -> val opts = config.getNullableString("customCompilerOpts")?.prefixIfNot("// ") ?: "" withCustomCompilerOptions(opts, project, module) { runRefactoring(testFile.path, config, rootDir, project) } } } override val testDataDirectory: File get() { val name = getTestName(true).substringBeforeLast('_').replace('_', '/') return super.testDataDirectory.resolve(name) } override fun fileName() = testDataDirectory.name + ".test" private fun doTestCommittingDocuments(testFile: File, action: (VirtualFile) -> Unit) { val beforeVFile = myFixture.copyDirectoryToProject("before", "") PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments() val afterDir = File(testFile.parentFile, "after") val afterVFile = LocalFileSystem.getInstance().findFileByIoFile(afterDir)?.apply { UsefulTestCase.refreshRecursively(this) } ?: error("`after` directory not found") action(beforeVFile) PsiDocumentManager.getInstance(project).commitAllDocuments() FileDocumentManager.getInstance().saveAllDocuments() PlatformTestUtil.assertDirectoriesEqual(afterVFile, beforeVFile) { file -> !KotlinTestUtils.isMultiExtensionName(file.name) } } } fun runRefactoringTest( path: String, config: JsonObject, rootDir: VirtualFile, project: Project, action: AbstractMultifileRefactoringTest.RefactoringAction ) { val mainFilePath = config.getNullableString("mainFile") ?: config.getAsJsonArray("filesToMove").first().asString val conflictFile = File(File(path).parentFile, "conflicts.txt") val mainFile = rootDir.findFileByRelativePath(mainFilePath)!! val mainPsiFile = PsiManager.getInstance(project).findFile(mainFile)!! val document = FileDocumentManager.getInstance().getDocument(mainFile)!! val editor = EditorFactory.getInstance()!!.createEditor(document, project)!! val caretOffsets = document.extractMultipleMarkerOffsets(project) val elementsAtCaret = caretOffsets.map { TargetElementUtil.getInstance().findTargetElement( editor, TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED or TargetElementUtil.ELEMENT_NAME_ACCEPTED, it )!! } try { action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config) assert(!conflictFile.exists()) } catch (e: BaseRefactoringProcessor.ConflictsInTestsException) { KotlinTestUtils.assertEqualsToFile(conflictFile, e.messages.distinct().sorted().joinToString("\n")) BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> { // Run refactoring again with ConflictsInTestsException suppressed action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config) } } finally { EditorFactory.getInstance()!!.releaseEditor(editor) } }
apache-2.0
a0f6992832c041b54f5678a070223fb7
42.45082
158
0.74434
5.257937
false
true
false
false
jwren/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/quickfix/CommonIntentionActionsTest.kt
1
41013
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.lang.jvm.* import com.intellij.lang.jvm.actions.* import com.intellij.lang.jvm.actions.AnnotationAttributeValueRequest.NestedAnnotation import com.intellij.lang.jvm.actions.AnnotationAttributeValueRequest.StringValue import com.intellij.lang.jvm.types.JvmSubstitutor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Pair.pair import com.intellij.psi.* import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.testFramework.fixtures.CodeInsightTestFixture import junit.framework.TestCase import org.intellij.lang.annotations.Language import org.jetbrains.kotlin.asJava.toLightElements import org.jetbrains.kotlin.idea.search.allScope import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.uast.toUElement import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @RunWith(JUnit38ClassRunner::class) class CommonIntentionActionsTest : BasePlatformTestCase() { private class SimpleMethodRequest( project: Project, private val methodName: String, private val modifiers: Collection<JvmModifier> = emptyList(), private val returnType: ExpectedTypes = emptyList(), private val annotations: Collection<AnnotationRequest> = emptyList(), @Suppress("MissingRecentApi") parameters: List<ExpectedParameter> = emptyList(), private val targetSubstitutor: JvmSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY) ) : CreateMethodRequest { private val expectedParameters = parameters override fun getTargetSubstitutor(): JvmSubstitutor = targetSubstitutor override fun getModifiers() = modifiers override fun getMethodName() = methodName override fun getAnnotations() = annotations @Suppress("MissingRecentApi") override fun getExpectedParameters(): List<ExpectedParameter> = expectedParameters override fun getReturnType() = returnType override fun isValid(): Boolean = true } override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE_FULL_JDK fun testMakeNotFinal() { myFixture.configureByText( "foo.kt", """ class Foo { fun bar<caret>(){} } """ ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false) ).findWithText("Make 'bar' 'open'") ) myFixture.checkResult( """ class Foo { open fun bar(){} } """ ) } fun testMakePrivate() { myFixture.configureByText( "foo.kt", """ class Foo<caret> { fun bar(){} } """ ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, true) ).findWithText("Make 'Foo' 'private'") ) myFixture.checkResult( """ private class Foo { fun bar(){} } """ ) } fun testMakeNotPrivate() { myFixture.configureByText( "foo.kt", """ private class Foo<caret> { fun bar(){} } """.trim() ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.PRIVATE, false) ).findWithText("Remove 'private' modifier") ) myFixture.checkResult( """ class Foo { fun bar(){} } """.trim(), true ) } fun testMakePrivatePublic() { myFixture.configureByText( "foo.kt", """class Foo { | private fun <caret>bar(){} |}""".trim().trimMargin() ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true) ).findWithText("Remove 'private' modifier") ) myFixture.checkResult( """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin(), true ) } fun testMakeProtectedPublic() { myFixture.configureByText( "foo.kt", """open class Foo { | protected fun <caret>bar(){} |}""".trim().trimMargin() ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true) ).findWithText("Remove 'protected' modifier") ) myFixture.checkResult( """open class Foo { | fun <caret>bar(){} |}""".trim().trimMargin(), true ) } fun testMakeInternalPublic() { myFixture.configureByText( "foo.kt", """class Foo { | internal fun <caret>bar(){} |}""".trim().trimMargin() ) myFixture.launchAction( createModifierActions( myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true) ).findWithText("Remove 'internal' modifier") ) myFixture.checkResult( """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin(), true ) } fun testAddAnnotation() { myFixture.configureByText( "foo.kt", """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest("kotlin.jvm.JvmName", stringAttribute("name", "foo")) ).single() ) myFixture.checkResult( """class Foo { | @JvmName(name = "foo") | fun <caret>bar(){} |}""".trim().trimMargin(), true ) } fun testAddJavaAnnotationValue() { myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; public @interface JavaAnnotation { String value(); int param() default 0; } """.trimIndent() ) myFixture.configureByText( "foo.kt", """class Foo { | fun bar(){} | fun baz(){} |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest("pkg.myannotation.JavaAnnotation", stringAttribute("value", "foo"), intAttribute("param", 2)) ).single() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("baz", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest("pkg.myannotation.JavaAnnotation", intAttribute("param", 2), stringAttribute("value", "foo")) ).single() ) myFixture.checkResult( """import pkg.myannotation.JavaAnnotation | |class Foo { | @JavaAnnotation("foo", param = 2) | fun bar(){} | @JavaAnnotation(param = 2, value = "foo") | fun baz(){} |}""".trim().trimMargin(), true ) } fun testAddJavaAnnotationArrayValue() { myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; public @interface JavaAnnotation { String[] value(); int param() default 0; } """.trimIndent() ) myFixture.configureByText( "foo.kt", """class Foo { | fun bar(){} | fun baz(){} |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest( "pkg.myannotation.JavaAnnotation", arrayAttribute("value", listOf(StringValue("foo1"), StringValue("foo2"), StringValue("foo3"))), intAttribute("param", 2) ) ).single() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("baz", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest( "pkg.myannotation.JavaAnnotation", intAttribute("param", 2), arrayAttribute("value", listOf(StringValue("foo1"), StringValue("foo2"), StringValue("foo3"))) ) ).single() ) myFixture.checkResult( """import pkg.myannotation.JavaAnnotation | |class Foo { | @JavaAnnotation("foo1", "foo2", "foo3", param = 2) | fun bar(){} | @JavaAnnotation(param = 2, value = ["foo1", "foo2", "foo3"]) | fun baz(){} |}""".trim().trimMargin(), true ) } fun testAddJavaAnnotationArrayValueWithNestedAnnotations() { myFixture.addJavaFileToProject( "pkg/myannotation/NestedJavaAnnotation.java", """ package pkg.myannotation; public @interface NestedJavaAnnotation { String[] value(); int nestedParam() default 0; } """.trimIndent() ) myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; public @interface JavaAnnotation { NestedJavaAnnotation[] value(); int param() default 0; } """.trimIndent() ) myFixture.configureByText( "foo.kt", """class Foo { | fun bar(){} | fun baz(){} |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest( "pkg.myannotation.JavaAnnotation", arrayAttribute( "value", listOf( NestedAnnotation(annotationRequest( "pkg.myannotation.NestedJavaAnnotation", arrayAttribute("value", listOf(StringValue("foo11"), StringValue("foo12"), StringValue("foo13"))), intAttribute("nestedParam", 1) )), NestedAnnotation(annotationRequest( "pkg.myannotation.NestedJavaAnnotation", intAttribute("nestedParam", 2), arrayAttribute("value", listOf(StringValue("foo21"), StringValue("foo22"), StringValue("foo23"))) )), ) ), intAttribute("param", 3) ) ).single() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("baz", KtModifierListOwner::class.java).toLightElements().single() as PsiMethod, annotationRequest( "pkg.myannotation.JavaAnnotation", intAttribute("param", 1), arrayAttribute( "value", listOf( NestedAnnotation(annotationRequest( "pkg.myannotation.NestedJavaAnnotation", arrayAttribute("value", listOf(StringValue("foo11"), StringValue("foo12"), StringValue("foo13"))), intAttribute("nestedParam", 2) )), NestedAnnotation(annotationRequest( "pkg.myannotation.NestedJavaAnnotation", intAttribute("nestedParam", 3), arrayAttribute("value", listOf(StringValue("foo21"), StringValue("foo22"), StringValue("foo23"))) )), ) ) ) ).single() ) myFixture.checkResult( """import pkg.myannotation.JavaAnnotation |import pkg.myannotation.NestedJavaAnnotation | |class Foo { | @JavaAnnotation(NestedJavaAnnotation("foo11", "foo12", "foo13", nestedParam = 1), NestedJavaAnnotation(nestedParam = 2, value = ["foo21", "foo22", "foo23"]), param = 3) | fun bar(){} | @JavaAnnotation(param = 1, value = [NestedJavaAnnotation("foo11", "foo12", "foo13", nestedParam = 2), NestedJavaAnnotation(nestedParam = 3, value = ["foo21", "foo22", "foo23"])]) | fun baz(){} |}""".trim().trimMargin(), true ) } fun testAddJavaAnnotationOnFieldWithoutTarget() { myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //no @Target @Retention(RetentionPolicy.RUNTIME) public @interface JavaAnnotation { String value(); int param() default 0; } """.trimIndent() ) myFixture.configureByText( "foo.kt", """class Foo { | val bar: String = null |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single { it is PsiField } as PsiField, annotationRequest("pkg.myannotation.JavaAnnotation") ).single() ) myFixture.checkResult( """ import pkg.myannotation.JavaAnnotation class Foo { @field:JavaAnnotation val bar: String = null } """.trimIndent(), true ) TestCase.assertEquals( "KtUltraLightMethodForSourceDeclaration -> org.jetbrains.annotations.NotNull," + " KtUltraLightFieldForSourceDeclaration -> pkg.myannotation.JavaAnnotation, org.jetbrains.annotations.NotNull", annotationsString(myFixture.findElementByText("bar", KtModifierListOwner::class.java)) ) } fun testAddJavaAnnotationOnField() { myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface JavaAnnotation { String value(); int param() default 0; } """.trimIndent() ) myFixture.configureByText( "foo.kt", """class Foo { | val bar: String = null |}""".trim().trimMargin() ) myFixture.launchAction( createAddAnnotationActions( myFixture.findElementByText("bar", KtModifierListOwner::class.java).toLightElements().single { it is PsiField } as PsiField, annotationRequest("pkg.myannotation.JavaAnnotation") ).single() ) myFixture.checkResult( """ import pkg.myannotation.JavaAnnotation class Foo { @JavaAnnotation val bar: String = null } """.trimIndent(), true ) TestCase.assertEquals( "KtUltraLightMethodForSourceDeclaration -> org.jetbrains.annotations.NotNull," + " KtUltraLightFieldForSourceDeclaration -> pkg.myannotation.JavaAnnotation, org.jetbrains.annotations.NotNull", annotationsString(myFixture.findElementByText("bar", KtModifierListOwner::class.java)) ) } fun testChangeMethodType() { myFixture.configureByText( "foo.kt", """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest("String", emptyList()) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """class Foo { | fun <caret>bar(): String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeToTypeWithAnnotations() { myFixture.configureByText( "foo.kt", """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin() ) myFixture.addKotlinFileToProject( "pkg/myannotation/annotations.kt", """ package pkg.myannotation @Target(AnnotationTarget.TYPE) annotation class MyAnno """.trimIndent() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest("String", listOf(annotationRequest("pkg.myannotation.MyAnno"))) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.myannotation.MyAnno | |class Foo { | fun <caret>bar(): @MyAnno String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeRemoveAnnotations() { myFixture.addKotlinFileToProject( "pkg/myannotation/annotations.kt", """ package pkg.myannotation @Target(AnnotationTarget.TYPE) annotation class MyAnno """.trimIndent() ) myFixture.configureByText( "foo.kt", """ |import pkg.myannotation.MyAnno | |class Foo { | fun <caret>bar(): @MyAnno String {} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest(null, emptyList()) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.myannotation.MyAnno | |class Foo { | fun <caret>bar(): String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeChangeAnnotationsOnly() { myFixture.addKotlinFileToProject( "pkg/myannotation/annotations.kt", """ package pkg.myannotation @Target(AnnotationTarget.TYPE) annotation class MyAnno @Target(AnnotationTarget.TYPE) annotation class MyOtherAnno """.trimIndent() ) myFixture.configureByText( "foo.kt", """ |import pkg.myannotation.MyAnno | |class Foo { | fun <caret>bar(): @MyAnno String {} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest(null, listOf(annotationRequest("pkg.myannotation.MyOtherAnno"))) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.myannotation.MyAnno |import pkg.myannotation.MyOtherAnno | |class Foo { | fun <caret>bar(): @MyOtherAnno String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeAddJavaAnnotation() { myFixture.addJavaFileToProject( "pkg/myannotation/JavaAnnotation.java", """ package pkg.myannotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface JavaAnnotation {} """.trimIndent() ) myFixture.addKotlinFileToProject( "pkg/myannotation/annotations.kt", """ package pkg.myannotation @Target(AnnotationTarget.TYPE) annotation class MyOtherAnno """.trimIndent() ) myFixture.configureByText( "foo.kt", """ |import pkg.myannotation.MyOtherAnno | |class Foo { | fun <caret>bar(): @MyOtherAnno String {} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest( null, listOf(annotationRequest("pkg.myannotation.JavaAnnotation"), annotationRequest("pkg.myannotation.MyOtherAnno")) ) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.myannotation.JavaAnnotation |import pkg.myannotation.MyOtherAnno | |class Foo { | fun <caret>bar(): @JavaAnnotation @MyOtherAnno String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeWithComments() { myFixture.addKotlinFileToProject( "pkg/myannotation/annotations.kt", """ package pkg.myannotation @Target(AnnotationTarget.TYPE) annotation class MyAnno @Target(AnnotationTarget.TYPE) annotation class MyOtherAnno """.trimIndent() ) myFixture.configureByText( "foo.kt", """ |import pkg.myannotation.MyOtherAnno | |class Foo { | fun <caret>bar(): @MyOtherAnno /*1*/ String {} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest(null, listOf(annotationRequest("pkg.myannotation.MyAnno"))) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.myannotation.MyAnno |import pkg.myannotation.MyOtherAnno | |class Foo { | fun <caret>bar(): /*1*/@MyAnno String {} |}""".trim().trimMargin(), true ) } fun testChangeMethodTypeToJavaType() { myFixture.addJavaFileToProject( "pkg/mytype/MyType.java", """ package pkg.mytype; public class MyType {} """.trimIndent() ) myFixture.configureByText( "foo.kt", """ |class Foo { | fun <caret>bar() {} |}""".trim().trimMargin() ) val method = myFixture.findElementByText("bar", KtNamedFunction::class.java).toLightElements().single() as JvmMethod val typeRequest = typeRequest("pkg.mytype.MyType", emptyList()) myFixture.launchAction(createChangeTypeActions(method, typeRequest).single()) myFixture.checkResult( """ |import pkg.mytype.MyType | |class Foo { | fun <caret>bar(): MyType {} |}""".trim().trimMargin(), true ) } private fun annotationsString(findElementByText: KtModifierListOwner) = findElementByText.toLightElements() .joinToString { elem -> "${elem.javaClass.simpleName} -> ${(elem as PsiModifierListOwner).annotations.mapNotNull { it.qualifiedName }.joinToString()}" } fun testDontMakePublicPublic() { myFixture.configureByText( "foo.kt", """class Foo { | fun <caret>bar(){} |}""".trim().trimMargin() ) assertEmpty(createModifierActions(myFixture.atCaret(), TestModifierRequest(JvmModifier.PUBLIC, true))) } fun testDontMakeFunInObjectsOpen() { myFixture.configureByText( "foo.kt", """ object Foo { fun bar<caret>(){} } """.trim() ) assertEmpty(createModifierActions(myFixture.atCaret(), TestModifierRequest(JvmModifier.FINAL, false))) } fun testAddVoidVoidMethod() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), methodRequest(project, "baz", listOf(JvmModifier.PRIVATE), PsiType.VOID) ).findWithText("Add method 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | fun bar() {} | private fun baz() { | | } |} """.trim().trimMargin(), true ) } fun testAddIntIntMethod() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "baz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.INT), parameters = expectedParams(PsiType.INT) ) ).findWithText("Add method 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | fun bar() {} | fun baz(param0: Int): Int { | TODO("Not yet implemented") | } |} """.trim().trimMargin(), true ) } fun testAddIntPrimaryConstructor() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { |} """.trim().trimMargin() ) myFixture.launchAction( createConstructorActions( myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) ).findWithText("Add primary constructor to 'Foo'") ) myFixture.checkResult( """ |class Foo(param0: Int) { |} """.trim().trimMargin(), true ) } fun testAddIntSecondaryConstructor() { myFixture.configureByText( "foo.kt", """ |class <caret>Foo() { |} """.trim().trimMargin() ) myFixture.launchAction( createConstructorActions( myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) ).findWithText("Add secondary constructor to 'Foo'") ) myFixture.checkResult( """ |class Foo() { | constructor(param0: Int) { | | } |} """.trim().trimMargin(), true ) } fun testChangePrimaryConstructorInt() { myFixture.configureByText( "foo.kt", """ |class <caret>Foo() { |} """.trim().trimMargin() ) myFixture.launchAction( createConstructorActions( myFixture.atCaret(), constructorRequest(project, listOf(pair("param0", PsiType.INT as PsiType))) ).findWithText("Add 'int' as 1st parameter to constructor 'Foo'") ) myFixture.checkResult( """ |class Foo(param0: Int) { |} """.trim().trimMargin(), true ) } fun testRemoveConstructorParameters() { myFixture.configureByText( "foo.kt", """ |class <caret>Foo(i: Int) { |} """.trim().trimMargin() ) myFixture.launchAction( createConstructorActions( myFixture.atCaret(), constructorRequest(project, emptyList()) ).findWithText("Remove 1st parameter from constructor 'Foo'") ) myFixture.checkResult( """ |class Foo() { |} """.trim().trimMargin(), true ) } fun testAddStringVarProperty() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) ) ).findWithText("Add 'var' property 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | var baz: String = TODO("initialize me") | | fun bar() {} |} """.trim().trimMargin(), true ) } fun testAddLateInitStringVarProperty() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) ) ).findWithText("Add 'lateinit var' property 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | lateinit var baz: String | | fun bar() {} |} """.trim().trimMargin(), true ) } fun testAddStringVarField() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createFieldActions( myFixture.atCaret(), FieldRequest(project, emptyList(), "java.util.Date", "baz") ).findWithText("Add 'var' property 'baz' to 'Foo'") ) myFixture.checkResult( """ |import java.util.Date | |class Foo { | @JvmField | var baz: Date = TODO("initialize me") | | fun bar() {} |} """.trim().trimMargin(), true ) } fun testAddLateInitStringVarField() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createFieldActions( myFixture.atCaret(), FieldRequest(project, listOf(JvmModifier.PRIVATE), "java.lang.String", "baz") ).findWithText("Add 'lateinit var' property 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | private lateinit var baz: String | | fun bar() {} |} """.trim().trimMargin(), true ) } private fun createFieldActions(atCaret: JvmClass, fieldRequest: CreateFieldRequest): List<IntentionAction> = EP_NAME.extensions.flatMap { it.createAddFieldActions(atCaret, fieldRequest) } fun testAddStringValProperty() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "getBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())), parameters = expectedParams() ) ).findWithText("Add 'val' property 'baz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | val baz: String = TODO("initialize me") | | fun bar() {} |} """.trim().trimMargin(), true ) } fun testGetMethodHasParameters() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "getBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) ) ).findWithText("Add method 'getBaz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | fun bar() {} | fun getBaz(param0: String): String { | TODO("Not yet implemented") | } |} """.trim().trimMargin(), true ) } fun testSetMethodHasStringReturnType() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.getTypeByName("java.lang.String", project, project.allScope())), parameters = expectedParams(PsiType.getTypeByName("java.lang.String", project, project.allScope())) ) ).findWithText("Add method 'setBaz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | fun bar() {} | fun setBaz(param0: String): String { | TODO("Not yet implemented") | } |} """.trim().trimMargin(), true ) } fun testSetMethodHasTwoParameters() { myFixture.configureByText( "foo.kt", """ |class Foo<caret> { | fun bar() {} |} """.trim().trimMargin() ) myFixture.launchAction( createMethodActions( myFixture.atCaret(), SimpleMethodRequest( project, methodName = "setBaz", modifiers = listOf(JvmModifier.PUBLIC), returnType = expectedTypes(PsiType.VOID), parameters = expectedParams( PsiType.getTypeByName("java.lang.String", project, project.allScope()), PsiType.getTypeByName("java.lang.String", project, project.allScope()) ) ) ).findWithText("Add method 'setBaz' to 'Foo'") ) myFixture.checkResult( """ |class Foo { | fun bar() {} | fun setBaz(param0: String, param1: String) { | | } |} """.trim().trimMargin(), true ) } private fun CodeInsightTestFixture.addJavaFileToProject(relativePath: String, @Language("JAVA") fileText: String) = this.addFileToProject(relativePath, fileText) private fun CodeInsightTestFixture.addKotlinFileToProject(relativePath: String, @Language("kotlin") fileText: String) = this.addFileToProject(relativePath, fileText) private fun expectedTypes(vararg psiTypes: PsiType) = psiTypes.map { expectedType(it) } private fun expectedParams(vararg psyTypes: PsiType) = psyTypes.mapIndexed { index, psiType -> expectedParameter(expectedTypes(psiType), "param$index") } class FieldRequest( private val project: Project, val modifiers: List<JvmModifier>, val type: String, val name: String ) : CreateFieldRequest { override fun getTargetSubstitutor(): JvmSubstitutor = PsiJvmSubstitutor(project, PsiSubstitutor.EMPTY) override fun getAnnotations(): Collection<AnnotationRequest> = emptyList() override fun getModifiers(): Collection<JvmModifier> = modifiers override fun isConstant(): Boolean = false override fun getFieldType(): List<ExpectedType> = expectedTypes(PsiType.getTypeByName(type, project, project.allScope())) override fun getFieldName(): String = name override fun isValid(): Boolean = true override fun getInitializer(): JvmValue? = null } } internal inline fun <reified T : JvmElement> CodeInsightTestFixture.atCaret() = elementAtCaret.toUElement() as T @Suppress("MissingRecentApi") private class TestModifierRequest(private val _modifier: JvmModifier, private val shouldBePresent: Boolean) : ChangeModifierRequest { override fun shouldBePresent(): Boolean = shouldBePresent override fun isValid(): Boolean = true override fun getModifier(): JvmModifier = _modifier } @Suppress("CAST_NEVER_SUCCEEDS") internal fun List<IntentionAction>.findWithText(text: String): IntentionAction = this.firstOrNull { it.text == text } ?: Assert.fail("intention with text '$text' was not found, only ${this.joinToString { "\"${it.text}\"" }} available") as Nothing
apache-2.0
82d8c4d02cabca0117570210df665a6e
32.895041
198
0.531076
5.418549
false
false
false
false
JetBrains/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/LocalEscapeAnalysis.kt
2
9478
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.konan.llvm.Lifetime import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.logMultiple import org.jetbrains.kotlin.backend.konan.descriptors.isArrayWithFixedSizeItems internal object LocalEscapeAnalysis { private enum class EscapeState { GLOBAL_ESCAPE, // escape through global reference ARG_ESCAPE, // escapes through function arguments, return or throw NO_ESCAPE // object does not escape } class FunctionAnalyzer(val function: DataFlowIR.Function, val context: Context) { // Escape states of nodes. private val nodesEscapeStates = mutableMapOf<DataFlowIR.Node, EscapeState>() // Connected objects map, escape state change of key node influences on all connected nodes states. private val connectedObjects = mutableMapOf<DataFlowIR.Node, MutableSet<DataFlowIR.Node>>() // Maximum size of array which is allowed to allocate on stack. // TODO: replace into KonanConfigKeys? private val stackAllocationArraySizeLimit = 64 private var DataFlowIR.Node.escapeState: EscapeState set(value) { // Write state only if it has more limitations. val writeState = nodesEscapeStates[this]?.let { value < it } ?: true if (writeState) { nodesEscapeStates[this] = value } } get() = nodesEscapeStates.getOrDefault(this, EscapeState.NO_ESCAPE) private fun connectObjects(node: DataFlowIR.Node, connectedNode: DataFlowIR.Node) { connectedObjects.getOrPut(node) { mutableSetOf() }.add(connectedNode) } private fun findOutArraySize(node: DataFlowIR.Node): Int? { if (node is DataFlowIR.Node.SimpleConst<*>) { return node.value as? Int } if (node is DataFlowIR.Node.Variable) { // In case of several possible values, it's unknown what is used. // TODO: if all values are constants which are less limit? if (node.values.size == 1) { return findOutArraySize(node.values.first().node) } } return null } private fun evaluateEscapeState(node: DataFlowIR.Node) { node.escapeState = EscapeState.NO_ESCAPE when (node) { is DataFlowIR.Node.Call -> { val pointsToMasks = (0..node.callee.parameters.size) .map { node.callee.pointsTo?.elementAtOrNull(it) ?: 0 } val returnPointsToMask = pointsToMasks[node.callee.parameters.size] node.arguments.forEachIndexed { index, arg -> // Check information about arguments escaping. val escapes = node.callee.escapes?.let { it and (1 shl index) != 0 } ?: node.callee !is DataFlowIR.FunctionSymbol.External // Connect with all arguments that return value points to. if (returnPointsToMask and (1 shl index) != 0) { connectObjects(node, arg.node) } // Connect current argument with other it points to. (0..node.callee.parameters.size).filter { pointsToMasks[index] and (1 shl it) != 0 }.forEach { if (it == node.callee.parameters.size) { // Argument points to this. connectObjects(arg.node, node) } else { connectObjects(arg.node, node.arguments[it].node) } } arg.node.escapeState = if (escapes) EscapeState.ARG_ESCAPE else EscapeState.NO_ESCAPE } // Check size for array allocation. if (node is DataFlowIR.Node.NewObject && node.constructedType is DataFlowIR.Type.Declared) { node.constructedType.irClass?.let { irClass -> // Work only with arrays which elements size is known. if (irClass.isArrayWithFixedSizeItems) { val sizeArgument = node.arguments.first().node val arraySize = findOutArraySize(sizeArgument) if (arraySize == null || arraySize > stackAllocationArraySizeLimit) { node.escapeState = EscapeState.GLOBAL_ESCAPE } } else { node.escapeState = EscapeState.GLOBAL_ESCAPE } } } } is DataFlowIR.Node.Singleton -> { node.escapeState = EscapeState.GLOBAL_ESCAPE } is DataFlowIR.Node.FieldRead -> { node.receiver?.let { obj -> connectObjects(node, obj.node) } ?: run { node.escapeState = EscapeState.GLOBAL_ESCAPE } } is DataFlowIR.Node.FieldWrite -> { node.receiver?.let { obj -> connectObjects(obj.node, node.value.node) } ?: run { node.escapeState = EscapeState.GLOBAL_ESCAPE node.value.node.escapeState = EscapeState.GLOBAL_ESCAPE } } is DataFlowIR.Node.ArrayWrite -> { connectObjects(node.array.node, node.value.node) } is DataFlowIR.Node.Variable -> { node.values.forEach { connectObjects(node, it.node) } } is DataFlowIR.Node.ArrayRead -> { // If element of array(return value) points to array(this value) and escapes then array also should escape. if (((node.callee.pointsTo?.elementAtOrNull(node.callee.parameters.size) ?: 0) and (1 shl 0)) != 0) { connectObjects(node, node.array.node) } } is DataFlowIR.Node.Parameter -> { node.escapeState = EscapeState.ARG_ESCAPE } } } private inner class ConnectedObjectsVisitor { val visitedObjects = mutableSetOf<DataFlowIR.Node>() fun visit(node: DataFlowIR.Node, action: (DataFlowIR.Node) -> Unit) { action(node) visitedObjects.add(node) connectedObjects[node]?.forEach { if (!visitedObjects.contains(it)) { visit(it, action) } } } } private fun propagateState(state: EscapeState, visitor: ConnectedObjectsVisitor) { connectedObjects.filter { it.key.escapeState == state }.forEach { (key, value) -> value.forEach { obj -> visitor.visit(obj) { it.escapeState = key.escapeState } } } } fun analyze(lifetimes: MutableMap<IrElement, Lifetime>) { function.body.forEachNonScopeNode { node -> evaluateEscapeState(node) } function.body.returns.escapeState = EscapeState.ARG_ESCAPE function.body.throws.escapeState = EscapeState.ARG_ESCAPE // Change state of connected objects. val visitor = ConnectedObjectsVisitor() propagateState(EscapeState.GLOBAL_ESCAPE, visitor) propagateState(EscapeState.ARG_ESCAPE, visitor) nodesEscapeStates.filter { it.value == EscapeState.NO_ESCAPE }.forEach { (irNode, _) -> val ir = when (irNode) { is DataFlowIR.Node.Call -> irNode.irCallSite else -> null } ir?.let { lifetimes.put(it, Lifetime.STACK) context.log { "$ir does not escape" } } } } } fun analyze(context: Context, moduleDFG: ModuleDFG, lifetimes: MutableMap<IrElement, Lifetime>) { moduleDFG.functions.forEach { (name, function) -> context.logMultiple { +"===============================================" +"Visiting $name" +"DATA FLOW IR:" +function.debugString() } FunctionAnalyzer(function, context).analyze(lifetimes) } } fun computeLifetimes(context: Context, moduleDFG: ModuleDFG, lifetimes: MutableMap<IrElement, Lifetime>) { context.log { "In local EA" } assert(lifetimes.isEmpty()) analyze(context, moduleDFG, lifetimes) } }
apache-2.0
db19bd3693312790a9ad1be5b4a15306
44.572115
127
0.522051
5.289063
false
false
false
false
youdonghai/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.kt
1
4277
/* * Copyright 2000-2013 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.gradle.service.resolve import com.intellij.patterns.PsiJavaPatterns.psiElement import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import groovy.lang.Closure import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_PROJECT import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil import org.jetbrains.plugins.groovy.lang.psi.patterns.groovyClosure import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DelegatesToInfo /** * @author Vladislav.Soroka * @since 11/18/13 */ class GradleIdeaPluginScriptContributor : GradleMethodContextContributor { companion object { val IDEA_METHOD = "idea" val IDEA_MODEL_FQN = "org.gradle.plugins.ide.idea.model.IdeaModel" val IDEA_PROJECT_FQN = "org.gradle.plugins.ide.idea.model.IdeaProject" val IDEA_MODULE_FQN = "org.gradle.plugins.ide.idea.model.IdeaModule" val IDEA_MODULE_IML_FQN = "org.gradle.plugins.ide.idea.model.IdeaModuleIml" val IDE_XML_MERGER_FQN = "org.gradle.plugins.ide.api.XmlFileContentMerger" val IDE_FILE_MERGER_FQN = "org.gradle.plugins.ide.api.FileContentMerger" val IDEA_XML_MODULE_FQN = "org.gradle.plugins.ide.idea.model.Module" val IDEA_XML_PROJECT_FQN = "org.gradle.plugins.ide.idea.model.Project" val ideaClosure = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, IDEA_METHOD)) val ideaProjectClosure = groovyClosure().inMethod(psiMethod(IDEA_MODEL_FQN, "project")) val ideaIprClosure = groovyClosure().inMethod(psiMethod(IDEA_PROJECT_FQN, "ipr")) val ideaModuleClosure = groovyClosure().inMethod(psiMethod(IDEA_MODEL_FQN, "module")) val ideaImlClosure = groovyClosure().inMethod(psiMethod(IDEA_MODULE_FQN, "iml")) val ideaBeforeMergedClosure = groovyClosure().inMethod(psiMethod(IDE_FILE_MERGER_FQN, "beforeMerged")) val ideaWhenMergedClosure = groovyClosure().inMethod(psiMethod(IDE_FILE_MERGER_FQN, "whenMerged")) } override fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? { if (ideaClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(IDEA_MODEL_FQN, closure), Closure.DELEGATE_FIRST) } if (ideaImlClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(IDEA_MODULE_IML_FQN, closure), Closure.DELEGATE_FIRST) } if (ideaProjectClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(IDEA_PROJECT_FQN, closure), Closure.DELEGATE_FIRST) } if (ideaModuleClosure.accepts(closure)) { return DelegatesToInfo(TypesUtil.createType(IDEA_MODULE_FQN, closure), Closure.DELEGATE_FIRST) } return null } override fun process(methodCallInfo: List<String>, processor: PsiScopeProcessor, state: ResolveState, place: PsiElement): Boolean { val ideaExtension = GradleExtensionsSettings.GradleExtension().apply { name = IDEA_METHOD rootTypeFqn = IDEA_MODEL_FQN } if (!processExtension(processor, state, place, ideaExtension)) return false val psiManager = GroovyPsiManager.getInstance(place.project) if (psiElement().inside(ideaIprClosure).inside(ideaProjectClosure).accepts(place)) { if (GradleResolverUtil.processDeclarations(psiManager, processor, state, place, IDE_XML_MERGER_FQN)) return false } return true } }
apache-2.0
e8212156a2eb4203012c534f1acdd501
48.172414
133
0.768997
4.046358
false
true
false
false
jrvermeer/Psalter
app/src/main/java/com/jrvermeer/psalter/helpers/RateHelper.kt
1
1705
package com.jrvermeer.psalter.helpers import android.app.Activity import com.google.android.play.core.review.ReviewManagerFactory import com.jrvermeer.psalter.infrastructure.Logger import java.util.concurrent.TimeUnit class RateHelper(private val activity: Activity, private val storage: StorageHelper) { fun showRateDialogIfAppropriate() { if (!shouldShowDialog()) return val manager = ReviewManagerFactory.create(activity) val request = manager.requestReviewFlow() request.addOnCompleteListener { request -> if (request.isSuccessful) { val reviewInfo = request.result manager.launchReviewFlow(activity, reviewInfo) showRatePromptAttempted() } } } private fun shouldShowDialog(): Boolean { // if prompt hasn't been shown yet, set it to now for the sake of calculation if(storage.lastRatePromptTime <= 0) storage.lastRatePromptTime = System.currentTimeMillis() return storage.launchCount > 5 && enoughTimeSinceLastShow() } private fun enoughTimeSinceLastShow(): Boolean { val daysSinceShown = TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis() - storage.lastRatePromptTime) val daysToWait = if (storage.ratePromptCount == 0) 7 else 31 return daysSinceShown >= daysToWait // no more than every month } private fun showRatePromptAttempted() { storage.ratePromptCount++ storage.lastRatePromptTime = System.currentTimeMillis() storage.launchCount = 0 // reset requirements for re-showing Logger.ratePromptAttempt(storage.ratePromptCount) } }
mit
6502d09f22d6aba057a989f8e644edc9
38.674419
114
0.689736
4.913545
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/style/TextIndent.kt
3
2909
/* * 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.compose.ui.text.style import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.ui.text.lerpTextUnitInheritable import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp /** * Specify the indentation of a paragraph. * * @param firstLine the amount of indentation applied to the first line. * @param restLine the amount of indentation applied to every line except the first line. */ @Immutable class TextIndent( val firstLine: TextUnit = 0.sp, val restLine: TextUnit = 0.sp ) { companion object { /** * Constant fot no text indent. */ @Stable val None = TextIndent() } fun copy( firstLine: TextUnit = this.firstLine, restLine: TextUnit = this.restLine ): TextIndent { return TextIndent(firstLine, restLine) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is TextIndent) return false if (firstLine != other.firstLine) return false if (restLine != other.restLine) return false return true } override fun hashCode(): Int { var result = firstLine.hashCode() result = 31 * result + restLine.hashCode() return result } override fun toString(): String { return "TextIndent(firstLine=$firstLine, restLine=$restLine)" } } /** * Linearly interpolate between two [TextIndent]s. * * The [fraction] argument represents position on the timeline, with 0.0 meaning * that the interpolation has not started, returning [start] (or something * equivalent to [start]), 1.0 meaning that the interpolation has finished, * returning [stop] (or something equivalent to [stop]), and values in between * meaning that the interpolation is at the relevant point on the timeline * between [start] and [stop]. The interpolation can be extrapolated beyond 0.0 and * 1.0, so negative values and values greater than 1.0 are valid. */ fun lerp(start: TextIndent, stop: TextIndent, fraction: Float): TextIndent { return TextIndent( lerpTextUnitInheritable(start.firstLine, stop.firstLine, fraction), lerpTextUnitInheritable(start.restLine, stop.restLine, fraction) ) }
apache-2.0
439267f33961c678d0ebc3b3f5403d4a
32.825581
89
0.700241
4.284242
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinLocalFunctionUVariable.kt
4
1328
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiExpression import com.intellij.psi.PsiVariable import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.psi.UastKotlinPsiVariable @ApiStatus.Internal class KotlinLocalFunctionUVariable( val function: KtFunction, override val javaPsi: PsiVariable, givenParent: UElement? ) : KotlinAbstractUElement(givenParent), UVariableEx, PsiVariable by javaPsi { override val psi get() = javaPsi override val sourcePsi: PsiElement = (javaPsi as? UastKotlinPsiVariable?)?.ktElement ?: javaPsi override val uastInitializer: UExpression? by lz { createLocalFunctionLambdaExpression(function, this) } override val typeReference: UTypeReferenceExpression? = null override val uastAnchor: UElement? = null override val uAnnotations: List<UAnnotation> = emptyList() override fun getOriginalElement(): PsiElement { return psi.originalElement } override fun getInitializer(): PsiExpression? { return psi.initializer } }
apache-2.0
bec0dea474849e7f843b3a7ecc4ab5e9
35.888889
158
0.767319
4.900369
false
false
false
false
GunoH/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/QueriesDuration.kt
12
995
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.completion.ml.personalization.session class QueriesDuration(private var lastUpdateTimestamp: Long) : CompletionQueryTracker.Durations { override fun getCurrentQueryDuration(): Long = System.currentTimeMillis() - lastUpdateTimestamp override fun getAverageQueryDuration(): Double = tracker.average(currentPeriodDuration()) override fun getMinQueryDuration(): Long = tracker.minDuration(currentPeriodDuration())!! override fun getMaxQueryDuration(): Long = tracker.maxDuration(currentPeriodDuration())!! private val tracker: PeriodTracker = PeriodTracker() fun fireQueryChanged() { val now = System.currentTimeMillis() tracker.addDuration(now - lastUpdateTimestamp) lastUpdateTimestamp = now } private fun currentPeriodDuration(): Long { return System.currentTimeMillis() - lastUpdateTimestamp } }
apache-2.0
1e4bb5859d23676dc884ce3bcdc9c615
46.428571
140
0.784925
5.025253
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/statistics/FeatureSuggestersStatistics.kt
8
3217
package training.featuresSuggester.statistics import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventId1 import com.intellij.internal.statistic.eventLog.validator.ValidationResultType import com.intellij.internal.statistic.eventLog.validator.rules.EventContext import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.internal.statistic.utils.getPluginInfo import com.intellij.openapi.util.registry.Registry import training.featuresSuggester.statistics.FeatureSuggesterStatistics.Companion.SUGGESTER_ID_VALIDATION_RULE import training.featuresSuggester.suggesters.FeatureSuggester class FeatureSuggesterStatistics : CounterUsagesCollector() { override fun getGroup() = GROUP companion object { private const val GROUP_ID = "feature_suggester" private const val NOTIFICATION_SHOWED_EVENT_ID = "notification.showed" private const val NOTIFICATION_DONT_SUGGEST_EVENT_ID = "notification.dont_suggest" private const val NOTIFICATION_LEARN_MORE_EVENT_ID = "notification.learn_more" private const val SUGGESTION_FOUND = "suggestion_found" private const val SUGGESTER_ID_FIELD = "suggester_id" const val SUGGESTER_ID_VALIDATION_RULE = "feature_suggester_id" private val GROUP = EventLogGroup(GROUP_ID, 4) private val suggesterIdField = EventFields.StringValidatedByCustomRule(SUGGESTER_ID_FIELD, FeatureSuggesterIdRuleValidator::class.java) private val notificationShowedEvent = GROUP.registerEvent(NOTIFICATION_SHOWED_EVENT_ID, suggesterIdField) private val notificationDontSuggestEvent = GROUP.registerEvent(NOTIFICATION_DONT_SUGGEST_EVENT_ID, suggesterIdField) private val notificationLearnMoreEvent = GROUP.registerEvent(NOTIFICATION_LEARN_MORE_EVENT_ID, suggesterIdField) private val suggestionFoundEvent = GROUP.registerEvent(SUGGESTION_FOUND, suggesterIdField) fun logNotificationShowed(suggesterId: String) = sendStatistics(notificationShowedEvent, suggesterId) fun logNotificationDontSuggest(suggesterId: String) = sendStatistics(notificationDontSuggestEvent, suggesterId) fun logNotificationLearnMore(suggesterId: String) = sendStatistics(notificationLearnMoreEvent, suggesterId) fun logSuggestionFound(suggesterId: String) = sendStatistics(suggestionFoundEvent, suggesterId) private fun sendStatistics(event: EventId1<String?>, suggesterId: String) { if (Registry.`is`("feature.suggester.send.statistics", false)) { event.log(suggesterId) } } } } class FeatureSuggesterIdRuleValidator : CustomValidationRule() { override fun getRuleId(): String = SUGGESTER_ID_VALIDATION_RULE override fun doValidate(data: String, context: EventContext): ValidationResultType { val suggesterIds = FeatureSuggester.suggesters.filter { getPluginInfo(it::class.java).isDevelopedByJetBrains() } .map(FeatureSuggester::id) return if (suggesterIds.contains(data)) ValidationResultType.ACCEPTED else ValidationResultType.REJECTED } }
apache-2.0
b75ed4053d751a95cf0504b63710dee1
55.438596
139
0.814734
4.780089
false
false
false
false
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/event/EventDispatcher.kt
1
2680
package com.haishinkit.event import androidx.core.util.Pools import java.util.ArrayList import java.util.Collections import java.util.concurrent.ConcurrentHashMap open class EventDispatcher(private val target: IEventDispatcher?) : IEventDispatcher { private val pool = Pools.SynchronizedPool<Event>(MAX_POOL_SIZE) private val listeners = ConcurrentHashMap<String, MutableList<IEventListener>>() override fun addEventListener(type: String, listener: IEventListener, useCapture: Boolean) { val key: String = "$type/$useCapture" listeners.putIfAbsent(key, Collections.synchronizedList(mutableListOf<IEventListener>())) listeners[key]?.add(listener) } override fun dispatchEvent(event: Event) { if (event.type == null) { throw IllegalArgumentException() } val targets = ArrayList<IEventDispatcher>() targets.add(target ?: this) for (target in targets) { event.currentTarget = target val isTargetPhase = target === event.target if (isTargetPhase) { event.eventPhase = Event.EVENT_PHASE_AT_TARGET } val isCapturingPhase = (event.eventPhase == Event.EVENT_PHASE_CAPTURING).toString() val listeners = this.listeners["${event.type}/$isCapturingPhase"] if (listeners != null) { for (listener in listeners) { listener.handleEvent(event) } if (event.propagationStopped) { break } } if (isTargetPhase) { event.eventPhase = Event.EVENT_PHASE_BUBBLING } } event.target = null event.currentTarget = null event.eventPhase = Event.EVENT_PHASE_NONE event.propagationStopped = false } override fun dispatchEventWith(type: String, bubbles: Boolean, data: Any?) { val event = pool.acquire() ?: Event(type, bubbles, data) event.type = type event.isBubbles = bubbles event.data = data dispatchEvent(event) pool.release(event) } override fun removeEventListener(type: String, listener: IEventListener, useCapture: Boolean) { val key = "$type/$useCapture" if (!listeners.containsKey(key)) { return } val list = listeners[key]!! var i = list.size - 1 while (0 <= i) { if (list[i] === listener) { list.removeAt(i) return } --i } } companion object { const val MAX_POOL_SIZE = 16 } }
bsd-3-clause
5816181f0cb3054437e35e88f3e8a341
30.904762
99
0.586567
4.710018
false
false
false
false
GunoH/intellij-community
plugins/kotlin/compiler-plugins/kotlinx-serialization/tests/testData/diagnostics/JsonRedundantFormat.kt
8
6509
@file:Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE") import kotlinx.serialization.* import kotlinx.serialization.json.* object Instance val defaultWarn = <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning> val receiverWarn = <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.encodeToString(Instance) val noWarnFormat = Json {encodeDefaults = true} val receiverNoWarn = noWarnFormat.encodeToString(Instance) val defaultNoWarn = Json.encodeToString(Instance) class SomeContainerClass { val memberDefaultWarn = <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning> val memberReceiverWarn = <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.encodeToString(Instance) val memberNoWarnFormat = Json {encodeDefaults = true} val memberReceiverNoWarn = noWarnFormat.encodeToString(Instance) val memberDefaultNoWarn = Json.encodeToString(Instance) fun testDefaultWarnings() { <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json() {}</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning>.encodeToString(Any()) <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning>.encodeToString(Instance) <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json { /*some comment*/ }</warning>.encodeToString(Instance) val localDefaultFormat = <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(Json.Default) {}</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(Json) {}</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(Json.Default, {})</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(builderAction = {})</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(builderAction = fun JsonBuilder.() {})</warning> <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json(builderAction = fun JsonBuilder.() = Unit)</warning> "{}".let { <warning descr="[JSON_FORMAT_REDUNDANT_DEFAULT] Redundant creation of Json default format. Creating instances for each usage can be slow.">Json {}</warning>.decodeFromString<Any>(it) } } fun testReceiverWarnings() { <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.encodeToString(Instance) val encoded = <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.encodeToString(Instance) <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.decodeFromString<Any>("{}") <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.hashCode() <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.toString() <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json(noWarnFormat) {encodeDefaults = true}</warning>.encodeToString(Instance) <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json(builderAction = {encodeDefaults = true})</warning>.encodeToString(Instance) <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json(noWarnFormat, {encodeDefaults = true})</warning>.encodeToString(Instance) <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json(builderAction = fun JsonBuilder.() {encodeDefaults = true})</warning>.encodeToString(Instance) "{}".let { <warning descr="[JSON_FORMAT_REDUNDANT] Redundant creation of Json format. Creating instances for each usage can be slow.">Json {encodeDefaults = true}</warning>.decodeFromString<Any>(it) } } fun testReceiverNoWarnings() { val localFormat = Json {encodeDefaults = true} localFormat.encodeToString(Instance) localFormat.decodeFromString<Any>("{}") localFormat.hashCode() localFormat.toString() } fun testDefaultNoWarnings() { val localDefault = Json Json.encodeToString(Instance) Json.decodeFromString<Any>("{}") Json.hashCode() Json.toString() Json(builderAction = this::builder) Json(Json.Default, this::builder) } private fun builder(builder: JsonBuilder) { //now its empty builder } }
apache-2.0
23b51f43c1e4f370bd03b1a34fccf5a0
80.3625
230
0.738055
4.793078
false
false
false
false
vovagrechka/fucking-everything
attic/alraune/alraune-back-very-old/src/db.kt
1
4357
package vgrechka import alraune.back.* object DBPile { interface Operator { val sql: String } object op { object eq : Operator { override fun toString() = "EQ" override val sql: String = "=" } } fun init() { phiEval(""" // 572cf316-de85-468f-8af9-c2097f39de51 global ${'$'}pdo; ${'$'}host = '127.0.0.1'; ${'$'}db = 'alraune'; ${'$'}user = 'root'; ${'$'}pass = ''; ${'$'}charset = 'utf8'; ${'$'}dsn = "mysql:host=${'$'}host;dbname=${'$'}db;charset=${'$'}charset"; ${'$'}opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ); ${'$'}pdo = new PDO(${'$'}dsn, ${'$'}user, ${'$'}pass, ${'$'}opt); """) // execute("set autocommit = 0") execute("set time_zone = '+0:00'") } fun execute(sql: String, params: List<Any?> = listOf(), uuid: String? = null) { phiEval("\$x = Phi::getCurrentEnv(); \$x = \$x->getVar('sql'); \$x = \$x->value; \$GLOBALS['sql'] = \$x;") phiEval("\$GLOBALS['params'] = array();") for (param in params) { phiEval("\$x = Phi::getCurrentEnv(); \$x = \$x->getVar('param'); \$x = \$x->value; array_push(\$GLOBALS['params'], \$x);") } phiEval(buildString { if (uuid != null) { ln("") ln("//") ln("// Query UUID: $uuid") ln("//") } ln("global ${'$'}pdo, ${'$'}sql, ${'$'}params, ${'$'}st;") ln("// var_dump(${'$'}sql);") ln("// var_dump(${'$'}params);") ln("${'$'}st = ${'$'}pdo->prepare(${'$'}sql);") ln("${'$'}res = ${'$'}st->execute(${'$'}params);") ln("if (!${'$'}res) {") ln(" throw new Exception('PDO error ' . ${'$'}st->errorCode() . ' 2503eb26-1f1e-4df2-b4e1-cfc677e3cd57');") ln("}") // ln("${'$'}st->closeCursor();") }) } fun query(sql: String, params: List<Any?> = listOf(), uuid: String? = null): List<List<Any?>> { execute(sql, params, uuid) // Sets global $st val rows = mutableListOf<List<Any?>>() phiEval(buildString { ln("global ${'$'}st, ${'$'}rows, ${'$'}numCols;") ln("${'$'}rows = ${'$'}st->fetchAll(PDO::FETCH_NUM);") ln("if (count(${'$'}rows) > 0) {") ln(" ${'$'}numCols = count(${'$'}rows[0]);") ln("}") }) val numRows = phiEval("return count(${'$'}GLOBALS['rows']);") as Int if (numRows > 0) { val numCols = phiEval("return ${'$'}GLOBALS['numCols'];") as Int for (rowIndex in 0 until numRows) { val row = mutableListOf<Any?>() for (colIndex in 0 until numCols) { @Suppress("UnsafeCastFromDynamic") row.add(phiEval(buildString { ln("${'$'}env = Phi::getCurrentEnv();") ln("${'$'}rowIndex = ${'$'}env->getVar('rowIndex'); ${'$'}rowIndex = ${'$'}rowIndex->value;") ln("${'$'}colIndex = ${'$'}env->getVar('colIndex'); ${'$'}colIndex = ${'$'}colIndex->value;") ln("return ${'$'}GLOBALS['rows'][${'$'}rowIndex][${'$'}colIndex];") })) } rows += row } } return rows } fun tx(block: () -> Unit) { execute("begin", uuid = "c1ba9d12-d7e6-4982-8d9d-3da40087ddb9") try { block() execute("commit", uuid = "e686454e-017f-4f0d-ade8-056bba22da2a") } catch (e: dynamic) { execute("rollback", uuid = "b0bb24e9-81d7-4b6a-8bc0-bcf54dea4a13") throw e } } fun mysqlValueToBoolean(x: Any?): Boolean { return when(x as String) { "1" -> true else -> false } } fun mysqlValueToPHPTimestamp(x: Any?): XTimestamp { return PHPTimestamp((x as String).toInt()) } fun currentTimestampForEntity(): PHPTimestamp { return PHPTimestamp(phiEval("return time();") as Int) } }
apache-2.0
5ae003f4f49ba994c191705ebae8c794
30.121429
134
0.431031
4.015668
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/codegen/arithmetic/github1856.kt
4
905
package codegen.arithmetic.github1856 import kotlin.test.* object RGBA { fun packFast(r: Int, g: Int, b: Int, a: Int) = (r shl 0) or (g shl 8) or (b shl 16) or (a shl 24) fun getFastR(v: Int): Int = (v ushr 0) and 0xFF fun getFastG(v: Int): Int = (v ushr 8) and 0xFF fun getFastB(v: Int): Int = (v ushr 16) and 0xFF fun getFastA(v: Int): Int = (v ushr 24) and 0xFF fun premultiplyFastInt(v: Int): Int { val A = getFastA(v) + 1 val RB = (((v and 0x00FF00FF) * A) ushr 8) and 0x00FF00FF val G = (((v and 0x0000FF00) * A) ushr 8) and 0x0000FF00 return (v and 0x00FFFFFF.inv()) or RB or G } } @Test fun main() { val source = listOf(0xFFFFFFFF.toInt(), 0xFFFFFF77.toInt(), 0x777777FF.toInt(), 0x77777777.toInt()) val expect = listOf(-1, -137, 2000107383, 2000107319) assertEquals(expect, source.map { RGBA.premultiplyFastInt(it) }) }
apache-2.0
58e03595eaed3f2daafdf51fb4aaa2f6
33.846154
103
0.623204
2.79321
false
true
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/webTypes/impl/WebTypesPatternUtils.kt
2
7282
// 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.webSymbols.webTypes.impl import com.intellij.util.containers.Stack import com.intellij.webSymbols.* import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem import com.intellij.webSymbols.patterns.ComplexPatternOptions import com.intellij.webSymbols.patterns.WebSymbolsPattern import com.intellij.webSymbols.patterns.impl.* import com.intellij.webSymbols.query.WebSymbolMatch import com.intellij.webSymbols.query.WebSymbolsNameMatchQueryParams import com.intellij.webSymbols.query.WebSymbolsQueryExecutor import com.intellij.webSymbols.webTypes.json.* internal fun NamePatternRoot.wrap(defaultDisplayName: String?): WebSymbolsPattern = when (val value = value) { is String -> RegExpPattern(value) is NamePatternBase -> value.wrap(defaultDisplayName) else -> throw IllegalArgumentException(value::class.java.name) } internal fun NamePatternBase.wrap(defaultDisplayName: String?): WebSymbolsPattern = when (this) { is NamePatternRegex -> RegExpPattern(regex, caseSensitive == true) is NamePatternDefault -> ComplexPattern(WebTypesComplexPatternConfigProvider(this, defaultDisplayName)) else -> throw IllegalArgumentException(this::class.java.name) } @Suppress("UNCHECKED_CAST") internal fun NamePatternTemplate.wrap(defaultDisplayName: String?): WebSymbolsPattern = when (val value = value) { is String -> when { value == "#item" -> ItemPattern(defaultDisplayName) value.startsWith("#item:") -> ItemPattern(value.substring(6)) value == "#..." -> CompletionAutoPopupPattern(false) value == "$..." -> CompletionAutoPopupPattern(true) else -> StaticPattern(value) } is NamePatternBase -> value.wrap(defaultDisplayName) is List<*> -> SequencePattern(SequencePatternPatternsProvider(value as List<NamePatternTemplate>)) else -> throw IllegalArgumentException(value::class.java.name) } private class SequencePatternPatternsProvider(private val list: List<NamePatternTemplate>) : () -> List<WebSymbolsPattern> { override fun invoke(): List<WebSymbolsPattern> = list.map { it.wrap(null) } } private class WebTypesComplexPatternConfigProvider(private val pattern: NamePatternDefault, private val defaultDisplayName: String?) : ComplexPatternConfigProvider { override fun getPatterns(): List<WebSymbolsPattern> = pattern.or.asSequence() .map { it.wrap(defaultDisplayName) } .let { val template = pattern.template if (template.isEmpty()) { it } else { it.plus(SequencePattern(SequencePatternPatternsProvider(template))) } } .toList() .ifEmpty { listOf(SequencePattern(ItemPattern(defaultDisplayName))) } override val isStaticAndRequired: Boolean get() = pattern.delegate == null && pattern.items == null && pattern.required != false override fun getOptions(params: MatchParameters, scopeStack: Stack<WebSymbolsScope>): ComplexPatternOptions { val queryParams = WebSymbolsNameMatchQueryParams(params.queryExecutor, true, false) val delegate = pattern.delegate?.resolve(null, scopeStack, queryParams.queryExecutor)?.firstOrNull() // Allow delegate pattern to override settings val isDeprecated = delegate?.deprecated ?: pattern.deprecated val isRequired = (delegate?.required ?: pattern.required) != false val priority = delegate?.priority ?: pattern.priority?.wrap() val proximity = delegate?.proximity ?: pattern.proximity val repeats = pattern.repeat == true val unique = pattern.unique != false val itemsProvider = createItemsProvider(delegate) return ComplexPatternOptions(delegate, isDeprecated, isRequired, priority, proximity, repeats, unique, itemsProvider) } private fun createItemsProvider(delegate: WebSymbol?) = if (pattern.delegate != null) { if (delegate != null) { PatternDelegateItemsProvider(delegate) } else null } else pattern.items ?.takeIf { it.isNotEmpty() } ?.let { PatternItemsProvider(it) } private class PatternDelegateItemsProvider(override val delegate: WebSymbol) : com.intellij.webSymbols.patterns.WebSymbolsPatternItemsProvider { override fun getSymbolKinds(context: WebSymbol?): Set<WebSymbolQualifiedKind> = setOf(WebSymbolQualifiedKind(delegate.namespace, delegate.kind)) override fun codeCompletion(name: String, position: Int, scopeStack: Stack<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor): List<WebSymbolCodeCompletionItem> = delegate.pattern ?.getCompletionResults(delegate, scopeStack, this, CompletionParameters(name, queryExecutor, position), 0, name.length) ?.items ?.applyIcons(delegate) ?: emptyList() override fun matchName(name: String, scopeStack: Stack<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor): List<WebSymbol> = delegate.pattern ?.match(delegate, scopeStack, null, MatchParameters(name, queryExecutor), 0, name.length) ?.asSequence() ?.flatMap { matchResult -> if (matchResult.start == matchResult.end) { emptySequence() } else if (matchResult.segments.size == 1 && matchResult.segments[0].canUnwrapSymbols()) { matchResult.segments[0].symbols.asSequence() } else { val lastContribution = scopeStack.peek() as WebSymbol sequenceOf(WebSymbolMatch.create(name, matchResult.segments, lastContribution.namespace, SPECIAL_MATCHED_CONTRIB, lastContribution.origin)) } } ?.toList() ?: emptyList() } private class PatternItemsProvider(val items: ListReference) : com.intellij.webSymbols.patterns.WebSymbolsPatternItemsProvider { override fun getSymbolKinds(context: WebSymbol?): Set<WebSymbolQualifiedKind> = items.asSequence().mapNotNull { it.getSymbolKind(context) }.toSet() override val delegate: WebSymbol? get() = null override fun codeCompletion(name: String, position: Int, scopeStack: Stack<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor): List<WebSymbolCodeCompletionItem> = items.flatMap { it.codeCompletion(name, scopeStack, queryExecutor, position) } override fun matchName(name: String, scopeStack: Stack<WebSymbolsScope>, queryExecutor: WebSymbolsQueryExecutor): List<WebSymbol> = items.asSequence() .flatMap { it.resolve(name, scopeStack, queryExecutor) } .flatMap { if (it is WebSymbolMatch && it.nameSegments.size == 1 && it.nameSegments[0].canUnwrapSymbols()) it.nameSegments[0].symbols else listOf(it) } .toList() } }
apache-2.0
a3a256081328118762f09e859d7fdc2f
42.345238
146
0.677286
5.032481
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/testSources/importing/GradleSetupProjectTestCase.kt
2
7496
// 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.importing import com.intellij.openapi.Disposable import com.intellij.openapi.application.EDT import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.externalSystem.action.AttachExternalProjectAction import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectNotificationAware import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.importProjectAsync import com.intellij.openapi.externalSystem.util.performAction import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.common.runAll import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import org.jetbrains.concurrency.asDeferred import org.jetbrains.plugins.gradle.action.ImportProjectFromScriptAction import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.testFramework.util.buildscript import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID import org.jetbrains.plugins.gradle.util.getProjectDataLoadPromise import org.jetbrains.plugins.gradle.util.whenResolveTaskStarted import org.junit.jupiter.api.Assertions.assertEquals import org.junit.runners.Parameterized import java.util.concurrent.atomic.AtomicInteger import kotlin.time.Duration.Companion.minutes import com.intellij.testFramework.useProjectAsync as useProjectAsyncImpl abstract class GradleSetupProjectTestCase : GradleImportingTestCase() { private lateinit var testDisposable: Disposable private lateinit var expectedImportActionsCounter: AtomicInteger private lateinit var actualImportActionsCounter: AtomicInteger override fun runInDispatchThread() = false override fun setUp() { super.setUp() testDisposable = Disposer.newDisposable() expectedImportActionsCounter = AtomicInteger(0) actualImportActionsCounter = AtomicInteger(0) whenResolveTaskStarted({ actualImportActionsCounter.incrementAndGet() }, testDisposable) AutoImportProjectTracker.enableAutoReloadInTests(testDisposable) } override fun tearDown() { runAll( { Disposer.dispose(testDisposable) }, { super.tearDown() } ) } fun generateProject(id: String): ProjectInfo { val name = "${System.currentTimeMillis()}-$id" createProjectSubFile("$name-composite/settings.gradle", "rootProject.name = '$name-composite'") createProjectSubFile("$name-project/settings.gradle", """ rootProject.name = '$name-project' include 'module' includeBuild '../$name-composite' includeFlat '$name-module' """.trimIndent()) val buildScript = buildscript { withJavaPlugin() } createProjectSubFile("$name-composite/build.gradle", buildScript) createProjectSubFile("$name-module/build.gradle", buildScript) createProjectSubFile("$name-project/module/build.gradle", buildScript) val projectFile = createProjectSubFile("$name-project/build.gradle", buildScript) return ProjectInfo(projectFile, "$name-project", "$name-project.main", "$name-project.test", "$name-project.module", "$name-project.module.main", "$name-project.module.test", "$name-project.$name-module", "$name-project.$name-module.main", "$name-project.$name-module.test", "$name-composite", "$name-composite.main", "$name-composite.test") } fun assertProjectState(project: Project, vararg projectsInfo: ProjectInfo) { assertProjectStructure(project, *projectsInfo) for (projectInfo in projectsInfo) { assertProjectSettings(project) } assertNotificationIsVisible(project, false) assertAutoReloadState() } private fun assertProjectStructure(project: Project, vararg projectsInfo: ProjectInfo) { assertModules(project, *projectsInfo.flatMap { it.modules }.toTypedArray()) } private fun assertProjectSettings(project: Project) { val externalProjectPath = project.basePath!! val settings = ExternalSystemApiUtil.getSettings(project, SYSTEM_ID) as GradleSettings val projectSettings = settings.getLinkedProjectSettings(externalProjectPath)!! assertEquals(projectSettings.externalProjectPath, externalProjectPath) assertEquals(projectSettings.isUseQualifiedModuleNames, true) assertEquals(settings.storeProjectFilesExternally, true) } @Suppress("SameParameterValue") private fun assertNotificationIsVisible(project: Project, isNotificationVisible: Boolean) { val notificationAware = AutoImportProjectNotificationAware.getInstance(project) assertEquals(isNotificationVisible, notificationAware.isNotificationVisible()) { notificationAware.getProjectsWithNotification().toString() } } private fun assertAutoReloadState() { assertEquals(expectedImportActionsCounter.get(), actualImportActionsCounter.get()) } suspend fun waitForImport(action: suspend () -> Project): Project { expectedImportActionsCounter.incrementAndGet() val promise = getProjectDataLoadPromise() val result = action() withTimeout(1.minutes) { promise.asDeferred().join() } return result } suspend fun importProjectAsync(projectFile: VirtualFile): Project { return importProjectAsync(projectFile, SYSTEM_ID) } suspend fun attachProjectAsync(project: Project, projectFile: VirtualFile): Project { performAction( action = AttachExternalProjectAction(), project = project, systemId = SYSTEM_ID, selectedFile = projectFile ) return project } suspend fun attachProjectFromScriptAsync(project: Project, projectFile: VirtualFile): Project { performAction( action = ImportProjectFromScriptAction(), project = project, systemId = SYSTEM_ID, selectedFile = projectFile ) return project } suspend fun <R> Project.useProjectAsync(save: Boolean = false, action: suspend (Project) -> R): R { return useProjectAsyncImpl(save) { try { action(it) } finally { cleanupProjectTestResources(this) } } } private suspend fun cleanupProjectTestResources(project: Project) { withContext(Dispatchers.EDT) { runWriteAction { val projectJdkTable = ProjectJdkTable.getInstance() val settings = GradleSettings.getInstance(project) for (projectSettings in settings.linkedProjectsSettings) { val gradleJvm = projectSettings.gradleJvm val sdk = ExternalSystemJdkUtil.getJdk(project, gradleJvm) if (sdk != null) projectJdkTable.removeJdk(sdk) } } } } data class ProjectInfo(val projectFile: VirtualFile, val modules: List<String>) { constructor(projectFile: VirtualFile, vararg modules: String) : this(projectFile, modules.toList()) } companion object { @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION)) } }
apache-2.0
e7a97e66ac63eb9894880b30aa726d82
39.524324
120
0.756804
5.054619
false
true
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/util/TipsOrderUtil.kt
4
6139
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.util import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.internal.statistic.eventLog.EventLogConfiguration import com.intellij.internal.statistic.local.ActionSummary import com.intellij.internal.statistic.local.ActionsLocalSummary import com.intellij.internal.statistic.utils.StatisticsUploadAssistant import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.util.PlatformUtils import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.io.HttpRequests import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import java.util.* import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicReference private val LOG = logger<TipsOrderUtil>() private const val EXPERIMENT_RANDOM_SEED = 0L private const val USED_BUCKETS_COUNT = 128 private const val RANDOM_SHUFFLE_ALGORITHM = "default_shuffle" private const val TIPS_SERVER_URL = "https://feature-recommendation.analytics.aws.intellij.net/tips/v1" internal data class RecommendationDescription(val algorithm: String, val tips: List<TipAndTrickBean>, val version: String?) private fun getUtilityExperiment(): TipsUtilityExperiment? { if (!ApplicationManager.getApplication().isEAP) return null val shuffledBuckets = (0 until USED_BUCKETS_COUNT).shuffled(Random(EXPERIMENT_RANDOM_SEED)) return when (shuffledBuckets[EventLogConfiguration.getInstance().bucket % USED_BUCKETS_COUNT]) { in 0..31 -> TipsUtilityExperiment.BY_TIP_UTILITY in 32..63 -> TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED in 64..95 -> TipsUtilityExperiment.RANDOM_IGNORE_USED else -> null } } private fun randomShuffle(tips: List<TipAndTrickBean>): RecommendationDescription { return RecommendationDescription(RANDOM_SHUFFLE_ALGORITHM, tips.shuffled(), null) } @Service internal class TipsOrderUtil { private class RecommendationsStartupActivity : StartupActivity.Background { private val scheduledFuture = AtomicReference<ScheduledFuture<*>>() override fun runActivity(project: Project) { val app = ApplicationManager.getApplication() if (!app.isEAP || app.isHeadlessEnvironment || !StatisticsUploadAssistant.isSendAllowed()) { return } scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable { try { sync() } finally { scheduledFuture.getAndSet(AppExecutorUtil.getAppScheduledExecutorService().schedule(Runnable(::sync), 3, TimeUnit.HOURS)) ?.cancel(false) } }, 5, TimeUnit.MILLISECONDS)) ?.cancel(false) } } companion object { private fun sync() { LOG.assertTrue(!ApplicationManager.getApplication().isDispatchThread) LOG.debug { "Fetching tips order from the server: ${TIPS_SERVER_URL}" } val allTips = TipAndTrickBean.EP_NAME.iterable.map { it.fileName } val actionsSummary = service<ActionsLocalSummary>().getActionsStats() val startTimestamp = System.currentTimeMillis() HttpRequests.post(TIPS_SERVER_URL, HttpRequests.JSON_CONTENT_TYPE) .connect(HttpRequests.RequestProcessor { request -> val bucket = EventLogConfiguration.getInstance().bucket val tipsRequest = TipsRequest(allTips, actionsSummary, PlatformUtils.getPlatformPrefix(), bucket) val objectMapper = ObjectMapper() request.write(objectMapper.writeValueAsBytes(tipsRequest)) val recommendation = objectMapper.readValue(request.readString(), ServerRecommendation::class.java) LOG.debug { val duration = System.currentTimeMillis() - startTimestamp val algorithmInfo = "${recommendation.usedAlgorithm}:${recommendation.version}" "Server recommendation made. Algorithm: $algorithmInfo. Duration: ${duration}" } service<TipsOrderUtil>().serverRecommendation = recommendation }, null, LOG) } } @Volatile private var serverRecommendation: ServerRecommendation? = null /** * Reorders tips to show the most useful ones in the beginning * * @return object that contains sorted tips and describes approach of how the tips are sorted */ fun sort(tips: List<TipAndTrickBean>): RecommendationDescription { getUtilityExperiment()?.let { return service<TipsUsageManager>().sortTips(tips, it) } serverRecommendation?.let { return it.reorder(tips) } return randomShuffle(tips) } } enum class TipsUtilityExperiment { BY_TIP_UTILITY { override fun toString(): String = "tip_utility" }, BY_TIP_UTILITY_IGNORE_USED { override fun toString(): String = "tip_utility_and_ignore_used" }, RANDOM_IGNORE_USED { override fun toString(): String = "random_ignore_used" } } private data class TipsRequest( val tips: List<String>, val usageInfo: Map<String, ActionSummary>, val ideName: String, // product code val bucket: Int ) private class ServerRecommendation { @JvmField var showingOrder = emptyList<String>() @JvmField var usedAlgorithm = "unknown" @JvmField var version: String? = null fun reorder(tips: List<TipAndTrickBean>): RecommendationDescription { val tipToIndex = Object2IntOpenHashMap<String>(showingOrder.size) showingOrder.forEachIndexed { index, tipFile -> tipToIndex.put(tipFile, index) } for (tip in tips) { if (!tipToIndex.containsKey(tip.fileName)) { LOG.error("Unknown tips file: ${tip.fileName}") return randomShuffle(tips) } } return RecommendationDescription(usedAlgorithm, tips.sortedBy { tipToIndex.getInt(it.fileName) }, version) } }
apache-2.0
e3332f012c357daebd16ed72be07ff13
38.10828
158
0.743281
4.554154
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/renderers/PackageVersionTableCellRenderer.kt
2
3381
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers import com.intellij.icons.AllIcons import com.intellij.ui.components.JBComboBoxLabel import com.intellij.ui.components.JBLabel import com.jetbrains.packagesearch.intellij.plugin.looksLikeGradleVariable import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageOperations import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import net.miginfocom.swing.MigLayout import org.jetbrains.annotations.Nls import javax.swing.JPanel import javax.swing.JTable import javax.swing.table.TableCellRenderer internal class PackageVersionTableCellRenderer : TableCellRenderer { private var onlyStable = false fun updateData(onlyStable: Boolean) { this.onlyStable = onlyStable } override fun getTableCellRendererComponent( table: JTable, value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int ) = JPanel(MigLayout("al left center, insets 0 8 0 0")).apply { table.colors.applyTo(this, isSelected) val bgColor = if (!isSelected && value is UiPackageModel.SearchResult) { PackageSearchUI.ListRowHighlightBackground } else { background } background = bgColor val viewModel = checkNotNull(value as? UiPackageModel<*>) val labelText = when (viewModel) { is UiPackageModel.Installed -> versionMessage(viewModel.packageModel, viewModel.packageOperations) is UiPackageModel.SearchResult -> viewModel.selectedVersion.displayName } val hasVersionsToChooseFrom = viewModel.sortedVersions.isNotEmpty() val labelComponent = if (hasVersionsToChooseFrom) { JBComboBoxLabel().apply { icon = AllIcons.General.LinkDropTriangle text = labelText } } else { JBLabel().apply { text = labelText } } add( labelComponent.apply { table.colors.applyTo(this, isSelected) background = bgColor } ) } @Nls private fun versionMessage(packageModel: PackageModel.Installed, packageOperations: PackageOperations): String { val installedVersions = packageModel.usageInfo.asSequence() .map { it.version } .distinct() .sorted() .joinToString { if (looksLikeGradleVariable(it)) "[${it.displayName}]" else it.displayName } require(installedVersions.isNotBlank()) { "An installed package cannot produce an empty installed versions list" } @Suppress("HardCodedStringLiteral") // Composed of @Nls components return buildString { append(installedVersions) if (packageOperations.canUpgradePackage) { val upgradeVersion = packageOperations.targetVersion ?: return@buildString append(" โ†’ ") append(upgradeVersion.displayName) } } } }
apache-2.0
e56b2cee85033a91e778e9491dcfd818
36.966292
122
0.685114
5.23065
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/listeners/PsiActionsListener.kt
1
5144
package training.featuresSuggester.listeners import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiTreeChangeAdapter import com.intellij.psi.PsiTreeChangeEvent import training.featuresSuggester.SuggesterSupport import training.featuresSuggester.actions.* import training.featuresSuggester.handleAction class PsiActionsListener(private val project: Project) : PsiTreeChangeAdapter() { override fun beforePropertyChange(event: PsiTreeChangeEvent) { if (event.parent == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforePropertyChangedAction( psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis() ) ) } override fun beforeChildAddition(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforeChildAddedAction( psiFile = event.file!!, parent = event.parent, newChild = event.child, timeMillis = System.currentTimeMillis() ) ) } override fun beforeChildReplacement(event: PsiTreeChangeEvent) { if (event.parent == null || event.newChild == null || event.oldChild == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforeChildReplacedAction( psiFile = event.file!!, parent = event.parent, newChild = event.newChild, oldChild = event.oldChild, timeMillis = System.currentTimeMillis() ) ) } override fun beforeChildrenChange(event: PsiTreeChangeEvent) { if (event.parent == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforeChildrenChangedAction( psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis() ) ) } override fun beforeChildMovement(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || event.oldParent == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforeChildMovedAction( psiFile = event.file!!, parent = event.parent, child = event.child, oldParent = event.oldParent, timeMillis = System.currentTimeMillis() ) ) } override fun beforeChildRemoval(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return handleAction( project, BeforeChildRemovedAction( psiFile = event.file!!, parent = event.parent, child = event.child, timeMillis = System.currentTimeMillis() ) ) } override fun propertyChanged(event: PsiTreeChangeEvent) { if (event.parent == null || !isLoadedSourceFile(event.file)) return handleAction(project, PropertyChangedAction(psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis())) } override fun childRemoved(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return handleAction( project, ChildRemovedAction( psiFile = event.file!!, parent = event.parent, child = event.child, timeMillis = System.currentTimeMillis() ) ) } override fun childReplaced(event: PsiTreeChangeEvent) { if (event.parent == null || event.newChild == null || event.oldChild == null || !isLoadedSourceFile(event.file)) return handleAction( project, ChildReplacedAction( psiFile = event.file!!, parent = event.parent, newChild = event.newChild, oldChild = event.oldChild, timeMillis = System.currentTimeMillis() ) ) } override fun childAdded(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || !isLoadedSourceFile(event.file)) return handleAction( project, ChildAddedAction( psiFile = event.file!!, parent = event.parent, newChild = event.child, timeMillis = System.currentTimeMillis() ) ) } override fun childrenChanged(event: PsiTreeChangeEvent) { if (event.parent == null || !isLoadedSourceFile(event.file)) return handleAction(project, ChildrenChangedAction(psiFile = event.file!!, parent = event.parent, timeMillis = System.currentTimeMillis())) } override fun childMoved(event: PsiTreeChangeEvent) { if (event.parent == null || event.child == null || event.oldParent == null || !isLoadedSourceFile(event.file)) return handleAction( project, ChildMovedAction( psiFile = event.file!!, parent = event.parent, child = event.child, oldParent = event.oldParent, timeMillis = System.currentTimeMillis() ) ) } private fun isLoadedSourceFile(psiFile: PsiFile?): Boolean { val language = psiFile?.language ?: return false return SuggesterSupport.getForLanguage(language)?.isLoadedSourceFile(psiFile) == true } }
apache-2.0
14503bff8026ab8853b9de572e4eec28
31.556962
136
0.666991
4.798507
false
false
false
false
SJ1337/Th-Bingen
src/main/kotlin/FinalProject/Car.kt
1
522
package FinalProject /* class for a single car in the simulation */ class Car(d: Boolean, h:MutableList<Int>) { /* variables */ private val drive = d private var jammed = false private val delayed = false private val driveInHours = h /* getters / setters */ public fun getDrive(): Boolean { return drive } public fun getJammed(): Boolean { return jammed } public fun setJammed(j: Boolean) { jammed = j } public fun getDelayed(): Boolean { return delayed } }
mit
f2c15ee66ef7dda54873801356a18976
15.4
43
0.636015
3.107143
false
false
false
false
7449/Album
sample/src/main/java/com/gallery/sample/dialog/SimpleGalleryDialog.kt
1
4646
package com.gallery.sample.dialog import android.app.AlertDialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.view.* import android.view.animation.Animation import android.view.animation.TranslateAnimation import android.widget.FrameLayout import android.widget.TextView import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.LinearLayoutManager import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.gallery.compat.fragment.GalleryCompatFragment import com.gallery.compat.internal.simple.SimpleGalleryCallback import com.gallery.compat.widget.GalleryImageView import com.gallery.core.GalleryBundle import com.gallery.core.callback.IGalleryImageLoader import com.gallery.core.delegate.IScanDelegate import com.gallery.core.entity.ScanEntity import com.gallery.core.widget.GalleryRecyclerViewConfig import com.gallery.sample.R class SimpleGalleryDialog : DialogFragment(), SimpleGalleryCallback, IGalleryImageLoader { companion object { fun newInstance(): SimpleGalleryDialog { return SimpleGalleryDialog() } } override fun onStart() { super.onStart() val window = dialog?.window window ?: return val params: WindowManager.LayoutParams = window.attributes params.gravity = Gravity.BOTTOM params.width = WindowManager.LayoutParams.MATCH_PARENT params.height = WindowManager.LayoutParams.WRAP_CONTENT window.attributes = params window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) val view: View = inflater.inflate(R.layout.simple_dialog_gallery, container, false) slideToUp(view) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) childFragmentManager.findFragmentByTag(GalleryCompatFragment::class.java.simpleName)?.let { childFragmentManager.beginTransaction().show(it).commitAllowingStateLoss() } ?: childFragmentManager.beginTransaction().add(R.id.galleryFragment, GalleryCompatFragment.newInstance( GalleryBundle( radio = true, crop = false, hideCamera = true, listViewConfig = GalleryRecyclerViewConfig( 3, LinearLayoutManager.HORIZONTAL, 1 ), ) ), GalleryCompatFragment::class.java.simpleName ).commitAllowingStateLoss() } private fun slideToUp(view: View) { val slide: Animation = TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f ) slide.duration = 400 slide.fillAfter = true slide.isFillEnabled = true view.startAnimation(slide) } override fun onGalleryResource(context: Context, scanEntity: ScanEntity) { AlertDialog .Builder(requireActivity()) .setMessage(scanEntity.toString()) .show() } override fun onGalleryCreated( delegate: IScanDelegate, bundle: GalleryBundle, savedInstanceState: Bundle? ) { delegate.rootView.setBackgroundColor(Color.BLACK) } override fun onDisplayGallery( width: Int, height: Int, scanEntity: ScanEntity, container: FrameLayout, checkBox: TextView ) { container.removeAllViews() val imageView = GalleryImageView(container.context) Glide.with(container.context) .load(scanEntity.uri) .apply( RequestOptions() .centerCrop() .override(width, height) ) .into(imageView) container.addView(imageView, FrameLayout.LayoutParams(width, height)) } }
mpl-2.0
9148a362d323c58525e516593eed0f23
35.788618
99
0.624408
5.303653
false
false
false
false
rbatista/algorithms
challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/hashmaps/HashTablesRansomNote.kt
1
626
/** * https://www.hackerrank.com/challenges/ctci-ransom-note/ * * Solution in 3 * n */ package com.raphaelnegrisoli.hackerrank.hashmaps fun main(args: Array<String>) { val (_, _) = readLine().orEmpty() .split(" ") .map { it.toInt() } val magazine = readLine().orEmpty().split(" ") val note = readLine().orEmpty().split(" ") val map = magazine.groupBy { it } .mapValues { it.value.size } .toMutableMap() val match = note.all { val value = (map[it] ?: 0) - 1 map[it] = value value >= 0 } println(if (match) "Yes" else "No") }
mit
bd957e69e2f914929185266a27925b8d
19.9
58
0.539936
3.497207
false
false
false
false
spinnaker/kork
kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/telemetry/JooqSlowQueryLogger.kt
3
1554
/* * Copyright 2018 Netflix, 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.kork.sql.telemetry import java.util.concurrent.TimeUnit import org.jooq.ExecuteContext import org.jooq.impl.DefaultExecuteListener import org.jooq.tools.StopWatch import org.slf4j.LoggerFactory /** * Logs slow queries into the application log. */ class JooqSlowQueryLogger( slowQuerySecondsThreshold: Long = 1 ) : DefaultExecuteListener() { private lateinit var watch: StopWatch private val log = LoggerFactory.getLogger(javaClass) private val slowQueryThreshold = TimeUnit.SECONDS.toNanos(slowQuerySecondsThreshold) override fun executeStart(ctx: ExecuteContext) { super.executeStart(ctx) watch = StopWatch() } override fun executeEnd(ctx: ExecuteContext) { super.executeEnd(ctx) if (watch.split() > slowQueryThreshold) { log.warn("Slow SQL (${watch.splitToMillis()}ms):\n${ctx.query()}") } } private fun StopWatch.splitToMillis() = TimeUnit.NANOSECONDS.toMillis(split()) }
apache-2.0
8f3fdf8de2f0e07e33928eafbbdf0ef7
30.714286
86
0.748391
4.068063
false
false
false
false
InflationX/ViewPump
viewpump/src/main/java/io/github/inflationx/viewpump/InflateResult.kt
1
1693
package io.github.inflationx.viewpump import android.content.Context import android.util.AttributeSet import android.view.View data class InflateResult( @get:JvmName("view") val view: View? = null, @get:JvmName("name") val name: String, @get:JvmName("context") val context: Context, @get:JvmName("attrs") val attrs: AttributeSet? = null ) { fun toBuilder(): Builder { return Builder(this) } class Builder { private var view: View? = null private var name: String? = null private var context: Context? = null private var attrs: AttributeSet? = null internal constructor() internal constructor(result: InflateResult) { this.view = result.view this.name = result.name this.context = result.context this.attrs = result.attrs } fun view(view: View?) = apply { this.view = view } fun name(name: String) = apply { this.name = name } fun context(context: Context) = apply { this.context = context } fun attrs(attrs: AttributeSet?) = apply { this.attrs = attrs } fun build(): InflateResult { val finalName = checkNotNull(name) { "name == null" } return InflateResult( view = view?.also { check(finalName == it.javaClass.name) { "name ($finalName) must be the view's fully qualified name (${it.javaClass.name})" } }, name = finalName, context = context ?: throw IllegalStateException("context == null"), attrs = attrs ) } } companion object { @JvmStatic fun builder(): Builder { return Builder() } } }
apache-2.0
b62e1ca93ef8913d7baeafc6e4cdc68a
21.573333
96
0.598346
4.159705
false
false
false
false
d9n/trypp.support
src/main/code/trypp/support/math/Angle.kt
1
3990
package trypp.support.math import trypp.support.math.Angle.Companion.ofDegrees import trypp.support.math.Angle.Companion.ofRadians import trypp.support.memory.Poolable import trypp.support.opt.OptFloat /** * Simple class that represents a 0 -> 360ยฐ angle. You can set and get this angle's value in either degreesOpt or * radiansOpt. */ class Angle /** * Use [ofDegrees] or [ofRadians] instead. */ internal constructor() : Poolable { // One or both of these values are guaranteed to be set at any time. When one value is set, the other invalidated, // but when a request is made to get an unset value, it will lazily be calculated at that time. private val degreesOpt = OptFloat.of(0f) private val radiansOpt = OptFloat.of(0f) fun getDegrees(): Float { if (!degreesOpt.hasValue()) { setDegrees(radiansOpt.get() * RAD_TO_DEG) } return degreesOpt.get() } fun setDegrees(degrees: Float): Angle { var boundedDegrees = degrees % FULL_REVOLUTION_DEG while (boundedDegrees < 0f) { boundedDegrees += FULL_REVOLUTION_DEG } degreesOpt.set(boundedDegrees) radiansOpt.clear() return this } fun getRadians(): Float { if (!radiansOpt.hasValue()) { setRadians(degreesOpt.get() * DEG_TO_RAD) } return radiansOpt.get() } fun setRadians(radians: Float): Angle { var boundedRadians = radians % FULL_REVOLUTION_RAD while (boundedRadians < 0f) { boundedRadians += FULL_REVOLUTION_RAD } radiansOpt.set(boundedRadians) degreesOpt.clear() return this } fun setFrom(rhs: Angle): Angle { degreesOpt.setFrom(rhs.degreesOpt) radiansOpt.setFrom(rhs.radiansOpt) return this } fun addDegrees(degrees: Float): Angle { setDegrees(getDegrees() + degrees) return this } fun addRadians(radians: Float): Angle { setRadians(getRadians() + radians) return this } fun add(rhs: Angle): Angle { addDegrees(rhs.getDegrees()) return this } fun subDegrees(degrees: Float): Angle { setDegrees(getDegrees() - degrees) return this } fun subRadians(radians: Float): Angle { setRadians(getRadians() - radians) return this } fun sub(rhs: Angle): Angle { subDegrees(rhs.getDegrees()) return this } override fun toString(): String { return if (degreesOpt.hasValue()) "${getDegrees()}ยฐ" else "%.2f ฯ€".format(getRadians() / Angle.PI) } override fun reset() { degreesOpt.set(0f) radiansOpt.set(0f) } companion object { /** * A float version of java.lang.Math.PI */ val PI = Math.PI.toFloat() /** * Convenience constant for ฯ€/2 */ val HALF_PI = PI / 2f /** * Convenience constant for ฯ€/4 */ val QUARTER_PI = PI / 4f /** * Convenience constant for 2ฯ€ */ val TWO_PI = PI * 2f /** * Multiplying this to a value in degrees converts it to radians. */ val RAD_TO_DEG = 180f / PI /** * Multiplying this to a value in radians converts it to degrees. */ val DEG_TO_RAD = PI / 180f private val FULL_REVOLUTION_RAD = 2 * PI private val FULL_REVOLUTION_DEG = 360f fun ofDegrees(degrees: Float): Angle { val angle = Angle() angle.setDegrees(degrees) return angle } fun ofRadians(radians: Float): Angle { val angle = Angle() angle.setRadians(radians) return angle } fun of(otherAngle: Angle): Angle { val angle = Angle() angle.setFrom(otherAngle) return angle } } }
mit
7a751e9ea3b44b189417f99aba9926b9
23.592593
118
0.572289
4.171728
false
false
false
false
OpenConference/OpenConference-android
app/src/main/java/com/openconference/speakerdetails/SpeakerDetailsJobInfoAdapterDelegate.kt
1
1801
package com.openconference.speakerdetails import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import butterknife.bindView import com.hannesdorfmann.adapterdelegates2.AbsListItemAdapterDelegate import com.openconference.R import com.openconference.speakerdetails.presentationmodel.SpeakerDetailsItem import com.openconference.speakerdetails.presentationmodel.SpeakerJobInfoItem /** * * * @author Hannes Dorfmann */ class SpeakerDetailsJobInfoAdapterDelegate(val inflater: LayoutInflater) : AbsListItemAdapterDelegate<SpeakerJobInfoItem, SpeakerDetailsItem, SpeakerDetailsJobInfoAdapterDelegate.JobInfoViewHolder>() { override fun isForViewType(item: SpeakerDetailsItem, items: MutableList<SpeakerDetailsItem>?, position: Int) = item is SpeakerJobInfoItem override fun onBindViewHolder(item: SpeakerJobInfoItem, viewHolder: JobInfoViewHolder) = viewHolder.bind(item) override fun onCreateViewHolder(parent: ViewGroup) = JobInfoViewHolder( inflater.inflate(R.layout.item_speaker_details_jobinfo, parent, false)) class JobInfoViewHolder(v: View) : RecyclerView.ViewHolder(v) { val jobTitle by bindView<TextView>(R.id.jobTitle) val companyName by bindView<TextView>(R.id.company) inline fun bind(info: SpeakerJobInfoItem) { val title = info.jobTitle if (title != null) { jobTitle.text = title jobTitle.visibility = View.VISIBLE } else { jobTitle.visibility = View.GONE } val company = info.company if (company != null) { companyName.text = company companyName.visibility = View.VISIBLE } else { companyName.visibility = View.GONE } } } }
apache-2.0
1753b3bf3dbe6cc852034822b50be6cd
32.37037
201
0.758468
4.536524
false
false
false
false
VerifAPS/verifaps-lib
lang/src/main/kotlin/edu/kit/iti/formal/automation/analysis/checks.kt
1
20578
package edu.kit.iti.formal.automation.analysis import edu.kit.iti.formal.automation.IEC61131Facade import edu.kit.iti.formal.automation.analysis.ReportCategory.* import edu.kit.iti.formal.automation.analysis.ReportLevel.* import edu.kit.iti.formal.automation.datatypes.AnyDt import edu.kit.iti.formal.automation.exceptions.DataTypeNotResolvedException import edu.kit.iti.formal.automation.exceptions.VariableNotDefinedException import edu.kit.iti.formal.automation.scope.Scope import edu.kit.iti.formal.automation.st.Identifiable import edu.kit.iti.formal.automation.st.ast.* import edu.kit.iti.formal.automation.st.util.AstVisitorWithScope import edu.kit.iti.formal.util.dlevenshtein import org.antlr.v4.runtime.Token import java.lang.Throwable import kotlin.math.ceil import kotlin.math.log fun getCheckers(reporter: Reporter) = listOf(CheckForTypes(reporter), CheckForLiterals(reporter), CheckForOO(reporter)) /** * Similarity is defined via degree of levensthein of the low-case strings. * Percentage of changed characters. */ fun variableSimilarity(expected: String, defined: String): Double = dlevenshtein(expected.toLowerCase(), defined.toLowerCase()).toDouble() / expected.length fun Iterable<String>.similarCandidates(reference: String, threshold: Double = .9) = this.map { it to variableSimilarity(reference, it) } .sortedByDescending { it.second } .filter { it.second > threshold } .map { it.first } class CheckForLiterals(private val reporter: Reporter) : AstVisitorWithScope<Unit>() { override fun defaultVisit(obj: Any) {} override fun visit(literal: Literal) { when (literal) { is IntegerLit -> check(literal) is StringLit -> check(literal) is RealLit -> check(literal) is EnumLit -> check(literal) is NullLit -> check(literal) is ToDLit -> check(literal) is DateLit -> check(literal) is TimeLit -> check(literal) is DateAndTimeLit -> check(literal) is BooleanLit -> check(literal) is BitLit -> check(literal) is UnindentifiedLit -> check(literal) } } private fun check(literal: EnumLit) { val dt = literal.dataType.obj if (dt == null) { reporter.report(literal, "Could not find enumeration type '${literal.dataType.identifier}' for this literal", DATATYPE_NOT_FOUND) } else { if (literal.value !in dt.allowedValues.keys) { reporter.report(literal, "Value ${literal.value} not allowed in the enumeration type '$dt'. ", DATATYPE_NOT_FOUND) { candidates.addAll(dt.allowedValues.keys.similarCandidates(literal.value)) } } } } private fun check(literal: ToDLit) {} private fun check(literal: DateLit) { if (literal.value.month !in 1..12) { reporter.report { position(literal) message = "Month not in range" category = UNKNOWN } } if (literal.value.day !in 1..12) { reporter.report { position(literal) message = "Day not in range" category = UNKNOWN error() } } } private fun check(literal: TimeLit) {} private fun check(literal: BooleanLit) {} private fun check(literal: DateAndTimeLit) {} private fun check(literal: BitLit) { literal.dataType.obj?.also { val bits = ceil(log(literal.value.toDouble(), 2.0)) if (it.bitLength < bits) { reporter.report(literal, "Length exceeded") } } } private fun check(literal: UnindentifiedLit) { reporter.report(literal, "Unknown literal", LITERAL_UNKNOWN) } private fun check(literal: NullLit) {} private fun check(literal: RealLit) {} private fun check(literal: StringLit) { //TODO check for not defined escape characters } private fun check(literal: IntegerLit) { val value = literal.value val dt = literal.dataType(scope) if (!dt.isValid(value)) { reporter.report(literal, "The given integer literal is not in range for the specified data type: $dt", LITERAL_RANGE_EXCEEDED, WARN) } } } class CheckForTypes(private val reporter: Reporter) : AstVisitorWithScope<Unit>() { override fun defaultVisit(obj: Any) {} override fun visit(symbolicReference: SymbolicReference) { try { scope.getVariable(symbolicReference.identifier) } catch (e: VariableNotDefinedException) { val candidates = scope.allVisibleVariables.map { it.name } .similarCandidates(symbolicReference.identifier) .joinToString(", ") reporter.report(symbolicReference, "Could not find variable ${symbolicReference.identifier}. " + "Possible candidates are: $candidates", VARIABLE_NOT_RESOLVED) } } override fun visit(functionDeclaration: FunctionDeclaration) { if (!functionDeclaration.returnType.isIdentified) { reporter.report(functionDeclaration, "Return type with name '${functionDeclaration.returnType.identifier}' for function DECLARATION ${functionDeclaration.name} not found.", TYPE_RESOLVE) } super.visit(functionDeclaration) } override fun visit(invocation: InvocationStatement) { invocation.invoked ?: reporter.report(invocation, "Invocation unresolved: ${invocation.callee}.", INVOCATION_RESOLVE, WARN) if (invocation.invoked != null) { //TODO check for recursive call //reporter.report(invocation, "Invocation unresolved: ${invocation.callee}.", // INVOCATION_RESOLVE, WARN) } invocation.inputParameters.forEach { it.expression.accept(this@CheckForTypes) val dt = inferDataTypeOrNull(it.expression) val dtIn = invocation.invoked?.findInputVariable(it.name) if (dtIn == null) { reporter.report(it, "Could not resolve data type for input variable: ${it.name}.", VARIABLE_NOT_RESOLVED, ERROR) } else { if (dt != null) { if (!dt.isAssignableTo(dtIn)) { reporter.report(it, "Type mismatch ($dt <= $dtIn) for expression ${it.expression.toHuman()} and parameter ${it.name}.", VARIABLE_NOT_RESOLVED, ERROR) } } } } invocation.outputParameters.forEach { it.expression.accept(this@CheckForTypes) val ref = it.expression as? SymbolicReference if (ref == null) { reporter.report(it, "Only refs", INVOCATION_RESOLVE, WARN) } else { val dt = inferDataTypeOrNull(it.expression) val dtIn = invocation.invoked?.findInputVariable(it.name) if (dtIn == null) { reporter.report(it, "Could not resolve data type for input variable: ${it.name}.", VARIABLE_NOT_RESOLVED, ERROR) } else { if (dt != null) { if (!dt.isAssignableTo(dtIn)) { reporter.report(it, "Type mismatch ($dt <= $dtIn) for expression ${it.expression.toHuman()} and parameter ${it.name}.", VARIABLE_NOT_RESOLVED, ERROR) } } } } } } override fun visit(invocation: Invocation) { val fd = scope.resolveFunction(invocation) if (fd == null) { val invoc = IEC61131Facade.print(invocation) reporter.report(invocation, "Invocation $invoc could not resolved.", FUNCTION_RESOLVE) } else { val expectedTypes = fd.scope.variables.filter { it.isInput } val exprTypes = invocation.parameters.map { try { //val scope = invocation.invoked?.getCalleeScope()!! it.expression.dataType(scope) } catch (e: VariableNotDefinedException) { reporter.report(e.reference!!, "Variable ${e.reference.toHuman()} could not be found in scope.", VARIABLE_NOT_RESOLVED) null } catch (e: DataTypeNotResolvedException) { reporter.report(e.expr, "Datatype of ${e.expr.toHuman()} could not be derived.", TYPE_RESOLVE) null } } if (expectedTypes.size != exprTypes.size) { val invoc = IEC61131Facade.print(invocation) reporter.report(invocation, "Exptected function arguments ${expectedTypes.size}, but only ${exprTypes.size} given in function call: $invoc.", ReportCategory.FUNCTIION_ARGUMENTS_MISMATCH) } else { expectedTypes.zip(exprTypes).forEach { (vd, def) -> val exp = vd.dataType if (exp != null) { val c = def?.isAssignableTo(exp) ?: false if (!c) { reporter.report(invocation, "Type mismatch for argument ${vd.name}: exptected ${exp} but got ${def}", ReportCategory.FUNCTION_CALL_TYPE_MISMATCH) } } } } } } override fun visit(variableDeclaration: VariableDeclaration) { variableDeclaration.initValue ?: reporter.report(variableDeclaration.token, "Could not determine initial value for variable: ${variableDeclaration.name} with ${variableDeclaration.typeDeclaration.toHuman()}", ReportCategory.INIT_VALUE) variableDeclaration.dataType ?: reporter.report(variableDeclaration.token, "Could not determine data type of variable: ${variableDeclaration.name} with ${variableDeclaration.typeDeclaration.toHuman()}", ReportCategory.TYPE_RESOLVE) } override fun visit(assignmentStatement: AssignmentStatement) { assignmentStatement.expression.accept(this) try { val vd = scope.getVariable(assignmentStatement.location) if (vd.isInput || vd.isConstant) { reporter.report(assignmentStatement.location, "Variable not writable", PERMISSION, WARN) } } catch (e: VariableNotDefinedException) { reporter.report(assignmentStatement.location, "Could not resolve ${assignmentStatement.location.toHuman()}.", VARIABLE_NOT_RESOLVED) } val lhsType = inferDataTypeOrNull(assignmentStatement.location, scope) val rhsType = inferDataTypeOrNull(assignmentStatement.expression, scope) if (lhsType != null && rhsType != null) { if (!rhsType.isAssignableTo(lhsType)) { reporter.report(assignmentStatement, "Assignment type conflict between $rhsType and $lhsType", ASSIGNMENT_TYPE_CONFLICT) } } } override fun visit(forStatement: ForStatement) { super.visit(forStatement) } private fun inferDataTypeOrNull(expr: Expression, s: Scope = scope): AnyDt? { return try { expr.dataType(s) } catch (e: VariableNotDefinedException) { reporter.report(e.reference!!, "Could not resolve variable: ${e.reference.toHuman()}", VARIABLE_NOT_RESOLVED) null } catch (e: DataTypeNotResolvedException) { reporter.report(expr, e.message!!, INFER) null } } } private fun Invoked?.findInputVariable(name: String?): AnyDt? { return if (name == null) null else when (this) { is Invoked.Program -> this.program.scope.variables[name]?.dataType is Invoked.FunctionBlock -> this.fb.scope.variables[name]?.dataType is Invoked.Function -> this.function.scope.variables[name]?.dataType is Invoked.Method -> this.method.scope.variables[name]?.dataType is Invoked.Action -> null null -> null } } class CheckForOO(private val reporter: Reporter) : AstVisitorWithScope<Unit>() { private var clazz: ClassDeclaration? = null private var interfaze: InterfaceDeclaration? = null override fun defaultVisit(obj: Any) {} override fun visit(interfaceDeclaration: InterfaceDeclaration) { interfaze = interfaceDeclaration interfaceDeclaration.interfaces.forEach { it.obj ?: reporter.report(interfaceDeclaration, "Could not resolve interface ${it.identifier}.", ReportCategory.INTERFACE_NOT_RESOLVED) } } override fun visit(clazz: ClassDeclaration) { this.clazz = clazz clazz.interfaces.forEach { it.obj ?: reporter.report(clazz, "Could not resolve interface ${it.identifier}.", ReportCategory.INTERFACE_NOT_RESOLVED) } if (clazz.parent.obj == null && clazz.parent.identifier != null) reporter.report(clazz, "Could not resolve parent class ${clazz.parent.identifier}.", ReportCategory.CLASS_NOT_RESOLVED) val declM = clazz.declaredMethods val defM = clazz.definedMethods for ((where, declared) in declM) { if (!defM.any { it.second sameSignature declared }) { reporter.report(clazz, "Declared method ${declared.toHuman()} in ${where.toHuman()} " + "is not defined in ${clazz.toHuman()}.", ReportCategory.METHOD_NOT_DEFINED, ERROR) } } } override fun visit(method: MethodDeclaration) { if (method.isOverride && method.overrides == null) { val candidates = (if (clazz != null) (clazz!!.declaredMethods + clazz!!.definedMethods) else interfaze!!.definedMethods) .filter { (_, m) -> m.name == method.name } .joinToString { (w, m) -> "${w.name}.${m.name}" } reporter.report(method, "Method is declared as override, but does not override any method. Candidates are: $candidates") } if (method.isAbstract && !method.stBody.isEmpty()) { reporter.report(method, "Abstract method has a body.", ReportCategory.METHOD_HAS_BODY) } } /*override fun visit(method: MethodDeclaration) { method.parent = get() //search for overrides if (method.isOverride) { val sm = getSuperMethods() for ((where, cand) in sm) { if (method sameSignature cand) { method.overrides = where to cand break } } } } private fun getSuperMethods(): List<Pair<HasMethods, MethodDeclaration>> { return when { clazz != null -> clazz!!.declaredMethods + clazz!!.definedMethods interfaze != null -> interfaze!!.definedMethods functionBlock != null -> TODO() else -> listOf() } }*/ } enum class ReportCategory { UNKNOWN, INFER, DATATYPE_NOT_FOUND, LITERAL_UNKNOWN, LITERAL_RANGE_EXCEEDED, VARIABLE_NOT_RESOLVED, INVOCATION_RESOLVE, TYPE_RESOLVE, DECLARATION, FUNCTION_RESOLVE, FUNCTIION_ARGUMENTS_MISMATCH, FUNCTION_CALL_TYPE_MISMATCH, INIT_VALUE, PERMISSION, METHOD_NOT_DEFINED, ASSIGNMENT_TYPE_CONFLICT, INTERFACE_NOT_RESOLVED, CLASS_NOT_RESOLVED, METHOD_HAS_BODY, SYNTAX } enum class ReportLevel { INFO, WARN, ERROR } /** * */ fun Any?.toHuman(): String = when (this) { null -> "null" is SymbolicReference -> IEC61131Facade.print(this) is ClassDeclaration -> "class '$name'" is InterfaceDeclaration -> "interface '$name'" is MethodDeclaration -> "method '${parent?.name}.$name'" is Identifiable -> this.name else -> toString() } class Reporter(val messages: MutableList<ReporterMessage> = ArrayList()) { fun getCaller(): String { val stackTrace = Throwable().stackTrace val firstNonReporterEntry = stackTrace.find { !it.className.startsWith(javaClass.name) } val caller = firstNonReporterEntry return if (caller == null) "" else caller.toString() } fun report(e: ReporterMessage) { messages += e } fun report(init: ReporterMessage.() -> Unit): ReporterMessage { val rm = ReporterMessage() init(rm) report(rm) return rm } fun report(node: Top?, msg: String, cat: ReportCategory = UNKNOWN, lvl: ReportLevel = ERROR, init: ReporterMessage.() -> Unit = {}) = report { position(node) message = msg category = cat level = lvl checkerId = getCaller() init(this) } fun report(node: Token?, msg: String, cat: ReportCategory, lvl: ReportLevel = ERROR, init: ReporterMessage.() -> Unit = {}) = report { position(node) message = msg category = cat level = lvl checkerId = getCaller() init(this) } } data class ReporterMessage( var sourceName: String = "", var message: String = "", var start: Position = Position(), var end: Position = Position(), var category: ReportCategory = UNKNOWN, var level: ReportLevel = ERROR, var candidates: MutableList<String> = arrayListOf(), var checkerId: String = "") { val length: Int get() = end.offset - start.offset + 1 val startLine get() = start.lineNumber val endLine get() = end.lineNumber val startOffsetInLine get() = start.charInLine val endOffsetInLine get() = end.charInLine val startOffset get() = start.offset val endOffset get() = end.offset fun toHuman() = "[$level] $sourceName:$startLine:$startOffsetInLine $message [$category] ($checkerId)" fun toJson() = toMap().toJson() fun toMap() = mapOf("level" to level, "file" to sourceName, "startLine" to startLine, "startOffsetInLine" to startOffsetInLine, "endLine" to endLine, "endOffsetInLine" to endOffsetInLine, "message" to message, "checkerId" to checkerId, "category" to category) fun position(node: Token?) { sourceName = node?.tokenSource?.sourceName ?: "" if (node != null) { start = Position.start(node) end = Position.end(node) } } fun position(node: Top?) { sourceName = node?.ruleContext?.start?.tokenSource?.sourceName ?: "" if (node != null) { start = node.startPosition end = node.endPosition } } fun error() { level = ERROR } fun warn() { level = WARN } fun info() { level = INFO } } fun <V> Map<String, V>.toJson(): String = this.entries.joinToString(", ", "{", "}") { (k, v) -> val a = when (v) { is String -> "\"${v.replace("\"", "\\\"")}\"" else -> v.toString() } "\"$k\" : $a" }
gpl-3.0
5f1e1f7681330202ec61b10ab653052f
34.665511
156
0.559967
4.795619
false
false
false
false
fobo66/BookcrossingMobile
app/src/main/java/com/bookcrossing/mobile/util/Constants.kt
1
1134
/* * Copyright 2019 Andrey Mukamolov * * 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.bookcrossing.mobile.util const val RC_SIGN_IN = 1236 const val EXTRA_KEY = "key" const val PACKAGE_NAME = "com.bookcrossing.mobile" const val DEFAULT_USER = "user" const val EXTRA_COORDINATES = "coordinates" const val EXTRA_TARGET_FRAGMENT = "targetFragment" const val KEY_CONSENT_STATUS = "consent_status" const val UNKNOWN_CONSENT_STATUS = "UNKNOWN" const val PRIVACY_POLICY_URL = "https://fobo66.github.io/BookcrossingMobile/privacy_policy.html" const val DEFAULT_DEBOUNCE_TIMEOUT = 300
apache-2.0
944305bf9d0eacfe97388546e4635196
38.137931
96
0.738095
3.844068
false
false
false
false
nsnikhil/Notes
app/src/main/java/com/nrs/nsnik/notes/util/AppUtil.kt
1
3464
/* * Notes Copyright (C) 2018 Nikhil Soni * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.nrs.nsnik.notes.util import android.app.Activity import android.content.res.ColorStateList import android.graphics.Color import androidx.navigation.findNavController import com.nrs.nsnik.notes.MyApplication import com.nrs.nsnik.notes.R import com.nrs.nsnik.notes.view.fragments.NewNoteFragment import java.util.* class AppUtil { companion object { fun stateList(colorString: String?): ColorStateList { val states = arrayOf(intArrayOf(android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_enabled), intArrayOf(-android.R.attr.state_checked), intArrayOf(android.R.attr.state_pressed)) val color = Color.parseColor(colorString) val colors = intArrayOf(color, color, color, color) return ColorStateList(states, colors) } fun goToIntro(activity: Activity?) { val sharedPreferences = (activity?.applicationContext as MyApplication).sharedPreferences val isWatched = sharedPreferences.getBoolean(activity.resources.getString(R.string.bundleIntroWatched), false) if (!isWatched) activity.findNavController(R.id.mainNavHost).navigate(R.id.introFragment) } fun saveIsVisitedIntro(activity: Activity?) { val sharedPreferences = (activity?.applicationContext as MyApplication).sharedPreferences sharedPreferences.edit().putBoolean(activity.resources.getString(R.string.bundleIntroWatched), true).apply() } fun getTimeDifference(diff: Long): String { val seconds = diff / 1000 if (seconds < 60) return "$seconds sec ago" val minutes = seconds / 60 if (minutes < 60) return "$minutes min ago" val hours = minutes / 60 return "$hours hrs ago" } fun makeName(type: NewNoteFragment.FILE_TYPES): String { return when (type) { NewNoteFragment.FILE_TYPES.TEXT -> Calendar.getInstance().timeInMillis.toString() + ".txt" NewNoteFragment.FILE_TYPES.IMAGE -> Calendar.getInstance().timeInMillis.toString() + ".jpg" NewNoteFragment.FILE_TYPES.AUDIO -> Calendar.getInstance().timeInMillis.toString() + ".3gp" } } } }
gpl-3.0
987dcf215e02e0cf382440a8783205d1
44.592105
202
0.69082
4.390368
false
false
false
false
lice-lang/lice
src/main/kotlin/org/lice/api/scripting/LiceScriptEngine.kt
1
1421
package org.lice.api.scripting import org.lice.Lice import org.lice.core.SymbolList import org.lice.util.cast import java.io.Reader import javax.script.* /** * Created by Glavo on 17-6-8. * * @author Glavo * @since 0.1.0 */ class LiceScriptEngine : ScriptEngine { private var context: LiceContext = LiceContext() override fun getContext() = context override fun setContext(context: ScriptContext) { if (context is LiceContext) this.context = context } override fun getFactory() = LiceScriptEngineFactory() override fun eval(script: String, context: ScriptContext) = eval(script, (context as LiceContext).bindings) override fun eval(script: String) = eval(script, context.bindings) override fun eval(reader: Reader) = eval(reader.readText(), context.bindings) override fun eval(reader: Reader, n: Bindings) = eval(reader.readText(), n) override fun eval(reader: Reader, context: ScriptContext) = eval(reader.readText(), (context as LiceContext).bindings) override fun eval(script: String, n: Bindings) = Lice.run(script, cast(n)) override fun get(key: String?): Any? = context.bindings[key] override fun put(key: String, value: Any?) { context.bindings[key] = value } override fun createBindings() = SymbolList() override fun getBindings(scope: Int) = context.bindings override fun setBindings(bindings: Bindings?, scope: Int) { if (bindings is SymbolList) context.bindings = bindings } }
gpl-3.0
8055a561f0f095cf6416a42d9149b39e
35.435897
119
0.744546
3.517327
false
false
false
false
coil-kt/coil
coil-base/src/main/java/coil/util/Requests.kt
1
1832
@file:JvmName("-Requests") package coil.util import android.graphics.drawable.Drawable import android.widget.ImageView import androidx.annotation.DrawableRes import coil.request.DefaultRequestOptions import coil.request.ImageRequest import coil.size.DisplaySizeResolver import coil.size.Precision import coil.size.ViewSizeResolver import coil.target.ViewTarget internal val DEFAULT_REQUEST_OPTIONS = DefaultRequestOptions() /** * Used to resolve [ImageRequest.placeholder], [ImageRequest.error], and [ImageRequest.fallback]. */ internal fun ImageRequest.getDrawableCompat( drawable: Drawable?, @DrawableRes resId: Int?, default: Drawable? ): Drawable? = when { drawable != null -> drawable resId != null -> if (resId == 0) null else context.getDrawableCompat(resId) else -> default } /** * Return 'true' if the request does not require the output image's size to match the * requested dimensions exactly. */ internal val ImageRequest.allowInexactSize: Boolean get() = when (precision) { Precision.EXACT -> false Precision.INEXACT -> true Precision.AUTOMATIC -> run { // If we haven't explicitly set a size and fell back to the default size resolver, // always allow inexact size. if (defined.sizeResolver == null && sizeResolver is DisplaySizeResolver) { return@run true } // If both our target and size resolver reference the same ImageView, allow the // dimensions to be inexact as the ImageView will scale the output image // automatically. Else, require the dimensions to be exact. return@run target is ViewTarget<*> && sizeResolver is ViewSizeResolver<*> && target.view is ImageView && target.view === sizeResolver.view } }
apache-2.0
49d78991e8ac34c03caf717113be7df2
34.921569
97
0.692686
4.770833
false
false
false
false
luxons/seven-wonders
sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/gameBrowser/GameList.kt
1
3554
package org.luxons.sevenwonders.ui.components.gameBrowser import com.palantir.blueprintjs.Intent import com.palantir.blueprintjs.bpButton import com.palantir.blueprintjs.bpHtmlTable import com.palantir.blueprintjs.bpIcon import com.palantir.blueprintjs.bpTag import kotlinx.css.* import kotlinx.html.title import org.luxons.sevenwonders.model.api.ConnectedPlayer import org.luxons.sevenwonders.model.api.LobbyDTO import org.luxons.sevenwonders.model.api.State import org.luxons.sevenwonders.ui.redux.RequestJoinGame import org.luxons.sevenwonders.ui.redux.connectStateAndDispatch import react.RBuilder import react.RComponent import react.RProps import react.RState import react.dom.* import styled.css import styled.styledDiv import styled.styledSpan import styled.styledTr interface GameListStateProps : RProps { var connectedPlayer: ConnectedPlayer var games: List<LobbyDTO> } interface GameListDispatchProps : RProps { var joinGame: (Long) -> Unit } interface GameListProps : GameListStateProps, GameListDispatchProps class GameListPresenter(props: GameListProps) : RComponent<GameListProps, RState>(props) { override fun RBuilder.render() { bpHtmlTable { thead { gameListHeaderRow() } tbody { props.games.forEach { gameListItemRow(it) } } } } private fun RBuilder.gameListHeaderRow() = tr { th { +"Name" } th { +"Status" } th { +"Nb Players" } th { +"Join" } } private fun RBuilder.gameListItemRow(lobby: LobbyDTO) = styledTr { css { verticalAlign = VerticalAlign.middle } attrs { key = lobby.id.toString() } td { +lobby.name } td { gameStatus(lobby.state) } td { playerCount(lobby.players.size) } td { joinButton(lobby) } } private fun RBuilder.gameStatus(state: State) { val intent = when (state) { State.LOBBY -> Intent.SUCCESS State.PLAYING -> Intent.WARNING State.FINISHED -> Intent.DANGER } bpTag(minimal = true, intent = intent) { +state.toString() } } private fun RBuilder.playerCount(nPlayers: Int) { styledDiv { css { display = Display.flex flexDirection = FlexDirection.row alignItems = Align.center } attrs { title = "Number of players" } bpIcon(name = "people", title = null) styledSpan { +nPlayers.toString() } } } private fun RBuilder.joinButton(lobby: LobbyDTO) { val joinability = lobby.joinability(props.connectedPlayer.displayName) bpButton( minimal = true, title = joinability.tooltip, icon = "arrow-right", disabled = !joinability.canDo, onClick = { props.joinGame(lobby.id) }, ) } } fun RBuilder.gameList() = gameList {} private val gameList = connectStateAndDispatch<GameListStateProps, GameListDispatchProps, GameListProps>( clazz = GameListPresenter::class, mapStateToProps = { state, _ -> connectedPlayer = state.connectedPlayer ?: error("there should be a connected player") games = state.games }, mapDispatchToProps = { dispatch, _ -> joinGame = { gameId -> dispatch(RequestJoinGame(gameId = gameId)) } }, )
mit
0de83a60ec28bae471aec9b77aaf2bb8
28.131148
105
0.619865
4.420398
false
false
false
false
LorittaBot/Loritta
web/dashboard/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/backend/routes/RequiresDiscordLoginRoute.kt
1
3286
package net.perfectdreams.loritta.cinnamon.dashboard.backend.routes import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.sessions.* import mu.KotlinLogging import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.cinnamon.dashboard.backend.LorittaDashboardBackend import net.perfectdreams.loritta.cinnamon.dashboard.backend.utils.LorittaJsonWebSession import net.perfectdreams.loritta.cinnamon.dashboard.backend.utils.LorittaWebSession import net.perfectdreams.loritta.cinnamon.dashboard.backend.utils.TemmieDiscordAuth import net.perfectdreams.loritta.cinnamon.dashboard.backend.utils.lorittaSession abstract class RequiresDiscordLoginRoute(m: LorittaDashboardBackend, path: String) : LocalizedRoute(m, path) { companion object { private val logger = KotlinLogging.logger {} } abstract suspend fun onAuthenticatedRequest( call: ApplicationCall, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification ) override suspend fun onLocalizedRequest(call: ApplicationCall, i18nContext: I18nContext) { if (m.config.userAuthenticationOverride.enabled) { onAuthenticatedRequest( call, TemmieDiscordAuth("dummy", "dummy", "dummy", "dummy", listOf()), LorittaJsonWebSession.UserIdentification( m.config.userAuthenticationOverride.id.toString(), m.config.userAuthenticationOverride.name, m.config.userAuthenticationOverride.discriminator, true, "[email protected]", m.config.userAuthenticationOverride.avatarId, System.currentTimeMillis(), System.currentTimeMillis() ) ) } else { // TODO: Fix and improve val session = call.lorittaSession val webSession = LorittaWebSession(m, session) val discordAuth = webSession.getDiscordAuthFromJson() val userIdentification = LorittaWebSession(m, session).getUserIdentification(call, true) if (discordAuth == null || userIdentification == null) { logger.info { "Clearing any set sessions and redirecting request to unauthorized redirect URL... Json Web Session? $session; Is Discord Auth null? ${discordAuth == null}; Is User Identification null? ${userIdentification == null}" } call.sessions.clear<LorittaJsonWebSession>() call.respondRedirect(m.config.unauthorizedRedirectUrl) return } // TODO: Check if user is banned /* val profile = com.mrpowergamerbr.loritta.utils.loritta.getOrCreateLorittaProfile(userIdentification.id) val bannedState = profile.getBannedState() if (bannedState != null) throw WebsiteAPIException( HttpStatusCode.Unauthorized, WebsiteUtils.createErrorPayload( LoriWebCode.BANNED, "You are Loritta Banned!" ) ) */ onAuthenticatedRequest(call, discordAuth, userIdentification) } } }
agpl-3.0
35d26b34a1120b525e416938a4bc69e5
45.295775
248
0.664942
5.386885
false
true
false
false
skydoves/WaterDrink
app/src/main/java/com/skydoves/waterdays/ui/activities/settings/NFCActivity.kt
1
4445
/* * Copyright (C) 2016 skydoves * * 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.skydoves.waterdays.ui.activities.settings import android.app.PendingIntent import android.content.Intent import android.content.IntentFilter import android.nfc.NdefMessage import android.nfc.NdefRecord import android.nfc.NfcAdapter import android.nfc.Tag import android.nfc.tech.Ndef import android.nfc.tech.NdefFormatable import android.os.Bundle import android.provider.Settings import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.skydoves.waterdays.R import kotlinx.android.synthetic.main.activity_nfc.* import java.io.IOException /** * Created by skydoves on 2016-10-15. * Updated by skydoves on 2017-08-17. * Copyright (c) 2017 skydoves rights reserved. */ class NFCActivity : AppCompatActivity() { private var mWriteMode = false private var mNfcAdapter: NfcAdapter? = null private var mNfcPendingIntent: PendingIntent? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_nfc) nfc_sticker.startRippleAnimation() nfc_btn_setnfcdata.setOnClickListener { if (CheckNFCEnabled()) { mNfcAdapter = NfcAdapter.getDefaultAdapter(this) mNfcPendingIntent = PendingIntent.getActivity(this, 0, Intent(this, NFCActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0) enableTagWriteMode() nfc_sticker.visibility = View.VISIBLE } else { val setnfc = Intent(Settings.ACTION_NFC_SETTINGS) startActivity(setnfc) Toast.makeText(this, getString(R.string.msg_require_nfc), Toast.LENGTH_SHORT).show() } } } private fun CheckNFCEnabled(): Boolean { val nfcAdpt = NfcAdapter.getDefaultAdapter(this) if (nfcAdpt != null) { if (!nfcAdpt.isEnabled) return false } return true } private fun enableTagWriteMode() { mWriteMode = true val tagDetected = IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED) val mWriteTagFilters = arrayOf(tagDetected) mNfcAdapter!!.enableForegroundDispatch(this, mNfcPendingIntent, mWriteTagFilters, null) } private fun disableTagWriteMode() { mWriteMode = false } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) if (mWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED == intent.action) { val detectedTag = intent.getParcelableExtra<Tag>(NfcAdapter.EXTRA_TAG) val record = NdefRecord.createMime("waterdays_nfc/NFC", nfc_edt01.text.toString().toByteArray()) val message = NdefMessage(arrayOf(record)) // detected tag if (writeTag(message, detectedTag)) { disableTagWriteMode() nfc_sticker.visibility = View.INVISIBLE Toast.makeText(this, "NFC ํƒœ๊ทธ์— ๋ฐ์ดํ„ฐ๋ฅผ ์ž‘์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show() } } } fun writeTag(message: NdefMessage, tag: Tag): Boolean { val size = message.toByteArray().size try { val ndef = Ndef.get(tag) if (ndef != null) { ndef.connect() if (!ndef.isWritable) { Toast.makeText(applicationContext, "ํƒœ๊ทธ์— ๋ฐ์ดํ„ฐ๋ฅผ ์ž‘์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show() return false } if (ndef.maxSize < size) { Toast.makeText(applicationContext, "ํƒœ๊ทธ ์‚ฌ์ด์ฆˆ๊ฐ€ ๋„ˆ๋ฌด ์ž‘์Šต๋‹ˆ๋‹ค.", Toast.LENGTH_SHORT).show() return false } ndef.writeNdefMessage(message) return true } else { val format = NdefFormatable.get(tag) return if (format != null) { try { format.connect() format.format(message) true } catch (e: IOException) { false } } else { false } } } catch (e: Exception) { return false } } }
apache-2.0
688f21e53f86748038084f649cc0c0b4
29.957447
146
0.684078
4.052925
false
false
false
false
DevCharly/kotlin-ant-dsl
generator/src/main/kotlin/com/devcharly/kotlin/ant/generator/reflect.kt
1
5894
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant.generator import org.apache.tools.ant.IntrospectionHelper import org.apache.tools.ant.Project import org.apache.tools.ant.ProjectComponent import org.apache.tools.ant.types.EnumeratedAttribute import java.lang.reflect.Method import java.util.* val tasks = HashMap<Class<*>, Task>() fun getTask(taskType: Class<*>): Task { return tasks[taskType] ?: reflectTask(taskType) } fun reflectTask(taskType: Class<*>, taskName: String? = null, funName: String? = null, order: String? = null, exclude: String? = null): Task { val aClass = aClass(taskType) // determine whether have to pass project to constructor var hasConstructor = false var projectAtConstructor = false try { taskType.getConstructor() hasConstructor = true } catch (ex: NoSuchMethodException) { try { taskType.getConstructor(Project::class.java) hasConstructor = true projectAtConstructor = true } catch (ex: NoSuchMethodException) { // ignore } } // use Ant IntrospectionHelper val ih = IntrospectionHelper.getHelper(taskType) // parameters (Ant attributes) val params = ArrayList<TaskParam>() for (it in ih.attributeMap) { var paramName = it.key var paramType = it.value var constructWithProject = false var paramMethod = ih.getAttributeMethod(paramName) // avoid reserved names in parameters paramName = unreserved(paramName) // some Ant attributes have two setters: one take String and another that take Object if (paramType == java.lang.Object::class.java) { try { // change Object to String paramMethod = taskType.getMethod(paramMethod.name, java.lang.String::class.java) paramType = java.lang.String::class.java } catch (ex: NoSuchMethodException) { // ignore } } // ignore unsupported types if (paramType.name.contains('.') && paramType != java.lang.String::class.java && paramType != java.io.File::class.java) { try { paramType.getConstructor(Project::class.java, java.lang.String::class.java) constructWithProject = true } catch (ex: NoSuchMethodException) { try { paramType.getConstructor(java.lang.String::class.java) } catch (ex: NoSuchMethodException) { if (!EnumeratedAttribute::class.java.isAssignableFrom(paramType) && !paramType.isEnum) { println("Unsupported type in $paramName\n\t<${paramType.name}>\n\t(${taskType.name})") continue // not supported parameter type } } } } params.add(TaskParam(paramName, paramType, paramMethod, constructWithProject)) } // remove deprecated attributes params.removeIf { aClass.deprecatedMethods.contains(it.method) } // always exclude some attributes params.removeIf { it.name == "refid" || it.name == "srcresource" } if (ProjectComponent::class.java.isAssignableFrom(taskType)) params.removeIf { it.name == "description" } if (org.apache.tools.ant.Task::class.java.isAssignableFrom(taskType)) params.removeIf { it.name == "taskname" } if (exclude != null) { val excludeList = exclude.split(' ') params.removeIf { excludeList.contains(it.name) } } // same order as in source code params.sortBy { aClass.orderedMethods[it.method] } // order attributes if (order != null) { val orderList = order.split(' ') params.sortBy { val orderIndex = orderList.indexOf(it.name) if (orderIndex >= 0) orderIndex else orderList.size + params.indexOfFirst { param -> it.name == param.name } } } // add type/text methods val addTypeMethods = ih.extensionPoints.sortedBy { it.parameterTypes[0].simpleName }.toTypedArray() val addTextMethod = if (ih.supportsCharacters()) ih.addTextMethod else null // nested val nested = ArrayList<TaskNested>() ih.nestedElementMap.forEach { if (it.key in unsupportedNested) return@forEach val em = ih.getElementMethod(it.key) nested.add(TaskNested(it.key, it.value, em)) } // same order as in source code nested.sortBy { aClass.orderedMethods[it.method] } val task = Task(taskType, taskName ?: taskType.simpleName.toLowerCase(), funName ?: taskType.simpleName.toLowerCase(), taskName?.capitalize() ?: taskType.simpleName, hasConstructor, projectAtConstructor, params.toTypedArray(), nested.toTypedArray(), addTypeMethods, addTextMethod) tasks[taskType] = task return task } fun unreserved(s: String) = if (s in arrayOf("class", "if", "package", "when")) s.capitalize() else s //---- class Task ------------------------------------------------------------- class Task(val type: Class<*>, val taskName: String, val funName: String, var nestedClassName: String, val hasConstructor: Boolean, val projectAtConstructor: Boolean, val params: Array<TaskParam>, val nested: Array<TaskNested>, val addTypeMethods: Array<Method>, val addTextMethod: Method?) { var baseInterface: Class<*>? = null val hasNested = !nested.isEmpty() || !addTypeMethods.isEmpty() || addTextMethod != null } //---- class TaskParam -------------------------------------------------------- class TaskParam(val name: String, val type: Class<*>, val method: Method, val constructWithProject: Boolean) //---- class TaskNested ------------------------------------------------------- class TaskNested(val name: String, val type: Class<*>, val method: Method)
apache-2.0
7e733914a16a5498d4ba95c2d5282d6f
31.032609
108
0.692399
3.778205
false
false
false
false
Muks14x/susi_android
app/src/androidTest/java/org/fossasia/susi/ai/ForgetPassTest.kt
1
3189
package org.fossasia.susi.ai import android.support.design.widget.TextInputEditText import android.support.design.widget.TextInputLayout import android.support.test.InstrumentationRegistry import android.support.test.espresso.Espresso.* import android.support.test.espresso.action.ViewActions.* import android.support.test.espresso.assertion.ViewAssertions import android.support.test.espresso.matcher.ViewMatchers.* import android.support.test.filters.MediumTest import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import android.util.Log import android.view.WindowManager import org.fossasia.susi.ai.forgotpassword.ForgotPasswordActivity import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Created by mayanktripathi on 18/07/17. */ @RunWith(AndroidJUnit4::class) @MediumTest class ForgetPassTest { @Rule @JvmField val mActivityRule = ActivityTestRule(ForgotPasswordActivity::class.java) @Before fun unlockScreen() { val activity = mActivityRule.activity val wakeUpDevice = Runnable { activity.window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } activity.runOnUiThread(wakeUpDevice) } @Test fun testUIViewsPresenceOnLoad() { Log.d(ForgetPassTest.TAG, "running testUIViewsPresenceOnLoad..") // checks if email input field is present onView(withId(R.id.forgot_email)).check(ViewAssertions.matches(isDisplayed())) // checks if reset button is present onView(withId(R.id.reset_button)).check(ViewAssertions.matches(isDisplayed())) //checks if checkbox present onView(withId(R.id.customer_server)).check(ViewAssertions.matches(isDisplayed())) } @Test fun testReset() { Log.d(ForgetPassTest.TAG, "running resetPassword test..") val emailInput = (mActivityRule.activity.findViewById(R.id.forgot_email) as TextInputLayout).editText as TextInputEditText? InstrumentationRegistry.getInstrumentation().runOnMainSync { emailInput!!.setText("[email protected]") } onView(withId(R.id.reset_button)).perform(click()) } @Test fun testPersonalServer() { Log.d(ForgetPassTest.TAG, "running resetPassword test on personal server..") val emailInput = (mActivityRule.activity.findViewById(R.id.forgot_email) as TextInputLayout).editText as TextInputEditText? InstrumentationRegistry.getInstrumentation().runOnMainSync { emailInput!!.setText("[email protected]") } onView(withId(R.id.customer_server)).perform(click()) val serverInput = (mActivityRule.activity.findViewById(R.id.input_url) as TextInputLayout).editText as TextInputEditText? InstrumentationRegistry.getInstrumentation().runOnMainSync { serverInput!!.setText("http://104.198.32.176/") } onView(withId(R.id.reset_button)).perform(click()) } companion object { private val TAG = "ForgetPassTest" } }
apache-2.0
26c3256b66392c8da139b7bdf3862992
34.831461
131
0.734086
4.398621
false
true
false
false