content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.reactnativenavigation.utils import com.reactnativenavigation.BaseTest import com.reactnativenavigation.views.stack.topbar.titlebar.DEFAULT_LEFT_MARGIN_PX import com.reactnativenavigation.views.stack.topbar.titlebar.resolveLeftButtonsBounds import com.reactnativenavigation.views.stack.topbar.titlebar.resolveRightButtonsBounds import com.reactnativenavigation.views.stack.topbar.titlebar.resolveHorizontalTitleBoundsLimit import org.junit.Test import kotlin.test.assertEquals class TitleAndButtonsMeasurer : BaseTest() { private val parentWidth = 1080 @Test fun `left buttons should be at parent start`() { val barWidth = 200 val isRTL = false val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(barWidth, right) } @Test fun `left buttons should not exceed parent width`() { val barWidth = parentWidth + 1 val isRTL = false val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(parentWidth, right) } @Test fun `RTL - left buttons should be at parent end`() { val barWidth = 200 val isRTL = true val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(parentWidth - barWidth, left) assertEquals(parentWidth, right) } @Test fun `RTL - left buttons should not exceed parent left`() { val barWidth = parentWidth + 1 val isRTL = true val (left, right) = resolveLeftButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(parentWidth, right) } @Test fun `right buttons should be at parent end`() { val barWidth = 200 val isRTL = false val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(parentWidth - barWidth, left) assertEquals(parentWidth, right) } @Test fun `right buttons should not exceed parent start`() { val barWidth = parentWidth + 1 val isRTL = false val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(parentWidth, right) } @Test fun `RTL - right buttons should be at parent start`() { val barWidth = 200 val isRTL = true val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(barWidth, right) } @Test fun `RTL - right buttons should not exceed parent end`() { val barWidth = parentWidth + 1 val isRTL = true val (left, right) = resolveRightButtonsBounds(parentWidth, barWidth, isRTL) assertEquals(0, left) assertEquals(parentWidth, right) } @Test fun `No Buttons - Aligned start - Title should be at default left margin bar width and right margin`() { val barWidth = 200 val leftButtons = 0 val rightButtons = 0 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(DEFAULT_LEFT_MARGIN_PX, left) assertEquals(DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `RTL - No Buttons - Aligned start - Title should be at the end with default margins`() { val barWidth = 200 val leftButtons = 0 val rightButtons = 0 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - barWidth - DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `RTL - No Buttons - Aligned start - Title should not exceed boundaries`() { val barWidth = parentWidth + 1 val leftButtons = 0 val rightButtons = 0 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `No Buttons - Aligned start - Title should not exceed parent boundaries`() { val barWidth = parentWidth + 1 val leftButtons = 0 val rightButtons = 0 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `No Buttons - Aligned center - Title should not exceed parent boundaries`() { val barWidth = parentWidth + 1 val leftButtons = 0 val rightButtons = 0 val isRTL = false val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(0, left) assertEquals(parentWidth, right) } @Test fun `No Buttons - Aligned center - Title should have no margin and in center`() { val barWidth = 200 val leftButtons = 0 val rightButtons = 0 val isRTL = false val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth / 2 - barWidth / 2, left) assertEquals(parentWidth / 2 + barWidth / 2, right) } @Test fun `RTL - No Buttons - Aligned center - Title should have no effect`() { val barWidth = 200 val leftButtons = 0 val rightButtons = 0 val isRTL = true val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth / 2 - barWidth / 2, left) assertEquals(parentWidth / 2 + barWidth / 2, right) } @Test fun `Left Buttons - Aligned start - Title should be after left buttons with default margins`() { val barWidth = 200 val leftButtons = 100 val rightButtons = 0 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `Left Buttons - Aligned start - Title should not exceed boundaries`() { val barWidth = parentWidth + 1 val leftButtons = 100 val rightButtons = 0 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `RTL - Left Buttons - Aligned start - Title should be after left (right) buttons with default margins`() { val barWidth = 200 val leftButtons = 100 val rightButtons = 0 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - leftButtons - barWidth - DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - DEFAULT_LEFT_MARGIN_PX - leftButtons, right) } @Test fun `RTL - Left Buttons - Aligned start - Title should not exceed boundaries`() { val barWidth = parentWidth + 1 val leftButtons = 100 val rightButtons = 0 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `Left Buttons - Aligned center - Title should be at center`() { val barWidth = 200 val leftButtons = 100 val rightButtons = 0 val isRTL = false val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth / 2 - barWidth / 2, left) assertEquals(parentWidth / 2 + barWidth / 2, right) } @Test fun `Left Buttons - Aligned center - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 0 val isRTL = false val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) val expectedOverlap = leftButtons - (parentWidth / 2 - barWidth / 2) assertEquals(parentWidth / 2 - barWidth / 2 + expectedOverlap, left) assertEquals(parentWidth / 2 + barWidth / 2 - expectedOverlap, right) } @Test fun `RTL - Left Buttons - Aligned center - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 0 val isRTL = true val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) val expectedOverlap = leftButtons - (parentWidth / 2 - barWidth / 2) assertEquals(parentWidth / 2 - barWidth / 2 + expectedOverlap, left) assertEquals(parentWidth / 2 + barWidth / 2 - expectedOverlap, right) } @Test fun `Left + Right Buttons - Aligned center - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 350 val isRTL = false val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(leftButtons, left) assertEquals(parentWidth - rightButtons, right) } @Test fun `RTL - Left + Right Buttons - Aligned center - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 350 val isRTL = true val center = true val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(rightButtons, left) assertEquals(parentWidth - leftButtons, right) } @Test fun `Left + Right Buttons - Aligned start - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 350 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - rightButtons - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `Left + Right Buttons - Aligned start - Title should'nt take amount of needed width only between buttons only`() { val barWidth = 100 val leftButtons = 300 val rightButtons = 350 val isRTL = false val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX, left) assertEquals(leftButtons + DEFAULT_LEFT_MARGIN_PX + barWidth + DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `RTL - Left + Right Buttons - Aligned start - Title should not exceed boundaries`() { val parentWidth = 1000 val barWidth = 500 val leftButtons = 300 val rightButtons = 350 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(rightButtons + DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right) } @Test fun `RTL - Left + Right Buttons - Aligned start - Title should take amount of needed width only`() { val parentWidth = 1000 val barWidth = 100 val leftButtons = 300 val rightButtons = 100 val isRTL = true val center = false val (left, right) = resolveHorizontalTitleBoundsLimit(parentWidth, barWidth, leftButtons, rightButtons, center, isRTL) assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX - barWidth - DEFAULT_LEFT_MARGIN_PX, left) assertEquals(parentWidth - leftButtons - DEFAULT_LEFT_MARGIN_PX, right) } }
lib/android/app/src/test/java/com/reactnativenavigation/utils/TitleAndButtonsMeasurer.kt
2631501999
fun testOr(b: Boolean): Boolean { return b || return !b; } fun testOr(): Boolean { return true || return false; } fun testAnd(b: Boolean): Boolean { return b && return !b; } fun testAnd(): Boolean { return true && return false; } fun box(): String { if (testOr(false) != true) return "fail 1" if (testOr(true) != true) return "fail 2" if (testAnd(false) != false) return "fail 3" if (testAnd(true) != false) return "fail 4" if (testOr() != true) return "fail 5" if (testAnd() != false) return "fail 6" return "OK" }
backend.native/tests/external/codegen/box/controlStructures/kt9022Return.kt
645405395
/* * Powered By [rapid-framework] * Web Site: http://www.rapid-framework.org.cn * Google Code: http://code.google.com/p/rapid-framework/ * Since 2008 - 2016 */ package com.haozileung.web.domain.permission import java.io.Serializable /** * @author Haozi * * * @version 1.0 * * * @since 1.0 */ data class User(var userId: Long? = null, var username: String? = null, var password: String? = null, var email: String? = null, var remarks: String? = null, var status: Int? = null) : Serializable
src/main/kotlin/com/haozileung/web/domain/permission/User.kt
3572033277
package eu.kanade.tachiyomi.ui.reader.viewer.pager import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import eu.kanade.tachiyomi.ui.reader.viewer.ReaderPageImageView import eu.kanade.tachiyomi.ui.reader.viewer.ViewerConfig import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.DisabledNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.EdgeNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.KindlishNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.LNavigation import eu.kanade.tachiyomi.ui.reader.viewer.navigation.RightAndLeftNavigation import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get /** * Configuration used by pager viewers. */ class PagerConfig( private val viewer: PagerViewer, scope: CoroutineScope, readerPreferences: ReaderPreferences = Injekt.get(), ) : ViewerConfig(readerPreferences, scope) { var theme = readerPreferences.readerTheme().get() private set var automaticBackground = false private set var dualPageSplitChangedListener: ((Boolean) -> Unit)? = null var imageScaleType = 1 private set var imageZoomType = ReaderPageImageView.ZoomStartPosition.LEFT private set var imageCropBorders = false private set var navigateToPan = false private set var landscapeZoom = false private set init { readerPreferences.readerTheme() .register( { theme = it automaticBackground = it == 3 }, { imagePropertyChangedListener?.invoke() }, ) readerPreferences.imageScaleType() .register({ imageScaleType = it }, { imagePropertyChangedListener?.invoke() }) readerPreferences.zoomStart() .register({ zoomTypeFromPreference(it) }, { imagePropertyChangedListener?.invoke() }) readerPreferences.cropBorders() .register({ imageCropBorders = it }, { imagePropertyChangedListener?.invoke() }) readerPreferences.navigateToPan() .register({ navigateToPan = it }) readerPreferences.landscapeZoom() .register({ landscapeZoom = it }, { imagePropertyChangedListener?.invoke() }) readerPreferences.navigationModePager() .register({ navigationMode = it }, { updateNavigation(navigationMode) }) readerPreferences.pagerNavInverted() .register({ tappingInverted = it }, { navigator.invertMode = it }) readerPreferences.pagerNavInverted().changes() .drop(1) .onEach { navigationModeChangedListener?.invoke() } .launchIn(scope) readerPreferences.dualPageSplitPaged() .register( { dualPageSplit = it }, { imagePropertyChangedListener?.invoke() dualPageSplitChangedListener?.invoke(it) }, ) readerPreferences.dualPageInvertPaged() .register({ dualPageInvert = it }, { imagePropertyChangedListener?.invoke() }) } private fun zoomTypeFromPreference(value: Int) { imageZoomType = when (value) { // Auto 1 -> when (viewer) { is L2RPagerViewer -> ReaderPageImageView.ZoomStartPosition.LEFT is R2LPagerViewer -> ReaderPageImageView.ZoomStartPosition.RIGHT else -> ReaderPageImageView.ZoomStartPosition.CENTER } // Left 2 -> ReaderPageImageView.ZoomStartPosition.LEFT // Right 3 -> ReaderPageImageView.ZoomStartPosition.RIGHT // Center else -> ReaderPageImageView.ZoomStartPosition.CENTER } } override var navigator: ViewerNavigation = defaultNavigation() set(value) { field = value.also { it.invertMode = this.tappingInverted } } override fun defaultNavigation(): ViewerNavigation { return when (viewer) { is VerticalPagerViewer -> LNavigation() else -> RightAndLeftNavigation() } } override fun updateNavigation(navigationMode: Int) { navigator = when (navigationMode) { 0 -> defaultNavigation() 1 -> LNavigation() 2 -> KindlishNavigation() 3 -> EdgeNavigation() 4 -> RightAndLeftNavigation() 5 -> DisabledNavigation() else -> defaultNavigation() } navigationModeChangedListener?.invoke() } }
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerConfig.kt
1152603592
package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import javax.inject.Inject /** * SoundInquirePacket */ class SoundInquirePacket( injector: HasAndroidInjector ) : DiaconnG8Packet(injector ) { @Inject lateinit var diaconnG8Pump: DiaconnG8Pump init { msgType = 0x4D.toByte() aapsLogger.debug(LTag.PUMPCOMM, "SoundInquirePacket request") } override fun encode(msgSeq:Int): ByteArray { val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) return suffixEncode(buffer) } override fun getFriendlyName(): String { return "PUMP_SOUND_INQUIRE" } }
diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquirePacket.kt
495703533
package info.nightscout.androidaps.plugins.aps.openAPSSMBDynamicISF import android.content.Context import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.annotations.OpenForTesting import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.aps.loop.ScriptReader import info.nightscout.androidaps.interfaces.DetermineBasalAdapterInterface import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @OpenForTesting @Singleton class OpenAPSSMBDynamicISFPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBus, constraintChecker: ConstraintChecker, rh: ResourceHelper, profileFunction: ProfileFunction, context: Context, activePlugin: ActivePlugin, iobCobCalculator: IobCobCalculator, hardLimits: HardLimits, profiler: Profiler, sp: SP, dateUtil: DateUtil, repository: AppRepository, glucoseStatusProvider: GlucoseStatusProvider, private val buildHelper: BuildHelper ) : OpenAPSSMBPlugin( injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider ) { init { pluginDescription .pluginName(R.string.openaps_smb_dynamic_isf) .description(R.string.description_smb_dynamic_isf) .shortName(R.string.dynisf_shortname) .preferencesId(R.xml.pref_openapssmbdynamicisf) .setDefault(false) .showInList(buildHelper.isEngineeringMode() && buildHelper.isDev()) } override fun specialEnableCondition(): Boolean = buildHelper.isEngineeringMode() && buildHelper.isDev() override fun provideDetermineBasalAdapter(): DetermineBasalAdapterInterface = DetermineBasalAdapterSMBDynamicISFJS(ScriptReader(context), injector) }
app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt
2185071038
package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag class MsgSetExtendedBolusStop( injector: HasAndroidInjector ) : MessageBase(injector) { init { setCommand(0x0406) aapsLogger.debug(LTag.PUMPBTCOMM, "New message") } override fun handleMessage(bytes: ByteArray) { val result = intFromBuff(bytes, 0, 1) if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus stop result: $result FAILED!!!") } else { failed = false aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus stop result: $result OK") } } }
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStop.kt
1616507104
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.exceptions import java.lang.Exception abstract class ExponentException(private val originalException: Exception?) : Exception() { abstract override fun toString(): String fun originalException(): Exception? { return originalException } fun originalExceptionMessage(): String { return originalException?.toString() ?: toString() } }
android/expoview/src/main/java/host/exp/exponent/exceptions/ExponentException.kt
3245620065
package com.rolandvitezhu.todocloud.ui.activity.main.bindingutils import android.view.MotionEvent import android.view.View import android.widget.ImageView import androidx.appcompat.widget.AppCompatCheckBox import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import com.rolandvitezhu.todocloud.app.AppController import com.rolandvitezhu.todocloud.data.Todo import com.rolandvitezhu.todocloud.listener.RecyclerViewOnItemTouchListener import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity import com.rolandvitezhu.todocloud.ui.activity.main.adapter.TodoAdapter import com.rolandvitezhu.todocloud.ui.activity.main.fragment.SearchFragment import com.rolandvitezhu.todocloud.ui.activity.main.fragment.TodoListFragment import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @BindingAdapter("todoSelectedState") fun ConstraintLayout.setTodoSelectedState(todo: Todo) { isActivated = todo.isSelected } @BindingAdapter("todoCompletedCheckedState") fun AppCompatCheckBox.setTodoCompletedCheckedState(todo: Todo) { isChecked = todo.completed ?: false } @BindingAdapter("todoPriority") fun ImageView.setTodoPriority(todo: Todo) { if (todo.priority != null && todo.priority == true) visibility = View.VISIBLE else visibility = View.GONE } @BindingAdapter("todoDragHandleVisible") fun ImageView.setTodoDragHandleVisible(todo: Todo) { visibility = if (AppController.isActionMode() && AppController.isDraggingEnabled) View.VISIBLE else View.GONE } @BindingAdapter(value = ["dragHandleOnTouchListenerTodoAdapter", "dragHandleOnTouchListenerItemViewHolder"]) fun ImageView.setDragHandleOnTouchListener( todoAdapter: TodoAdapter, itemViewHolder: TodoAdapter.ItemViewHolder) { setOnTouchListener { v, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { todoAdapter.itemTouchHelper?.startDrag(itemViewHolder) } false } } @BindingAdapter(value = ["checkBoxTodoCompletedOnTouchListenerTodoAdapter", "checkBoxTodoCompletedOnTouchListenerItemViewHolder", "checkBoxTodoCompletedOnTouchListenerTodo"]) fun AppCompatCheckBox.setCheckBoxTodoCompletedOnTouchListener( todoAdapter: TodoAdapter, itemViewHolder: TodoAdapter.ItemViewHolder, todo: Todo) { setOnTouchListener { v, event -> if (todoAdapter.shouldHandleCheckBoxTouchEvent(event, itemViewHolder)) { todoAdapter.toggleCompleted(todo) val scope = CoroutineScope(Dispatchers.IO) scope.launch { todoAdapter.updateTodo(todo) } todoAdapter.removeTodoFromAdapter(itemViewHolder.adapterPosition) todoAdapter.handleReminderService(todo) } true } } @BindingAdapter("todoListItemTouchListener") fun RecyclerView.setTodoListItemTouchListener(todoListFragment: TodoListFragment) { addOnItemTouchListener(RecyclerViewOnItemTouchListener( context, this, object : RecyclerViewOnItemTouchListener.OnClickListener { override fun onClick(childView: View, childViewAdapterPosition: Int) { if (!todoListFragment.isActionMode()) { todoListFragment.openModifyTodoFragment(childViewAdapterPosition) } else { todoListFragment.todoAdapter.toggleSelection(childViewAdapterPosition) if (todoListFragment.areSelectedItems()) { todoListFragment.actionMode?.invalidate() } else { todoListFragment.actionMode?.finish() } } } override fun onLongClick(childView: View, childViewAdapterPosition: Int) { if (!todoListFragment.isActionMode()) { (todoListFragment.activity as MainActivity?)?. onStartActionMode(todoListFragment.callback) todoListFragment.todoAdapter.toggleSelection(childViewAdapterPosition) todoListFragment.actionMode?.invalidate() } } } ) ) } @BindingAdapter("searchItemTouchListener") fun RecyclerView.setSearchItemTouchListener(searchFragment: SearchFragment) { addOnItemTouchListener(RecyclerViewOnItemTouchListener( context, this, object : RecyclerViewOnItemTouchListener.OnClickListener { override fun onClick(childView: View, childViewAdapterPosition: Int) { if (!searchFragment.isActionMode()) { searchFragment.openModifyTodoFragment(childViewAdapterPosition) } else { searchFragment.todoAdapter.toggleSelection(childViewAdapterPosition) if (searchFragment.areSelectedItems()) { searchFragment.actionMode?.invalidate() } else { searchFragment.actionMode?.finish() } } } override fun onLongClick(childView: View, childViewAdapterPosition: Int) { if (!searchFragment.isActionMode()) { (searchFragment.activity as MainActivity?)?. onStartActionMode(searchFragment.callback) searchFragment.todoAdapter.toggleSelection(childViewAdapterPosition) searchFragment.actionMode?.invalidate() } } } ) ) }
app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/bindingutils/TodoBindingUtils.kt
1568936068
package com.github.sumimakito.awesomeqr.option.logo import android.graphics.Bitmap import android.graphics.RectF class Logo(var bitmap: Bitmap? = null, var scale: Float = 0.2f, var borderRadius: Int = 8, var borderWidth: Int = 10, var clippingRect: RectF? = null) { fun recycle() { if (bitmap == null) return if (bitmap!!.isRecycled) return bitmap!!.recycle() bitmap = null } fun duplicate(): Logo { return Logo( if (bitmap != null) bitmap!!.copy(Bitmap.Config.ARGB_8888, true) else null, scale, borderRadius, borderWidth, clippingRect ) } }
library/src/main/java/com/github/sumimakito/awesomeqr/option/logo/Logo.kt
702169314
/* * Copyright (c) 2022. Adventech <info@adventech.io> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.lessons.data.di import app.ss.auth.api.TokenAuthenticator import app.ss.lessons.data.BuildConfig import app.ss.lessons.data.api.SSLessonsApi import app.ss.lessons.data.api.SSMediaApi import app.ss.lessons.data.api.SSQuarterliesApi import app.ss.storage.db.dao.UserDao import com.cryart.sabbathschool.core.misc.SSConstants import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object ApiModule { private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private fun retrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder() .baseUrl(SSConstants.apiBaseUrl()) .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(okHttpClient) .build() @Provides @Singleton fun provideOkhttpClient( userDao: UserDao, tokenAuthenticator: TokenAuthenticator ): OkHttpClient = OkHttpClient.Builder() .connectTimeout(1, TimeUnit.MINUTES) .readTimeout(1, TimeUnit.MINUTES) .writeTimeout(2, TimeUnit.MINUTES) .addInterceptor( HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) { HttpLoggingInterceptor.Level.BODY } else { HttpLoggingInterceptor.Level.NONE } } ) .addInterceptor { chain -> chain.proceed( chain.request().newBuilder().also { request -> request.addHeader("Accept", "application/json") userDao.getCurrent()?.let { request.addHeader("x-ss-auth-access-token", it.stsTokenManager.accessToken) } }.build() ) } .authenticator(tokenAuthenticator) .retryOnConnectionFailure(true) .build() @Provides @Singleton internal fun provideMediaApi( okHttpClient: OkHttpClient ): SSMediaApi = retrofit(okHttpClient) .create(SSMediaApi::class.java) @Provides @Singleton internal fun provideQuarterliesApi( okHttpClient: OkHttpClient ): SSQuarterliesApi = retrofit(okHttpClient) .create(SSQuarterliesApi::class.java) @Provides @Singleton internal fun provideLessonsApi( okHttpClient: OkHttpClient ): SSLessonsApi = retrofit(okHttpClient) .create(SSLessonsApi::class.java) }
common/lessons-data/src/main/java/app/ss/lessons/data/di/ApiModule.kt
770198805
//package ogl_samples.framework // //import glm_.vec2.Vec2i //import org.lwjgl.glfw.Callbacks //import org.lwjgl.glfw.GLFW.* //import uno.buffer.destroyBuffers //import uno.buffer.floatBufferBig //import uno.buffer.intBufferBig // ///** // * Created by elect on 18/04/17. // */ // //val mat3Buffer = floatBufferBig(9) //val mat4Buffer = floatBufferBig(16) //val vec4Buffer = floatBufferBig(4) //val int = intBufferBig(1) //val float = floatBufferBig(1) // // //object windowHint { // var resizable = true // set(value) = glfwWindowHint(GLFW_RESIZABLE, if (value) GLFW_TRUE else GLFW_FALSE) // var visible = true // set(value) = glfwWindowHint(GLFW_VISIBLE, if (value) GLFW_TRUE else GLFW_FALSE) // var srgb = true // set(value) = glfwWindowHint(GLFW_SRGB_CAPABLE, if (value) GLFW_TRUE else GLFW_FALSE) // var decorated = true // set(value) = glfwWindowHint(GLFW_DECORATED, if (value) GLFW_TRUE else GLFW_FALSE) // var api = "" // set(value) = glfwWindowHint(GLFW_CLIENT_API, when (value) { // "gl" -> GLFW_OPENGL_API // "es" -> GLFW_OPENGL_ES_API // else -> GLFW_NO_API // }) // var major = 0 // set(value) = glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, value) // var minor = 0 // set(value) = glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, value) // var profile = "" // set(value) = glfwWindowHint(GLFW_OPENGL_PROFILE, // when (value) { // "core" -> GLFW_OPENGL_CORE_PROFILE // "compat" -> GLFW_OPENGL_COMPAT_PROFILE // else -> GLFW_OPENGL_ANY_PROFILE // }) // var forwardComp = true // set(value) = glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, if (value) GLFW_TRUE else GLFW_FALSE) // var debug = true // set(value) = glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, if (value) GLFW_TRUE else GLFW_FALSE) //} // //infix fun Int.or(e: Test.Heuristic) = this or e.i // // //class GlfwWindow(windowSize: Vec2i, title: String) { // // private val x = intBufferBig(1) // val y = intBufferBig(1) // val handle = glfwCreateWindow(windowSize.x, windowSize.y, title, 0L, 0L) // var shouldClose = false // // var pos = Vec2i() // get() { // glfwGetWindowPos(handle, x, y) // return field.put(x[0], y[0]) // } // set(value) = glfwSetWindowPos(handle, value.x, value.y) // // fun dispose() { // // destroyBuffers(x, y) // // // Free the window callbacks and destroy the window // Callbacks.glfwFreeCallbacks(handle) // glfwDestroyWindow(handle) // // // Terminate GLFW and free the error callback // glfwTerminate() //// glfwSetErrorCallback(null).free() // } //}
src/main/kotlin/ogl_samples/framework/helper.kt
3090306284
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.gradle import com.squareup.wire.VERSION import com.squareup.wire.gradle.internal.libraryProtoOutputPath import com.squareup.wire.gradle.internal.targetDefaultOutputPath import com.squareup.wire.gradle.kotlin.Source import com.squareup.wire.gradle.kotlin.sourceRoots import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.artifacts.UnknownConfigurationException import org.gradle.api.internal.file.FileOrUriNotationConverter import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.compile.JavaCompile import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import java.io.File import java.util.concurrent.atomic.AtomicBoolean import java.lang.reflect.Array as JavaArray class WirePlugin : Plugin<Project> { private val android = AtomicBoolean(false) private val java = AtomicBoolean(false) private val kotlin = AtomicBoolean(false) private lateinit var extension: WireExtension internal lateinit var project: Project private val sources by lazy { this.sourceRoots(kotlin = kotlin.get(), java = java.get()) } override fun apply(project: Project) { this.extension = project.extensions.create("wire", WireExtension::class.java, project) this.project = project project.configurations.create("protoSource") .also { it.isCanBeConsumed = false it.isTransitive = false } project.configurations.create("protoPath") .also { it.isCanBeConsumed = false it.isTransitive = false } val androidPluginHandler = { _: Plugin<*> -> android.set(true) project.afterEvaluate { project.setupWireTasks(afterAndroid = true) } } project.plugins.withId("com.android.application", androidPluginHandler) project.plugins.withId("com.android.library", androidPluginHandler) project.plugins.withId("com.android.instantapp", androidPluginHandler) project.plugins.withId("com.android.feature", androidPluginHandler) project.plugins.withId("com.android.dynamic-feature", androidPluginHandler) val kotlinPluginHandler = { _: Plugin<*> -> kotlin.set(true) } project.plugins.withId("org.jetbrains.kotlin.multiplatform", kotlinPluginHandler) project.plugins.withId("org.jetbrains.kotlin.android", kotlinPluginHandler) project.plugins.withId("org.jetbrains.kotlin.jvm", kotlinPluginHandler) project.plugins.withId("kotlin2js", kotlinPluginHandler) val javaPluginHandler = { _: Plugin<*> -> java.set(true) } project.plugins.withId("java", javaPluginHandler) project.plugins.withId("java-library", javaPluginHandler) project.afterEvaluate { project.setupWireTasks(afterAndroid = false) } } private fun Project.setupWireTasks(afterAndroid: Boolean) { if (android.get() && !afterAndroid) return check(android.get() || java.get() || kotlin.get()) { "Missing either the Java, Kotlin, or Android plugin" } project.tasks.register(ROOT_TASK) { it.group = GROUP it.description = "Aggregation task which runs every generation task for every given source" } if (extension.protoLibrary) { val libraryProtoSources = File(project.libraryProtoOutputPath()) val sourceSets = project.extensions.getByType(SourceSetContainer::class.java) sourceSets.getByName("main") { main: SourceSet -> main.resources.srcDir(libraryProtoSources) } extension.proto { protoOutput -> protoOutput.out = libraryProtoSources.path } } val outputs = extension.outputs check(outputs.isNotEmpty()) { "At least one target must be provided for project '${project.path}\n" + "See our documentation for details: https://square.github.io/wire/wire_compiler/#customizing-output" } val hasJavaOutput = outputs.any { it is JavaOutput } val hasKotlinOutput = outputs.any { it is KotlinOutput } check(!hasKotlinOutput || kotlin.get()) { "Wire Gradle plugin applied in " + "project '${project.path}' but no supported Kotlin plugin was found" } addWireRuntimeDependency(hasJavaOutput, hasKotlinOutput) val protoPathInput = WireInput(project.configurations.getByName("protoPath")) protoPathInput.addTrees(project, extension.protoTrees) protoPathInput.addJars(project, extension.protoJars) protoPathInput.addPaths(project, extension.protoPaths) sources.forEach { source -> val protoSourceInput = WireInput(project.configurations.getByName("protoSource").copy()) protoSourceInput.addTrees(project, extension.sourceTrees) protoSourceInput.addJars(project, extension.sourceJars) protoSourceInput.addPaths(project, extension.sourcePaths) // TODO(Benoit) Should we add our default source folders everytime? Right now, someone could // not combine a custom protoSource with our default using variants. if (protoSourceInput.dependencies.isEmpty()) { protoSourceInput.addPaths(project, defaultSourceFolders(source)) } val inputFiles = project.layout.files(protoSourceInput.inputFiles, protoPathInput.inputFiles) val projectDependencies = (protoSourceInput.dependencies + protoPathInput.dependencies) .filterIsInstance<ProjectDependency>() val targets = outputs.map { output -> output.toTarget( if (output.out == null) { project.relativePath(source.outputDir(project)) } else { output.out!! } ) } val generatedSourcesDirectories = targets.map { target -> project.file(target.outDirectory) }.toSet() // Both the JavaCompile and KotlinCompile tasks might already have been configured by now. // Even though we add the Wire output directories into the corresponding sourceSets, the // compilation tasks won't know about them so we fix that here. if (hasJavaOutput) { project.tasks .withType(JavaCompile::class.java) .matching { it.name == "compileJava" } .configureEach { it.source(generatedSourcesDirectories) } } if (hasJavaOutput || hasKotlinOutput) { project.tasks .withType(KotlinCompile::class.java) .matching { it.name == "compileKotlin" || it.name == "compile${source.name.capitalize()}Kotlin" }.configureEach { // Note that [KotlinCompile.source] will process files but will ignore strings. SOURCE_FUNCTION.invoke(it, arrayOf(generatedSourcesDirectories)) } } // TODO: pair up generatedSourceDirectories with their targets so we can be precise. for (generatedSourcesDirectory in generatedSourcesDirectories) { val relativePath = generatedSourcesDirectory.toRelativeString(project.projectDir) if (hasJavaOutput) { source.javaSourceDirectorySet?.srcDir(relativePath) } if (hasKotlinOutput) { source.kotlinSourceDirectorySet?.srcDir(relativePath) } } val taskName = "generate${source.name.capitalize()}Protos" val task = project.tasks.register(taskName, WireTask::class.java) { task: WireTask -> task.group = GROUP task.description = "Generate protobuf implementation for ${source.name}" task.source(protoSourceInput.configuration) if (task.logger.isDebugEnabled) { protoSourceInput.debug(task.logger) protoPathInput.debug(task.logger) } task.outputDirectories.setFrom(targets.map { it.outDirectory }) task.sourceInput.set(protoSourceInput.toLocations(project)) task.protoInput.set(protoPathInput.toLocations(project)) task.roots.set(extension.roots.toList()) task.prunes.set(extension.prunes.toList()) task.moves.set(extension.moves.toList()) task.sinceVersion.set(extension.sinceVersion) task.untilVersion.set(extension.untilVersion) task.onlyVersion.set(extension.onlyVersion) task.rules.set(extension.rules) task.targets.set(targets) task.permitPackageCycles.set(extension.permitPackageCycles) task.inputFiles.setFrom(inputFiles) task.projectDirProperty.set(project.layout.projectDirectory) task.buildDirProperty.set(project.layout.buildDirectory) for (projectDependency in projectDependencies) { task.dependsOn(projectDependency) } } project.tasks.named(ROOT_TASK).configure { it.dependsOn(task) } if (extension.protoLibrary) { project.tasks.named("processResources").configure { it.dependsOn(task) } } source.registerTaskDependency(task) } } private fun Source.outputDir(project: Project): File { return if (sources.size > 1) File(project.targetDefaultOutputPath(), name) else File(project.targetDefaultOutputPath()) } private fun Project.addWireRuntimeDependency( hasJavaOutput: Boolean, hasKotlinOutput: Boolean ) { val isMultiplatform = project.plugins.hasPlugin("org.jetbrains.kotlin.multiplatform") // Only add the dependency for Java and Kotlin. if (hasJavaOutput || hasKotlinOutput) { if (isMultiplatform) { val sourceSets = project.extensions.getByType(KotlinMultiplatformExtension::class.java).sourceSets val sourceSet = (sourceSets.getByName("commonMain") as DefaultKotlinSourceSet) project.configurations.getByName(sourceSet.apiConfigurationName).dependencies .add(project.dependencies.create("com.squareup.wire:wire-runtime:$VERSION")) } else { try { project.configurations.getByName("api").dependencies .add(project.dependencies.create("com.squareup.wire:wire-runtime:$VERSION")) } catch (_: UnknownConfigurationException) { // No `api` configuration on Java applications. project.configurations.getByName("implementation").dependencies .add(project.dependencies.create("com.squareup.wire:wire-runtime:$VERSION")) } } } } private fun defaultSourceFolders(source: Source): Set<String> { val parser = FileOrUriNotationConverter.parser() return source.sourceSets .map { "src/$it/proto" } .filter { path -> val converted = parser.parseNotation(path) as File val file = if (!converted.isAbsolute) File(project.projectDir, converted.path) else converted return@filter file.exists() } .toSet() } internal companion object { const val ROOT_TASK = "generateProtos" const val GROUP = "wire" // The signature of this function changed in Kotlin 1.7, so we invoke it reflectively to support // both. // 1.6.x: `fun source(vararg sources: Any): SourceTask` // 1.7.x: `fun source(vararg sources: Any)` private val SOURCE_FUNCTION = KotlinCompile::class.java .getMethod("source", JavaArray.newInstance(Any::class.java, 0).javaClass) } }
wire-library/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt
368515609
package com.devops.skeletor import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class SkeletorApplication fun main(args: Array<String>) { SpringApplication.run(SkeletorApplication::class.java, *args) }
openshift/skeletor/src/main/kotlin/com/devops/skeletor/SkeletorApplication.kt
4030076042
/* * Copyright (c) 2022. Adventech <info@adventech.io> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package app.ss.design.compose.widget.icon import androidx.compose.material3.LocalContentColor import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.State import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.graphics.Color /** * Copy of [androidx.compose.material3.IconButtonColors] * Represents the container and content colors used in an icon button in different states. */ @Immutable class SsIconButtonColors internal constructor( private val containerColor: Color, private val contentColor: Color, private val disabledContainerColor: Color, private val disabledContentColor: Color ) { /** * Represents the container color for this icon button, depending on [enabled]. * * @param enabled whether the icon button is enabled */ @Composable internal fun containerColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor) } /** * Represents the content color for this icon button, depending on [enabled]. * * @param enabled whether the icon button is enabled */ @Composable internal fun contentColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) contentColor else disabledContentColor) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is SsIconButtonColors) return false if (containerColor != other.containerColor) return false if (contentColor != other.contentColor) return false if (disabledContainerColor != other.disabledContainerColor) return false if (disabledContentColor != other.disabledContentColor) return false return true } override fun hashCode(): Int { var result = containerColor.hashCode() result = 31 * result + contentColor.hashCode() result = 31 * result + disabledContainerColor.hashCode() result = 31 * result + disabledContentColor.hashCode() return result } } object SsIconButtonColorsDefaults { private const val DisabledIconOpacity = 0.38f @Composable fun iconButtonColors( containerColor: Color = Color.Transparent, contentColor: Color = LocalContentColor.current, disabledContainerColor: Color = Color.Transparent, disabledContentColor: Color = contentColor.copy(alpha = DisabledIconOpacity) ): SsIconButtonColors = SsIconButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) }
common/design-compose/src/main/kotlin/app/ss/design/compose/widget/icon/SsIconButtonColors.kt
2453120060
package com.nytclient.data.api.service import android.arch.lifecycle.LiveData import com.nytclient.data.api.ApiResponse import com.nytclient.data.model.NewsApiResponse import retrofit2.http.GET import retrofit2.http.Query /** * NYT API service class. * * @link https://developer.nytimes.com/ * * Created by Dogan Gulcan on 9/12/17. */ interface NYTService { @GET("svc/news/v3/content/nyt/all") fun getNews(@Query("limit") itemCount: Int, @Query("offset") pageIndex: Int): LiveData<ApiResponse<NewsApiResponse>> }
app/src/main/java/com/nytclient/data/api/service/NYTService.kt
1478013358
// 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.presentation import com.intellij.ide.IconProvider import com.intellij.navigation.ColoredItemPresentation import com.intellij.navigation.ItemPresentation import com.intellij.navigation.ItemPresentationProvider import com.intellij.openapi.editor.colors.CodeInsightColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.util.Iconable import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.KotlinIconProvider import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import javax.swing.Icon open class KotlinDefaultNamedDeclarationPresentation(private val declaration: KtNamedDeclaration) : ColoredItemPresentation { override fun getTextAttributesKey(): TextAttributesKey? { if (KtPsiUtil.isDeprecated(declaration)) { return CodeInsightColors.DEPRECATED_ATTRIBUTES } return null } override fun getPresentableText() = declaration.name override fun getLocationString(): String? { if ((declaration is KtFunction && declaration.isLocal) || (declaration is KtClassOrObject && declaration.isLocal)) { val containingDeclaration = declaration.getStrictParentOfType<KtNamedDeclaration>() ?: return null val containerName = containingDeclaration.fqName ?: containingDeclaration.name return KotlinBundle.message("presentation.text.in.container.paren", containerName.toString()) } val name = declaration.fqName val parent = declaration.parent val containerText = if (name != null) { val qualifiedContainer = name.parent().toString() if (parent is KtFile && declaration.hasModifier(KtTokens.PRIVATE_KEYWORD)) { KotlinBundle.message("presentation.text.in.container", parent.name, qualifiedContainer) } else { qualifiedContainer } } else { getNameForContainingObjectLiteral() ?: return null } val receiverTypeRef = (declaration as? KtCallableDeclaration)?.receiverTypeReference return when { receiverTypeRef != null -> { KotlinBundle.message("presentation.text.for.receiver.in.container.paren", receiverTypeRef.text, containerText) } parent is KtFile -> KotlinBundle.message("presentation.text.paren", containerText) else -> KotlinBundle.message("presentation.text.in.container.paren", containerText) } } private fun getNameForContainingObjectLiteral(): String? { val objectLiteral = declaration.getStrictParentOfType<KtObjectLiteralExpression>() ?: return null val container = objectLiteral.getStrictParentOfType<KtNamedDeclaration>() ?: return null val containerFqName = container.fqName?.asString() ?: return null return KotlinBundle.message("presentation.text.object.in.container", containerFqName) } override fun getIcon(unused: Boolean): Icon? { val instance = IconProvider.EXTENSION_POINT_NAME.findFirstSafe { it is KotlinIconProvider } return instance?.getIcon(declaration, Iconable.ICON_FLAG_VISIBILITY or Iconable.ICON_FLAG_READ_STATUS) } } class KtDefaultDeclarationPresenter : ItemPresentationProvider<KtNamedDeclaration> { override fun getPresentation(item: KtNamedDeclaration) = KotlinDefaultNamedDeclarationPresentation(item) } open class KotlinFunctionPresentation( private val function: KtFunction, private val name: String? = function.name ) : KotlinDefaultNamedDeclarationPresentation(function) { override fun getPresentableText(): String { return buildString { name?.let { append(it) } append("(") append(function.valueParameters.joinToString { (if (it.isVarArg) "vararg " else "") + (it.typeReference?.text ?: "") }) append(")") } } override fun getLocationString(): String? { if (function is KtConstructor<*>) { val name = function.getContainingClassOrObject().fqName ?: return null return KotlinBundle.message("presentation.text.in.container.paren", name) } return super.getLocationString() } } class KtFunctionPresenter : ItemPresentationProvider<KtFunction> { override fun getPresentation(function: KtFunction): ItemPresentation? { if (function is KtFunctionLiteral) return null return KotlinFunctionPresentation(function) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/presentation/DeclarationPresenters.kt
2969984456
// 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.github.ui.cloneDialog import org.jetbrains.plugins.github.api.data.GithubAuthenticatedUser import org.jetbrains.plugins.github.api.data.GithubRepo import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import javax.swing.AbstractListModel internal class GHCloneDialogRepositoryListModel : AbstractListModel<GHRepositoryListItem>() { private val itemsByAccount = LinkedHashMap<GithubAccount, MutableList<GHRepositoryListItem>>() private val repositoriesByAccount = hashMapOf<GithubAccount, MutableSet<GithubRepo>>() override fun getSize(): Int = itemsByAccount.values.sumOf { it.size } override fun getElementAt(index: Int): GHRepositoryListItem { var offset = 0 for ((_, items) in itemsByAccount) { if (index >= offset + items.size) { offset += items.size continue } return items[index - offset] } throw IndexOutOfBoundsException(index) } fun clear(account: GithubAccount) { repositoriesByAccount.remove(account) val (startOffset, endOffset) = findAccountOffsets(account) ?: return itemsByAccount.remove(account) fireIntervalRemoved(this, startOffset, endOffset) } fun setError(account: GithubAccount, error: Throwable) { val accountItems = itemsByAccount.getOrPut(account) { mutableListOf() } val (startOffset, endOffset) = findAccountOffsets(account) ?: return val errorItem = GHRepositoryListItem.Error(account, error) accountItems.add(0, errorItem) fireIntervalAdded(this, endOffset, endOffset + 1) fireContentsChanged(this, startOffset, endOffset + 1) } /** * Since each repository can be in several states at the same time (shared access for a collaborator and shared access for org member) and * repositories for collaborators are loaded in separate request before repositories for org members, we need to update order of re-added * repo in order to place it close to other organization repos */ fun addRepositories(account: GithubAccount, details: GithubAuthenticatedUser, repos: List<GithubRepo>) { val repoSet = repositoriesByAccount.getOrPut(account) { mutableSetOf() } val items = itemsByAccount.getOrPut(account) { mutableListOf() } var (startOffset, endOffset) = findAccountOffsets(account) ?: return val toAdd = mutableListOf<GHRepositoryListItem.Repo>() for (repo in repos) { val item = GHRepositoryListItem.Repo(account, details, repo) val isNew = repoSet.add(repo) if (isNew) { toAdd.add(item) } else { val idx = items.indexOf(item) items.removeAt(idx) fireIntervalRemoved(this, startOffset + idx, startOffset + idx) endOffset-- } } items.addAll(toAdd) fireIntervalAdded(this, endOffset, endOffset + toAdd.size) } private fun findAccountOffsets(account: GithubAccount): Pair<Int, Int>? { if (!itemsByAccount.containsKey(account)) return null var startOffset = 0 var endOffset = 0 for ((_account, items) in itemsByAccount) { endOffset = startOffset + items.size if (_account == account) { break } else { startOffset += items.size } } return startOffset to endOffset } }
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogRepositoryListModel.kt
359482665
/* * Copyright 2020 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.acornui.component.text import com.acornui.component.ComponentInit import com.acornui.component.style.cssClass import com.acornui.di.Context import com.acornui.dom.createElement import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLImageElement import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * Common text style tags. */ object TextStyleTags { val error by cssClass() val warning by cssClass() val info by cssClass() } /** * A shortcut to creating a text field with the [TextStyleTags.error] tag. */ inline fun Context.errorText(text: String = "", init: ComponentInit<TextField> = {}): TextField { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val t = TextField(this) t.addClass(TextStyleTags.error) t.text = text t.init() return t } /** * A shortcut to creating a text field with the [TextStyleTags.warning] tag. */ inline fun Context.warningText(text: String = "", init: ComponentInit<TextField> = {}): TextField { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val t = TextField(this) t.addClass(TextStyleTags.warning) t.text = text t.init() return t } /** * A shortcut to creating a text field with the [TextStyleTags.info] tag. */ inline fun Context.infoText(text: String = "", init: ComponentInit<TextField> = {}): TextField { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } val t = TextField(this) t.addClass(TextStyleTags.info) t.text = text t.init() return t } object FontStyle { const val NORMAL = "normal" const val ITALIC = "italic" } /** * Needs to be an inline element without a baseline (so its bottom (not baseline) is used for alignment) */ private val baselineLocator by lazy { createElement<HTMLImageElement>("img") { style.verticalAlign = "baseline" } } /** * Calculates the baseline height of this element by temporarily adding an empty component with no baseline and a * baseline alignment to this element, measuring its bottom bounds and comparing to this component's bottom bounds. */ fun HTMLElement.calculateBaselineHeight(): Double { val bottomY = getBoundingClientRect().bottom appendChild(baselineLocator) val baselineY = baselineLocator.getBoundingClientRect().bottom removeChild(baselineLocator) return bottomY - baselineY }
acornui-core/src/main/kotlin/com/acornui/component/text/TextStyles.kt
2116685877
/* * Copyright 2020 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Thanks to Aaron Iker * https://css-tricks.com/custom-styling-form-inputs-with-modern-css-features/ */ @file:Suppress("unused") package com.acornui.component.input import com.acornui.Disposable import com.acornui.UidUtil import com.acornui.component.* import com.acornui.component.input.LabelComponentStyle.labelComponent import com.acornui.component.input.LabelComponentStyle.labelComponentSpan import com.acornui.component.style.CommonStyleTags import com.acornui.component.style.CssClassToggle import com.acornui.component.style.cssClass import com.acornui.component.text.text import com.acornui.css.prefix import com.acornui.di.Context import com.acornui.dom.addStyleToHead import com.acornui.dom.createElement import com.acornui.formatters.* import com.acornui.google.Icons import com.acornui.google.icon import com.acornui.graphic.Color import com.acornui.input.* import com.acornui.number.zeroPadding import com.acornui.observe.Observable import com.acornui.properties.afterChange import com.acornui.recycle.Clearable import com.acornui.signal.once import com.acornui.signal.signal import com.acornui.signal.unmanagedSignal import com.acornui.skins.CssProps import com.acornui.time.Date import org.w3c.dom.* import org.w3c.dom.events.MouseEvent import org.w3c.dom.events.MouseEventInit import org.w3c.files.FileList import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.js.Date as JsDate object InputStyles { val switch by cssClass() init { @Suppress("CssUnresolvedCustomProperty", "CssInvalidFunction", "CssInvalidPropertyValue", "CssNoGenericFontName" ) addStyleToHead( """ input { font: inherit; } select { font: inherit; color: ${CssProps.inputTextColor.v};; border-width: ${CssProps.borderThickness.v};; border-color: ${CssProps.borderColor.v}; border-radius: ${CssProps.inputBorderRadius.v}; padding: ${CssProps.inputPadding.v}; background: ${CssProps.inputBackground.v}; box-shadow: ${CssProps.componentShadow.v}; } option { font: inherit; color: ${CssProps.inputTextColor.v}; background: ${CssProps.inputBackground.v}; } input[type="datetime-local"]:after, input[type="week"]:after, input[type="month"]:after, input[type="time"]:after, input[type="date"]:after { font-family: "Material Icons"; -webkit-font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; text-transform: none; font-size: 1.2em; margin-right: 3px; pointer-events: none; } input[type="week"]:after, input[type="month"]:after, input[type="date"]:after { content: "calendar_today"; } input[type="time"]:after { content: "access_time"; } ::-webkit-calendar-picker-indicator { background: transparent; color: rgba(0, 0, 0, 0); opacity: 1; margin-right: -20px; } input[type='date'], input[type='month'], input[type='number'], input[type='email'], input[type='password'], input[type='search'], input[type='time'], input[type='color'], input[type='text'] { color: ${CssProps.inputTextColor.v}; border-width: ${CssProps.borderThickness.v};; border-color: ${CssProps.borderColor.v}; border-radius: ${CssProps.inputBorderRadius.v}; border-style: solid; padding: ${CssProps.inputPadding.v}; background: ${CssProps.inputBackground.v}; box-shadow: ${CssProps.componentShadow.v}; } input:disabled { background: ${CssProps.disabledInner.v}; border-color: ${CssProps.disabled.v}; color: ${CssProps.toggledInnerDisabled.v}; pointer-events: none; } input:active { border-color: ${CssProps.accentActive.v}; } input[type='date'], input[type='month'], input[type='time'], input[type='datetime-local'], input[type='button'], input[type='submit'], input[type='reset'], input[type='search'], input[type='checkbox'], input[type='radio'] { ${prefix("appearance", "none")}; } input:disabled { opacity: ${CssProps.disabledOpacity.v}; } input[type='checkbox'], input[type='radio'] { height: 21px; outline: none; display: inline-block; vertical-align: top; position: relative; margin: 0; cursor: pointer; border: 1px solid var(--bc, ${CssProps.borderColor.v}); background: var(--b, ${CssProps.componentBackground.v}); transition: background 0.3s, border-color 0.3s, box-shadow 0.2s; } input[type='checkbox']::after, input[type='radio']::after { content: ''; display: block; left: 0; top: 0; position: absolute; transition: transform var(--d-t, 0.3s) var(--d-t-e, ease), opacity var(--d-o, 0.2s); box-sizing: border-box; } input[type='checkbox']:indeterminate, input[type='checkbox']:checked, input[type='radio']:checked { --b: ${CssProps.accentFill.v}; --bc: ${CssProps.accentFill.v}; --d-o: 0.3s; --d-t: 0.6s; --d-t-e: cubic-bezier(0.2, 0.85, 0.32, 1.2); } input[type='checkbox']:disabled, input[type='radio']:disabled { --b: ${CssProps.disabled.v}; cursor: not-allowed; } input[type='checkbox']:disabled:indeterminate, input[type='checkbox']:disabled:checked, input[type='radio']:disabled:checked { --b: ${CssProps.disabledInner.v}; --bc: ${CssProps.borderDisabled.v}; } input[type='checkbox']:disabled + label, input[type='radio']:disabled + label { cursor: not-allowed; opacity: ${CssProps.disabledOpacity.v}; } input[type='checkbox']:hover:not(:indeterminate):not(:disabled), input[type='checkbox']:hover:not(:checked):not(:disabled), input[type='radio']:hover:not(:checked):not(:disabled) { --bc: ${CssProps.accentHover.v}; } input[type='checkbox']:not($switch), input[type='radio']:not($switch) { width: 21px; } input[type='checkbox']:not($switch)::after, input[type='radio']:not($switch)::after { opacity: var(--o, 0); } input[type='checkbox']:not($switch):indeterminate, input[type='checkbox']:not($switch):checked, input[type='radio']:not($switch):checked { --o: 1; } input[type='checkbox'] + label, input[type='radio'] + label { display: inline-block; vertical-align: top; cursor: pointer; user-select: none; -moz-user-select: none; } input[type='checkbox']:not($switch) { border-radius: 7px; } input[type='checkbox']:not($switch):not(:indeterminate)::after { width: 5px; height: 9px; border: 2px solid ${CssProps.toggledInner.v}; border-top: 0; border-left: 0; left: 7px; top: 4px; transform: rotate(var(--r, 20deg)); } input[type='checkbox']:not(.switch):indeterminate::after { width: 9px; height: 2px; border-top: 2px solid ${CssProps.toggledInner.v}; left: 5px; top: 9px; } input[type='checkbox']:not($switch)::after { width: 7px; height: 2px; border-top: 2px solid ${CssProps.toggledInner.v}; left: 4px; top: 7px; } input[type='checkbox']:not($switch):checked { --r: 43deg; } input[type='checkbox']$switch { width: 38px; border-radius: 11px; } input[type='checkbox']$switch::after { left: 2px; top: 2px; border-radius: 50%; width: 15px; height: 15px; background: var(--ab, ${CssProps.borderColor.v}); transform: translateX(var(--x, 0)); } input[type='checkbox']$switch:checked { --ab: ${CssProps.toggledInner.v}; --x: 17px; } input[type='checkbox']$switch:disabled:not(:checked)::after { opacity: 0.6; } input[type='radio'] { border-radius: 50%; } input[type='radio']:checked { --scale: 0.5; } input[type='radio']::after { width: 19px; height: 19px; border-radius: 50%; background: ${CssProps.toggledInner.v}; opacity: 0; transform: scale(var(--scale, 0.7)); } input::before, input::after { box-sizing: border-box; } input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:focus, textarea:-webkit-autofill, textarea:-webkit-autofill:hover, textarea:-webkit-autofill:focus, select:-webkit-autofill, select:-webkit-autofill:hover, select:-webkit-autofill:focus { -webkit-text-fill-color: ${CssProps.inputTextColor.v}; font-style: italic; } """ ) } } open class Button(owner: Context, type: String = "button") : DivWithInputComponent(owner) { var toggleOnClick = false final override val inputComponent = addChild(InputImpl(this, type).apply { addClass(CommonStyleTags.hidden) tabIndex = -1 }) val labelComponent = addChild(text { addClass(ButtonStyle.label) }) var type: String get() = inputComponent.dom.type set(value) { inputComponent.dom.type = value } var multiple: Boolean get() = inputComponent.dom.multiple set(value) { inputComponent.dom.multiple = value } init { addClass(ButtonStyle.button) tabIndex = 0 mousePressOnKey() mousePressed.listen { active = true stage.mouseReleased.once { active = false } } touchStarted.listen { active = true stage.touchEnded.once { active = false } } clicked.listen { if (it.target != inputComponent.dom) { inputComponent.dom.dispatchEvent(MouseEvent("click", MouseEventInit(bubbles = false))) if (toggleOnClick) { toggled = !toggled toggledChanged.dispatch(Unit) } } } } override var label: String get() = labelComponent.label set(value) { labelComponent.label = value } override fun onElementAdded(oldIndex: Int, newIndex: Int, element: WithNode) { labelComponent.addElement(newIndex, element) } override fun onElementRemoved(index: Int, element: WithNode) { labelComponent.removeElement(index) } override var disabled: Boolean by afterChange(false) { inputComponent.disabled = it toggleClass(CommonStyleTags.disabled) } private var active: Boolean by CssClassToggle(CommonStyleTags.active) /** * If [toggleOnClick] is true, when the user clicks this button, [toggled] is changed and [toggledChanged] is * dispatched. * This will only dispatch on a user event, not on setting [toggled]. */ val toggledChanged = signal<Unit>() /** * Returns true if the dom contains the class [CommonStyleTags.toggled]. */ var toggled: Boolean by CssClassToggle(CommonStyleTags.toggled) } object ButtonStyle { val button by cssClass() val label by cssClass() init { addStyleToHead(""" $button { -webkit-tap-highlight-color: transparent; padding: ${CssProps.componentPadding.v}; border-radius: ${CssProps.borderRadius.v}; background: ${CssProps.buttonBackground.v}; border-color: ${CssProps.borderColor.v}; border-width: ${CssProps.borderThickness.v}; color: ${CssProps.buttonTextColor.v}; font-size: inherit; /*text-shadow: 1px 1px 1px #0004;*/ border-style: solid; user-select: none; -webkit-user-select: none; -moz-user-select: none; text-align: center; vertical-align: middle; overflow: hidden; box-sizing: border-box; box-shadow: ${CssProps.componentShadow.v}; cursor: pointer; font-weight: bolder; flex-shrink: 0; } $button:hover { background: ${CssProps.buttonBackgroundHover.v}; border-color: ${CssProps.accentHover.v}; color: ${CssProps.buttonTextHoverColor.v}; } $button${CommonStyleTags.active} { background: ${CssProps.buttonBackgroundActive.v}; border-color: ${CssProps.accentActive.v}; color: ${CssProps.buttonTextActiveColor.v}; } $button${CommonStyleTags.toggled} { background: ${CssProps.accentFill.v}; border-color: ${CssProps.accentFill.v}; color: ${CssProps.toggledInner.v}; } $button${CommonStyleTags.toggled}:hover { background: ${CssProps.accentFill.v}; border-color: ${CssProps.accentHover.v}; } $button${CommonStyleTags.toggled}${CommonStyleTags.active} { border-color: ${CssProps.accentActive.v}; } $button${CommonStyleTags.disabled} { background: ${CssProps.disabledInner.v}; border-color: ${CssProps.disabled.v}; color: ${CssProps.toggledInnerDisabled.v}; pointer-events: none; opacity: ${CssProps.disabledOpacity.v}; } $button > div { overflow: hidden; display: flex; flex-direction: row; align-items: center; justify-content: center; } """) } } inline fun Context.button(label: String = "", init: ComponentInit<Button> = {}): Button { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return Button(this).apply { this.label = label init() } } inline fun Context.checkbox(defaultChecked: Boolean = false, init: ComponentInit<ToggleInput> = {}): ToggleInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return ToggleInput(this, "checkbox").apply { this.defaultChecked = defaultChecked init() } } open class ColorInput(owner: Context) : InputImpl(owner, "color") { var valueAsColor: Color? get() = if (dom.value.length < 3) null else Color.fromStr(dom.value) set(value) { dom.value = if (value == null) "" else "#" + value.toRgbString() } } inline fun Context.colorInput(init: ComponentInit<ColorInput> = {}): ColorInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return ColorInput(this).apply(init) } open class DateInput(owner: Context) : InputImpl(owner, "date") { private val parser = DateTimeParser() /** * Sets/gets the default date. */ var defaultValueAsDate: Date? get() = parseDate(dom.defaultValue, isUtc = true) set(value) { dom.defaultValue = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}" } var valueAsDate: Date? get() = Date(dom.valueAsDate.unsafeCast<JsDate>()) set(value) { dom.valueAsDate = value?.jsDate } var step: Double? get() = dom.step.toDoubleOrNull() set(value) { dom.step = value.toString() } var min: Date? get() = parseDate(dom.min, isUtc = true) set(value) { dom.min = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}" } var max: Date? get() = parseDate(dom.max, isUtc = true) set(value) { dom.max = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}-${value.utcDayOfMonth.zeroPadding(2)}" } /** * Returns a String representation of the value. * This will use the [DateTimeFormatter], set to UTC timezone. */ fun valueToString(year: YearFormat = YearFormat.NUMERIC, month: MonthFormat = MonthFormat.TWO_DIGIT, day: TimePartFormat = TimePartFormat.TWO_DIGIT) : String { val valueAsDate = valueAsDate ?: return "" val formatter = DateTimeFormatter(timeZone = "UTC", year = year, month = month, day = day) return formatter.format(valueAsDate) } } inline fun Context.dateInput(init: ComponentInit<DateInput> = {}): DateInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return DateInput(this).apply(init) } // Does not work in Fx @ExperimentalJsExport inline fun Context.dateTimeInput(init: ComponentInit<InputImpl> = {}): InputImpl { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return InputImpl(this, "datetime-local").apply(init) } open class FileInput(owner: Context) : Button(owner, "file"), Clearable { var accept: String get() = inputComponent.dom.accept set(value) { inputComponent.dom.accept = value } val files: FileList? get() = inputComponent.dom.files var value: String get() = inputComponent.dom.value set(value) { inputComponent.dom.value = value } override fun clear() { value = "" } } /** * Creates an input element of type file, styled like a button. */ inline fun Context.fileInput(init: ComponentInit<FileInput> = {}): FileInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return FileInput(this).apply { init() } } inline fun Context.hiddenInput(init: ComponentInit<InputImpl> = {}): InputImpl { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return InputImpl(this, "hidden").apply(init) } open class MonthInput(owner: Context) : InputImpl(owner, "month") { private val parser = DateTimeParser() /** * Returns the default month as a UTC Date. */ var defaultValueAsDate: Date? get() = parseDate(dom.defaultValue, isUtc = true) set(value) { dom.defaultValue = if (value == null) "" else "${value.utcFullYear}-${value.utcMonth.zeroPadding(2)}" } /** * Returns/sets the selected month as a UTC Date. */ var valueAsDate: Date? get() = Date(dom.valueAsDate.unsafeCast<JsDate>()) set(value) { dom.valueAsDate = value?.jsDate } var value: String get() = dom.value set(value) { dom.value = value } /** * Returns a String representation of the value. * This will use the [DateTimeFormatter], set to UTC timezone. */ fun valueToString(year: YearFormat = YearFormat.NUMERIC, month: MonthFormat = MonthFormat.TWO_DIGIT) : String { val valueAsDate = valueAsDate ?: return "" val formatter = DateTimeFormatter(timeZone = "UTC", year = year, month = month) return formatter.format(valueAsDate) } } inline fun Context.monthInput(init: ComponentInit<MonthInput> = {}): MonthInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return MonthInput(this).apply(init) } inline fun Context.resetInput(label: String = "", init: ComponentInit<Button> = {}): Button { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return Button(this, "reset").apply { this.label = label init() } } inline fun Context.submitInput(label: String = "", init: ComponentInit<Button> = {}): Button { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return Button(this, "submit").apply { this.label = label init() } } open class TimeInput(owner: Context) : InputImpl(owner, "time") { private val parser = DateTimeParser() /** * Sets/gets the default date. */ var defaultValueAsDate: Date? get() = parseDate(dom.defaultValue) set(value) { dom.defaultValue = if (value == null) "" else "${value.hours.zeroPadding(2)}:${value.minutes.zeroPadding(2)}" } fun defaultValueAsDate(value: Date, useMinutes: Boolean = true, useSeconds: Boolean = false, useMilliseconds: Boolean = false) { dom.defaultValue = formatTimeForDom(value, useMinutes, useSeconds, useMilliseconds) } var valueAsDate: Date? get() = Date(dom.valueAsDate.unsafeCast<JsDate>()) set(value) { dom.valueAsDate = value?.jsDate } var step: Double? get() = dom.step.toDoubleOrNull() set(value) { dom.step = value.toString() } var min: Date? get() = parseDate(dom.min) set(value) { dom.min = formatTimeForDom(value) } var max: Date? get() = parseDate(dom.max, isUtc = true) set(value) { dom.max = formatTimeForDom(value) } /** * Returns a String representation of the value. * This will use the [DateTimeFormatter], set to UTC timezone. */ fun valueToString(hour: TimePartFormat? = TimePartFormat.NUMERIC, minute: TimePartFormat? = TimePartFormat.TWO_DIGIT, second: TimePartFormat? = TimePartFormat.TWO_DIGIT) : String { val valueAsDate = valueAsDate ?: return "" val formatter = DateTimeFormatter(hour = hour, minute = minute, second = second) return formatter.format(valueAsDate) } private fun formatTimeForDom(value: Date?, useMinutes: Boolean = true, useSeconds: Boolean = false, useMilliseconds: Boolean = false): String { if (value == null) return "" val minutes = if (useMinutes || useSeconds || useMilliseconds) ":${value.minutes.zeroPadding(2)}" else "" val seconds = if (useSeconds || useMilliseconds) ":${value.seconds.zeroPadding(2)}" else "" val milli = if (useMilliseconds) ".${value.milliseconds.zeroPadding(3)}" else "" return "${value.hours.zeroPadding(2)}$minutes$seconds$milli" } } inline fun Context.timeInput(init: ComponentInit<TimeInput> = {}): TimeInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return TimeInput(this).apply(init) } @ExperimentalJsExport inline fun Context.weekInput(init: ComponentInit<InputImpl> = {}): InputImpl { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return InputImpl(this, "week").apply(init) } /** * An input component such as a radio, switch, or checkbox that should be inline with a label. */ open class ToggleInput(owner: Context, type: String) : DivWithInputComponent(owner) { public final override val inputComponent = addChild(InputImpl(this, type)) val labelComponent = addChild(label(inputComponent) { hide() }) init { addClass(ToggleInputStyle.toggleInput) inputComponent.style.flexShrink = "0" } var indeterminate: Boolean get() = inputComponent.dom.indeterminate set(value) { inputComponent.dom.indeterminate = value } var defaultChecked: Boolean get() = inputComponent.dom.defaultChecked set(value) { inputComponent.dom.defaultChecked = value } var checked: Boolean get() = inputComponent.dom.checked set(value) { inputComponent.dom.checked = value } var value: String get() = inputComponent.dom.value set(value) { inputComponent.dom.value = value } override fun onElementAdded(oldIndex: Int, newIndex: Int, element: WithNode) { labelComponent.addElement(newIndex, element) } override fun onElementRemoved(index: Int, element: WithNode) { labelComponent.removeElement(index) } override var label: String get() = labelComponent.label set(value) { labelComponent.label = value labelComponent.visible(value.isNotEmpty()) } } object ToggleInputStyle { val toggleInput by cssClass() init { addStyleToHead(""" $toggleInput { display: inline-flex; flex-direction: row; align-items: center; } $toggleInput label { padding-left: 0.8ch; display: inline-flex; flex-direction: row; align-items: center; } """) } } inline fun Context.switch(defaultChecked: Boolean = false, init: ComponentInit<ToggleInput> = {}): ToggleInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return ToggleInput(this, "checkbox").apply { inputComponent.addClass(InputStyles.switch) this.defaultChecked = defaultChecked init() } } /** * * This name should be unique to the radio button groups on the page. */ class RadioGroup(val name: String = UidUtil.createUid()) : Observable, Disposable { override val changed = unmanagedSignal<Observable>() /** * A list of all radio inputs belonging to this radio group. */ val allButtons = ArrayList<ToggleInput>() var value: String? get() = allButtons.first { it.checked }.value set(value) { for (radio in allButtons) { radio.checked = radio.value == value } } fun notifyChanged() { changed.dispatch(this) } override fun dispose() { allButtons.clear() changed.dispose() } } open class RadioInput(owner: Context, val group: RadioGroup) : ToggleInput(owner, "radio") { init { name = group.name group.allButtons.add(this) changed.listen { group.notifyChanged() } } } inline fun Context.radio(group: RadioGroup, value: String, defaultChecked: Boolean = false, init: ComponentInit<RadioInput> = {}): RadioInput { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return RadioInput(this, group).apply { this.defaultChecked = defaultChecked this.value = value init() } } /** * LabelComponent is a label element with a nested span. Settings [UiComponent.label] will set the text on that span, * thus not replacing any other nested elements. */ class LabelComponent(owner: Context) : UiComponentImpl<HTMLLabelElement>(owner, createElement<Element>("label").unsafeCast<HTMLLabelElement>()) { private val span = addChild(span { addClass(labelComponentSpan) }) /** * Sets the text within a span. */ override var label: String get() = span.label set(value) { span.label = value } init { addClass(labelComponent) } } object LabelComponentStyle { val labelComponent by cssClass() val labelComponentSpan by cssClass() } inline fun Context.label(htmlFor: String = "", value: String = "", init: ComponentInit<LabelComponent> = {}): LabelComponent { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return LabelComponent(this).apply { if (htmlFor.isNotEmpty()) dom.htmlFor = htmlFor label = value init() } } inline fun Context.label(forComponent: UiComponent, value: String = "", init: ComponentInit<LabelComponent> = {}): LabelComponent = label(forComponent.id, value, init) open class Select(owner: Context) : UiComponentImpl<HTMLSelectElement>(owner, createElement("select")) { var disabled: Boolean get() = dom.disabled set(value) { dom.disabled = value } var multiple: Boolean get() = dom.multiple set(value) { dom.multiple = value } var required: Boolean get() = dom.required set(value) { dom.required = value } val size: Int get() = dom.size val options: HTMLOptionsCollection get() = dom.options val selectedOptions: HTMLCollection get() = dom.selectedOptions var selectedIndex: Int get() = dom.selectedIndex set(value) { dom.selectedIndex = value } var value: String get() = dom.value set(value) { dom.value = value } val willValidate: Boolean get() = dom.willValidate val validity: ValidityState get() = dom.validity val validationMessage: String get() = dom.validationMessage val labels: NodeList get() = dom.labels fun namedItem(name: String): HTMLOptionElement? = dom.namedItem(name) fun add(element: UnionHTMLOptGroupElementOrHTMLOptionElement) = dom.add(element) fun add(element: UnionHTMLOptGroupElementOrHTMLOptionElement, before: dynamic) = dom.add(element, before) fun remove(index: Int) = dom.remove(index) fun checkValidity(): Boolean = dom.checkValidity() fun reportValidity(): Boolean = dom.reportValidity() fun setCustomValidity(error: String) = dom.setCustomValidity(error) } inline fun Context.select(init: ComponentInit<Select> = {}): Select { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return Select(this).apply(init) } open class Option(owner: Context) : UiComponentImpl<HTMLOptionElement>(owner, createElement("option")) { open var disabled: Boolean get() = dom.disabled set(value) { dom.disabled = value } override var label: String get() = dom.label set(value) { dom.label = value } var defaultSelected: Boolean get() = dom.defaultSelected set(value) { dom.defaultSelected = value } var selected: Boolean get() = dom.selected set(value) { dom.selected = value } var value: String get() = dom.value set(value) { dom.value = value } val index: Int get() = dom.index } inline fun Context.option(init: ComponentInit<Option> = {}): Option { contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) } return Option(this).apply(init) }
acornui-core/src/main/kotlin/com/acornui/component/input/inputComponents.kt
2212267025
package com.timepath.vgui import com.timepath.Logger import com.timepath.steam.io.VDFNode import java.awt.Font import java.awt.GraphicsEnvironment import java.awt.Toolkit import java.io.File import java.util.logging.Level public class HudFont(private val fontname: String, node: VDFNode) { var name: String? = null var tall: Int = 0 var aa: Boolean = false init { for (p in node.getProperties()) { val key = p.getKey().toLowerCase() val value = p.getValue().toString().toLowerCase() when (key) { "name" -> name = value "tall" -> tall = value.toInt() "antialias" -> aa = value.toInt() == 1 } } } public val font: Font? get() { val screenRes = Toolkit.getDefaultToolkit().getScreenResolution() val fontSize = Math.round((tall * screenRes).toDouble() / 72.0).toInt() val ge = GraphicsEnvironment.getLocalGraphicsEnvironment() val fontFamilies = ge.getAvailableFontFamilyNames() if (name in fontFamilies) { // System font return Font(name, Font.PLAIN, fontSize) } try { LOG.info { "Loading font: ${fontname}... (${name})}" } fontFileForName(name!!)?.let { ge.registerFont(it) return Font(fontname, Font.PLAIN, fontSize) } } catch (ex: Exception) { LOG.log(Level.SEVERE, { null }, ex) } return null } companion object { private val LOG = Logger() private fun fontFileForName(name: String): Font? { File("").listFiles { dir, name -> name.endsWith(".ttf") // XXX: hardcoded }?.forEach { val f = Font.createFont(Font.TRUETYPE_FONT, it) // System.out.println(f.getFamily().toLowerCase()); if (f.getFamily().equals(name, ignoreCase = true)) { LOG.info { "Found font for ${name}" } return f } } return null } } }
src/main/kotlin/com/timepath/vgui/HudFont.kt
2107610649
package org.ligi.passandroid import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.net.toUri import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.LatLngBounds import com.google.android.gms.maps.model.MarkerOptions import org.koin.android.ext.android.inject import org.ligi.kaxt.startActivityFromClass import org.ligi.passandroid.model.PassStore import org.ligi.passandroid.ui.PassViewActivityBase import kotlin.math.min class LocationsMapFragment : SupportMapFragment() { var clickToFullscreen = false val passStore : PassStore by inject() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val root = super.onCreateView(inflater, container, savedInstanceState) val baseActivity = activity as PassViewActivityBase getMapAsync { map -> map.setOnMapLoadedCallback { if (clickToFullscreen) map.setOnMapClickListener { passStore.currentPass = baseActivity.currentPass baseActivity.startActivityFromClass(FullscreenMapActivity::class.java) } var boundBuilder = LatLngBounds.Builder() val locations = baseActivity.currentPass.locations for (l in locations) { // yea that looks stupid but need to split LatLng free/nonfree - google play services ^^ val latLng = LatLng(l.lat, l.lon) val marker = MarkerOptions().position(latLng).title(l.getNameWithFallback(baseActivity.currentPass)) map.addMarker(marker) boundBuilder = boundBuilder.include(latLng) } map.setOnInfoWindowClickListener { marker -> val i = Intent() i.action = Intent.ACTION_VIEW i.data = ("geo:" + marker.position.latitude + "," + marker.position.longitude + "?q=" + marker.title).toUri() baseActivity.startActivity(i) } map.moveCamera(CameraUpdateFactory.newLatLngBounds(boundBuilder.build(), 100)) // limit zoom-level to 17 - otherwise we could be so zoomed in that it looks buggy map.moveCamera(CameraUpdateFactory.zoomTo(min(17f, map.cameraPosition.zoom))) } } return root } }
android/src/withMaps/java/org/ligi/passandroid/LocationsMapFragment.kt
63706932
package org.wordpress.android.widgets import android.view.View import com.google.android.material.snackbar.Snackbar import dagger.Reusable import javax.inject.Inject /** * Injectable wrapper around WPSnackbar. * * WPSnackbar interfaces are consisted of static methods, which * makes the client code difficult to test/mock. Main purpose of this wrapper is to make testing easier. */ @Reusable class WPSnackbarWrapper @Inject constructor() { fun make(view: View, text: CharSequence, duration: Int): Snackbar = WPSnackbar.make(view, text, duration) }
WordPress/src/main/java/org/wordpress/android/widgets/WPSnackbarWrapper.kt
2923278185
package org.rust.cargo.project.model /** * This class is merely a wrapper of the metadata for the project extracted * out of `Cargo.toml` * * NOTE: * Params are named accordingly to the output of the `cargo metadata` * therefore should stay consistent, and remain in snake-form */ data class CargoProjectInfo( val root: CargoPackageRoot, val packages: List<CargoPackageInfo> )
src/main/kotlin/org/rust/cargo/project/model/CargoProjectInfo.kt
1419170912
package forpdateam.ru.forpda.model.repository.search import forpdateam.ru.forpda.entity.remote.others.user.ForumUser import forpdateam.ru.forpda.entity.remote.search.SearchResult import forpdateam.ru.forpda.entity.remote.search.SearchSettings import forpdateam.ru.forpda.model.SchedulersProvider import forpdateam.ru.forpda.model.data.cache.forumuser.ForumUsersCache import forpdateam.ru.forpda.model.data.remote.api.search.SearchApi import forpdateam.ru.forpda.model.repository.BaseRepository import io.reactivex.Observable import io.reactivex.Single /** * Created by radiationx on 01.01.18. */ class SearchRepository( private val schedulers: SchedulersProvider, private val searchApi: SearchApi, private val forumUsersCache: ForumUsersCache ) : BaseRepository(schedulers) { fun getSearch(settings: SearchSettings): Single<SearchResult> = Single .fromCallable { searchApi.getSearch(settings) } .doOnSuccess { saveUsers(it) } .runInIoToUi() private fun saveUsers(page: SearchResult) { val forumUsers = page.items.map { post -> ForumUser().apply { id = post.userId nick = post.nick avatar = post.avatar } } forumUsersCache.saveUsers(forumUsers) } }
app/src/main/java/forpdateam/ru/forpda/model/repository/search/SearchRepository.kt
3641884918
package com.firebase.hackweek.tank18thscale.data import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.firebase.hackweek.tank18thscale.model.DeviceInfo class BluetoothDeviceList { private val devices = mutableSetOf<DeviceInfo>() private val devicesLiveData = MutableLiveData<List<DeviceInfo>>() val liveData : LiveData<List<DeviceInfo>> get() = devicesLiveData fun addDevice(device : DeviceInfo) { devices.add(device) devicesLiveData.postValue(devices.toList().sortedBy { it.name }) } // TODO: Remove devices too }
app/src/main/java/com/firebase/hackweek/tank18thscale/data/BluetoothDeviceList.kt
912411281
package org.rust.ide.formatter import com.intellij.psi.formatter.FormatterTestCase import org.rust.lang.RustTestCaseBase class RustFormatterTestCase : FormatterTestCase() { override fun getTestDataPath() = "src/test/resources" override fun getBasePath() = "org/rust/ide/formatter/fixtures" override fun getFileExtension() = "rs" override fun getTestName(lowercaseFirstLetter: Boolean): String? { val camelCase = super.getTestName(lowercaseFirstLetter) return RustTestCaseBase.camelToSnake(camelCase) } fun testBlocks() = doTest() fun testItems() = doTest() fun testExpressions() = doTest() fun testArgumentAlignment() = doTest() fun testArgumentIndent() = doTest() fun testTraits() = doTest() }
src/test/kotlin/org/rust/ide/formatter/RustFormatterTestCase.kt
2024959374
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.move.changePackage import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.codeInsight.template.* import com.intellij.codeInsight.template.impl.TemplateState import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.quoteSegmentsIfNeeded import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.idea.refactoring.hasIdentifiersOnly import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqNameUnsafe import org.jetbrains.kotlin.psi.KtPackageDirective class ChangePackageIntention : SelfTargetingOffsetIndependentIntention<KtPackageDirective>( KtPackageDirective::class.java, KotlinBundle.lazyMessage("intention.change.package.text") ) { companion object { private const val PACKAGE_NAME_VAR = "PACKAGE_NAME" } override fun isApplicableTo(element: KtPackageDirective) = element.packageNameExpression != null override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { // Rename template only intention: no reasonable preview possible return IntentionPreviewInfo.EMPTY } override fun applyTo(element: KtPackageDirective, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val file = element.containingKtFile val project = file.project val nameExpression = element.packageNameExpression!! val currentName = element.qualifiedName val builder = TemplateBuilderImpl(file) builder.replaceElement( nameExpression, PACKAGE_NAME_VAR, object : Expression() { override fun calculateQuickResult(context: ExpressionContext?) = TextResult(currentName) override fun calculateResult(context: ExpressionContext?) = TextResult(currentName) override fun calculateLookupItems(context: ExpressionContext?) = arrayOf(LookupElementBuilder.create(currentName)) }, true ) var enteredName: String? = null var affectedRange: TextRange? = null editor.caretModel.moveToOffset(0) TemplateManager.getInstance(project).startTemplate( editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() { override fun beforeTemplateFinished(state: TemplateState, template: Template?) { enteredName = state.getVariableValue(PACKAGE_NAME_VAR)!!.text affectedRange = state.getSegmentRange(0) } override fun templateFinished(template: Template, brokenOff: Boolean) { if (brokenOff) return val name = enteredName ?: return val range = affectedRange ?: return // Restore original name and run refactoring val document = editor.document project.executeWriteCommand(text) { document.replaceString( range.startOffset, range.endOffset, FqName(currentName).quoteSegmentsIfNeeded() ) } PsiDocumentManager.getInstance(project).commitDocument(document) PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document) if (!FqNameUnsafe(name).hasIdentifiersOnly()) { KotlinSurrounderUtils.showErrorHint( project, editor, KotlinBundle.message("text.0.is.not.valid.package.name", name), KotlinBundle.message("intention.change.package.text"), null ) return } KotlinChangePackageRefactoring(file).run(FqName(name)) } } ) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/changePackage/ChangePackageIntention.kt
3093743042
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.ui import com.intellij.ide.ui.UISettings import com.intellij.openapi.components.* import com.intellij.openapi.project.Project class BookmarksViewState : BaseState() { companion object { @JvmStatic fun getInstance(project: Project) = project.getService(BookmarksViewStateComponent::class.java).state } var proportionPopup by property(0.3f) var proportionView by property(0.5f) var groupLineBookmarks by property(true) var rewriteBookmarkType by property(false) var askBeforeDeletingLists by property(true) var autoscrollFromSource by property(false) var autoscrollToSource by property(false) var showPreview by property(false) } @State(name = "BookmarksViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))]) internal class BookmarksViewStateComponent : SimplePersistentStateComponent<BookmarksViewState>(BookmarksViewState()) { override fun noStateLoaded() { state.autoscrollToSource = UISettings.getInstance().state.defaultAutoScrollToSource } }
platform/lang-impl/src/com/intellij/ide/bookmark/ui/BookmarksViewState.kt
571583480
package dev.mfazio.abl import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.NavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import androidx.preference.PreferenceManager import dev.mfazio.abl.databinding.ActivityMainBinding import dev.mfazio.abl.settings.SettingsFragment import dev.mfazio.abl.settings.getSelectedStartingScreen import dev.mfazio.abl.teams.UITeam class MainActivity : AppCompatActivity() { private lateinit var navController: NavController private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val prefs = PreferenceManager.getDefaultSharedPreferences(this) val navHostFragment = supportFragmentManager.findFragmentById(R.id.containerFragment) as NavHostFragment this.navController = navHostFragment.navController val navGraph = navController.navInflater.inflate(R.navigation.nav_graph) navGraph.startDestination = getSelectedStartingScreen(prefs) navController.graph = navGraph binding.navView.setupWithNavController(this.navController) this.appBarConfiguration = AppBarConfiguration(binding.navView.menu, binding.drawerLayout) setupActionBarWithNavController(this.navController, appBarConfiguration) if (prefs.getBoolean(SettingsFragment.favoriteTeamColorsPreferenceKey, false)) { UITeam.getTeamPalette( this, prefs.getString(SettingsFragment.favoriteTeamPreferenceKey, null) )?.dominantSwatch?.rgb?.let { window.navigationBarColor = it } } } override fun onSupportNavigateUp(): Boolean = (this::navController.isInitialized && this.navController.navigateUp(this.appBarConfiguration) ) || super.onSupportNavigateUp() }
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-12/app-code/app/src/main/java/dev/mfazio/abl/MainActivity.kt
2787871071
package rs.emulate.scene3d.backend.opengl.bindings import org.joml.* import org.lwjgl.BufferUtils import org.lwjgl.opengl.GL20.* import rs.emulate.scene3d.backend.opengl.bindings.util.glmType import rs.emulate.scene3d.buffer.GeometryDataBuffer import kotlin.reflect.KClass /** * A high-level representation of a compiled and linked OpenGL shader program. * * @param id The unique ID of the shader program returned by OpenGL. * @param uniformTypes A mapping of uniform names to the index they occur at. * @param uniformBuffers A mapping of uniform locations to th buffers representing them. */ class OpenGLShaderProgram( private val id: Int, val attributeLocations: Map<String, Int>, val attributeTypes: Map<String, KClass<out Any>>, private val uniformBuffers: Map<String, GeometryDataBuffer<out Any>>, private val uniformLocations: Map<String, Int> ) { /** * Bind this shader program as active and bind the [uniforms] to * their respective locations. */ fun bind(vararg uniforms: Pair<String, Any>) { glUseProgram(id) for ((name, value) in uniforms) { val location = uniformLocations[name] ?: throw IllegalArgumentException("No uniform named ${name}") val data = uniformBuffers[name] as GeometryDataBuffer<Any> data.set(value) val buffer = data.buffer.asFloatBuffer() buffer.position(0) when (value) { is Vector2f -> glUniform2fv(location, buffer) is Vector3f -> glUniform3fv(location, buffer) is Vector4f -> glUniform4fv(location, buffer) // is Matrix -> glUniformMatrix2fv(location, false, buffer) is Matrix3f -> glUniformMatrix3fv(location, false, buffer) is Matrix4f -> glUniformMatrix4fv(location, false, buffer) } } glValidateProgram(id) if (glGetProgrami(id, GL_VALIDATE_STATUS) <= 0) { throw RuntimeException("Failed to validate program: ${glGetProgramInfoLog(id)}, error: ${glGetError()}") } } fun dispose() { glDeleteProgram(id) } companion object { fun create(vararg modules: OpenGLShaderModule): OpenGLShaderProgram { val id = glCreateProgram() val attributeLocations = mutableMapOf<String, Int>() val attributeTypes = mutableMapOf<String, KClass<out Any>>() val uniformBuffers = mutableMapOf<String, GeometryDataBuffer<out Any>>() val uniformLocations = mutableMapOf<String, Int>() modules.forEach { glAttachShader(id, it.id) } glLinkProgram(id) if (glGetProgrami(id, GL_LINK_STATUS) <= 0) { throw RuntimeException("Failed to link program: ${glGetProgramInfoLog(id)}") } val typeBuffer = BufferUtils.createIntBuffer(1) val sizeBuffer = BufferUtils.createIntBuffer(1) val attributesLength = glGetProgrami(id, GL_ACTIVE_ATTRIBUTES) for (attributeOffset in 0 until attributesLength) { val name = glGetActiveAttrib(id, attributeOffset, sizeBuffer, typeBuffer) val loc = glGetAttribLocation(id, name) attributeLocations[name] = loc attributeTypes[name] = glmType(typeBuffer[0]) } val uniformsLength = glGetProgrami(id, GL_ACTIVE_UNIFORMS); for (uniformOffset in 0 until uniformsLength) { val name = glGetActiveUniform(id, uniformOffset, sizeBuffer, typeBuffer) val loc = glGetUniformLocation(id, name) val type = glmType(typeBuffer[0]) val size = sizeBuffer[0] if (size > 1) { throw IllegalStateException("Uniform arrays are currently unsupported") } val buffer = GeometryDataBuffer.create(type) uniformLocations[name] = loc uniformBuffers[name] = buffer } return OpenGLShaderProgram( id, attributeLocations, attributeTypes, uniformBuffers, uniformLocations ) } } }
scene3d/src/main/kotlin/rs/emulate/scene3d/backend/opengl/bindings/OpenGLShaderProgram.kt
1212134847
package rs.emulate.legacy.widget.script /** * A ClientScript from legacy client builds (widely known as CS1). * * Unlike CS2, legacy client scripts operate using a simple accumulator machine, with four registers: * - The register holding the program counter, which points to the next instruction to interpret. * - The operator register, containing the type of operator that should be evaluated by the next instruction. * - The value register, containing the current value of the ClientScript. * - The accumulator register, which contains the result of the evaluation of the current instruction, and will modify * the current value stored in the value register using the operator type held in the operator register. * * @param operator The [RelationalOperator] used to evaluate if the script state has changed. * @param default The default value of the clientscript. * @param instructions The [List] of [LegacyInstruction]s that make up this clientscript. */ class LegacyClientScript internal constructor( val operator: RelationalOperator, val default: Int, instructions: List<LegacyInstruction> ) { val instructions: List<LegacyInstruction> = instructions.toList() override fun toString(): String { return instructions.joinToString("\n", transform = LegacyInstruction::toString) } }
legacy/src/main/kotlin/rs/emulate/legacy/widget/script/LegacyClientScript.kt
2147610439
/* * Copyright 2016 * * 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.acra.collector import android.content.Context import android.os.Build import com.google.auto.service.AutoService import org.acra.ReportField import org.acra.builder.ReportBuilder import org.acra.config.CoreConfiguration import org.acra.data.CrashReportData import org.acra.util.Installation.id import java.net.NetworkInterface import java.net.SocketException import java.util.* /** * Collects various simple values * * @author F43nd1r * @since 4.9.1 */ @AutoService(Collector::class) class SimpleValuesCollector : BaseReportFieldCollector(ReportField.IS_SILENT, ReportField.REPORT_ID, ReportField.INSTALLATION_ID, ReportField.PACKAGE_NAME, ReportField.PHONE_MODEL, ReportField.ANDROID_VERSION, ReportField.BRAND, ReportField.PRODUCT, ReportField.FILE_PATH, ReportField.USER_IP) { @Throws(Exception::class) override fun collect(reportField: ReportField, context: Context, config: CoreConfiguration, reportBuilder: ReportBuilder, target: CrashReportData) { when (reportField) { ReportField.IS_SILENT -> target.put(ReportField.IS_SILENT, reportBuilder.isSendSilently) ReportField.REPORT_ID -> target.put(ReportField.REPORT_ID, UUID.randomUUID().toString()) ReportField.INSTALLATION_ID -> target.put(ReportField.INSTALLATION_ID, id(context)) ReportField.PACKAGE_NAME -> target.put(ReportField.PACKAGE_NAME, context.packageName) ReportField.PHONE_MODEL -> target.put(ReportField.PHONE_MODEL, Build.MODEL) ReportField.ANDROID_VERSION -> target.put(ReportField.ANDROID_VERSION, Build.VERSION.RELEASE) ReportField.BRAND -> target.put(ReportField.BRAND, Build.BRAND) ReportField.PRODUCT -> target.put(ReportField.PRODUCT, Build.PRODUCT) ReportField.FILE_PATH -> target.put(ReportField.FILE_PATH, getApplicationFilePath(context)) ReportField.USER_IP -> target.put(ReportField.USER_IP, getLocalIpAddress()) else -> throw IllegalArgumentException() } } override fun shouldCollect(context: Context, config: CoreConfiguration, collect: ReportField, reportBuilder: ReportBuilder): Boolean { return collect == ReportField.IS_SILENT || collect == ReportField.REPORT_ID || super.shouldCollect(context, config, collect, reportBuilder) } private fun getApplicationFilePath(context: Context): String { return context.filesDir.absolutePath } companion object { @Throws(SocketException::class) private fun getLocalIpAddress(): String { val result = StringBuilder() var first = true val en = NetworkInterface.getNetworkInterfaces() while (en.hasMoreElements()) { val intf = en.nextElement() val enumIpAddr = intf.inetAddresses while (enumIpAddr.hasMoreElements()) { val inetAddress = enumIpAddr.nextElement() if (!inetAddress.isLoopbackAddress) { if (!first) { result.append('\n') } result.append(inetAddress.hostAddress) first = false } } } return result.toString() } } }
acra-core/src/main/java/org/acra/collector/SimpleValuesCollector.kt
1478911183
package io.ipoli.android.quest.show.usecase import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import io.ipoli.android.TestUtil import io.ipoli.android.quest.Quest import io.ipoli.android.quest.TimeRange import io.ipoli.android.quest.data.persistence.QuestRepository import io.ipoli.android.quest.show.job.TimerCompleteScheduler import io.ipoli.android.quest.show.pomodoros import org.amshove.kluent.`should be false` import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.threeten.bp.Instant /** * Created by Polina Zhelyazkova <polina@mypoli.fun> * on 1/18/18. */ class CancelTimerUseCaseSpek : Spek({ describe("CancelTimerUseCase") { fun executeUseCase( quest: Quest ): Quest { val questRepoMock = mock<QuestRepository> { on { findById(any()) } doReturn quest on { save(any<Quest>()) } doAnswer { invocation -> invocation.getArgument(0) } } return CancelTimerUseCase(questRepoMock, mock(), mock()) .execute(CancelTimerUseCase.Params(quest.id)) } val simpleQuest = TestUtil.quest it("should cancel count down") { val result = executeUseCase( simpleQuest.copy( timeRanges = listOf( TimeRange( TimeRange.Type.COUNTDOWN, simpleQuest.duration, start = Instant.now(), end = null ) ) ) ) result.hasCountDownTimer.`should be false`() } it("should cancel current pomodoro") { val result = executeUseCase( simpleQuest.copy( timeRanges = listOf( TimeRange( TimeRange.Type.POMODORO_WORK, 1.pomodoros(), start = Instant.now(), end = null ) ) ) ) result.hasPomodoroTimer.`should be false`() } } })
app/src/test/java/io/ipoli/android/quest/show/usecase/CancelTimerUseCaseSpek.kt
4265547485
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sweers.catchup.service.api import io.reactivex.rxjava3.core.Single interface Service { fun meta(): ServiceMeta fun fetchPage(request: DataRequest): Single<DataResult> fun bindItemView( item: CatchUpItem, holder: BindableCatchUpItemViewHolder, clicksReceiver: (UrlMeta) -> Boolean, markClicksReceiver: (UrlMeta) -> Boolean, longClicksReceiver: (UrlMeta) -> Boolean ) fun rootService(): Service = this }
service-api/src/main/kotlin/io/sweers/catchup/service/api/Service.kt
346021693
package com.phicdy.totoanticipation.advertisement import android.view.View import androidx.recyclerview.widget.RecyclerView abstract class AdViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind() }
android/advertisement/src/main/java/com/phicdy/totoanticipation/advertisement/AdViewHolder.kt
2971201029
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("BlockingMethodInNonBlockingContext") package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.use import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.diagnostic.telemetry.useWithScope2 import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.NioFiles import com.intellij.openapi.util.text.Formats import com.intellij.util.io.Decompressor import com.intellij.util.io.ZipUtil import com.intellij.util.system.CpuArch import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.* import org.apache.commons.compress.archivers.zip.Zip64Mode import org.apache.commons.compress.archivers.zip.ZipArchiveEntry import org.jetbrains.idea.maven.aether.ArtifactKind import org.jetbrains.idea.maven.aether.ArtifactRepositoryManager import org.jetbrains.idea.maven.aether.ProgressConsumer import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.impl.productInfo.ProductInfoLaunchData import org.jetbrains.intellij.build.impl.productInfo.checkInArchive import org.jetbrains.intellij.build.impl.productInfo.generateMultiPlatformProductJson import org.jetbrains.intellij.build.impl.projectStructureMapping.DistributionFileEntry import org.jetbrains.intellij.build.impl.projectStructureMapping.includedModules import org.jetbrains.intellij.build.impl.projectStructureMapping.writeProjectStructureReport import org.jetbrains.intellij.build.io.copyDir import org.jetbrains.intellij.build.io.writeNewFile import org.jetbrains.intellij.build.io.zipWithCompression import org.jetbrains.intellij.build.tasks.* import org.jetbrains.jps.model.JpsGlobal import org.jetbrains.jps.model.JpsSimpleElement import org.jetbrains.jps.model.artifact.JpsArtifactService import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryService import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.library.* import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.util.JpsPathUtil import java.io.FileOutputStream import java.nio.file.FileSystems import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.nio.file.attribute.DosFileAttributeView import java.nio.file.attribute.PosixFilePermission import java.util.* import java.util.function.Predicate import java.util.stream.Collectors import java.util.zip.ZipOutputStream class BuildTasksImpl(context: BuildContext) : BuildTasks { private val context = context as BuildContextImpl override suspend fun zipSourcesOfModules(modules: List<String>, targetFile: Path, includeLibraries: Boolean) { zipSourcesOfModules(modules = modules, targetFile = targetFile, includeLibraries = includeLibraries, context = context) } override suspend fun compileModulesFromProduct() { checkProductProperties(context) compileModulesForDistribution(context) } override suspend fun buildDistributions() { buildDistributions(context) } override suspend fun buildDmg(macZipDir: Path) { supervisorScope { sequenceOf(JvmArchitecture.x64, JvmArchitecture.aarch64) .map { arch -> val macZip = find(directory = macZipDir, suffix = "${arch}.zip", context = context) val builtModule = readBuiltinModulesFile(find(directory = macZipDir, suffix = "builtinModules.json", context = context)) async { MacDistributionBuilder(context = context, customizer = context.macDistributionCustomizer!!, ideaProperties = null).buildAndSignDmgFromZip(macZip = macZip, macZipWithoutRuntime = null, arch = arch, builtinModule = builtModule) } } .toList() }.collectCompletedOrError() } override suspend fun buildNonBundledPlugins(mainPluginModules: List<String>) { checkProductProperties(context) checkPluginModules(mainPluginModules, "mainPluginModules", context) copyDependenciesFile(context) val pluginsToPublish = getPluginLayoutsByJpsModuleNames(mainPluginModules, context.productProperties.productLayout) val distributionJARsBuilder = DistributionJARsBuilder(compilePlatformAndPluginModules(pluginsToPublish, context)) distributionJARsBuilder.buildSearchableOptions(context) distributionJARsBuilder.buildNonBundledPlugins(pluginsToPublish = pluginsToPublish, compressPluginArchive = context.options.compressZipFiles, buildPlatformLibJob = null, context = context) } override fun compileProjectAndTests(includingTestsInModules: List<String>) { compileModules(null, includingTestsInModules) } override fun compileModules(moduleNames: Collection<String>?, includingTestsInModules: List<String>) { CompilationTasks.create(context).compileModules(moduleNames, includingTestsInModules) } override fun compileModules(moduleNames: Collection<String>?) { CompilationTasks.create(context).compileModules(moduleNames) } override fun buildFullUpdaterJar() { buildUpdaterJar(context, "updater-full.jar") } override suspend fun buildUnpackedDistribution(targetDirectory: Path, includeBinAndRuntime: Boolean) { val currentOs = OsFamily.currentOs context.paths.distAllDir = targetDirectory context.options.targetOs = persistentListOf(currentOs) context.options.buildStepsToSkip.add(BuildOptions.GENERATE_JAR_ORDER_STEP) BundledMavenDownloader.downloadMavenCommonLibs(context.paths.communityHomeDirRoot) BundledMavenDownloader.downloadMavenDistribution(context.paths.communityHomeDirRoot) DistributionJARsBuilder(compileModulesForDistribution(context)).buildJARs(context = context, isUpdateFromSources = true) val arch = if (SystemInfo.isMac && CpuArch.isIntel64() && CpuArch.isEmulated()) { JvmArchitecture.aarch64 } else { JvmArchitecture.currentJvmArch } layoutShared(context) if (includeBinAndRuntime) { val propertiesFile = patchIdeaPropertiesFile(context) val builder = getOsDistributionBuilder(os = currentOs, ideaProperties = propertiesFile, context = context)!! builder.copyFilesForOsDistribution(targetDirectory, arch) context.bundledRuntime.extractTo(prefix = BundledRuntimeImpl.getProductPrefix(context), os = currentOs, destinationDir = targetDirectory.resolve("jbr"), arch = arch) updateExecutablePermissions(targetDirectory, builder.generateExecutableFilesPatterns(true)) builder.checkExecutablePermissions(targetDirectory, root = "") } else { copyDistFiles(context = context, newDir = targetDirectory, os = currentOs, arch = arch) } } } /** * Generates a JSON file containing mapping between files in the product distribution and modules and libraries in the project configuration */ suspend fun generateProjectStructureMapping(targetFile: Path, context: BuildContext) { val pluginLayoutRoot = withContext(Dispatchers.IO) { Files.createDirectories(context.paths.tempDir) Files.createTempDirectory(context.paths.tempDir, "pluginLayoutRoot") } writeProjectStructureReport( entries = generateProjectStructureMapping(context = context, state = DistributionBuilderState(pluginsToPublish = emptySet(), context = context), pluginLayoutRoot = pluginLayoutRoot), file = targetFile, buildPaths = context.paths ) } data class SupportedDistribution(@JvmField val os: OsFamily, @JvmField val arch: JvmArchitecture) @JvmField val SUPPORTED_DISTRIBUTIONS: PersistentList<SupportedDistribution> = persistentListOf( SupportedDistribution(os = OsFamily.MACOS, arch = JvmArchitecture.x64), SupportedDistribution(os = OsFamily.MACOS, arch = JvmArchitecture.aarch64), SupportedDistribution(os = OsFamily.WINDOWS, arch = JvmArchitecture.x64), SupportedDistribution(os = OsFamily.WINDOWS, arch = JvmArchitecture.aarch64), SupportedDistribution(os = OsFamily.LINUX, arch = JvmArchitecture.x64), SupportedDistribution(os = OsFamily.LINUX, arch = JvmArchitecture.aarch64), ) private fun isSourceFile(path: String): Boolean { return path.endsWith(".java") || path.endsWith(".groovy") || path.endsWith(".kt") } private fun getLocalArtifactRepositoryRoot(global: JpsGlobal): Path { JpsModelSerializationDataService.getPathVariablesConfiguration(global)!!.getUserVariableValue("MAVEN_REPOSITORY")?.let { return Path.of(it) } val root = System.getProperty("user.home", null) return if (root == null) Path.of(".m2/repository") else Path.of(root, ".m2/repository") } /** * Building a list of modules that the IDE will provide for plugins. */ private suspend fun buildProvidedModuleList(targetFile: Path, state: DistributionBuilderState, context: BuildContext) { context.executeStep(spanBuilder("build provided module list"), BuildOptions.PROVIDED_MODULES_LIST_STEP) { withContext(Dispatchers.IO) { Files.deleteIfExists(targetFile) val ideClasspath = DistributionJARsBuilder(state).createIdeClassPath(context) // start the product in headless mode using com.intellij.ide.plugins.BundledPluginsLister runApplicationStarter(context = context, tempDir = context.paths.tempDir.resolve("builtinModules"), ideClasspath = ideClasspath, arguments = listOf("listBundledPlugins", targetFile.toString())) check(Files.exists(targetFile)) { "Failed to build provided modules list: $targetFile doesn\'t exist" } } context.productProperties.customizeBuiltinModules(context, targetFile) context.builtinModule = readBuiltinModulesFile(targetFile) context.notifyArtifactWasBuilt(targetFile) } } private fun patchIdeaPropertiesFile(buildContext: BuildContext): Path { val builder = StringBuilder(Files.readString(buildContext.paths.communityHomeDir.resolve("bin/idea.properties"))) for (it in buildContext.productProperties.additionalIDEPropertiesFilePaths) { builder.append('\n').append(Files.readString(it)) } //todo[nik] introduce special systemSelectorWithoutVersion instead? val settingsDir = buildContext.systemSelector.replaceFirst("\\d+(\\.\\d+)?".toRegex(), "") val temp = builder.toString() builder.setLength(0) val map = LinkedHashMap<String, String>(1) map["settings_dir"] = settingsDir builder.append(BuildUtils.replaceAll(temp, map, "@@")) if (buildContext.applicationInfo.isEAP) { builder.append( "\n#-----------------------------------------------------------------------\n" + "# Change to 'disabled' if you don't want to receive instant visual notifications\n" + "# about fatal errors that happen to an IDE or plugins installed.\n" + "#-----------------------------------------------------------------------\n" + "idea.fatal.error.notification=enabled\n") } else { builder.append( "\n#-----------------------------------------------------------------------\n" + "# Change to 'enabled' if you want to receive instant visual notifications\n" + "# about fatal errors that happen to an IDE or plugins installed.\n" + "#-----------------------------------------------------------------------\n" + "idea.fatal.error.notification=disabled\n") } val propertiesFile = buildContext.paths.tempDir.resolve("idea.properties") Files.writeString(propertiesFile, builder) return propertiesFile } private suspend fun layoutShared(context: BuildContext) { spanBuilder("copy files shared among all distributions").useWithScope2 { val licenseOutDir = context.paths.distAllDir.resolve("license") withContext(Dispatchers.IO) { copyDir(context.paths.communityHomeDir.resolve("license"), licenseOutDir) for (additionalDirWithLicenses in context.productProperties.additionalDirectoriesWithLicenses) { copyDir(additionalDirWithLicenses, licenseOutDir) } context.applicationInfo.svgRelativePath?.let { svgRelativePath -> val from = findBrandingResource(svgRelativePath, context) val to = context.paths.distAllDir.resolve("bin/${context.productProperties.baseFileName}.svg") Files.createDirectories(to.parent) Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) } context.productProperties.copyAdditionalFiles(context, context.paths.getDistAll()) } } } private fun findBrandingResource(relativePath: String, context: BuildContext): Path { val normalizedRelativePath = relativePath.removePrefix("/") val inModule = context.findFileInModuleSources(context.productProperties.applicationInfoModule, normalizedRelativePath) if (inModule != null) { return inModule } for (brandingResourceDir in context.productProperties.brandingResourcePaths) { val file = brandingResourceDir.resolve(normalizedRelativePath) if (Files.exists(file)) { return file } } throw RuntimeException("Cannot find \'$normalizedRelativePath\' " + "neither in sources of \'${context.productProperties.applicationInfoModule}\' " + "nor in ${context.productProperties.brandingResourcePaths}") } internal fun updateExecutablePermissions(destinationDir: Path, executableFilesPatterns: List<String>) { val executable = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE) val regular = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_READ, PosixFilePermission.OTHERS_READ) val executableFilesMatchers = executableFilesPatterns.map { FileSystems.getDefault().getPathMatcher("glob:$it") } Files.walk(destinationDir).use { stream -> for (file in stream) { if (Files.isDirectory(file)) { continue } if (SystemInfoRt.isUnix) { val relativeFile = destinationDir.relativize(file) val isExecutable = Files.getPosixFilePermissions(file).contains(PosixFilePermission.OWNER_EXECUTE) || executableFilesMatchers.any { it.matches(relativeFile) } Files.setPosixFilePermissions(file, if (isExecutable) executable else regular) } else { (Files.getFileAttributeView(file, DosFileAttributeView::class.java) as DosFileAttributeView).setReadOnly(false) } } } } private fun downloadMissingLibrarySources( librariesWithMissingSources: List<JpsTypedLibrary<JpsSimpleElement<JpsMavenRepositoryLibraryDescriptor>>>, context: BuildContext, ) { spanBuilder("download missing sources") .setAttribute(AttributeKey.stringArrayKey("librariesWithMissingSources"), librariesWithMissingSources.map { it.name }) .use { span -> val configuration = JpsRemoteRepositoryService.getInstance().getRemoteRepositoriesConfiguration(context.project) val repositories = configuration?.repositories?.map { ArtifactRepositoryManager.createRemoteRepository(it.id, it.url) } ?: emptyList() val repositoryManager = ArtifactRepositoryManager(getLocalArtifactRepositoryRoot(context.projectModel.global).toFile(), repositories, ProgressConsumer.DEAF) for (library in librariesWithMissingSources) { val descriptor = library.properties.data span.addEvent("downloading sources for library", Attributes.of( AttributeKey.stringKey("name"), library.name, AttributeKey.stringKey("mavenId"), descriptor.mavenId, )) val downloaded = repositoryManager.resolveDependencyAsArtifact(descriptor.groupId, descriptor.artifactId, descriptor.version, EnumSet.of(ArtifactKind.SOURCES), descriptor.isIncludeTransitiveDependencies, descriptor.excludedDependencies) span.addEvent("downloaded sources for library", Attributes.of( AttributeKey.stringArrayKey("artifacts"), downloaded.map { it.toString() }, )) } } } private class DistributionForOsTaskResult(@JvmField val builder: OsSpecificDistributionBuilder, @JvmField val arch: JvmArchitecture, @JvmField val outDir: Path) private fun find(directory: Path, suffix: String, context: BuildContext): Path { Files.walk(directory).use { stream -> val found = stream.filter { (it.fileName.toString()).endsWith(suffix) }.collect(Collectors.toList()) if (found.isEmpty()) { context.messages.error("No file with suffix $suffix is found in $directory") } if (found.size > 1) { context.messages.error("Multiple files with suffix $suffix are found in $directory:\n${found.joinToString(separator = "\n")}") } return found.first() } } private suspend fun buildOsSpecificDistributions(context: BuildContext): List<DistributionForOsTaskResult> { val stepMessage = "build OS-specific distributions" if (context.options.buildStepsToSkip.contains(BuildOptions.OS_SPECIFIC_DISTRIBUTIONS_STEP)) { Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage)) return emptyList() } val propertiesFile = patchIdeaPropertiesFile(context) return supervisorScope { SUPPORTED_DISTRIBUTIONS.mapNotNull { (os, arch) -> if (!context.shouldBuildDistributionForOS(os, arch)) { return@mapNotNull null } val builder = getOsDistributionBuilder(os = os, ideaProperties = propertiesFile, context = context) ?: return@mapNotNull null val stepId = "${os.osId} ${arch.name}" if (context.options.buildStepsToSkip.contains(stepId)) { Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("id"), stepId)) return@mapNotNull null } async { spanBuilder(stepId).useWithScope2 { val osAndArchSpecificDistDirectory = getOsAndArchSpecificDistDirectory(os, arch, context) builder.buildArtifacts(osAndArchSpecificDistDirectory, arch) DistributionForOsTaskResult(builder, arch, osAndArchSpecificDistDirectory) } } } }.collectCompletedOrError() } // call only after supervisorScope private fun <T> List<Deferred<T>>.collectCompletedOrError(): List<T> { var error: Throwable? = null for (deferred in this) { val e = deferred.getCompletionExceptionOrNull() ?: continue if (error == null) { error = e } else { error.addSuppressed(e) } } error?.let { throw it } return map { it.getCompleted() } } private fun copyDependenciesFile(context: BuildContext): Path { val outputFile = context.paths.artifactDir.resolve("dependencies.txt") Files.createDirectories(outputFile.parent) context.dependenciesProperties.copy(outputFile) context.notifyArtifactWasBuilt(outputFile) return outputFile } private fun checkProjectLibraries(names: Collection<String>, fieldName: String, context: BuildContext) { val unknownLibraries = names.filter { context.project.libraryCollection.findLibrary(it) == null } if (!unknownLibraries.isEmpty()) { context.messages.error("The following libraries from $fieldName aren\'t found in the project: $unknownLibraries") } } private suspend fun buildSourcesArchive(entries: List<DistributionFileEntry>, context: BuildContext) { val productProperties = context.productProperties val archiveName = "${productProperties.getBaseArtifactName(context.applicationInfo, context.buildNumber)}-sources.zip" val modulesFromCommunity = entries.includedModules.filter { moduleName -> productProperties.includeIntoSourcesArchiveFilter.test(context.findRequiredModule(moduleName), context) }.toList() zipSourcesOfModules(modules = modulesFromCommunity, targetFile = context.paths.artifactDir.resolve(archiveName), includeLibraries = true, context = context) } suspend fun zipSourcesOfModules(modules: List<String>, targetFile: Path, includeLibraries: Boolean, context: BuildContext) { context.executeStep(spanBuilder("build module sources archives") .setAttribute("path", context.paths.buildOutputDir.toString()) .setAttribute(AttributeKey.stringArrayKey("modules"), modules), BuildOptions.SOURCES_ARCHIVE_STEP) { withContext(Dispatchers.IO) { Files.createDirectories(targetFile.parent) Files.deleteIfExists(targetFile) } val includedLibraries = LinkedHashSet<JpsLibrary>() if (includeLibraries) { val debugMapping = mutableListOf<String>() for (moduleName in modules) { val module = context.findRequiredModule(moduleName) if (moduleName.startsWith("intellij.platform.") && context.findModule("$moduleName.impl") != null) { val libraries = JpsJavaExtensionService.dependencies(module).productionOnly().compileOnly().recursivelyExportedOnly().libraries includedLibraries.addAll(libraries) libraries.mapTo(debugMapping) { "${it.name} for $moduleName" } } } Span.current().addEvent("collect libraries to include into archive", Attributes.of(AttributeKey.stringArrayKey("mapping"), debugMapping)) val librariesWithMissingSources = includedLibraries .asSequence() .map { it.asTyped(JpsRepositoryLibraryType.INSTANCE) } .filterNotNull() .filter { library -> library.getFiles(JpsOrderRootType.SOURCES).any { Files.notExists(it.toPath()) } } .toList() if (!librariesWithMissingSources.isEmpty()) { withContext(Dispatchers.IO) { downloadMissingLibrarySources(librariesWithMissingSources, context) } } } val zipFileMap = LinkedHashMap<Path, String>() for (moduleName in modules) { val module = context.findRequiredModule(moduleName) for (root in module.getSourceRoots(JavaSourceRootType.SOURCE)) { if (root.file.absoluteFile.exists()) { val sourceFiles = filterSourceFilesOnly(root.file.name, context) { FileUtil.copyDirContent(root.file.absoluteFile, it.toFile()) } zipFileMap[sourceFiles] = root.properties.packagePrefix.replace(".", "/") } } for (root in module.getSourceRoots(JavaResourceRootType.RESOURCE)) { if (root.file.absoluteFile.exists()) { val sourceFiles = filterSourceFilesOnly(root.file.name, context) { FileUtil.copyDirContent(root.file.absoluteFile, it.toFile()) } zipFileMap[sourceFiles] = root.properties.relativeOutputPath } } } val libraryRootUrls = includedLibraries.flatMap { it.getRootUrls(JpsOrderRootType.SOURCES) } context.messages.debug(" include ${libraryRootUrls.size} roots from ${includedLibraries.size} libraries:") for (url in libraryRootUrls) { if (url.startsWith(JpsPathUtil.JAR_URL_PREFIX) && url.endsWith(JpsPathUtil.JAR_SEPARATOR)) { val file = JpsPathUtil.urlToFile(url).absoluteFile if (file.isFile) { context.messages.debug(" $file, ${Formats.formatFileSize(file.length())}, ${file.length().toString().padEnd(9, '0')} bytes") val sourceFiles = filterSourceFilesOnly(file.name, context) { tempDir -> Decompressor.Zip(file).filter(Predicate { isSourceFile(it) }).extract(tempDir) } zipFileMap[sourceFiles] = "" } else { context.messages.debug(" skipped root $file: file doesn\'t exist") } } else { context.messages.debug(" skipped root $url: not a jar file") } } spanBuilder("pack") .setAttribute("targetFile", context.paths.buildOutputDir.relativize(targetFile).toString()) .useWithScope { zipWithCompression(targetFile, zipFileMap) } context.notifyArtifactWasBuilt(targetFile) } } private inline fun filterSourceFilesOnly(name: String, context: BuildContext, configure: (Path) -> Unit): Path { val sourceFiles = context.paths.tempDir.resolve("$name-${UUID.randomUUID()}") NioFiles.deleteRecursively(sourceFiles) Files.createDirectories(sourceFiles) configure(sourceFiles) Files.walk(sourceFiles).use { stream -> stream.forEach { if (!Files.isDirectory(it) && !isSourceFile(it.toString())) { Files.delete(it) } } } return sourceFiles } private fun compilePlatformAndPluginModules(pluginsToPublish: Set<PluginLayout>, context: BuildContext): DistributionBuilderState { val distState = DistributionBuilderState(pluginsToPublish, context) val compilationTasks = CompilationTasks.create(context) compilationTasks.compileModules( distState.getModulesForPluginsToPublish() + listOf("intellij.idea.community.build.tasks", "intellij.platform.images.build", "intellij.tools.launcherGenerator")) compilationTasks.buildProjectArtifacts(distState.getIncludedProjectArtifacts()) return distState } private suspend fun compileModulesForDistribution(pluginsToPublish: Set<PluginLayout>, context: BuildContext): DistributionBuilderState { val productProperties = context.productProperties val mavenArtifacts = productProperties.mavenArtifacts val toCompile = LinkedHashSet<String>() toCompile.addAll(getModulesToCompile(context)) context.proprietaryBuildTools.scrambleTool?.let { toCompile.addAll(it.additionalModulesToCompile) } toCompile.addAll(productProperties.productLayout.mainModules) toCompile.addAll(mavenArtifacts.additionalModules) toCompile.addAll(mavenArtifacts.squashedModules) toCompile.addAll(mavenArtifacts.proprietaryModules) toCompile.addAll(productProperties.modulesToCompileTests) CompilationTasks.create(context).compileModules(toCompile) if (context.shouldBuildDistributions()) { val providedModuleFile = context.paths.artifactDir.resolve("${context.applicationInfo.productCode}-builtinModules.json") val state = compilePlatformAndPluginModules(pluginsToPublish, context) buildProvidedModuleList(targetFile = providedModuleFile, state = state, context = context) if (!productProperties.productLayout.buildAllCompatiblePlugins) { return state } if (context.options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) { Span.current().addEvent("skip collecting compatible plugins because PROVIDED_MODULES_LIST_STEP was skipped") } else { return compilePlatformAndPluginModules( pluginsToPublish = pluginsToPublish + collectCompatiblePluginsToPublish(providedModuleFile, context), context = context ) } } return compilePlatformAndPluginModules(pluginsToPublish, context) } private suspend fun compileModulesForDistribution(context: BuildContext): DistributionBuilderState { return compileModulesForDistribution( pluginsToPublish = getPluginLayoutsByJpsModuleNames(modules = context.productProperties.productLayout.pluginModulesToPublish, productLayout = context.productProperties.productLayout), context = context ) } suspend fun buildDistributions(context: BuildContext): Unit = spanBuilder("build distributions").useWithScope2 { checkProductProperties(context as BuildContextImpl) copyDependenciesFile(context) logFreeDiskSpace("before compilation", context) val pluginsToPublish = getPluginLayoutsByJpsModuleNames(modules = context.productProperties.productLayout.pluginModulesToPublish, productLayout = context.productProperties.productLayout) val distributionState = compileModulesForDistribution(context) logFreeDiskSpace("after compilation", context) coroutineScope { createMavenArtifactJob(context, distributionState) spanBuilder("build platform and plugin JARs").useWithScope2<Unit> { val distributionJARsBuilder = DistributionJARsBuilder(distributionState) if (context.productProperties.buildDocAuthoringAssets) buildInspectopediaArtifacts(distributionJARsBuilder, context) if (context.shouldBuildDistributions()) { val entries = distributionJARsBuilder.buildJARs(context) if (context.productProperties.buildSourcesArchive) { buildSourcesArchive(entries, context) } } else { Span.current().addEvent("skip building product distributions because " + "\"intellij.build.target.os\" property is set to \"${BuildOptions.OS_NONE}\"") distributionJARsBuilder.buildSearchableOptions(context) distributionJARsBuilder.buildNonBundledPlugins(pluginsToPublish = pluginsToPublish, compressPluginArchive = context.options.compressZipFiles, buildPlatformLibJob = null, context = context) } } if (!context.shouldBuildDistributions()) { return@coroutineScope } layoutShared(context) val distDirs = buildOsSpecificDistributions(context) @Suppress("SpellCheckingInspection") if (java.lang.Boolean.getBoolean("intellij.build.toolbox.litegen")) { @Suppress("SENSELESS_COMPARISON") if (context.buildNumber == null) { Span.current().addEvent("Toolbox LiteGen is not executed - it does not support SNAPSHOT build numbers") } else if (context.options.targetOs != OsFamily.ALL) { Span.current().addEvent("Toolbox LiteGen is not executed - it doesn't support installers are being built only for specific OS") } else { context.executeStep("build toolbox lite-gen links", BuildOptions.TOOLBOX_LITE_GEN_STEP) { val toolboxLiteGenVersion = System.getProperty("intellij.build.toolbox.litegen.version") checkNotNull(toolboxLiteGenVersion) { "Toolbox Lite-Gen version is not specified!" } ToolboxLiteGen.runToolboxLiteGen(context.paths.communityHomeDirRoot, context.messages, toolboxLiteGenVersion, "/artifacts-dir=" + context.paths.artifacts, "/product-code=" + context.applicationInfo.productCode, "/isEAP=" + context.applicationInfo.isEAP.toString(), "/output-dir=" + context.paths.buildOutputRoot + "/toolbox-lite-gen") } } } if (context.productProperties.buildCrossPlatformDistribution) { if (distDirs.size == SUPPORTED_DISTRIBUTIONS.size) { context.executeStep(spanBuilder("build cross-platform distribution"), BuildOptions.CROSS_PLATFORM_DISTRIBUTION_STEP) { buildCrossPlatformZip(distDirs, context) } } else { Span.current().addEvent("skip building cross-platform distribution because some OS/arch-specific distributions were skipped") } } logFreeDiskSpace("after building distributions", context) } } private fun CoroutineScope.createMavenArtifactJob(context: BuildContext, distributionState: DistributionBuilderState): Job? { val mavenArtifacts = context.productProperties.mavenArtifacts if (!mavenArtifacts.forIdeModules && mavenArtifacts.additionalModules.isEmpty() && mavenArtifacts.squashedModules.isEmpty() && mavenArtifacts.proprietaryModules.isEmpty()) { return null } return createSkippableJob(spanBuilder("generate maven artifacts"), BuildOptions.MAVEN_ARTIFACTS_STEP, context) { val moduleNames = ArrayList<String>() if (mavenArtifacts.forIdeModules) { moduleNames.addAll(distributionState.platformModules) val productLayout = context.productProperties.productLayout moduleNames.addAll(productLayout.getIncludedPluginModules(productLayout.bundledPluginModules)) } val mavenArtifactsBuilder = MavenArtifactsBuilder(context) moduleNames.addAll(mavenArtifacts.additionalModules) if (!moduleNames.isEmpty()) { mavenArtifactsBuilder.generateMavenArtifacts(moduleNames, mavenArtifacts.squashedModules, "maven-artifacts") } if (!mavenArtifacts.proprietaryModules.isEmpty()) { mavenArtifactsBuilder.generateMavenArtifacts(mavenArtifacts.proprietaryModules, emptyList(), "proprietary-maven-artifacts") } } } private fun checkProductProperties(context: BuildContextImpl) { checkProductLayout(context) val properties = context.productProperties checkPaths2(properties.brandingResourcePaths, "productProperties.brandingResourcePaths") checkPaths2(properties.additionalIDEPropertiesFilePaths, "productProperties.additionalIDEPropertiesFilePaths") checkPaths2(properties.additionalDirectoriesWithLicenses, "productProperties.additionalDirectoriesWithLicenses") checkModules(properties.additionalModulesToCompile, "productProperties.additionalModulesToCompile", context) checkModules(properties.modulesToCompileTests, "productProperties.modulesToCompileTests", context) context.windowsDistributionCustomizer?.let { winCustomizer -> checkPaths(listOfNotNull(winCustomizer.icoPath), "productProperties.windowsCustomizer.icoPath") checkPaths(listOfNotNull(winCustomizer.icoPathForEAP), "productProperties.windowsCustomizer.icoPathForEAP") checkPaths(listOfNotNull(winCustomizer.installerImagesPath), "productProperties.windowsCustomizer.installerImagesPath") } context.linuxDistributionCustomizer?.let { linuxDistributionCustomizer -> checkPaths(listOfNotNull(linuxDistributionCustomizer.iconPngPath), "productProperties.linuxCustomizer.iconPngPath") checkPaths(listOfNotNull(linuxDistributionCustomizer.iconPngPathForEAP), "productProperties.linuxCustomizer.iconPngPathForEAP") } context.macDistributionCustomizer?.let { macCustomizer -> checkMandatoryField(macCustomizer.bundleIdentifier, "productProperties.macCustomizer.bundleIdentifier") checkMandatoryPath(macCustomizer.icnsPath, "productProperties.macCustomizer.icnsPath") checkPaths(listOfNotNull(macCustomizer.icnsPathForEAP), "productProperties.macCustomizer.icnsPathForEAP") checkMandatoryPath(macCustomizer.dmgImagePath, "productProperties.macCustomizer.dmgImagePath") checkPaths(listOfNotNull(macCustomizer.dmgImagePathForEAP), "productProperties.macCustomizer.dmgImagePathForEAP") } checkModules(properties.mavenArtifacts.additionalModules, "productProperties.mavenArtifacts.additionalModules", context) checkModules(properties.mavenArtifacts.squashedModules, "productProperties.mavenArtifacts.squashedModules", context) if (context.productProperties.scrambleMainJar) { context.proprietaryBuildTools.scrambleTool?.let { checkModules(modules = it.namesOfModulesRequiredToBeScrambled, fieldName = "ProprietaryBuildTools.scrambleTool.namesOfModulesRequiredToBeScrambled", context = context) } } } private fun checkProductLayout(context: BuildContext) { val layout = context.productProperties.productLayout // todo mainJarName type specified as not-null - does it work? val messages = context.messages @Suppress("SENSELESS_COMPARISON") check(layout.mainJarName != null) { "productProperties.productLayout.mainJarName is not specified" } val pluginLayouts = layout.pluginLayouts checkScrambleClasspathPlugins(pluginLayouts) checkPluginDuplicates(pluginLayouts) checkPluginModules(layout.bundledPluginModules, "productProperties.productLayout.bundledPluginModules", context) checkPluginModules(layout.pluginModulesToPublish, "productProperties.productLayout.pluginModulesToPublish", context) checkPluginModules(layout.compatiblePluginsToIgnore, "productProperties.productLayout.compatiblePluginsToIgnore", context) if (!layout.buildAllCompatiblePlugins && !layout.compatiblePluginsToIgnore.isEmpty()) { messages.warning("layout.buildAllCompatiblePlugins option isn't enabled. Value of " + "layout.compatiblePluginsToIgnore property will be ignored (${layout.compatiblePluginsToIgnore})") } if (layout.buildAllCompatiblePlugins && !layout.compatiblePluginsToIgnore.isEmpty()) { checkPluginModules(layout.compatiblePluginsToIgnore, "productProperties.productLayout.compatiblePluginsToIgnore", context) } if (!context.shouldBuildDistributions() && layout.buildAllCompatiblePlugins) { messages.warning("Distribution is not going to build. Hence all compatible plugins won't be built despite " + "layout.buildAllCompatiblePlugins option is enabled. layout.pluginModulesToPublish will be used (" + layout.pluginModulesToPublish + ")") } check(!layout.prepareCustomPluginRepositoryForPublishedPlugins || !layout.pluginModulesToPublish.isEmpty() || layout.buildAllCompatiblePlugins) { "productProperties.productLayout.prepareCustomPluginRepositoryForPublishedPlugins option is enabled" + " but no pluginModulesToPublish are specified" } checkModules(layout.productApiModules, "productProperties.productLayout.productApiModules", context) checkModules(layout.productImplementationModules, "productProperties.productLayout.productImplementationModules", context) checkModules(layout.additionalPlatformJars.values(), "productProperties.productLayout.additionalPlatformJars", context) checkModules(layout.moduleExcludes.keys, "productProperties.productLayout.moduleExcludes", context) checkModules(layout.mainModules, "productProperties.productLayout.mainModules", context) checkProjectLibraries(layout.projectLibrariesToUnpackIntoMainJar, "productProperties.productLayout.projectLibrariesToUnpackIntoMainJar", context) for (plugin in pluginLayouts) { checkBaseLayout(plugin, "\'${plugin.mainModule}\' plugin", context) } } private fun checkBaseLayout(layout: BaseLayout, description: String, context: BuildContext) { checkModules(layout.includedModuleNames.toList(), "moduleJars in $description", context) checkArtifacts(layout.includedArtifacts.keys, "includedArtifacts in $description", context) checkModules(layout.resourcePaths.map { it.moduleName }, "resourcePaths in $description", context) checkModules(layout.moduleExcludes.keys, "moduleExcludes in $description", context) checkProjectLibraries(layout.includedProjectLibraries.map { it.libraryName }, "includedProjectLibraries in $description", context) for ((moduleName, libraryName) in layout.includedModuleLibraries) { checkModules(listOf(moduleName), "includedModuleLibraries in $description", context) check(context.findRequiredModule(moduleName).libraryCollection.libraries.any { getLibraryFileName(it) == libraryName }) { "Cannot find library \'$libraryName\' in \'$moduleName\' (used in $description)" } } checkModules(layout.excludedModuleLibraries.keySet(), "excludedModuleLibraries in $description", context) for ((key, value) in layout.excludedModuleLibraries.entrySet()) { val libraries = context.findRequiredModule(key).libraryCollection.libraries for (libraryName in value) { check(libraries.any { getLibraryFileName(it) == libraryName }) { "Cannot find library \'$libraryName\' in \'$key\' (used in \'excludedModuleLibraries\' in $description)" } } } checkProjectLibraries(layout.projectLibrariesToUnpack.values(), "projectLibrariesToUnpack in $description", context) checkModules(layout.modulesWithExcludedModuleLibraries, "modulesWithExcludedModuleLibraries in $description", context) } private fun checkPluginDuplicates(nonTrivialPlugins: List<PluginLayout>) { val pluginsGroupedByMainModule = nonTrivialPlugins.groupBy { it.mainModule to it.bundlingRestrictions }.values for (duplicatedPlugins in pluginsGroupedByMainModule) { check(duplicatedPlugins.size <= 1) { "Duplicated plugin description in productLayout.pluginLayouts: main module ${duplicatedPlugins.first().mainModule}" } } // indexing-shared-ultimate has a separate layout for bundled & public plugins val duplicateDirectoryNameExceptions = setOf("indexing-shared-ultimate") val pluginsGroupedByDirectoryName = nonTrivialPlugins.groupBy { it.directoryName to it.bundlingRestrictions }.values for (duplicatedPlugins in pluginsGroupedByDirectoryName) { val pluginDirectoryName = duplicatedPlugins.first().directoryName if (duplicateDirectoryNameExceptions.contains(pluginDirectoryName)) { continue } check(duplicatedPlugins.size <= 1) { "Duplicated plugin description in productLayout.pluginLayouts: directory name '$pluginDirectoryName', main modules: ${duplicatedPlugins.joinToString { it.mainModule }}" } } } private fun checkModules(modules: Collection<String>?, fieldName: String, context: CompilationContext) { if (modules != null) { val unknownModules = modules.filter { context.findModule(it) == null } check(unknownModules.isEmpty()) { "The following modules from $fieldName aren\'t found in the project: $unknownModules" } } } private fun checkArtifacts(names: Collection<String>, fieldName: String, context: CompilationContext) { val unknownArtifacts = names - JpsArtifactService.getInstance().getArtifacts(context.project).map { it.name }.toSet() check(unknownArtifacts.isEmpty()) { "The following artifacts from $fieldName aren\'t found in the project: $unknownArtifacts" } } private fun checkScrambleClasspathPlugins(pluginLayoutList: List<PluginLayout>) { val pluginDirectories = pluginLayoutList.mapTo(HashSet()) { it.directoryName } for (pluginLayout in pluginLayoutList) { for ((pluginDirectoryName, _) in pluginLayout.scrambleClasspathPlugins) { check(pluginDirectories.contains(pluginDirectoryName)) { "Layout of plugin '${pluginLayout.mainModule}' declares an unresolved plugin directory name" + " in ${pluginLayout.scrambleClasspathPlugins}: $pluginDirectoryName" } } } } private fun checkPluginModules(pluginModules: Collection<String>?, fieldName: String, context: BuildContext) { if (pluginModules == null) { return } checkModules(pluginModules, fieldName, context) val unknownBundledPluginModules = pluginModules.filter { context.findFileInModuleSources(it, "META-INF/plugin.xml") == null } check(unknownBundledPluginModules.isEmpty()) { "The following modules from $fieldName don\'t contain META-INF/plugin.xml file and aren\'t specified as optional plugin modules" + "in productProperties.productLayout.pluginLayouts: ${unknownBundledPluginModules.joinToString()}." } } private fun checkPaths(paths: Collection<String>, propertyName: String) { val nonExistingFiles = paths.filter { Files.notExists(Path.of(it)) } check(nonExistingFiles.isEmpty()) { "$propertyName contains non-existing files: ${nonExistingFiles.joinToString()}" } } private fun checkPaths2(paths: Collection<Path>, propertyName: String) { val nonExistingFiles = paths.filter { Files.notExists(it) } check(nonExistingFiles.isEmpty()) { "$propertyName contains non-existing files: ${nonExistingFiles.joinToString()}" } } private fun checkMandatoryField(value: String?, fieldName: String) { checkNotNull(value) { "Mandatory property \'$fieldName\' is not specified" } } private fun checkMandatoryPath(path: String, fieldName: String) { checkMandatoryField(path, fieldName) checkPaths(listOf(path), fieldName) } private fun logFreeDiskSpace(phase: String, context: CompilationContext) { if (context.options.printFreeSpace) { logFreeDiskSpace(context.paths.buildOutputDir, phase) } } internal fun logFreeDiskSpace(dir: Path, phase: String) { Span.current().addEvent("free disk space", Attributes.of( AttributeKey.stringKey("phase"), phase, AttributeKey.stringKey("usableSpace"), Formats.formatFileSize(Files.getFileStore(dir).usableSpace), AttributeKey.stringKey("dir"), dir.toString(), )) } fun buildUpdaterJar(context: BuildContext, artifactName: String = "updater.jar") { val updaterModule = context.findRequiredModule("intellij.platform.updater") val updaterModuleSource = DirSource(context.getModuleOutputDir(updaterModule)) val librarySources = JpsJavaExtensionService.dependencies(updaterModule) .productionOnly() .runtimeOnly() .libraries .asSequence() .flatMap { it.getRootUrls(JpsOrderRootType.COMPILED) } .filter { !JpsPathUtil.isJrtUrl(it) } .map { ZipSource(Path.of(JpsPathUtil.urlToPath(it)), listOf(Regex("^META-INF/.*"))) } val updaterJar = context.paths.artifactDir.resolve(artifactName) buildJar(targetFile = updaterJar, sources = (sequenceOf(updaterModuleSource) + librarySources).toList(), compress = true) context.notifyArtifactBuilt(updaterJar) } private suspend fun buildCrossPlatformZip(distResults: List<DistributionForOsTaskResult>, context: BuildContext): Path { val executableName = context.productProperties.baseFileName val productJson = generateMultiPlatformProductJson( relativePathToBin = "bin", builtinModules = context.builtinModule, launch = sequenceOf(JvmArchitecture.x64, JvmArchitecture.aarch64).flatMap { arch -> listOf( ProductInfoLaunchData( os = OsFamily.WINDOWS.osName, arch = arch.dirName, launcherPath = "bin/${executableName}.bat", javaExecutablePath = null, vmOptionsFilePath = "bin/win/${executableName}64.exe.vmoptions", bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.WINDOWS, arch, isScript = true)), ProductInfoLaunchData( os = OsFamily.LINUX.osName, arch = arch.dirName, launcherPath = "bin/${executableName}.sh", javaExecutablePath = null, vmOptionsFilePath = "bin/linux/${executableName}64.vmoptions", startupWmClass = getLinuxFrameClass(context), bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.LINUX, arch, isScript = true)), ProductInfoLaunchData( os = OsFamily.MACOS.osName, arch = arch.dirName, launcherPath = "MacOS/$executableName", javaExecutablePath = null, vmOptionsFilePath = "bin/mac/${executableName}.vmoptions", bootClassPathJarNames = context.bootClassPathJarNames, additionalJvmArguments = context.getAdditionalJvmArguments(OsFamily.MACOS, arch, isPortableDist = true)) ) }.toList(), context = context, ) val zipFileName = context.productProperties.getCrossPlatformZipFileName(context.applicationInfo, context.buildNumber) val targetFile = context.paths.artifactDir.resolve(zipFileName) val dependenciesFile = copyDependenciesFile(context) crossPlatformZip( macX64DistDir = distResults.first { it.builder.targetOs == OsFamily.MACOS && it.arch == JvmArchitecture.x64 }.outDir, macArm64DistDir = distResults.first { it.builder.targetOs == OsFamily.MACOS && it.arch == JvmArchitecture.aarch64 }.outDir, linuxX64DistDir = distResults.first { it.builder.targetOs == OsFamily.LINUX && it.arch == JvmArchitecture.x64 }.outDir, winX64DistDir = distResults.first { it.builder.targetOs == OsFamily.WINDOWS && it.arch == JvmArchitecture.x64 }.outDir, targetFile = targetFile, executableName = executableName, productJson = productJson.encodeToByteArray(), executablePatterns = distResults.flatMap { it.builder.generateExecutableFilesPatterns(includeRuntime = false) }, distFiles = context.getDistFiles(os = null, arch = null), extraFiles = mapOf("dependencies.txt" to dependenciesFile), distAllDir = context.paths.distAllDir, compress = context.options.compressZipFiles, ) coroutineScope { launch { checkInArchive(archiveFile = targetFile, pathInArchive = "", context = context) } launch { checkClassFiles(targetFile = targetFile, context = context) } } context.notifyArtifactBuilt(targetFile) return targetFile } private suspend fun checkClassFiles(targetFile: Path, context: BuildContext) { val versionCheckerConfig = if (context.isStepSkipped(BuildOptions.VERIFY_CLASS_FILE_VERSIONS)) { emptyMap() } else { context.productProperties.versionCheckerConfig } val forbiddenSubPaths = if (context.options.validateClassFileSubpaths) { context.productProperties.forbiddenClassFileSubPaths } else { emptyList() } val classFileCheckRequired = (versionCheckerConfig.isNotEmpty() || forbiddenSubPaths.isNotEmpty()) if (classFileCheckRequired) { checkClassFiles(versionCheckerConfig, forbiddenSubPaths, targetFile, context.messages) } } private fun getOsDistributionBuilder(os: OsFamily, ideaProperties: Path? = null, context: BuildContext): OsSpecificDistributionBuilder? { return when (os) { OsFamily.WINDOWS -> WindowsDistributionBuilder(context = context, customizer = context.windowsDistributionCustomizer ?: return null, ideaProperties = ideaProperties) OsFamily.LINUX -> LinuxDistributionBuilder(context = context, customizer = context.linuxDistributionCustomizer ?: return null, ideaProperties = ideaProperties) OsFamily.MACOS -> MacDistributionBuilder(context = context, customizer = (context as BuildContextImpl).macDistributionCustomizer ?: return null, ideaProperties = ideaProperties) } } // keep in sync with AppUIUtil#getFrameClass internal fun getLinuxFrameClass(context: BuildContext): String { val name = context.applicationInfo.productNameWithEdition .lowercase() .replace(' ', '-') .replace("intellij-idea", "idea") .replace("android-studio", "studio") .replace("-community-edition", "-ce") .replace("-ultimate-edition", "") .replace("-professional-edition", "") return if (name.startsWith("jetbrains-")) name else "jetbrains-$name" } private fun crossPlatformZip(macX64DistDir: Path, macArm64DistDir: Path, linuxX64DistDir: Path, winX64DistDir: Path, targetFile: Path, executableName: String, productJson: ByteArray, executablePatterns: List<String>, distFiles: Collection<DistFile>, extraFiles: Map<String, Path>, distAllDir: Path, compress: Boolean) { writeNewFile(targetFile) { outFileChannel -> NoDuplicateZipArchiveOutputStream(outFileChannel, compress = compress).use { out -> out.setUseZip64(Zip64Mode.Never) out.entryToDir(winX64DistDir.resolve("bin/idea.properties"), "bin/win") out.entryToDir(linuxX64DistDir.resolve("bin/idea.properties"), "bin/linux") out.entryToDir(macX64DistDir.resolve("bin/idea.properties"), "bin/mac") out.entryToDir(macX64DistDir.resolve("bin/${executableName}.vmoptions"), "bin/mac") out.entry("bin/mac/${executableName}64.vmoptions", macX64DistDir.resolve("bin/${executableName}.vmoptions")) for ((p, f) in extraFiles) { out.entry(p, f) } out.entry("product-info.json", productJson) Files.newDirectoryStream(winX64DistDir.resolve("bin")).use { for (file in it) { val path = file.toString() if (path.endsWith(".exe.vmoptions")) { out.entryToDir(file, "bin/win") } else { val fileName = file.fileName.toString() if (fileName.startsWith("fsnotifier") && fileName.endsWith(".exe")) { out.entry("bin/win/$fileName", file) } } } } Files.newDirectoryStream(linuxX64DistDir.resolve("bin")).use { for (file in it) { val name = file.fileName.toString() when { name.endsWith(".vmoptions") -> out.entryToDir(file, "bin/linux") name.endsWith(".sh") || name.endsWith(".py") -> out.entry("bin/${file.fileName}", file, unixMode = executableFileUnixMode) name == "fsnotifier" -> out.entry("bin/linux/${name}", file, unixMode = executableFileUnixMode) } } } // At the moment, there is no ARM64 hardware suitable for painless IDEA plugin development, // so corresponding artifacts are not packed in. Files.newDirectoryStream(macX64DistDir.resolve("bin")).use { for (file in it) { if (file.toString().endsWith(".jnilib")) { out.entry("bin/mac/${file.fileName.toString().removeSuffix(".jnilib")}.dylib", file) } else { val fileName = file.fileName.toString() if (fileName.startsWith("restarter") || fileName.startsWith("printenv")) { out.entry("bin/$fileName", file, unixMode = executableFileUnixMode) } else if (fileName.startsWith("fsnotifier")) { out.entry("bin/mac/$fileName", file, unixMode = executableFileUnixMode) } } } } val patterns = executablePatterns.map { FileSystems.getDefault().getPathMatcher("glob:$it") } val entryCustomizer: (ZipArchiveEntry, Path, String) -> Unit = { entry, _, relativePathString -> val relativePath = Path.of(relativePathString) if (patterns.any { it.matches(relativePath) }) { entry.unixMode = executableFileUnixMode } } val commonFilter: (String) -> Boolean = { relPath -> !relPath.startsWith("Info.plist") && !relPath.startsWith("bin/fsnotifier") && !relPath.startsWith("bin/repair") && !relPath.startsWith("bin/restart") && !relPath.startsWith("bin/printenv") && !(relPath.startsWith("bin/") && (relPath.endsWith(".sh") || relPath.endsWith(".vmoptions")) && relPath.count { it == '/' } == 1) && relPath != "bin/idea.properties" && !relPath.startsWith("help/") } val zipFileUniqueGuard = HashMap<String, Path>() out.dir(distAllDir, "", fileFilter = { _, relPath -> relPath != "bin/idea.properties" }, entryCustomizer = entryCustomizer) out.dir(macX64DistDir, "", fileFilter = { _, relativePath -> commonFilter.invoke(relativePath) && filterFileIfAlreadyInZip(relativePath, macX64DistDir.resolve(relativePath), zipFileUniqueGuard) }, entryCustomizer = entryCustomizer) out.dir(macArm64DistDir, "", fileFilter = { _, relPath -> commonFilter.invoke(relPath) && filterFileIfAlreadyInZip(relPath, macArm64DistDir.resolve(relPath), zipFileUniqueGuard) }, entryCustomizer = entryCustomizer) out.dir(linuxX64DistDir, "", fileFilter = { _, relPath -> commonFilter.invoke(relPath) && filterFileIfAlreadyInZip(relPath, linuxX64DistDir.resolve(relPath), zipFileUniqueGuard) }, entryCustomizer = entryCustomizer) out.dir(startDir = winX64DistDir, prefix = "", fileFilter = { _, relativePath -> commonFilter.invoke(relativePath) && !(relativePath.startsWith("bin/${executableName}") && relativePath.endsWith(".exe")) && filterFileIfAlreadyInZip(relativePath, winX64DistDir.resolve(relativePath), zipFileUniqueGuard) }, entryCustomizer = entryCustomizer) for (distFile in distFiles) { // linux and windows: we don't add win and linux specific dist dirs for ARM, so, copy distFiles explicitly // macOS: we don't copy dist files for macOS distribution to avoid extra copy operation if (zipFileUniqueGuard.putIfAbsent(distFile.relativePath, distFile.file) == null) { out.entry(distFile.relativePath, distFile.file) } } } } } fun getModulesToCompile(buildContext: BuildContext): Set<String> { val productLayout = buildContext.productProperties.productLayout val result = LinkedHashSet<String>() result.addAll(productLayout.getIncludedPluginModules(java.util.Set.copyOf(productLayout.bundledPluginModules))) PlatformModules.collectPlatformModules(result) result.addAll(productLayout.productApiModules) result.addAll(productLayout.productImplementationModules) result.addAll(productLayout.additionalPlatformJars.values()) result.addAll(getToolModules()) result.addAll(buildContext.productProperties.additionalModulesToCompile) result.add("intellij.idea.community.build.tasks") result.add("intellij.platform.images.build") result.removeAll(productLayout.excludedModuleNames) return result } // Captures information about all available inspections in a JSON format as part of Inspectopedia project. This is later used by Qodana and other tools. private suspend fun buildInspectopediaArtifacts(builder: DistributionJARsBuilder, context: BuildContext) { val ideClasspath = builder.createIdeClassPath(context) val tempDir = context.paths.tempDir.resolve("inspectopedia-generator") val inspectionsPath = tempDir.resolve("inspections-${context.applicationInfo.productCode.lowercase()}") runApplicationStarter(context = context, tempDir = tempDir, ideClasspath = ideClasspath, arguments = listOf("inspectopedia-generator", inspectionsPath.toAbsolutePath().toString())) val targetFile = context.paths.artifactDir.resolve("inspections-${context.applicationInfo.productCode.lowercase()}.zip").toFile() ZipOutputStream(FileOutputStream(targetFile)).use { zip -> ZipUtil.addDirToZipRecursively(zip, targetFile, inspectionsPath.toFile(), "", null, null) } }
platform/build-scripts/src/org/jetbrains/intellij/build/impl/BuildTasksImpl.kt
391375356
// 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.dsl.gridLayout import com.intellij.ui.dsl.doLayout import com.intellij.ui.dsl.gridLayout.builders.RowsGridBuilder import org.junit.Test import javax.swing.JLabel import javax.swing.JPanel import kotlin.test.assertEquals import kotlin.test.assertTrue class GridLayoutSizeGroupTest { @Test fun testWidthGroup() { val panel = JPanel(GridLayout()) val builder = RowsGridBuilder(panel) val label1 = label("Label") val label2 = label("Label") val label = label("Label") val bigLabel = label("A very long label<br>second line") builder.cell(label1) builder.cell(label2, widthGroup = "anotherGroup") builder.cell(label, widthGroup = "group") builder.cell(bigLabel, widthGroup = "group") doLayout(panel) val label1Size = label1.size val labelSize = label.size val bigLabelSize = bigLabel.size assertEquals(label1Size, label2.size) assertEquals(label1Size.height, labelSize.height) assertEquals(labelSize.width, bigLabelSize.width) assertTrue(labelSize.height < bigLabelSize.height) } private fun label(text: String): JLabel { return JLabel("<html>$text") } }
platform/platform-tests/testSrc/com/intellij/ui/dsl/gridLayout/GridLayoutSizeGroupTest.kt
2188453843
// 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.analysis.problemsView.toolWindow import com.intellij.analysis.problemsView.Problem import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.ide.CopyPasteManager import com.intellij.openapi.project.DumbAwareAction import java.awt.datatransfer.StringSelection import javax.swing.JTree internal class CopyProblemDescriptionAction : NodeAction<Problem>() { override fun getData(node: Any?) = (node as? ProblemNode)?.problem override fun actionPerformed(data: Problem) = CopyPasteManager.getInstance().setContents(StringSelection(data.description ?: data.text)) } internal abstract class NodeAction<Data> : DumbAwareAction() { abstract fun getData(node: Any?): Data? abstract fun actionPerformed(data: Data) open fun isEnabled(data: Data) = true override fun update(event: AnActionEvent) { val data = getData(getSelectedNode(event)) event.presentation.isEnabledAndVisible = data != null && isEnabled(data) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(event: AnActionEvent) { val data = getData(getSelectedNode(event)) if (data != null) actionPerformed(data) } } private fun getSelectedNode(event: AnActionEvent): Any? { val tree = event.getData(CONTEXT_COMPONENT) as? JTree return tree?.selectionPath?.lastPathComponent }
platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/NodeAction.kt
3559382945
// 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.github.pullrequest.ui.toolwindow import com.intellij.collaboration.async.combineState import com.intellij.collaboration.async.mapStateScoped import com.intellij.collaboration.util.URIUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.jetbrains.plugins.github.api.GHRepositoryConnection import org.jetbrains.plugins.github.authentication.accounts.GHAccountManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.pullrequest.config.GithubPullRequestsProjectUISettings import org.jetbrains.plugins.github.util.GHGitRepositoryMapping import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager internal class GHPRToolWindowTabViewModel(private val scope: CoroutineScope, private val repositoriesManager: GHHostedRepositoriesManager, private val accountManager: GHAccountManager, private val connectionManager: GHRepositoryConnectionManager, private val settings: GithubPullRequestsProjectUISettings) { private val connectionState = MutableStateFlow<GHRepositoryConnection?>(null).apply { scope.launch { collectLatest { if (it != null) { it.awaitClose() compareAndSet(it, null) } } } } private val singleRepoAndAccountState: StateFlow<Pair<GHGitRepositoryMapping, GithubAccount>?> = combineState(scope, repositoriesManager.knownRepositoriesState, accountManager.accountsState) { repos, accounts -> repos.singleOrNull()?.let { repo -> accounts.singleOrNull { URIUtil.equalWithoutSchema(it.server.toURI(), repo.repository.serverPath.toURI()) }?.let { repo to it } } } val viewState: StateFlow<GHPRTabContentViewModel> = connectionState.mapStateScoped(scope) { scope, connection -> if (connection != null) { createConnectedVm(connection) } else { createNotConnectedVm(scope) } } private fun createNotConnectedVm(cs: CoroutineScope): GHPRTabContentViewModel.Selectors { val selectorVm = GHRepositoryAndAccountSelectorViewModel(cs, repositoriesManager, accountManager, ::connect) settings.selectedRepoAndAccount?.let { (repo, account) -> with(selectorVm) { repoSelectionState.value = repo accountSelectionState.value = account submitSelection() } } cs.launch { singleRepoAndAccountState.collect { if (it != null) { with(selectorVm) { repoSelectionState.value = it.first accountSelectionState.value = it.second submitSelection() } } } } return GHPRTabContentViewModel.Selectors(selectorVm) } private suspend fun connect(repo: GHGitRepositoryMapping, account: GithubAccount) { connectionState.value = connectionManager.connect(scope, repo, account) settings.selectedRepoAndAccount = repo to account } private fun createConnectedVm(connection: GHRepositoryConnection) = GHPRTabContentViewModel.PullRequests(connection) fun canSelectDifferentRepoOrAccount(): Boolean { return viewState.value is GHPRTabContentViewModel.PullRequests && singleRepoAndAccountState.value == null } fun selectDifferentRepoOrAccount() { scope.launch { settings.selectedRepoAndAccount = null connectionState.value?.close() } } } internal sealed interface GHPRTabContentViewModel { class Selectors(val selectorVm: GHRepositoryAndAccountSelectorViewModel) : GHPRTabContentViewModel class PullRequests(val connection: GHRepositoryConnection) : GHPRTabContentViewModel }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/toolwindow/GHPRToolWindowTabViewModel.kt
3440231660
package com.sevenander.timetable.previewLesson import com.sevenander.timetable.App import com.sevenander.timetable.R import com.sevenander.timetable.data.cache.LessonCache import com.sevenander.timetable.data.model.LessonEntity /** * Created by andrii on 6/2/17. */ class PreviewPresenter(private val view: PreviewView) { private var cache = LessonCache(App.instance.getDatabase()) fun init(id: Int) { loadData(id) } private fun loadData(id: Int) { view.hideError() view.showProgress() val data = cache.getLesson(id) dataReceived(data) } private fun dataReceived(data: LessonEntity?) { if (data == null) { view.showError(view.context().getString(R.string.no_data_to_show)) view.hideLesson() } else { view.showLesson(data) view.hideError() } view.hideProgress() } }
app/src/main/java/com/sevenander/timetable/previewLesson/PreviewPresenter.kt
2288482041
package lt.markmerkk.export.utils import java.io.File fun String.execute( workingDir: File ): Process { val parts = this.split("\\s".toRegex()) return parts .toList() .execute(workingDir) } fun List<String>.execute(workingDir: File): Process { println("Command: ${this.joinToString(" ")}") return ProcessBuilder(this) .directory(workingDir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() } val Process.text: String get() = inputStream.bufferedReader().readText() fun Process.errorAsString(): String { return this.errorStream .bufferedReader() .use { it.readText() } }
buildSrc/src/main/java/lt/markmerkk/export/utils/ExecutorUtils.kt
2452479358
package io.ktor.utils.io.internal import io.ktor.utils.io.ByteChannelSequentialBase import io.ktor.utils.io.close import io.ktor.utils.io.core.internal.ChunkBuffer internal suspend fun ByteChannelSequentialBase.joinToImpl(dst: ByteChannelSequentialBase, closeOnEnd: Boolean) { copyToSequentialImpl(dst, Long.MAX_VALUE) if (closeOnEnd) dst.close() } /** * Reads up to [limit] bytes from receiver channel and writes them to [dst] channel. * Closes [dst] channel if fails to read or write with cause exception. * @return a number of copied bytes */ internal suspend fun ByteChannelSequentialBase.copyToSequentialImpl(dst: ByteChannelSequentialBase, limit: Long): Long { require(this !== dst) if (closedCause != null) { dst.close(closedCause) return 0L } var remainingLimit = limit while (remainingLimit > 0) { if (!awaitInternalAtLeast1()) { break } val transferred = transferTo(dst, remainingLimit) val copied = if (transferred == 0L) { val tail = copyToTail(dst, remainingLimit) if (tail == 0L) { break } tail } else { if (dst.availableForWrite == 0) { dst.awaitAtLeastNBytesAvailableForWrite(1) } transferred } remainingLimit -= copied if (copied > 0) { dst.flush() } } return limit - remainingLimit } private suspend fun ByteChannelSequentialBase.copyToTail(dst: ByteChannelSequentialBase, limit: Long): Long { val lastPiece = ChunkBuffer.Pool.borrow() try { lastPiece.resetForWrite(limit.coerceAtMost(lastPiece.capacity.toLong()).toInt()) val rc = readAvailable(lastPiece) if (rc == -1) { lastPiece.release(ChunkBuffer.Pool) return 0 } dst.writeFully(lastPiece) return rc.toLong() } finally { lastPiece.release(ChunkBuffer.Pool) } }
ktor-io/common/src/io/ktor/utils/io/internal/SequentialCopyTo.kt
254754242
package de.tarent.axon.query import java.util.* import javax.persistence.Entity import javax.persistence.Id @Entity data class Movement( @Id val movementId: UUID, val gameUuid: UUID, val row: Int, val column: Int, val version: Long ) { // Just for JPA @Suppress("unused") private constructor(): this(UUID.randomUUID(), UUID.randomUUID(), 0, 0, 0) }
src/main/kotlin/de/tarent/axon/query/Movement.kt
74590023
package eu.kanade.tachiyomi.ui.manga.track import android.app.Dialog import android.os.Bundle import androidx.core.os.bundleOf import com.bluelinelabs.conductor.Controller import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.ui.base.controller.DialogController import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get class SetTrackStatusDialog<T> : DialogController where T : Controller { private val item: TrackItem private lateinit var listener: Listener constructor(target: T, listener: Listener, item: TrackItem) : super( bundleOf(KEY_ITEM_TRACK to item.track) ) { targetController = target this.listener = listener this.item = item } @Suppress("unused") constructor(bundle: Bundle) : super(bundle) { val track = bundle.getSerializable(KEY_ITEM_TRACK) as Track val service = Injekt.get<TrackManager>().getService(track.sync_id)!! item = TrackItem(track, service) } override fun onCreateDialog(savedViewState: Bundle?): Dialog { val statusList = item.service.getStatusList() val statusString = statusList.map { item.service.getStatus(it) } var selectedIndex = statusList.indexOf(item.track?.status) return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.status) .setSingleChoiceItems(statusString.toTypedArray(), selectedIndex) { _, which -> selectedIndex = which } .setPositiveButton(android.R.string.ok) { _, _ -> listener.setStatus(item, selectedIndex) } .setNegativeButton(android.R.string.cancel, null) .create() } interface Listener { fun setStatus(item: TrackItem, selection: Int) } } private const val KEY_ITEM_TRACK = "SetTrackStatusDialog.item.track"
app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackStatusDialog.kt
2774182519
package vn.eazy.base.mvp.example.mvp.di.module import android.app.Application import android.content.Context import android.support.v4.app.FragmentManager import android.util.Log import vn.eazy.base.mvp.delegate.AppDelegate import vn.eazy.base.mvp.di.module.GlobalModule import vn.eazy.base.mvp.example.mvp.lifecycles.LogFragmentLifeCycle import vn.eazy.base.mvp.example.mvp.lifecycles.LogLifeCycle import vn.eazy.base.mvp.example.mvp.model.api.service.UserService import vn.eazy.base.mvp.intergration.ConfigModule import vn.eazy.base.mvp.intergration.IRepositoryManager /** * Created by harryle on 6/17/17. */ class GlobalConfiguration : ConfigModule { override fun applyOptions(context: Context, builder: GlobalModule.Builder) { builder.baseUrl("http://demo6594088.mockable.io") builder.retrofitConfiguration { context, builder -> Log.d("TAG", "Config retrofit") } builder.gsonConfiguration { context, builder -> Log.d("TAG", "Config Gson") } builder.okHttpConfiguration { context, builder -> Log.d("TAG", "Config OkHttpConfiguration") } builder.responseErrorListener { context, builder -> Log.d("TAG", "Handle Response Error") } } override fun registerComponents(context: Context, repositoryManager: IRepositoryManager) { repositoryManager.injectRetrofitService(UserService::class.java) } override fun injectAppLifeCycles(context: Context, lifeCycles: MutableList<AppDelegate.LifeCycle>) { lifeCycles.add(object : AppDelegate.LifeCycle { override fun onCreate(application: Application) { Log.d("TAG", "OnCreate LifeCycle") } override fun onTerminate(application: Application) { Log.d("TAG", "OnTerminate LifeCycle") } }) } override fun injectFragmentLifeCycles(context: Context?, fragmentLifecycleCallbacks: MutableList<FragmentManager.FragmentLifecycleCallbacks>?) { fragmentLifecycleCallbacks?.add(LogFragmentLifeCycle()) } override fun injectActivityLifeCycles(context: Context?, activityLifeCycles: MutableList<Application.ActivityLifecycleCallbacks>?) { activityLifeCycles?.add(LogLifeCycle()) } }
code/app/src/main/java/vn/eazy/base/mvp/example/mvp/di/module/GlobalConfiguration.kt
1214120572
package eu.kanade.tachiyomi.data.notification import android.content.Context import androidx.core.app.NotificationManagerCompat import androidx.core.app.NotificationManagerCompat.IMPORTANCE_DEFAULT import androidx.core.app.NotificationManagerCompat.IMPORTANCE_HIGH import androidx.core.app.NotificationManagerCompat.IMPORTANCE_LOW import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.buildNotificationChannel import eu.kanade.tachiyomi.util.system.buildNotificationChannelGroup /** * Class to manage the basic information of all the notifications used in the app. */ object Notifications { /** * Common notification channel and ids used anywhere. */ const val CHANNEL_COMMON = "common_channel" const val ID_DOWNLOAD_IMAGE = 2 /** * Notification channel and ids used by the library updater. */ private const val GROUP_LIBRARY = "group_library" const val CHANNEL_LIBRARY_PROGRESS = "library_progress_channel" const val ID_LIBRARY_PROGRESS = -101 const val CHANNEL_LIBRARY_ERROR = "library_errors_channel" const val ID_LIBRARY_ERROR = -102 /** * Notification channel and ids used by the downloader. */ private const val GROUP_DOWNLOADER = "group_downloader" const val CHANNEL_DOWNLOADER_PROGRESS = "downloader_progress_channel" const val ID_DOWNLOAD_CHAPTER_PROGRESS = -201 const val CHANNEL_DOWNLOADER_COMPLETE = "downloader_complete_channel" const val ID_DOWNLOAD_CHAPTER_COMPLETE = -203 const val CHANNEL_DOWNLOADER_ERROR = "downloader_error_channel" const val ID_DOWNLOAD_CHAPTER_ERROR = -202 /** * Notification channel and ids used by the library updater. */ const val CHANNEL_NEW_CHAPTERS = "new_chapters_channel" const val ID_NEW_CHAPTERS = -301 const val GROUP_NEW_CHAPTERS = "eu.kanade.tachiyomi.NEW_CHAPTERS" /** * Notification channel and ids used by the backup/restore system. */ private const val GROUP_BACKUP_RESTORE = "group_backup_restore" const val CHANNEL_BACKUP_RESTORE_PROGRESS = "backup_restore_progress_channel" const val ID_BACKUP_PROGRESS = -501 const val ID_RESTORE_PROGRESS = -503 const val CHANNEL_BACKUP_RESTORE_COMPLETE = "backup_restore_complete_channel_v2" const val ID_BACKUP_COMPLETE = -502 const val ID_RESTORE_COMPLETE = -504 /** * Notification channel used for crash log file sharing. */ const val CHANNEL_CRASH_LOGS = "crash_logs_channel" const val ID_CRASH_LOGS = -601 /** * Notification channel used for Incognito Mode */ const val CHANNEL_INCOGNITO_MODE = "incognito_mode_channel" const val ID_INCOGNITO_MODE = -701 /** * Notification channel and ids used for app and extension updates. */ private const val GROUP_APK_UPDATES = "group_apk_updates" const val CHANNEL_APP_UPDATE = "app_apk_update_channel" const val ID_APP_UPDATER = 1 const val CHANNEL_EXTENSIONS_UPDATE = "ext_apk_update_channel" const val ID_UPDATES_TO_EXTS = -401 const val ID_EXTENSION_INSTALLER = -402 private val deprecatedChannels = listOf( "downloader_channel", "backup_restore_complete_channel", "library_channel", "library_progress_channel", "updates_ext_channel", ) /** * Creates the notification channels introduced in Android Oreo. * This won't do anything on Android versions that don't support notification channels. * * @param context The application context. */ fun createChannels(context: Context) { val notificationService = NotificationManagerCompat.from(context) // Delete old notification channels deprecatedChannels.forEach(notificationService::deleteNotificationChannel) notificationService.createNotificationChannelGroupsCompat( listOf( buildNotificationChannelGroup(GROUP_BACKUP_RESTORE) { setName(context.getString(R.string.label_backup)) }, buildNotificationChannelGroup(GROUP_DOWNLOADER) { setName(context.getString(R.string.download_notifier_downloader_title)) }, buildNotificationChannelGroup(GROUP_LIBRARY) { setName(context.getString(R.string.label_library)) }, buildNotificationChannelGroup(GROUP_APK_UPDATES) { setName(context.getString(R.string.label_recent_updates)) }, ) ) notificationService.createNotificationChannelsCompat( listOf( buildNotificationChannel(CHANNEL_COMMON, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_common)) }, buildNotificationChannel(CHANNEL_LIBRARY_PROGRESS, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_progress)) setGroup(GROUP_LIBRARY) setShowBadge(false) }, buildNotificationChannel(CHANNEL_LIBRARY_ERROR, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_errors)) setGroup(GROUP_LIBRARY) setShowBadge(false) }, buildNotificationChannel(CHANNEL_NEW_CHAPTERS, IMPORTANCE_DEFAULT) { setName(context.getString(R.string.channel_new_chapters)) }, buildNotificationChannel(CHANNEL_DOWNLOADER_PROGRESS, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_progress)) setGroup(GROUP_DOWNLOADER) setShowBadge(false) }, buildNotificationChannel(CHANNEL_DOWNLOADER_COMPLETE, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_complete)) setGroup(GROUP_DOWNLOADER) setShowBadge(false) }, buildNotificationChannel(CHANNEL_DOWNLOADER_ERROR, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_errors)) setGroup(GROUP_DOWNLOADER) setShowBadge(false) }, buildNotificationChannel(CHANNEL_BACKUP_RESTORE_PROGRESS, IMPORTANCE_LOW) { setName(context.getString(R.string.channel_progress)) setGroup(GROUP_BACKUP_RESTORE) setShowBadge(false) }, buildNotificationChannel(CHANNEL_BACKUP_RESTORE_COMPLETE, IMPORTANCE_HIGH) { setName(context.getString(R.string.channel_complete)) setGroup(GROUP_BACKUP_RESTORE) setShowBadge(false) setSound(null, null) }, buildNotificationChannel(CHANNEL_CRASH_LOGS, IMPORTANCE_HIGH) { setName(context.getString(R.string.channel_crash_logs)) }, buildNotificationChannel(CHANNEL_INCOGNITO_MODE, IMPORTANCE_LOW) { setName(context.getString(R.string.pref_incognito_mode)) }, buildNotificationChannel(CHANNEL_APP_UPDATE, IMPORTANCE_DEFAULT) { setGroup(GROUP_APK_UPDATES) setName(context.getString(R.string.channel_app_updates)) }, buildNotificationChannel(CHANNEL_EXTENSIONS_UPDATE, IMPORTANCE_DEFAULT) { setGroup(GROUP_APK_UPDATES) setName(context.getString(R.string.channel_ext_updates)) }, ) ) } }
app/src/main/java/eu/kanade/tachiyomi/data/notification/Notifications.kt
3331903731
/* * 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.orca.qos import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService import com.netflix.spinnaker.orca.ExecutionStatus.BUFFERED import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.events.BeforeInitialExecutionPersist import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.qos.BufferAction.BUFFER import com.netflix.spinnaker.orca.qos.BufferAction.ENQUEUE import com.netflix.spinnaker.orca.qos.BufferState.ACTIVE import com.netflix.spinnaker.orca.qos.BufferState.INACTIVE import com.netflix.spinnaker.orca.qos.bufferstate.BufferStateSupplierProvider import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode import org.jetbrains.spek.subject.SubjectSpek class ExecutionBufferActuatorTest : SubjectSpek<ExecutionBufferActuator>({ val configService: DynamicConfigService = mock() val bufferStateSupplier: BufferStateSupplier = mock() val policy1: BufferPolicy = mock() val policy2: BufferPolicy = mock() subject(CachingMode.GROUP) { ExecutionBufferActuator( BufferStateSupplierProvider(listOf(bufferStateSupplier)), configService, NoopRegistry(), listOf(policy1, policy2) ) } fun resetMocks() = reset(bufferStateSupplier, policy1, policy2) describe("buffering executions") { beforeGroup { whenever(configService.isEnabled(eq("qos"), any())) doReturn true whenever(configService.isEnabled(eq("qos.learningMode"), any())) doReturn false } afterGroup(::resetMocks) given("buffer state is INACTIVE") { val execution = pipeline { application = "spintest" status = NOT_STARTED } beforeGroup { whenever(bufferStateSupplier.enabled()) doReturn true whenever(bufferStateSupplier.get()) doReturn INACTIVE } afterGroup(::resetMocks) on("before initial persist event") { subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution)) } it("does nothing") { verify(policy1, never()).apply(execution) verify(policy2, never()).apply(execution) assert(execution.status == NOT_STARTED) } } given("buffer state is ACTIVE and policies decide ENQUEUE") { val execution = pipeline { application = "spintest" status = NOT_STARTED } beforeGroup { whenever(bufferStateSupplier.enabled()) doReturn true whenever(bufferStateSupplier.get()) doReturn ACTIVE whenever(policy1.apply(any())) doReturn BufferResult( action = ENQUEUE, force = false, reason = "Cannot determine action" ) whenever(policy2.apply(any())) doReturn BufferResult( action = ENQUEUE, force = false, reason = "Cannot determine action" ) } on("before initial persist event") { subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution)) } it("does nothing") { verify(policy1, times(1)).apply(execution) verify(policy2, times(1)).apply(execution) assert(execution.status == NOT_STARTED) } } given("buffer state is ACTIVE and policies decide BUFFER") { val execution = pipeline { application = "spintest" status = NOT_STARTED } beforeGroup { whenever(bufferStateSupplier.get()) doReturn ACTIVE whenever(policy1.apply(any())) doReturn BufferResult( action = BUFFER, force = false, reason = "Going to buffer" ) whenever(policy2.apply(any())) doReturn BufferResult( action = ENQUEUE, force = false, reason = "Cannot determine action" ) } on("before initial persist event") { subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution)) } it("does nothing") { verify(policy1, times(1)).apply(execution) verify(policy2, times(1)).apply(execution) assert(execution.status == BUFFERED) } } given("buffer state is ACTIVE and policy forces ENQUEUE") { val execution = pipeline { application = "spintest" status = NOT_STARTED } beforeGroup { whenever(bufferStateSupplier.get()) doReturn ACTIVE whenever(policy1.apply(any())) doReturn BufferResult( action = ENQUEUE, force = true, reason = "Going to buffer" ) whenever(policy2.apply(any())) doReturn BufferResult( action = BUFFER, force = false, reason = "Should buffer" ) } on("before initial persist event") { subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution)) } it("does nothing") { verify(policy1, times(1)).apply(execution) verify(policy2, times(1)).apply(execution) assert(execution.status == NOT_STARTED) } } given("in learning mode and buffer state is ACTIVE") { val execution = pipeline { application = "spintest" status = NOT_STARTED } beforeGroup { whenever(bufferStateSupplier.get()) doReturn ACTIVE whenever(policy1.apply(any())) doReturn BufferResult( action = BUFFER, force = false, reason = "Buffer" ) whenever(policy2.apply(any())) doReturn BufferResult( action = BUFFER, force = false, reason = "Should" ) whenever(configService.isEnabled(any(), any())) doReturn true } on("before initial persist event") { subject.beforeInitialPersist(BeforeInitialExecutionPersist("orca-core", execution)) } it("does nothing") { verify(policy1, times(1)).apply(execution) verify(policy2, times(1)).apply(execution) assert(execution.status == NOT_STARTED) } } } })
orca-qos/src/test/kotlin/com/netflix/spinnaker/orca/qos/ExecutionBufferActuatorTest.kt
489654270
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.barcodedetection import android.graphics.Canvas import android.graphics.Path import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.camera.GraphicOverlay import com.google.android.fhir.datacapture.contrib.views.barcode.mlkit.md.settings.PreferenceUtils import com.google.mlkit.vision.barcode.Barcode /** Guides user to move camera closer to confirm the detected barcode. */ internal class BarcodeConfirmingGraphic(overlay: GraphicOverlay, private val barcode: Barcode) : BarcodeGraphicBase(overlay) { override fun draw(canvas: Canvas) { super.draw(canvas) // Draws a highlighted path to indicate the current progress to meet size requirement. val sizeProgress = PreferenceUtils.getProgressToMeetBarcodeSizeRequirement(overlay, barcode) val path = Path() if (sizeProgress > 0.95f) { // To have a completed path with all corners rounded. path.moveTo(boxRect.left, boxRect.top) path.lineTo(boxRect.right, boxRect.top) path.lineTo(boxRect.right, boxRect.bottom) path.lineTo(boxRect.left, boxRect.bottom) path.close() } else { path.moveTo(boxRect.left, boxRect.top + boxRect.height() * sizeProgress) path.lineTo(boxRect.left, boxRect.top) path.lineTo(boxRect.left + boxRect.width() * sizeProgress, boxRect.top) path.moveTo(boxRect.right, boxRect.bottom - boxRect.height() * sizeProgress) path.lineTo(boxRect.right, boxRect.bottom) path.lineTo(boxRect.right - boxRect.width() * sizeProgress, boxRect.bottom) } canvas.drawPath(path, pathPaint) } }
contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/barcodedetection/BarcodeConfirmingGraphic.kt
3469314813
package imgui.impl.bgfx import glm_.b val fs_imgui_image = mapOf( "glsl" to intArrayOf( 0x46, 0x53, 0x48, 0x06, 0x6f, 0x1e, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x11, 0x75, // FSH.o.><.......u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x02, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, // .......s_texColo 0x72, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x30, 0x01, 0x00, 0x00, 0x76, 0x61, 0x72, 0x79, 0x69, // r......0...varyi 0x6e, 0x67, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x76, 0x5f, // ng highp vec2 v_ 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, // texcoord0;.unifo 0x72, 0x6d, 0x20, 0x68, 0x69, 0x67, 0x68, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x75, 0x5f, // rm highp vec4 u_ 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x3b, // imageLodEnabled; 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, // .uniform sampler 0x32, 0x44, 0x20, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x3b, 0x0a, 0x76, // 2D s_texColor;.v 0x6f, 0x69, 0x64, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x20, 0x28, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, // oid main ().{. 0x6c, 0x6f, 0x77, 0x70, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, // lowp vec4 tmpvar 0x5f, 0x31, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x2e, 0x78, // _1;. tmpvar_1.x 0x79, 0x7a, 0x20, 0x3d, 0x20, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, 0x65, 0x32, 0x44, 0x4c, 0x6f, // yz = texture2DLo 0x64, 0x20, 0x20, 0x20, 0x20, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, // d (s_texColor 0x2c, 0x20, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x2c, 0x20, 0x75, // , v_texcoord0, u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x2e, 0x78, 0x29, 0x2e, 0x78, 0x79, 0x7a, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x6d, 0x70, 0x76, 0x61, // .x).xyz;. tmpva 0x72, 0x5f, 0x31, 0x2e, 0x77, 0x20, 0x3d, 0x20, 0x28, 0x30, 0x2e, 0x32, 0x20, 0x2b, 0x20, 0x28, // r_1.w = (0.2 + ( 0x30, 0x2e, 0x38, 0x20, 0x2a, 0x20, 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, // 0.8 * u_imageLod 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x2e, 0x79, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x67, // Enabled.y));. g 0x6c, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x74, 0x6d, // l_FragColor = tm 0x70, 0x76, 0x61, 0x72, 0x5f, 0x31, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x00) // pvar_1;.}... .let { ByteArray(it.size) { i -> it[i].b } }, "spv" to intArrayOf( 0x46, 0x53, 0x48, 0x06, 0x6f, 0x1e, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x11, 0x75, // FSH.o.><.......u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x12, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, // .......s_texColo 0x72, 0x10, 0x00, 0x40, 0x00, 0x50, 0x00, 0xc8, 0x04, 0x00, 0x00, 0x03, 0x02, 0x23, 0x07, 0x00, // r..@.P.......#.. 0x00, 0x01, 0x00, 0x07, 0x00, 0x08, 0x00, 0xa9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, // ................ 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, // ...............G 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, // LSL.std.450..... 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x04, // ................ 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x65, // .......main....e 0x00, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, // ...n............ 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x05, 0x00, 0x00, 0x00, 0xf4, 0x01, 0x00, 0x00, 0x05, // ................ 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, // .......main..... 0x00, 0x07, 0x00, 0x22, 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, // ..."...s_texColo 0x72, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x07, 0x00, 0x25, // rSampler.......% 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x54, 0x65, 0x78, // ...s_texColorTex 0x74, 0x75, 0x72, 0x65, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x46, 0x00, 0x00, 0x00, 0x24, // ture.......F...$ 0x47, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x00, 0x06, 0x00, 0x08, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, // Global.....F.... 0x00, 0x00, 0x00, 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, // ...u_imageLodEna 0x62, 0x6c, 0x65, 0x64, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, // bled.......H.... 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x65, 0x00, 0x00, 0x00, 0x76, 0x5f, 0x74, 0x65, 0x78, // .......e...v_tex 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x00, 0x05, 0x00, 0x06, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x62, // coord0.....n...b 0x67, 0x66, 0x78, 0x5f, 0x46, 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x00, 0x00, 0x47, // gfx_FragData0..G 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, // ..."...".......G 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x47, // ..."...!...P...G 0x00, 0x04, 0x00, 0x25, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, // ...%...".......G 0x00, 0x04, 0x00, 0x25, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x48, // ...%...!...@...H 0x00, 0x05, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, // ...F.......#.... 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x46, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, // ...G...F.......G 0x00, 0x04, 0x00, 0x48, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, // ...H...".......G 0x00, 0x04, 0x00, 0x48, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x47, // ...H...!...0...G 0x00, 0x04, 0x00, 0x65, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, // ...e...........G 0x00, 0x04, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, // ...n............ 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, // .......!........ 0x00, 0x00, 0x00, 0x1a, 0x00, 0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x07, // ................ 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x08, 0x00, 0x00, 0x00, 0x07, // ... ............ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0b, // ................ 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0e, // ................ 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x21, // ........... ...! 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x21, // ...........;...! 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x24, // ..."....... ...$ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x24, // ...........;...$ 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x28, // ...%...........( 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x28, // ... .......+...( 0x00, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x31, // ...-...........1 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x46, 0x00, 0x00, 0x00, 0x0e, // ...........F.... 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x47, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x46, // ... ...G.......F 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x47, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x02, // ...;...G...H.... 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, // .......N... .... 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x00, // ...+...N...O.... 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x50, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x07, // ... ...P........ 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00, 0xcd, // ...+.......V.... 0xcc, 0x4c, 0x3e, 0x2b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0xcd, // .L>+.......W.... 0xcc, 0x4c, 0x3f, 0x2b, 0x00, 0x04, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x01, // .L?+...N...X.... 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x64, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, // ... ...d........ 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x64, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x01, // ...;...d...e.... 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x6d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0e, // ... ...m........ 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x6d, 0x00, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x03, // ...;...m...n.... 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, // ...6............ 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, // ...............= 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x3d, // .......#..."...= 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x3d, // .......&...%...= 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x41, // .......f...e...A 0x00, 0x06, 0x00, 0x50, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x2d, // ...P.......H...- 0x00, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x8d, // ...O...=........ 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x56, 0x00, 0x05, 0x00, 0x31, 0x00, 0x00, 0x00, 0xa5, // .......V...1.... 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x58, 0x00, 0x07, 0x00, 0x0e, // ...&...#...X.... 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0xa5, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x02, // ...........f.... 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x50, 0x00, 0x00, 0x00, 0x90, // .......A...P.... 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x3d, // ...H...-...X...= 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x85, // ................ 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x92, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x91, // ...........W.... 0x00, 0x00, 0x00, 0x81, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0x56, // ...............V 0x00, 0x00, 0x00, 0x92, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x96, // .......Q........ 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x07, // ...........Q.... 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x51, // ...............Q 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x98, 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0x02, // ................ 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x96, // ...P............ 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00, 0x98, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0x3e, // ...............> 0x00, 0x03, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, // ...n...........8 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00) // ....... .let { ByteArray(it.size) { i -> it[i].b } }, "dx9" to intArrayOf( 0x46, 0x53, 0x48, 0x06, 0x6f, 0x1e, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x0a, 0x73, // FSH.o.><.......s 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x30, 0x01, 0x00, 0x00, 0x01, 0x00, 0x11, // _texColor0...... 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, // u_imageLodEnable 0x64, 0x12, 0x01, 0x00, 0x00, 0x01, 0x00, 0x4c, 0x01, 0x00, 0x00, 0x00, 0x03, 0xff, 0xff, 0xfe, // d......L........ 0xff, 0x2e, 0x00, 0x43, 0x54, 0x41, 0x42, 0x1c, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x00, // ...CTAB......... 0x03, 0xff, 0xff, 0x02, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x91, 0x00, 0x00, 0x84, // ................ 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x50, // ...D...........P 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, // .......`........ 0x00, 0x00, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x5f, 0x74, 0x65, 0x78, // ...t.......s_tex 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0xab, 0x04, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, // Color........... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, // .......u_imageLo 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x00, 0xab, 0xab, 0x01, 0x00, 0x03, 0x00, 0x01, // dEnabled........ 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x73, 0x5f, 0x33, 0x5f, // ...........ps_3_ 0x30, 0x00, 0x4d, 0x69, 0x63, 0x72, 0x6f, 0x73, 0x6f, 0x66, 0x74, 0x20, 0x28, 0x52, 0x29, 0x20, // 0.Microsoft (R) 0x48, 0x4c, 0x53, 0x4c, 0x20, 0x53, 0x68, 0x61, 0x64, 0x65, 0x72, 0x20, 0x43, 0x6f, 0x6d, 0x70, // HLSL Shader Comp 0x69, 0x6c, 0x65, 0x72, 0x20, 0x31, 0x30, 0x2e, 0x31, 0x00, 0xab, 0x51, 0x00, 0x00, 0x05, 0x01, // iler 10.1..Q.... 0x00, 0x0f, 0xa0, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0xcd, 0xcc, 0x4c, 0x3f, 0xcd, // ......?......L?. 0xcc, 0x4c, 0x3e, 0x1f, 0x00, 0x00, 0x02, 0x05, 0x00, 0x00, 0x80, 0x00, 0x00, 0x03, 0x90, 0x1f, // .L>............. 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x90, 0x00, 0x08, 0x0f, 0xa0, 0x05, 0x00, 0x00, 0x03, 0x00, // ................ 0x00, 0x07, 0x80, 0x01, 0x00, 0xd0, 0xa0, 0x00, 0x00, 0xc4, 0x90, 0x01, 0x00, 0x00, 0x02, 0x00, // ................ 0x00, 0x08, 0x80, 0x00, 0x00, 0x00, 0xa0, 0x5f, 0x00, 0x00, 0x03, 0x00, 0x00, 0x0f, 0x80, 0x00, // ......._........ 0x00, 0xe4, 0x80, 0x00, 0x08, 0xe4, 0xa0, 0x01, 0x00, 0x00, 0x02, 0x00, 0x08, 0x07, 0x80, 0x00, // ................ 0x00, 0xe4, 0x80, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x0c, 0x80, 0x01, 0x00, 0xe4, 0xa0, 0x04, // ................ 0x00, 0x00, 0x04, 0x00, 0x08, 0x08, 0x80, 0x00, 0x00, 0x55, 0xa0, 0x00, 0x00, 0xaa, 0x80, 0x00, // .........U...... 0x00, 0xff, 0x80, 0xff, 0xff, 0x00, 0x00, 0x00) // ........ .let { ByteArray(it.size) { i -> it[i].b } }, "dx11" to intArrayOf( 0x46, 0x53, 0x48, 0x06, 0x6f, 0x1e, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x11, 0x75, // FSH.o.><.......u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x12, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, // .......s_texColo 0x72, 0x30, 0x01, 0x00, 0x00, 0x01, 0x00, 0x84, 0x01, 0x00, 0x00, 0x44, 0x58, 0x42, 0x43, 0x60, // r0.........DXBC` 0x83, 0xa2, 0x5c, 0x77, 0x3d, 0xcc, 0x9b, 0xb9, 0x73, 0xdf, 0x41, 0x6b, 0x18, 0x8f, 0x0e, 0x01, // ...w=...s.Ak.... 0x00, 0x00, 0x00, 0x84, 0x01, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x84, // ...........,.... 0x00, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x49, 0x53, 0x47, 0x4e, 0x50, 0x00, 0x00, 0x00, 0x02, // .......ISGNP.... 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // .......8........ 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x44, // ...............D 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, // ................ 0x00, 0x00, 0x00, 0x03, 0x03, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x50, 0x4f, 0x53, 0x49, 0x54, 0x49, // .......SV_POSITI 0x4f, 0x4e, 0x00, 0x54, 0x45, 0x58, 0x43, 0x4f, 0x4f, 0x52, 0x44, 0x00, 0xab, 0xab, 0xab, 0x4f, // ON.TEXCOORD....O 0x53, 0x47, 0x4e, 0x2c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x20, // SGN,........... 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, // ................ 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x53, 0x56, 0x5f, 0x54, 0x41, 0x52, 0x47, 0x45, 0x54, // .......SV_TARGET 0x00, 0xab, 0xab, 0x53, 0x48, 0x44, 0x52, 0xc4, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x31, // ...SHDR....@...1 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x04, 0x46, 0x8e, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // ...Y...F. ...... 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x03, 0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, // ...Z....`......X 0x18, 0x00, 0x04, 0x00, 0x70, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x00, 0x00, 0x62, // ....p......UU..b 0x10, 0x00, 0x03, 0x32, 0x10, 0x10, 0x00, 0x01, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x03, 0xf2, // ...2.......e.... 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x48, // ......h.......H 0x00, 0x00, 0x0c, 0xf2, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x10, 0x10, 0x00, 0x01, // ...........F.... 0x00, 0x00, 0x00, 0x46, 0x7e, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x10, 0x00, 0x00, // ...F~.......`... 0x00, 0x00, 0x00, 0x0a, 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, // ..... .........6 0x00, 0x00, 0x05, 0x72, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x02, 0x10, 0x00, 0x00, // ...r ......F.... 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x0a, 0x82, 0x20, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, // ...2.... ....... 0x80, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0xcd, // . ..........@... 0xcc, 0x4c, 0x3f, 0x01, 0x40, 0x00, 0x00, 0xcd, 0xcc, 0x4c, 0x3e, 0x3e, 0x00, 0x00, 0x01, 0x00, // .L?.@....L>>.... 0x00, 0x10, 0x00) // ... .let { ByteArray(it.size) { i -> it[i].b } }, "mtl" to intArrayOf( 0x46, 0x53, 0x48, 0x06, 0x6f, 0x1e, 0x3e, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x11, 0x75, // FSH.o.><.......u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x12, 0x01, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, // .......s_texColo 0x72, 0x10, 0x00, 0x40, 0x00, 0x50, 0x00, 0xd2, 0x02, 0x00, 0x00, 0x23, 0x69, 0x6e, 0x63, 0x6c, // r..@.P.....#incl 0x75, 0x64, 0x65, 0x20, 0x3c, 0x6d, 0x65, 0x74, 0x61, 0x6c, 0x5f, 0x73, 0x74, 0x64, 0x6c, 0x69, // ude <metal_stdli 0x62, 0x3e, 0x0a, 0x23, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x20, 0x3c, 0x73, 0x69, 0x6d, // b>.#include <sim 0x64, 0x2f, 0x73, 0x69, 0x6d, 0x64, 0x2e, 0x68, 0x3e, 0x0a, 0x0a, 0x75, 0x73, 0x69, 0x6e, 0x67, // d/simd.h>..using 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x6d, 0x65, 0x74, 0x61, 0x6c, // namespace metal 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x20, 0x5f, 0x47, 0x6c, 0x6f, 0x62, 0x61, // ;..struct _Globa 0x6c, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x75, // l.{. float4 u 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, // _imageLodEnabled 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x20, 0x78, 0x6c, 0x61, // ;.};..struct xla 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x0a, 0x7b, 0x0a, 0x20, // tMtlMain_out.{. 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x34, 0x20, 0x62, 0x67, 0x66, 0x78, 0x5f, 0x46, // float4 bgfx_F 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x20, 0x5b, 0x5b, 0x63, 0x6f, 0x6c, 0x6f, 0x72, // ragData0 [[color 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, // (0)]];.};..struc 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x6e, // t xlatMtlMain_in 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x32, 0x20, 0x76, 0x5f, // .{. float2 v_ 0x74, 0x65, 0x78, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x20, 0x5b, 0x5b, 0x75, 0x73, 0x65, 0x72, // texcoord0 [[user 0x28, 0x6c, 0x6f, 0x63, 0x6e, 0x30, 0x29, 0x5d, 0x5d, 0x3b, 0x0a, 0x7d, 0x3b, 0x0a, 0x0a, 0x66, // (locn0)]];.};..f 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, // ragment xlatMtlM 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, // ain_out xlatMtlM 0x61, 0x69, 0x6e, 0x28, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, 0x61, 0x69, 0x6e, 0x5f, // ain(xlatMtlMain_ 0x69, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x5b, 0x5b, 0x73, 0x74, 0x61, 0x67, 0x65, 0x5f, 0x69, 0x6e, // in in [[stage_in 0x5d, 0x5d, 0x2c, 0x20, 0x63, 0x6f, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x74, 0x20, 0x5f, 0x47, 0x6c, // ]], constant _Gl 0x6f, 0x62, 0x61, 0x6c, 0x26, 0x20, 0x5f, 0x6d, 0x74, 0x6c, 0x5f, 0x75, 0x20, 0x5b, 0x5b, 0x62, // obal& _mtl_u [[b 0x75, 0x66, 0x66, 0x65, 0x72, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x2c, 0x20, 0x74, 0x65, 0x78, 0x74, // uffer(0)]], text 0x75, 0x72, 0x65, 0x32, 0x64, 0x3c, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x3e, 0x20, 0x73, 0x5f, 0x74, // ure2d<float> s_t 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x5b, 0x5b, 0x74, 0x65, 0x78, 0x74, 0x75, 0x72, // exColor [[textur 0x65, 0x28, 0x30, 0x29, 0x5d, 0x5d, 0x2c, 0x20, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x20, // e(0)]], sampler 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, // s_texColorSample 0x72, 0x20, 0x5b, 0x5b, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x28, 0x30, 0x29, 0x5d, 0x5d, // r [[sampler(0)]] 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x6c, 0x61, 0x74, 0x4d, 0x74, 0x6c, 0x4d, // ).{. xlatMtlM 0x61, 0x69, 0x6e, 0x5f, 0x6f, 0x75, 0x74, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x7b, 0x7d, // ain_out out = {} 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x62, 0x67, 0x66, 0x78, 0x5f, 0x46, // ;. out.bgfx_F 0x72, 0x61, 0x67, 0x44, 0x61, 0x74, 0x61, 0x30, 0x20, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, // ragData0 = float 0x34, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x2e, 0x73, 0x61, 0x6d, // 4(s_texColor.sam 0x70, 0x6c, 0x65, 0x28, 0x73, 0x5f, 0x74, 0x65, 0x78, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x53, 0x61, // ple(s_texColorSa 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x2c, 0x20, 0x69, 0x6e, 0x2e, 0x76, 0x5f, 0x74, 0x65, 0x78, 0x63, // mpler, in.v_texc 0x6f, 0x6f, 0x72, 0x64, 0x30, 0x2c, 0x20, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x28, 0x5f, 0x6d, 0x74, // oord0, level(_mt 0x6c, 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, // l_u.u_imageLodEn 0x61, 0x62, 0x6c, 0x65, 0x64, 0x2e, 0x78, 0x29, 0x29, 0x2e, 0x78, 0x79, 0x7a, 0x2c, 0x20, 0x30, // abled.x)).xyz, 0 0x2e, 0x32, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x32, 0x39, 0x38, 0x30, 0x32, 0x33, 0x32, // .200000002980232 0x32, 0x33, 0x38, 0x37, 0x36, 0x39, 0x35, 0x33, 0x31, 0x32, 0x35, 0x20, 0x2b, 0x20, 0x28, 0x30, // 23876953125 + (0 0x2e, 0x38, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x31, 0x39, 0x32, 0x30, 0x39, 0x32, 0x38, // .800000011920928 0x39, 0x35, 0x35, 0x30, 0x37, 0x38, 0x31, 0x32, 0x35, 0x20, 0x2a, 0x20, 0x5f, 0x6d, 0x74, 0x6c, // 955078125 * _mtl 0x5f, 0x75, 0x2e, 0x75, 0x5f, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x4c, 0x6f, 0x64, 0x45, 0x6e, 0x61, // _u.u_imageLodEna 0x62, 0x6c, 0x65, 0x64, 0x2e, 0x79, 0x29, 0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, // bled.y));. re 0x74, 0x75, 0x72, 0x6e, 0x20, 0x6f, 0x75, 0x74, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x00, 0x00, 0x10, // turn out;.}..... 0x00) // . .let { ByteArray(it.size) { i -> it[i].b } })
bgfx/src/main/kotlin/imgui/impl/bgfx/fs_imgui_image.kt
2564744279
package it.codingjam.github.ui.search import android.content.SharedPreferences import com.nalulabs.prefs.string import it.codingjam.github.FeatureAppScope import it.codingjam.github.core.GithubInteractor import it.codingjam.github.core.OpenForTesting import it.codingjam.github.core.RepoId import it.codingjam.github.util.* import it.codingjam.github.vo.lce import java.util.* import javax.inject.Inject @OpenForTesting @FeatureAppScope class SearchUseCase @Inject constructor( private val githubInteractor: GithubInteractor, prefs: SharedPreferences ) { private var lastSearch by prefs.string("") fun initialState() = SearchViewState(lastSearch) fun setQuery(originalInput: String, state: SearchViewState): ActionsFlow<SearchViewState> { lastSearch = originalInput val input = originalInput.toLowerCase(Locale.getDefault()).trim { it <= ' ' } return if (state.repos.data?.searchInvoked != true || input != state.query) { reloadData(input) } else emptyActionsFlow() } fun loadNextPage(state: SearchViewState): ActionsFlow<SearchViewState> = actionsFlow<ReposViewState> { state.repos.doOnData { (_, nextPage, _, loadingMore) -> val query = state.query if (query.isNotEmpty() && nextPage != null && !loadingMore) { emit { copy(loadingMore = true) } try { val (items, newNextPage) = githubInteractor.searchNextPage(query, nextPage) emit { copy(list = list + items, nextPage = newNextPage, loadingMore = false) } } catch (t: Exception) { emit { copy(loadingMore = false) } emit(ErrorSignal(t)) } } } }.mapActions { stateAction -> copy(repos = repos.map { stateAction(it) }) } private fun reloadData(query: String): ActionsFlow<SearchViewState> = lce { val (items, nextPage) = githubInteractor.search(query) ReposViewState(items, nextPage, true) }.mapActions { stateAction -> copy(repos = stateAction(repos), query = query) } fun refresh(state: SearchViewState): ActionsFlow<SearchViewState> { return if (state.query.isNotEmpty()) { reloadData(state.query) } else emptyActionsFlow() } fun openRepoDetail(id: RepoId) = NavigationSignal("repo", id) }
uisearch/src/main/java/it/codingjam/github/ui/search/SearchUseCase.kt
4159627483
fun main(args: Array<String>) { val name = "kotlin" var new1:String new1 = "Newbee" println(name) println(new1) println("$name, $new1") }
languages/kotlin/programming-kotlin/2-chapter/0-ValVar.kt
1268570262
package org.kymjs.oschina.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import org.kymjs.oschina.R /** * 今日话题,(话题列表) * @author kymjs (http://www.kymjs.com/) on 8/13/15. */ public class TopicList : BaseMainFragment() { override fun inflaterView(layoutInflater: LayoutInflater, viewGroup: ViewGroup, bundle: Bundle?): View? { val rootView: View = layoutInflater.inflate(R.layout.frag_main_topiclist, null) return rootView } override fun initWidget(parentView: View?) { super.initWidget(parentView) } }
app/src/main/java/org/kymjs/oschina/ui/fragment/TopicList.kt
1453289764
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.annotationprocessing.propertyelement import com.tickaroo.tikxml.annotation.PropertyElement import com.tickaroo.tikxml.annotation.Xml import com.tickaroo.tikxml.annotationprocessing.DateConverter import java.util.Date /** * @author Hannes Dorfmann */ @Xml(name = "item") data class PropertyItemDataClass( @field:PropertyElement @JvmField var aString: String? = null, @field:PropertyElement @JvmField var anInt: Int = 0, @field:PropertyElement @JvmField var aBoolean: Boolean = false, @field:PropertyElement @JvmField var aDouble: Double = 0.toDouble(), @field:PropertyElement @JvmField var aLong: Long = 0, @field:PropertyElement(converter = DateConverter::class) @JvmField var aDate: Date? = null, @field:PropertyElement @JvmField var intWrapper: Int? = null, @field:PropertyElement @JvmField var booleanWrapper: Boolean? = null, @field:PropertyElement @JvmField var doubleWrapper: Double? = null, @field:PropertyElement @JvmField var longWrapper: Long? = null )
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/propertyelement/PropertyItemDataClass.kt
100623731
// 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.openapi.vcs.changes import com.intellij.diff.FrameDiffTool import com.intellij.diff.util.DiffPlaces import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.* import com.intellij.openapi.vcs.changes.actions.diff.lst.LocalChangeListDiffTool.ALLOW_EXCLUDE_FROM_COMMIT import com.intellij.openapi.vcs.changes.ui.ChangesBrowserChangeListNode import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode.MODIFIED_WITHOUT_EDITING_TAG import com.intellij.openapi.vcs.changes.ui.ChangesListView import com.intellij.openapi.vcs.changes.ui.TagChangesBrowserNode import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ui.tree.TreeUtil import com.intellij.vcs.commit.EditedCommitDetails import com.intellij.vcs.commit.EditedCommitNode import one.util.streamex.StreamEx import java.util.* import java.util.stream.Stream private fun wrap(project: Project, changesNodes: Stream<ChangesBrowserNode<*>>, unversioned: Stream<FilePath>): Stream<Wrapper> = Stream.concat( changesNodes.map { wrapNode(project, it) }.filter(Objects::nonNull), unversioned.map { UnversionedFileWrapper(it) } ) private fun wrapNode(project: Project, node: ChangesBrowserNode<*>): Wrapper? { return when (val nodeObject = node.userObject) { is Change -> ChangeWrapper(nodeObject, node.let(::wrapNodeToTag)) is VirtualFile -> if (findTagNode(node)?.userObject == MODIFIED_WITHOUT_EDITING_TAG) wrapHijacked(project, nodeObject) else null else -> null } } private fun wrapHijacked(project: Project, file: VirtualFile): Wrapper? { return ChangesListView.toHijackedChange(project, file) ?.let { c -> ChangeWrapper(c, MODIFIED_WITHOUT_EDITING_TAG) } } private fun wrapNodeToTag(node: ChangesBrowserNode<*>): ChangesBrowserNode.Tag? { return findChangeListNode(node)?.let { ChangeListWrapper(it.userObject) } ?: findAmendNode(node)?.let { AmendChangeWrapper(it.userObject) } } private fun findTagNode(node: ChangesBrowserNode<*>): TagChangesBrowserNode? = findNodeOfType(node) private fun findChangeListNode(node: ChangesBrowserNode<*>): ChangesBrowserChangeListNode? = findNodeOfType(node) private fun findAmendNode(node: ChangesBrowserNode<*>): EditedCommitNode? = findNodeOfType(node) private inline fun <reified T : ChangesBrowserNode<*>> findNodeOfType(node: ChangesBrowserNode<*>): T? { if (node is T) return node var parent = node.parent while (parent != null) { if (parent is T) return parent parent = parent.parent } return null } private class ChangesViewDiffPreviewProcessor(private val changesView: ChangesListView, private val isInEditor: Boolean) : ChangeViewDiffRequestProcessor(changesView.project, if (isInEditor) DiffPlaces.DEFAULT else DiffPlaces.CHANGES_VIEW) { init { putContextUserData(DiffUserDataKeysEx.LAST_REVISION_WITH_LOCAL, true) } override fun shouldAddToolbarBottomBorder(toolbarComponents: FrameDiffTool.ToolbarComponents): Boolean { return !isInEditor || super.shouldAddToolbarBottomBorder(toolbarComponents) } override fun getSelectedChanges(): Stream<Wrapper> = wrap(project, StreamEx.of(changesView.selectedChangesNodes.iterator()), StreamEx.of(changesView.selectedUnversionedFiles.iterator())) override fun getAllChanges(): Stream<Wrapper> = wrap(project, StreamEx.of(changesView.changesNodes.iterator()), changesView.unversionedFiles) override fun showAllChangesForEmptySelection(): Boolean = false override fun selectChange(change: Wrapper) { val tag = (change.tag as? ChangesViewUserObjectTag)?.userObject val treePath = changesView.findNodePathInTree(change.userObject, tag) ?: return TreeUtil.selectPath(changesView, treePath, false) } fun setAllowExcludeFromCommit(value: Boolean) { if (DiffUtil.isUserDataFlagSet(ALLOW_EXCLUDE_FROM_COMMIT, context) == value) return context.putUserData(ALLOW_EXCLUDE_FROM_COMMIT, value) fireDiffSettingsChanged() } fun fireDiffSettingsChanged() { dropCaches() updateRequest(true) } } private class AmendChangeWrapper(override val userObject: EditedCommitDetails) : ChangesViewUserObjectTag { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as AmendChangeWrapper if (userObject.commit.id != other.userObject.commit.id) return false return true } override fun toString(): String = userObject.commit.subject override fun hashCode(): Int = userObject.commit.id.hashCode() } private class ChangeListWrapper(override val userObject: ChangeList) : ChangesViewUserObjectTag { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ChangeListWrapper if (userObject.name != other.userObject.name) return false return true } override fun hashCode(): Int = userObject.name.hashCode() override fun toString(): String = userObject.name } interface ChangesViewUserObjectTag : ChangesBrowserNode.Tag { val userObject: Any }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangesViewDiffPreviewProcessor.kt
3215867255
package soutvoid.com.DsrWeatherApp.app.log import android.util.Log import timber.log.Timber /** * логгирует в logcat * логи уровня DEBUG и выше логируется в [RemoteLogger] */ class LoggerTree @JvmOverloads constructor(private val mLogPriority: Int = Log.DEBUG) : Timber.DebugTree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { super.log(priority, tag, message, t) try { if (priority >= mLogPriority) { RemoteLogger.logMessage(String.format(REMOTE_LOGGER_LOG_FORMAT, tag, message)) if (t != null && priority >= Log.ERROR) { RemoteLogger.logError(t) } } } catch (e: Exception) { super.log(priority, tag, "Remote logger error", t) } } companion object { val REMOTE_LOGGER_LOG_FORMAT = "%s: %s" val REMOTE_LOGGER_SEND_LOG_ERROR = "error sending to RemoteLogger" } } /** * приоритет по умолчанию - DEBUG */
app/src/main/java/soutvoid/com/DsrWeatherApp/app/log/LoggerTree.kt
596413235
package com.homemods.relay.pi.pin import com.homemods.relay.pin.InputPin import com.homemods.relay.pin.PinEdge import com.homemods.relay.pin.PinState import com.pi4j.io.gpio.GpioPinDigitalInput import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent import com.pi4j.io.gpio.event.GpioPinListenerDigital /** * @author sergeys */ class PiInputPin(val inputPin: GpioPinDigitalInput) : InputPin { override fun get(): PinState = inputPin.state.convert() override fun addListener(listener: (PinState, PinEdge) -> Unit) { inputPin.addListener(object : GpioPinListenerDigital { override fun handleGpioPinDigitalStateChangeEvent(event: GpioPinDigitalStateChangeEvent) { listener(event.state.convert(), event.edge.convert()) } }) } }
pi/src/com/homemods/relay/pi/pin/PiInputPin.kt
3944809048
fun empty() { fun test() { } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/fromCompanion/overloadsExtension/Empty.kt
1821896165
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.referrersx import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class AttachedEntityToParentImpl: AttachedEntityToParent, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _data: String? = null override val data: String get() = _data!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: AttachedEntityToParentData?): ModifiableWorkspaceEntityBase<AttachedEntityToParent>(), AttachedEntityToParent.Builder { constructor(): this(AttachedEntityToParentData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity AttachedEntityToParent is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isDataInitialized()) { error("Field AttachedEntityToParent#data should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field AttachedEntityToParent#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData().data = value changedProperty.add("data") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): AttachedEntityToParentData = result ?: super.getEntityData() as AttachedEntityToParentData override fun getEntityClass(): Class<AttachedEntityToParent> = AttachedEntityToParent::class.java } } class AttachedEntityToParentData : WorkspaceEntityData<AttachedEntityToParent>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<AttachedEntityToParent> { val modifiable = AttachedEntityToParentImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): AttachedEntityToParent { val entity = AttachedEntityToParentImpl() entity._data = data entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return AttachedEntityToParent::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as AttachedEntityToParentData if (this.data != other.data) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as AttachedEntityToParentData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/AttachedEntityToParentImpl.kt
3591296275
// "Create parameter 'foo'" "false" // ACTION: Create local variable 'foo' // ACTION: Create property 'foo' // ACTION: Rename reference // ERROR: Unresolved reference: foo object A { val test: Int get() { return <caret>foo } }
plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createVariable/parameter/inAccessorInObject.kt
286041653
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.profile.codeInspection.ui.table import com.intellij.analysis.AnalysisBundle import com.intellij.psi.search.scope.packageSet.NamedScope import com.intellij.ui.OffsetIcon import com.intellij.ui.table.TableView import com.intellij.util.ui.ColumnInfo import com.intellij.util.ui.JBUI import com.intellij.util.ui.ListTableModel import com.intellij.util.ui.table.IconTableCellRenderer import javax.swing.Icon import javax.swing.JTable import javax.swing.ListSelectionModel import javax.swing.table.TableCellRenderer class ScopesOrderTable : TableView<NamedScope>() { private val model = ListTableModel<NamedScope>(IconColumn, NameColumn, SetColumn) init { setModelAndUpdateColumns(model) rowSelectionAllowed = true columnSelectionAllowed = false setShowGrid(false) tableHeader.reorderingAllowed = false setSelectionMode(ListSelectionModel.SINGLE_SELECTION) getColumnModel().getColumn(0).apply { maxWidth = JBUI.scale(34) minWidth = JBUI.scale(34) } getColumnModel().getColumn(1).apply { preferredWidth = JBUI.scale(200) } } fun updateItems(scopes: Collection<NamedScope>) { while (model.rowCount > 0) model.removeRow(0) model.addRows(scopes) } fun getScopeAt(i: Int): NamedScope? { return model.getItem(i) } fun moveUp() { if (selectedRow > 0) move(-1) } fun moveDown() { if (selectedRow + 1 < rowCount) move(1) } private fun move(offset: Int) { val selected = selectedRow model.exchangeRows(selected, selected + offset) selectionModel.apply { clearSelection() addSelectionInterval(selected + offset, selected + offset) } scrollRectToVisible(getCellRect(selectedRow, 0, true)) repaint() } private object IconColumn : ColumnInfo<NamedScope, String?>("") { override fun valueOf(item: NamedScope): String = "" override fun getRenderer(item: NamedScope?): TableCellRenderer { return object : IconTableCellRenderer<String>() { override fun getIcon(value: String, table: JTable?, row: Int): Icon? { when (item?.icon) { is OffsetIcon -> return (item.icon as OffsetIcon).icon else -> return item?.icon } } override fun isCenterAlignment(): Boolean = true } } } private object NameColumn : ColumnInfo<NamedScope, String>(AnalysisBundle.message("inspections.settings.scopes.name")) { override fun valueOf(item: NamedScope): String = item.presentableName } private object SetColumn : ColumnInfo<NamedScope, String>(AnalysisBundle.message("inspections.settings.scopes.pattern")) { override fun valueOf(item: NamedScope): String = item.value?.text ?: "" } }
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/table/ScopesOrderTable.kt
3239556827
fun foo(s: String){} fun foo(c: Char){} fun bar(b: Boolean, s: String, c: Char){ foo(if (b) <caret>) } // EXIST: s // EXIST: c // ABSENT: b
plugins/kotlin/completion/tests/testData/smart/ifValue/1.kt
1798968705
// snippet-sourcedescription:[DescribeDBInstances.kt demonstrates how to describe Amazon Relational Database Service (RDS) instances.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Relational Database Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.rds // snippet-start:[rds.kotlin.describe_instances.import] import aws.sdk.kotlin.services.rds.RdsClient import aws.sdk.kotlin.services.rds.model.DescribeDbInstancesRequest // snippet-end:[rds.kotlin.describe_instances.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { describeInstances() } // snippet-start:[rds.kotlin.describe_instances.main] suspend fun describeInstances() { RdsClient { region = "us-west-2" }.use { rdsClient -> val response = rdsClient.describeDbInstances(DescribeDbInstancesRequest {}) response.dbInstances?.forEach { instance -> println("Instance Identifier is ${instance.dbInstanceIdentifier}") println("The Engine is ${instance.engine}") println("Connection endpoint is ${instance.endpoint?.address}") } } } // snippet-end:[rds.kotlin.describe_instances.main]
kotlin/services/rds/src/main/kotlin/com/kotlin/rds/DescribeDBInstances.kt
2056235871
// snippet-sourcedescription:[ListNamedQueryExample.Kt demonstrates how to obtain a list of named query Id values.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Athena] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.athena // snippet-start:[athena.kotlin.ListNamedQueryExample.import] import aws.sdk.kotlin.services.athena.AthenaClient import aws.sdk.kotlin.services.athena.model.ListNamedQueriesRequest // snippet-end:[athena.kotlin.ListNamedQueryExample.import] suspend fun main() { listNamedQueries() } // snippet-start:[athena.kotlin.ListNamedQueryExample.main] suspend fun listNamedQueries() { val request = ListNamedQueriesRequest { this.maxResults = 10 } AthenaClient { region = "us-west-2" }.use { athenaClient -> val responses = athenaClient.listNamedQueries(request) responses.namedQueryIds?.forEach { queries -> println("Retrieved account alias $queries") } } } // snippet-end:[athena.kotlin.ListNamedQueryExample.main]
kotlin/services/athena/src/main/kotlin/com/kotlin/athena/ListNamedQueryExample.kt
1111665279
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.photolog_start import android.content.ContentResolver import android.content.Context import android.net.Uri import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.io.File class PhotoSaverRepository(context: Context, private val contentResolver: ContentResolver) { private val _photos = mutableListOf<File>() fun getPhotos() = _photos.toList() fun isEmpty() = _photos.isEmpty() fun canAddPhoto() = _photos.size < MAX_LOG_PHOTOS_LIMIT private val cacheFolder = File(context.cacheDir, "photos").also { it.mkdir() } val photoFolder = File(context.filesDir, "photos").also { it.mkdir() } private fun generateFileName() = "${System.currentTimeMillis()}.jpg" private fun generatePhotoLogFile() = File(photoFolder, generateFileName()) fun generatePhotoCacheFile() = File(cacheFolder, generateFileName()) fun cacheCapturedPhoto(photo: File) { if (_photos.size + 1 > MAX_LOG_PHOTOS_LIMIT) { return } _photos += photo } @Suppress("BlockingMethodInNonBlockingContext") suspend fun cacheFromUri(uri: Uri) { withContext(Dispatchers.IO) { if (_photos.size + 1 > MAX_LOG_PHOTOS_LIMIT) { return@withContext } contentResolver.openInputStream(uri)?.use { input -> val cachedPhoto = generatePhotoCacheFile() cachedPhoto.outputStream().use { output -> input.copyTo(output) _photos += cachedPhoto } } } } suspend fun cacheFromUris(uris: List<Uri>) { uris.forEach { cacheFromUri(it) } } suspend fun removeFile(photo: File) { withContext(Dispatchers.IO) { photo.delete() _photos -= photo } } suspend fun savePhotos(): List<File> { return withContext(Dispatchers.IO) { val savedPhotos = _photos.map { it.copyTo(generatePhotoLogFile()) } _photos.forEach { it.delete() } _photos.clear() savedPhotos } } }
PhotoLog_start/src/main/java/com/example/photolog_start/PhotoSaverRepository.kt
597780514
package co.smartreceipts.android.model import androidx.annotation.StringRes import co.smartreceipts.core.sync.model.Syncable /** * Provides a contract for how each individual column in a report should operate */ interface Column<T> : Keyed, Syncable, Draggable<Column<T>> { /** * Gets the column type of this particular column * * @return int enum type from [ColumnDefinitions] */ val type: Int /** * Gets the column header resource id of this particular column * * @return the [StringRes] of the header for this particular column */ @get:StringRes val headerStringResId: Int /** * Gets the value of a particular row item as determined by this column. If this column * represented the name of this item, [T], then this would return the name. * * @param rowItem the row item to get the value for (based on the column definition) * @return the [String] representation of the value */ fun getValue(rowItem: T): String /** * Gets the footer value for this particular column based on a series of rows. The * footer in a report generally tends to correspond to some type of summation. * * @param rows the [List] of rows of [T] to process for the footer * @return the [String] representation of the footer for this particular column */ fun getFooter(rows: List<T>): String }
app/src/main/java/co/smartreceipts/android/model/Column.kt
8031256
package com.github.kurtyan.fanfou4j.request.account import com.github.kurtyan.fanfou4j.core.AbstractRequest import com.github.kurtyan.fanfou4j.core.HttpMethod import com.github.kurtyan.fanfou4j.entity.User import com.github.kurtyan.fanfou4j.request.RequestMode /** * Created by yanke on 2016/12/19. */ class UpdateProfileImageRequest : AbstractRequest<User>("/account/update_profile_image.json", HttpMethod.POST){ var image: String by stringDelegate var mode: RequestMode by requestModeDelegate }
src/main/java/com/github/kurtyan/fanfou4j/request/account/UpdateProfileImageRequest.kt
2600272019
package top.zbeboy.isy.web import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.ui.ModelMap import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.servlet.LocaleResolver import org.springframework.web.servlet.ModelAndView import top.zbeboy.isy.annotation.logging.RecordSystemLogging import top.zbeboy.isy.config.ISYProperties import top.zbeboy.isy.config.Workbook import top.zbeboy.isy.service.common.UploadService import top.zbeboy.isy.service.system.AuthoritiesService import top.zbeboy.isy.web.util.AjaxUtils import java.io.File import java.util.* import javax.annotation.Resource import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** * Created by zbeboy 2017-11-03 . **/ @Controller open class MainController { @Resource open lateinit var localeResolver: LocaleResolver @Resource open lateinit var authoritiesService: AuthoritiesService @Autowired open lateinit var isyProperties: ISYProperties @Resource open lateinit var uploadService: UploadService /** * main page * * @return main page */ @RequestMapping("/") fun root(): String { return "index" } /** * Home page. * * @return home page */ @RequestMapping("/index") fun index(): String { return "index" } /** * 登录页 * * @return 登录页. */ @RequestMapping(value = ["/login"], method = [(RequestMethod.GET)]) fun login(): String { return if (!authoritiesService.isAnonymousAuthenticated()) { "redirect:/web/menu/backstage" } else { "login" } } /** * 注册页 * * @param type 注册类型(学生,教职工) * @return 注册页 */ @RequestMapping(value = ["/register"], method = [(RequestMethod.GET)]) fun register(@RequestParam("type") type: String): String { // 注册学生 if (type.equals(Workbook.STUDENT_REGIST, ignoreCase = true)) { return "student_register" } // 注册教师 return if (type.equals(Workbook.STAFF_REGIST, ignoreCase = true)) { "staff_register" } else "login" } /** * 注册完成时,但并不是成功 * * @param modelMap 页面对象 * @return 完成页面 */ @RequestMapping(value = ["/register/finish"], method = [(RequestMethod.GET)]) fun registerFinish(modelMap: ModelMap): String { modelMap["msg"] = "验证邮件已发送至您的邮箱,请登录邮箱进行验证!" return "msg" } /** * 忘记密码 * * @return 忘记密码页面 */ @RequestMapping(value = ["/user/login/password/forget"], method = [(RequestMethod.GET)]) fun loginPasswordForget(): String { return "forget_password" } /** * 忘记密码完成时,但并不是成功 * * @param modelMap 页面对象 * @return 完成页面 */ @RequestMapping(value = ["/user/login/password/forget/finish"], method = [(RequestMethod.GET)]) fun loginPasswordForgetFinish(modelMap: ModelMap): String { modelMap["msg"] = "密码重置邮件已发送至您的邮箱。" return "msg" } /** * 密码重置成功 * * @param modelMap 页面对象 * @return 重置成功页面 */ @RequestMapping(value = ["/user/login/password/reset/finish"], method = [(RequestMethod.GET)]) fun passwordResetFinish(modelMap: ModelMap): String { modelMap["msg"] = "密码重置成功。" return "msg" } /** * 后台欢迎页 * * @return 后台欢迎页 */ @RecordSystemLogging(module = "Main", methods = "backstage", description = "访问系统主页") @RequestMapping(value = ["/web/menu/backstage"], method = [(RequestMethod.GET)]) open fun backstage(request: HttpServletRequest): String { return "backstage" } /** * 语言切换,暂时不用 * * @param request 请求对象 * @param response 响应对象 * @param language 语言 * @return 重置页面 */ @RequestMapping("/language") fun language(request: HttpServletRequest, response: HttpServletResponse, language: String): ModelAndView { val languageLowerCase = language.toLowerCase() if (languageLowerCase == "") { return ModelAndView("redirect:/") } else { when (languageLowerCase) { "zh_cn" -> localeResolver.setLocale(request, response, Locale.CHINA) "en" -> localeResolver.setLocale(request, response, Locale.ENGLISH) else -> localeResolver.setLocale(request, response, Locale.CHINA) } } return ModelAndView("redirect:/") } /** * 用于集群时,对服务器心跳检测 * * @return 服务器是否正常运行 */ @RequestMapping(value = ["/server/probe"], method = [(RequestMethod.GET)]) @ResponseBody fun serverHealthCheck(): AjaxUtils<*> { return AjaxUtils.of<Any>().success().msg("Server is running ...") } /** * let's encrypt certificate check. * * @param request 请求 * @param response 响应 */ @RequestMapping(value = ["/.well-known/acme-challenge/*"], method = [(RequestMethod.GET)]) fun letUsEncryptCertificateCheck(request: HttpServletRequest, response: HttpServletResponse) { val uri = request.requestURI.replace("/", "\\") //文件路径自行替换一下就行,就是上图中生成验证文件的路径,因为URI中已经包含了/.well-known/acme-challenge/,所以这里不需要 val file = File(isyProperties.getCertificate().place + uri) uploadService.download("验证文件", file, response, request) } }
src/main/java/top/zbeboy/isy/web/MainController.kt
3230630500
package com.esafirm.androidplayground.main import android.content.Context import android.content.Intent import android.os.Bundle import android.view.ViewGroup import com.bluelinelabs.conductor.Conductor import com.bluelinelabs.conductor.Router import com.bluelinelabs.conductor.RouterTransaction import com.esafirm.androidplayground.R import com.esafirm.androidplayground.common.BaseAct import com.esafirm.androidplayground.common.ControllerMaker import com.esafirm.conductorextra.getTopController class RouterAct : BaseAct() { private var router: Router? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_router) val maker = intent .extras!! .getSerializable(EXTRA_CONTROLLER) as ControllerMaker router = Conductor.attachRouter(this, findViewById(R.id.container), savedInstanceState) if (!router!!.hasRootController()) { router!!.setRoot(RouterTransaction.with(maker.makeController())) } } override fun onBackPressed() { if (!router!!.handleBack()) { super.onBackPressed() } } companion object { private const val EXTRA_CONTROLLER = "Extra.Controller" /* --------------------------------------------------- */ /* > Stater */ /* --------------------------------------------------- */ fun start(context: Context, controller: ControllerMaker) { context.startActivity(Intent(context, RouterAct::class.java) .putExtra(EXTRA_CONTROLLER, controller)) } } }
app/src/main/java/com/esafirm/androidplayground/main/RouterAct.kt
4188679301
// Copyright 2000-2017 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.gradle.frameworkSupport import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.Function import org.gradle.util.GradleVersion class KotlinBuildScriptDataBuilder : BuildScriptDataBuilder { constructor(buildScriptFile: VirtualFile) : super(buildScriptFile) constructor(buildScriptFile: VirtualFile, gradleVersion: GradleVersion) : super(buildScriptFile, gradleVersion) override fun addPluginsLines(lines: MutableList<String>, padding: Function<String, String>) { if (plugins.isEmpty()) { return } lines.add("apply {") lines.addAll(plugins.map { padding.`fun`(it) }) lines.add("}") lines.add("") } }
plugins/gradle/src/org/jetbrains/plugins/gradle/frameworkSupport/KotlinBuildScriptDataBuilder.kt
4022105870
package backend.model.event import backend.exceptions.DomainException import backend.model.location.Location import backend.model.misc.Coord import backend.model.misc.EmailAddress import backend.model.user.Participant import backend.model.user.User import org.javamoney.moneta.Money import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.powermock.api.mockito.PowerMockito.mock import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.time.LocalDateTime import kotlin.test.assertFails import kotlin.test.assertFailsWith @RunWith(PowerMockRunner::class) @PrepareForTest(Location::class, Event::class) class TeamTest { lateinit var event: Event lateinit var team: Team lateinit var creator: Participant @Before fun setUp() { creator = User.create("creator@mail.de", "password").addRole(Participant::class) event = Event("Awesome Event", LocalDateTime.now(), "Munich", Coord(0.0, 0.0), duration = 36, teamFee = Money.of(60, "EUR"), brand = "BreakOut", bank = "Bank", iban = "IBAN", bic = "BIC") team = Team(creator, "Team awesome", "our team is awesome", event, null) } @Test fun testCreateTeam() { val creator = User.create("creator@mail.de", "password").addRole(Participant::class) val team = Team(creator, "Team awesome", "our team is awesome", event, null) assertEquals(team, creator.getCurrentTeam()) assertEquals(team.members.size, 1) assertTrue(team.members.contains(creator)) } @Test fun failToCreateTeam() { assertFailsWith<Exception>("Participant ${creator.email} is already part of a team", { Team(creator, "Team not Awesome", "our team sucks", event, null) }) } @Test fun testJoin() { val inviteeEmail = EmailAddress("invitee@mail.com") val invitee = User.create(inviteeEmail.toString(), "password").addRole(Participant::class) team.invite(inviteeEmail) team.join(invitee) } @Test fun testFailToJoinIfNotInvited() { val inviteeEmail = EmailAddress("invitee@mail.com") val notInvitee = User.create("notinvitee@mail.com", "password").addRole(Participant::class) team.invite(inviteeEmail) assertFails({ team.join(notInvitee) }) } @Test fun testJoinWithEmailInDifferentCase1() { val inviteeEmail = EmailAddress("invitee@mail.com") val invitee = User.create("INVITEE@mail.com", "password").addRole(Participant::class) team.invite(inviteeEmail) team.join(invitee) } @Test fun testJoinWithEmailInDifferentCase2() { val inviteeEmail = EmailAddress("INVITEE@mail.com") val invitee = User.create("invitee@mail.com", "password").addRole(Participant::class) team.invite(inviteeEmail) team.join(invitee) } @Test fun testFailToJoinIfTeamAlreadyFull() { val inviteeEmail = EmailAddress("invitee@mail.com") val secondInvitee = EmailAddress("secondInvitee@mail.com") team.invite(inviteeEmail) team.invite(secondInvitee) val firstUser = User.create(inviteeEmail.toString(), "password").addRole(Participant::class) val secondUser = User.create(secondInvitee.toString(), "password").addRole(Participant::class) team.join(firstUser) assertFails { team.join(secondUser) } } @Test fun testInvite() { val firstInvitee = EmailAddress("invitee@mail.de") val secondInvitee = EmailAddress("second@mail.de") team.invite(firstInvitee) team.invite(secondInvitee) } @Test fun testFailToInviteIfAlreadyInvited() { val firstInvitee = EmailAddress("invitee@mail.de") val secondInvitee = EmailAddress("second@mail.de") team.invite(firstInvitee) team.invite(secondInvitee) assertFails { team.invite(secondInvitee) } } @Test fun testIsInvited() { val firstInvitee = EmailAddress("invitee@mail.de") val secondInvitee = EmailAddress("second@mail.de") team.invite(firstInvitee) team.invite(secondInvitee) assertTrue(team.isInvited(firstInvitee)) assertTrue(team.isInvited(secondInvitee)) } @Test fun testIsFull() { val firstInvitee = EmailAddress("invitee@mail.de") val invitee = User.create(firstInvitee.toString(), "password").addRole(Participant::class) team.invite(firstInvitee) team.join(invitee) assertTrue(team.isFull()) } @Test fun testUserEventsSetCorrectly() { val user = User.create("firstname@example.com", "pw").addRole(Participant::class) val mockEvent1 = mock(Event::class.java) val mockEvent2 = mock(Event::class.java) val team1 = Team(user, "", "", mockEvent1, null) val team2 = Team(user, "", "", mockEvent2, null) assertEquals(team2, user.getCurrentTeam()) assertTrue(user.getAllTeams().contains(team1)) assertTrue(user.getAllTeams().contains(team2)) } @Test fun testCantJoinMultipleTeamsAtSameEvent() { val user = User.create("firstname@example.com", "pw").addRole(Participant::class) val mockEvent = mock(Event::class.java) val team1 = Team(user, "", "", mockEvent, null) assertFails { Team(user, "", "", mockEvent, null) } assertEquals(team1, user.getCurrentTeam()) assertTrue(user.getAllTeams().contains(team1)) assertEquals(1, user.getAllTeams().size) } @Test fun givenThatAUserHasBeenInATeamAtAnEvent_whenCreatingANewTeamForThatEvent_thenAnExceptionOccurs() { val anotherEvent = mock(Event::class.java) val anotherTeam = Team(creator, "", "", anotherEvent, null) assertFailsWith(DomainException::class) { Team(creator, "", "", event, null) } } @Test fun whenNoLocation_thenGetCurrentDistanceReturnsZero() { assertEquals(0.0, team.getCurrentDistance(), 0.0) } }
src/test/java/backend/model/event/TeamTest.kt
2015651430
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.utils.js @JsModule("xml-beautify") @JsNonModule external class XmlBeautify { fun beautify(xmlString: String, options: Any): String }
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/utils/js/XmlBeautify.kt
4140394787
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.ide import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.workspaceModel.ide.impl.jps.serialization.toConfigLocation import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.addContentRootEntity import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.junit.* class ReplaceBySourceTest { @Rule @JvmField val projectModel = ProjectModelRule() private lateinit var virtualFileManager: VirtualFileUrlManager @Before fun setUp() { virtualFileManager = VirtualFileUrlManager.getInstance(projectModel.project) } @Test fun checkOrderAtReplaceBySourceNotDependsOnExecutionCount() { val expectedResult = mutableListOf<String>() for (i in 1..100) { val builder = createBuilder() val storage = MutableEntityStorage.create() storage.replaceBySource({ entitySource -> entitySource is JpsFileEntitySource }, builder) val contentRootEntity = storage.entities(ContentRootEntity::class.java).first() if (i == 1) { contentRootEntity.sourceRoots.forEach { expectedResult.add(it.url.toString()) } } else { Assert.assertArrayEquals(expectedResult.toTypedArray(), contentRootEntity.sourceRoots.map { it.url.toString() }.toList().toTypedArray()) } } } private fun createBuilder(): MutableEntityStorage { val fileUrl = "/user/opt/app/a.txt" val fileUrl2 = "/user/opt/app/b.txt" val fileUrl3 = "/user/opt/app/c.txt" val fileUrl4 = "/user/opt/app/d.txt" val fileUrl5 = "/user/opt/app/e.txt" val builder = MutableEntityStorage.create() val baseDir = projectModel.baseProjectDir.rootPath.resolve("test") val iprFile = baseDir.resolve("testProject.ipr") val configLocation = toConfigLocation(iprFile, virtualFileManager) val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation) val moduleEntity = builder.addModuleEntity("name", emptyList(), source) val contentRootEntity = builder.addContentRootEntity(virtualFileManager.fromUrl(fileUrl), emptyList(), emptyList(), moduleEntity) builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl2), "", source) builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl3), "", source) builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl4), "", source) builder.addSourceRootEntity(contentRootEntity, virtualFileManager.fromUrl(fileUrl5), "", source) return builder } companion object { @JvmField @ClassRule val appRule = ApplicationRule() } }
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ReplaceBySourceTest.kt
3929462528
package com.apollographql.apollo3.compiler.codegen.kotlin.file import com.apollographql.apollo3.ast.GQLFragmentDefinition import com.apollographql.apollo3.ast.Schema import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder import com.apollographql.apollo3.compiler.ir.IrNamedFragment import com.apollographql.apollo3.compiler.codegen.kotlin.selections.CompiledSelectionsBuilder import com.squareup.kotlinpoet.ClassName class FragmentSelectionsBuilder( val context: KotlinContext, val fragment: IrNamedFragment, val schema: Schema, val allFragmentDefinitions: Map<String, GQLFragmentDefinition>, ) : CgOutputFileBuilder { private val packageName = context.layout.fragmentResponseFieldsPackageName(fragment.filePath) private val simpleName = context.layout.fragmentSelectionsName(fragment.name) override fun prepare() { context.resolver.registerFragmentSelections( fragment.name, ClassName(packageName, simpleName) ) } override fun build(): CgFile { return CgFile( packageName = packageName, fileName = simpleName, typeSpecs = listOf( CompiledSelectionsBuilder( context = context, allFragmentDefinitions = allFragmentDefinitions, schema = schema ).build(fragment.selections, simpleName, fragment.typeCondition) ) ) } }
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/FragmentSelectionsBuilder.kt
3696263830
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.shared.data import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.FirebaseFirestore fun FirebaseFirestore.document2020(): DocumentReference = // This is a prefix for Firestore document for this year collection("google_io_events").document("2020")
shared/src/main/java/com/google/samples/apps/iosched/shared/data/FirestoreExtensions.kt
3635032534
package com.github.vhromada.catalog.web.connector.impl import com.github.vhromada.catalog.common.entity.Page import com.github.vhromada.catalog.web.connector.GenreConnector import com.github.vhromada.catalog.web.connector.common.ConnectorConfig import com.github.vhromada.catalog.web.connector.common.RestConnector import com.github.vhromada.catalog.web.connector.common.RestLoggingInterceptor import com.github.vhromada.catalog.web.connector.common.RestRequest import com.github.vhromada.catalog.web.connector.common.UserInterceptor import com.github.vhromada.catalog.web.connector.common.error.ResponseErrorHandler import com.github.vhromada.catalog.web.connector.entity.ChangeGenreRequest import com.github.vhromada.catalog.web.connector.entity.Genre import com.github.vhromada.catalog.web.connector.entity.GenreStatistics import com.github.vhromada.catalog.web.connector.filter.NameFilter import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpMethod import org.springframework.stereotype.Component import org.springframework.web.util.UriComponentsBuilder /** * A class represents implementation of connector for genres. * * @author Vladimir Hromada */ @Component("genreConnector") class GenreConnectorImpl( /** * Configuration for connector */ connectorConfig: ConnectorConfig, /** * Error handler */ errorHandler: ResponseErrorHandler, /** * Interceptor for logging */ loggingInterceptor: RestLoggingInterceptor, /** * Interceptor for processing header X-User */ userInterceptor: UserInterceptor ) : RestConnector( system = "CatalogWebSpring", config = connectorConfig, errorHandler = errorHandler, loggingInterceptor = loggingInterceptor, userInterceptor = userInterceptor ), GenreConnector { override fun getAll(): List<Genre> { val filter = NameFilter() filter.page = 1 filter.limit = Int.MAX_VALUE return search(filter = filter).data } override fun search(filter: NameFilter): Page<Genre> { val url = UriComponentsBuilder.fromUriString(getUrl()) filter.createUrl(builder = url) return exchange(request = RestRequest(method = HttpMethod.GET, url = url.build().toUriString(), parameterizedType = object : ParameterizedTypeReference<Page<Genre>>() {})) .throwExceptionIfAny() .get() } override fun get(uuid: String): Genre { return exchange(request = RestRequest(method = HttpMethod.GET, url = getUrl(uuid = uuid), responseType = Genre::class.java)) .throwExceptionIfAny() .get() } override fun add(request: ChangeGenreRequest): Genre { return exchange(request = RestRequest(method = HttpMethod.PUT, url = getUrl(), entity = request, responseType = Genre::class.java)) .throwExceptionIfAny() .get() } override fun update(uuid: String, request: ChangeGenreRequest): Genre { return exchange(request = RestRequest(method = HttpMethod.POST, url = getUrl(uuid = uuid), entity = request, responseType = Genre::class.java)) .throwExceptionIfAny() .get() } override fun remove(uuid: String) { exchange(request = RestRequest(method = HttpMethod.DELETE, url = getUrl(uuid = uuid), responseType = Unit::class.java)) .throwExceptionIfAny() } override fun duplicate(uuid: String): Genre { return exchange(request = RestRequest(method = HttpMethod.POST, url = "${getUrl(uuid = uuid)}/duplicate", responseType = Genre::class.java)) .throwExceptionIfAny() .get() } override fun getStatistics(): GenreStatistics { return exchange(request = RestRequest(method = HttpMethod.GET, url = "${getUrl()}/statistics", responseType = GenreStatistics::class.java)) .throwExceptionIfAny() .get() } override fun getUrl(): String { return super.getUrl() + "/rest/genres" } /** * Returns URL UUID. * * @param uuid UUID * @return URL for UUID */ private fun getUrl(uuid: String): String { return "${getUrl()}/${uuid}" } }
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/impl/GenreConnectorImpl.kt
2421062933
// 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.loopToCallChain.result import org.jetbrains.kotlin.idea.intentions.loopToCallChain.* import org.jetbrains.kotlin.idea.intentions.loopToCallChain.sequence.MapTransformation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.blockExpressionsOrSingle class MaxOrMinTransformation( loop: KtForExpression, initialization: VariableInitialization, private val isMax: Boolean ) : AssignToVariableResultTransformation(loop, initialization) { override val presentation: String get() = if (isMax) "maxOrNull()" else "minOrNull()" override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { val call = chainedCallGenerator.generate(presentation) return KtPsiFactory(call.project).createExpressionByPattern( "$0\n ?: $1", call, initialization.initializer, reformat = chainedCallGenerator.reformat ) } /** * Matches: * val variable = <initial> * for (...) { * ... * if (variable > <input variable>) { // or '<' or operands swapped * variable = <input variable> * } * } * * or * * val variable = <initial> * for (...) { * ... * // or '<', '<=', '>=' or operands swapped * variable = if (variable > <input variable>) <input variable> else variable * } * } * or * * val variable = <initial> * for (...) { * ... * // or Math.min or operands swapped * variable = Math.max(variable, <expression>) * } * } */ object Matcher : TransformationMatcher { override val indexVariableAllowed: Boolean get() = true override fun match(state: MatchingState): TransformationMatch.Result? { return matchIfAssign(state) ?: matchAssignIf(state) ?: matchMathMaxOrMin(state) } private fun matchIfAssign(state: MatchingState): TransformationMatch.Result? { val ifExpression = state.statements.singleOrNull() as? KtIfExpression ?: return null if (ifExpression.`else` != null) return null val then = ifExpression.then ?: return null val statement = then.blockExpressionsOrSingle().singleOrNull() as? KtBinaryExpression ?: return null if (statement.operationToken != KtTokens.EQ) return null return match(ifExpression.condition, statement.left, statement.right, null, state.inputVariable, state.outerLoop) } private fun matchAssignIf(state: MatchingState): TransformationMatch.Result? { val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null if (assignment.operationToken != KtTokens.EQ) return null val ifExpression = assignment.right as? KtIfExpression ?: return null return match( ifExpression.condition, assignment.left, ifExpression.then, ifExpression.`else`, state.inputVariable, state.outerLoop ) } private fun matchMathMaxOrMin(state: MatchingState): TransformationMatch.Result? { val assignment = state.statements.singleOrNull() as? KtBinaryExpression ?: return null if (assignment.operationToken != KtTokens.EQ) return null val variableInitialization = assignment.left.findVariableInitializationBeforeLoop(state.outerLoop, checkNoOtherUsagesInLoop = false) ?: return null return matchMathMaxOrMin(variableInitialization, assignment, state, isMax = true) ?: matchMathMaxOrMin(variableInitialization, assignment, state, isMax = false) } private fun matchMathMaxOrMin( variableInitialization: VariableInitialization, assignment: KtBinaryExpression, state: MatchingState, isMax: Boolean ): TransformationMatch.Result? { val functionName = if (isMax) "max" else "min" val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null if (arguments.size != 2) return null val value = when { arguments[0].isVariableReference(variableInitialization.variable) -> arguments[1] ?: return null arguments[1].isVariableReference(variableInitialization.variable) -> arguments[0] ?: return null else -> return null } val mapTransformation = if (value.isVariableReference(state.inputVariable)) null else MapTransformation(state.outerLoop, state.inputVariable, state.indexVariable, value, mapNotNull = false) val transformation = MaxOrMinTransformation(state.outerLoop, variableInitialization, isMax) return TransformationMatch.Result(transformation, listOfNotNull(mapTransformation)) } private fun match( condition: KtExpression?, assignmentTarget: KtExpression?, valueAssignedIfTrue: KtExpression?, valueAssignedIfFalse: KtExpression?, inputVariable: KtCallableDeclaration, loop: KtForExpression ): TransformationMatch.Result? { if (condition !is KtBinaryExpression) return null val comparison = condition.operationToken if (comparison !in setOf(KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ)) return null val left = condition.left as? KtNameReferenceExpression ?: return null val right = condition.right as? KtNameReferenceExpression ?: return null val otherHand = when { left.isVariableReference(inputVariable) -> right right.isVariableReference(inputVariable) -> left else -> return null } val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false) ?: return null if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null val valueToBeVariable = when { valueAssignedIfTrue.isVariableReference(inputVariable) -> valueAssignedIfFalse valueAssignedIfFalse.isVariableReference(inputVariable) -> valueAssignedIfTrue else -> return null } if (valueToBeVariable != null && !valueToBeVariable.isVariableReference(variableInitialization.variable)) return null val isMax = (comparison == KtTokens.GT || comparison == KtTokens.GTEQ) xor (otherHand == left) val transformation = MaxOrMinTransformation(loop, variableInitialization, isMax) return TransformationMatch.Result(transformation) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/loopToCallChain/result/MaxOrMinTransformation.kt
488411041
@file:Suppress("unused") package io.customerly.utils.ggkext /* * Copyright (C) 2017 Customerly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created by Gianni on 11/08/17. */ internal val Boolean.as1or0 :Int get() { return if(this) 1 else 0 } /** * Convert a 0 Int value to false Boolean value * Convert any other Int value to Boolean true */ internal val Int?.asBool :Boolean get() { return this == 1 } /** * Convert a 1 Int value to true Boolean value * Convert a 0 Int value to false Boolean value * Convert any other Int value to null */ internal val Int.asBoolStrict :Boolean? get() { return when(this) { 1 -> true 0 -> false else -> null } }
customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_Boolean_1_or_0.kt
3374378941
package ch.difty.scipamato.core.sync.code import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component private const val AGGR_5ABC = "5abc" /** * HARDCODED consider moving aggregation into some table in scipamato-core (see also CodeSyncConfig#selectSql) */ private val codeAggregation: Map<String, String> = setOf("5A", "5B", "5C").associateWith { AGGR_5ABC } private val populationCodeMapper: Map<String, Short> = ( setOf("3A", "3B").associateWith { 1 } + setOf("3C").associateWith { 2 } ).map { it.key to it.value.toShort() }.toMap() private val studyDesignCodeMapper: Map<String, Short> = ( setOf(AGGR_5ABC).associateWith { 1 } + setOf("5E", "5F", "5G", "5H", "5I").associateWith { 2 } + setOf("5U", "5M").associateWith { 3 } ).map { it.key to it.value.toShort() }.toMap() /** * The [HidingInternalsCodeAggregator] has the purpose of * * * Providing aggregated codes by * * Enriching codes with aggregated codes * * Filtering out internal codes * * * providing the aggregated * * codesPopulation values * * codesStudyDesign values */ @Component @Scope("prototype") class HidingInternalsCodeAggregator : CodeAggregator { private val _internalCodes: MutableList<String> = ArrayList() private val _codes: MutableList<String> = ArrayList() private val _codesPopulation: MutableList<Short> = ArrayList() private val _codesStudyDesign: MutableList<Short> = ArrayList() override fun setInternalCodes(internalCodes: List<String>) { this._internalCodes.clear() this._internalCodes.addAll(internalCodes) } override fun load(codes: Array<String>) { clearAll() this._codes.addAll(aggregateCodes(codes)) _codesPopulation.addAll(gatherCodesPopulation()) _codesStudyDesign.addAll(gatherCodesStudyDesign()) } private fun clearAll() { _codes.clear() _codesPopulation.clear() _codesStudyDesign.clear() } private fun aggregateCodes(codeArray: Array<String>): List<String> = filterAndEnrich(codeArray).sorted() private fun filterAndEnrich(codeArray: Array<String>): List<String> = codeArray .map { codeAggregation[it] ?: it } .filterNot { it in _internalCodes } .distinct() private fun gatherCodesPopulation(): List<Short> = _codes.mapNotNull { populationCodeMapper[it] }.distinct() private fun gatherCodesStudyDesign(): List<Short> = _codes.mapNotNull { studyDesignCodeMapper[it] }.distinct() override val aggregatedCodes: Array<String> get() = _codes.toTypedArray() override val codesPopulation: Array<Short> get() = _codesPopulation.toTypedArray() override val codesStudyDesign: Array<Short> get() = _codesStudyDesign.toTypedArray() }
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/code/HidingInternalsCodeAggregator.kt
1047735963
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.copyright import com.maddyhome.idea.copyright.pattern.DateInfo import com.maddyhome.idea.copyright.pattern.VelocityHelper import org.junit.Assert import org.junit.Test class CommentInfoTest { val template = "Copyright (c) \$originalComment.match(\"Copyright \\(c\\) (\\d+)\", 1, \" - \")\$today.year. " + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n" @Test fun noComment() { val dateInfo = DateInfo().year Assert.assertEquals("Copyright (c) $dateInfo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n", VelocityHelper.evaluate (null, null, null, template, null)) } @Test fun withAnotherComment() { val dateInfo = DateInfo().year Assert.assertEquals("Copyright (c) $dateInfo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n", VelocityHelper.evaluate (null, null, null, template, "Copyright (c). Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n")) } @Test fun withComment() { val dateInfo = DateInfo().year Assert.assertEquals("Copyright (c) 2020 - $dateInfo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n", VelocityHelper.evaluate (null, null, null, template, "Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit. \n")) } }
plugins/copyright/testSrc/com/intellij/copyright/CommentInfoTest.kt
778691259
package com.wenhui.shimmerimageview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) updateStartAnimationButton() startAnimationButton.setOnClickListener { if (shimmerImageView.isAnimationRunning) { shimmerImageView.stopAnimation() } else { shimmerImageView.startAnimation() } updateStartAnimationButton() } } private fun updateStartAnimationButton() { if (shimmerImageView.isAnimationRunning) { startAnimationButton.text = "Stop Animation" } else { startAnimationButton.text = "Start Animation" } } }
example/src/main/java/com/wenhui/shimmerimageview/MainActivity.kt
3574357216
package no.skatteetaten.aurora.boober.feature import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import com.fkorotkov.kubernetes.newEnvVar import com.fkorotkov.openshift.customStrategy import com.fkorotkov.openshift.from import com.fkorotkov.openshift.metadata import com.fkorotkov.openshift.newBuildConfig import com.fkorotkov.openshift.output import com.fkorotkov.openshift.spec import com.fkorotkov.openshift.strategy import com.fkorotkov.openshift.to import io.fabric8.openshift.api.model.BuildConfig import io.fabric8.openshift.api.model.DeploymentConfig import io.fabric8.openshift.api.model.ImageStream import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler import no.skatteetaten.aurora.boober.model.AuroraContextCommand import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec import no.skatteetaten.aurora.boober.model.AuroraResource import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeployment import no.skatteetaten.aurora.boober.model.openshift.ApplicationDeploymentBuildInformation import no.skatteetaten.aurora.boober.service.AuroraDeploymentSpecValidationException @Service class BuildFeature( @Value("\${integrations.docker.registry}") val dockerRegistryUrl: String, @Value("\${auroraconfig.builder.version}") val builderVersion: String, @Value("\${openshift.majorversion:3}") val openshiftVersion: String ) : Feature { override fun enable(header: AuroraDeploymentSpec): Boolean { return header.type == TemplateType.development } override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> { val applicationPlatform: ApplicationPlatform = header.applicationPlatform return gavHandlers(header, cmd) + setOf( AuroraConfigFieldHandler("builder/name", defaultValue = "architect"), AuroraConfigFieldHandler("builder/version", defaultValue = builderVersion), AuroraConfigFieldHandler( "baseImage/name", defaultValue = applicationPlatform.baseImageName ), AuroraConfigFieldHandler( "baseImage/version", defaultValue = applicationPlatform.baseImageVersion ) ) } override fun validate( adc: AuroraDeploymentSpec, fullValidation: Boolean, context: FeatureContext ): List<Exception> { if (adc.type == TemplateType.development && adc.deployState == DeploymentState.deployment) { throw AuroraDeploymentSpecValidationException("Development type is not supported for deployState=deployment") } return emptyList() } override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> { val shouldGenerateBuildConfig = openshiftVersion != "4" if (shouldGenerateBuildConfig) { return setOf(generateResource(createBuild(adc))) } return emptySet() } override fun modify( adc: AuroraDeploymentSpec, resources: Set<AuroraResource>, context: FeatureContext ) { resources.forEach { if (it.resource.kind == "ApplicationDeployment") { modifyResource(it, "Add build information") val ad: ApplicationDeployment = it.resource as ApplicationDeployment ad.spec.build = ApplicationDeploymentBuildInformation( baseImageName = adc.applicationPlatform.baseImageName, baseImageVersion = adc.applicationPlatform.baseImageVersion, type = adc.applicationPlatform.name ) } if (it.resource.kind == "ImageStream") { modifyResource(it, "Remove spec from imagestream") val imageStream: ImageStream = it.resource as ImageStream imageStream.spec = null } if (it.resource.kind == "DeploymentConfig") { modifyResource(it, "Change imageChangeTrigger to follow latest") val dc: DeploymentConfig = it.resource as DeploymentConfig dc.spec.triggers.forEach { dtp -> if (dtp.type == "ImageChange") { dtp.imageChangeParams.from.name = "${adc.name}:latest" } } } } } fun createBuild(adc: AuroraDeploymentSpec): BuildConfig { return newBuildConfig { metadata { name = adc.name namespace = adc.namespace } spec { strategy { type = "Custom" customStrategy { from { kind = "ImageStreamTag" namespace = "openshift" name = "${adc.get<String>("builder/name")}:${adc.get<String>("builder/version")}" } val envMap = mapOf( "ARTIFACT_ID" to adc.artifactId, "GROUP_ID" to adc.groupId, "VERSION" to adc["version"], "DOCKER_BASE_VERSION" to adc["baseImage/version"], "DOCKER_BASE_IMAGE" to "aurora/${adc.get<String>("baseImage/name")}", "PUSH_EXTRA_TAGS" to "latest,major,minor,patch", "INTERNAL_PULL_REGISTRY" to dockerRegistryUrl ) env = envMap.map { newEnvVar { name = it.key value = it.value } } exposeDockerSocket = true } output { to { kind = "ImageStreamTag" name = "${adc.name}:latest" } } } } } } }
src/main/kotlin/no/skatteetaten/aurora/boober/feature/BuildFeature.kt
3815187130
package org.neo4j.graphql import graphql.ExecutionInput import graphql.schema.idl.SchemaPrinter import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.logging.Log import org.neo4j.logging.LogProvider import java.io.PrintWriter import java.io.StringWriter import javax.ws.rs.* import javax.ws.rs.core.Context import javax.ws.rs.core.HttpHeaders import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * @author mh * @since 30.10.16 */ @Path("") class GraphQLResource(@Context val provider: LogProvider, @Context val db: GraphDatabaseService) { val log: Log init { log = provider.getLog(GraphQLResourceExperimental::class.java) } companion object { val OBJECT_MAPPER = com.fasterxml.jackson.databind.ObjectMapper() } @Path("") @OPTIONS fun options(@Context headers: HttpHeaders) = Response.ok().build() @Path("") @GET fun get(@QueryParam("query") query: String?, @QueryParam("variables") variableParam: String?): Response { if (query == null) return Response.noContent().build() return executeQuery(hashMapOf("query" to query, "variables" to (variableParam ?: emptyMap<String,Any>()))) } @Path("") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) fun executeOperation(body: String): Response { return executeQuery(parseMap(body)) } @Path("/idl") @POST fun storeIdl(schema: String): Response { try { val text = if (schema.trim().startsWith('{')) { parseMap(schema).get("query")?.toString() ?: throw IllegalArgumentException("Can't read schema as JSON despite starting with '{'") } else { if (schema.trim().let { it.startsWith('"') && it.endsWith('"') }) schema.trim('"', ' ', '\t', '\n') else schema } val metaDatas = GraphSchemaScanner.storeIdl(db, text) return Response.ok().entity(OBJECT_MAPPER.writeValueAsString(metaDatas)).build() } catch(e: Exception) { return Response.serverError().entity(OBJECT_MAPPER.writeValueAsString(mapOf("error" to e.message,"trace" to e.stackTraceAsString()))).build() } } @Path("/idl") @DELETE fun deleteIdl(): Response { GraphSchemaScanner.deleteIdl(db) return Response.ok().build() // todo JSON } @Path("/idl") @GET fun getIdl(): Response { val schema = GraphQLSchemaBuilder.buildSchema(db!!) val printed = SchemaPrinter().print(schema) return Response.ok().entity(printed).build() // todo JSON } private fun executeQuery(params: Map<String, Any>): Response { val query = params["query"] as String val variables = getVariables(params) if (log.isDebugEnabled()) log.debug("Executing {} with {}", query, variables) val tx = db.beginTx() try { val ctx = GraphQLContext(db, log, variables) val graphQL = GraphSchema.getGraphQL(db) val execution = ExecutionInput.Builder() .query(query).variables(variables).context(ctx).root(ctx) // todo proper mutation root params.get("operationName")?.let { execution.operationName(it.toString()) } val executionResult = graphQL.execute(execution.build()) val result = linkedMapOf("data" to executionResult.getData<Any>()) if (ctx.backLog.isNotEmpty()) { result["extensions"]=ctx.backLog } if (executionResult.errors.isNotEmpty()) { log.warn("Errors: {}", executionResult.errors) result.put("errors", executionResult.errors) tx.failure() } else { tx.success() } return Response.ok().entity(formatMap(result)).build() } finally { tx.close() } } @Suppress("UNCHECKED_CAST") private fun getVariables(requestBody: Map<String, Any?>): Map<String, Any> { val varParam = requestBody["variables"] return when (varParam) { is String -> parseMap(varParam) is Map<*, *> -> varParam as Map<String, Any> else -> emptyMap() } } private fun formatMap(result: Map<String, Any>) = OBJECT_MAPPER.writeValueAsString(result) @Suppress("UNCHECKED_CAST") private fun parseMap(value: String?): Map<String, Any> = if (value == null || value.isNullOrBlank()|| value == "null") emptyMap() else { val v = value.trim('"',' ','\t','\n','\r') OBJECT_MAPPER.readValue(v, Map::class.java) as Map<String, Any> } }
src/main/kotlin/org/neo4j/graphql/GraphQLResource.kt
2704327453
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.dotnet.commands import jetbrains.buildServer.dotnet.DotnetCommandType /** * Provides parameters for dotnet publish command. */ class PublishCommandType : DotnetType() { override val name: String = DotnetCommandType.Publish.id override val editPage: String = "editPublishParameters.jsp" override val viewPage: String = "viewPublishParameters.jsp" }
plugin-dotnet-server/src/main/kotlin/jetbrains/buildServer/dotnet/commands/PublishCommandType.kt
4131556696
package co.paystack.android.api.di import android.os.Build import co.paystack.android.BuildConfig import co.paystack.android.api.service.ApiService import co.paystack.android.api.utils.TLSSocketFactory import com.google.gson.Gson import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit internal fun apiComponent(): ApiComponent = ApiModule internal interface ApiComponent { val gson: Gson val tlsV1point2factory: TLSSocketFactory val okHttpClient: OkHttpClient val apiService: ApiService } internal object ApiModule : ApiComponent { const val API_URL = "https://standard.paystack.co/" override val gson = GsonBuilder() .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'") .create() override val tlsV1point2factory = TLSSocketFactory() override val okHttpClient = OkHttpClient.Builder() .addInterceptor { chain -> val original = chain.request() // Add headers so we get Android version and Paystack Library version val builder = original.newBuilder() .header("User-Agent", "Android_" + Build.VERSION.SDK_INT + "_Paystack_" + BuildConfig.VERSION_NAME) .header("X-Paystack-Build", BuildConfig.VERSION_CODE.toString()) .header("Accept", "application/json") .method(original.method(), original.body()) chain.proceed(builder.build()) } .sslSocketFactory(tlsV1point2factory, tlsV1point2factory.getX509TrustManager()) .connectTimeout(5, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .writeTimeout(5, TimeUnit.MINUTES) .build() override val apiService = Retrofit.Builder() .baseUrl(API_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(ApiService::class.java) }
paystack/src/main/java/co/paystack/android/api/di/ApiComponent.kt
3224497850
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.ui.actions import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.data.LoadingDetails import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import com.intellij.vcs.log.ui.VcsLogUiEx import com.intellij.vcs.log.ui.frame.CommitPresentationUtil import java.awt.event.KeyEvent open class GoToParentOrChildAction(val parent: Boolean) : DumbAwareAction() { override fun update(e: AnActionEvent) { val ui = e.getData(VcsLogInternalDataKeys.LOG_UI_EX) if (ui == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true if (e.inputEvent is KeyEvent) { e.presentation.isEnabled = ui.table.isFocusOwner } else { e.presentation.isEnabled = getRowsToJump(ui).isNotEmpty() } } override fun actionPerformed(e: AnActionEvent) { triggerUsage(e) val ui = e.getRequiredData(VcsLogInternalDataKeys.LOG_UI_EX) val rows = getRowsToJump(ui) if (rows.isEmpty()) { // can happen if the action was invoked by shortcut return } if (rows.size == 1) { ui.jumpToRow(rows.single(), false) } else { val popup = JBPopupFactory.getInstance().createActionGroupPopup("Select ${if (parent) "Parent" else "Child"} to Navigate", createGroup(ui, rows), e.dataContext, JBPopupFactory.ActionSelectionAid.NUMBERING, false) popup.showInBestPositionFor(e.dataContext) } } private fun createGroup(ui: VcsLogUiEx, rows: List<Int>): ActionGroup { val actions = rows.mapTo(mutableListOf()) { row -> val text = getActionText(ui.table.model.getCommitMetadata(row)) object : DumbAwareAction(text, "Navigate to $text", null) { override fun actionPerformed(e: AnActionEvent) { triggerUsage(e) ui.jumpToRow(row, false) } } } return DefaultActionGroup(actions) } private fun DumbAwareAction.triggerUsage(e: AnActionEvent) { VcsLogUsageTriggerCollector.triggerUsage(e, this) { data -> data.addData("parent_commit", parent) } } private fun getActionText(commitMetadata: VcsCommitMetadata): String { var text = commitMetadata.id.toShortString() if (commitMetadata !is LoadingDetails) { text += " " + CommitPresentationUtil.getShortSummary(commitMetadata, false, 40) } return text } private fun getRowsToJump(ui: VcsLogUiEx): List<Int> { val selectedRows = ui.table.selectedRows if (selectedRows.size != 1) return emptyList() return ui.dataPack.visibleGraph.getRowInfo(selectedRows.single()).getAdjacentRows(parent).sorted() } } class GoToParentRowAction : GoToParentOrChildAction(true) class GoToChildRowAction : GoToParentOrChildAction(false)
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/GoToParentOrChildAction.kt
3106690685
package com.dbflow5.rx2.query import com.dbflow5.BaseUnitTest import com.dbflow5.config.databaseForTable import com.dbflow5.models.SimpleModel import com.dbflow5.models.SimpleModel_Table import com.dbflow5.query.delete import com.dbflow5.query.insert import com.dbflow5.query.select import com.dbflow5.reactivestreams.query.queryStreamResults import com.dbflow5.reactivestreams.transaction.asFlowable import com.dbflow5.structure.delete import com.dbflow5.structure.insert import com.dbflow5.structure.save import org.junit.Assert.assertEquals import org.junit.Test class CursorResultSubscriberTest : BaseUnitTest() { @Test fun testCanQueryStreamResults() { databaseForTable<SimpleModel> { db -> (0..9).forEach { SimpleModel("$it").save(db) } var count = 0 (select from SimpleModel::class) .queryStreamResults(db) .subscribe { count++ assert(it != null) } assertEquals(10, count) } } @Test fun testCanObserveOnTableChangesWithModelOps() { var count = 0 (select from SimpleModel::class) .asFlowable { db -> queryList(db) } .subscribe { count++ } val model = SimpleModel("test") databaseForTable<SimpleModel>().executeTransaction { db -> model.save(db) model.delete(db) model.insert(db) } assertEquals(2, count) // once for subscription, 1 for operations in transaction. } @Test fun testCanObserveOnTableChangesWithTableOps() { databaseForTable<SimpleModel> { db -> delete<SimpleModel>().executeUpdateDelete(db) var count = 0 var curList: MutableList<SimpleModel> = arrayListOf() (select from SimpleModel::class) .asFlowable { db -> queryList(db) } .subscribe { curList = it count++ } db.executeTransaction { d -> insert(SimpleModel::class, SimpleModel_Table.name) .values("test") .executeInsert(d) insert(SimpleModel::class, SimpleModel_Table.name) .values("test1") .executeInsert(d) insert(SimpleModel::class, SimpleModel_Table.name) .values("test2") .executeInsert(d) } assertEquals(3, curList.size) db.executeTransaction { d -> val model = (select from SimpleModel::class where SimpleModel_Table.name.eq("test")).requireSingle(d) model.delete(d) } db.tableObserver.checkForTableUpdates() assertEquals(2, curList.size) assertEquals(3, count) // once for subscription, 2 for transactions } } }
tests/src/androidTest/java/com/dbflow5/rx2/query/CursorResultSubscriberTest.kt
2282203279
package com.intellij.workspace.legacyBridge.libraries.libraries import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectModelExternalSource import com.intellij.openapi.roots.RootProvider import com.intellij.openapi.roots.RootProvider.RootSetChangedListener import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.roots.libraries.LibraryProperties import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.PersistentLibraryKind import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.TraceableDisposable import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.EventDispatcher import com.intellij.workspace.api.* import com.intellij.workspace.ide.WorkspaceModel import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeFilePointerProviderImpl import com.intellij.workspace.legacyBridge.intellij.LegacyBridgeModuleLibraryTable import com.intellij.workspace.legacyBridge.typedModel.library.LibraryViaTypedEntity import org.jdom.Element import org.jetbrains.annotations.ApiStatus interface LegacyBridgeLibrary : LibraryEx { val libraryId: LibraryId @ApiStatus.Internal fun getModifiableModel(builder: TypedEntityStorageBuilder): LibraryEx.ModifiableModelEx } @ApiStatus.Internal internal class LegacyBridgeLibraryImpl( private val libraryTable: LibraryTable, val project: Project, initialId: LibraryId, initialEntityStore: TypedEntityStore, parent: Disposable ) : LegacyBridgeLibrary, RootProvider, TraceableDisposable(true) { companion object { private const val UNNAMED_LIBRARY_NAME_PREFIX = "#" private const val UNIQUE_INDEX_LIBRARY_NAME_SUFFIX = "-d1a6f608-UNIQUE-INDEX-f29c-4df6-" fun getLegacyLibraryName(libraryId: LibraryId): String? { if (libraryId.name.startsWith(UNNAMED_LIBRARY_NAME_PREFIX)) return null if (libraryId.name.contains(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX)) return libraryId.name.substringBefore(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX) return libraryId.name } fun generateLibraryEntityName(legacyLibraryName: String?, exists: (String) -> Boolean): String { if (legacyLibraryName == null) { // TODO Make it O(1) if required var index = 1 while (true) { val candidate = "$UNNAMED_LIBRARY_NAME_PREFIX$index" if (!exists(candidate)) { return candidate } index++ } @Suppress("UNREACHABLE_CODE") error("Unable to suggest unique name for unnamed module library") } if (!exists(legacyLibraryName)) return legacyLibraryName var index = 1 while (true) { val candidate = "$legacyLibraryName${UNIQUE_INDEX_LIBRARY_NAME_SUFFIX}$index" if (!exists(candidate)) { return candidate } index++ } } } override fun getModule(): Module? = (libraryTable as? LegacyBridgeModuleLibraryTable)?.module init { Disposer.register(parent, this) } val filePointerProvider = LegacyBridgeFilePointerProviderImpl().also { Disposer.register(this, it) } var entityStore: TypedEntityStore = initialEntityStore internal set(value) { ApplicationManager.getApplication().assertWriteAccessAllowed() field = value } var entityId: LibraryId = initialId internal set(value) { ApplicationManager.getApplication().assertWriteAccessAllowed() field = value } private var disposed = false // null to update project model via ProjectModelUpdater var modifiableModelFactory: ((LibraryViaTypedEntity, TypedEntityStorageBuilder) -> LegacyBridgeLibraryModifiableModelImpl)? = null private val dispatcher = EventDispatcher.create(RootSetChangedListener::class.java) private val libraryEntityValue = CachedValueWithParameter { storage, id: LibraryId -> storage.resolve(id) } internal val libraryEntity get() = entityStore.cachedValue(libraryEntityValue, entityId) internal val snapshotValue = CachedValueWithParameter { storage, id: LibraryId -> LibraryViaTypedEntity( libraryImpl = this, libraryEntity = storage.resolve(id) ?: object : LibraryEntity { override val entitySource: EntitySource get() = throw NotImplementedError() override fun hasEqualProperties(e: TypedEntity): Boolean { return e is LibraryEntity && e.name == name && e.roots.isEmpty() && e.excludedRoots.isEmpty() } override val tableId: LibraryTableId get() = throw NotImplementedError() override val name: String get() = id.name override val roots: List<LibraryRoot> get() = emptyList() override val excludedRoots: List<VirtualFileUrl> get() = emptyList() override fun <R : TypedEntity> referrers(entityClass: Class<R>, propertyName: String) = emptySequence<R>() }, storage = storage, libraryTable = libraryTable, filePointerProvider = filePointerProvider, modifiableModelFactory = modifiableModelFactory ?: { librarySnapshot, diff -> LegacyBridgeLibraryModifiableModelImpl( originalLibrary = this, originalLibrarySnapshot = librarySnapshot, diff = diff, committer = { _, diffBuilder -> WorkspaceModel.getInstance(project).updateProjectModel { it.addDiff(diffBuilder) } }) } ) } private val snapshot: LibraryViaTypedEntity get() { checkDisposed() return entityStore.cachedValue(snapshotValue, entityId) } override val libraryId: LibraryId get() = entityId override fun getTable(): LibraryTable? = if (libraryTable is LegacyBridgeModuleLibraryTable) null else libraryTable override fun getRootProvider(): RootProvider = this override fun getModifiableModel(): LibraryEx.ModifiableModelEx = snapshot.modifiableModel override fun getModifiableModel(builder: TypedEntityStorageBuilder): LibraryEx.ModifiableModelEx = snapshot.getModifiableModel(builder) override fun getSource(): Library? = null override fun getExternalSource(): ProjectModelExternalSource? = snapshot.externalSource override fun getInvalidRootUrls(type: OrderRootType): List<String> = snapshot.getInvalidRootUrls(type) override fun getKind(): PersistentLibraryKind<*>? = snapshot.kind override fun getName(): String? = getLegacyLibraryName(entityId) override fun getUrls(rootType: OrderRootType): Array<String> = snapshot.getUrls(rootType) override fun getFiles(rootType: OrderRootType): Array<VirtualFile> = snapshot.getFiles(rootType) override fun getProperties(): LibraryProperties<*>? = snapshot.properties override fun getExcludedRoots(): Array<VirtualFile> = snapshot.excludedRoots override fun getExcludedRootUrls(): Array<String> = snapshot.excludedRootUrls override fun isJarDirectory(url: String): Boolean = snapshot.isJarDirectory(url) override fun isJarDirectory(url: String, rootType: OrderRootType): Boolean = snapshot.isJarDirectory(url, rootType) override fun isValid(url: String, rootType: OrderRootType): Boolean = snapshot.isValid(url, rootType) override fun readExternal(element: Element?) = throw NotImplementedError() override fun writeExternal(element: Element) = snapshot.writeExternal(element) override fun addRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.addListener(listener) override fun addRootSetChangedListener(listener: RootSetChangedListener, parentDisposable: Disposable) { dispatcher.addListener(listener, parentDisposable) } override fun removeRootSetChangedListener(listener: RootSetChangedListener) = dispatcher.removeListener(listener) override fun isDisposed(): Boolean = disposed override fun dispose() { checkDisposed() disposed = true kill(null) } private fun checkDisposed() { if (isDisposed) { throwDisposalError("library $entityId already disposed: $stackTrace") } } override fun equals(other: Any?): Boolean { val otherLib = other as? LegacyBridgeLibraryImpl ?: return false return libraryEntity == otherLib.libraryEntity } override fun hashCode(): Int = libraryEntity.hashCode() }
platform/workspaceModel-ide/src/com/intellij/workspace/legacyBridge/libraries/libraries/LegacyBridgeLibraryImpl.kt
2993282696
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.ui import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestPendingReview import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener interface GHPRReviewProcessModel { val pendingReview: GHPullRequestPendingReview? val isActual: Boolean fun populatePendingReviewData(review: GHPullRequestPendingReview?) fun clearPendingReviewData() fun addAndInvokeChangesListener(listener: SimpleEventListener) fun removeChangesListener(listener: SimpleEventListener) }
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewProcessModel.kt
2044713627
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherdata.proxies.local import android.arch.persistence.room.TypeConverter import android.support.annotation.RestrictTo import com.dbeginc.dbweatherdata.proxies.local.weather.LocalAlert import com.dbeginc.dbweatherdata.proxies.local.weather.LocalDailyData import com.dbeginc.dbweatherdata.proxies.local.weather.LocalHourlyData import com.dbeginc.dbweatherdata.proxies.local.weather.LocalMinutelyData import com.google.gson.Gson import com.google.gson.reflect.TypeToken /** * Created by darel on 16.09.17. * * Local Converters */ @RestrictTo(RestrictTo.Scope.LIBRARY) class WeatherLocalConverters { @TypeConverter fun jsonStringToMinutelyData(json: String): List<LocalMinutelyData>? { return if (json.isNotEmpty()) Gson().fromJson(json, object : TypeToken<List<LocalMinutelyData>>() {}.type) else null } @TypeConverter fun minutelyDataToJson(list: List<LocalMinutelyData>?): String = if (list != null) Gson().toJson(list) else "" @TypeConverter fun jsonStringToHourlyData(json: String): List<LocalHourlyData> = Gson().fromJson(json, object : TypeToken<List<LocalHourlyData>>() {}.type) @TypeConverter fun hourlyDataToJson(list: List<LocalHourlyData>): String = Gson().toJson(list) @TypeConverter fun jsonStringToDailyData(json: String): List<LocalDailyData> = Gson().fromJson(json, object : TypeToken<List<LocalDailyData>>() {}.type) @TypeConverter fun dailyDataToJson(dailyData: List<LocalDailyData>): String = Gson().toJson(dailyData) @TypeConverter fun jsonStringToAlerts(json: String): List<LocalAlert>? { return if (json.isNotEmpty()) Gson().fromJson(json, object : TypeToken<List<LocalAlert>>() {}.type) else null } @TypeConverter fun alertsToJson(alerts: List<LocalAlert>?): String = if (alerts != null) Gson().toJson(alerts) else "" }
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/WeatherLocalConverters.kt
2306087901
// IGNORE_BACKEND: NATIVE // FILE: 1.kt // WITH_RUNTIME package test inline fun <R> mfun(f: () -> R) { f() } fun noInline(suffix: String, l: (s: String) -> Unit) { l(suffix) } // FILE: 2.kt //NO_CHECK_LAMBDA_INLINING import test.* import java.util.* fun test1(prefix: String): String { var result = "fail" mfun { noInline("start") { if (it.startsWith(prefix)) { result = "OK" } } } return result } fun box(): String { if (test1("start") != "OK") return "fail1" if (test1("nostart") != "fail") return "fail2" return "OK" }
backend.native/tests/external/codegen/boxInline/lambdaTransformation/lambdaInLambda2.kt
2519420704
@file:JsQualifier("THREE") package three.math @JsName("Color") external class Color { constructor() constructor(hex: String) constructor(hex: Int) constructor(color: Color) constructor(r: Number, g: Number, b: Number) var r: Double var g: Double var b: Double fun set(value: Color): Color fun set(value: Int): Color fun set(value: String): Color fun setScalar(scalar: Double): Color fun setRGB(r: Number, g: Number, b: Number): Color fun setHSL(hue: Float, saturation: Float, lightness: Float) fun setHex(hex: Int): Color fun getHex(): Int fun getHexString(): String fun clone(): Color fun copy(color: Color): Color }
threejs/src/main/kotlin/three/math/Color.kt
1766472632
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Incident import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.isJava import org.jetbrains.uast.UAnnotation /** * Checks for usages of JetBrains nullability annotations in Java code. */ class NullabilityAnnotationsDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes() = listOf(UAnnotation::class.java) override fun createUastHandler(context: JavaContext): UElementHandler { return AnnotationChecker(context) } private inner class AnnotationChecker(val context: JavaContext) : UElementHandler() { override fun visitAnnotation(node: UAnnotation) { if (isJava(node.sourcePsi)) { checkForAnnotation(node, "NotNull", "NonNull") checkForAnnotation(node, "Nullable", "Nullable") } } /** * Check if the node is org.jetbrains.annotations.$jetBrainsAnnotation, replace with * androidx.annotation.$androidxAnnotation if so. */ private fun checkForAnnotation( node: UAnnotation, jetBrainsAnnotation: String, androidxAnnotation: String ) { val incorrectAnnotation = "org.jetbrains.annotations.$jetBrainsAnnotation" val replacementAnnotation = "androidx.annotation.$androidxAnnotation" val patternToReplace = "(?:org\\.jetbrains\\.annotations\\.)?$jetBrainsAnnotation" if (node.qualifiedName == incorrectAnnotation) { val lintFix = fix().name("Replace with `@$replacementAnnotation`") .replace() .pattern(patternToReplace) .with(replacementAnnotation) .shortenNames() .autoFix(true, true) .build() val incident = Incident(context) .issue(ISSUE) .fix(lintFix) .location(context.getNameLocation(node)) .message("Use `@$replacementAnnotation` instead of `@$incorrectAnnotation`") .scope(node) context.report(incident) } } } companion object { val ISSUE = Issue.create( "NullabilityAnnotationsDetector", "Replace usages of JetBrains nullability annotations with androidx " + "versions in Java code", "The androidx nullability annotations should be used in androidx libraries " + "instead of JetBrains annotations.", Category.CORRECTNESS, 5, Severity.ERROR, Implementation(NullabilityAnnotationsDetector::class.java, Scope.JAVA_FILE_SCOPE) ) } }
lint-checks/src/main/java/androidx/build/lint/NullabilityAnnotationsDetector.kt
1301379279
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * Video badges data. * * @param hdr Whether the video has an HDR-compatible transcode. * @param live Live data. * @param weekendChallenge Whether the video is a Vimeo Weekend Challenge. */ @JsonClass(generateAdapter = true) data class VideoBadges( @Json(name = "hdr") val hdr: Boolean? = null, @Json(name = "live") val live: Live? = null, @Json(name = "weekendChallenge") val weekendChallenge: Boolean? = null )
models/src/main/java/com/vimeo/networking2/VideoBadges.kt
1266842569
/** * ownCloud Android client application * * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.owncloud.android.domain.exceptions import java.lang.Exception class BadOcVersionException : Exception()
owncloudDomain/src/main/java/com/owncloud/android/domain/exceptions/BadOcVersionException.kt
556495878
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.reply.ui import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.DrawerValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.PermanentNavigationDrawer import androidx.compose.material3.rememberDrawerState import androidx.compose.material3.windowsizeclass.WindowHeightSizeClass import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.window.layout.DisplayFeature import androidx.window.layout.FoldingFeature import com.example.reply.ui.navigation.ModalNavigationDrawerContent import com.example.reply.ui.navigation.PermanentNavigationDrawerContent import com.example.reply.ui.navigation.ReplyBottomNavigationBar import com.example.reply.ui.navigation.ReplyNavigationActions import com.example.reply.ui.navigation.ReplyNavigationRail import com.example.reply.ui.navigation.ReplyRoute import com.example.reply.ui.navigation.ReplyTopLevelDestination import com.example.reply.ui.utils.DevicePosture import com.example.reply.ui.utils.ReplyContentType import com.example.reply.ui.utils.ReplyNavigationContentPosition import com.example.reply.ui.utils.ReplyNavigationType import com.example.reply.ui.utils.isBookPosture import com.example.reply.ui.utils.isSeparating import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun ReplyApp( windowSize: WindowSizeClass, displayFeatures: List<DisplayFeature>, replyHomeUIState: ReplyHomeUIState, closeDetailScreen: () -> Unit = {}, navigateToDetail: (Long, ReplyContentType) -> Unit = { _, _ -> } ) { /** * This will help us select type of navigation and content type depending on window size and * fold state of the device. */ val navigationType: ReplyNavigationType val contentType: ReplyContentType /** * We are using display's folding features to map the device postures a fold is in. * In the state of folding device If it's half fold in BookPosture we want to avoid content * at the crease/hinge */ val foldingFeature = displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull() val foldingDevicePosture = when { isBookPosture(foldingFeature) -> DevicePosture.BookPosture(foldingFeature.bounds) isSeparating(foldingFeature) -> DevicePosture.Separating(foldingFeature.bounds, foldingFeature.orientation) else -> DevicePosture.NormalPosture } when (windowSize.widthSizeClass) { WindowWidthSizeClass.Compact -> { navigationType = ReplyNavigationType.BOTTOM_NAVIGATION contentType = ReplyContentType.SINGLE_PANE } WindowWidthSizeClass.Medium -> { navigationType = ReplyNavigationType.NAVIGATION_RAIL contentType = if (foldingDevicePosture != DevicePosture.NormalPosture) { ReplyContentType.DUAL_PANE } else { ReplyContentType.SINGLE_PANE } } WindowWidthSizeClass.Expanded -> { navigationType = if (foldingDevicePosture is DevicePosture.BookPosture) { ReplyNavigationType.NAVIGATION_RAIL } else { ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER } contentType = ReplyContentType.DUAL_PANE } else -> { navigationType = ReplyNavigationType.BOTTOM_NAVIGATION contentType = ReplyContentType.SINGLE_PANE } } /** * Content inside Navigation Rail/Drawer can also be positioned at top, bottom or center for * ergonomics and reachability depending upon the height of the device. */ val navigationContentPosition = when (windowSize.heightSizeClass) { WindowHeightSizeClass.Compact -> { ReplyNavigationContentPosition.TOP } WindowHeightSizeClass.Medium, WindowHeightSizeClass.Expanded -> { ReplyNavigationContentPosition.CENTER } else -> { ReplyNavigationContentPosition.TOP } } ReplyNavigationWrapper( navigationType = navigationType, contentType = contentType, displayFeatures = displayFeatures, navigationContentPosition = navigationContentPosition, replyHomeUIState = replyHomeUIState, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ReplyNavigationWrapper( navigationType: ReplyNavigationType, contentType: ReplyContentType, displayFeatures: List<DisplayFeature>, navigationContentPosition: ReplyNavigationContentPosition, replyHomeUIState: ReplyHomeUIState, closeDetailScreen: () -> Unit, navigateToDetail: (Long, ReplyContentType) -> Unit ) { val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) val scope = rememberCoroutineScope() val navController = rememberNavController() val navigationActions = remember(navController) { ReplyNavigationActions(navController) } val navBackStackEntry by navController.currentBackStackEntryAsState() val selectedDestination = navBackStackEntry?.destination?.route ?: ReplyRoute.INBOX if (navigationType == ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER) { // TODO check on custom width of PermanentNavigationDrawer: b/232495216 PermanentNavigationDrawer(drawerContent = { PermanentNavigationDrawerContent( selectedDestination = selectedDestination, navigationContentPosition = navigationContentPosition, navigateToTopLevelDestination = navigationActions::navigateTo, ) }) { ReplyAppContent( navigationType = navigationType, contentType = contentType, displayFeatures = displayFeatures, navigationContentPosition = navigationContentPosition, replyHomeUIState = replyHomeUIState, navController = navController, selectedDestination = selectedDestination, navigateToTopLevelDestination = navigationActions::navigateTo, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail ) } } else { ModalNavigationDrawer( drawerContent = { ModalNavigationDrawerContent( selectedDestination = selectedDestination, navigationContentPosition = navigationContentPosition, navigateToTopLevelDestination = navigationActions::navigateTo, onDrawerClicked = { scope.launch { drawerState.close() } } ) }, drawerState = drawerState ) { ReplyAppContent( navigationType = navigationType, contentType = contentType, displayFeatures = displayFeatures, navigationContentPosition = navigationContentPosition, replyHomeUIState = replyHomeUIState, navController = navController, selectedDestination = selectedDestination, navigateToTopLevelDestination = navigationActions::navigateTo, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail ) { scope.launch { drawerState.open() } } } } } @Composable fun ReplyAppContent( modifier: Modifier = Modifier, navigationType: ReplyNavigationType, contentType: ReplyContentType, displayFeatures: List<DisplayFeature>, navigationContentPosition: ReplyNavigationContentPosition, replyHomeUIState: ReplyHomeUIState, navController: NavHostController, selectedDestination: String, navigateToTopLevelDestination: (ReplyTopLevelDestination) -> Unit, closeDetailScreen: () -> Unit, navigateToDetail: (Long, ReplyContentType) -> Unit, onDrawerClicked: () -> Unit = {} ) { Row(modifier = modifier.fillMaxSize()) { AnimatedVisibility(visible = navigationType == ReplyNavigationType.NAVIGATION_RAIL) { ReplyNavigationRail( selectedDestination = selectedDestination, navigationContentPosition = navigationContentPosition, navigateToTopLevelDestination = navigateToTopLevelDestination, onDrawerClicked = onDrawerClicked, ) } Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.inverseOnSurface) ) { ReplyNavHost( navController = navController, contentType = contentType, displayFeatures = displayFeatures, replyHomeUIState = replyHomeUIState, navigationType = navigationType, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail, modifier = Modifier.weight(1f), ) AnimatedVisibility(visible = navigationType == ReplyNavigationType.BOTTOM_NAVIGATION) { ReplyBottomNavigationBar( selectedDestination = selectedDestination, navigateToTopLevelDestination = navigateToTopLevelDestination ) } } } } @Composable private fun ReplyNavHost( navController: NavHostController, contentType: ReplyContentType, displayFeatures: List<DisplayFeature>, replyHomeUIState: ReplyHomeUIState, navigationType: ReplyNavigationType, closeDetailScreen: () -> Unit, navigateToDetail: (Long, ReplyContentType) -> Unit, modifier: Modifier = Modifier, ) { NavHost( modifier = modifier, navController = navController, startDestination = ReplyRoute.INBOX, ) { composable(ReplyRoute.INBOX) { ReplyInboxScreen( contentType = contentType, replyHomeUIState = replyHomeUIState, navigationType = navigationType, displayFeatures = displayFeatures, closeDetailScreen = closeDetailScreen, navigateToDetail = navigateToDetail, ) } composable(ReplyRoute.DM) { EmptyComingSoon() } composable(ReplyRoute.ARTICLES) { EmptyComingSoon() } composable(ReplyRoute.GROUPS) { EmptyComingSoon() } } }
Reply/app/src/main/java/com/example/reply/ui/ReplyApp.kt
2279803161
package transitiveStory.midActual.sourceCalls.intemediateInheritorCall import transitiveStory.midActual.sourceCalls.intemediateCall.BottomActualCommonInheritor import transitiveStory.midActual.sourceCalls.intemediateCall.BottomActualMPPInheritor val t123 = BottomActualCommonInheritor() val t122 = BottomActualMPPInheritor()
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/bottom-mpp/src/jvmWithJavaMain/kotlin/transitiveStory/midActual/sourceCalls/intemediateInheritorCall/TheCall.kt
1309543108
// 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.project import com.intellij.application.options.PathMacrosImpl import com.intellij.openapi.application.PathManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.testFramework.UsefulTestCase import com.intellij.util.SmartList import com.intellij.util.SystemProperties import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryDescription import org.jetbrains.jps.model.jarRepository.JpsRemoteRepositoryService import org.jetbrains.jps.model.library.JpsLibraryCollection import org.jetbrains.jps.model.library.JpsOrderRootType import org.jetbrains.jps.model.serialization.JpsSerializationManager import org.jetbrains.jps.util.JpsPathUtil import org.junit.Assert import java.io.File /** * Provides access to IntelliJ project configuration so the tests from IntelliJ project sources may locate project and module libraries without * hardcoding paths to their JARs. */ class IntelliJProjectConfiguration { private val projectHome = PathManager.getHomePath() private val projectLibraries: Map<String, LibraryRoots> private val moduleLibraries: Map<String, Map<String, LibraryRoots>> private val remoteRepositoryDescriptions : List<JpsRemoteRepositoryDescription> init { val project = loadIntelliJProject(projectHome) fun extractLibrariesRoots(collection: JpsLibraryCollection) = collection.libraries.associateBy({ it.name }, { LibraryRoots(SmartList(it.getFiles(JpsOrderRootType.COMPILED)), SmartList(it.getFiles(JpsOrderRootType.SOURCES))) }) projectLibraries = extractLibrariesRoots(project.libraryCollection) moduleLibraries = project.modules.associateBy({it.name}, { val libraries = extractLibrariesRoots(it.libraryCollection) if (libraries.isNotEmpty()) libraries else emptyMap() }) remoteRepositoryDescriptions = JpsRemoteRepositoryService.getInstance().getRemoteRepositoriesConfiguration(project)!!.repositories } companion object { private val instance by lazy { IntelliJProjectConfiguration() } @JvmStatic fun getRemoteRepositoryDescriptions() : List<JpsRemoteRepositoryDescription> { return instance.remoteRepositoryDescriptions } @JvmStatic fun getProjectLibraryClassesRootPaths(libraryName: String): List<String> { return getProjectLibrary(libraryName).classesPaths } @JvmStatic fun getProjectLibraryClassesRootUrls(libraryName: String): List<String> { return getProjectLibrary(libraryName).classesUrls } @JvmStatic fun getProjectLibrary(libraryName: String): LibraryRoots { return instance.projectLibraries[libraryName] ?: throw IllegalArgumentException("Cannot find project library '$libraryName' in ${instance.projectHome}") } @JvmStatic fun getModuleLibrary(moduleName: String, libraryName: String): LibraryRoots { val moduleLibraries = instance.moduleLibraries[moduleName] ?: throw IllegalArgumentException("Cannot find module '$moduleName' in ${instance.projectHome}") return moduleLibraries[libraryName] ?: throw IllegalArgumentException("Cannot find module library '$libraryName' in $moduleName") } @JvmStatic fun getJarFromSingleJarProjectLibrary(projectLibraryName: String): VirtualFile { val jarUrl = UsefulTestCase.assertOneElement(getProjectLibraryClassesRootUrls(projectLibraryName)) val jarRoot = VirtualFileManager.getInstance().refreshAndFindFileByUrl(jarUrl) Assert.assertNotNull(jarRoot) return jarRoot!! } @JvmStatic fun loadIntelliJProject(projectHome: String): JpsProject { val m2Repo = FileUtil.toSystemIndependentName(File(SystemProperties.getUserHome(), ".m2/repository").absolutePath) return JpsSerializationManager.getInstance().loadProject(projectHome, mapOf(PathMacrosImpl.MAVEN_REPOSITORY to m2Repo), true) } } class LibraryRoots(val classes: List<File>, val sources: List<File>) { val classesPaths: List<String> get() = classes.map { FileUtil.toSystemIndependentName(it.absolutePath) } val classesUrls: List<String> get() = classes.map { JpsPathUtil.getLibraryRootUrl(it) } val sourcesUrls: List<String> get() = sources.map { JpsPathUtil.getLibraryRootUrl(it) } } }
platform/testFramework/src/com/intellij/project/IntelliJProjectConfiguration.kt
3825083773
// test.C package test annotation class AllOpen @AllOpen class C { fun f() {} fun g() {} val p: Int class D { fun z() { } } @AllOpen class H { fun j() {} } } // SKIP_SANITY_TEST // LAZINESS:NoLaziness
plugins/kotlin/idea/tests/testData/compiler/asJava/lightClasses/ideRegression/AllOpenAnnotatedClasses.kt
3342191453
// AFTER-WARNING: Variable 'foo' is never used fun test(x: Int, b: Boolean) { val foo = if (x == 1) if (b) 1 else<caret> 2 // comment else 0 }
plugins/kotlin/idea/tests/testData/intentions/addBraces/addBracesForElseWithCommentInsideIf.kt
3913336269