repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/AbsDoKitViewManager.kt
1
2056
package com.didichuxing.doraemonkit.kit.core import android.app.Activity import com.didichuxing.doraemonkit.constant.DoKitModule import com.didichuxing.doraemonkit.kit.health.CountDownDoKitView /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-09-28-15:18 * 描 述:页面浮标管理类接口 * 修订历史: * ================================================ */ abstract class AbsDoKitViewManager : DoKitViewManagerInterface { protected var TAG = this.javaClass.simpleName /** * 添加倒计时DokitView */ fun attachCountDownDoKitView(activity: Activity) { if (!DoKitManager.APP_HEALTH_RUNNING) { return } if (activity is UniversalActivity) { return } val dokitIntent = DoKitIntent(CountDownDoKitView::class.java) dokitIntent.mode = DoKitViewLaunchMode.COUNTDOWN attach(dokitIntent) } /** * 添加一机多控标识 * * @param activity */ fun attachMcRecodingDoKitView(activity: Activity) { val action: Map<String, String> = mapOf("action" to "launch_recoding_view") DoKitManager.getModuleProcessor(DoKitModule.MODULE_MC)?.proceed(action) } /** * 添加主icon */ abstract fun attachMainIcon(activity: Activity?) /** * 移除主icon */ abstract fun detachMainIcon() /** * 添加toolPanel */ abstract fun attachToolPanel(activity: Activity?) /** * 移除toolPanel */ abstract fun detachToolPanel() /** * main activity 创建时回调 * * @param activity */ abstract fun onMainActivityResume(activity: Activity?) /** * Activity 创建时回调 * * @param activity */ abstract fun onActivityResume(activity: Activity?) /** * Activity 页面回退的时候回调 * * @param activity */ abstract fun onActivityBackResume(activity: Activity?) }
apache-2.0
3bad94c05002cf59886c4db8e3840056
21.714286
83
0.589099
4.184211
false
false
false
false
MidsizeMango/Permissions-Handler
permissionhelper/src/main/java/com/midsizemango/permissionhelper/PermissionHelperFragment.kt
1
4241
package com.midsizemango.permissionhelper import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat /** * Created by prasad on 7/16/17. */ open class PermissionHelperFragment : Fragment() { private val REQUEST_PERMISSION = 123 private var permissionResult: PermissionResult? = null private var permissionsRequest:Array<String>? = null private var permissionRequestSingle:String? = null override fun onCreate(args: Bundle?) { super.onCreate(args) retainInstance = false } fun isPermissionGranted(context: Context, permission:String):Boolean{ return ((Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || (ContextCompat.checkSelfPermission(context,permission) == PackageManager.PERMISSION_GRANTED)) } fun arePermissionsGranted(context: Context, permissions:Array<String>?):Boolean{ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true var granted:Boolean = true for(permission in permissions!!){ if(ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) granted = false } return granted } fun requestPermissionHandler(permission:String) { val permissions = mutableListOf(permission) if (permissions.isEmpty()) { if (permissionResult != null) { permissionResult?.permissionGranted() } }else { requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSION) } } fun requestPermissionsHandler(permissionRequest:Array<String>?) { var permissions = mutableListOf<String>() for (i in permissionRequest!!.indices) { if (!isPermissionGranted(activity,permissionRequest[i])) { permissions.add(permissionRequest[i]) } } if (permissions.isEmpty()) { if (permissionResult != null) { permissionResult?.permissionGranted() } }else { requestPermissions(permissions.toTypedArray(), REQUEST_PERMISSION) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if(requestCode != REQUEST_PERMISSION) return val permissionDenied = mutableListOf<String>() var granted:Boolean = true for(i in grantResults.indices){ if(grantResults[i] != PackageManager.PERMISSION_GRANTED){ granted = false permissionDenied.add(permissions[i]) } } if(permissionResult != null){ if(granted){ (permissionResult as PermissionResult).permissionGranted() }else{ for(s in permissionDenied){ if(!shouldShowRequestPermissionRationale(s)){ (permissionResult as PermissionResult).permissionDeniedPermanently() return } } (permissionResult as PermissionResult).permissionDenied() } } } fun requestPermissions(permissions:Array<String>?, permissionResult:PermissionResult){ permissionsRequest = permissions this.permissionResult = permissionResult requestPermissionsHandler(permissionsRequest) } fun requestPermission(permission:String, permissionResult:PermissionResult){ permissionRequestSingle = permission this.permissionResult = permissionResult requestPermissionHandler(permissionRequestSingle!!) } fun openSettingsPermission(context: Context){ val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = Uri.parse("package:"+context.packageName) startActivity(intent) } }
mit
95703b54ee434afebe988c1e0f18f1dd
33.487805
160
0.655506
5.395674
false
false
false
false
ibaton/3House
mobile/src/main/java/treehou/se/habit/ui/control/cells/config/CellVoiceConfigFragment.kt
1
6069
package treehou.se.habit.ui.control.cells.config import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import com.trello.rxlifecycle2.components.support.RxFragment import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.realm.Realm import kotlinx.android.synthetic.main.fragment_cell_voice_config.* import se.treehou.ng.ohcommunicator.connector.models.OHItem import treehou.se.habit.R import treehou.se.habit.core.db.model.ItemDB import treehou.se.habit.core.db.model.ServerDB import treehou.se.habit.core.db.model.controller.CellDB import treehou.se.habit.core.db.model.controller.VoiceCellDB import treehou.se.habit.ui.util.IconPickerActivity import treehou.se.habit.util.ConnectionFactory import treehou.se.habit.util.Util import treehou.se.habit.util.logging.Logger import java.util.* import javax.inject.Inject class CellVoiceConfigFragment : RxFragment() { @Inject lateinit var connectionFactory: ConnectionFactory @Inject lateinit var logger: Logger private var voiceCell: VoiceCellDB? = null private var cell: CellDB? = null private var item: OHItem? = null private var itemAdapter: ArrayAdapter<OHItem>? = null private val items = ArrayList<OHItem>() private lateinit var realm: Realm override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Util.getApplicationComponent(this).inject(this) realm = Realm.getDefaultInstance() itemAdapter = ArrayAdapter(activity!!, android.R.layout.simple_spinner_dropdown_item, items) if (arguments != null) { val id = arguments!!.getLong(ARG_CELL_ID) cell = CellDB.load(realm, id) voiceCell = cell!!.getCellVoice() if (voiceCell == null) { realm.executeTransaction { realm -> voiceCell = VoiceCellDB() voiceCell = realm.copyToRealm(voiceCell!!) cell!!.setCellVoice(voiceCell!!) realm.copyToRealmOrUpdate(cell) } } val itemDB = voiceCell!!.item if (itemDB != null) { item = itemDB.toGeneric() } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_cell_voice_config, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) itemsSpinner.adapter = itemAdapter val servers = realm.where(ServerDB::class.java).findAll() items.clear() for (serverDB in servers) { val server = serverDB.toGeneric() val serverHandler = connectionFactory.createServerHandler(server, context) serverHandler.requestItemsRx() .map<List<OHItem>>({ this.filterItems(it) }) .compose(bindToLifecycle()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ items -> this.items.addAll(items) itemAdapter!!.notifyDataSetChanged() }, { logger.e(TAG, "Failed to load items", it) }) } itemsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { val item = items[position] realm.beginTransaction() val itemDB = ItemDB.createOrLoadFromGeneric(realm, item) voiceCell!!.item = itemDB realm.commitTransaction() } override fun onNothingSelected(parent: AdapterView<*>) {} } val item = item if (item != null) { items.add(item) itemAdapter!!.add(item) itemAdapter!!.notifyDataSetChanged() } updateIconImage() setIconButton.setOnClickListener { val intent = Intent(activity, IconPickerActivity::class.java) startActivityForResult(intent, REQUEST_ICON) } } private fun filterItems(items: MutableList<OHItem>): List<OHItem> { val tempItems = ArrayList<OHItem>() for (item in items) { if (item.type == OHItem.TYPE_STRING) { tempItems.add(item) } } items.clear() items.addAll(tempItems) return items } override fun onDestroy() { super.onDestroy() realm.close() } private fun updateIconImage() { setIconButton.setImageDrawable(Util.getIconDrawable(activity, voiceCell!!.icon)) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_ICON && resultCode == Activity.RESULT_OK && data!!.hasExtra(IconPickerActivity.RESULT_ICON)) { realm.beginTransaction() val iconName = data.getStringExtra(IconPickerActivity.RESULT_ICON) voiceCell!!.icon = if (iconName == "") null else iconName updateIconImage() realm.commitTransaction() } } companion object { private val TAG = "CellVoiceConfigFragment" private val ARG_CELL_ID = "ARG_CELL_ID" private val REQUEST_ICON = 183 fun newInstance(cell: CellDB): CellVoiceConfigFragment { val fragment = CellVoiceConfigFragment() val args = Bundle() args.putLong(ARG_CELL_ID, cell.id) fragment.arguments = args return fragment } } }// Required empty public constructor
epl-1.0
ea17fd2330eb4b8b25dd59935b3b02bc
33.482955
116
0.632065
4.866881
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/Processors.kt
1
2294
package org.rust.lang.core.resolve import com.intellij.codeInsight.lookup.LookupElement import org.rust.lang.core.completion.createLookupElement import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.psi.ext.isTest import org.rust.lang.core.types.BoundElement import org.rust.lang.core.types.ty.TypeArguments import org.rust.lang.core.types.ty.emptyTypeArguments /** * ScopeEntry is some PsiElement visible in some code scope. * * [ScopeEntry] handles the two case: * * aliases (that's why we need a [name] property) * * lazy resolving of actual elements (that's why [element] can return `null`) */ interface ScopeEntry { val name: String val element: RsCompositeElement? val typeArguments: TypeArguments get() = emptyTypeArguments } /** * This special event allows to transmit "out of band" information * to the resolve processor */ enum class ScopeEvent : ScopeEntry { // Communicate to the resolve processor that we are about // to process wildecard imports. This is basically a hack // to make winapi 0.2 work in a reasonable amount of time. STAR_IMPORTS; override val element: RsCompositeElement? get() = null } /** * Return `true` to stop further processing, * return `false` to continue search */ typealias RsResolveProcessor = (ScopeEntry) -> Boolean fun collectResolveVariants(referenceName: String, f: (RsResolveProcessor) -> Unit): List<BoundElement<RsCompositeElement>> { val result = mutableListOf<BoundElement<RsCompositeElement>>() f { e -> if (e == ScopeEvent.STAR_IMPORTS && result.isNotEmpty()) return@f true if (e.name == referenceName) { val element = e.element ?: return@f false result += BoundElement(element, e.typeArguments) } false } return result } fun collectCompletionVariants(f: (RsResolveProcessor) -> Unit): Array<LookupElement> { val result = mutableListOf<LookupElement>() f { e -> if ((e.element as? RsFunction?)?.isTest ?: false) return@f false val lookupElement = e.element?.createLookupElement(e.name) if (lookupElement != null) { result += lookupElement } false } return result.toTypedArray() }
mit
4ef5f7e99240b204332133d7849bd50d
32.246377
124
0.702267
4.140794
false
false
false
false
U1F4F1/PowerBottomSheet
powerbottomsheet/src/main/java/com/u1f4f1/powerbottomsheet/coordinatorlayoutbehaviors/BackdropBottomSheetBehavior.kt
1
3755
package com.u1f4f1.powerbottomsheet.coordinatorlayoutbehaviors import android.content.Context import android.opengl.Visibility import android.support.design.widget.CoordinatorLayout import android.support.v4.view.ViewCompat import android.support.v4.widget.NestedScrollView import android.util.AttributeSet import android.view.View import android.view.Window import com.u1f4f1.powerbottomsheet.R import com.u1f4f1.powerbottomsheet.bottomsheet.BottomSheet import com.u1f4f1.powerbottomsheet.bottomsheet.BottomSheetState import com.u1f4f1.powerbottomsheet.debug import com.u1f4f1.powerbottomsheet.info import com.u1f4f1.powerbottomsheet.logLevel import java.lang.ref.WeakReference import android.opengl.ETC1.getHeight import android.icu.lang.UCharacter.GraphemeClusterBreak.V class BackdropBottomSheetBehavior<V : View>(context: Context?, attrs: AttributeSet?) : CoordinatorLayout.Behavior<V>(context, attrs) { var peekHeight = 0 var anchorPointY = 0 var currentChildY = 0 override fun layoutDependsOn(parent: CoordinatorLayout?, child: V, dependency: View): Boolean { val behavior = AnchorPointBottomSheetBehavior.Companion.from(dependency) if (behavior != null) { anchorPointY = behavior.anchorPoint peekHeight = behavior.peekHeight return true } return false } override fun onLayoutChild(parent: CoordinatorLayout, child: V, layoutDirection: Int): Boolean { child.layoutParams.height = anchorPointY parent.onLayoutChild(child, layoutDirection) ViewCompat.offsetTopAndBottom(child, 0) return true } /** * [child] is the instance of the view that we're scrolling behind the [BottomSheet] * [dependency] the instance of the [BottomSheet] */ @Suppress("UnnecessaryVariable") override fun onDependentViewChanged(parent: CoordinatorLayout, child: V, dependency: View): Boolean { super.onDependentViewChanged(parent, child, dependency) val activityLayout = parent val backdrop = child val bottomSheet = dependency if (bottomSheet is BottomSheet) { // sheet is expanded if (bottomSheet.y <= 0) { // preventing that overdraw son backdrop.visibility = View.INVISIBLE } // sheet is bellow the peek height, so we'll just align our top if (bottomSheet.y >= activityLayout.height - peekHeight) { currentChildY = bottomSheet.y.toInt() backdrop.y = bottomSheet.y // also no overdraw backdrop.visibility = View.INVISIBLE } val bottomSheetCollapsedHeight = bottomSheet.getHeight() - peekHeight val bottomSheetDistanceFromAnchorPoint = bottomSheet.y - anchorPointY val collapsedHeightAnchorOffset = bottomSheetCollapsedHeight - anchorPointY val numerator = bottomSheetDistanceFromAnchorPoint * bottomSheetCollapsedHeight val calculatedBackdropY = numerator / collapsedHeightAnchorOffset currentChildY = calculatedBackdropY.toInt() // we know we need the sheet to be showing by this point... so this is probably fine to just have here // this is a nice reset state for the backdrop so it isn't permanently fucked if callback hell takes over if (bottomSheet.y <= anchorPointY) { currentChildY = 0 backdrop.y = 0f } else { backdrop.y = currentChildY.toFloat() } } // if we made it this far we should probably show the view backdrop.visibility = View.VISIBLE return true } }
mit
cecff49f788a6c86030063dc0cd992b7
35.456311
134
0.683622
4.814103
false
false
false
false
karollewandowski/aem-intellij-plugin
src/test/kotlin/co/nums/intellij/aem/htl/documentation/HtlDisplayContextsDocumentationProviderTest.kt
1
4366
package co.nums.intellij.aem.htl.documentation import co.nums.intellij.aem.htl.DOLLAR class HtlDisplayContextsDocumentationProviderTest : HtlDocumentationProviderTestBase() { fun testAttributeDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='attribute'} ^ """, "Applies HTML attribute value escaping." ) fun testAttributeNameDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='attributeName'} ^ """, "Outputs nothing if the value doesn't correspond to the HTML attribute name syntax. Doesn't allow <code>style</code> and <code>on</code>* attributes." ) fun testCommentDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='comment'} ^ """, "Applies HTML comment escaping." ) fun testElementNameDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='elementName'} ^ """, "Allows only element names that are white-listed, outputs <code>div</code> otherwise." ) fun testHtmlDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='html'} ^ """, "Removes markup that may contain XSS risks." ) fun testNumberDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='number'} ^ """, "Outputs zero if the value is not a number." ) fun testScriptCommentDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='scriptComment'} ^ """, "Outputs nothing if value is trying to break out of the JavaScript comment context." ) fun testScriptRegExpDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='scriptRegExp'} ^ """, "Applies JavaScript regular expression escaping." ) fun testScriptStringDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='scriptString'} ^ """, "Applies JavaScript string escaping." ) fun testScriptTokenDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='scriptToken'} ^ """, "Outputs nothing if the value doesn't correspond to the JavaScript token syntax." ) fun testStyleCommentDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='styleComment'} ^ """, "Outputs nothing if value is trying to break out of the CSS comment context." ) fun testStyleStringDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='styleString'} ^ """, "Applies CSS string escaping." ) fun testStyleTokenDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='styleToken'} ^ """, "Outputs nothing if the value doesn't correspond to the CSS token syntax." ) fun testTextDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='text'} ^ """, "Escapes all HTML tokens." ) fun testUnsafeDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='unsafe'} ^ """, "Disables XSS protection." ) fun testUriDisplayContextDoc() = doTestWithDollarConstant( """ $DOLLAR{ @ context='uri'} ^ """, "Outputs nothing if the value contains XSS risks." ) }
gpl-3.0
e541145e17d74c063e6a0e689585550e
31.340741
162
0.494045
5.852547
false
true
false
false
ToxicBakery/ViewPagerTransforms
library/src/main/java/com/ToxicBakery/viewpager/transforms/RotateUpTransformer.kt
1
1138
/* * Copyright 2014 Toxic Bakery * * 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.ToxicBakery.viewpager.transforms import android.view.View open class RotateUpTransformer : ABaseTransformer() { override val isPagingEnabled: Boolean get() = true override fun onTransform(page: View, position: Float) { val width = page.width.toFloat() val rotation = ROT_MOD * position page.pivotX = width * 0.5f page.pivotY = 0f page.translationX = 0f page.rotation = rotation } companion object { private const val ROT_MOD = -15f } }
apache-2.0
0f0fd3315e054de69adbff762ff344ff
27.45
75
0.688928
4.093525
false
false
false
false
stripe/stripe-android
paymentsheet/src/main/java/com/stripe/android/paymentsheet/forms/TransformSpecToElement.kt
1
1602
package com.stripe.android.paymentsheet.forms import android.content.Context import com.stripe.android.paymentsheet.addresselement.toIdentifierMap import com.stripe.android.paymentsheet.paymentdatacollection.FormFragmentArguments import com.stripe.android.paymentsheet.paymentdatacollection.getInitialValuesMap import com.stripe.android.ui.core.address.AddressRepository import com.stripe.android.ui.core.elements.FormItemSpec import com.stripe.android.ui.core.forms.TransformSpecToElements import com.stripe.android.ui.core.forms.resources.ResourceRepository import javax.inject.Inject /** * Wrapper around [TransformSpecToElements] that uses the parameters from [FormFragmentArguments]. */ internal class TransformSpecToElement @Inject constructor( addressResourceRepository: ResourceRepository<AddressRepository>, formFragmentArguments: FormFragmentArguments, context: Context ) { private val transformSpecToElements = TransformSpecToElements( addressResourceRepository = addressResourceRepository, initialValues = formFragmentArguments.getInitialValuesMap(), amount = formFragmentArguments.amount, saveForFutureUseInitialValue = formFragmentArguments.showCheckboxControlledFields, merchantName = formFragmentArguments.merchantName, context = context, shippingValues = formFragmentArguments.shippingDetails ?.toIdentifierMap(formFragmentArguments.billingDetails) ) internal fun transform(list: List<FormItemSpec>) = transformSpecToElements.transform(list) }
mit
ce729da7df7f4e20953903a1bd88185a
46.117647
98
0.794632
5.053628
false
false
false
false
stripe/stripe-android
payments-ui-core/src/test/java/com/stripe/android/ui/core/elements/CardDetailsElementTest.kt
1
3531
package com.stripe.android.ui.core.elements import androidx.appcompat.view.ContextThemeWrapper import androidx.lifecycle.asLiveData import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth import com.stripe.android.model.CardBrand import com.stripe.android.ui.core.R import com.stripe.android.ui.core.forms.FormFieldEntry import com.stripe.android.utils.TestUtils.idleLooper import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class CardDetailsElementTest { private val context = ContextThemeWrapper(ApplicationProvider.getApplicationContext(), R.style.StripeDefaultTheme) @Test fun `test form field values returned and expiration date parsing`() { val cardController = CardDetailsController(context, emptyMap()) val cardDetailsElement = CardDetailsElement( IdentifierSpec.Generic("card_details"), context, initialValues = emptyMap(), viewOnlyFields = emptySet(), cardController ) val flowValues = mutableListOf<List<Pair<IdentifierSpec, FormFieldEntry>>>() cardDetailsElement.getFormFieldValueFlow().asLiveData() .observeForever { flowValues.add(it) } cardDetailsElement.controller.numberElement.controller.onValueChange("4242424242424242") cardDetailsElement.controller.cvcElement.controller.onValueChange("321") cardDetailsElement.controller.expirationDateElement.controller.onValueChange("130") idleLooper() Truth.assertThat(flowValues[flowValues.size - 1]).isEqualTo( listOf( IdentifierSpec.CardNumber to FormFieldEntry("4242424242424242", true), IdentifierSpec.CardCvc to FormFieldEntry("321", true), IdentifierSpec.CardBrand to FormFieldEntry("visa", true), IdentifierSpec.CardExpMonth to FormFieldEntry("01", true), IdentifierSpec.CardExpYear to FormFieldEntry("2030", true) ) ) } @Test fun `test view only form field values returned and expiration date parsing`() { val cardDetailsElement = CardDetailsElement( IdentifierSpec.Generic("card_details"), context, initialValues = mapOf( IdentifierSpec.CardNumber to "4242424242424242", IdentifierSpec.CardBrand to CardBrand.Visa.code ), viewOnlyFields = setOf(IdentifierSpec.CardNumber) ) val flowValues = mutableListOf<List<Pair<IdentifierSpec, FormFieldEntry>>>() cardDetailsElement.getFormFieldValueFlow().asLiveData() .observeForever { flowValues.add(it) } cardDetailsElement.controller.cvcElement.controller.onValueChange("321") cardDetailsElement.controller.expirationDateElement.controller.onValueChange("1230") idleLooper() Truth.assertThat(flowValues[flowValues.size - 1]).isEqualTo( listOf( IdentifierSpec.CardNumber to FormFieldEntry("4242424242424242", true), IdentifierSpec.CardCvc to FormFieldEntry("321", true), IdentifierSpec.CardBrand to FormFieldEntry("visa", true), IdentifierSpec.CardExpMonth to FormFieldEntry("12", true), IdentifierSpec.CardExpYear to FormFieldEntry("2030", true) ) ) } }
mit
ee501e6f31113695a1916fc2f32c474d
39.125
100
0.678278
5.254464
false
true
false
false
ham1/jmeter
buildSrc/subprojects/batchtest/src/main/kotlin/org/apache/jmeter/buildtools/batchtest/BatchTestServer.kt
3
5592
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.buildtools.batchtest import org.gradle.api.GradleException import org.gradle.api.model.ObjectFactory import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.OutputFile import org.gradle.kotlin.dsl.findByType import org.gradle.kotlin.dsl.property import org.gradle.testing.jacoco.plugins.JacocoTaskExtension import java.io.File import java.net.ConnectException import java.net.InetAddress import java.net.ServerSocket import java.net.Socket import java.time.Duration import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import javax.inject.Inject open class BatchTestServer @Inject constructor(objects: ObjectFactory) : BatchTest(objects) { private val executor = Executors.newFixedThreadPool(project.gradle.startParameter.maxWorkerCount) @Internal val serverLogFile = objects.fileProperty() .convention(outputDirectory.file(testName.map { "${it}Server.log" })) @OutputFile val jacocoExecFile = objects.fileProperty() .convention(project.layout.buildDirectory.file("jacoco/$name.exec")) @Input val startupTimeout = objects.property<Duration>() .convention(Duration.ofSeconds(15)) private fun deleteWorkfiles() { project.delete(serverLogFile) } private fun getFreePort(): Int = ServerSocket(0).use { return it.localPort } private fun waitForPort(host: String, port: Int, timeout: Duration): Boolean { val deadline = System.nanoTime() + timeout.toNanos() while (System.nanoTime() < deadline) { try { Socket(host, port).close() return true } catch (e: ConnectException) { /* ignore */ Thread.sleep(50) } } throw GradleException("Unable to connect to $host:$port with timeout of $timeout") } override fun checkErrors(summary: MutableList<String>) { super.checkErrors(summary) catLogFile(serverLogFile.get().asFile, summary) } override fun exec() { deleteWorkfiles() val client = this val serverPort = getFreePort() val serverHost = InetAddress.getLocalHost().canonicalHostName args("-R$serverHost:$serverPort") val jacoco = extensions.findByType<JacocoTaskExtension>() // The extension might not exist, so don't fail if so // When the extension is present, we get javaagent argumet from it val jvmarg = jacoco?.takeIf { it.isEnabled }?.let { val dst = it.destinationFile ?: throw GradleException("destinationFile is not configured for task $this") val serverExec = jacocoExecFile.get().asFile it.setDestinationFile(serverExec) if (serverExec.exists()) { // We want to capture new coverage, not a merged result from previous runs // so previous .exec should be deleted if exists serverExec.delete() } val jvmarg = it.asJvmArg it.setDestinationFile(dst) jvmarg } val server = executor.submit { project.javaexec { workingDir = File(project.rootDir, "bin") mainClass.set("org.apache.jmeter.NewDriver") classpath(client.classpath) standardOutput = System.out.writer().withPrefix("[server] ") errorOutput = System.err.writer().withPrefix("[server] ") maxHeapSize = client.maxHeapSize jvmArgs("-Xss256k", "-XX:MaxMetaspaceSize=128m") if (jvmarg != null) { jvmArgs(jvmarg) } systemProperty("java.rmi.server.hostname", serverHost) systemProperty("server_port", serverPort) systemProperty("java.awt.headless", "true") systemProperty("user.language", userLanguage.get()) systemProperty("user.region", userRegion.get()) systemProperty("user.country", userCountry.get()) args("-pjmeter.properties") args("-q", batchProperties.get()) args("-i", log4jXml.get()) args("-j", serverLogFile.get()) args("-s", "-Jserver.exitaftertest=true") } .rethrowFailure() .assertNormalExitValue() } waitForPort(serverHost, serverPort, startupTimeout.get()) super.exec() try { server.get(1, TimeUnit.SECONDS) } catch (e: TimeoutException) { server.cancel(true) } deleteWorkfiles() } }
apache-2.0
3900c85a421547af57c4ff654e767cf3
36.783784
117
0.637876
4.636816
false
false
false
false
AndroidX/androidx
navigation/navigation-dynamic-features-runtime/src/main/java/androidx/navigation/dynamicfeatures/DynamicGraphNavigator.kt
3
9749
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.dynamicfeatures import android.content.Context import android.os.Bundle import android.util.AttributeSet import androidx.annotation.RestrictTo import androidx.core.content.withStyledAttributes import androidx.navigation.NavBackStackEntry import androidx.navigation.NavDestination import androidx.navigation.NavGraph import androidx.navigation.NavGraphNavigator import androidx.navigation.NavOptions import androidx.navigation.Navigator import androidx.navigation.NavigatorProvider /** * Navigator for graphs in dynamic feature modules. * * This class handles navigating to a progress destination when the installation * of a dynamic feature module is required. By default, the progress destination set * by [installDefaultProgressDestination] will be used, but this can be overridden * by setting the `app:progressDestinationId` attribute in your navigation XML file. */ @Navigator.Name("navigation") public class DynamicGraphNavigator( private val navigatorProvider: NavigatorProvider, private val installManager: DynamicInstallManager ) : NavGraphNavigator(navigatorProvider) { /** * @return The progress destination supplier if any is set. */ internal var defaultProgressDestinationSupplier: (() -> NavDestination)? = null private set internal val destinationsWithoutDefaultProgressDestination = mutableListOf<DynamicNavGraph>() /** * Navigate to a destination. * * In case the destination module is installed the navigation will trigger directly. * Otherwise the dynamic feature module is requested and navigation is postponed until the * module has successfully been installed. */ override fun navigate( entries: List<NavBackStackEntry>, navOptions: NavOptions?, navigatorExtras: Extras? ) { for (entry in entries) { navigate(entry, navOptions, navigatorExtras) } } private fun navigate( entry: NavBackStackEntry, navOptions: NavOptions?, navigatorExtras: Extras? ) { val destination = entry.destination val extras = if (navigatorExtras is DynamicExtras) navigatorExtras else null if (destination is DynamicNavGraph) { val moduleName = destination.moduleName if (moduleName != null && installManager.needsInstall(moduleName)) { installManager.performInstall(entry, extras, moduleName) return } } super.navigate( listOf(entry), navOptions, if (extras != null) extras.destinationExtras else navigatorExtras ) } /** * Create a destination for the [DynamicNavGraph]. * * @return The created graph. */ override fun createDestination(): DynamicNavGraph { return DynamicNavGraph(this, navigatorProvider) } /** * Installs the default progress destination to this graph via a lambda. * This supplies a [NavDestination] to use when the actual destination is not installed at * navigation time. * * This **must** be called before you call [androidx.navigation.NavController.setGraph] to * ensure that all [DynamicNavGraph] instances have the correct progress destination * installed in [onRestoreState]. * * @param progressDestinationSupplier The default progress destination supplier. */ public fun installDefaultProgressDestination( progressDestinationSupplier: () -> NavDestination ) { this.defaultProgressDestinationSupplier = progressDestinationSupplier } /** * Navigates to a destination after progress is done. * * @return The destination to navigate to if any. */ internal fun navigateToProgressDestination( dynamicNavGraph: DynamicNavGraph, progressArgs: Bundle? ) { var progressDestinationId = dynamicNavGraph.progressDestination if (progressDestinationId == 0) { progressDestinationId = installDefaultProgressDestination(dynamicNavGraph) } val progressDestination = dynamicNavGraph.findNode(progressDestinationId) ?: throw IllegalStateException( "The progress destination id must be set and " + "accessible to the module of this navigator." ) val navigator = navigatorProvider.getNavigator<Navigator<NavDestination>>( progressDestination.navigatorName ) val entry = state.createBackStackEntry(progressDestination, progressArgs) navigator.navigate(listOf(entry), null, null) } /** * Install the default progress destination * * @return The [NavDestination#getId] of the newly added progress destination */ private fun installDefaultProgressDestination(dynamicNavGraph: DynamicNavGraph): Int { val progressDestinationSupplier = defaultProgressDestinationSupplier checkNotNull(progressDestinationSupplier) { "You must set a default progress destination " + "using DynamicNavGraphNavigator.installDefaultProgressDestination or " + "pass in an DynamicInstallMonitor in the DynamicExtras.\n" + "Alternatively, when using NavHostFragment make sure to swap it with " + "DynamicNavHostFragment. This will take care of setting the default " + "progress destination for you." } val progressDestination = progressDestinationSupplier.invoke() dynamicNavGraph.addDestination(progressDestination) dynamicNavGraph.progressDestination = progressDestination.id return progressDestination.id } override fun onSaveState(): Bundle? { // Return a non-null Bundle to get a callback to onRestoreState return Bundle.EMPTY } override fun onRestoreState(savedState: Bundle) { super.onRestoreState(savedState) val iterator = destinationsWithoutDefaultProgressDestination.iterator() while (iterator.hasNext()) { val dynamicNavGraph = iterator.next() installDefaultProgressDestination(dynamicNavGraph) iterator.remove() } } /** * The [NavGraph] for dynamic features. */ public class DynamicNavGraph( /** * @hide */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) internal val navGraphNavigator: DynamicGraphNavigator, /** * @hide */ @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) internal val navigatorProvider: NavigatorProvider ) : NavGraph(navGraphNavigator) { internal companion object { /** * Get the [DynamicNavGraph] for a supplied [NavDestination] or throw an * exception if it's not a [DynamicNavGraph]. */ internal fun getOrThrow(destination: NavDestination): DynamicNavGraph { return destination.parent as? DynamicNavGraph ?: throw IllegalStateException( "Dynamic destinations must be part of a DynamicNavGraph.\n" + "You can use DynamicNavHostFragment, which will take care of " + "setting up the NavController for Dynamic destinations.\n" + "If you're not using Fragments, you must set up the " + "NavigatorProvider manually." ) } } /** * The dynamic feature's module name. */ public var moduleName: String? = null /** * Resource id of progress destination. This will be preferred over any * default progress destination set by [installDefaultProgressDestination]. */ public var progressDestination: Int = 0 override fun onInflate(context: Context, attrs: AttributeSet) { super.onInflate(context, attrs) context.withStyledAttributes(attrs, R.styleable.DynamicGraphNavigator) { moduleName = getString(R.styleable.DynamicGraphNavigator_moduleName) progressDestination = getResourceId( R.styleable.DynamicGraphNavigator_progressDestination, 0 ) if (progressDestination == 0) { navGraphNavigator.destinationsWithoutDefaultProgressDestination .add(this@DynamicNavGraph) } } } override fun equals(other: Any?): Boolean { if (other == null || other !is DynamicNavGraph) return false return super.equals(other) && moduleName == other.moduleName && progressDestination == other.progressDestination } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + moduleName.hashCode() result = 31 * result + progressDestination.hashCode() return result } } }
apache-2.0
e6c1fd620330ffc50fb0988ca515b701
37.686508
97
0.659042
5.517261
false
false
false
false
deeplearning4j/deeplearning4j
codegen/op-codegen/src/main/kotlin/org/nd4j/codegen/api/doc/DocSection.kt
1
1348
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.codegen.api.doc import org.nd4j.codegen.api.CodeComponent import org.nd4j.codegen.api.Language data class DocSection(var scope: DocScope? = null, var language: Language? = null, var text: String? = null) { fun applies(language: Language, codeComponent: CodeComponent): Boolean { return (this.language === Language.ANY || language === this.language) && scope!!.applies(codeComponent) } }
apache-2.0
b74b3d8083753193851700af1f9a5a36
38.676471
111
0.610534
4.292994
false
false
false
false
deva666/anko
anko/library/generator/src/org/jetbrains/android/anko/utils/MethodInfo.kt
4
5784
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko import org.jetbrains.android.anko.annotations.ExternalAnnotation.* import org.jetbrains.android.anko.config.GeneratorContext import org.jetbrains.android.anko.utils.* import org.objectweb.asm.Opcodes import org.objectweb.asm.Type import org.objectweb.asm.tree.MethodNode private val specialLayoutParamsArguments = mapOf( "width" to "android.view.ViewGroup.LayoutParams.WRAP_CONTENT", "height" to "android.view.ViewGroup.LayoutParams.WRAP_CONTENT", "w" to "android.view.ViewGroup.LayoutParams.WRAP_CONTENT", "h" to "android.view.ViewGroup.LayoutParams.WRAP_CONTENT" ) private val specialLayoutParamsNames = mapOf( "w" to "width", "h" to "height" ) internal val MethodNode.parameterRawTypes: Array<Type> get() = Type.getArgumentTypes(desc) internal fun getParameterKTypes(node: MethodNode): List<KType> { if (node.signature == null) { return node.parameterRawTypes.map { KType(it.asString(false), isNullable = false) } } val parsed = parseGenericMethodSignature(node.signature) return parsed.valueParameters.map { genericTypeToKType(it.genericType) } } internal fun MethodNodeWithClass.toKMethod(context: GeneratorContext): KMethod { val parameterTypes = getParameterKTypes(this.method) val localVariables = method.localVariables?.map { it.index to it }?.toMap() ?: emptyMap() val parameterRawTypes = this.method.parameterRawTypes val javaArgs = parameterRawTypes.map(Type::asJavaString) val parameterNames = context.sourceManager.getParameterNames(clazz.fqName, method.name, javaArgs) val javaArgsString = javaArgs.joinToString() val methodAnnotationSignature = "${clazz.fqName} ${method.returnType.asJavaString()} ${method.name}($javaArgsString)" var nameIndex = if (method.isStatic) 0 else 1 val parameters = parameterTypes.mapIndexed { index, type -> val parameterAnnotationSignature = "$methodAnnotationSignature $index" val isSimpleType = parameterRawTypes[index].isSimpleType val isNullable = !isSimpleType && !context.annotationManager.hasAnnotation(parameterAnnotationSignature, NotNull) val parameterName = parameterNames?.get(index) ?: localVariables[nameIndex]?.name ?: "p$index" nameIndex += parameterRawTypes[index].size KVariable(parameterName, type.copy(isNullable = isNullable)) } return KMethod(method.name, parameters, method.returnType.toKType()) } internal fun MethodNodeWithClass.formatArguments(context: GeneratorContext): String { return toKMethod(context).parameters.joinToString { "${it.name}: ${it.type}" } } internal fun MethodNodeWithClass.formatLayoutParamsArguments( context: GeneratorContext, importList: ImportList ): List<String> { return toKMethod(context).parameters.map { param -> val renderType = importList.let { it[param.type] } val defaultValue = specialLayoutParamsArguments[param.name] val realName = specialLayoutParamsNames.getOrElse(param.name, { param.name }) if (defaultValue == null) "$realName: $renderType" else "$realName: $renderType = $defaultValue" } } internal fun MethodNodeWithClass.formatLayoutParamsArgumentsInvoke(context: GeneratorContext): String { return toKMethod(context).parameters.joinToString { param -> val realName = specialLayoutParamsNames.getOrElse(param.name, { param.name }) val explicitNotNull = if (param.type.isNullable) "!!" else "" "$realName$explicitNotNull" } } internal fun MethodNodeWithClass.formatArgumentsTypes(context: GeneratorContext): String { return toKMethod(context).parameters.joinToString { it.type.toString() } } internal fun MethodNodeWithClass.formatArgumentsNames(context: GeneratorContext): String { return toKMethod(context).parameters.joinToString { it.name } } fun MethodNode.isGetter(): Boolean { val isNonBooleanGetter = name.startsWith("get") && name.length > 3 && Character.isUpperCase(name[3]) val isBooleanGetter = name.startsWith("is") && name.length > 2 && Character.isUpperCase(name[2]) return (isNonBooleanGetter || isBooleanGetter) && parameterRawTypes.isEmpty() && !returnType.isVoid && isPublic } internal fun MethodNode.isNonListenerSetter(): Boolean { val isSetter = name.startsWith("set") && name.length > 3 && Character.isUpperCase(name[3]) return isSetter && !(isListenerSetter() || name.endsWith("Listener")) && parameterRawTypes.size == 1 && isPublic } internal val MethodNode.isConstructor: Boolean get() = name == "<init>" internal fun MethodNode.isListenerSetter(set: Boolean = true, add: Boolean = true): Boolean { return ((set && name.startsWith("setOn")) || (add && name.startsWith("add"))) && name.endsWith("Listener") } internal val MethodNode.isPublic: Boolean get() = (access and Opcodes.ACC_PUBLIC) != 0 internal val MethodNode.isOverridden: Boolean get() = (access and Opcodes.ACC_BRIDGE) != 0 internal val MethodNode.isStatic: Boolean get() = (access and Opcodes.ACC_STATIC) != 0 internal val MethodNode.returnType: Type get() = Type.getReturnType(desc)
apache-2.0
60c4bcd279b6c99f074376645cef9400
40.618705
121
0.731674
4.303571
false
false
false
false
yzbzz/beautifullife
icore/src/main/java/com/ddu/icore/common/Executors.kt
2
1889
package com.ddu.icore.common import android.os.Handler import android.os.Looper import java.util.concurrent.* import java.util.concurrent.Executors import kotlin.math.max import kotlin.math.min /** * Created by yzbzz on 2019-08-11. */ object Executors { val CPU_COUNT = Runtime.getRuntime().availableProcessors() val CORE_POOL_SIZE = max(2, min(CPU_COUNT - 1, 4)) val MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1 const val KEEP_ALIVE_SECONDS = 30L val sPoolWorkQueue = LinkedBlockingQueue<Runnable>(128) val DISK_IO_EXECUTOR = Executors.newSingleThreadExecutor() val NETWORK_IO_EXECUTOR = Executors.newFixedThreadPool(3) val MAIN_THREAD_EXECUTOR = MainThreadExecutor() val SCHEDULED_IO__EXECUTOR = Executors.newSingleThreadScheduledExecutor() var THREAD_POOL_EXECUTOR: ThreadPoolExecutor init { val threadPoolExecutor = ThreadPoolExecutor( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue ) threadPoolExecutor.allowCoreThreadTimeOut(true) THREAD_POOL_EXECUTOR = threadPoolExecutor } fun ioThread(f: () -> Unit) = DISK_IO_EXECUTOR.execute(f) fun netWorkIoThread(f: () -> Unit) = NETWORK_IO_EXECUTOR.execute(f) fun mainThread(f: () -> Unit) = MAIN_THREAD_EXECUTOR.execute(f) fun excute(f: () -> Unit) = THREAD_POOL_EXECUTOR.execute(f) fun schedule(f: () -> Unit, delay: Long, unit: TimeUnit) = SCHEDULED_IO__EXECUTOR.schedule(f, delay, unit) fun scheduleAtFixedRat(f: () -> Unit, initialDelay: Long, period: Long, unit: TimeUnit) = SCHEDULED_IO__EXECUTOR.scheduleAtFixedRate(f, initialDelay, period, unit) class MainThreadExecutor : Executor { val handler = Handler(Looper.getMainLooper()) override fun execute(command: Runnable?) { handler.post(command) } } }
apache-2.0
b67496165f588ca0c150a1bb870e01a5
31.016949
110
0.689254
4.010616
false
false
false
false
cqjjjzr/Laplacian
Laplacian.Framework/src/main/kotlin/charlie/laplacian/frontend/FrontendRegistry.kt
1
702
package charlie.laplacian.frontend import java.util.* object FrontendRegistry { private val frontends: MutableSet<Frontend> = HashSet() fun registerFrontend(gui: Frontend) { frontends += gui } fun unregisterFrontend(gui: Frontend) { frontends -= gui } fun findFrontend(className: String) = frontends.find { it.javaClass.name == className } ?: throw NoSuchElementException(className) fun getFrontends(): Set<Frontend> = Collections.unmodifiableSet(frontends) private var currentFrontend: Frontend? = null fun startupGUI(frontend: Frontend) { currentFrontend?.destroy() currentFrontend = frontend frontend.init() } }
apache-2.0
f87e66371af01db1aa26e40120575a9e
25.037037
134
0.689459
4.588235
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/net/social/Actor.kt
1
38258
/* * Copyright (C) 2013-2018 yvolk (Yuri Volkov), http://yurivolkov.com * * 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.andstatus.app.net.social import android.database.Cursor import android.net.Uri import android.provider.BaseColumns import io.vavr.control.Try import org.andstatus.app.R import org.andstatus.app.account.AccountName import org.andstatus.app.actor.Group import org.andstatus.app.actor.GroupType import org.andstatus.app.context.ActorInTimeline import org.andstatus.app.context.MyContext import org.andstatus.app.context.MyPreferences import org.andstatus.app.data.ActorSql import org.andstatus.app.data.AvatarFile import org.andstatus.app.data.DbUtils import org.andstatus.app.data.DownloadStatus import org.andstatus.app.data.MyQuery import org.andstatus.app.data.OidEnum import org.andstatus.app.database.table.ActorTable import org.andstatus.app.origin.Origin import org.andstatus.app.origin.OriginPumpio import org.andstatus.app.origin.OriginType import org.andstatus.app.os.AsyncUtil import org.andstatus.app.service.CommandData import org.andstatus.app.service.CommandEnum import org.andstatus.app.service.MyServiceManager import org.andstatus.app.timeline.meta.TimelineType import org.andstatus.app.user.User import org.andstatus.app.util.IsEmpty import org.andstatus.app.util.LazyVal import org.andstatus.app.util.MyHtml import org.andstatus.app.util.MyLog import org.andstatus.app.util.MyStringBuilder import org.andstatus.app.util.NullUtil import org.andstatus.app.util.RelativeTime import org.andstatus.app.util.SharedPreferencesUtil import org.andstatus.app.util.StringUtil import org.andstatus.app.util.TriState import org.andstatus.app.util.UriUtils import org.andstatus.app.util.UrlUtils import org.junit.Assert import java.net.URL import java.util.* import java.util.function.Supplier import java.util.stream.Collectors /** * @author [email protected] */ class Actor private constructor(// In our system val origin: Origin, val groupType: GroupType, @Volatile var actorId: Long, actorOid: String? ) : Comparable<Actor>, IsEmpty { val oid: String = if (actorOid.isNullOrEmpty()) "" else actorOid private var parentActorId: Long = 0 private var parentActor: LazyVal<Actor> = LazyVal.of(::EMPTY) private var username: String = "" private var webFingerId: String = "" private var isWebFingerIdValid = false private var realName: String = "" private var summary: String = "" var location: String = "" private var profileUri = Uri.EMPTY private var homepage: String = "" private var avatarUri = Uri.EMPTY val endpoints: ActorEndpoints = ActorEndpoints.from(origin.myContext, actorId) private val connectionHost: LazyVal<String> = LazyVal.of { evalConnectionHost() } private val idHost: LazyVal<String> = LazyVal.of { evalIdHost() } var notesCount: Long = 0 var favoritesCount: Long = 0 var followingCount: Long = 0 var followersCount: Long = 0 private var createdDate = RelativeTime.DATETIME_MILLIS_NEVER private var updatedDate = RelativeTime.DATETIME_MILLIS_NEVER private var latestActivity: AActivity? = null // Hack for Twitter-like origins... var isMyFriend: TriState = TriState.UNKNOWN var avatarFile: AvatarFile = AvatarFile.EMPTY /** null value really happened for [EMPTY]. * Caused by cyclic initialization or by lazy initialization... */ get() = field ?: AvatarFile.EMPTY @Volatile var user: User = User.EMPTY @Volatile private var isFullyDefined: TriState = TriState.UNKNOWN fun getDefaultMyAccountTimelineTypes(): List<TimelineType> { return if (origin.originType.isPrivatePostsSupported()) TimelineType.getDefaultMyAccountTimelineTypes() else TimelineType.getDefaultMyAccountTimelineTypes().stream() .filter { t: TimelineType? -> t != TimelineType.PRIVATE } .collect(Collectors.toList()) } private fun betterToCache(other: Actor): Actor { return if (isBetterToCacheThan(other)) this else other } /** this Actor is MyAccount and the Actor updates objActor */ fun update(objActor: Actor): AActivity { return update(this, objActor) } /** this actor updates objActor */ fun update(accountActor: Actor, objActor: Actor): AActivity { return if (objActor === EMPTY) AActivity.EMPTY else act(accountActor, ActivityType.UPDATE, objActor) } /** this actor acts on objActor */ fun act(accountActor: Actor, activityType: ActivityType, objActor: Actor): AActivity { if (this === EMPTY || accountActor === EMPTY || objActor === EMPTY) { return AActivity.EMPTY } val mbActivity: AActivity = AActivity.from(accountActor, activityType) mbActivity.setActor(this) mbActivity.setObjActor(objActor) return mbActivity } fun isConstant(): Boolean = this === EMPTY || this === PUBLIC || this === FOLLOWERS override val isEmpty: Boolean get() { if (this === EMPTY) return true if (isConstant()) return false if (!origin.isValid) return true return actorId == 0L && UriUtils.nonRealOid(oid) && !isWebFingerIdValid() && !isUsernameValid() } fun dontStore(): Boolean { return isConstant() } fun isFullyDefined(): Boolean { if (isFullyDefined.unknown) { isFullyDefined = calcIsFullyDefined() } return isFullyDefined.isTrue } private fun calcIsFullyDefined(): TriState { if (cannotAdd || UriUtils.nonRealOid(oid)) return TriState.FALSE return TriState.fromBoolean(isWebFingerIdValid() && isUsernameValid()) } val cannotAdd: Boolean get() { val parentIsValid = if (groupType.isGroupLike) { if (groupType.hasParentActor) { parentActorId != 0L } else { parentActorId == 0L } } else { parentActorId == 0L } return isEmpty || !parentIsValid } fun isNotFullyDefined(): Boolean { return !isFullyDefined() } fun isBetterToCacheThan(other: Actor): Boolean { if (this === other) return false if (other.isConstant()) return true if (isFullyDefined() && other.isNotFullyDefined()) return true if (groupType.isGroupLike && !other.groupType.isGroupLike) { MyLog.v(this) { "isBetterToCacheThan : $this,\n other:$other\n${MyLog.currentStackTrace}" } return true } if (this === EMPTY) return false if (isNotFullyDefined() && other.isFullyDefined()) return false return if (isFullyDefined()) { if (getUpdatedDate() != other.getUpdatedDate()) { return getUpdatedDate() > other.getUpdatedDate() } if (avatarFile.downloadedDate != other.avatarFile.downloadedDate) { avatarFile.downloadedDate > other.avatarFile.downloadedDate } else notesCount > other.notesCount } else { if (isOidReal() && !other.isOidReal()) return true if (!isOidReal() && other.isOidReal()) return false if (isUsernameValid() && !other.isUsernameValid()) return true if (!isUsernameValid() && other.isUsernameValid()) return false if (isWebFingerIdValid() && !other.isWebFingerIdValid()) return true if (!isWebFingerIdValid() && other.isWebFingerIdValid()) return false if (UriUtils.nonEmpty(profileUri) && UriUtils.isEmpty(other.profileUri)) return true if (UriUtils.isEmpty(profileUri) && UriUtils.nonEmpty(other.profileUri)) false else getUpdatedDate() > other.getUpdatedDate() } } fun isIdentified(): Boolean { return actorId != 0L && isOidReal() } fun isOidReal(): Boolean { return UriUtils.isRealOid(oid) } fun canGetActor(): Boolean { return (isOidReal() || isWebFingerIdValid()) && getConnectionHost().isNotEmpty() } override fun toString(): String { if (this === EMPTY) { return "Actor:EMPTY" } val members: MyStringBuilder = MyStringBuilder.of("origin:" + origin.name) .withComma("id", actorId) .withComma("oid", oid) .withComma( if (isWebFingerIdValid()) "webFingerId" else "", if (webFingerId.isEmpty()) "" else if (isWebFingerIdValid()) webFingerId else "(invalid webFingerId)" ) .withComma("username", username) .withComma("realName", realName) .withComma("groupType", if (groupType == GroupType.UNKNOWN) "" else groupType) .withComma("", user) { user.nonEmpty } .withComma<Uri?>("profileUri", profileUri, { obj: Uri? -> UriUtils.nonEmpty(obj) }) .withComma<Uri?>("avatar", avatarUri, { obj: Uri? -> UriUtils.nonEmpty(obj) }) .withComma<AvatarFile>("avatarFile", avatarFile, { obj: AvatarFile -> obj.nonEmpty }) .withComma("banner", endpoints.findFirst(ActorEndpointType.BANNER).orElse(null)) .withComma("", "latest note present", { hasLatestNote() }) if (parentActor.isEvaluated() && parentActor.get().nonEmpty) { members.withComma("parent", parentActor.get()) } else if (parentActorId != 0L) { members.withComma("parentId", parentActorId) } return MyStringBuilder.formatKeyValue(this, members) } fun getUsername(): String { return username } fun getUniqueNameWithOrigin(): String { return uniqueName + AccountName.ORIGIN_SEPARATOR + origin.name } val uniqueName: String get() { if (StringUtil.nonEmptyNonTemp(username)) return username + getOptAtHostForUniqueName() if (StringUtil.nonEmptyNonTemp(realName)) return realName + getOptAtHostForUniqueName() if (isWebFingerIdValid()) return webFingerId return if (StringUtil.nonEmptyNonTemp(oid)) oid else "id:" + actorId + getOptAtHostForUniqueName() } private fun getOptAtHostForUniqueName(): String { return if (origin.originType.uniqueNameHasHost()) if (getIdHost().isEmpty()) "" else "@" + getIdHost() else "" } fun withUniqueName(uniqueName: String?): Actor { uniqueNameToUsername(origin, uniqueName).ifPresent { username: String? -> setUsername(username) } uniqueNameToWebFingerId( origin, uniqueName ).ifPresent { webFingerIdIn: String? -> setWebFingerId(webFingerIdIn) } return this } fun setUsername(username: String?): Actor { check(this !== EMPTY) { "Cannot set username of EMPTY Actor" } this.username = if (username.isNullOrEmpty()) "" else username.trim { it <= ' ' } return this } fun getProfileUrl(): String { return profileUri.toString() } fun setProfileUrl(url: String?): Actor { profileUri = UriUtils.fromString(url) return this } fun setProfileUrlToOriginUrl(originUrl: URL?) { profileUri = UriUtils.fromUrl(originUrl) } override fun equals(other: Any?): Boolean { if (this === other) return true return if (other !is Actor) false else isSame(other as Actor, true) } override fun hashCode(): Int { var result = origin.hashCode() if (actorId != 0L) { return 31 * result + java.lang.Long.hashCode(actorId) } if (UriUtils.isRealOid(oid)) { return 31 * result + oid.hashCode() } else if (isWebFingerIdValid) { return 31 * result + getWebFingerId().hashCode() } else if (isUsernameValid()) { result = 31 * result + getUsername().hashCode() } return result } /** Doesn't take origin into account */ fun isSame(that: Actor): Boolean { return isSame(that, false) } fun isSame(other: Actor, sameOriginOnly: Boolean): Boolean { if (this === other) return true if (other == null) return false if (actorId != 0L) { if (actorId == other.actorId) return true } if (origin == other.origin) { if (UriUtils.isRealOid(oid) && oid == other.oid) { return true } } else if (sameOriginOnly) { return false } if (isWebFingerIdValid()) { if (webFingerId == other.webFingerId) return true if (other.isWebFingerIdValid) return false } return if (groupType.isDifferentActor(other.groupType)) false else isUsernameValid() && other.isUsernameValid() && username.equals(other.username, ignoreCase = true) } fun notSameUser(other: Actor): Boolean { return !isSameUser(other) } fun isSameUser(other: Actor): Boolean { return if (user.actorIds.isEmpty() || other.actorId == 0L) { if (other.user.actorIds.isEmpty() || actorId == 0L) isSame(other) else other.user.actorIds.contains(actorId) } else user.actorIds.contains(other.actorId) } fun build(): Actor { if (this.isConstant()) return this connectionHost.reset() if (username.isEmpty() || isWebFingerIdValid) return this if (username.contains("@")) { setWebFingerId(username) } else if (!UriUtils.isEmpty(profileUri)) { if (origin.isValid) { setWebFingerId(username + "@" + origin.fixUriForPermalink(profileUri).host) } else { setWebFingerId(username + "@" + profileUri.host) } // Don't infer "id host" from the Origin's host } return this } fun setWebFingerId(webFingerIdIn: String?): Actor { if (webFingerIdIn.isNullOrEmpty() || !webFingerIdIn.contains("@")) return this var potentialUsername = webFingerIdIn val nameBeforeTheLastAt = webFingerIdIn.substring(0, webFingerIdIn.lastIndexOf("@")) if (isWebFingerIdValid(webFingerIdIn)) { webFingerId = webFingerIdIn.toLowerCase() isWebFingerIdValid = true potentialUsername = nameBeforeTheLastAt } else { val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@") if (lastButOneIndex > -1) { val potentialWebFingerId = webFingerIdIn.substring(lastButOneIndex + 1) if (isWebFingerIdValid(potentialWebFingerId)) { webFingerId = potentialWebFingerId.toLowerCase() isWebFingerIdValid = true potentialUsername = webFingerIdIn.substring(0, lastButOneIndex) } } } if (!isUsernameValid() && origin.isUsernameValid(potentialUsername)) { username = potentialUsername } return this } fun getWebFingerId(): String { return webFingerId } fun isWebFingerIdValid(): Boolean { return isWebFingerIdValid } fun getBestUri(): String { if (!StringUtil.isEmptyOrTemp(oid)) { return oid } if (isUsernameValid() && getIdHost().isNotEmpty()) { return OriginPumpio.ACCOUNT_PREFIX + getUsername() + "@" + getIdHost() } return if (isWebFingerIdValid()) { OriginPumpio.ACCOUNT_PREFIX + getWebFingerId() } else "" } /** Lookup the application's id from other IDs */ fun lookupActorId() { if (isConstant()) return if (actorId == 0L && isOidReal()) { actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, oid) } if (actorId == 0L && isWebFingerIdValid()) { actorId = MyQuery.webFingerIdToId(origin.myContext, origin.id, webFingerId, true) } if (actorId == 0L && username.isNotEmpty()) { val actorId2 = origin.usernameToId(username) if (actorId2 != 0L) { var skip2 = false if (isWebFingerIdValid()) { val webFingerId2 = MyQuery.actorIdToWebfingerId(origin.myContext, actorId2) if (isWebFingerIdValid(webFingerId2)) { skip2 = !webFingerId.equals(webFingerId2, ignoreCase = true) if (!skip2) actorId = actorId2 } } if (actorId == 0L && !skip2 && isOidReal()) { val oid2 = MyQuery.idToOid(origin.myContext, OidEnum.ACTOR_OID, actorId2, 0) if (UriUtils.isRealOid(oid2)) skip2 = !oid.equals(oid2, ignoreCase = true) } if (actorId == 0L && !skip2 && groupType != GroupType.UNKNOWN) { val groupTypeStored = origin.myContext.users.idToGroupType(actorId2) if (Group.groupTypeNeedsCorrection(groupTypeStored, groupType)) { val updatedDateStored = MyQuery.actorIdToLongColumnValue(ActorTable.UPDATED_DATE, actorId) if (getUpdatedDate() <= updatedDateStored) { setUpdatedDate(Math.max(updatedDateStored + 1, RelativeTime.SOME_TIME_AGO + 1)) } } } if (actorId == 0L && !skip2) { actorId = actorId2 } } } if (actorId == 0L) { actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, toTempOid()) } if (actorId == 0L && hasAltTempOid()) { actorId = MyQuery.oidToId(origin.myContext, OidEnum.ACTOR_OID, origin.id, toAltTempOid()) } } fun hasAltTempOid(): Boolean { return toTempOid() != toAltTempOid() && username.isNotEmpty() } fun hasLatestNote(): Boolean { return latestActivity?.isEmpty == false } fun toAltTempOid(): String { return toTempOid("", username) } /** Tries to find this actor in his home origin (the same host...). * Returns the same Actor, if not found */ fun toHomeOrigin(): Actor { return if (origin.getHost() == getIdHost()) this else user.actorIds.stream() .map { id: Long -> NullUtil.getOrDefault(origin.myContext.users.actors, id, EMPTY) } .filter { a: Actor -> a.nonEmpty && a.origin.getHost() == getIdHost() } .findAny().orElse(this) } fun extractActorsFromContent(text: String?, inReplyToActorIn: Actor): List<Actor> { return extractActorsFromContent( MyHtml.htmlToCompactPlainText(text), 0, ArrayList(), inReplyToActorIn.withValidUsernameAndWebfingerId() ) } private fun extractActorsFromContent( text: String, textStart: Int, actors: MutableList<Actor>, inReplyToActor: Actor ): MutableList<Actor> { val actorReference = origin.getActorReference(text, textStart) if (actorReference.index < textStart) return actors var validUsername: String? = "" var validWebFingerId: String? = "" var ind = actorReference.index while (ind < text.length) { if (Patterns.WEBFINGER_ID_CHARS.indexOf(text.get(ind)) < 0) { break } val username = text.substring(actorReference.index, ind + 1) if (origin.isUsernameValid(username)) { validUsername = username } if (isWebFingerIdValid(username)) { validWebFingerId = username } ind++ } if (!validWebFingerId.isNullOrEmpty() || !validUsername.isNullOrEmpty()) { addExtractedActor(actors, validWebFingerId, validUsername, actorReference.groupType, inReplyToActor) } return extractActorsFromContent(text, ind + 1, actors, inReplyToActor) } private fun withValidUsernameAndWebfingerId(): Actor { return if (isWebFingerIdValid && isUsernameValid() || actorId == 0L) this else load(origin.myContext, actorId) } fun isUsernameValid(): Boolean { return StringUtil.nonEmptyNonTemp(username) && origin.isUsernameValid(username) } private fun addExtractedActor( actors: MutableList<Actor>, webFingerId: String?, validUsername: String?, groupType: GroupType, inReplyToActor: Actor ) { var actor = newUnknown(origin, groupType) if (isWebFingerIdValid(webFingerId)) { actor.setWebFingerId(webFingerId) actor.setUsername(validUsername) } else { // Is this a reply to Actor if (validUsername.equals(inReplyToActor.getUsername(), ignoreCase = true)) { actor = inReplyToActor } else if (validUsername.equals(getUsername(), ignoreCase = true)) { actor = this } else { // Don't infer "id host", if it wasn't explicitly provided actor.setUsername(validUsername) } } actor.build() actors.add(actor) } fun getConnectionHost(): String { return connectionHost.get() } private fun evalConnectionHost(): String { if (origin.shouldHaveUrl()) { return origin.getHost() } return if (!profileUri.host.isNullOrEmpty()) { profileUri.host ?: "" } else UrlUtils.getHost(oid).orElseGet { if (isWebFingerIdValid) { val pos = getWebFingerId().indexOf('@') if (pos >= 0) { return@orElseGet getWebFingerId().substring(pos + 1) } } "" } } fun getIdHost(): String { return idHost.get() } private fun evalIdHost(): String { return UrlUtils.getHost(oid).orElseGet { if (isWebFingerIdValid) { val pos = getWebFingerId().indexOf('@') if (pos >= 0) { return@orElseGet getWebFingerId().substring(pos + 1) } } if (!profileUri.host.isNullOrEmpty()) { return@orElseGet profileUri.host } "" } } fun getSummary(): String { return summary } fun setSummary(summary: String?): Actor { if (!isEmpty && !summary.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(summary)) { this.summary = summary } return this } fun getHomepage(): String { return homepage } fun setHomepage(homepage: String?) { if (!homepage.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(homepage)) { this.homepage = homepage } } fun getRecipientName(): String { return if (groupType == GroupType.FOLLOWERS) { origin.myContext.context.getText(R.string.followers).toString() } else uniqueName } fun getActorNameInTimelineWithOrigin(): String { return if (MyPreferences.getShowOrigin() && nonEmpty) { val name = actorNameInTimeline + " / " + origin.name if (origin.originType === OriginType.GNUSOCIAL && MyPreferences.isShowDebuggingInfoInUi() && oid.isNotEmpty() ) { "$name oid:$oid" } else name } else actorNameInTimeline } val actorNameInTimeline: String get() { val name1 = getActorNameInTimeline1() return if (name1.isNotEmpty()) name1 else getUniqueNameWithOrigin() } private fun getActorNameInTimeline1(): String { if (groupType.isGroupLike) { return prefferrablyRealName() } return when (MyPreferences.getActorInTimeline()) { ActorInTimeline.AT_USERNAME -> if (username.isEmpty()) "" else "@$username" ActorInTimeline.WEBFINGER_ID -> if (isWebFingerIdValid) webFingerId else "" ActorInTimeline.REAL_NAME -> prefferrablyRealName() ActorInTimeline.REAL_NAME_AT_USERNAME -> if (realName.isNotEmpty() && username.isNotEmpty()) "$realName @$username" else username ActorInTimeline.REAL_NAME_AT_WEBFINGER_ID -> if (realName.isNotEmpty() && webFingerId.isNotEmpty()) "$realName @$webFingerId" else webFingerId else -> username } } private fun prefferrablyRealName() = if (realName.isNotEmpty()) realName else username fun getRealName(): String { return realName } fun setRealName(realName: String?): Actor { if (!realName.isNullOrEmpty() && !SharedPreferencesUtil.isEmpty(realName)) { this.realName = realName } return this } fun getCreatedDate(): Long { return createdDate } fun setCreatedDate(createdDate: Long) { this.createdDate = if (createdDate < RelativeTime.SOME_TIME_AGO) RelativeTime.SOME_TIME_AGO else createdDate } fun getUpdatedDate(): Long { return updatedDate } fun setUpdatedDate(updatedDate: Long): Actor { if (this.updatedDate < updatedDate) { this.updatedDate = if (updatedDate < RelativeTime.SOME_TIME_AGO) RelativeTime.SOME_TIME_AGO else updatedDate } return this } override operator fun compareTo(other: Actor): Int { if (actorId != 0L && other.actorId != 0L) { if (actorId == other.actorId) { return 0 } return if (origin.id > other.origin.id) 1 else -1 } return if (origin.id != other.origin.id) { if (origin.id > other.origin.id) 1 else -1 } else oid.compareTo(other.oid) } fun getLatestActivity(): AActivity { return latestActivity ?: AActivity.EMPTY } fun setLatestActivity(latestActivity: AActivity) { this.latestActivity = latestActivity if (latestActivity.getAuthor().isEmpty) { latestActivity.setAuthor(this) } } fun toActorTitle(): String { val builder = StringBuilder() val uniqueName = uniqueName if (uniqueName.isNotEmpty()) { builder.append("@$uniqueName") } if (getRealName().isNotEmpty()) { MyStringBuilder.appendWithSpace(builder, "(" + getRealName() + ")") } return builder.toString() } fun lookupUser(): Actor { return if (isEmpty) this else origin.myContext.users.lookupUser(this) } fun saveUser() { if (user.isMyUser.unknown && origin.myContext.users.isMe(this)) { user.isMyUser = TriState.TRUE } if (user.userId == 0L) user.setKnownAs(uniqueName) user.save(origin.myContext) } fun hasAvatar(): Boolean { return UriUtils.nonEmpty(avatarUri) } fun hasAvatarFile(): Boolean { return AvatarFile.EMPTY !== avatarFile } fun requestDownload(isManuallyLaunched: Boolean) { if (canGetActor()) { MyLog.v(this) { "Actor $this will be loaded from the Internet" } val command: CommandData = CommandData.newActorCommandAtOrigin( CommandEnum.GET_ACTOR, this, getUsername(), origin ) .setManuallyLaunched(isManuallyLaunched) MyServiceManager.sendForegroundCommand(command) } else { MyLog.v(this) { "Cannot get Actor $this" } } } fun isPublic(): Boolean { return groupType == GroupType.PUBLIC } fun isFollowers(): Boolean { return groupType == GroupType.FOLLOWERS } fun nonPublic(): Boolean { return !isPublic() } fun getAvatarUri(): Uri? { return avatarUri } fun getAvatarUrl(): String { return avatarUri.toString() } fun setAvatarUrl(avatarUrl: String?) { setAvatarUri(UriUtils.fromString(avatarUrl)) } fun setAvatarUri(avatarUri: Uri?) { this.avatarUri = UriUtils.notNull(avatarUri) if (hasAvatar() && avatarFile.isEmpty) { avatarFile = AvatarFile.fromActorOnly(this) } } fun requestAvatarDownload() { if (hasAvatar() && MyPreferences.getShowAvatars() && avatarFile.downloadStatus != DownloadStatus.LOADED) { avatarFile.requestDownload() } } fun getEndpoint(type: ActorEndpointType?): Optional<Uri> { val uri = endpoints.findFirst(type) return if (uri.isPresent) uri else if (type == ActorEndpointType.API_PROFILE) UriUtils.toDownloadableOptional(oid) else Optional.empty() } fun assertContext() { if (isConstant()) return try { origin.assertContext() } catch (e: Throwable) { Assert.fail("Failed on $this\n${e.message}") } } fun setParentActor(myContext: MyContext, parentActor: Actor): Actor { if (this.parentActorId != parentActor.actorId) { this.parentActorId = parentActor.actorId this.parentActor = LazyVal.of(parentActor) } return this } fun setParentActorId(myContext: MyContext, parentActorId: Long): Actor { if (this.parentActorId != parentActorId) { this.parentActorId = parentActorId parentActor = if (parentActorId == 0L) LazyVal.of(EMPTY) else LazyVal.of { load(myContext, parentActorId) } } return this } fun getParentActorId(): Long { return parentActorId } fun getParent(): Actor { return parentActor.get() } fun toTempOid(): String { return toTempOid(webFingerId, username) } companion object { val lazyEmpty: Lazy<Actor> = lazy { newUnknown(Origin.EMPTY, GroupType.UNKNOWN).apply { username = "Empty" } } val EMPTY: Actor by lazyEmpty val TRY_EMPTY: Try<Actor> by lazy { Try.success(EMPTY) } val PUBLIC: Actor by lazy { fromTwoIds( Origin.EMPTY, GroupType.PUBLIC, 0, "https://www.w3.org/ns/activitystreams#Public" ).apply { username = "Public" } } val FOLLOWERS: Actor by lazy { fromTwoIds( Origin.EMPTY, GroupType.FOLLOWERS, 0, "org.andstatus.app.net.social.Actor#Followers" ).apply { username = "Followers" } } fun load(myContext: MyContext, actorId: Long): Actor { return load(myContext, actorId, false, ::EMPTY) } fun load(myContext: MyContext, actorId: Long, reloadFirst: Boolean, supplier: Supplier<Actor>): Actor { if (actorId == 0L) return supplier.get() val cached = myContext.users.actors.getOrDefault(actorId, EMPTY) return if (AsyncUtil.nonUiThread && (reloadFirst || cached.isNotFullyDefined())) loadFromDatabase(myContext, actorId, supplier, true).betterToCache(cached) else cached } fun loadFromDatabase( myContext: MyContext, actorId: Long, supplier: Supplier<Actor>, useCache: Boolean ): Actor { val sql = ("SELECT " + ActorSql.selectFullProjection() + " FROM " + ActorSql.allTables() + " WHERE " + ActorTable.TABLE_NAME + "." + BaseColumns._ID + "=" + actorId) val function = { cursor: Cursor -> fromCursor(myContext, cursor, useCache) } return MyQuery.get(myContext, sql, function).stream().findFirst().orElseGet(supplier) } /** Updates cache on load */ fun fromCursor(myContext: MyContext, cursor: Cursor, useCache: Boolean): Actor { val updatedDate = DbUtils.getLong(cursor, ActorTable.UPDATED_DATE) val actor = fromTwoIds( myContext.origins.fromId(DbUtils.getLong(cursor, ActorTable.ORIGIN_ID)), GroupType.fromId(DbUtils.getLong(cursor, ActorTable.GROUP_TYPE)), DbUtils.getLong(cursor, ActorTable.ACTOR_ID), DbUtils.getString(cursor, ActorTable.ACTOR_OID) ) actor.setParentActorId(myContext, DbUtils.getLong(cursor, ActorTable.PARENT_ACTOR_ID)) actor.setRealName(DbUtils.getString(cursor, ActorTable.REAL_NAME)) actor.setUsername(DbUtils.getString(cursor, ActorTable.USERNAME)) actor.setWebFingerId(DbUtils.getString(cursor, ActorTable.WEBFINGER_ID)) actor.setSummary(DbUtils.getString(cursor, ActorTable.SUMMARY)) actor.location = DbUtils.getString(cursor, ActorTable.LOCATION) actor.setProfileUrl(DbUtils.getString(cursor, ActorTable.PROFILE_PAGE)) actor.setHomepage(DbUtils.getString(cursor, ActorTable.HOMEPAGE)) actor.setAvatarUrl(DbUtils.getString(cursor, ActorTable.AVATAR_URL)) actor.notesCount = DbUtils.getLong(cursor, ActorTable.NOTES_COUNT) actor.favoritesCount = DbUtils.getLong(cursor, ActorTable.FAVORITES_COUNT) actor.followingCount = DbUtils.getLong(cursor, ActorTable.FOLLOWING_COUNT) actor.followersCount = DbUtils.getLong(cursor, ActorTable.FOLLOWERS_COUNT) actor.setCreatedDate(DbUtils.getLong(cursor, ActorTable.CREATED_DATE)) actor.setUpdatedDate(updatedDate) actor.user = User.fromCursor(myContext, cursor, useCache) actor.avatarFile = AvatarFile.fromCursor(actor, cursor) return if (useCache) { val cachedActor = myContext.users.actors.getOrDefault(actor.actorId, EMPTY) if (actor.isBetterToCacheThan(cachedActor)) { myContext.users.updateCache(actor) return actor } cachedActor } else { actor } } fun newUnknown(origin: Origin, groupType: GroupType): Actor { return fromTwoIds(origin, groupType, 0, "") } fun fromId(origin: Origin, actorId: Long): Actor { return fromTwoIds(origin, GroupType.UNKNOWN, actorId, "") } fun fromOid(origin: Origin, actorOid: String?): Actor { return fromTwoIds(origin, GroupType.UNKNOWN, 0, actorOid) } fun fromTwoIds(origin: Origin, groupType: GroupType, actorId: Long, actorOid: String?): Actor { return Actor(origin, groupType, actorId, actorOid) } fun uniqueNameToUsername(origin: Origin, uniqueName: String?): Optional<String> { if (!uniqueName.isNullOrEmpty()) { if (uniqueName.contains("@")) { val nameBeforeTheLastAt = uniqueName.substring(0, uniqueName.lastIndexOf("@")) if (isWebFingerIdValid(uniqueName)) { if (origin.isUsernameValid(nameBeforeTheLastAt)) return Optional.of(nameBeforeTheLastAt) } else { val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@") if (lastButOneIndex > -1) { // A case when a Username contains "@" val potentialWebFingerId = uniqueName.substring(lastButOneIndex + 1) if (isWebFingerIdValid(potentialWebFingerId)) { val nameBeforeLastButOneAt = uniqueName.substring(0, lastButOneIndex) if (origin.isUsernameValid(nameBeforeLastButOneAt)) return Optional.of( nameBeforeLastButOneAt ) } } } } if (origin.isUsernameValid(uniqueName)) return Optional.of(uniqueName) } return Optional.empty() } fun uniqueNameToWebFingerId(origin: Origin, uniqueName: String?): Optional<String> { if (!uniqueName.isNullOrEmpty()) { if (uniqueName.contains("@")) { val nameBeforeTheLastAt = uniqueName.substring(0, uniqueName.lastIndexOf("@")) if (isWebFingerIdValid(uniqueName)) { return Optional.of(uniqueName.toLowerCase()) } else { val lastButOneIndex = nameBeforeTheLastAt.lastIndexOf("@") if (lastButOneIndex > -1) { val potentialWebFingerId = uniqueName.substring(lastButOneIndex + 1) if (isWebFingerIdValid(potentialWebFingerId)) { return Optional.of(potentialWebFingerId.toLowerCase()) } } } } else { return Optional.of( uniqueName.toLowerCase() + "@" + origin.fixUriForPermalink(UriUtils.fromUrl(origin.url)).host ) } } return Optional.empty() } fun isWebFingerIdValid(webFingerId: String?): Boolean { return !webFingerId.isNullOrEmpty() && Patterns.WEBFINGER_ID_REGEX_PATTERN.matcher(webFingerId).matches() } fun toTempOid(webFingerId: String, validUserName: String?): String { return StringUtil.toTempOid(if (isWebFingerIdValid(webFingerId)) webFingerId else validUserName) } } }
apache-2.0
df6882ad9723a0cca0885f32fb9830a6
37.334669
154
0.602802
4.620531
false
false
false
false
stonexx/ideavim
src/com/maddyhome/idea/vim/ex/handler/DumpLineHandler.kt
1
2016
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2016 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.ex.handler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.ex.CommandHandler import com.maddyhome.idea.vim.ex.ExCommand import com.maddyhome.idea.vim.ex.commands class DumpLineHandler : CommandHandler(commands("dump[line]"), CommandHandler.RANGE_OPTIONAL) { override fun execute(editor: Editor, context: DataContext, cmd: ExCommand): Boolean { if (!logger.isDebugEnabled) return false val range = cmd.getLineRange(editor, context) val chars = editor.document.charsSequence for (l in range.startLine..range.endLine) { val start = editor.document.getLineStartOffset(l) val end = editor.document.getLineEndOffset(l) logger.debug("Line $l, start offset=$start, end offset=$end") for (i in start..end) { logger.debug("Offset $i, char=${chars[i]}, lp=${editor.offsetToLogicalPosition(i)}, vp=${editor.offsetToVisualPosition(i)}") } } return true } companion object { private val logger = Logger.getInstance(DumpLineHandler::class.java.name) } }
gpl-2.0
43838e113c56260b6d9a41ce334b08e6
38.529412
140
0.711806
4.280255
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/search/SearchContext.kt
2
5731
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.search import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.ProjectAndLibrariesScope import com.tang.intellij.lua.ext.ILuaTypeInfer import com.tang.intellij.lua.psi.LuaTypeGuessable import com.tang.intellij.lua.ty.ITy import com.tang.intellij.lua.ty.Ty import java.util.* /** * Created by tangzx on 2017/1/14. */ class SearchContext private constructor(val project: Project) { companion object { private val threadLocal = object : ThreadLocal<Stack<SearchContext>>() { override fun initialValue(): Stack<SearchContext> { return Stack() } } fun get(project: Project): SearchContext { val stack = threadLocal.get() return if (stack.isEmpty()) { SearchContext(project) } else { stack.peek() } } fun infer(psi: LuaTypeGuessable): ITy { return with(psi.project) { it.inferAndCache(psi) } } fun infer(psi: LuaTypeGuessable, context: SearchContext): ITy { return with(context, Ty.UNKNOWN) { it.inferAndCache(psi) } } private fun <T> with(ctx: SearchContext, defaultValue: T, action: (ctx: SearchContext) -> T): T { return if (ctx.myInStack) { action(ctx) } else { val stack = threadLocal.get() val size = stack.size stack.push(ctx) ctx.myInStack = true val result = try { action(ctx) } catch (e: Exception) { defaultValue } ctx.myInStack = false stack.pop() assert(size == stack.size) result } } private fun <T> with(project: Project, action: (ctx: SearchContext) -> T): T { val ctx = get(project) return with(ctx, action) } fun <T> withStub(project: Project, file: PsiFile, defaultValue: T, action: (ctx: SearchContext) -> T): T { val context = SearchContext(project) return withStub(context, defaultValue, action) } private fun <T> withStub(ctx: SearchContext, defaultValue: T, action: (ctx: SearchContext) -> T): T { return with(ctx, defaultValue) { val dumb = it.myDumb val stub = it.myForStub it.myDumb = true it.myForStub = true val ret = action(it) it.myDumb = dumb it.myForStub = stub ret } } fun invalidateCache(project: Project) { var searchContext = get(project) searchContext.invalidateInferCache() } } /** * 用于有多返回值的索引设定 */ val index: Int get() = myIndex private var myDumb = false private var myForStub = false private var myIndex = -1 private var myInStack = false private val myGuardList = mutableListOf<InferRecursionGuard>() private val myInferCache = mutableMapOf<LuaTypeGuessable, ITy>() private var myScope: GlobalSearchScope? = null fun <T> withIndex(index: Int, action: () -> T): T { val savedIndex = this.index myIndex = index val ret = action() myIndex = savedIndex return ret } fun guessTuple() = index < 0 val scope get(): GlobalSearchScope { if (isDumb) return GlobalSearchScope.EMPTY_SCOPE if (myScope == null) { myScope = ProjectAndLibrariesScope(project) } return myScope!! } val isDumb: Boolean get() = myDumb || DumbService.isDumb(project) val forStub get() = myForStub fun <T> withScope(scope: GlobalSearchScope, action: () -> T): T { val oriScope = myScope myScope = scope val ret = action() myScope = oriScope return ret } fun withRecursionGuard(psi: PsiElement, type: GuardType, action: () -> ITy): ITy { myGuardList.forEach { if (it.check(psi, type)) { return Ty.UNKNOWN } } val guard = createGuard(psi, type) if (guard != null) myGuardList.add(guard) val result = action() if (guard != null) myGuardList.remove(guard) return result } private fun inferAndCache(psi: LuaTypeGuessable): ITy { /*if (inferCache.containsKey(psi)) { println("use cache!!!") }*/ return myInferCache.getOrPut(psi) { ILuaTypeInfer.infer(psi, this) } } fun getTypeFromCache(psi: LuaTypeGuessable): ITy { return myInferCache.getOrElse(psi) { Ty.UNKNOWN } } fun invalidateInferCache() { myInferCache.clear() } }
apache-2.0
ca6561ae076775d0ae61f87a5408b576
29.682796
114
0.579113
4.369832
false
false
false
false
torebre/EarTrainingAndroid
app/src/main/java/com/kjipo/eartraining/eartrainer/EarTrainerImpl.kt
1
1418
package com.kjipo.eartraining.eartrainer import com.kjipo.eartraining.midi.sonivox.SonivoxMidiPlayer import com.kjipo.score.Duration import com.kjipo.scoregenerator.NoteSequenceElement import com.kjipo.scoregenerator.SequenceGenerator import com.kjipo.scoregenerator.SimpleNoteSequence import com.kjipo.scoregenerator.SimpleSequenceGenerator class EarTrainerImpl : EarTrainer { private var sequenceGeneratorInternal = SequenceGenerator() private var midiPlayer = SonivoxMidiPlayer() override var currentTargetSequence = SimpleNoteSequence(emptyList()) override fun getSequenceGenerator() = sequenceGeneratorInternal override fun getMidiInterface() = midiPlayer override fun createNewTrainingSequence() { currentTargetSequence = SimpleSequenceGenerator.createSequence() // TODO Add a clear method // sequenceGeneratorInternal.loadSimpleNoteSequence(createEmptySequence()) sequenceGeneratorInternal = SequenceGenerator() sequenceGeneratorInternal.loadSimpleNoteSequence(createEmptySequence()) } private fun createEmptySequence() = SimpleNoteSequence(listOf(NoteSequenceElement.RestElement(Duration.QUARTER), NoteSequenceElement.RestElement(Duration.QUARTER), NoteSequenceElement.RestElement(Duration.QUARTER), NoteSequenceElement.RestElement(Duration.QUARTER))) }
mit
6cba0ff3e7161a7a3dc21b60541b28f8
35.358974
88
0.772214
4.742475
false
false
false
false
TCA-Team/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/api/tumonline/interceptors/CheckTokenInterceptor.kt
1
1117
package de.tum.`in`.tumcampusapp.api.tumonline.interceptors import android.content.Context import de.tum.`in`.tumcampusapp.api.tumonline.exception.InvalidTokenException import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.Utils import okhttp3.Interceptor import okhttp3.Response class CheckTokenInterceptor(private val context: Context) : Interceptor { @Throws(InvalidTokenException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // Check for special requests val path = request.url.encodedPath val isTokenRequest = path.contains("requestToken") val isTokenConfirmationCheck = path.contains("isTokenConfirmed") // TUMonline requests are disabled if a request previously threw an InvalidTokenException val isTumOnlineDisabled = Utils.getSettingBool(context, Const.TUMO_DISABLED, false) if (!isTokenRequest && !isTokenConfirmationCheck && isTumOnlineDisabled) { throw InvalidTokenException() } return chain.proceed(request) } }
gpl-3.0
df12a2f12bfa55669b71d10ef5261651
36.266667
97
0.739481
4.654167
false
false
false
false
btnewton/tartarus
cli/src/com/brandtsoftwarecompany/Runner.kt
1
2061
package com.brandtsoftwarecompany import org.apache.commons.cli.* /** * Created by brandt on 7/23/17. */ class Runner { val header = "psm [--version] [--help] <command> [<args>]" val help = "" val version = "0.1.0" fun run(args: Array<String>) { val tools: Array<CliTool> = arrayOf( PasswordTool() ) // TODO intercept --help try { val options = Options() val versionOption = Option("v", "version", false, "get version of psm") options.addOption(versionOption) val cmd = DefaultParser().parse(options, args) if (cmd.hasOption(versionOption.opt)) { println("psm version $version") return } } catch (e: Exception) { } val tool: CliTool try { val toolName = args.firstOrNull() ?: throw NoSuchElementException("No tool provided") tool = tools.find { it.name == toolName } ?: throw NoSuchElementException("No such tool: $toolName") } catch (e: Exception) { HelpFormatter().printHelp("Password Manager", "", Options(), e.message ?: "") System.exit(1) return } val options = Options() try { tool.options.forEach { option -> options.addOption(option) } val cmd = DefaultParser().parse(options, args.tail) tool.run(cmd) } catch (e: Exception) { HelpFormatter().printHelp(tool.usage, tool.header, options, e.message ?: "") System.exit(1) return } } inline val <reified T> Array<T>.tail: Array<T> get() = when { isEmpty() -> throw NoSuchElementException("Array is empty") size == 1 -> emptyArray() else -> copyOfRange(1, size) } fun prompt(text: String): String { print(text) return readLine() ?: "" } } fun main(args: Array<String>) { Runner().run(args) }
mit
7c3e2bffd1153c5a64b38fb85792e840
24.775
112
0.522077
4.29375
false
false
false
false
btnewton/tartarus
cli/src/com/brandtsoftwarecompany/PasswordTool.kt
1
2600
package com.brandtsoftwarecompany import org.apache.commons.cli.* import java.io.File /** * Created by brandt on 7/26/17. */ class PasswordTool : CliTool { override val name = "generate" override val header = "Use generate to create secure passwords and binary files" override val usage = "psm generate [--version] [--help] [<args>] " private val binaryOption = Option("b", "binary", false, "generate a binary file instead of a password") private val fileOption: Option get() { val opt = Option("f", "file", true, "location to write binary to. Required if creating a binary file") opt.argName = "file" opt.setType(File::class.java) return opt } private val lengthOption :Option get() { val opt = Option("l", "length", true, "[REQUIRED] length of password or binary file") opt.argName = "length" opt.isRequired = true opt.setType(Number::class.java) return opt } private val symbolsOption = Option("s", "symbols", true, "symbols to use ${SymbolGroup.values().map { it.displayName }}") private val excludeOption = Option("e", "exclude", true, "characters to exclude") private val atLeastOnceOption = Option("a", "at-least-once", false, "use each symbol group at least once") override val options = arrayOf( binaryOption, fileOption, lengthOption, symbolsOption, excludeOption, atLeastOnceOption ) override fun run(cmd: CommandLine) { val usePasswordGenerator = !cmd.hasOption(binaryOption.opt) val length = (cmd.getParsedOptionValue(lengthOption.opt) as Number).toInt() if (length <= 0) throw IllegalArgumentException("length must be greater than 0") if (usePasswordGenerator) { val characterGroups = if (cmd.hasOption(symbolsOption.opt)) cmd.getOptionValues(symbolsOption.opt).map { value -> symbolGroupFactory(value) }.toTypedArray() else SymbolGroup.values() val exclusions = cmd.getOptionValue(excludeOption.opt, "") val atLeastOnce = cmd.hasOption(atLeastOnceOption.opt) val config = PasswordGenerator.Config(characterGroups, exclusions, length, atLeastOnce) val password = PasswordGenerator(config).generate() println(password) } else { fileOption.isRequired = true val location = File(cmd.getOptionValue(fileOption.opt)) createBinaryFile(location, length) } } }
mit
56021cbcf89ca82446150608f75a1aad
37.820896
194
0.635
4.49827
false
false
false
false
kryptnostic/rhizome
src/main/kotlin/com/openlattice/postgres/CitusDistributedTableDefinition.kt
1
2748
/* * Copyright (C) 2018. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.postgres import java.util.* /** * * Used to define a partitioned postgres table. */ class CitusDistributedTableDefinition( name: String ) : PostgresTableDefinition(name) { private lateinit var distributionColumn: PostgresColumnDefinition private var colocationColumn: Optional<PostgresTableDefinition> = Optional.empty() private var unlogged = false fun colocationColumn(column: PostgresTableDefinition): CitusDistributedTableDefinition { this.colocationColumn = Optional.of(column) return this } fun distributionColumn(column: PostgresColumnDefinition): CitusDistributedTableDefinition { this.distributionColumn = column return this } fun createDistributedTableQuery(): String { return if( colocationColumn.isPresent ) { val colocationSql = colocationColumn.map { "colocate_with =>'${it.name}'" }.get() "SELECT create_distributed_table('$name','${distributionColumn.name}', $colocationSql)" } else { "SELECT create_distributed_table('$name','${distributionColumn.name}')" } } override fun unlogged(): CitusDistributedTableDefinition { super.unlogged() return this } override fun addColumns(vararg columnsToAdd: PostgresColumnDefinition): CitusDistributedTableDefinition { super.addColumns(*columnsToAdd) return this } override fun addIndexes(vararg indexes: PostgresIndexDefinition): CitusDistributedTableDefinition { super.addIndexes(*indexes) return this } override fun primaryKey(vararg primaryKeyColumns: PostgresColumnDefinition): CitusDistributedTableDefinition { super.primaryKey(*primaryKeyColumns) return this } override fun setUnique(vararg uniqueColumns: PostgresColumnDefinition): CitusDistributedTableDefinition { super.setUnique(*uniqueColumns) return this } }
apache-2.0
67b3c93b7a5b4582859f1e699fe914b5
33.3625
114
0.716521
4.681431
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/domain/step_quiz/interactor/StepQuizInteractor.kt
2
5858
package org.stepik.android.domain.step_quiz.interactor import io.reactivex.Maybe import io.reactivex.Observable import io.reactivex.Single import io.reactivex.rxkotlin.Singles.zip import io.reactivex.subjects.PublishSubject import org.stepic.droid.persistence.model.StepPersistentWrapper import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.util.AppConstants import ru.nobird.android.domain.rx.maybeFirst import ru.nobird.android.domain.rx.toMaybe import org.stepik.android.domain.attempt.repository.AttemptRepository import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.filter.model.SubmissionsFilterQuery import org.stepik.android.domain.lesson.model.LessonData import org.stepik.android.domain.step_quiz.model.StepQuizRestrictions import org.stepik.android.domain.submission.repository.SubmissionRepository import org.stepik.android.model.DiscountingPolicyType import org.stepik.android.model.Reply import org.stepik.android.model.Step import org.stepik.android.model.Submission import org.stepik.android.model.attempts.Attempt import org.stepik.android.view.injection.solutions.SolutionsBus import org.stepik.android.view.injection.step.StepDiscussionBus import org.stepik.android.view.injection.step_quiz.StepQuizBus import java.util.concurrent.TimeUnit import javax.inject.Inject class StepQuizInteractor @Inject constructor( @StepQuizBus private val stepQuizPublisher: PublishSubject<Long>, @StepDiscussionBus private val stepDiscussionSubject: PublishSubject<Long>, @SolutionsBus private val solutionsPublisher: PublishSubject<Unit>, private val attemptRepository: AttemptRepository, private val submissionRepository: SubmissionRepository, private val sharedPreferenceHelper: SharedPreferenceHelper ) { fun getAttempt(stepId: Long): Single<Attempt> = attemptRepository .getAttemptsForStep(stepId, sharedPreferenceHelper.profile?.id ?: 0) .maybeFirst() .filter { it.status == "active" } .switchIfEmpty(attemptRepository.createAttemptForStep(stepId)) fun createAttempt(stepId: Long): Single<Attempt> = attemptRepository .createAttemptForStep(stepId) fun getSubmission(attemptId: Long): Maybe<Submission> = zip( submissionRepository .getSubmissionsForAttempt(attemptId, DataSourceType.REMOTE) .onErrorReturnItem(emptyList()), submissionRepository .getSubmissionsForAttempt(attemptId, DataSourceType.CACHE) ) .flatMapMaybe { (remoteSubmissions, localSubmissions) -> val remoteSubmission = remoteSubmissions .firstOrNull() val localSubmission = localSubmissions .firstOrNull() if (remoteSubmission != null && localSubmission != null) { if (remoteSubmission.id >= localSubmission.id) { remoteSubmission } else { localSubmission } } else { remoteSubmission ?: localSubmission }.toMaybe() } fun createSubmission(stepId: Long, attemptId: Long, reply: Reply): Single<Submission> = submissionRepository .createSubmission(Submission(attempt = attemptId, _reply = reply)) .flatMapObservable { Observable .interval(1, TimeUnit.SECONDS) .flatMapMaybe { submissionRepository.getSubmissionsForAttempt(attemptId).maybeFirst() } .skipWhile { it.status == Submission.Status.EVALUATION } } .firstOrError() .doOnSuccess { newSubmission -> if (newSubmission.status == Submission.Status.CORRECT) { stepQuizPublisher.onNext(stepId) } stepDiscussionSubject.onNext(stepId) solutionsPublisher.onNext(Unit) sharedPreferenceHelper.incrementSubmissionsCount() } fun createLocalSubmission(submission: Submission): Single<Submission> = submissionRepository .createSubmission(submission, dataSourceType = DataSourceType.CACHE) .doOnSuccess { solutionsPublisher.onNext(Unit) } fun getStepRestrictions(stepPersistentWrapper: StepPersistentWrapper, lessonData: LessonData): Single<StepQuizRestrictions> = getStepSubmissionCount(stepPersistentWrapper.step.id) .map { submissionCount -> StepQuizRestrictions( submissionCount = submissionCount, maxSubmissionCount = stepPersistentWrapper .step .maxSubmissionCount .takeIf { stepPersistentWrapper.step.hasSubmissionRestriction } ?: -1, discountingPolicyType = lessonData.section?.discountingPolicy ?: DiscountingPolicyType.NoDiscount ) } private fun getStepSubmissionCount(stepId: Long): Single<Int> = submissionRepository .getSubmissionsForStep(stepId, SubmissionsFilterQuery()) .map { it.size } .onErrorReturnItem(0) fun isNeedRecreateAttemptForNewSubmission(step: Step): Boolean = when (step.block?.name) { AppConstants.TYPE_STRING, AppConstants.TYPE_NUMBER, AppConstants.TYPE_MATH, AppConstants.TYPE_FREE_ANSWER, AppConstants.TYPE_CODE, AppConstants.TYPE_SORTING, AppConstants.TYPE_MATCHING, AppConstants.TYPE_FILL_BLANKS -> false else -> true } }
apache-2.0
9ae573e6cc39b154ffaa952d2809af08
40.260563
129
0.661659
5.29178
false
false
false
false
savvasdalkitsis/gameframe
widget/src/main/java/com/savvasdalkitsis/gameframe/feature/widget/view/ClickableWidgetProvider.kt
1
2766
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.widget.view import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.content.ComponentName import android.content.Context import android.content.Intent import android.support.annotation.LayoutRes import android.widget.RemoteViews import com.savvasdalkitsis.gameframe.feature.analytics.injector.AnalyticsInjector import com.savvasdalkitsis.gameframe.feature.widget.R import com.savvasdalkitsis.gameframe.feature.injector.WidgetInjector import com.savvasdalkitsis.gameframe.feature.message.injector.MessageDisplayInjector abstract class ClickableWidgetProvider : AppWidgetProvider(), WidgetView { private val messageDisplay = MessageDisplayInjector.toastMessageDisplay() protected val presenter = WidgetInjector.widgetPresenter() protected val analytics = AnalyticsInjector.analytics() override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val remoteViews = RemoteViews(context.packageName, layoutResId()) val watchWidget = ComponentName(context, javaClass) remoteViews.setOnClickPendingIntent(R.id.view_widget_action, getPendingSelfIntent(context, CLICKED)) appWidgetManager.updateAppWidget(watchWidget, remoteViews) analytics.logEvent("widget_event", "event" to "update") } override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) presenter.bindView(this) if (CLICKED == intent.action) { onClick() } } @LayoutRes protected abstract fun layoutResId(): Int protected abstract fun onClick() private fun getPendingSelfIntent(context: Context, intentAction: String) = PendingIntent.getBroadcast(context, 0, Intent(context, javaClass).apply { action = intentAction }, 0) override fun operationError() { messageDisplay.show(R.string.error_communicating) } companion object { private const val CLICKED = "click" } }
apache-2.0
0301830b5e3da17d5a164ea57b147988
37.416667
108
0.754158
4.869718
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/SimplifyCallChainFix.kt
2
5564
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections.collections import com.intellij.codeInsight.actions.OptimizeImportsProcessor import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.moveFunctionLiteralOutsideParentheses import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.intentions.callExpression import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange import org.jetbrains.kotlin.utils.addToStdlib.safeAs class SimplifyCallChainFix( private val conversion: AbstractCallChainChecker.Conversion, private val removeReceiverOfFirstCall: Boolean = false, private val runOptimizeImports: Boolean = false, private val modifyArguments: KtPsiFactory.(KtCallExpression) -> Unit = {} ) : LocalQuickFix { private val shortenedText = conversion.replacement.substringAfterLast(".") override fun getName() = KotlinBundle.message("simplify.call.chain.fix.text", shortenedText) override fun getFamilyName() = name fun apply(qualifiedExpression: KtQualifiedExpression) { val factory = KtPsiFactory(qualifiedExpression) val firstExpression = qualifiedExpression.receiverExpression val operationSign = if (removeReceiverOfFirstCall) "" else when (firstExpression) { is KtSafeQualifiedExpression -> "?." is KtQualifiedExpression -> "." else -> "" } val receiverExpressionOrEmptyString = if (!removeReceiverOfFirstCall && firstExpression is KtQualifiedExpression) firstExpression.receiverExpression.text else "" val firstCallExpression = AbstractCallChainChecker.getCallExpression(firstExpression) ?: return factory.modifyArguments(firstCallExpression) val firstCallArgumentList = firstCallExpression.valueArgumentList val secondCallExpression = qualifiedExpression.selectorExpression as? KtCallExpression ?: return val secondCallArgumentList = secondCallExpression.valueArgumentList val secondCallTrailingComma = secondCallArgumentList?.trailingComma secondCallTrailingComma?.delete() fun KtValueArgumentList.getTextInsideParentheses(): String { val range = PsiChildRange(leftParenthesis?.nextSibling ?: firstChild, rightParenthesis?.prevSibling ?: lastChild) return range.joinToString(separator = "") { it.text } } val lambdaExpression = firstCallExpression.lambdaArguments.singleOrNull()?.getLambdaExpression() val additionalArgument = conversion.additionalArgument val secondCallHasArguments = secondCallArgumentList?.arguments?.isNotEmpty() == true val firstCallHasArguments = firstCallArgumentList?.arguments?.isNotEmpty() == true val argumentsText = listOfNotNull( secondCallArgumentList.takeIf { secondCallHasArguments }?.getTextInsideParentheses(), firstCallArgumentList.takeIf { firstCallHasArguments }?.getTextInsideParentheses(), additionalArgument.takeIf { !firstCallHasArguments && !secondCallHasArguments }, lambdaExpression?.text ).joinToString(separator = ",") val newCallText = conversion.replacement val newQualifiedOrCallExpression = factory.createExpression( "$receiverExpressionOrEmptyString$operationSign$newCallText($argumentsText)" ) val project = qualifiedExpression.project val file = qualifiedExpression.containingKtFile var result = qualifiedExpression.replaced(newQualifiedOrCallExpression) if (lambdaExpression != null || additionalArgument != null) { val callExpression = when (result) { is KtQualifiedExpression -> result.callExpression is KtCallExpression -> result else -> null } callExpression?.moveFunctionLiteralOutsideParentheses() } if (secondCallTrailingComma != null && !firstCallHasArguments) { val call = result.safeAs<KtQualifiedExpression>()?.callExpression ?: result.safeAs<KtCallExpression>() call?.valueArgumentList?.arguments?.lastOrNull()?.add(factory.createComma()) } if (conversion.addNotNullAssertion) { result = result.replaced(factory.createExpressionByPattern("$0!!", result)) } if (conversion.removeNotNullAssertion) { val parent = result.parent if (parent is KtPostfixExpression && parent.operationToken == KtTokens.EXCLEXCL) { result = parent.replaced(result) } } result.containingKtFile.commitAndUnblockDocument() if (result.isValid) ShortenReferences.DEFAULT.process(result.reformatted() as KtElement) if (runOptimizeImports) { OptimizeImportsProcessor(project, file).run() } } override fun applyFix(project: Project, descriptor: ProblemDescriptor) { (descriptor.psiElement as? KtQualifiedExpression)?.let(this::apply) } }
apache-2.0
2330d27f1a95ce9e20fbca84da9b0501
48.6875
158
0.729152
5.742002
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/data/entities/UserWarnPoints.kt
1
2144
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.data.entities import org.springframework.util.Assert import java.time.OffsetDateTime import java.util.* import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table import javax.validation.constraints.Future import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull import javax.validation.constraints.Positive @Entity @Table(name = "user_warn_points") data class UserWarnPoints( @Id @Column(updatable = false, columnDefinition = "BINARY(16)") val id: UUID = UUID.randomUUID(), @field:Positive @Column(nullable = false, updatable = false) val points: Int, @field:NotNull @Column(nullable = false, updatable = false) val creatorId: Long, @field:NotBlank @Column(nullable = false, updatable = false, columnDefinition = "TEXT") val reason: String, @field:NotNull @Column(nullable = false, updatable = false) val creationDate: OffsetDateTime = OffsetDateTime.now(), @field:Future @field:NotNull @Column(nullable = false, updatable = false) val expireDate: OffsetDateTime ) { init { if (points <= 0) { throw IllegalArgumentException("Points need to be a positive number") } if (expireDate.isBefore(creationDate)) { throw IllegalArgumentException("UserWarnPoints can't expire before the date it was created.") } Assert.hasLength(reason, "The reason can not be empty.") } }
apache-2.0
44b4b1a25e2243886fcbd03e75c62a8b
33.031746
105
0.720149
4.262425
false
false
false
false
hpost/kommon
app/src/main/java/cc/femto/kommon/ui/Scrims.kt
1
3128
package cc.femto.kommon.ui import android.graphics.Color import android.graphics.LinearGradient import android.graphics.Shader import android.graphics.drawable.Drawable import android.graphics.drawable.PaintDrawable import android.graphics.drawable.ShapeDrawable import android.graphics.drawable.shapes.RectShape import android.view.Gravity /** * Utility for creating pretty gradient scrims. */ object Scrims { /** 40% opacity black to transparent */ val TOOLBAR_SCRIM = makeCubicGradientScrimDrawable( Color.argb(102, 0, 0, 0), 9, Gravity.TOP) /** transparent to 50% opacity black */ val PHOTO_SCRIM = makeCubicGradientScrimDrawable( Color.argb(128, 0, 0, 0), 9, Gravity.BOTTOM) /** 80% opacity white to transparent */ val PHOTO_SCRIM_INVERSE = makeCubicGradientScrimDrawable( Color.argb(204, 255, 255, 255), 9, Gravity.TOP) /** * Creates an approximated cubic gradient using a multi-stop linear gradient. * See [this post](https://plus.google.com/+RomanNurik/posts/2QvHVFWrHZf) for more details. */ fun makeCubicGradientScrimDrawable(baseColor: Int, numStops: Int, gravity: Int): Drawable { var numStops = numStops numStops = Math.max(numStops, 2) val paintDrawable = PaintDrawable() paintDrawable.shape = RectShape() val stopColors = IntArray(numStops) val red = Color.red(baseColor) val green = Color.green(baseColor) val blue = Color.blue(baseColor) val alpha = Color.alpha(baseColor) for (i in 0 until numStops) { val x = i * 1f / (numStops - 1) val opacity = Math.pow(x.toDouble(), 3.0) stopColors[i] = Color.argb((alpha * opacity).toInt(), red, green, blue) } val x0: Float val x1: Float val y0: Float val y1: Float when (gravity and Gravity.HORIZONTAL_GRAVITY_MASK) { Gravity.LEFT -> { x0 = 1f x1 = 0f } Gravity.RIGHT -> { x0 = 0f x1 = 1f } else -> { x0 = 0f x1 = 0f } } when (gravity and Gravity.VERTICAL_GRAVITY_MASK) { Gravity.TOP -> { y0 = 1f y1 = 0f } Gravity.BOTTOM -> { y0 = 0f y1 = 1f } else -> { y0 = 0f y1 = 0f } } paintDrawable.shaderFactory = object : ShapeDrawable.ShaderFactory() { override fun resize(width: Int, height: Int): Shader { val linearGradient = LinearGradient( width * x0, height * y0, width * x1, height * y1, stopColors, null, Shader.TileMode.CLAMP) return linearGradient } } return paintDrawable } }
apache-2.0
02abea14f2b9f3ac43097a5e52b20c3d
29.666667
95
0.530371
4.374825
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/people/WPEditTextWithChipsOutlined.kt
1
26063
package org.wordpress.android.ui.people import android.animation.Animator import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.os.Parcel import android.os.Parcelable import android.os.Parcelable.Creator import android.text.Editable import android.text.TextUtils.TruncateAt import android.text.TextWatcher import android.util.AttributeSet import android.util.TypedValue import android.view.KeyEvent import android.view.View import android.view.inputmethod.EditorInfo import android.widget.TextView.OnEditorActionListener import androidx.annotation.AttrRes import androidx.annotation.ColorInt import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.ColorUtils import com.google.android.flexbox.FlexboxLayout import com.google.android.material.chip.Chip import com.google.android.material.shape.CornerFamily import com.google.android.material.shape.MaterialShapeDrawable import com.google.android.material.shape.ShapeAppearanceModel import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textview.MaterialTextView import org.wordpress.android.R import org.wordpress.android.databinding.WpEditTextWithChipsOutlinedBinding import org.wordpress.android.util.RtlUtils import org.wordpress.android.util.extensions.getColorResIdFromAttribute import java.util.LinkedHashMap /** * As of our understanding, currently the TextInputLayout (that is a LinearLayout) works in OutlinedBox mode having * a single TextInputEditText as a direct child, inflating needed views into an internal not accessible FrameLayout; * so not easily possible to add additional views over the main TextInputLayout keeping the usual * behaviours of the TextInputEditText. * * This component was mainly created to address the move of PeopleInviteFragment into material design. * Specifically tries to cover the usage of chips in combination with an EditText while mimic an * OutlinedBox with TextInputLayout material design behaviour. * * The implementation is pretty basic and do not cover all possible use cases. We should leave this component usage * once we find a more out of the box solution with material design lib (keep an eye on future releases) that * covers our use cases. * * Supports hint/label animation (with RTL support). * * Based and inspired by https://stackoverflow.com/a/61748466 * * Note: other possible implementation is using ImageSpan in the EditText but we found cursor/keyboard management * to be more complex and less clean and preferred to use the FlexBox approach for now. */ class WPEditTextWithChipsOutlined @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private enum class HelperTextState { HINT_VISIBLE, LABEL_VISIBLE } private var helperTextState: HelperTextState = HelperTextState.HINT_VISIBLE private var flexBox: FlexboxLayout private var editor: TextInputEditText private var label: MaterialTextView private var hint: MaterialTextView private lateinit var outlineDrawable: MaterialShapeDrawable private var outlineColorDefault: Int = 0 private var outlineColorFocused: Int = 0 private var colorSurface: Int = 0 private var outlineColorAlphaFocused: Float = 0f private var outlineColorAlphaDefault: Float = 0f private var hintLabelColorAlphaDefault: Float = 0f private var outlinePixelWidthDefault: Int = 0 private var outlinePixelWidthFocused: Int = 0 private var hintResourceId = 0 private var chipifyEnabled = false private var maxChips = 0 private var isRightToLeft = false private var itemsManager: ItemsManagerInterface? = null fun setItemsManager(itemsManager: ItemsManagerInterface?) { this.itemsManager = itemsManager } interface ItemsManagerInterface { fun onRemoveItem(item: String) fun onAddItem(item: String) } enum class ItemValidationState(@AttrRes val colorAttr: Int) { NEUTRAL(R.attr.colorOnSurface), VALIDATED(R.attr.colorPrimary), VALIDATED_WITH_ERRORS(R.attr.wpColorError); @ColorInt fun colorFromState(context: Context): Int { val color = context.getColorResIdFromAttribute(this.colorAttr) return ContextCompat.getColor(context, color) } companion object { fun stateFromColor(context: Context, color: Int): ItemValidationState { return values().first { value -> ContextCompat.getColor(context, context.getColorResIdFromAttribute(value.colorAttr)) == color } } } } init { attrs?.also { val stylesAttributes = context.theme.obtainStyledAttributes( attrs, R.styleable.WPEditTextWithChipsOutlined, 0, 0 ) try { hintResourceId = stylesAttributes.getResourceId( R.styleable.WPEditTextWithChipsOutlined_wpHint, 0 ) chipifyEnabled = stylesAttributes.getBoolean( R.styleable.WPEditTextWithChipsOutlined_wpChipifyEnabled, false ) maxChips = stylesAttributes.getInteger( R.styleable.WPEditTextWithChipsOutlined_wpMaxNumberChips, 0 ) } finally { stylesAttributes.recycle() } } inflate(getContext(), R.layout.wp_edit_text_with_chips_outlined, this) flexBox = findViewById(R.id.flexbox) editor = findViewById(R.id.flexbox_editor) label = findViewById(R.id.flexbox_label) hint = findViewById(R.id.flexbox_hint) isRightToLeft = RtlUtils.isRtl(context) if (hasHint()) { label.setText(hintResourceId) hint.setText(hintResourceId) } isSaveEnabled = true loadOutlineDrawable() loadDimensions() loadColors() styleView(isEditorFocused(), hasItemsOrText(), false) setListeners() } fun getTextIfAvailableOrNull(): String? { throwExceptionIfChipifyNotEnabled() if (!hasText() || !canAddMoreChips()) { resetText() return null } return removeDelimiterFromItemIfPresent(editor.text.toString()) } fun addOrUpdateChip(item: String, state: ItemValidationState) { throwExceptionIfChipifyNotEnabled() chipify(item, state) } fun removeChip(item: String) { throwExceptionIfChipifyNotEnabled() val chips = getChipsMap() chips[item]?.let { withBinding { flexbox.removeView(it) if (flexbox.childCount == 1) { styleView(isEditorFocused(), hasItemsOrText(), true) } } } } fun getChipsStrings(): MutableSet<String> { throwExceptionIfChipifyNotEnabled() return getChipsMap().keys } fun hasChips(): Boolean { throwExceptionIfChipifyNotEnabled() return getChipsMap().isNotEmpty() } fun containsChip(item: String): Boolean { throwExceptionIfChipifyNotEnabled() return getChipsMap().containsKey(item) } private fun <T> withBinding(block: WpEditTextWithChipsOutlinedBinding.() -> T): T { return with(WpEditTextWithChipsOutlinedBinding.bind(this)) { block() } } private fun loadOutlineDrawable() { val shapeAppearanceModel = ShapeAppearanceModel.builder() .setAllCorners( CornerFamily.ROUNDED, resources.getDimension(R.dimen.edit_with_chips_outline_radius) ) .build() outlineDrawable = MaterialShapeDrawable(shapeAppearanceModel) } private fun loadDimensions() { outlinePixelWidthDefault = resources.getDimensionPixelSize(R.dimen.edit_with_chips_outline_default_width) outlinePixelWidthFocused = resources.getDimensionPixelSize(R.dimen.edit_with_chips_outline_focused_width) } private fun loadColors() { outlineColorDefault = ContextCompat.getColor(context, TypedValue().let { getContext().theme.resolveAttribute(R.attr.colorOnSurface, it, true) it.resourceId }) outlineColorFocused = ContextCompat.getColor(context, TypedValue().let { getContext().theme.resolveAttribute(R.attr.colorPrimary, it, true) it.resourceId }) colorSurface = ContextCompat.getColor(context, TypedValue().let { getContext().theme.resolveAttribute(R.attr.colorSurface, it, true) it.resourceId }) outlineColorAlphaDefault = ResourcesCompat.getFloat( resources, R.dimen.edit_with_chips_outline_default_alpha ) outlineColorAlphaFocused = ResourcesCompat.getFloat( resources, R.dimen.edit_with_chips_outline_focused_alpha ) hintLabelColorAlphaDefault = ResourcesCompat.getFloat( resources, R.dimen.edit_with_chips_hint_label_default_alpha ) } private fun setListeners() { editor.setOnFocusChangeListener { _, hasFocus -> val canAnimate = hint.width > 0 && label.width > 0 && hint.height > 0 && label.height > 0 if (canAnimate) { styleView(hasFocus, hasItemsOrText(), true) } if (chipifyEnabled && !hasFocus && hasText()) { addItem(editor.text.toString()) } } if (chipifyEnabled) { editor.addTextChangedListener(object : TextWatcher { private var mShouldIgnoreChanges = false override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (mShouldIgnoreChanges) { // used to avoid double call after calling setText from this method return } mShouldIgnoreChanges = true if (s.isNotBlank() && endsWithDelimiter(s.toString())) { addItem(s.toString()) } mShouldIgnoreChanges = false } override fun afterTextChanged(s: Editable) {} }) editor.setOnEditorActionListener(OnEditorActionListener { _, actionId, event -> if (actionId == EditorInfo.IME_ACTION_DONE || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER) { val editable = editor.text editable?.let { val item = it.toString() if (item.isNotBlank()) { addItem(item) } } return@OnEditorActionListener true } else { return@OnEditorActionListener false } }) // handle key preses from hardware keyboard editor.setOnKeyListener { _, _, keyEvent -> keyEvent.keyCode == KeyEvent.KEYCODE_DEL && keyEvent.action == KeyEvent.ACTION_DOWN && removeLastEnteredItem() } } } private fun canAddMoreChips(): Boolean { return withBinding { flexbox.childCount < maxChips + 1 || maxChips == 0 } } private fun addItem(item: String) { if (!canAddMoreChips() && item.isNotBlank()) { resetText() } else { val cleanedItem = removeDelimiterFromItemIfPresent(item) if (cleanedItem.isNullOrBlank()) return resetText() itemsManager?.onAddItem(cleanedItem) ?: chipify(cleanedItem, ItemValidationState.NEUTRAL) } } private data class ChipReplaceData(val index: Int, val chip: Chip, val isAlreadyInGroup: Boolean) private fun chipify(item: String, state: ItemValidationState) { if (!chipifyEnabled) return val chipsMap = getChipsMap() val (index, chip, isAlreadyInGroup) = if (chipsMap.containsKey(item)) { ChipReplaceData(flexBox.indexOfChild(chipsMap[item]), chipsMap[item]!!, true) } else { ChipReplaceData(flexBox.childCount - 1, Chip(context), false) } chip.layoutDirection = View.LAYOUT_DIRECTION_LOCALE chip.setEnsureMinTouchTargetSize(true) chip.ensureAccessibleTouchTarget(resources.getDimensionPixelSize(R.dimen.people_chips_min_target)) chip.text = item chip.setTextColor(state.colorFromState(context)) chip.isCloseIconVisible = true chip.isClickable = false chip.isCheckable = false chip.ellipsize = TruncateAt.MIDDLE chip.closeIconContentDescription = resources.getString( R.string.invite_user_delete_desc, item ) if (!isAlreadyInGroup) { chip.setOnCloseIconClickListener { chipView -> val itemName = chip.text.toString() withBinding { flexbox.removeView(chipView) itemsManager?.onRemoveItem(itemName) if (flexbox.childCount == 1) { styleView(isEditorFocused(), hasItemsOrText(), true) } } } flexBox.addView(chip as View, index) } resetText() } private fun resetText() { editor.apply { text?.clear() ?: setText("") } } private fun removeDelimiterFromItemIfPresent(item: String?): String? { if (item.isNullOrBlank()) { return null } val trimmedItem = item.trim() for (itemDelimiter in ITEM_DELIMITERS) { if (trimmedItem.endsWith(itemDelimiter)) { return trimmedItem.substring(0, trimmedItem.length - itemDelimiter.length) } } return trimmedItem } private fun throwExceptionIfChipifyNotEnabled() { require(chipifyEnabled) { "Please set chipifyEnabled to true in order to use chips feature" } } // This should be fast enough for our use case, so we get fresh data always private fun getChipsMap(): MutableMap<String, Chip> { val chips: MutableMap<String, Chip> = LinkedHashMap() withBinding { for (i in 0 until flexbox.childCount) { val v: View = flexbox.getChildAt(i) if (v is Chip) { chips[v.text.toString()] = v } } } return chips } private fun removeLastEnteredItem(): Boolean { if (hasText()) { return false } return withBinding { // try and remove the last entered username if (flexbox.childCount > 1) { val chipToRemove = flexBox.getChildAt(flexbox.childCount - 2) as Chip val itemName = chipToRemove.text.toString() flexBox.removeViewAt(flexbox.childCount - 2) itemsManager?.onRemoveItem(itemName) true } else { false } } } private fun endsWithDelimiter(string: String): Boolean { if (string.isBlank()) { return false } for (usernameDelimiter in ITEM_DELIMITERS) { if (string.endsWith(usernameDelimiter)) { return true } } return false } private fun styleView(hasFocus: Boolean, hasText: Boolean, animateOnChange: Boolean) { flexBox.background = outlineDrawable setLabelColor(hint, outlineColorDefault, hintLabelColorAlphaDefault) if (hasFocus) { setOutlineStroke( outlinePixelWidthFocused, outlineColorFocused, outlineColorAlphaFocused ) } else { setOutlineStroke( outlinePixelWidthDefault, outlineColorDefault, outlineColorAlphaDefault ) } if (!hasHint()) { hint.visibility = View.INVISIBLE label.visibility = View.INVISIBLE return } val previousLabelState = helperTextState if (hasFocus || hasText) { helperTextState = HelperTextState.LABEL_VISIBLE if (animateOnChange && previousLabelState != helperTextState) { animateViewTo(HelperTextState.LABEL_VISIBLE) } else { if (hasFocus) { setLabelColor(label, outlineColorFocused, outlineColorAlphaFocused) hint.visibility = View.INVISIBLE label.visibility = View.VISIBLE } else { setLabelColor(label, outlineColorDefault, hintLabelColorAlphaDefault) hint.visibility = View.INVISIBLE label.visibility = View.VISIBLE } } } else { helperTextState = HelperTextState.HINT_VISIBLE if (animateOnChange && previousLabelState != helperTextState) { animateViewTo(HelperTextState.HINT_VISIBLE) } else { setLabelColor(label, colorSurface, outlineColorAlphaFocused) hint.visibility = View.VISIBLE label.visibility = View.INVISIBLE } } } private fun animateViewTo(targetState: HelperTextState) { if (isRightToLeft) { hint.pivotX = hint.width.toFloat() hint.pivotY = 0f } else { hint.pivotX = 0f hint.pivotY = 0f } when (targetState) { HelperTextState.HINT_VISIBLE -> { hint.animate().cancel() if (hint.translationY == 0f) { hint.translationY = label.y - hint.y hint.scaleX = label.width.toFloat() / hint.width hint.scaleX = label.height.toFloat() / hint.height } hint.animate() .translationY(0f) .scaleX(1f) .scaleY(1f) .setDuration(LABEL_ANIMATION_DURATION) .setListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator?) { label.visibility = View.INVISIBLE hint.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator?) { } override fun onAnimationCancel(animation: Animator?) { } override fun onAnimationRepeat(animation: Animator?) { } }).start() } HelperTextState.LABEL_VISIBLE -> { hint.animate().cancel() if (hint.translationY != 0f) { hint.translationY = 0f hint.scaleX = 1f hint.scaleX = 1f } hint.animate() .translationY(label.y - hint.y) .scaleX(label.width.toFloat() / hint.width) .scaleY(label.height.toFloat() / hint.height) .setDuration(LABEL_ANIMATION_DURATION) .setListener(object : Animator.AnimatorListener { override fun onAnimationStart(animation: Animator?) { setLabelColor(label, colorSurface, outlineColorAlphaFocused) label.visibility = View.VISIBLE hint.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator?) { hint.visibility = View.INVISIBLE setLabelColor(label, outlineColorFocused, outlineColorAlphaFocused) } override fun onAnimationCancel(animation: Animator?) { } override fun onAnimationRepeat(animation: Animator?) { } }).start() } } } private fun setOutlineStroke(width: Int, color: Int, alpha: Float) { outlineDrawable.apply { this.setStroke(width.toFloat(), color) this.alpha = (alpha * 255).coerceAtMost(255f).toInt() this.fillColor = ColorStateList.valueOf(Color.TRANSPARENT) } } private fun setLabelColor(textView: MaterialTextView, color: Int, alpha: Float) { val colorWithAlpha = ColorUtils.setAlphaComponent(color, (alpha * 255).coerceAtMost(255f).toInt()) textView.setTextColor(colorWithAlpha) } private fun hasItemsOrText() = hasItems() || hasText() private fun hasItems() = withBinding { flexbox.childCount > 1 } private fun hasText() = (editor.text?.length ?: 0) > 0 private fun isEditorFocused() = editor.isFocused private fun hasHint() = hintResourceId != 0 override fun onSaveInstanceState(): Parcelable { val savedState = SavedState(super.onSaveInstanceState()) savedState.isFocused = isEditorFocused() savedState.labelState = helperTextState savedState.hasText = hasItemsOrText() savedState.chipsData.clear() savedState.chipsData.addAll( getChipsMap().map { (_, v) -> ChipData(v.text.toString(), v.currentTextColor) } ) return savedState } override fun onRestoreInstanceState(state: Parcelable?) { if (state !is SavedState) { super.onRestoreInstanceState(state) return } val savedState: SavedState = state super.onRestoreInstanceState(savedState.superState) helperTextState = savedState.labelState val chipsData = savedState.chipsData for (chip: ChipData in chipsData) { chipify(chip.text, ItemValidationState.stateFromColor(context, chip.color)) } styleView(savedState.isFocused, savedState.hasText, false) } private data class ChipData(val text: String, val color: Int) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString()!!, parcel.readInt() ) override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(text) parcel.writeInt(color) } override fun describeContents(): Int { return 0 } companion object CREATOR : Creator<ChipData> { override fun createFromParcel(parcel: Parcel): ChipData { return ChipData(parcel) } override fun newArray(size: Int): Array<ChipData?> { return arrayOfNulls(size) } } } private class SavedState : BaseSavedState { var labelState = HelperTextState.HINT_VISIBLE var isFocused = false var hasText = false var chipsData = mutableListOf<ChipData>() constructor(superState: Parcelable?) : super(superState) {} @Suppress("unused") private constructor(`in`: Parcel) : super(`in`) { this.labelState = HelperTextState.values()[`in`.readInt()] this.isFocused = `in`.readInt() == 1 this.hasText = `in`.readInt() == 1 val arrayLen = `in`.readInt() if (arrayLen > 0) { val chipsDataArray = arrayOfNulls<ChipData>(arrayLen) `in`.readTypedArray(chipsDataArray, ChipData.CREATOR) this.chipsData = chipsDataArray.filterNotNull().toMutableList() } } override fun writeToParcel(out: Parcel, flags: Int) { super.writeToParcel(out, flags) out.writeInt(labelState.ordinal) out.writeInt(if (this.isFocused) 1 else 0) out.writeInt(if (this.hasText) 1 else 0) if (chipsData.size == 0) { out.writeInt(0) } else { out.writeInt(chipsData.size) out.writeTypedArray(chipsData.toTypedArray(), flags) } } companion object { @JvmField val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> { override fun createFromParcel(`in`: Parcel): SavedState { return SavedState(`in`) } override fun newArray(size: Int): Array<SavedState?> { return arrayOfNulls(size) } } } } companion object { // this duration should be the material design default for the animation private const val LABEL_ANIMATION_DURATION = 167L private val ITEM_DELIMITERS = arrayOf(" ", ",") } }
gpl-2.0
67ea769baad82aba8cdf2f33368ad780
34.508174
116
0.58397
5.232483
false
false
false
false
Yubico/yubioath-android
app/src/main/kotlin/com/yubico/yubioath/ui/add/AddCredentialFragment.kt
1
7344
/* * Copyright (c) 2013, Yubico AB. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package com.yubico.yubioath.ui.add import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.TextView import com.yubico.yubikitold.application.Version import com.yubico.yubikitold.application.oath.HashAlgorithm import com.yubico.yubikitold.application.oath.OathType import com.yubico.yubioath.R import com.yubico.yubioath.client.CredentialData import kotlinx.android.synthetic.main.fragment_add_credential.* import org.apache.commons.codec.binary.Base32 import org.jetbrains.anko.inputMethodManager class AddCredentialFragment : Fragment() { private val viewModel: AddCredentialViewModel by lazy { ViewModelProviders.of(activity!!).get(AddCredentialViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_add_credential, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) credential_type.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) = Unit override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { credential_period.isEnabled = id == 0L } } credential_period.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> if (!hasFocus && credential_period.text.isEmpty()) { credential_period.setText(R.string.period_30, TextView.BufferType.NORMAL) } } credential_period.setSelectAllOnFocus(true) viewModel.data?.apply { issuer?.let { credential_issuer.setText(it) } credential_account.setText(name) credential_secret.setText(encodedSecret) credential_type.setSelection(when (oathType) { OathType.TOTP -> 0 OathType.HOTP -> 1 }) credential_period.setText(period.toString()) credential_digits.setSelection(digits - 6) credential_algo.setSelection(when (algorithm) { HashAlgorithm.SHA1 -> 0 HashAlgorithm.SHA256 -> 1 HashAlgorithm.SHA512 -> 2 }) } if (credential_issuer.text.isNullOrEmpty()) { activity?.apply { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY) } } } var isEnabled: Boolean = true set(value) { if (field != value) { listOf(credential_issuer, credential_account, credential_secret, credential_type, credential_period, credential_digits, credential_algo, credential_touch).forEach { it.isEnabled = value } field = value } } fun validateData(): CredentialData? { activity?.apply { inputMethodManager.hideSoftInputFromWindow(currentFocus?.applicationWindowToken, 0) } credential_account_wrapper.error = null credential_touch_wrapper.error = null credential_algo_wrapper.error = null var valid = true val encodedSecret = credential_secret.text.toString().replace(" ", "").toUpperCase() val decoder = Base32() val secret = if (encodedSecret.isNotEmpty() && decoder.isInAlphabet(encodedSecret)) { credential_secret_wrapper.error = null decoder.decode(encodedSecret) } else { credential_secret_wrapper.error = getString(R.string.add_credential_secret_invalid) valid = false byteArrayOf() } val issuer = credential_issuer.text.toString().let { if (it.isEmpty()) null else it } val name = credential_account.text.toString() if (name.isEmpty()) { credential_account_wrapper.error = getString(R.string.add_credential_account_empty) valid = false } else { credential_account_wrapper.error = null } val type = when (credential_type.selectedItemId) { 0L -> OathType.TOTP 1L -> OathType.HOTP else -> throw IllegalArgumentException("Invalid OATH type!") } val algo = when (credential_algo.selectedItemId) { 0L -> HashAlgorithm.SHA1 1L -> HashAlgorithm.SHA256 2L -> HashAlgorithm.SHA512 else -> throw IllegalArgumentException("Invalid hash algorithm!") } val digits = (6 + credential_digits.selectedItemId).toInt() val period = credential_period.text.toString().toInt() val touch = credential_touch.isChecked return if (valid) { CredentialData(secret, issuer, name, type, algo, digits, period, touch = touch) } else null } fun validateVersion(data: CredentialData, version: Version) { // These TextInputLayouts don't contain EditTexts, and need two leading spaces for alignment. if (data.touch && version.isLessThan(4, 0, 0)) { credential_touch_wrapper.error = " " + getString(R.string.add_credential_touch_version) } if (data.algorithm == HashAlgorithm.SHA512 && version.isLessThan(4, 3, 1)) { credential_algo_wrapper.error = " " + getString(R.string.add_credential_algo_512) } } fun markDuplicateName() { credential_account_wrapper.error = "Credential with this issuer and name already exists!" } }
bsd-2-clause
8ed07cad6e1d52555070584cf5a6462c
41.206897
137
0.662037
4.72283
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/nullableBooleanElvis/inIfWithBinaryExpression.kt
4
258
fun foo() { var a: Int? = null var b: Boolean? = null fun isOddNumber(n: Int?): Boolean? { if (n == null) return null if (n < 0) return null return n % 2 == 1 } if ((isOddNumber(a) ?: b) <caret>?: false) { } }
apache-2.0
92f66240d81d7942a21ee99a6732269d
20.583333
48
0.472868
3.225
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/KeywordCompletion.kt
1
31785
// 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.completion import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.* import com.intellij.psi.filters.* import com.intellij.psi.filters.position.LeftNeighbour import com.intellij.psi.filters.position.PositionElementFilter import com.intellij.psi.tree.IElementType import com.intellij.psi.util.parentOfType import com.intellij.psi.util.parentOfTypes import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.config.LanguageVersionSettingsImpl import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget.* import org.jetbrains.kotlin.idea.completion.handlers.WithTailInsertHandler import org.jetbrains.kotlin.idea.completion.handlers.createKeywordConstructLookupElement import org.jetbrains.kotlin.lexer.KtKeywordToken import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.* import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull /** * We want all [KeywordLookupObject]s to be equal to each other. * * That way, if the same keyword is completed twice, it would not be duplicated in the completion. This is not required in the regular * completion, but can be a problem in CodeWithMe plugin (see https://youtrack.jetbrains.com/issue/CWM-438). */ open class KeywordLookupObject { override fun equals(other: Any?): Boolean = this === other || javaClass == other?.javaClass override fun hashCode(): Int = javaClass.hashCode() } class KeywordCompletion(private val languageVersionSettingProvider: LanguageVersionSettingProvider) { interface LanguageVersionSettingProvider { fun getLanguageVersionSetting(element: PsiElement): LanguageVersionSettings fun getLanguageVersionSetting(module: Module): LanguageVersionSettings } companion object { private val ALL_KEYWORDS = (KEYWORDS.types + SOFT_KEYWORDS.types) .map { it as KtKeywordToken } private val INCOMPATIBLE_KEYWORDS_AROUND_SEALED = setOf( SEALED_KEYWORD, ANNOTATION_KEYWORD, DATA_KEYWORD, ENUM_KEYWORD, OPEN_KEYWORD, INNER_KEYWORD, ABSTRACT_KEYWORD ).mapTo(HashSet()) { it.value } private val COMPOUND_KEYWORDS = mapOf<KtKeywordToken, Set<KtKeywordToken>>( COMPANION_KEYWORD to setOf(OBJECT_KEYWORD), DATA_KEYWORD to setOf(CLASS_KEYWORD), ENUM_KEYWORD to setOf(CLASS_KEYWORD), ANNOTATION_KEYWORD to setOf(CLASS_KEYWORD), SEALED_KEYWORD to setOf(CLASS_KEYWORD, INTERFACE_KEYWORD, FUN_KEYWORD), LATEINIT_KEYWORD to setOf(VAR_KEYWORD), CONST_KEYWORD to setOf(VAL_KEYWORD), SUSPEND_KEYWORD to setOf(FUN_KEYWORD) ) private val COMPOUND_KEYWORDS_NOT_SUGGEST_TOGETHER = mapOf<KtKeywordToken, Set<KtKeywordToken>>( // 'fun' can follow 'sealed', e.g. "sealed fun interface". But "sealed fun" looks irrelevant differ to "sealed interface/class". SEALED_KEYWORD to setOf(FUN_KEYWORD), ) private val KEYWORD_CONSTRUCTS = mapOf<KtKeywordToken, String>( IF_KEYWORD to "fun foo() { if (caret)", WHILE_KEYWORD to "fun foo() { while(caret)", FOR_KEYWORD to "fun foo() { for(caret)", TRY_KEYWORD to "fun foo() { try {\ncaret\n}", CATCH_KEYWORD to "fun foo() { try {} catch (caret)", FINALLY_KEYWORD to "fun foo() { try {\n}\nfinally{\ncaret\n}", DO_KEYWORD to "fun foo() { do {\ncaret\n}", INIT_KEYWORD to "class C { init {\ncaret\n}", CONSTRUCTOR_KEYWORD to "class C { constructor(caret)" ) private val NO_SPACE_AFTER = listOf( THIS_KEYWORD, SUPER_KEYWORD, NULL_KEYWORD, TRUE_KEYWORD, FALSE_KEYWORD, BREAK_KEYWORD, CONTINUE_KEYWORD, ELSE_KEYWORD, WHEN_KEYWORD, FILE_KEYWORD, DYNAMIC_KEYWORD, GET_KEYWORD, SET_KEYWORD ).map { it.value } + "companion object" } fun complete(position: PsiElement, prefixMatcher: PrefixMatcher, isJvmModule: Boolean, consumer: (LookupElement) -> Unit) { if (!GENERAL_FILTER.isAcceptable(position, position)) return val sealedInterfacesEnabled = languageVersionSettingProvider.getLanguageVersionSetting(position).supportsFeature(LanguageFeature.SealedInterfaces) val parserFilter = buildFilter(position) for (keywordToken in ALL_KEYWORDS) { val nextKeywords = keywordToken.getNextPossibleKeywords(position) ?: setOf(null) nextKeywords.forEach { if (keywordToken == SEALED_KEYWORD && it == INTERFACE_KEYWORD && !sealedInterfacesEnabled) return@forEach handleCompoundKeyword(position, keywordToken, it, isJvmModule, prefixMatcher, parserFilter, consumer) } } } private fun KtKeywordToken.getNextPossibleKeywords(position: PsiElement): Set<KtKeywordToken>? { return when { this == SUSPEND_KEYWORD && position.isInsideKtTypeReference -> null else -> COMPOUND_KEYWORDS[this] } } private fun KtKeywordToken.avoidSuggestingWith(keywordToken: KtKeywordToken): Boolean { val nextKeywords = COMPOUND_KEYWORDS_NOT_SUGGEST_TOGETHER[this] ?: return false return keywordToken in nextKeywords } private fun ignorePrefixForKeyword(completionPosition: PsiElement, keywordToken: KtKeywordToken): Boolean = when (keywordToken) { // it's needed to complete overrides that should work by member name too OVERRIDE_KEYWORD -> true // keywords that might be used with labels (@label) after them THIS_KEYWORD, RETURN_KEYWORD, BREAK_KEYWORD, CONTINUE_KEYWORD -> { // If the position is parsed as an expression and has a label, it means that the completion is performed // in a place like `return@la<caret>`. The prefix matcher in this case will have its prefix == "la", // and it won't match with the keyword text ("return" in this case). // That's why we want to ignore the prefix matcher for such positions completionPosition is KtExpressionWithLabel && completionPosition.getTargetLabel() != null } else -> false } private fun handleCompoundKeyword( position: PsiElement, keywordToken: KtKeywordToken, nextKeyword: KtKeywordToken?, isJvmModule: Boolean, prefixMatcher: PrefixMatcher, parserFilter: (KtKeywordToken) -> Boolean, consumer: (LookupElement) -> Unit ) { var keyword = keywordToken.value var applicableAsCompound = false if (nextKeyword != null) { fun PsiElement.isSpace() = this is PsiWhiteSpace && '\n' !in getText() var next = position.nextLeaf { !(it.isSpace() || it.text == "$") }?.text next = next?.removePrefix("$") if (keywordToken == SEALED_KEYWORD) { if (next in INCOMPATIBLE_KEYWORDS_AROUND_SEALED) return val prev = position.prevLeaf { !(it.isSpace() || it is PsiErrorElement) }?.text if (prev in INCOMPATIBLE_KEYWORDS_AROUND_SEALED) return } val nextIsNotYetPresent = keywordToken.getNextPossibleKeywords(position)?.none { it.value == next } == true if (nextIsNotYetPresent && keywordToken.avoidSuggestingWith(nextKeyword)) return if (nextIsNotYetPresent) keyword += " " + nextKeyword.value else applicableAsCompound = true } if (keywordToken == DYNAMIC_KEYWORD && isJvmModule) return // not supported for JVM if (!ignorePrefixForKeyword(position, keywordToken) && !prefixMatcher.isStartMatch(keyword)) return if (!parserFilter(keywordToken)) return val constructText = KEYWORD_CONSTRUCTS[keywordToken] if (constructText != null && !applicableAsCompound) { val element = createKeywordConstructLookupElement(position.project, keyword, constructText) consumer(element) } else { if (listOf(CLASS_KEYWORD, OBJECT_KEYWORD, INTERFACE_KEYWORD).any { keyword.endsWith(it.value) }) { val topLevelClassName = getTopLevelClassName(position) if (topLevelClassName != null) { if (keyword.startsWith(DATA_KEYWORD.value)) { consumer(createKeywordConstructLookupElement(position.project, keyword, "$keyword $topLevelClassName(caret)")) } else { consumer(createLookupElementBuilder("$keyword $topLevelClassName", position)) } } } consumer(createLookupElementBuilder(keyword, position)) } } private fun createLookupElementBuilder( keyword: String, position: PsiElement ): LookupElementBuilder { val isUseSiteAnnotationTarget = position.prevLeaf()?.node?.elementType == AT val insertHandler = when { isUseSiteAnnotationTarget -> UseSiteAnnotationTargetInsertHandler keyword in NO_SPACE_AFTER -> null else -> SpaceAfterInsertHandler } val element = LookupElementBuilder.create(KeywordLookupObject(), keyword).bold().withInsertHandler(insertHandler) return if (isUseSiteAnnotationTarget) { element.withPresentableText("$keyword:") } else { element } } private fun getTopLevelClassName(position: PsiElement): String? { if (position.parents.any { it is KtDeclaration }) return null val file = position.containingFile as? KtFile ?: return null val name = FileUtil.getNameWithoutExtension(file.name) if (!Name.isValidIdentifier(name) || Name.identifier(name).render() != name || !name[0].isUpperCase() || file.declarations.any { it is KtClassOrObject && it.name == name } ) return null return name } private object UseSiteAnnotationTargetInsertHandler : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { WithTailInsertHandler(":", spaceBefore = false, spaceAfter = false).postHandleInsert(context, item) } } private object SpaceAfterInsertHandler : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { WithTailInsertHandler.SPACE.postHandleInsert(context, item) } } private val GENERAL_FILTER = NotFilter( OrFilter( CommentFilter(), ParentFilter(ClassFilter(KtLiteralStringTemplateEntry::class.java)), ParentFilter(ClassFilter(KtConstantExpression::class.java)), FileFilter(ClassFilter(KtTypeCodeFragment::class.java)), LeftNeighbour(TextFilter(".")), LeftNeighbour(TextFilter("?.")) ) ) private class CommentFilter() : ElementFilter { override fun isAcceptable(element: Any?, context: PsiElement?) = (element is PsiElement) && KtPsiUtil.isInComment(element) override fun isClassAcceptable(hintClass: Class<out Any?>) = true } private class ParentFilter(filter: ElementFilter) : PositionElementFilter() { init { setFilter(filter) } override fun isAcceptable(element: Any?, context: PsiElement?): Boolean { val parent = (element as? PsiElement)?.parent return parent != null && (filter?.isAcceptable(parent, context) ?: true) } } private class FileFilter(filter: ElementFilter) : PositionElementFilter() { init { setFilter(filter) } override fun isAcceptable(element: Any?, context: PsiElement?): Boolean { val file = (element as? PsiElement)?.containingFile return file != null && (filter?.isAcceptable(file, context) ?: true) } } private fun buildFilter(position: PsiElement): (KtKeywordToken) -> Boolean { var parent = position.parent var prevParent = position while (parent != null) { when (parent) { is KtBlockExpression -> { var prefixText = "fun foo() { " if (prevParent is KtExpression) { // check that we are right after a try-expression without finally-block or after if-expression without else val prevLeaf = prevParent.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment && it !is PsiErrorElement } if (prevLeaf != null) { val isAfterThen = prevLeaf.goUpWhileIsLastChild().any { it.node.elementType == KtNodeTypes.THEN } var isAfterTry = false var isAfterCatch = false if (prevLeaf.node.elementType == RBRACE) { when ((prevLeaf.parent as? KtBlockExpression)?.parent) { is KtTryExpression -> isAfterTry = true is KtCatchClause -> { isAfterTry = true; isAfterCatch = true } } } if (isAfterThen) { prefixText += if (isAfterTry) { "if (a)\n" } else { "if (a) {}\n" } } if (isAfterTry) { prefixText += "try {}\n" } if (isAfterCatch) { prefixText += "catch (e: E) {}\n" } } return buildFilterWithContext(prefixText, prevParent, position) } else { val lastExpression = prevParent .siblings(forward = false, withItself = false) .firstIsInstanceOrNull<KtExpression>() if (lastExpression != null) { val contextAfterExpression = lastExpression .siblings(forward = true, withItself = false) .takeWhile { it != prevParent } .joinToString { it.text } return buildFilterWithContext(prefixText + "x" + contextAfterExpression, prevParent, position) } } } is KtDeclarationWithInitializer -> { val initializer = parent.initializer if (prevParent == initializer) { return buildFilterWithContext("val v = ", initializer, position) } } is KtParameter -> { val default = parent.defaultValue if (prevParent == default) { return buildFilterWithContext("val v = ", default, position) } } // for type references in places like 'listOf<' or 'List<' we want to filter almost all keywords // (except maybe for 'suspend' and 'in'/'out', since they can be a part of a type reference) is KtTypeReference -> { val shouldIntroduceTypeReferenceContext = when { // it can be a receiver type, or it can be a declaration's name, // so we don't want to change the context parent.isExtensionReceiverInCallableDeclaration -> false // it is probably an annotation entry, or a super class constructor's invocation, // in this case we don't want to change the context parent.parent is KtConstructorCalleeExpression -> false else -> true } if (shouldIntroduceTypeReferenceContext) { // we cannot just search for an outer element of KtTypeReference type, because // we can be inside the lambda type args (e.g. 'val foo: (bar: <caret>) -> Unit'); // that's why we have to do a more precise check val prefixText = if (parent.isTypeArgumentOfOuterKtTypeReference) { "fun foo(x: X<" } else { "fun foo(x: " } return buildFilterWithContext(prefixText, contextElement = parent, position) } } is KtDeclaration -> { when (parent.parent) { is KtClassOrObject -> { return if (parent is KtPrimaryConstructor) { buildFilterWithReducedContext("class X ", parent, position) } else { buildFilterWithReducedContext("class X { ", parent, position) } } is KtFile -> return buildFilterWithReducedContext("", parent, position) } } } prevParent = parent parent = parent.parent } return buildFilterWithReducedContext("", null, position) } private val KtTypeReference.isExtensionReceiverInCallableDeclaration: Boolean get() { val parent = parent return parent is KtCallableDeclaration && parent.receiverTypeReference == this } private val KtTypeReference.isTypeArgumentOfOuterKtTypeReference: Boolean get() { val typeProjection = parent as? KtTypeProjection val typeArgumentList = typeProjection?.parent as? KtTypeArgumentList val userType = typeArgumentList?.parent as? KtUserType return userType?.parent is KtTypeReference } private fun computeKeywordApplications(prefixText: String, keyword: KtKeywordToken): Sequence<String> = when (keyword) { SUSPEND_KEYWORD -> sequenceOf("suspend () -> Unit>", "suspend X") else -> { if (prefixText.endsWith("@")) sequenceOf(keyword.value + ":X Y.Z") else sequenceOf(keyword.value + " X") } } private fun buildFilterWithContext( prefixText: String, contextElement: PsiElement, position: PsiElement ): (KtKeywordToken) -> Boolean { val offset = position.getStartOffsetInAncestor(contextElement) val truncatedContext = contextElement.text!!.substring(0, offset) return buildFilterByText(prefixText + truncatedContext, position) } private fun buildFilterWithReducedContext( prefixText: String, contextElement: PsiElement?, position: PsiElement ): (KtKeywordToken) -> Boolean { val builder = StringBuilder() buildReducedContextBefore(builder, position, contextElement) return buildFilterByText(prefixText + builder.toString(), position) } private fun buildFilesWithKeywordApplication( keywordTokenType: KtKeywordToken, prefixText: String, psiFactory: KtPsiFactory ): Sequence<KtFile> { return computeKeywordApplications(prefixText, keywordTokenType) .map { application -> psiFactory.createFile(prefixText + application) } } private fun buildFilterByText(prefixText: String, position: PsiElement): (KtKeywordToken) -> Boolean { val psiFactory = KtPsiFactory(position.project) fun PsiElement.isSecondaryConstructorInObjectDeclaration(): Boolean { val secondaryConstructor = parentOfType<KtSecondaryConstructor>() ?: return false return secondaryConstructor.getContainingClassOrObject() is KtObjectDeclaration } fun isKeywordCorrectlyApplied(keywordTokenType: KtKeywordToken, file: KtFile): Boolean { val elementAt = file.findElementAt(prefixText.length)!! val languageVersionSettings = ModuleUtilCore.findModuleForPsiElement(position)?.let(languageVersionSettingProvider::getLanguageVersionSetting) ?: LanguageVersionSettingsImpl.DEFAULT when { !elementAt.node!!.elementType.matchesKeyword(keywordTokenType) -> return false elementAt.getNonStrictParentOfType<PsiErrorElement>() != null -> return false isErrorElementBefore(elementAt) -> return false !isModifierSupportedAtLanguageLevel(elementAt, keywordTokenType, languageVersionSettings) -> return false (keywordTokenType == VAL_KEYWORD || keywordTokenType == VAR_KEYWORD) && elementAt.parent is KtParameter && elementAt.parentOfTypes(KtNamedFunction::class, KtSecondaryConstructor::class) != null -> return false keywordTokenType == CONSTRUCTOR_KEYWORD && elementAt.isSecondaryConstructorInObjectDeclaration() -> return false keywordTokenType !is KtModifierKeywordToken -> return true else -> { if (elementAt.parent !is KtModifierList) return true val container = elementAt.parent.parent val possibleTargets = when (container) { is KtParameter -> { if (container.ownerFunction is KtPrimaryConstructor) listOf(VALUE_PARAMETER, MEMBER_PROPERTY) else listOf(VALUE_PARAMETER) } is KtTypeParameter -> listOf(TYPE_PARAMETER) is KtEnumEntry -> listOf(ENUM_ENTRY) is KtClassBody -> listOf( CLASS_ONLY, INTERFACE, OBJECT, ENUM_CLASS, ANNOTATION_CLASS, MEMBER_FUNCTION, MEMBER_PROPERTY, FUNCTION, PROPERTY ) is KtFile -> listOf( CLASS_ONLY, INTERFACE, OBJECT, ENUM_CLASS, ANNOTATION_CLASS, TOP_LEVEL_FUNCTION, TOP_LEVEL_PROPERTY, FUNCTION, PROPERTY ) else -> listOf() } val modifierTargets = possibleTargetMap[keywordTokenType]?.intersect(possibleTargets) if (modifierTargets != null && possibleTargets.isNotEmpty() && modifierTargets.none { isModifierTargetSupportedAtLanguageLevel(keywordTokenType, it, languageVersionSettings) } ) return false val parentTarget = when (val ownerDeclaration = container?.getParentOfType<KtDeclaration>(strict = true)) { null -> FILE is KtClass -> { when { ownerDeclaration.isInterface() -> INTERFACE ownerDeclaration.isEnum() -> ENUM_CLASS ownerDeclaration.isAnnotation() -> ANNOTATION_CLASS else -> CLASS_ONLY } } is KtObjectDeclaration -> if (ownerDeclaration.isObjectLiteral()) OBJECT_LITERAL else OBJECT else -> return keywordTokenType != CONST_KEYWORD } if (!isPossibleParentTarget(keywordTokenType, parentTarget, languageVersionSettings)) return false if (keywordTokenType == CONST_KEYWORD) { return when (parentTarget) { OBJECT -> true FILE -> { val prevSiblings = elementAt.parent.siblings(withItself = false, forward = false) val hasLineBreak = prevSiblings .takeWhile { it is PsiWhiteSpace || it.isSemicolon() } .firstOrNull { it.text.contains("\n") || it.isSemicolon() } != null hasLineBreak || prevSiblings.none { it !is PsiWhiteSpace && !it.isSemicolon() && it !is KtImportList && it !is KtPackageDirective } } else -> false } } return true } } } return fun(keywordTokenType): Boolean { val files = buildFilesWithKeywordApplication(keywordTokenType, prefixText, psiFactory) return files.any { file -> isKeywordCorrectlyApplied(keywordTokenType, file); } } } private fun PsiElement.isSemicolon() = node.elementType == SEMICOLON private fun isErrorElementBefore(token: PsiElement): Boolean { for (leaf in token.prevLeafs) { if (leaf is PsiWhiteSpace || leaf is PsiComment) continue if (leaf.parentsWithSelf.any { it is PsiErrorElement }) return true if (leaf.textLength != 0) break } return false } private fun IElementType.matchesKeyword(keywordType: KtKeywordToken): Boolean { return when (this) { keywordType -> true NOT_IN -> keywordType == IN_KEYWORD NOT_IS -> keywordType == IS_KEYWORD else -> false } } private fun isModifierSupportedAtLanguageLevel( position: PsiElement, keyword: KtKeywordToken, languageVersionSettings: LanguageVersionSettings ): Boolean { val feature = when (keyword) { TYPE_ALIAS_KEYWORD -> LanguageFeature.TypeAliases HEADER_KEYWORD, IMPL_KEYWORD -> return false EXPECT_KEYWORD, ACTUAL_KEYWORD -> LanguageFeature.MultiPlatformProjects SUSPEND_KEYWORD -> LanguageFeature.Coroutines FIELD_KEYWORD -> { if (!position.isExplicitBackingFieldDeclaration) return true LanguageFeature.ExplicitBackingFields } CONTEXT_KEYWORD -> LanguageFeature.ContextReceivers else -> return true } return languageVersionSettings.supportsFeature(feature) } private fun isModifierTargetSupportedAtLanguageLevel( keyword: KtKeywordToken, target: KotlinTarget, languageVersionSettings: LanguageVersionSettings ): Boolean { if (keyword == LATEINIT_KEYWORD) { val feature = when (target) { TOP_LEVEL_PROPERTY -> LanguageFeature.LateinitTopLevelProperties LOCAL_VARIABLE -> LanguageFeature.LateinitLocalVariables else -> return true } return languageVersionSettings.supportsFeature(feature) } else { return true } } // builds text within scope (or from the start of the file) before position element excluding almost all declarations private fun buildReducedContextBefore(builder: StringBuilder, position: PsiElement, scope: PsiElement?) { if (position == scope) return if (position is KtCodeFragment) { val ktContext = position.context as? KtElement ?: return buildReducedContextBefore(builder, ktContext, scope) return } else if (position is PsiFile) { return } val parent = position.parent ?: return buildReducedContextBefore(builder, parent, scope) val prevDeclaration = position.siblings(forward = false, withItself = false).firstOrNull { it is KtDeclaration } var child = parent.firstChild while (child != position) { if (child is KtDeclaration) { if (child == prevDeclaration) { builder.appendReducedText(child) } } else { builder.append(child!!.text) } child = child.nextSibling } } private fun StringBuilder.appendReducedText(element: PsiElement) { var child = element.firstChild if (child == null) { append(element.text!!) } else { while (child != null) { when (child) { is KtBlockExpression, is KtClassBody -> append("{}") else -> appendReducedText(child) } child = child.nextSibling } } } private fun PsiElement.getStartOffsetInAncestor(ancestor: PsiElement): Int { if (ancestor == this) return 0 return parent!!.getStartOffsetInAncestor(ancestor) + startOffsetInParent } private fun PsiElement.goUpWhileIsLastChild(): Sequence<PsiElement> = generateSequence(this) { when { it is PsiFile -> null it != it.parent.lastChild -> null else -> it.parent } } private fun isPossibleParentTarget( modifier: KtModifierKeywordToken, parentTarget: KotlinTarget, languageVersionSettings: LanguageVersionSettings ): Boolean { deprecatedParentTargetMap[modifier]?.let { if (parentTarget in it) return false } possibleParentTargetPredicateMap[modifier]?.let { return it.isAllowed(parentTarget, languageVersionSettings) } return true } private val PsiElement.isExplicitBackingFieldDeclaration get() = parent is KtBackingField }
apache-2.0
a158c5a206e7f87f8df03840c33d99f5
41.954054
158
0.579015
5.688082
false
false
false
false
mantono/GymData
src/main/kotlin/com/mantono/gym/Weight.kt
1
2310
package com.mantono.gym sealed class Weight: Comparable<Weight>, Number() { abstract val kilograms: Double abstract val pounds: Double override fun compareTo(other: Weight): Int = kilograms.compareTo(other.kilograms) override fun equals(other: Any?): Boolean { if(other == null || other !is Weight) return false val diff: Double = Math.abs(this.kilograms - other.kilograms) return diff <= 0.1 } override fun toString(): String = when(this) { is Pound -> "$pounds lbs" is Kilogram -> "$kilograms kg" Zero -> "0.0" } override fun hashCode(): Int = kilograms.toInt() operator fun minus(other: Weight): Weight = Kilogram(this.kilograms - other.kilograms) operator fun plus(other: Weight): Weight = Kilogram(this.kilograms + other.kilograms) operator fun times(multiplier: Number): Weight = Kilogram(this.kilograms*multiplier.toDouble()) operator fun div(dividend: Number): Weight = Kilogram(this.kilograms/dividend.toDouble()) override fun toByte(): Byte = kilograms.toByte() override fun toChar(): Char = kilograms.toChar() override fun toDouble(): Double = kilograms override fun toFloat(): Float = kilograms.toFloat() override fun toInt(): Int = kilograms.toInt() override fun toLong(): Long = kilograms.toLong() override fun toShort(): Short = kilograms.toShort() } class Kilogram(private val amount: Double): Weight() { private val conversionRatio: Double = 2.20462262 override val kilograms: Double = amount override val pounds: Double by lazy { toPounds().pounds } constructor(amount: Float): this(amount.toDouble()) fun toPounds(): Pound = Pound(amount*conversionRatio) } class Pound(private val amount: Double): Weight() { private val conversionRatio: Double = 0.45359237 override val pounds: Double = amount override val kilograms: Double by lazy { toKilograms().kilograms } constructor(amount: Float): this(amount.toDouble()) fun toKilograms(): Kilogram = Kilogram(amount*conversionRatio) } object Zero: Weight() { override val kilograms: Double = 0.0 override val pounds: Double = 0.0 } fun weightOf(amount: Double, unit: String): Weight = when { amount == 0.0 -> Zero unit in listOf("kg", "kilo", "kilogram") -> Kilogram(amount) unit in listOf("lbs", "pound") -> Pound(amount) else -> throw IllegalArgumentException("Invalid unit $unit") }
gpl-3.0
1dfae97aa68811147971d5a0bc173b13
32.014286
96
0.72684
3.494705
false
false
false
false
all-of-us/workbench
api/src/test/java/org/pmiops/workbench/actionaudit/targetproperties/TargetPropertyExtractorTest.kt
1
2337
package org.pmiops.workbench.actionaudit.targetproperties import com.google.common.truth.Truth.assertThat import kotlin.reflect.KClass import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.pmiops.workbench.access.AccessTierService import org.pmiops.workbench.model.ResearchPurpose import org.pmiops.workbench.model.Workspace class TargetPropertyExtractorTest { private var workspace: Workspace? = null private var researchPurpose1: ResearchPurpose? = null @BeforeEach fun setUp() { researchPurpose1 = ResearchPurpose() .apply { intendedStudy = "stubbed toes" } .apply { additionalNotes = "I really like the cloud." } val now = System.currentTimeMillis() workspace = Workspace() .apply { name = "DbWorkspace 1" } .apply { id = "fc-id-1" } .apply { namespace = "aou-rw-local1-c4be869a" } .apply { creator = "[email protected]" } .apply { cdrVersionId = "1" } .apply { researchPurpose = researchPurpose1 } .apply { creationTime = now } .apply { lastModifiedTime = now } .apply { etag = "etag_1" } .apply { accessTierShortName = AccessTierService.REGISTERED_TIER_SHORT_NAME } .apply { published = false } } @Test fun testGetsWorkspaceProperties() { val propertyValuesByName = TargetPropertyExtractor.getPropertyValuesByName( WorkspaceTargetProperty.values(), workspace!!) assertThat(propertyValuesByName[WorkspaceTargetProperty.NAME.propertyName]) .isEqualTo("DbWorkspace 1") assertThat(propertyValuesByName).hasSize(19) } @Test fun testGetTargetPropertyEnumByTargetClass() { val result: Map<KClass<out Any>, KClass<out Any>> = TargetPropertyExtractor.getTargetPropertyEnumByTargetClass() assertThat(result).hasSize(2) assertThat(result[Workspace::class]).isEqualTo(WorkspaceTargetProperty::class) } @Test fun testGetPropertyEnum() { val result: KClass<out Any> = TargetPropertyExtractor.getTargetPropertyEnum(Workspace::class) assertThat(result).isEqualTo(WorkspaceTargetProperty::class) } }
bsd-3-clause
d80d40fbea2e5bb2e9a094bde4f92b1a
38.610169
89
0.656397
4.555556
false
true
false
false
icela/FriceEngine
src/org/frice/util/message/FDialog.kt
1
407
package org.frice.util.message const val YES_NO_OPTION = 0 const val YES_NO_CANCEL_OPTION = 1 const val OK_CANCEL_OPTION = 2 const val YES_OPTION = 0 const val NO_OPTION = 1 const val CANCEL_OPTION = 2 const val OK_OPTION = 0 const val CLOSED_OPTION = -1 const val ERROR_MESSAGE = 0 const val INFORMATION_MESSAGE = 1 const val WARNING_MESSAGE = 2 const val QUESTION_MESSAGE = 3 const val PLAIN_MESSAGE = -1
agpl-3.0
59de5e8cd0857d73bb268b5dd848db61
26.2
34
0.749386
3.308943
false
false
false
false
Meisolsson/PocketHub
app/src/main/java/com/github/pockethub/android/ui/issue/IssuesFragment.kt
1
8357
/* * Copyright (c) 2015 PocketHub * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pockethub.android.ui.issue import android.app.Activity.RESULT_OK import android.app.SearchManager import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.appcompat.widget.SearchView import com.github.pockethub.android.Intents.EXTRA_ISSUE import com.github.pockethub.android.Intents.EXTRA_ISSUE_FILTER import com.github.pockethub.android.Intents.EXTRA_REPOSITORY import com.github.pockethub.android.ui.helpers.ItemListHandler import com.github.pockethub.android.ui.helpers.PagedListFetcher import com.github.pockethub.android.ui.helpers.PagedScrollListener import com.github.pockethub.android.R import com.github.pockethub.android.RequestCodes.ISSUE_CREATE import com.github.pockethub.android.RequestCodes.ISSUE_FILTER_EDIT import com.github.pockethub.android.RequestCodes.ISSUE_VIEW import com.github.pockethub.android.core.issue.IssueFilter import com.github.pockethub.android.core.issue.IssueStore import com.github.pockethub.android.persistence.AccountDataManager import com.github.pockethub.android.ui.base.BaseFragment import com.github.pockethub.android.ui.item.issue.IssueFilterHeaderItem import com.github.pockethub.android.ui.item.issue.IssueItem import com.github.pockethub.android.util.AvatarLoader import com.github.pockethub.android.util.ToastUtils import com.meisolsson.githubsdk.model.Issue import com.meisolsson.githubsdk.model.Page import com.meisolsson.githubsdk.model.Repository import com.meisolsson.githubsdk.service.issues.IssueService import com.xwray.groupie.Item import com.xwray.groupie.OnItemClickListener import io.reactivex.Single import kotlinx.android.synthetic.main.fragment_item_list.view.* import retrofit2.Response import javax.inject.Inject /** * Fragment to display a list of issues */ class IssuesFragment : BaseFragment() { @Inject lateinit var cache: AccountDataManager @Inject lateinit var store: IssueStore @Inject lateinit var avatars: AvatarLoader @Inject lateinit var service: IssueService private lateinit var pagedListFetcher: PagedListFetcher<Issue> private lateinit var itemListHandler: ItemListHandler private var filter: IssueFilter? = null private var repository: Repository? = null val errorMessage= R.string.error_issues_load override fun onAttach(context: Context) { super.onAttach(context) val intent = activity?.intent filter = intent?.getParcelableExtra(EXTRA_ISSUE_FILTER) repository = intent?.getParcelableExtra(EXTRA_REPOSITORY) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (filter == null) { filter = IssueFilter(repository) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_item_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true); itemListHandler = ItemListHandler( view.list, view.empty, lifecycle, activity, OnItemClickListener(this::onItemClick) ) pagedListFetcher = PagedListFetcher( view.swipe_item, lifecycle, itemListHandler, { t -> ToastUtils.show(activity, errorMessage) }, this::loadData, this::createItem ) view.list.addOnScrollListener( PagedScrollListener(itemListHandler.mainSection, pagedListFetcher) ) itemListHandler.setEmptyText(R.string.no_issues) itemListHandler.mainSection.setHeader(IssueFilterHeaderItem(avatars, filter!!)) } private fun onItemClick(item: Item<*>, view: View) { if (item is IssueItem) { // Remove one since we have a header val position = itemListHandler.getItemPosition(item) - 1 val issues = itemListHandler.items .filterIsInstance<IssueItem>() .map { it.issue } startActivityForResult(IssuesViewActivity.createIntent(issues, repository!!, position), ISSUE_VIEW) } else if (item is IssueFilterHeaderItem) { startActivityForResult(EditIssuesFilterActivity.createIntent(filter!!), ISSUE_FILTER_EDIT) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.fragment_issues, menu) val searchManager = activity!!.getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchItem = menu.findItem(R.id.m_search) val searchView = searchItem.actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(activity!!.componentName)) val args = Bundle() args.putParcelable(EXTRA_REPOSITORY, repository) searchView.setAppSearchData(args) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (!isAdded) { return false } when (item.itemId) { R.id.m_refresh -> { pagedListFetcher.refresh() return true } R.id.create_issue -> { startActivityForResult(EditIssueActivity.createIntent(repository), ISSUE_CREATE) return true } R.id.m_filter -> { startActivityForResult(EditIssuesFilterActivity.createIntent(filter!!), ISSUE_FILTER_EDIT) return true } R.id.m_bookmark -> { cache.addIssueFilter(filter) .subscribe( { ToastUtils.show(activity, R.string.message_filter_saved) }, { ToastUtils.show(activity, R.string.message_filter_save_failed) } ) return true } else -> return super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (resultCode == RESULT_OK && requestCode == ISSUE_FILTER_EDIT && data != null) { val newFilter = data.getParcelableExtra<IssueFilter>(EXTRA_ISSUE_FILTER) if (filter != newFilter) { filter = newFilter itemListHandler.mainSection.setHeader(IssueFilterHeaderItem(avatars, filter!!)) pagedListFetcher.refresh() return } } if (requestCode == ISSUE_VIEW) { pagedListFetcher.refresh() return } if (requestCode == ISSUE_CREATE && resultCode == RESULT_OK) { val created = data!!.getParcelableExtra<Issue>(EXTRA_ISSUE) pagedListFetcher.refresh() startActivityForResult( IssuesViewActivity.createIntent(created, repository!!), ISSUE_VIEW ) return } super.onActivityResult(requestCode, resultCode, data) } private fun loadData(page: Int): Single<Response<Page<Issue>>> { return service.getRepositoryIssues( repository!!.owner()!!.login(), repository!!.name(), filter!!.toFilterMap(), page.toLong() ) } private fun createItem(item: Issue) = IssueItem(avatars, item) }
apache-2.0
900393e273e081f3a7fa51d71c83894d
35.021552
111
0.674405
4.86721
false
false
false
false
GunoH/intellij-community
plugins/kotlin/code-insight/line-markers/src/org/jetbrains/kotlin/idea/codeInsight/lineMarkers/KotlinSuspendCallLineMarkerProvider.kt
2
3675
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.lineMarkers import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.codeInsight.daemon.MergeableLineMarkerInfo import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiElement import com.intellij.psi.SmartPsiElementPointer import com.intellij.refactoring.suggested.createSmartPointer import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtKotlinPropertySymbol import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.base.codeInsight.KotlinCallProcessor import org.jetbrains.kotlin.idea.base.codeInsight.process import org.jetbrains.kotlin.name.CallableId import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name internal class KotlinSuspendCallLineMarkerProvider : LineMarkerProvider { private companion object { private val COROUTINE_CONTEXT_CALLABLE_ID = CallableId(FqName("kotlin.coroutines"), Name.identifier("coroutineContext")) } override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<in LineMarkerInfo<*>>) { KotlinCallProcessor.process(elements) { target -> val symbol = target.symbol if (symbol is KtFunctionSymbol && symbol.isSuspend) { val name = symbol.name.asString() val isOperator = symbol.isOperator @NlsSafe val declarationName = "$name()" val message = when { isOperator -> KotlinLineMarkersBundle.message("line.markers.suspend.operator.call.description", declarationName) else -> KotlinLineMarkersBundle.message("line.markers.suspend.function.call.description", declarationName) } result += SuspendCallLineMarkerInfo(target.anchorLeaf, message, declarationName, symbol.psi?.createSmartPointer()) } else if (symbol is KtKotlinPropertySymbol && symbol.callableIdIfNonLocal == COROUTINE_CONTEXT_CALLABLE_ID) { val message = KotlinLineMarkersBundle.message("line.markers.coroutine.context.call.description") result += SuspendCallLineMarkerInfo(target.anchorLeaf, message, symbol.name.asString(), symbol.psi?.createSmartPointer()) } } } private class SuspendCallLineMarkerInfo( anchor: PsiElement, message: String, @NlsSafe private val declarationName: String, targetElementPointer: SmartPsiElementPointer<PsiElement>?, ) : MergeableLineMarkerInfo<PsiElement>( /* element = */ anchor, /* textRange = */ anchor.textRange, /* icon = */ KotlinIcons.SUSPEND_CALL, /* tooltipProvider = */ { message }, /* navHandler = */ targetElementPointer?.let(::SimpleNavigationHandler), /* alignment = */ GutterIconRenderer.Alignment.RIGHT, /* accessibleNameProvider = */ { message } ) { override fun createGutterRenderer() = LineMarkerGutterIconRenderer(this) override fun getElementPresentation(element: PsiElement) = declarationName override fun canMergeWith(info: MergeableLineMarkerInfo<*>) = info is SuspendCallLineMarkerInfo override fun getCommonIcon(infos: List<MergeableLineMarkerInfo<*>>) = infos.firstNotNullOf { it.icon } } }
apache-2.0
fe22d6ca86f17a302e6acd4e4d71a612
50.774648
137
0.728435
5.183357
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/recentProjects/RecentProjectTreeItem.kt
1
6542
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.welcomeScreen.recentProjects import com.intellij.CommonBundle import com.intellij.ide.* import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.lightEdit.LightEdit import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame import com.intellij.openapi.wm.impl.welcomeScreen.ProjectDetector import com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects.CloneableProjectsService import com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects.CloneableProjectsService.CloneableProject import com.intellij.openapi.wm.impl.welcomeScreen.projectActions.RemoveSelectedProjectsAction import com.intellij.util.BitUtil import com.intellij.util.SystemProperties import kotlinx.coroutines.launch import org.jetbrains.annotations.SystemIndependent import java.awt.event.InputEvent import java.nio.file.Files import java.nio.file.Path import javax.swing.SwingUtilities /** * Items of recent project tree: * - RootItem: collect all items of interface * - RecentProjectItem: an item project which can be interacted * - ProjectsGroupItem: group of RecentProjectItem * * @see com.intellij.openapi.wm.impl.welcomeScreen.ProjectsTabFactory.createWelcomeTab * @see com.intellij.ide.ManageRecentProjectsAction */ internal sealed interface RecentProjectTreeItem { fun displayName(): String fun children(): List<RecentProjectTreeItem> fun removeItem() { RemoveSelectedProjectsAction.removeItem(this) } } internal data class RecentProjectItem( val projectPath: @SystemIndependent String, @NlsSafe val projectName: String, @NlsSafe val displayName: String, val projectGroup: ProjectGroup? ) : RecentProjectTreeItem { override fun displayName(): String = displayName override fun children(): List<RecentProjectTreeItem> = emptyList() companion object { fun openProjectAndLogRecent(file: Path, options: OpenProjectTask, projectGroup: ProjectGroup?) { ApplicationManager.getApplication().coroutineScope.launch { RecentProjectsManagerBase.getInstanceEx().openProject(file, options) for (extension in ProjectDetector.EXTENSION_POINT_NAME.extensions) { extension.logRecentProjectOpened(projectGroup) } } } } fun openProject(event: AnActionEvent) { // Force move focus to IdeFrame IdeEventQueue.getInstance().popupManager.closeAllPopups() val file = Path.of(projectPath).normalize() if (!Files.exists(file)) { val exitCode = Messages.showYesNoDialog( IdeBundle.message("message.the.path.0.does.not.exist.maybe.on.remote", FileUtil.toSystemDependentName(projectPath)), IdeBundle.message("dialog.title.reopen.project"), IdeBundle.message("button.remove.from.list"), CommonBundle.getCancelButtonText(), Messages.getErrorIcon() ) if (exitCode == Messages.YES) { RecentProjectsManager.getInstance().removePath(projectPath) } return } if (event.place == ActionPlaces.WELCOME_SCREEN) { val welcomeFrame = SwingUtilities.getAncestorOfClass(FlatWelcomeFrame::class.java, event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)) as FlatWelcomeFrame? if (welcomeFrame != null) { Disposer.dispose(welcomeFrame) } } val modifiers = event.modifiers // Deprecated constants are used because com.intellij.openapi.actionSystem.AnActionEvent // doesn't work with java.awt.event.InputEvent.getModifiersEx API val forceOpenInNewFrame = BitUtil.isSet(modifiers, InputEvent.CTRL_MASK) || BitUtil.isSet(modifiers, InputEvent.SHIFT_MASK) || event.place == ActionPlaces.WELCOME_SCREEN || LightEdit.owns(null) openProjectAndLogRecent(file, OpenProjectTask { this.forceOpenInNewFrame = forceOpenInNewFrame runConfigurators = true showFrameAsap = true }, projectGroup) } fun searchName(): String { val home = SystemProperties.getUserHome() var path = projectPath if (FileUtil.startsWith(path, home)) { path = path.substring(home.length) } val groupName = RecentProjectsManagerBase.getInstanceEx().findGroup(projectPath)?.name.orEmpty() return "$groupName $path $displayName" } } internal data class ProjectsGroupItem( val group: ProjectGroup, val children: List<RecentProjectItem> ) : RecentProjectTreeItem { override fun displayName(): String = group.name override fun children(): List<RecentProjectTreeItem> = children } internal data class CloneableProjectItem( val projectPath: @SystemIndependent String, @NlsSafe val projectName: String, @NlsSafe val displayName: String, val cloneableProject: CloneableProject ) : RecentProjectTreeItem { override fun displayName(): String = displayName override fun children(): List<RecentProjectTreeItem> = emptyList() } // The root node is required for the filtering tree internal class RootItem(private val collectors: List<() -> List<RecentProjectTreeItem>>) : RecentProjectTreeItem { override fun displayName(): String = "" // Not visible in tree override fun children(): List<RecentProjectTreeItem> = collectors.flatMap { collector -> collector() } } internal object ProjectCollectors { @JvmField val recentProjectsCollector: () -> List<RecentProjectTreeItem> = { RecentProjectListActionProvider.getInstance().collectProjects() } @JvmField val cloneableProjectsCollector: () -> List<RecentProjectTreeItem> = { CloneableProjectsService.getInstance().collectCloneableProjects() } @JvmField val all = listOf(cloneableProjectsCollector, recentProjectsCollector) @JvmStatic fun createRecentProjectsWithoutCurrentCollector(currentProject: Project): () -> List<RecentProjectTreeItem> { return { RecentProjectListActionProvider.getInstance().collectProjectsWithoutCurrent(currentProject) } } }
apache-2.0
9613179c7021c63758c136aff9a2fe5c
37.040698
134
0.753592
4.828044
false
false
false
false
jk1/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/driver/ExtendedJTreePathFinder.kt
1
6433
// 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.testGuiFramework.driver import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader import com.intellij.ui.LoadingNode import org.fest.swing.cell.JTreeCellReader import org.fest.swing.exception.LocationUnavailableException import javax.swing.JTree import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import javax.swing.tree.TreeNode import javax.swing.tree.TreePath typealias FinderPredicate = (String, String) -> Boolean class ExtendedJTreePathFinder(val jTree: JTree) { private val cellReader: JTreeCellReader = ExtendedJTreeCellReader() fun findMatchingPath(vararg pathStrings: String): TreePath = findMatchingPathByPredicate(pathStrings = *pathStrings, predicate = predicateEquality) fun findMatchingPathWithVersion(vararg pathStrings: String): TreePath = findMatchingPathByPredicate(pathStrings = *pathStrings, predicate = predicateWithVersion) // this is ex-XPath version fun findMatchingPathByPredicate(vararg pathStrings: String, predicate: FinderPredicate): TreePath { val model = jTree.model if (jTree.isRootVisible) { val childValue = jTree.value(model.root) ?: "" if (!predicate(pathStrings[0], childValue)) pathNotFound(*pathStrings) if (pathStrings.size == 1) return TreePath(arrayOf<Any>(model.root)) } return jTree.traverseChildren( node = model.root, pathStrings = *pathStrings, pathTree = TreePath(model.root), predicate = predicate) ?: throw pathNotFound(*pathStrings) } fun exists(vararg pathStrings: String) = existsByPredicate(pathStrings = *pathStrings, predicate = predicateEquality) fun existsWithVersion(vararg pathStrings: String) = existsByPredicate(pathStrings= *pathStrings, predicate = predicateWithVersion) fun existsByPredicate(vararg pathStrings: String, predicate: FinderPredicate): Boolean{ return try{ findMatchingPathByPredicate( pathStrings = *pathStrings, predicate = predicate ) true } catch (e: Exception){ false } } // JTree extensions private fun JTree.traverseChildren(node: Any, vararg pathStrings: String, pathTree: TreePath, predicate: FinderPredicate): TreePath? { val childCount = this.model.getChildCount(node) val order = pathStrings[0].getOrder() ?: 0 val original = pathStrings[0].getWithoutOrder() var currentOrder = 0 for (childIndex in 0 until childCount) { val child = this.model.getChild(node, childIndex) if (child is LoadingNode) throw ExtendedJTreeDriver.LoadingNodeException(node = child, treePath = this.getPathToNode(node)) val childValue = value(child) ?: continue if (predicate(original, childValue)) { if (currentOrder == order) { val newPath = TreePath(arrayOf<Any>(*pathTree.path, child)) return if (pathStrings.size == 1) { newPath } else { this.traverseChildren( node = child, pathStrings = *pathStrings.toList().subList(1, pathStrings.size).toTypedArray(), pathTree = newPath, predicate = predicate ) } } else { currentOrder++ } } } return null } private fun JTree.getPathToNode(node: Any): TreePath { val treeModel = model as DefaultTreeModel var path = treeModel.getPathToRoot(node as TreeNode) if (!isRootVisible) path = path.sliceArray(1 until path.size) return TreePath(path) } private fun JTree.value(modelValue: Any): String? { return cellReader.valueAt(this, modelValue)?.eraseZeroSpaceSymbols() } private fun String.eraseZeroSpaceSymbols(): String = replace("\u200B", "") // function to work with order - so with lines like `abc(0)` private val orderPattern = Regex("\\(\\d+\\)") private fun String.getWithoutOrder(): String = if (this.hasOrder()) this.dropLast(2 + this.getOrder().toString().length) else this private fun String.hasOrder(): Boolean = orderPattern.find(this)?.value?.isNotEmpty() ?: false // TODO: may be to throw an exception instead of returning null? private fun String.getOrder(): Int? { val find: MatchResult = orderPattern.find(this) ?: return null return find.value.removeSurrounding("(", ")").toInt() } // exception wrappers private fun pathNotFound(vararg path: String): LocationUnavailableException { throw LocationUnavailableException("Unable to find path \"${path.toList()}\"") } private fun multipleMatchingNodes(pathString: String, parentText: Any): LocationUnavailableException { throw LocationUnavailableException( "There is more than one node with value '$pathString' under \"$parentText\"") } companion object { val predicateEquality: FinderPredicate = { left: String, right: String -> left == right } val predicateWithVersion = { left: String, right: String -> val pattern = Regex(",\\s+\\(.*\\)$") if (right.contains(pattern)) left == right.dropLast(right.length - right.indexOfLast { it == ',' }) else left == right } } fun findPathToNode(node: String) = findPathToNodeByPredicate(node, predicateEquality) fun findPathToNodeWithVersion(node: String) = findPathToNodeByPredicate(node, predicateWithVersion) fun findPathToNodeByPredicate(node: String, predicate: FinderPredicate): TreePath{ // expandNodes() // Pause.pause(1000) //Wait for EDT thread to finish expanding val result: MutableList<String> = mutableListOf() var currentNode = jTree.model.root as DefaultMutableTreeNode val e = currentNode.preorderEnumeration() while (e.hasMoreElements()) { currentNode = e.nextElement() as DefaultMutableTreeNode if (predicate(currentNode.toString(), node)) { break } } result.add(0, currentNode.toString()) while (currentNode.parent != null) { currentNode = currentNode.parent as DefaultMutableTreeNode result.add(0, currentNode.toString()) } return findMatchingPathByPredicate(pathStrings = *result.toTypedArray(), predicate = predicate) } }
apache-2.0
7fff5ae5db7213a1a95e006822b16a63
36.406977
140
0.689569
4.628058
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/components/settings/conversation/ConversationSettingsViewModel.kt
1
16764
package org.thoughtcrime.securesms.components.settings.conversation import android.database.Cursor import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import org.signal.core.util.CursorUtil import org.signal.core.util.ThreadUtil import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.components.settings.conversation.preferences.ButtonStripPreference import org.thoughtcrime.securesms.components.settings.conversation.preferences.LegacyGroupPreference import org.thoughtcrime.securesms.database.AttachmentDatabase import org.thoughtcrime.securesms.database.RecipientDatabase import org.thoughtcrime.securesms.database.model.StoryViewState import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.groups.LiveGroup import org.thoughtcrime.securesms.groups.v2.GroupAddMembersResult import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.recipients.RecipientId import org.thoughtcrime.securesms.recipients.RecipientUtil import org.thoughtcrime.securesms.util.FeatureFlags import org.thoughtcrime.securesms.util.SingleLiveEvent import org.thoughtcrime.securesms.util.livedata.LiveDataUtil import org.thoughtcrime.securesms.util.livedata.Store import java.util.Optional sealed class ConversationSettingsViewModel( private val repository: ConversationSettingsRepository, specificSettingsState: SpecificSettingsState, ) : ViewModel() { private val openedMediaCursors = HashSet<Cursor>() @Volatile private var cleared = false protected val store = Store( ConversationSettingsState( specificSettingsState = specificSettingsState ) ) protected val internalEvents = SingleLiveEvent<ConversationSettingsEvent>() private val sharedMediaUpdateTrigger = MutableLiveData(Unit) val state: LiveData<ConversationSettingsState> = store.stateLiveData val events: LiveData<ConversationSettingsEvent> = internalEvents protected val disposable = CompositeDisposable() init { val threadId: LiveData<Long> = Transformations.distinctUntilChanged(Transformations.map(state) { it.threadId }) val updater: LiveData<Long> = LiveDataUtil.combineLatest(threadId, sharedMediaUpdateTrigger) { tId, _ -> tId } val sharedMedia: LiveData<Optional<Cursor>> = LiveDataUtil.mapAsync(SignalExecutors.BOUNDED, updater) { tId -> repository.getThreadMedia(tId) } store.update(sharedMedia) { cursor, state -> if (!cleared) { if (cursor.isPresent) { openedMediaCursors.add(cursor.get()) } val ids: List<Long> = cursor.map<List<Long>> { val result = mutableListOf<Long>() while (it.moveToNext()) { result.add(CursorUtil.requireLong(it, AttachmentDatabase.ROW_ID)) } result }.orElse(listOf()) state.copy( sharedMedia = cursor.orElse(null), sharedMediaIds = ids, sharedMediaLoaded = true, displayInternalRecipientDetails = repository.isInternalRecipientDetailsEnabled() ) } else { cursor.orElse(null).ensureClosed() state.copy(sharedMedia = null) } } } fun refreshSharedMedia() { sharedMediaUpdateTrigger.postValue(Unit) } open fun refreshRecipient(): Unit = error("This ViewModel does not support this interaction") abstract fun setMuteUntil(muteUntil: Long) abstract fun unmute() abstract fun block() abstract fun unblock() abstract fun onAddToGroup() abstract fun onAddToGroupComplete(selected: List<RecipientId>, onComplete: () -> Unit) abstract fun revealAllMembers() override fun onCleared() { cleared = true openedMediaCursors.forEach { it.ensureClosed() } store.clear() disposable.clear() } private fun Cursor?.ensureClosed() { if (this != null && !this.isClosed) { this.close() } } open fun initiateGroupUpgrade(): Unit = error("This ViewModel does not support this interaction") private class RecipientSettingsViewModel( private val recipientId: RecipientId, private val repository: ConversationSettingsRepository ) : ConversationSettingsViewModel( repository, SpecificSettingsState.RecipientSettingsState() ) { private val liveRecipient = Recipient.live(recipientId) init { disposable += StoryViewState.getForRecipientId(recipientId).subscribe { storyViewState -> store.update { it.copy(storyViewState = storyViewState) } } store.update(liveRecipient.liveData) { recipient, state -> state.copy( recipient = recipient, buttonStripState = ButtonStripPreference.State( isVideoAvailable = recipient.registered == RecipientDatabase.RegisteredState.REGISTERED && !recipient.isSelf && !recipient.isBlocked && !recipient.isReleaseNotes, isAudioAvailable = !recipient.isGroup && !recipient.isSelf && !recipient.isBlocked && !recipient.isReleaseNotes, isAudioSecure = recipient.registered == RecipientDatabase.RegisteredState.REGISTERED, isMuted = recipient.isMuted, isMuteAvailable = !recipient.isSelf, isSearchAvailable = true ), disappearingMessagesLifespan = recipient.expiresInSeconds, canModifyBlockedState = !recipient.isSelf && RecipientUtil.isBlockable(recipient), specificSettingsState = state.requireRecipientSettingsState().copy( contactLinkState = when { recipient.isSelf || recipient.isReleaseNotes -> ContactLinkState.NONE recipient.isSystemContact -> ContactLinkState.OPEN else -> ContactLinkState.ADD } ) ) } repository.getThreadId(recipientId) { threadId -> store.update { state -> state.copy(threadId = threadId) } } if (recipientId != Recipient.self().id) { repository.getGroupsInCommon(recipientId) { groupsInCommon -> store.update { state -> val recipientSettings = state.requireRecipientSettingsState() val canShowMore = !recipientSettings.groupsInCommonExpanded && groupsInCommon.size > 6 state.copy( specificSettingsState = recipientSettings.copy( allGroupsInCommon = groupsInCommon, groupsInCommon = if (!canShowMore) groupsInCommon else groupsInCommon.take(5), canShowMoreGroupsInCommon = canShowMore ) ) } } repository.hasGroups { hasGroups -> store.update { state -> val recipientSettings = state.requireRecipientSettingsState() state.copy( specificSettingsState = recipientSettings.copy( selfHasGroups = hasGroups ) ) } } repository.getIdentity(recipientId) { identityRecord -> store.update { state -> state.copy(specificSettingsState = state.requireRecipientSettingsState().copy(identityRecord = identityRecord)) } } } } override fun onAddToGroup() { repository.getGroupMembership(recipientId) { internalEvents.postValue(ConversationSettingsEvent.AddToAGroup(recipientId, it)) } } override fun onAddToGroupComplete(selected: List<RecipientId>, onComplete: () -> Unit) { } override fun revealAllMembers() { store.update { state -> state.copy( specificSettingsState = state.requireRecipientSettingsState().copy( groupsInCommon = state.requireRecipientSettingsState().allGroupsInCommon, groupsInCommonExpanded = true, canShowMoreGroupsInCommon = false ) ) } } override fun refreshRecipient() { repository.refreshRecipient(recipientId) } override fun setMuteUntil(muteUntil: Long) { repository.setMuteUntil(recipientId, muteUntil) } override fun unmute() { repository.setMuteUntil(recipientId, 0) } override fun block() { repository.block(recipientId) } override fun unblock() { repository.unblock(recipientId) } } private class GroupSettingsViewModel( private val groupId: GroupId, private val repository: ConversationSettingsRepository ) : ConversationSettingsViewModel(repository, SpecificSettingsState.GroupSettingsState(groupId)) { private val liveGroup = LiveGroup(groupId) init { disposable += repository.getStoryViewState(groupId).subscribe { storyViewState -> store.update { it.copy(storyViewState = storyViewState) } } val recipientAndIsActive = LiveDataUtil.combineLatest(liveGroup.groupRecipient, liveGroup.isActive) { r, a -> r to a } store.update(recipientAndIsActive) { (recipient, isActive), state -> state.copy( recipient = recipient, buttonStripState = ButtonStripPreference.State( isVideoAvailable = recipient.isPushV2Group && !recipient.isBlocked && isActive, isAudioAvailable = false, isAudioSecure = recipient.isPushV2Group, isMuted = recipient.isMuted, isMuteAvailable = true, isSearchAvailable = true ), canModifyBlockedState = RecipientUtil.isBlockable(recipient), specificSettingsState = state.requireGroupSettingsState().copy( legacyGroupState = getLegacyGroupState(recipient) ) ) } repository.getThreadId(groupId) { threadId -> store.update { state -> state.copy(threadId = threadId) } } store.update(liveGroup.selfCanEditGroupAttributes()) { selfCanEditGroupAttributes, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( canEditGroupAttributes = selfCanEditGroupAttributes ) ) } store.update(liveGroup.isSelfAdmin) { isSelfAdmin, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( isSelfAdmin = isSelfAdmin ) ) } store.update(liveGroup.expireMessages) { expireMessages, state -> state.copy( disappearingMessagesLifespan = expireMessages ) } store.update(liveGroup.selfCanAddMembers()) { canAddMembers, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( canAddToGroup = canAddMembers ) ) } store.update(liveGroup.fullMembers) { fullMembers, state -> val groupState = state.requireGroupSettingsState() val canShowMore = !groupState.groupMembersExpanded && fullMembers.size > 6 state.copy( specificSettingsState = groupState.copy( allMembers = fullMembers, members = if (!canShowMore) fullMembers else fullMembers.take(5), canShowMoreGroupMembers = canShowMore ) ) } store.update(liveGroup.isAnnouncementGroup) { announcementGroup, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( isAnnouncementGroup = announcementGroup ) ) } val isMessageRequestAccepted: LiveData<Boolean> = LiveDataUtil.mapAsync(liveGroup.groupRecipient) { r -> repository.isMessageRequestAccepted(r) } val descriptionState: LiveData<DescriptionState> = LiveDataUtil.combineLatest(liveGroup.description, isMessageRequestAccepted, ::DescriptionState) store.update(descriptionState) { d, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( groupDescription = d.description, groupDescriptionShouldLinkify = d.canLinkify, groupDescriptionLoaded = true ) ) } store.update(liveGroup.isActive) { isActive, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( canLeave = isActive && groupId.isPush ) ) } store.update(liveGroup.title) { title, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( groupTitle = title, groupTitleLoaded = true ) ) } store.update(liveGroup.groupLink) { groupLink, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( groupLinkEnabled = groupLink.isEnabled ) ) } store.update(repository.getMembershipCountDescription(liveGroup)) { description, state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( membershipCountDescription = description ) ) } } private fun getLegacyGroupState(recipient: Recipient): LegacyGroupPreference.State { val showLegacyInfo = recipient.requireGroupId().isV1 return if (showLegacyInfo && recipient.participants.size > FeatureFlags.groupLimits().hardLimit) { LegacyGroupPreference.State.TOO_LARGE } else if (showLegacyInfo) { LegacyGroupPreference.State.UPGRADE } else if (groupId.isMms) { LegacyGroupPreference.State.MMS_WARNING } else { LegacyGroupPreference.State.NONE } } override fun onAddToGroup() { repository.getGroupCapacity(groupId) { capacityResult -> if (capacityResult.getRemainingCapacity() > 0) { internalEvents.postValue( ConversationSettingsEvent.AddMembersToGroup( groupId, capacityResult.getSelectionWarning(), capacityResult.getSelectionLimit(), capacityResult.isAnnouncementGroup, capacityResult.getMembersWithoutSelf() ) ) } else { internalEvents.postValue(ConversationSettingsEvent.ShowGroupHardLimitDialog) } } } override fun onAddToGroupComplete(selected: List<RecipientId>, onComplete: () -> Unit) { repository.addMembers(groupId, selected) { ThreadUtil.runOnMain { onComplete() } when (it) { is GroupAddMembersResult.Success -> { if (it.newMembersInvited.isNotEmpty()) { internalEvents.postValue(ConversationSettingsEvent.ShowGroupInvitesSentDialog(it.newMembersInvited)) } if (it.numberOfMembersAdded > 0) { internalEvents.postValue(ConversationSettingsEvent.ShowMembersAdded(it.numberOfMembersAdded)) } } is GroupAddMembersResult.Failure -> internalEvents.postValue(ConversationSettingsEvent.ShowAddMembersToGroupError(it.reason)) } } } override fun revealAllMembers() { store.update { state -> state.copy( specificSettingsState = state.requireGroupSettingsState().copy( members = state.requireGroupSettingsState().allMembers, groupMembersExpanded = true, canShowMoreGroupMembers = false ) ) } } override fun setMuteUntil(muteUntil: Long) { repository.setMuteUntil(groupId, muteUntil) } override fun unmute() { repository.setMuteUntil(groupId, 0) } override fun block() { repository.block(groupId) } override fun unblock() { repository.unblock(groupId) } override fun initiateGroupUpgrade() { repository.getExternalPossiblyMigratedGroupRecipientId(groupId) { internalEvents.postValue(ConversationSettingsEvent.InitiateGroupMigration(it)) } } } class Factory( private val recipientId: RecipientId? = null, private val groupId: GroupId? = null, private val repository: ConversationSettingsRepository, ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return requireNotNull( modelClass.cast( when { recipientId != null -> RecipientSettingsViewModel(recipientId, repository) groupId != null -> GroupSettingsViewModel(groupId, repository) else -> error("One of RecipientId or GroupId required.") } ) ) } } private class DescriptionState( val description: String?, val canLinkify: Boolean ) }
gpl-3.0
959a02ca322a10ee571b99e430d069c9
33.142566
174
0.671916
5.128174
false
false
false
false
marius-m/wt4
app/src/main/java/lt/markmerkk/widgets/main/SidePaneStateProviderDrawer.kt
1
639
package lt.markmerkk.widgets.main import com.jfoenix.controls.JFXDrawer class SidePaneStateProviderDrawer( private val jfxDrawer: JFXDrawer ): SidePaneHandler.SidePaneStateProvider { override fun isOpen(): Boolean { val paneState = state() return paneState.isOpened || paneState.isOpening } override fun state(): SidePaneHandler.SidePaneState { return SidePaneHandler.SidePaneState( isOpening = jfxDrawer.isOpening, isOpened = jfxDrawer.isOpened, isClosing = jfxDrawer.isClosing, isClosed = jfxDrawer.isClosed ) } }
apache-2.0
e2e7be66ce9c198641f31a71a9d726fe
28.090909
57
0.660407
4.4375
false
false
false
false
Kerooker/rpg-npc-generator
app/src/main/java/me/kerooker/rpgnpcgenerator/repository/model/random/npc/NpcGenerators.kt
1
5366
package me.kerooker.rpgnpcgenerator.repository.model.random.npc import org.koin.core.KoinComponent import org.koin.dsl.module import kotlin.random.Random val npcGeneratorsModule = module { } @Suppress("TooManyFunctions") class NpcDataGenerator( private val nameGenerator: NameGenerator, private val nicknameGenerator: NicknameGenerator, private val professionGenerator: ProfessionGenerator, private val motivationGenerator: MotivationGenerator, private val personalityTraitGenerator: PersonalityTraitGenerator ) { fun generateFullName() = nameGenerator.random() + " " + nameGenerator.random() fun generateNickname() = nicknameGenerator.random() fun generateGender() = Gender.random() fun generateDistributedGender() = Gender.distributedRandom() fun generateSexuality() = Sexuality.random() fun generateDistributedSexuality() = Sexuality.distributedRandom() fun generateRace() = Race.random() fun generateDistributedRace() = Race.distributedRandom() fun generateAge() = Age.random() fun generateDistributedAge() = Age.distributedRandom() fun generateProfession(age: Age) = professionGenerator.random(age) fun generateMotivation() = motivationGenerator.random() fun generateAlignment() = Alignment.random() fun generateDistributedAlignment() = Alignment.distributedRandom() fun generatePersonalityTrait() = personalityTraitGenerator.random() fun generateRandomLanguage() = Language.random() fun generateCommonLanguage(excluding: List<Language>) = CommonLanguage.random(excluding) fun generateExoticLanguage(excluding: List<Language>) = ExoticLanguage.random(excluding) } class CompleteNpcGenerator( private val npcDataGenerator: NpcDataGenerator ) : KoinComponent { fun generate(): GeneratedNpc { val name = generateFullName() val nickname = generateNickname() val gender = generateGender() val sexuality = generateSexuality() val race = generateRace() val age = generateAge() val profession = generateProfession(age) val motivation = generateMotivation() val alignment = generateAlignment() val personalityTraits = generatePersonalityTraits() val languages = generateLanguages(race.racialLanguage) return GeneratedNpc( name, nickname, gender, sexuality, race, age, profession, motivation, alignment, personalityTraits, languages ) } private fun generateFullName() = npcDataGenerator.generateFullName() private fun generateNickname() = npcDataGenerator.generateNickname() private fun generateGender() = npcDataGenerator.generateDistributedGender() private fun generateSexuality() = npcDataGenerator.generateDistributedSexuality() private fun generateRace() = npcDataGenerator.generateDistributedRace() private fun generateAge() = npcDataGenerator.generateDistributedAge() private fun generateProfession(age: Age) = npcDataGenerator.generateProfession(age) private fun generateMotivation() = npcDataGenerator.generateMotivation() private fun generateAlignment() = npcDataGenerator.generateDistributedAlignment() private fun generatePersonalityTraits(): MutableList<String> { val list = MutableList(2) { npcDataGenerator.generatePersonalityTrait() } repeat(MaxAmountOfExtraPersonalityTraits) { if(hitsChance(ChanceOfExtraPersonalityTraits)) list += npcDataGenerator.generatePersonalityTrait() } return list } private fun generateLanguages(racialLanguage: Language?): MutableList<Language> { return mutableListOf<Language>() .tryToAddCommon() .tryToAddRacial(racialLanguage) .tryToAddExtraCommonLanguage(racialLanguage) .tryToAddExtraExoticLanguage(racialLanguage) } private fun MutableList<Language>.tryToAddCommon() = apply { if (hitsChance(ChanceOfSpeakingCommon)) this += CommonLanguage.Common } private fun MutableList<Language>.tryToAddRacial(racialLanguage: Language?) = apply { if(hitsChance(ChanceOfSpeakingRacial) && racialLanguage != null) this += racialLanguage } private fun MutableList<Language>.tryToAddExtraCommonLanguage(racialLanguage: Language?) = apply { if(hitsChance(ChanceOfExtraCommonLanguage)) this += npcDataGenerator.generateCommonLanguage(this + listOfNotNull(racialLanguage)) } private fun MutableList<Language>.tryToAddExtraExoticLanguage(racialLanguage: Language?) = apply { if(hitsChance(ChanceOfExtraExoticLanguage)) this += npcDataGenerator.generateExoticLanguage(this + listOfNotNull(racialLanguage)) } private fun hitsChance(chance: Double) = Random.nextDouble() <= chance companion object { private const val ChanceOfSpeakingCommon = 0.995 private const val ChanceOfSpeakingRacial = 0.995 private const val ChanceOfExtraCommonLanguage = 0.25 private const val ChanceOfExtraExoticLanguage = 0.05 private const val MaxAmountOfExtraPersonalityTraits = 3 private const val ChanceOfExtraPersonalityTraits = 0.25 } }
apache-2.0
be141eda194a37d3fd17ea08d576c66b
33.619355
102
0.715803
4.678291
false
false
false
false
anibyl/slounik
main/src/main/java/org/anibyl/slounik/dialogs/ArticleDialog.kt
1
3254
package org.anibyl.slounik.dialogs import android.app.Dialog import android.os.Bundle import android.support.v4.app.DialogFragment import android.text.method.ScrollingMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.widget.Button import android.widget.TextView import org.anibyl.slounik.Notifier import org.anibyl.slounik.R import org.anibyl.slounik.SlounikApplication import org.anibyl.slounik.core.copyToClipboard import org.anibyl.slounik.data.Article import org.anibyl.slounik.data.ArticlesInfo import org.anibyl.slounik.ui.ProgressBar import javax.inject.Inject /** * Dialog for the text of an article. * * @author Usievaład Kimajeŭ * @created 01.03.2015 */ class ArticleDialog : DialogFragment() { @Inject lateinit var notifier: Notifier private lateinit var article: Article override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) SlounikApplication.graph.inject(this) article = arguments?.getSerializable("article") as Article? ?: savedInstanceState?.getSerializable("article") as Article } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.article, container, false) val isLoadable = article.linkToFullDescription != null val title = view.findViewById(R.id.article_title) as TextView val dictionary = view.findViewById(R.id.article_dictionary) as TextView val description = view.findViewById(R.id.article_description) as TextView val closeButton = view.findViewById(R.id.article_button_close) as Button val loadButton = view.findViewById(R.id.article_button_load) as Button val progressBar = view.findViewById(R.id.article_progress) as ProgressBar title.text = article.title dictionary.text = article.dictionary description.text = article.spannedDescription description.movementMethod = ScrollingMovementMethod() description.setOnLongClickListener { context?.copyToClipboard(description.text) notifier.toast(R.string.toast_text_copied) true } closeButton.setOnClickListener { dismiss() } if (isLoadable) { loadButton.setOnClickListener { loadButton.isEnabled = false if (article.fullDescription == null) { progressBar.progressiveStart() article.loadArticleDescription { info: ArticlesInfo -> when (info.status) { ArticlesInfo.Status.SUCCESS -> description.text = article.spannedFullDescription else -> loadButton.isEnabled = true } progressBar.progressiveStop() } } else { description.text = article.spannedFullDescription } } } else { loadButton.visibility = View.GONE progressBar.visibility = View.GONE } isCancelable = true return view } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } } fun newArticleDialog(article: Article): ArticleDialog { val instance = ArticleDialog() val args = Bundle() args.putSerializable("article", article) instance.arguments = args return instance }
gpl-3.0
362c8f0d8fa3819edec2685896648920
27.526316
113
0.768758
3.825882
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/RowImpl.kt
1
16058
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.dsl.builder.impl import com.intellij.BundleBase import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.observable.properties.GraphProperty import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.panel.ComponentPanelBuilder import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ContextHelpLabel import com.intellij.ui.JBIntSpinner import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.UIBundle import com.intellij.ui.components.* import com.intellij.ui.components.fields.ExpandableTextField import com.intellij.ui.dsl.UiDslException import com.intellij.ui.dsl.builder.* import com.intellij.ui.dsl.builder.Cell import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.components.* import com.intellij.ui.dsl.gridLayout.Gaps import com.intellij.ui.dsl.gridLayout.VerticalGaps import com.intellij.ui.layout.* import com.intellij.ui.popup.PopupState import com.intellij.util.Function import com.intellij.util.MathUtil import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import java.awt.event.ActionEvent import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import java.util.* import javax.swing.* @ApiStatus.Internal internal open class RowImpl(private val dialogPanelConfig: DialogPanelConfig, private val panelContext: PanelContext, private val parent: PanelImpl, rowLayout: RowLayout) : Row { var rowLayout = rowLayout private set var resizableRow = false private set var rowComment: JComponent? = null private set var topGap: TopGap? = null private set /** * Used if topGap is not set, skipped for first row */ var internalTopGap = 0 var bottomGap: BottomGap? = null private set /** * Used if bottomGap is not set, skipped for last row */ var internalBottomGap = 0 val cells = mutableListOf<CellBaseImpl<*>?>() private var visible = true private var enabled = true override fun layout(rowLayout: RowLayout): RowImpl { this.rowLayout = rowLayout return this } override fun resizableRow(): RowImpl { resizableRow = true return this } override fun rowComment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int): Row { this.rowComment = ComponentPanelBuilder.createCommentComponent(comment, true, maxLineLength, true) return this } override fun rowComment(@NlsContexts.DetailedDescription comment: String, maxLineLength: Int, action: HyperlinkEventAction): RowImpl { this.rowComment = createComment(comment, maxLineLength, action) return this } override fun <T : JComponent> cell(component: T, viewComponent: JComponent): CellImpl<T> { val result = CellImpl(dialogPanelConfig, component, this, viewComponent) cells.add(result) return result } override fun <T : JComponent> cell(component: T): CellImpl<T> { return cell(component, component) } override fun cell() { cells.add(null) } override fun <T : JComponent> scrollCell(component: T): CellImpl<T> { return cell(component, JBScrollPane(component)) } fun cell(cell: CellBaseImpl<*>) { cells.add(cell) } override fun placeholder(): PlaceholderImpl { val result = PlaceholderImpl(this) cells.add(result) return result } override fun enabled(isEnabled: Boolean): RowImpl { enabled = isEnabled if (parent.isEnabled()) { doEnabled(enabled) } return this } fun enabledFromParent(parentEnabled: Boolean): RowImpl { doEnabled(parentEnabled && enabled) return this } fun isEnabled(): Boolean { return enabled && parent.isEnabled() } override fun enabledIf(predicate: ComponentPredicate): RowImpl { enabled(predicate()) predicate.addListener { enabled(it) } return this } override fun visible(isVisible: Boolean): RowImpl { visible = isVisible if (parent.isVisible()) { doVisible(visible) } return this } override fun visibleIf(predicate: ComponentPredicate): Row { visible(predicate()) predicate.addListener { visible(it) } return this } fun visibleFromParent(parentVisible: Boolean): RowImpl { doVisible(parentVisible && visible) return this } fun isVisible(): Boolean { return visible && parent.isVisible() } override fun topGap(topGap: TopGap): RowImpl { this.topGap = topGap return this } override fun bottomGap(bottomGap: BottomGap): RowImpl { this.bottomGap = bottomGap return this } override fun panel(init: Panel.() -> Unit): PanelImpl { val result = PanelImpl(dialogPanelConfig, parent.spacingConfiguration, this) result.init() cells.add(result) return result } override fun checkBox(@NlsContexts.Checkbox text: String): CellImpl<JBCheckBox> { return cell(JBCheckBox(text)) } override fun radioButton(@NlsContexts.RadioButton text: String): Cell<JBRadioButton> { return radioButton(text, null) } override fun radioButton(text: String, value: Any?): Cell<JBRadioButton> { val buttonsGroup = dialogPanelConfig.context.getButtonsGroup() ?: throw UiDslException( "Button group must be defined before using radio button") val result = cell(JBRadioButton(text)) buttonsGroup.add(result, value) return result } override fun button(@NlsContexts.Button text: String, actionListener: (event: ActionEvent) -> Unit): CellImpl<JButton> { val button = JButton(BundleBase.replaceMnemonicAmpersand(text)) button.addActionListener(actionListener) return cell(button) } override fun button(text: String, action: AnAction, actionPlace: String): Cell<JButton> { lateinit var result: CellImpl<JButton> result = button(text) { ActionUtil.invokeAction(action, result.component, actionPlace, null, null) } return result } override fun actionButton(action: AnAction, actionPlace: String): Cell<ActionButton> { val component = ActionButton(action, action.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) return cell(component) } override fun actionsButton(vararg actions: AnAction, actionPlace: String, icon: Icon): Cell<ActionButton> { val actionGroup = PopupActionGroup(arrayOf(*actions)) actionGroup.templatePresentation.icon = icon return cell(ActionButton(actionGroup, actionGroup.templatePresentation.clone(), actionPlace, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE)) } override fun <T> segmentedButton(options: Collection<T>, property: GraphProperty<T>, renderer: (T) -> String): Cell<SegmentedButtonToolbar> { val actionGroup = DefaultActionGroup(options.map { DeprecatedSegmentedButtonAction(it, property, renderer(it)) }) val toolbar = SegmentedButtonToolbar(actionGroup, parent.spacingConfiguration) toolbar.targetComponent = null // any data context is supported, suppress warning return cell(toolbar) } override fun <T> segmentedButton(items: Collection<T>, renderer: (T) -> String): SegmentedButton<T> { val result = SegmentedButtonImpl(this, renderer) result.items(items) cells.add(result) return result } override fun tabbedPaneHeader(items: Collection<String>): Cell<JBTabbedPane> { val tabbedPaneHeader = TabbedPaneHeader() for (item in items) { tabbedPaneHeader.add(item, JPanel()) } return cell(tabbedPaneHeader) } override fun slider(min: Int, max: Int, minorTickSpacing: Int, majorTickSpacing: Int): Cell<JSlider> { val slider = JSlider() UIUtil.setSliderIsFilled(slider, true) slider.paintLabels = true slider.paintTicks = true slider.paintTrack = true slider.minimum = min slider.maximum = max slider.minorTickSpacing = minorTickSpacing slider.majorTickSpacing = majorTickSpacing return cell(slider) } override fun label(text: String): CellImpl<JLabel> { return cell(Label(text)) } override fun labelHtml(@NlsContexts.Label text: String, action: HyperlinkEventAction): Cell<JEditorPane> { return text(removeHtml(text), MAX_LINE_LENGTH_WORD_WRAP, action) } override fun text(@NlsContexts.Label text: String, maxLineLength: Int, action: HyperlinkEventAction): Cell<JEditorPane> { val dslLabel = DslLabel(DslLabelType.LABEL) dslLabel.action = action dslLabel.maxLineLength = maxLineLength dslLabel.text = text return cell(dslLabel) } override fun comment(@NlsContexts.DetailedDescription text: String, maxLineLength: Int): Cell<JLabel> { return cell(ComponentPanelBuilder.createCommentComponent(text, true, maxLineLength, true)) } override fun comment(comment: String, maxLineLength: Int, action: HyperlinkEventAction): CellImpl<JEditorPane> { return cell(createComment(comment, maxLineLength, action)) } override fun commentNoWrap(text: String): Cell<JLabel> { return cell(ComponentPanelBuilder.createNonWrappingCommentComponent(text)) } override fun commentHtml(text: String, action: HyperlinkEventAction): Cell<JEditorPane> { return comment(text, MAX_LINE_LENGTH_WORD_WRAP, action) } override fun link(text: String, action: (ActionEvent) -> Unit): CellImpl<ActionLink> { return cell(ActionLink(text, action)) } override fun browserLink(text: String, url: String): CellImpl<BrowserLink> { return cell(BrowserLink(text, url)) } override fun <T> dropDownLink(item: T, items: List<T>, onSelected: ((T) -> Unit)?, updateText: Boolean): Cell<DropDownLink<T>> { return cell(DropDownLink(item, items, onSelect = { t -> onSelected?.let { it(t) } }, updateText = updateText)) } override fun icon(icon: Icon): CellImpl<JLabel> { return cell(JBLabel(icon)) } override fun contextHelp(description: String, title: String?): CellImpl<JLabel> { val result = if (title == null) ContextHelpLabel.create(description) else ContextHelpLabel.create(title, description) return cell(result) } override fun textField(): CellImpl<JBTextField> { val result = cell(JBTextField()) result.columns(COLUMNS_SHORT) return result } override fun textFieldWithBrowseButton(browseDialogTitle: String?, project: Project?, fileChooserDescriptor: FileChooserDescriptor, fileChosen: ((chosenFile: VirtualFile) -> String)?): Cell<TextFieldWithBrowseButton> { val result = cell(textFieldWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, fileChosen)) result.columns(COLUMNS_SHORT) return result } override fun expandableTextField(parser: Function<in String, out MutableList<String>>, joiner: Function<in MutableList<String>, String>): Cell<ExpandableTextField> { val result = cell(ExpandableTextField(parser, joiner)) result.columns(COLUMNS_SHORT) return result } override fun intTextField(range: IntRange?, keyboardStep: Int?): CellImpl<JBTextField> { val result = cell(JBTextField()) .validationOnInput { val value = it.text.toIntOrNull() when { value == null -> error(UIBundle.message("please.enter.a.number")) range != null && value !in range -> error(UIBundle.message("please.enter.a.number.from.0.to.1", range.first, range.last)) else -> null } } result.columns(COLUMNS_TINY) result.component.putClientProperty(DSL_INT_TEXT_RANGE_PROPERTY, range) keyboardStep?.let { result.component.addKeyListener(object : KeyAdapter() { override fun keyPressed(e: KeyEvent?) { val increment: Int = when (e?.keyCode) { KeyEvent.VK_UP -> keyboardStep KeyEvent.VK_DOWN -> -keyboardStep else -> return } var value = result.component.text.toIntOrNull() if (value != null) { value += increment if (range != null) { value = MathUtil.clamp(value, range.first, range.last) } result.component.text = value.toString() e.consume() } } }) } return result } override fun spinner(range: IntRange, step: Int): CellImpl<JBIntSpinner> { return cell(JBIntSpinner(range.first, range.first, range.last, step)) } override fun spinner(range: ClosedRange<Double>, step: Double): Cell<JSpinner> { return cell(JSpinner(SpinnerNumberModel(range.start, range.start, range.endInclusive, step))) } override fun textArea(): Cell<JBTextArea> { val textArea = JBTextArea() // Text area should have same margins as TextField. When margin is TestArea used then border is MarginBorder and margins are taken // into account twice, which is hard to workaround in current API. So use border instead textArea.border = JBEmptyBorder(3, 5, 3, 5) textArea.columns = COLUMNS_SHORT textArea.font = JBFont.regular() textArea.emptyText.setFont(JBFont.regular()) textArea.putClientProperty(DslComponentProperty.VISUAL_PADDINGS, Gaps.EMPTY) return scrollCell(textArea) } override fun <T> comboBox(model: ComboBoxModel<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> { val component = ComboBox(model) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } override fun <T> comboBox(items: Collection<T>, renderer: ListCellRenderer<in T?>?): Cell<ComboBox<T>> { val component = ComboBox(DefaultComboBoxModel(Vector(items))) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } override fun <T> comboBox(items: Array<T>, renderer: ListCellRenderer<T?>?): Cell<ComboBox<T>> { val component = ComboBox(items) component.renderer = renderer ?: SimpleListCellRenderer.create("") { it.toString() } return cell(component) } override fun customize(customRowGaps: VerticalGaps): Row { internalTopGap = customRowGaps.top internalBottomGap = customRowGaps.bottom topGap = null bottomGap = null return this } fun getIndent(): Int { return panelContext.indentCount * parent.spacingConfiguration.horizontalIndent } private fun doVisible(isVisible: Boolean) { for (cell in cells) { cell?.visibleFromParent(isVisible) } rowComment?.let { it.isVisible = isVisible } } private fun doEnabled(isEnabled: Boolean) { for (cell in cells) { cell?.enabledFromParent(isEnabled) } rowComment?.let { it.isEnabled = isEnabled } } } private class PopupActionGroup(private val actions: Array<AnAction>): ActionGroup(), DumbAware { private val popupState = PopupState.forPopup() init { isPopup = true templatePresentation.isPerformGroup = actions.isNotEmpty() } override fun getChildren(e: AnActionEvent?): Array<AnAction> = actions override fun actionPerformed(e: AnActionEvent) { if (popupState.isRecentlyHidden) { return } val popup = JBPopupFactory.getInstance().createActionGroupPopup(null, this, e.dataContext, JBPopupFactory.ActionSelectionAid.MNEMONICS, true) popupState.prepareToShow(popup) PopupUtil.showForActionButtonEvent(popup, e) } }
apache-2.0
562f3f3e6f02900da664008d0423c8d1
33.238806
158
0.713289
4.494263
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/util/TootTextEncoder.kt
1
10345
package jp.juggler.subwaytooter.util import android.content.Context import android.content.Intent import androidx.annotation.StringRes import jp.juggler.subwaytooter.ActText import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.util.notEmpty import java.util.* object TootTextEncoder { private fun StringBuilder.addAfterLine(text: CharSequence) { if (isNotEmpty() && this[length - 1] != '\n') { append('\n') } append(text) } private fun addHeader( context: Context, sb: StringBuilder, @StringRes keyStrId: Int, value: Any? ) { if (sb.isNotEmpty() && sb[sb.length - 1] != '\n') { sb.append('\n') } sb.addAfterLine(context.getString(keyStrId)) sb.append(": ") sb.append(value?.toString() ?: "(null)") } fun encodeStatus( intent: Intent, context: Context, accessInfo: SavedAccount, status: TootStatus ) { val sb = StringBuilder() addHeader(context, sb, R.string.send_header_url, status.url) addHeader( context, sb, R.string.send_header_date, TootStatus.formatTime(context, status.time_created_at, false) ) addHeader( context, sb, R.string.send_header_from_acct, accessInfo.getFullAcct(status.account) ) val sv: String = status.spoiler_text if (sv.isNotEmpty()) { addHeader(context, sb, R.string.send_header_content_warning, sv) } sb.addAfterLine("\n") intent.putExtra(ActText.EXTRA_CONTENT_START, sb.length) sb.append( DecodeOptions( context, accessInfo, mentions = status.mentions, authorDomain = status.account, ).decodeHTML(status.content) ) encodePolls(sb, context, status) intent.putExtra(ActText.EXTRA_CONTENT_END, sb.length) dumpAttachment(sb, status.media_attachments) sb.addAfterLine(String.format(Locale.JAPAN, "Status-Source: %s", status.json.toString(2))) sb.addAfterLine("") intent.putExtra(ActText.EXTRA_TEXT, sb.toString()) } fun encodeStatusForTranslate( context: Context, accessInfo: SavedAccount, status: TootStatus ): String { val sb = StringBuilder() status.spoiler_text.notEmpty()?.let { sb.append(it).append("\n\n") } sb.append( DecodeOptions( context, accessInfo, mentions = status.mentions, authorDomain = status.account, ).decodeHTML(status.content) ) encodePolls(sb, context, status) return sb.toString() } private fun dumpAttachment(sb: StringBuilder, src: ArrayList<TootAttachmentLike>?) { if (src == null) return var i = 0 for (ma in src) { ++i if (ma is TootAttachment) { sb.addAfterLine("\n") sb.addAfterLine(String.format(Locale.JAPAN, "Media-%d-Url: %s", i, ma.url)) sb.addAfterLine( String.format(Locale.JAPAN, "Media-%d-Remote-Url: %s", i, ma.remote_url) ) sb.addAfterLine( String.format(Locale.JAPAN, "Media-%d-Preview-Url: %s", i, ma.preview_url) ) sb.addAfterLine( String.format(Locale.JAPAN, "Media-%d-Text-Url: %s", i, ma.text_url) ) } else if (ma is TootAttachmentMSP) { sb.addAfterLine("\n") sb.addAfterLine( String.format(Locale.JAPAN, "Media-%d-Preview-Url: %s", i, ma.preview_url) ) } } } private fun encodePolls(sb: StringBuilder, context: Context, status: TootStatus) { val enquete = status.enquete ?: return val items = enquete.items ?: return val now = System.currentTimeMillis() val canVote = when (enquete.pollType) { // friends.nico の場合は本文に投票の選択肢が含まれるので // アプリ側での文字列化は不要 TootPollsType.FriendsNico -> return // MastodonとMisskeyは投票の選択肢が本文に含まれないので // アプリ側で文字列化する TootPollsType.Mastodon, TootPollsType.Notestock -> when { enquete.expired -> false now >= enquete.expired_at -> false enquete.ownVoted -> false else -> true } TootPollsType.Misskey -> enquete.ownVoted } sb.addAfterLine("\n") items.forEach { choice -> encodePollChoice(sb, context, enquete, canVote, choice) } when (enquete.pollType) { TootPollsType.Mastodon -> encodePollFooterMastodon(sb, context, enquete) else -> { } } } private fun encodePollChoice( sb: StringBuilder, context: Context, enquete: TootPolls, canVote: Boolean, item: TootPollsChoice ) { val text = when (enquete.pollType) { TootPollsType.Misskey -> { val sb2 = StringBuilder().append(item.decoded_text) if (enquete.ownVoted) { sb2.append(" / ") sb2.append(context.getString(R.string.vote_count_text, item.votes)) if (item.isVoted) sb2.append(' ').append(0x2713.toChar()) } sb2 } TootPollsType.FriendsNico -> { item.decoded_text } TootPollsType.Mastodon, TootPollsType.Notestock -> if (canVote) { item.decoded_text } else { val sb2 = StringBuilder().append(item.decoded_text) if (!canVote) { sb2.append(" / ") sb2.append( when (val v = item.votes) { null -> context.getString(R.string.vote_count_unavailable) else -> context.getString(R.string.vote_count_text, v) } ) } sb2 } } sb.addAfterLine(text) } private fun encodePollFooterMastodon( sb: StringBuilder, context: Context, enquete: TootPolls ) { val line = StringBuilder() val votes_count = enquete.votes_count ?: 0 when { votes_count == 1 -> line.append(context.getString(R.string.vote_1)) votes_count > 1 -> line.append(context.getString(R.string.vote_2, votes_count)) } when (val t = enquete.expired_at) { Long.MAX_VALUE -> { } else -> { if (line.isNotEmpty()) line.append(" ") line.append( context.getString( R.string.vote_expire_at, TootStatus.formatTime(context, t, false) ) ) } } sb.addAfterLine(line) } fun encodeAccount( intent: Intent, context: Context, accessInfo: SavedAccount, who: TootAccount ) { val sb = StringBuilder() intent.putExtra(ActText.EXTRA_CONTENT_START, sb.length) sb.append(who.display_name) sb.append("\n") sb.append("@") sb.append(accessInfo.getFullAcct(who)) sb.append("\n") intent.putExtra(ActText.EXTRA_CONTENT_START, sb.length) sb.append(who.url) intent.putExtra(ActText.EXTRA_CONTENT_END, sb.length) sb.addAfterLine("\n") sb.append( DecodeOptions( context, accessInfo, authorDomain = who, ).decodeHTML(who.note) ) sb.addAfterLine("\n") addHeader(context, sb, R.string.send_header_account_name, who.display_name) addHeader(context, sb, R.string.send_header_account_acct, accessInfo.getFullAcct(who)) addHeader(context, sb, R.string.send_header_account_url, who.url) addHeader(context, sb, R.string.send_header_account_image_avatar, who.avatar) addHeader( context, sb, R.string.send_header_account_image_avatar_static, who.avatar_static ) addHeader(context, sb, R.string.send_header_account_image_header, who.header) addHeader( context, sb, R.string.send_header_account_image_header_static, who.header_static ) addHeader(context, sb, R.string.send_header_account_created_at, who.created_at) addHeader(context, sb, R.string.send_header_account_statuses_count, who.statuses_count) if (!PrefB.bpHideFollowCount(App1.getAppState(context).pref)) { addHeader( context, sb, R.string.send_header_account_followers_count, who.followers_count ) addHeader( context, sb, R.string.send_header_account_following_count, who.following_count ) } addHeader(context, sb, R.string.send_header_account_locked, who.locked) sb.addAfterLine(String.format(Locale.JAPAN, "Account-Source: %s", who.json.toString(2))) sb.addAfterLine("") intent.putExtra(ActText.EXTRA_TEXT, sb.toString()) } }
apache-2.0
39f2bfe26cf16e14d49dda89554d6fbb
29.346626
98
0.516293
4.302737
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/dialog/ProgressDialogEx.kt
1
771
@file:Suppress("DEPRECATION") package jp.juggler.subwaytooter.dialog import android.app.ProgressDialog import android.content.Context import jp.juggler.util.runOnMainLooper class ProgressDialogEx(context: Context) : ProgressDialog(context) { companion object { const val STYLE_SPINNER = ProgressDialog.STYLE_SPINNER const val STYLE_HORIZONTAL = ProgressDialog.STYLE_HORIZONTAL } var isIndeterminateEx: Boolean get() = isIndeterminate set(value) { isIndeterminate = value } fun setMessageEx(msg: CharSequence?) = runOnMainLooper { super.setMessage(msg) } // synchronizedの中から呼ばれることがあるので、コルーチンではなくHandlerで制御する }
apache-2.0
3c158f8eb16a131547cb1e89dfc9f97c
27.625
84
0.704641
4.361963
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/lexer/PyLexerFStringHelper.kt
3
5779
// 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.jetbrains.python.lexer import com.intellij.psi.tree.IElementType import com.intellij.util.containers.Stack import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.psi.PyElementType import com.jetbrains.python.psi.PyStringLiteralUtil class PyLexerFStringHelper(private val myLexer: FlexLexerEx) { private val myFStringStates: Stack<FStringState> = Stack() fun handleFStringStartInFragment(): IElementType { val prefixAndQuotes = myLexer.yytext().toString() val (_, offset) = findFStringTerminator(prefixAndQuotes) if (offset == prefixAndQuotes.length) { return pushFString(prefixAndQuotes) } return PyTokenTypes.IDENTIFIER } fun handleFStringStart(): IElementType { return pushFString(myLexer.yytext().toString()) } private fun pushFString(prefixAndQuotes: String): PyElementType { val openingQuotes = prefixAndQuotes.substring(PyStringLiteralUtil.getPrefixLength(prefixAndQuotes)) myFStringStates.push(FStringState(myLexer.yystate(), myLexer.tokenStart, openingQuotes)) myLexer.yybegin(_PythonLexer.FSTRING) return PyTokenTypes.FSTRING_START } fun handleFStringEnd(): IElementType { val (type, offset) = findFStringTerminator(myLexer.yytext().toString()) return if (offset == 0) type!! else PyTokenTypes.FSTRING_TEXT } fun handleFragmentStart(): IElementType { myFStringStates.peek().fragmentStates.push(FragmentState(myLexer.yystate(), myLexer.tokenStart)) myLexer.yybegin(_PythonLexer.FSTRING_FRAGMENT) return PyTokenTypes.FSTRING_FRAGMENT_START } fun handleFragmentEnd(): IElementType { val state = myFStringStates.peek().fragmentStates.pop() myLexer.yybegin(state.oldState) return PyTokenTypes.FSTRING_FRAGMENT_END } fun handleLeftBracketInFragment(type: IElementType): IElementType { myFStringStates.peek().fragmentStates.peek().braceBalance++ return type } fun handleRightBracketInFragment(type: IElementType): IElementType { val activeFragmentState = myFStringStates.peek().fragmentStates.peek() if (activeFragmentState.braceBalance == 0 && type == PyTokenTypes.RBRACE) { return handleFragmentEnd() } else { activeFragmentState.braceBalance-- return type } } fun handleColonInFragment(): IElementType { if (myFStringStates.peek().fragmentStates.peek().braceBalance == 0) { myLexer.yybegin(_PythonLexer.FSTRING_FRAGMENT_FORMAT) return PyTokenTypes.FSTRING_FRAGMENT_FORMAT_START } else { return PyTokenTypes.COLON } } fun handleLineBreakInFragment(): IElementType { val text = myLexer.yytext().toString() // We will return a line break anyway, but we need to transit from FSTRING state of the lexer findFStringTerminator(text) return PyTokenTypes.LINE_BREAK } fun handleLineBreakInLiteralText(): IElementType { val text = myLexer.yytext().toString() val (_, offset) = findFStringTerminator(text) if (offset == text.length) { return PyTokenTypes.FSTRING_TEXT } return PyTokenTypes.LINE_BREAK } fun handleStringLiteral(stringLiteralType: IElementType): IElementType { val stringText = myLexer.yytext().toString() val prefixLength = PyStringLiteralUtil.getPrefixLength(stringText) val (type, offset) = findFStringTerminator(stringText) return when (offset) { 0 -> type!! prefixLength -> PyTokenTypes.IDENTIFIER else -> stringLiteralType } } private fun findFStringTerminator(text: String): Pair<IElementType?, Int> { var i = 0 while (i < text.length) { val c = text[i] if (c == '\\') { i += 2 continue } if (c == '\n') { val insideSingleQuoted = myFStringStates.any { it.openingQuotes.length == 1 } if (insideSingleQuoted) { if (i == 0) { // Terminate all f-strings and insert STATEMENT_BREAK at this point dropFStringStateWithAllNested(0) } pushBackToOrConsumeMatch(i, 1) return Pair(PyTokenTypes.LINE_BREAK, i) } } else { val nextThree = text.substring(i, Math.min(text.length, i + 3)) val lastWithMatchingQuotesIndex = myFStringStates.indexOfLast { nextThree.startsWith(it.openingQuotes) } if (lastWithMatchingQuotesIndex >= 0) { val state = myFStringStates[lastWithMatchingQuotesIndex] if (i == 0) { dropFStringStateWithAllNested(lastWithMatchingQuotesIndex) } pushBackToOrConsumeMatch(i, state.openingQuotes.length) return Pair(PyTokenTypes.FSTRING_END, i) } } i++ } return Pair(null, text.length) } private fun dropFStringStateWithAllNested(fStringIndex: Int) { myLexer.yybegin(myFStringStates[fStringIndex].oldState) myFStringStates.subList(fStringIndex, myFStringStates.size).clear() } private fun pushBackToOrConsumeMatch(matchOffset: Int, matchSize: Int) { if (matchOffset == 0) { myLexer.yypushback(myLexer.yylength() - matchSize) } else { myLexer.yypushback(myLexer.yylength() - matchOffset) } } fun reset() { // There is no need to be smarter about it, since LexerEditorHighlighter always resets // the lexer state to YYINITIAL where there can't be any f-strings. myFStringStates.clear() } private data class FStringState(val oldState: Int, val offset: Int, val openingQuotes: String) { val fragmentStates = Stack<FragmentState>() } private data class FragmentState(val oldState: Int, val offset: Int) { var braceBalance: Int = 0 } }
apache-2.0
d44b4f1b08a0d585a0a4154c571af0b1
33.195266
140
0.701159
4.035615
false
false
false
false
paplorinc/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/PartiallyExcludedChangesTest.kt
3
12110
// 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.openapi.vcs import com.intellij.openapi.vcs.BaseLineStatusTrackerTestCase.Companion.parseInput import com.intellij.openapi.vcs.ex.ExclusionState.* import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker class PartiallyExcludedChangesTest : BasePartiallyExcludedChangesTest() { private val FILE_1 = "file1.txt" private val FILE_2 = "file2.txt" fun `test operations without trackers`() { setHolderPaths("file1", "file2", "file3", "file4", "file5") assertIncluded() toggle("file1") assertIncluded("file1") toggle("file1", "file3") assertIncluded("file1", "file3") toggle("file1", "file3", "file5") assertIncluded("file1", "file3", "file5") toggle("file1", "file5") assertIncluded("file3") toggle("file3") assertIncluded() include("file3") assertIncluded("file3") include("file3", "file5") assertIncluded("file3", "file5") exclude("file5") assertIncluded("file3") "file3".assertExcludedState(ALL_INCLUDED) "file4".assertExcludedState(ALL_EXCLUDED) } fun `test operations with fully tracked file`() { setHolderPaths(FILE_1, "file1", "file2", "file3") assertIncluded() val file = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a_b1_c_d1_e") refreshCLM() file.withOpenedEditor { val tracker = file.tracker as PartialLocalLineStatusTracker lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded() toggle(FILE_1, "file1") assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) exclude(FILE_1) assertIncluded("file1") FILE_1.assertExcludedState(ALL_EXCLUDED) include(FILE_1, "file2") assertIncluded(FILE_1, "file1", "file2") tracker.setExcludedFromCommit(true) assertIncluded(FILE_1, "file1", "file2") waitExclusionStateUpdate() assertIncluded("file1", "file2") tracker.setExcludedFromCommit(false) assertIncluded("file1", "file2") waitExclusionStateUpdate() assertIncluded(FILE_1, "file1", "file2") } } fun `test operations with partially tracked file`() { setHolderPaths(FILE_1, "file1", "file2", "file3") assertIncluded() val file = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a_b1_c_d1_e") refreshCLM() file.withOpenedEditor { val tracker = file.tracker as PartialLocalLineStatusTracker lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded() tracker.exclude(0, false) assertIncluded(FILE_1) FILE_1.assertExcludedState(PARTIALLY) toggle("file1") assertIncluded(FILE_1, "file1") toggle(FILE_1) assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) tracker.exclude(0, true) assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(PARTIALLY) toggle(FILE_1, "file1") assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) tracker.exclude(0, true) assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(PARTIALLY) toggle(FILE_1, "file3") assertIncluded(FILE_1, "file1", "file3") FILE_1.assertExcludedState(ALL_INCLUDED) } } fun `test operations with unchanged tracked file`() { setHolderPaths(FILE_1, "file1", "file2", "file3") assertIncluded() val file = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a_b_c_d_e") refreshCLM() file.withOpenedEditor { val tracker = file.tracker as PartialLocalLineStatusTracker lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded() FILE_1.assertExcludedState(ALL_EXCLUDED, NO_CHANGES) toggle("file1") assertIncluded("file1") toggle(FILE_1) assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED, NO_CHANGES) toggle(FILE_1, "file1") assertIncluded() FILE_1.assertExcludedState(ALL_EXCLUDED, NO_CHANGES) toggle(FILE_1, "file1") assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED, NO_CHANGES) tracker.setExcludedFromCommit(true) waitExclusionStateUpdate() FILE_1.assertExcludedState(ALL_INCLUDED, NO_CHANGES) } } fun `test state transition with trackers`() { setHolderPaths(FILE_1, FILE_2, "file1", "file2", "file3") assertIncluded() val file1 = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a1_b_c_d_e1") val file2 = addLocalFile(FILE_2, "a_b_c_d_e") setBaseVersion(FILE_2, "a2_b_c_d_e2") refreshCLM() include(FILE_1, "file1") assertIncluded(FILE_1, "file1") file1.withOpenedEditor { file2.withOpenedEditor { assertIncluded(FILE_1, "file1") lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) } } assertIncluded(FILE_1, "file1") releaseUnneededTrackers() waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") assertNull(file1.tracker) assertNull(file2.tracker) } fun `test state transition with empty trackers`() { setHolderPaths(FILE_1, FILE_2, "file1", "file2", "file3") assertIncluded() val file1 = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a_b_c_d_e") val file2 = addLocalFile(FILE_2, "a_b_c_d_e") setBaseVersion(FILE_2, "a_b_c_d_e") refreshCLM() include(FILE_1, "file1") assertIncluded(FILE_1, "file1") file1.withOpenedEditor { file2.withOpenedEditor { assertIncluded(FILE_1, "file1") lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED, NO_CHANGES) FILE_2.assertExcludedState(ALL_EXCLUDED, NO_CHANGES) } } assertIncluded(FILE_1, "file1") releaseUnneededTrackers() waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") assertNull(file1.tracker) assertNull(file2.tracker) } fun `test state transition with trackers - partially excluded changes`() { setHolderPaths(FILE_1, FILE_2, "file1", "file2", "file3") assertIncluded() val file1 = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a1_b_c_d_e1") val file2 = addLocalFile(FILE_2, "a_b_c_d_e") setBaseVersion(FILE_2, "a2_b_c_d_e2") refreshCLM() include(FILE_1, "file1") assertIncluded(FILE_1, "file1") file1.withOpenedEditor { file2.withOpenedEditor { val tracker1 = file1.tracker as PartialLocalLineStatusTracker val tracker2 = file2.tracker as PartialLocalLineStatusTracker assertIncluded(FILE_1, "file1") lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) tracker1.exclude(0, true) tracker2.exclude(0, false) assertIncluded(FILE_1, FILE_2, "file1") FILE_1.assertExcludedState(PARTIALLY) FILE_2.assertExcludedState(PARTIALLY) tracker1.exclude(0, false) assertIncluded(FILE_1, FILE_2, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(PARTIALLY) } } assertIncluded(FILE_1, FILE_2, "file1") releaseUnneededTrackers() waitExclusionStateUpdate() assertNull(file1.tracker) assertNotNull(file2.tracker) assertIncluded(FILE_1, FILE_2, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(PARTIALLY) lstm.resetExcludedFromCommitMarkers() assertNull(file1.tracker) assertNull(file2.tracker) assertIncluded(FILE_1, FILE_2, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_INCLUDED) } fun `test state transition with trackers - changelists`() { createChangelist("Test") setHolderPaths(FILE_1, FILE_2, "file1", "file2", "file3") assertIncluded() val file1 = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a1_b_c1_d_e1") val file2 = addLocalFile(FILE_2, "a_b_c_d_e") setBaseVersion(FILE_2, "a2_b_c2_d_e2") refreshCLM() include(FILE_1, "file1") assertIncluded(FILE_1, "file1") file1.withOpenedEditor { file2.withOpenedEditor { val tracker1 = file1.tracker as PartialLocalLineStatusTracker val tracker2 = file2.tracker as PartialLocalLineStatusTracker lstm.waitUntilBaseContentsLoaded() tracker1.moveTo(2, "Test") tracker2.moveTo(2, "Test") waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) tracker1.exclude(2, true) tracker2.exclude(2, false) assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) tracker1.moveTo(2, DEFAULT) tracker2.moveTo(2, DEFAULT) waitExclusionStateUpdate() assertIncluded(FILE_1, FILE_2, "file1") FILE_1.assertExcludedState(PARTIALLY) FILE_2.assertExcludedState(PARTIALLY) tracker1.moveTo(2, "Test") tracker2.moveTo(2, "Test") waitExclusionStateUpdate() assertIncluded(FILE_1, "file1") FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) } } assertIncluded(FILE_1, "file1") } fun `test state transition with trackers - initialisation`() { setHolderPaths(FILE_1, FILE_2, "file1", "file2", "file3") assertIncluded() val file1 = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a1_b_c1_d_e1") val file2 = addLocalFile(FILE_2, "a_b_c_d_e") setBaseVersion(FILE_2, "a2_b_c2_d_e2") refreshCLM() file1.withOpenedEditor { file2.withOpenedEditor { val tracker1 = file1.tracker as PartialLocalLineStatusTracker val tracker2 = file2.tracker as PartialLocalLineStatusTracker include(FILE_1) assertIncluded(FILE_1) FILE_1.assertExcludedState(ALL_INCLUDED, NO_CHANGES) FILE_2.assertExcludedState(ALL_EXCLUDED, NO_CHANGES) assertNull(tracker1.getRanges()) assertNull(tracker2.getRanges()) lstm.waitUntilBaseContentsLoaded() waitExclusionStateUpdate() assertIncluded(FILE_1) FILE_1.assertExcludedState(ALL_INCLUDED) FILE_2.assertExcludedState(ALL_EXCLUDED) } } } fun `test state tracking on file modifications`() { setHolderPaths(FILE_1) include(FILE_1) assertIncluded(FILE_1) val file = addLocalFile(FILE_1, "a_b_c_d_e") setBaseVersion(FILE_1, "a1_b_c1_d_e1") refreshCLM() file.withOpenedEditor { val tracker = file.tracker as PartialLocalLineStatusTracker lstm.waitUntilBaseContentsLoaded() tracker.exclude(0, true) tracker.exclude(2, true) tracker.assertExcluded(0, true) tracker.assertExcluded(1, false) tracker.assertExcluded(2, true) runCommand { file.document.replaceString(0, 1, "a2") } tracker.assertExcluded(0, true) tracker.assertExcluded(1, false) tracker.assertExcluded(2, true) runCommand { file.document.replaceString(4, 5, "2") } assertEquals(tracker.getRanges()!!.size, 2) tracker.assertExcluded(0, false) tracker.assertExcluded(1, true) runCommand { file.document.replaceString(4, 5, parseInput("2_i_i_i_i")) } assertEquals(tracker.getRanges()!!.size, 2) tracker.assertExcluded(0, false) tracker.assertExcluded(1, true) } } }
apache-2.0
c16cbd0fc6e5579763877a823069ba7f
28.043165
140
0.665648
3.588148
false
false
false
false
paplorinc/intellij-community
platform/credential-store/src/kdbx/kdbx.kt
3
2921
// 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.credentialStore.kdbx import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.io.inputStream import org.bouncycastle.crypto.SkippingStreamCipher import org.bouncycastle.crypto.engines.Salsa20Engine import org.bouncycastle.crypto.params.KeyParameter import org.bouncycastle.crypto.params.ParametersWithIV import java.io.InputStream import java.nio.file.Path import java.security.MessageDigest import java.util.* import java.util.zip.GZIPInputStream // https://gist.github.com/lgg/e6ccc6e212d18dd2ecd8a8c116fb1e45 @Throws(IncorrectMasterPasswordException::class) internal fun loadKdbx(file: Path, credentials: KeePassCredentials): KeePassDatabase { return file.inputStream().buffered().use { readKeePassDatabase(credentials, it) } } private fun readKeePassDatabase(credentials: KeePassCredentials, inputStream: InputStream): KeePassDatabase { val kdbxHeader = KdbxHeader(inputStream) val decryptedInputStream = kdbxHeader.createDecryptedStream(credentials.key, inputStream) val startBytes = FileUtilRt.loadBytes(decryptedInputStream, 32) if (!Arrays.equals(startBytes, kdbxHeader.streamStartBytes)) { throw IncorrectMasterPasswordException() } var resultInputStream: InputStream = HashedBlockInputStream(decryptedInputStream) if (kdbxHeader.compressionFlags == KdbxHeader.CompressionFlags.GZIP) { resultInputStream = GZIPInputStream(resultInputStream) } val element = JDOMUtil.load(resultInputStream) element.getChild(KdbxDbElementNames.root)?.let { rootElement -> XmlProtectedValueTransformer(createSalsa20StreamCipher(kdbxHeader.protectedStreamKey)).processEntries(rootElement) } return KeePassDatabase(element) } internal class KdbxPassword(password: ByteArray) : KeePassCredentials { companion object { // KdbxPassword hashes value, so, it can be cleared before file write (to reduce time when master password exposed in memory) fun createAndClear(value: ByteArray): KeePassCredentials { val result = KdbxPassword(value) value.fill(0) return result } } override val key: ByteArray init { val md = sha256MessageDigest() key = md.digest(md.digest(password)) } } internal fun sha256MessageDigest(): MessageDigest = MessageDigest.getInstance("SHA-256") // 0xE830094B97205D2A private val SALSA20_IV = byteArrayOf(-24, 48, 9, 75, -105, 32, 93, 42) internal fun createSalsa20StreamCipher(key: ByteArray): SkippingStreamCipher { val streamCipher = Salsa20Engine() val keyParameter = KeyParameter(sha256MessageDigest().digest(key)) streamCipher.init(true /* doesn't matter, Salsa20 encryption and decryption is completely symmetrical */, ParametersWithIV(keyParameter, SALSA20_IV)) return streamCipher }
apache-2.0
0b2ab300d98c1096ed0c2162bae8048e
39.583333
151
0.79596
4.172857
false
false
false
false
deso88/TinyGit
src/main/kotlin/hamburg/remme/tinygit/gui/component/Chart.kt
1
1534
package hamburg.remme.tinygit.gui.component import hamburg.remme.tinygit.gui.builder.addClass import hamburg.remme.tinygit.gui.builder.label import javafx.scene.layout.Pane import javafx.scene.layout.Region private const val DEFAULT_STYLE_CLASS = "chart" private const val TITLE_STYLE_CLASS = "title" abstract class Chart(title: String) : Region() { private val titleLabel = label { addClass(TITLE_STYLE_CLASS) text = title } private val chartContent = object : Pane() { override fun layoutChildren() { layoutChartChildren(snapSizeX(width), snapSizeY(height)) } } protected val chartChildren get() = chartContent.children!! init { addClass(DEFAULT_STYLE_CLASS) chartContent.isManaged = false children.addAll(titleLabel, chartContent) } override fun layoutChildren() { var top = snappedTopInset() val left = snappedLeftInset() val bottom = snappedBottomInset() val right = snappedRightInset() val titleHeight = snapSizeY(titleLabel.prefHeight(width - left - right)) titleLabel.resizeRelocate(left, top, width - left - right, titleHeight) top += titleHeight + titleLabel.insets.top + titleLabel.insets.bottom // TODO: with insets? chartContent.resizeRelocate(left, top, width - left - right, height - top - bottom) } protected fun requestChartLayout() = chartContent.requestLayout() abstract fun layoutChartChildren(width: Double, height: Double) }
bsd-3-clause
c015cd830f58c865327bf654a7a08c42
31.638298
99
0.6897
4.382857
false
false
false
false
google/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/CompletionBindingContextProvider.kt
2
8114
// 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.completion import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiErrorElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener import org.jetbrains.kotlin.idea.caches.trackers.PureKotlinCodeBlockModificationListener import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.CompositeBindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.lang.ref.SoftReference import java.util.* class CompletionBindingContextProvider(project: Project) { private val LOG = Logger.getInstance(CompletionBindingContextProvider::class.java) @get:TestOnly var TEST_LOG: StringBuilder? = null companion object { fun getInstance(project: Project): CompletionBindingContextProvider = project.service() var ENABLED = true } private class CompletionData( val block: KtBlockExpression, val prevStatement: KtExpression?, val psiElementsBeforeAndAfter: List<PsiElementData>, val bindingContext: BindingContext, val moduleDescriptor: ModuleDescriptor, val statementResolutionScope: LexicalScope, val statementDataFlowInfo: DataFlowInfo, val debugText: String ) private data class PsiElementData(val element: PsiElement, val level: Int) private class DataHolder { private var reference: SoftReference<CompletionData>? = null var data: CompletionData? get() = reference?.get() set(value) { reference = value?.let { SoftReference(it) } } } private var prevCompletionDataCache: CachedValue<DataHolder> = CachedValuesManager.getManager(project).createCachedValue( { CachedValueProvider.Result.create( DataHolder(), KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker ) }, false ) fun getBindingContext(position: PsiElement, resolutionFacade: ResolutionFacade): BindingContext = if (ENABLED) { _getBindingContext(position, resolutionFacade) } else { resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance<KtElement>(), BodyResolveMode.PARTIAL_FOR_COMPLETION) } private fun _getBindingContext(position: PsiElement, resolutionFacade: ResolutionFacade): BindingContext { val inStatement = position.findStatementInBlock() val block = inStatement?.parent as KtBlockExpression? val prevStatement = inStatement?.siblings(forward = false, withItself = false)?.firstIsInstanceOrNull<KtExpression>() val modificationScope = inStatement?.let { PureKotlinCodeBlockModificationListener.getInsideCodeBlockModificationScope(it)?.element } val psiElementsBeforeAndAfter = modificationScope?.let { collectPsiElementsBeforeAndAfter(modificationScope, inStatement) } val prevCompletionData = prevCompletionDataCache.value.data when { prevCompletionData == null -> log("No up-to-date data from previous completion\n") block != prevCompletionData.block -> log("Not in the same block\n") prevStatement != prevCompletionData.prevStatement -> log("Previous statement is not the same\n") psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter -> log("PSI-tree has changed inside current scope\n") prevCompletionData.moduleDescriptor != resolutionFacade.moduleDescriptor -> log("ModuleDescriptor has been reset") inStatement.isTooComplex() -> log("Current statement is too complex to use optimization\n") else -> { log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n") LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"") //TODO: expected type? val statementContext = inStatement.analyzeInContext( scope = prevCompletionData.statementResolutionScope, contextExpression = block, dataFlowInfo = prevCompletionData.statementDataFlowInfo, isStatement = true ) // we do not update prevCompletionDataCache because the same data should work return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext)) } } val bindingContext = resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance<KtElement>(), BodyResolveMode.PARTIAL_FOR_COMPLETION) prevCompletionDataCache.value.data = if (block != null && modificationScope != null) { val resolutionScope = inStatement.getResolutionScope(bindingContext, resolutionFacade) val dataFlowInfo = bindingContext.getDataFlowInfoBefore(inStatement) CompletionData( block, prevStatement, psiElementsBeforeAndAfter!!, bindingContext, resolutionFacade.moduleDescriptor, resolutionScope, dataFlowInfo, debugText = position.text ) } else { null } return bindingContext } private fun log(message: String) { TEST_LOG?.append(message) LOG.debug(message) } private fun collectPsiElementsBeforeAndAfter(scope: PsiElement, statement: KtExpression): List<PsiElementData> { return ArrayList<PsiElementData>().apply { addElementsInTree(scope, 0, statement) } } private fun MutableList<PsiElementData>.addElementsInTree(root: PsiElement, initialLevel: Int, skipSubtree: PsiElement) { if (root == skipSubtree) return add(PsiElementData(root, initialLevel)) var child = root.firstChild while (child != null) { if (child !is PsiWhiteSpace && child !is PsiComment && child !is PsiErrorElement) { addElementsInTree(child, initialLevel + 1, skipSubtree) } child = child.nextSibling } } private fun PsiElement.findStatementInBlock(): KtExpression? { return parents.filterIsInstance<KtExpression>().firstOrNull { it.parent is KtBlockExpression } } private fun KtExpression.isTooComplex(): Boolean { return anyDescendantOfType<KtBlockExpression> { it.statements.size > 1 } } }
apache-2.0
c5a24003245c0153b965639c718adb72
44.077778
158
0.709021
5.369954
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInstaller.kt
1
7396
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.updateSettings.impl import com.intellij.ide.IdeBundle import com.intellij.ide.util.DelegatingProgressIndicator import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.BuildNumber import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.io.HttpRequests import com.intellij.util.io.copy import com.intellij.util.system.CpuArch import java.io.File import java.io.IOException import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.util.zip.ZipException import java.util.zip.ZipFile import javax.swing.UIManager internal object UpdateInstaller { const val UPDATER_MAIN_CLASS = "com.intellij.updater.Runner" private val LOG = logger<UpdateInstaller>() private const val PATCH_FILE_NAME = "patch-file.zip" private const val UPDATER_ENTRY = "com/intellij/updater/Runner.class" private val patchesUrl: URL get() = URL(System.getProperty("idea.patches.url") ?: ApplicationInfoEx.getInstanceEx().updateUrls!!.patchesUrl) @JvmStatic @Throws(IOException::class) fun downloadPatchChain(chain: List<BuildNumber>, indicator: ProgressIndicator): List<File> { indicator.text = IdeBundle.message("update.downloading.patch.progress") val files = mutableListOf<File>() val product = ApplicationInfo.getInstance().build.productCode val jdk = getRuntimeSuffix() val share = 1.0 / (chain.size - 1) for (i in 1 until chain.size) { val from = chain[i - 1].withoutProductCode().asString() val to = chain[i].withoutProductCode().asString() val patchName = "${product}-${from}-${to}-patch${jdk}-${PatchInfo.OS_SUFFIX}.jar" val patchFile = File(getTempDir(), patchName) val url = URL(patchesUrl, patchName).toString() val partIndicator = object : DelegatingProgressIndicator(indicator) { override fun setFraction(fraction: Double) { super.setFraction((i - 1) * share + fraction / share) } } LOG.info("downloading ${url}") HttpRequests.request(url).gzip(false).saveToFile(patchFile, partIndicator) try { ZipFile(patchFile).use { if (it.getEntry(PATCH_FILE_NAME) == null || it.getEntry(UPDATER_ENTRY) == null) { throw IOException("Corrupted patch file: ${patchFile.name}") } } } catch (e: ZipException) { throw IOException("Corrupted patch file: ${patchFile.name}", e) } files += patchFile } return files } @JvmStatic @RequiresBackgroundThread fun downloadPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): List<PluginDownloader> { indicator.text = IdeBundle.message("update.downloading.plugins.progress") UpdateChecker.saveDisabledToUpdatePlugins() val disabledToUpdate = UpdateChecker.disabledToUpdate val readyToInstall = mutableListOf<PluginDownloader>() for (downloader in downloaders) { try { if (downloader.id !in disabledToUpdate && downloader.prepareToInstall(indicator)) { readyToInstall += downloader } indicator.checkCanceled() } catch (e: ProcessCanceledException) { throw e } catch (e: Exception) { LOG.info(e) } } return readyToInstall } @JvmStatic @RequiresBackgroundThread fun installPluginUpdates(downloaders: Collection<PluginDownloader>, indicator: ProgressIndicator): Boolean { val downloadedPluginUpdates = downloadPluginUpdates(downloaders, indicator) if (downloadedPluginUpdates.isEmpty()) { return false } ProgressManager.getInstance().executeNonCancelableSection { for (downloader in downloadedPluginUpdates) { try { downloader.install() } catch (e: Exception) { LOG.info(e) } } } return true } @JvmStatic fun cleanupPatch() { val tempDir = getTempDir() if (tempDir.exists()) FileUtil.delete(tempDir) } @JvmStatic @Throws(IOException::class) fun preparePatchCommand(patchFiles: List<File>, indicator: ProgressIndicator): Array<String> { indicator.text = IdeBundle.message("update.preparing.patch.progress") val tempDir = getTempDir() if (FileUtil.isAncestor(PathManager.getHomePath(), tempDir.path, true)) { throw IOException("Temp directory inside installation: $tempDir") } if (!(tempDir.exists() || tempDir.mkdirs())) { throw IOException("Cannot create temp directory: $tempDir") } var java = System.getProperty("java.home") if (PathManager.isUnderHomeDirectory(Path.of(java))) { val javaCopy = File(tempDir, "jre") if (javaCopy.exists()) FileUtil.delete(javaCopy) FileUtil.copyDir(File(java), javaCopy) val jnf = File(java, "../Frameworks/JavaNativeFoundation.framework") if (jnf.isDirectory) { val jnfCopy = File(tempDir, "Frameworks/JavaNativeFoundation.framework") if (jnfCopy.exists()) FileUtil.delete(jnfCopy) FileUtil.copyDir(jnf, jnfCopy) } java = javaCopy.path } val args = mutableListOf<String>() if (SystemInfo.isWindows && !Files.isWritable(Path.of(PathManager.getHomePath()))) { val launcher = PathManager.findBinFile("launcher.exe") val elevator = PathManager.findBinFile("elevator.exe") // "launcher" depends on "elevator" if (launcher != null && elevator != null && Files.isExecutable(launcher) && Files.isExecutable(elevator)) { args.add(launcher.copy(tempDir.toPath().resolve(launcher.fileName)).toString()) elevator.copy(tempDir.toPath().resolve(elevator.fileName)) } } args += File(java, if (SystemInfo.isWindows) "bin\\java.exe" else "bin/java").path args += "-Xmx${2000}m" args += "-cp" args += patchFiles.last().path args += "-Djna.nosys=true" args += "-Djna.boot.library.path=" args += "-Djna.debug_load=true" args += "-Djna.debug_load.jna=true" args += "-Djava.io.tmpdir=${tempDir.path}" args += "-Didea.updater.log=${PathManager.getLogPath()}" args += "-Dswing.defaultlaf=${UIManager.getSystemLookAndFeelClassName()}" args += UPDATER_MAIN_CLASS args += if (patchFiles.size == 1) "install" else "batch-install" args += PathManager.getHomePath() if (patchFiles.size > 1) { args += patchFiles.joinToString(File.pathSeparator) } return args.toTypedArray() } private fun getTempDir() = File(PathManager.getTempPath(), "patch-update") private fun getRuntimeSuffix(): String = when { SystemInfo.isUnix && !SystemInfo.isMac && !Files.isDirectory(Path.of(PathManager.getHomePath(), "jbr")) -> "-no-jbr" (SystemInfo.isMac || SystemInfo.isLinux || SystemInfo.isWindows) && CpuArch.isArm64() -> "-aarch64" else -> "" } }
apache-2.0
45b85be917be134d64144efe12ba1380
35.433498
126
0.696322
4.255466
false
false
false
false
aguba/HighNoon
app/src/main/java/com/rafaelmallare/highnoon/Skills.kt
1
680
package com.rafaelmallare.highnoon /** * Created by Rj on 7/17/2017. */ open class Skill(val name: String, val parentStat1: BaseStat, val parentStat2: BaseStat? = null, val untrained: Boolean = false) { var lvl = -1 val costToNextLvl get() = if (lvl < 10) lvl + 6 else 0 var description = "Skill Description" fun lvlUp(): Boolean { if (lvl >= 10) return false lvl++ return false } } class ClassSkill(name: String, parentStat1: BaseStat, parentStat2: BaseStat? = null, untrained: Boolean = false, val requiredClasses: List<String> = listOf<String>()) : Skill(name, parentStat1, parentStat2, untrained)
agpl-3.0
cbcd342b53a482a9ba04d4d548d37740
28.608696
130
0.642647
3.560209
false
false
false
false
fluidsonic/fluid-json
annotation-processor/test-cases/1/output-expected/json/decoding/DefaultSecondaryConstructorPrimaryNotPresentJsonCodec.kt
1
2226
package json.decoding import codecProvider.CustomCodingContext import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.missingPropertyError import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readFromMapByElementValue import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeBooleanOrNull import io.fluidsonic.json.writeByteOrNull import io.fluidsonic.json.writeCharOrNull import io.fluidsonic.json.writeDoubleOrNull import io.fluidsonic.json.writeFloatOrNull import io.fluidsonic.json.writeIntOrNull import io.fluidsonic.json.writeIntoMap import io.fluidsonic.json.writeLongOrNull import io.fluidsonic.json.writeMapElement import io.fluidsonic.json.writeShortOrNull import io.fluidsonic.json.writeStringOrNull import io.fluidsonic.json.writeValueOrNull import kotlin.Unit internal object DefaultSecondaryConstructorPrimaryNotPresentJsonCodec : AbstractJsonCodec<DefaultSecondaryConstructorPrimaryNotPresent, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<DefaultSecondaryConstructorPrimaryNotPresent>): DefaultSecondaryConstructorPrimaryNotPresent { var _value = 0 var value_isPresent = false readFromMapByElementValue { key -> when (key) { "value" -> { _value = readInt() value_isPresent = true } else -> skipValue() } } value_isPresent || missingPropertyError("value") return DefaultSecondaryConstructorPrimaryNotPresent( `value` = _value ) } public override fun JsonEncoder<CustomCodingContext>.encode(`value`: DefaultSecondaryConstructorPrimaryNotPresent): Unit { writeIntoMap { writeMapElement("value", string = value.`value`) } } }
apache-2.0
56d5a7b316f4d8d599f85dfe4b9b535f
32.223881
120
0.827942
4.706131
false
false
false
false
udevbe/westford
compositor/src/main/kotlin/org/westford/nativ/libxcb/xcb_expose_event_t.kt
3
1535
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.libxcb import org.freedesktop.jaccall.CType import org.freedesktop.jaccall.Field import org.freedesktop.jaccall.Struct @Struct(Field(name = "response_type", type = CType.CHAR), Field(name = "pad0", type = CType.CHAR), Field(name = "sequence", type = CType.SHORT), Field(name = "window", type = CType.INT), Field(name = "x", type = CType.SHORT), Field(name = "y", type = CType.SHORT), Field(name = "width", type = CType.SHORT), Field(name = "height", type = CType.SHORT), Field(name = "count", type = CType.SHORT)) class xcb_expose_event_t : Struct_xcb_expose_event_t()
agpl-3.0
3b3f0bbbce9226252dfb981322aa0609
36.439024
89
0.637785
4.071618
false
false
false
false
io53/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/bluetooth/di/BluetoothScannerInjectionModule.kt
1
3181
package com.ruuvi.station.bluetooth.di import android.app.PendingIntent import android.content.Context import android.content.Intent import com.ruuvi.station.R import com.ruuvi.station.bluetooth.BluetoothInteractor import com.ruuvi.station.bluetooth.BluetoothLibrary import com.ruuvi.station.bluetooth.DefaultOnTagFoundListener import com.ruuvi.station.bluetooth.IRuuviTagScanner import com.ruuvi.station.bluetooth.util.ScannerSettings import com.ruuvi.station.startup.ui.StartupActivity import com.ruuvi.station.util.BackgroundScanModes import com.ruuvi.station.app.preferences.Preferences import com.ruuvi.station.bluetooth.domain.BluetoothStateWatcher import com.ruuvi.station.util.TimeUtils import com.ruuvi.station.util.test.FakeScanResultsSender import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.instance import org.kodein.di.generic.singleton object BluetoothScannerInjectionModule { val module = Kodein.Module(BluetoothScannerInjectionModule.javaClass.name) { bind<BluetoothInteractor>() with singleton { BluetoothLibrary.getBluetoothInteractor(instance(), instance(), instance()) } bind<BluetoothStateWatcher>() with singleton { BluetoothStateWatcher(instance()) } bind<IRuuviTagScanner.OnTagFoundListener>() with singleton { instance<DefaultOnTagFoundListener>() } bind<DefaultOnTagFoundListener>() with singleton { DefaultOnTagFoundListener(instance(), instance(), instance()) } bind<FakeScanResultsSender>() with singleton { FakeScanResultsSender(instance()) } bind<ScannerSettings>() with singleton { object : ScannerSettings { var context = instance<Context>() var prefs = Preferences(context) override fun allowBackgroundScan(): Boolean { return prefs.backgroundScanMode != BackgroundScanModes.DISABLED } override fun getBackgroundScanInterval(): Long { return prefs.backgroundScanInterval * 1000L } override fun getNotificationIconId() = R.drawable.ic_ruuvi_bgscan_icon override fun getNotificationTitle(): String { val seconds = prefs.backgroundScanInterval val stringMessage = context.getString(R.string.scanner_notification_scanning_every) return "$stringMessage ${TimeUtils.convertSecondsToText(context, seconds)}" } override fun getNotificationText() = context.getString(R.string.scanner_notification_message) override fun getNotificationPendingIntent(): PendingIntent? { val resultIntent = Intent(context, StartupActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } return PendingIntent.getActivity( context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT ) } } } } }
mit
edbf6e49dd69d73b5879dfa6b83ecce4
42
130
0.675888
5.163961
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/operations/ModuleOperationExecutor.kt
1
7034
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations import com.intellij.buildsystem.model.OperationFailure import com.intellij.openapi.project.Project import com.jetbrains.packagesearch.intellij.plugin.extensibility.DependencyOperationMetadata import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModuleOperationProvider import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.util.logDebug import com.jetbrains.packagesearch.intellij.plugin.util.logTrace import com.jetbrains.packagesearch.intellij.plugin.util.logWarn import com.jetbrains.packagesearch.intellij.plugin.util.nullIfBlank import com.intellij.buildsystem.model.unified.UnifiedDependency internal class ModuleOperationExecutor(private val project: Project) { fun doOperation(operation: PackageSearchOperation<*>) = try { when (operation) { is PackageSearchOperation.Package.Install -> installPackage(operation) is PackageSearchOperation.Package.Remove -> removePackage(operation) is PackageSearchOperation.Package.ChangeInstalled -> changePackage(operation) is PackageSearchOperation.Repository.Install -> installRepository(operation) is PackageSearchOperation.Repository.Remove -> removeRepository(operation) } null } catch (e: OperationException) { logWarn("ModuleOperationExecutor#doOperation()", e) { "Failure while performing operation $operation" } PackageSearchOperationFailure(operation, e) } private fun installPackage(operation: PackageSearchOperation.Package.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installPackage()") { "Installing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addDependencyToProject( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), project = project, virtualFile = projectModule.buildFile ).throwIfAnyFailures() logTrace("ModuleOperationExecutor#installPackage()") { "Package ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removePackage(operation: PackageSearchOperation.Package.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removePackage()") { "Removing package ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeDependencyFromProject( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model), project = project, virtualFile = projectModule.buildFile ).throwIfAnyFailures() logTrace("ModuleOperationExecutor#removePackage()") { "Package ${operation.model.displayName} removed from ${projectModule.name}" } } private fun changePackage(operation: PackageSearchOperation.Package.ChangeInstalled) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#changePackage()") { "Changing package ${operation.model.displayName} in ${projectModule.name}" } operationProvider.updateDependencyInProject( operationMetadata = dependencyOperationMetadataFrom(projectModule, operation.model, operation.newVersion, operation.newScope), project = project, virtualFile = projectModule.buildFile ).throwIfAnyFailures() logTrace("ModuleOperationExecutor#changePackage()") { "Package ${operation.model.displayName} changed in ${projectModule.name}" } } private fun dependencyOperationMetadataFrom( projectModule: ProjectModule, dependency: UnifiedDependency, newVersion: PackageVersion? = null, newScope: PackageScope? = null ) = DependencyOperationMetadata( module = projectModule, groupId = dependency.coordinates.groupId ?: throw OperationException.InvalidPackage(dependency), artifactId = dependency.coordinates.artifactId ?: throw OperationException.InvalidPackage(dependency), currentVersion = dependency.coordinates.version, currentScope = dependency.scope, newVersion = newVersion?.versionName.nullIfBlank() ?: dependency.coordinates.version, newScope = newScope?.scopeName.nullIfBlank() ?: dependency.scope ) private fun installRepository(operation: PackageSearchOperation.Repository.Install) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#installRepository()") { "Installing repository ${operation.model.displayName} in ${projectModule.name}" } operationProvider.addRepositoryToProject(operation.model, project, projectModule.buildFile) .throwIfAnyFailures() logTrace("ModuleOperationExecutor#installRepository()") { "Repository ${operation.model.displayName} installed in ${projectModule.name}" } } private fun removeRepository(operation: PackageSearchOperation.Repository.Remove) { val projectModule = operation.projectModule val operationProvider = ProjectModuleOperationProvider.forProjectModuleType(projectModule.moduleType) ?: throw OperationException.unsupportedBuildSystem(projectModule) logDebug("ModuleOperationExecutor#removeRepository()") { "Removing repository ${operation.model.displayName} from ${projectModule.name}" } operationProvider.removeRepositoryFromProject(operation.model, project, projectModule.buildFile) .throwIfAnyFailures() logTrace("ModuleOperationExecutor#removeRepository()") { "Repository ${operation.model.displayName} removed from ${projectModule.name}" } } private fun List<OperationFailure<*>>.throwIfAnyFailures() { when { isEmpty() -> return size > 1 -> throw IllegalStateException("A single operation resulted in multiple failures") } } }
apache-2.0
9c5ad9a45b0359d79d678c86a7ab5ec6
54.385827
147
0.756326
6.213781
false
false
false
false
zdary/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewLoadingDecorator.kt
11
1757
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.intention.impl.preview import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.LoadingDecorator import com.intellij.ui.ColorUtil import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.components.panels.OpaquePanel import com.intellij.util.ui.AsyncProcessIcon import java.awt.BorderLayout import java.awt.Color import java.awt.FlowLayout import javax.swing.JLabel import javax.swing.JPanel internal class IntentionPreviewLoadingDecorator(panel: JPanel, project: Project) : LoadingDecorator(panel, project, 500, false, AsyncProcessIcon("IntentionPreviewProcessLoading")) { override fun customizeLoadingLayer(parent: JPanel, text: JLabel, icon: AsyncProcessIcon): NonOpaquePanel { val editorBackground = EditorColorsManager.getInstance().globalScheme.defaultBackground val iconNonOpaquePanel = OpaquePanel(FlowLayout(FlowLayout.RIGHT, 2, 2)) .apply { add(icon, BorderLayout.NORTH) background = editorBackground } icon.background = editorBackground.withAlpha(0.0) icon.isOpaque = true val opaquePanel = OpaquePanel() opaquePanel.background = editorBackground.withAlpha(0.6) val nonOpaquePanel = NonOpaquePanel(BorderLayout()) nonOpaquePanel.add(iconNonOpaquePanel, BorderLayout.EAST) nonOpaquePanel.add(opaquePanel, BorderLayout.CENTER) parent.layout = BorderLayout() parent.add(nonOpaquePanel) return nonOpaquePanel } fun Color.withAlpha(alpha: Double) = ColorUtil.withAlpha(this, alpha) }
apache-2.0
8b0e071446cc5ca01da0afbb37cbc434
38.954545
140
0.789983
4.470738
false
false
false
false
JuliusKunze/kotlin-native
klib/src/main/kotlin/org/jetbrains/kotlin/cli/klib/main.kt
1
6253
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.cli.klib import kotlin.system.exitProcess // TODO: Extract these as a shared jar? import org.jetbrains.kotlin.backend.konan.library.impl.* import org.jetbrains.kotlin.backend.konan.library.KonanLibrarySearchPathResolver import org.jetbrains.kotlin.konan.file.File import org.jetbrains.kotlin.konan.target.TargetManager fun printUsage() { println("Usage: klib <command> <library> <options>") println("where the commands are:") println("\tinfo\tgeneral information about the library") println("\tinstall\tinstall the library to the local repository") println("\tcontents\tlist contents of the library") println("\tremove\tremove the library from the local repository") println("and the options are:") println("\t-repository <path>\twork with the specified repository") println("\t-target <name>\tinspect specifics of the given target") } private fun parseArgs(args: Array<String>): Map<String, List<String>> { val commandLine = mutableMapOf<String, MutableList<String>>() for (index in 0..args.size - 1 step 2) { val key = args[index] if (key[0] != '-') { throw IllegalArgumentException("Expected a flag with initial dash: $key") } if (index + 1 == args.size) { throw IllegalArgumentException("Expected an value after $key") } val value = listOf(args[index + 1]) commandLine[key]?.addAll(value) ?: commandLine.put(key, value.toMutableList()) } return commandLine } class Command(args: Array<String>){ init { if (args.size < 2) { printUsage() exitProcess(0) } } val verb = args[0] val library = args[1] val options = parseArgs(args.drop(2).toTypedArray()) } fun warn(text: String) { println("warning: $text") } fun error(text: String) { println("error: $text") exitProcess(1) } // TODO: Get rid of the hardcoded path. val defaultRepository = File(File.userHome, ".konan/klib") class Library(val name: String, val requestedRepository: String?, val target: String) { val repository = requestedRepository?.File() ?: defaultRepository fun info() { val library = libraryInRepoOrCurrentDir(repository, name) val reader = LibraryReaderImpl(library, currentAbiVersion) val headerAbiVersion = reader.abiVersion val moduleName = ModuleDeserializer(reader.moduleHeaderData).moduleName println("") println("Resolved to: ${reader.libraryName.File().absolutePath}") println("Module name: $moduleName") println("ABI version: $headerAbiVersion") val targets = reader.targetList.joinToString(", ") print("Available targets: $targets\n") } fun install() { Library(File(name).name.removeSuffix(".klib"), requestedRepository, target).remove(true) val library = ZippedKonanLibrary(libraryInCurrentDir(name)) val newLibDir = File(repository, library.libraryName.File().name) newLibDir.mkdirs() library.unpackTo(newLibDir) } fun remove(blind: Boolean = false) { if (!repository.exists) error("Repository does not exist: $repository") val reader = try { val library = libraryInRepo(repository, name) if (blind) warn("Removing The previously installed $name from $repository.") UnzippedKonanLibrary(library) } catch (e: Throwable) { if (!blind) println(e.message) null } reader?.libDir?.deleteRecursively() } fun contents() { val reader = LibraryReaderImpl(libraryInRepoOrCurrentDir(repository, name), currentAbiVersion) val printer = PrettyPrinter( reader.moduleHeaderData, {name -> reader.packageMetadata(name)}) printer.packageFragmentNameList.forEach{ printer.printPackageFragment(it) } } } // TODO: need to do something here. val currentAbiVersion = 1 fun libraryInRepo(repository: File, name: String): File { val resolver = KonanLibrarySearchPathResolver( repositories = listOf(repository.absolutePath), targetManager = null, distributionKlib = null, localKonanDir = null, skipCurrentDir = true ) return resolver.resolve(name) } fun libraryInCurrentDir(name: String): File { val resolver = KonanLibrarySearchPathResolver( repositories = emptyList(), targetManager = null, distributionKlib = null, localKonanDir = null ) return resolver.resolve(name) } fun libraryInRepoOrCurrentDir(repository: File, name: String): File { val resolver = KonanLibrarySearchPathResolver( repositories = listOf(repository.absolutePath), targetManager = null, distributionKlib = null, localKonanDir = null ) return resolver.resolve(name) } fun main(args: Array<String>) { val command = Command(args) val targetManager = TargetManager(command.options["-target"]?.last()) val target = targetManager.targetName val repository = command.options["-repository"]?.last() val library = Library(command.library, repository, target) warn("IMPORTANT: the library format is unstable now. It can change with any new git commit without warning!") when (command.verb) { "contents" -> library.contents() "info" -> library.info() "install" -> library.install() "remove" -> library.remove() else -> error("Unknown command ${command.verb}.") } }
apache-2.0
0124c492fe92d7492bf83e613583d909
32.438503
113
0.661602
4.422207
false
false
false
false
AndroidX/androidx
external/paparazzi/paparazzi/src/main/java/app/cash/paparazzi/internal/MatrixMatrixMultiplicationInterceptor.kt
3
1564
package app.cash.paparazzi.internal // Sampled from https://cs.android.com/android/platform/superproject/+/master:external/robolectric-shadows/shadows/framework/src/main/java/org/robolectric/shadows/ShadowOpenGLMatrix.java;l=10-67 object MatrixMatrixMultiplicationInterceptor { @Suppress("unused") @JvmStatic fun intercept( result: FloatArray, resultOffset: Int, lhs: FloatArray, lhsOffset: Int, rhs: FloatArray, rhsOffset: Int ) { require(resultOffset + 16 <= result.size) { "resultOffset + 16 > result.length" } require(lhsOffset + 16 <= lhs.size) { "lhsOffset + 16 > lhs.length" } require(rhsOffset + 16 <= rhs.size) { "rhsOffset + 16 > rhs.length" } for (i in 0..3) { val rhs_i0 = rhs[I(i, 0, rhsOffset)] var ri0 = lhs[I(0, 0, lhsOffset)] * rhs_i0 var ri1 = lhs[I(0, 1, lhsOffset)] * rhs_i0 var ri2 = lhs[I(0, 2, lhsOffset)] * rhs_i0 var ri3 = lhs[I(0, 3, lhsOffset)] * rhs_i0 for (j in 1..3) { val rhs_ij = rhs[I(i, j, rhsOffset)] ri0 += lhs[I(j, 0, lhsOffset)] * rhs_ij ri1 += lhs[I(j, 1, lhsOffset)] * rhs_ij ri2 += lhs[I(j, 2, lhsOffset)] * rhs_ij ri3 += lhs[I(j, 3, lhsOffset)] * rhs_ij } result[I(i, 0, resultOffset)] = ri0 result[I(i, 1, resultOffset)] = ri1 result[I(i, 2, resultOffset)] = ri2 result[I(i, 3, resultOffset)] = ri3 } } @Suppress("FunctionName") private fun I(i: Int, j: Int, offset: Int): Int { // #define I(_i, _j) ((_j)+ 4*(_i)) return offset + j + 4 * i } }
apache-2.0
f7be03f45db02c1fe4c5d9948b152e89
35.372093
194
0.595269
2.950943
false
false
false
false
AndroidX/androidx
glance/glance/src/androidMain/kotlin/androidx/glance/text/Text.kt
3
2572
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.text import androidx.annotation.RestrictTo import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.glance.Emittable import androidx.glance.GlanceModifier import androidx.glance.GlanceNode import androidx.glance.text.TextDefaults.defaultTextStyle import androidx.glance.unit.ColorProvider /** * Adds a text view to the glance view. * * @param text The text to be displayed. * @param modifier [GlanceModifier] to apply to this layout node. * @param style [TextStyle]] configuration for the text such as color, font, text align etc. * @param maxLines An optional maximum number of lines for the text to span, wrapping if * necessary. If the text exceeds the given number of lines, it will be truncated. */ @Composable fun Text( text: String, modifier: GlanceModifier = GlanceModifier, style: TextStyle = defaultTextStyle(), maxLines: Int = Int.MAX_VALUE, ) { GlanceNode( factory = ::EmittableText, update = { this.set(text) { this.text = it } this.set(modifier) { this.modifier = it } this.set(style) { this.style = it } this.set(maxLines) { this.maxLines = it } } ) } object TextDefaults { val defaultTextColor = ColorProvider(Color.Black) fun defaultTextStyle(): TextStyle = TextStyle(color = defaultTextColor) } /** @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class EmittableText : Emittable { override var modifier: GlanceModifier = GlanceModifier var text: String = "" var style: TextStyle? = null var maxLines: Int = Int.MAX_VALUE override fun copy(): Emittable = EmittableText().also { it.modifier = modifier it.text = text it.style = style it.maxLines = it.maxLines } override fun toString(): String = "EmittableText($text, style=$style, modifier=$modifier, maxLines=$maxLines)" }
apache-2.0
918564614894e8acf746a6e007f36038
31.974359
92
0.704899
4.182114
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/IndexedPropertyTransformationSupport.kt
32
2339
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.transformations.indexedProperty import com.intellij.psi.PsiType import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags.PUBLIC_MASK import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils.getGetterNameNonBoolean import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils.getSetterName import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport import org.jetbrains.plugins.groovy.transformations.TransformationContext import org.jetbrains.plugins.groovy.transformations.plusAssign class IndexedPropertyTransformationSupport : AstTransformationSupport { override fun applyTransformation(context: TransformationContext) { for (field in context.fields) { if (!field.isProperty) continue PsiImplUtil.getAnnotation(field, indexedPropertyFqn) ?: continue val componentType = field.getIndexedComponentType() ?: continue val fieldName = field.name context += context.memberBuilder.method(getGetterNameNonBoolean(fieldName)) { addModifier(PUBLIC_MASK) returnType = componentType addParameter("index", PsiType.INT) navigationElement = field originInfo = indexedPropertyOriginInfo methodKind = indexedMethodKind } context += context.memberBuilder.method(getSetterName(fieldName)) { addModifier(PUBLIC_MASK) returnType = PsiType.VOID addParameter("index", PsiType.INT) addParameter("value", componentType) navigationElement = field originInfo = indexedPropertyOriginInfo methodKind = indexedMethodKind } } } }
apache-2.0
9854833dc7bbc917d4089f409e8db364
40.767857
96
0.760581
4.687375
false
false
false
false
fabmax/kool
kool-core/src/jsMain/kotlin/de/fabmax/kool/platform/webgl/LoadedTextureWebGl.kt
1
3862
package de.fabmax.kool.platform.webgl import de.fabmax.kool.pipeline.AddressMode import de.fabmax.kool.pipeline.FilterMethod import de.fabmax.kool.pipeline.LoadedTexture import de.fabmax.kool.pipeline.TextureProps import de.fabmax.kool.platform.JsContext import de.fabmax.kool.platform.WebGL2RenderingContext.Companion.TEXTURE_3D import de.fabmax.kool.platform.WebGL2RenderingContext.Companion.TEXTURE_WRAP_R import de.fabmax.kool.util.logW import org.khronos.webgl.WebGLRenderingContext.Companion.CLAMP_TO_EDGE import org.khronos.webgl.WebGLRenderingContext.Companion.LINEAR import org.khronos.webgl.WebGLRenderingContext.Companion.LINEAR_MIPMAP_LINEAR import org.khronos.webgl.WebGLRenderingContext.Companion.MIRRORED_REPEAT import org.khronos.webgl.WebGLRenderingContext.Companion.NEAREST import org.khronos.webgl.WebGLRenderingContext.Companion.NEAREST_MIPMAP_NEAREST import org.khronos.webgl.WebGLRenderingContext.Companion.REPEAT import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_MAG_FILTER import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_MIN_FILTER import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_WRAP_S import org.khronos.webgl.WebGLRenderingContext.Companion.TEXTURE_WRAP_T import org.khronos.webgl.WebGLTexture import kotlin.math.min class LoadedTextureWebGl(val ctx: JsContext, val target: Int, val texture: WebGLTexture?, estimatedSize: Int) : LoadedTexture { val texId = nextTexId++ var isDestroyed = false private set override var width = 0 override var height = 0 override var depth = 0 init { ctx.engineStats.textureAllocated(texId, estimatedSize) } fun setSize(width: Int, height: Int, depth: Int) { this.width = width this.height = height this.depth = depth } fun applySamplerProps(props: TextureProps) { val gl = ctx.gl gl.bindTexture(target, texture) gl.texParameteri(target, TEXTURE_MIN_FILTER, props.minFilter.glMinFilterMethod(props.mipMapping)) gl.texParameteri(target, TEXTURE_MAG_FILTER, props.magFilter.glMagFilterMethod()) gl.texParameteri(target, TEXTURE_WRAP_S, props.addressModeU.glAddressMode()) gl.texParameteri(target, TEXTURE_WRAP_T, props.addressModeV.glAddressMode()) if (target == TEXTURE_3D) { gl.texParameteri(target, TEXTURE_WRAP_R, props.addressModeW.glAddressMode()) } val anisotropy = min(props.maxAnisotropy, ctx.glCapabilities.maxAnisotropy) if (anisotropy > 1) { gl.texParameteri(target, ctx.glCapabilities.glTextureMaxAnisotropyExt, anisotropy) } if (anisotropy > 1 && (props.minFilter == FilterMethod.NEAREST || props.magFilter == FilterMethod.NEAREST)) { logW { "Texture filtering is NEAREST but anisotropy is $anisotropy (> 1)" } } } override fun dispose() { if (!isDestroyed) { isDestroyed = true ctx.gl.deleteTexture(texture) ctx.engineStats.textureDeleted(texId) } } private fun FilterMethod.glMinFilterMethod(mipMapping: Boolean): Int { return when(this) { FilterMethod.NEAREST -> if (mipMapping) NEAREST_MIPMAP_NEAREST else NEAREST FilterMethod.LINEAR -> if (mipMapping) LINEAR_MIPMAP_LINEAR else LINEAR } } private fun FilterMethod.glMagFilterMethod(): Int { return when (this) { FilterMethod.NEAREST -> NEAREST FilterMethod.LINEAR -> LINEAR } } private fun AddressMode.glAddressMode(): Int { return when(this) { AddressMode.CLAMP_TO_EDGE -> CLAMP_TO_EDGE AddressMode.MIRRORED_REPEAT -> MIRRORED_REPEAT AddressMode.REPEAT -> REPEAT } } companion object { private var nextTexId = 1L } }
apache-2.0
bbacf7c919822ce2a09dfa1c64017003
37.63
127
0.714656
4.014553
false
false
false
false
mdaniel/intellij-community
platform/vcs-impl/src/com/intellij/vcs/commit/CommitModeManager.kt
1
7792
// 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.vcs.commit import com.intellij.ide.ApplicationInitializedListener import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager.getApplication import com.intellij.openapi.application.ConfigImportHelper.isNewUser import com.intellij.openapi.application.ModalityState import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsChangeListener import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.registry.RegistryValue import com.intellij.openapi.util.registry.RegistryValueListener import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.impl.VcsEP import com.intellij.openapi.vcs.impl.VcsInitObject import com.intellij.openapi.vcs.impl.VcsStartupActivity import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.SimpleMessageBusConnection import com.intellij.util.messages.Topic import com.intellij.vcs.commit.NonModalCommitUsagesCollector.logStateChanged import org.jetbrains.annotations.CalledInAny import java.util.* private const val TOGGLE_COMMIT_UI = "vcs.non.modal.commit.toggle.ui" private val isToggleCommitUi get() = AdvancedSettings.getBoolean(TOGGLE_COMMIT_UI) private val isForceNonModalCommit get() = Registry.get("vcs.force.non.modal.commit") private val appSettings get() = VcsApplicationSettings.getInstance() internal fun AnActionEvent.getProjectCommitMode(): CommitMode? = project?.let { CommitModeManager.getInstance(it).getCurrentCommitMode() } internal class NonModalCommitCustomization : ApplicationInitializedListener { override suspend fun execute() { if (!isNewUser()) { return } PropertiesComponent.getInstance().setValue(KEY, true) appSettings.COMMIT_FROM_LOCAL_CHANGES = true logStateChanged(null) } companion object { private const val KEY = "NonModalCommitCustomization.IsApplied" internal fun isNonModalCustomizationApplied(): Boolean = PropertiesComponent.getInstance().isTrueValue(KEY) } } @Service(Service.Level.PROJECT) class CommitModeManager(private val project: Project) : Disposable { internal class MyStartupActivity : VcsStartupActivity { override fun runActivity(project: Project) { @Suppress("TestOnlyProblems") if (project is ProjectEx && project.isLight) { return } AppUIExecutor.onUiThread().expireWith(project).execute { val commitModeManager = getInstance(project) commitModeManager.subscribeToChanges() commitModeManager.updateCommitMode() } } override fun getOrder(): Int = VcsInitObject.MAPPINGS.order + 50 } private var commitMode: CommitMode = CommitMode.PendingCommitMode private fun scheduleUpdateCommitMode() { getApplication().invokeLater(::updateCommitMode, ModalityState.NON_MODAL, project.disposed) } @RequiresEdt private fun updateCommitMode() { val newCommitMode = getNewCommitMode() if (commitMode == newCommitMode) { return } commitMode = newCommitMode project.messageBus.syncPublisher(COMMIT_MODE_TOPIC).commitModeChanged() } private fun getNewCommitMode(): CommitMode { val activeVcses = ProjectLevelVcsManager.getInstance(project).allActiveVcss val singleVcs = activeVcses.singleOrNull() if (activeVcses.isEmpty()) return CommitMode.PendingCommitMode if (singleVcs != null && singleVcs.isWithCustomLocalChanges) { return CommitMode.ExternalCommitMode(singleVcs) } if (isNonModalInSettings() && canSetNonModal()) { return CommitMode.NonModalCommitMode(isToggleCommitUi) } return CommitMode.ModalCommitMode } @CalledInAny fun getCurrentCommitMode() = commitMode internal fun canSetNonModal(): Boolean { if (isForceNonModalCommit.asBoolean()) return true val activeVcses = ProjectLevelVcsManager.getInstance(project).allActiveVcss return activeVcses.isNotEmpty() && activeVcses.all { it.type == VcsType.distributed } } private fun subscribeToChanges() { isForceNonModalCommit.addListener(object : RegistryValueListener { override fun afterValueChanged(value: RegistryValue) = updateCommitMode() }, this) val connection = getApplication().messageBus.connect(this) connection.subscribe(AdvancedSettingsChangeListener.TOPIC, object : AdvancedSettingsChangeListener { override fun advancedSettingChanged(id: String, oldValue: Any, newValue: Any) { if (id == TOGGLE_COMMIT_UI) { updateCommitMode() } } }) connection.subscribe(SETTINGS, object : SettingsListener { override fun settingsChanged() = updateCommitMode() }) VcsEP.EP_NAME.addChangeListener(::scheduleUpdateCommitMode, this) project.messageBus.connect(this).subscribe(VCS_CONFIGURATION_CHANGED, VcsListener(::scheduleUpdateCommitMode)) } companion object { @JvmField @Topic.AppLevel val SETTINGS: Topic<SettingsListener> = Topic(SettingsListener::class.java, Topic.BroadcastDirection.TO_DIRECT_CHILDREN, true) @Topic.ProjectLevel private val COMMIT_MODE_TOPIC: Topic<CommitModeListener> = Topic(CommitModeListener::class.java, Topic.BroadcastDirection.NONE, true) @JvmStatic fun subscribeOnCommitModeChange(connection: SimpleMessageBusConnection, listener: CommitModeListener) { connection.subscribe(COMMIT_MODE_TOPIC, listener) } @JvmStatic fun getInstance(project: Project): CommitModeManager = project.service() @JvmStatic fun setCommitFromLocalChanges(project: Project?, value: Boolean) { val oldValue = appSettings.COMMIT_FROM_LOCAL_CHANGES if (oldValue == value) return appSettings.COMMIT_FROM_LOCAL_CHANGES = value logStateChanged(project) getApplication().messageBus.syncPublisher(SETTINGS).settingsChanged() } fun isNonModalInSettings(): Boolean = isForceNonModalCommit.asBoolean() || appSettings.COMMIT_FROM_LOCAL_CHANGES } interface SettingsListener : EventListener { fun settingsChanged() } interface CommitModeListener : EventListener { @RequiresEdt fun commitModeChanged() } override fun dispose() { } } sealed class CommitMode { abstract fun useCommitToolWindow(): Boolean open fun hideLocalChangesTab(): Boolean = false open fun disableDefaultCommitAction(): Boolean = false object PendingCommitMode : CommitMode() { override fun useCommitToolWindow(): Boolean { // Enable 'Commit' toolwindow before vcses are activated return CommitModeManager.isNonModalInSettings() } override fun disableDefaultCommitAction(): Boolean { // Disable `Commit` action until vcses are activated return true } } object ModalCommitMode : CommitMode() { override fun useCommitToolWindow(): Boolean = false } data class NonModalCommitMode(val isToggleMode: Boolean) : CommitMode() { override fun useCommitToolWindow(): Boolean = true } data class ExternalCommitMode(val vcs: AbstractVcs) : CommitMode() { override fun useCommitToolWindow(): Boolean = true override fun hideLocalChangesTab(): Boolean = true override fun disableDefaultCommitAction(): Boolean = true } }
apache-2.0
49b653c04852f03077b246053cd55f8b
35.246512
137
0.766042
4.836747
false
false
false
false
ncoe/rosetta
Geometric_algebra/Kotlin/src/app.kt
1
3557
fun bitCount(i: Int): Int { var j = i j -= ((j shr 1) and 0x55555555) j = (j and 0x33333333) + ((j shr 2) and 0x33333333) j = (j + (j shr 4)) and 0x0F0F0F0F j += (j shr 8) j += (j shr 16) return j and 0x0000003F } fun reorderingSign(i: Int, j: Int): Double { var k = i shr 1 var sum = 0 while (k != 0) { sum += bitCount(k and j) k = k shr 1 } return if (sum and 1 == 0) 1.0 else -1.0 } class Vector(private val dims: DoubleArray) { infix fun dot(rhs: Vector): Vector { return (this * rhs + rhs * this) * 0.5 } operator fun unaryMinus(): Vector { return this * -1.0 } operator fun plus(rhs: Vector): Vector { val result = DoubleArray(32) dims.copyInto(result) for (i in 0 until rhs.dims.size) { result[i] += rhs[i] } return Vector(result) } operator fun times(rhs: Vector): Vector { val result = DoubleArray(32) for (i in 0 until dims.size) { if (dims[i] != 0.0) { for (j in 0 until rhs.dims.size) { if (rhs[j] != 0.0) { val s = reorderingSign(i, j) * dims[i] * rhs[j] val k = i xor j result[k] += s } } } } return Vector(result) } operator fun times(scale: Double): Vector { val result = dims.clone() for (i in 0 until 5) { dims[i] = dims[i] * scale } return Vector(result) } operator fun get(index: Int): Double { return dims[index] } operator fun set(index: Int, value: Double) { dims[index] = value } override fun toString(): String { val sb = StringBuilder("(") val it = dims.iterator() if (it.hasNext()) { sb.append(it.next()) } while (it.hasNext()) { sb.append(", ").append(it.next()) } return sb.append(")").toString() } } fun e(n: Int): Vector { if (n > 4) { throw IllegalArgumentException("n must be less than 5") } val result = Vector(DoubleArray(32)) result[1 shl n] = 1.0 return result } val rand = java.util.Random() fun randomVector(): Vector { var result = Vector(DoubleArray(32)) for (i in 0 until 5) { result += Vector(doubleArrayOf(rand.nextDouble())) * e(i) } return result } fun randomMultiVector(): Vector { val result = Vector(DoubleArray(32)) for (i in 0 until 32) { result[i] = rand.nextDouble() } return result } fun main() { for (i in 0..4) { for (j in 0..4) { if (i < j) { if ((e(i) dot e(j))[0] != 0.0) { println("Unexpected non-null scalar product.") return } else if (i == j) { if ((e(i) dot e(j))[0] == 0.0) { println("Unexpected null scalar product.") } } } } } val a = randomMultiVector() val b = randomMultiVector() val c = randomMultiVector() val x = randomVector() // (ab)c == a(bc) println((a * b) * c) println(a * (b * c)) println() // a(b+c) == ab + ac println(a * (b + c)) println(a * b + a * c) println() // (a+b)c == ac + bc println((a + b) * c) println(a * c + b * c) println() // x^2 is real println(x * x) }
mit
d2cda6b39e478d72d7354d9722864c7e
22.713333
71
0.468372
3.477028
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.kt
1
19861
// 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 org.jetbrains.plugins.github import com.intellij.CommonBundle import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Splitter import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.* import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ui.SelectFilesDialog import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.BrowserLink import com.intellij.ui.components.JBLabel import com.intellij.util.containers.ContainerUtil import com.intellij.util.containers.mapSmartSet import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.VcsFileUtil import git4idea.DialogManager import git4idea.GitUtil import git4idea.actions.GitInit import git4idea.commands.Git import git4idea.commands.GitCommand import git4idea.commands.GitLineHandler import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import git4idea.util.GitFileUtils import org.jetbrains.annotations.NonNls import org.jetbrains.annotations.TestOnly import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.data.request.Type import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.ui.GithubShareDialog import org.jetbrains.plugins.github.util.* import java.awt.BorderLayout import java.awt.Component import java.awt.Container import java.io.IOException import javax.swing.BoxLayout import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class GithubShareAction : DumbAwareAction(GithubBundle.messagePointer("share.action"), GithubBundle.messagePointer("share.action.description"), AllIcons.Vcs.Vendors.Github) { override fun update(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) e.presentation.isEnabledAndVisible = project != null && !project.isDefault } // get gitRepository // check for existing git repo // check available repos and privateRepo access (net) // Show dialog (window) // create GitHub repo (net) // create local git repo (if not exist) // add GitHub as a remote host // make first commit // push everything (net) override fun actionPerformed(e: AnActionEvent) { val project = e.getData(CommonDataKeys.PROJECT) val file = e.getData(CommonDataKeys.VIRTUAL_FILE) if (project == null || project.isDisposed) { return } shareProjectOnGithub(project, file) } companion object { private val LOG = GithubUtil.LOG @JvmStatic fun shareProjectOnGithub(project: Project, file: VirtualFile?) { FileDocumentManager.getInstance().saveAllDocuments() val gitRepository = GithubGitHelper.findGitRepository(project, file) val possibleRemotes = gitRepository ?.let(project.service<GHProjectRepositoriesManager>()::findKnownRepositories) ?.map { it.gitRemoteUrlCoordinates.url }.orEmpty() if (possibleRemotes.isNotEmpty()) { val existingRemotesDialog = GithubExistingRemotesDialog(project, possibleRemotes) DialogManager.show(existingRemotesDialog) if (!existingRemotesDialog.isOK) { return } } val authManager = service<GithubAuthenticationManager>() val progressManager = service<ProgressManager>() val requestExecutorManager = service<GithubApiRequestExecutorManager>() val accountInformationProvider = service<GithubAccountInformationProvider>() val gitHelper = service<GithubGitHelper>() val git = service<Git>() val accountInformationLoader = object : (GithubAccount, Component) -> Pair<Boolean, Set<String>> { private val loadedInfo = mutableMapOf<GithubAccount, Pair<Boolean, Set<String>>>() @Throws(IOException::class) override fun invoke(account: GithubAccount, parentComponent: Component) = loadedInfo.getOrPut(account) { val requestExecutor = requestExecutorManager.getExecutor(account, parentComponent) ?: throw ProcessCanceledException() progressManager.runProcessWithProgressSynchronously(ThrowableComputable<Pair<Boolean, Set<String>>, IOException> { val user = requestExecutor.execute(progressManager.progressIndicator, GithubApiRequests.CurrentUser.get(account.server)) val names = GithubApiPagesLoader .loadAll(requestExecutor, progressManager.progressIndicator, GithubApiRequests.CurrentUser.Repos.pages(account.server, Type.OWNER)) .mapSmartSet { it.name } user.canCreatePrivateRepo() to names }, GithubBundle.message("share.process.loading.account.info", account), true, project) } } val shareDialog = GithubShareDialog(project, authManager.getAccounts(), authManager.getDefaultAccount(project), gitRepository?.remotes?.map { it.name }?.toSet() ?: emptySet(), accountInformationLoader) DialogManager.show(shareDialog) if (!shareDialog.isOK) { return } val name: String = shareDialog.getRepositoryName() val isPrivate: Boolean = shareDialog.isPrivate() val remoteName: String = shareDialog.getRemoteName() val description: String = shareDialog.getDescription() val account: GithubAccount = shareDialog.getAccount()!! val requestExecutor = requestExecutorManager.getExecutor(account, project) ?: return object : Task.Backgroundable(project, GithubBundle.message("share.process")) { private lateinit var url: String override fun run(indicator: ProgressIndicator) { // create GitHub repo (network) LOG.info("Creating GitHub repository") indicator.text = GithubBundle.message("share.process.creating.repository") url = requestExecutor .execute(indicator, GithubApiRequests.CurrentUser.Repos.create(account.server, name, description, isPrivate)).htmlUrl LOG.info("Successfully created GitHub repository") val root = gitRepository?.root ?: project.baseDir // creating empty git repo if git is not initialized LOG.info("Binding local project with GitHub") if (gitRepository == null) { LOG.info("No git detected, creating empty git repo") indicator.text = GithubBundle.message("share.process.creating.git.repository") if (!createEmptyGitRepository(project, root)) { return } } val repositoryManager = GitUtil.getRepositoryManager(project) val repository = repositoryManager.getRepositoryForRoot(root) if (repository == null) { GithubNotifications.showError(project, GithubNotificationIdsHolder.SHARE_CANNOT_FIND_GIT_REPO, GithubBundle.message("share.error.failed.to.create.repo"), GithubBundle.message("cannot.find.git.repo")) return } indicator.text = GithubBundle.message("share.process.retrieving.username") val username = accountInformationProvider.getInformation(requestExecutor, indicator, account).login val remoteUrl = gitHelper.getRemoteUrl(account.server, username, name) //git remote add origin [email protected]:login/name.git LOG.info("Adding GitHub as a remote host") indicator.text = GithubBundle.message("share.process.adding.gh.as.remote.host") git.addRemote(repository, remoteName, remoteUrl).throwOnError() repository.update() // create sample commit for binding project if (!performFirstCommitIfRequired(project, root, repository, indicator, name, url)) { return } //git push origin master LOG.info("Pushing to github master") indicator.text = GithubBundle.message("share.process.pushing.to.github.master") if (!pushCurrentBranch(project, repository, remoteName, remoteUrl, name, url)) { return } GithubNotifications.showInfoURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_SUCCESSFULLY_SHARED, GithubBundle.message("share.process.successfully.shared"), name, url) } private fun createEmptyGitRepository(project: Project, root: VirtualFile): Boolean { val result = Git.getInstance().init(project, root) if (!result.success()) { VcsNotifier.getInstance(project).notifyError(GithubNotificationIdsHolder.GIT_REPO_INIT_REPO, GitBundle.message("initializing.title"), result.errorOutputAsHtmlString) LOG.info("Failed to create empty git repo: " + result.errorOutputAsJoinedString) return false } GitInit.refreshAndConfigureVcsMappings(project, root, root.path) GitUtil.generateGitignoreFileIfNeeded(project, root) return true } private fun performFirstCommitIfRequired(project: Project, root: VirtualFile, repository: GitRepository, indicator: ProgressIndicator, @NlsSafe name: String, url: String): Boolean { // check if there is no commits if (!repository.isFresh) { return true } LOG.info("Trying to commit") try { LOG.info("Adding files for commit") indicator.text = GithubBundle.message("share.process.adding.files") // ask for files to add val trackedFiles = ChangeListManager.getInstance(project).affectedFiles val untrackedFiles = filterOutIgnored(project, repository.untrackedFilesHolder.retrieveUntrackedFilePaths().mapNotNull(FilePath::getVirtualFile)) trackedFiles.removeAll(untrackedFiles) // fix IDEA-119855 val allFiles = ArrayList<VirtualFile>() allFiles.addAll(trackedFiles) allFiles.addAll(untrackedFiles) val dialog = invokeAndWaitIfNeeded(indicator.modalityState) { GithubUntrackedFilesDialog(project, allFiles).apply { if (!trackedFiles.isEmpty()) { selectedFiles = trackedFiles } DialogManager.show(this) } } val files2commit = dialog.selectedFiles if (!dialog.isOK || files2commit.isEmpty()) { GithubNotifications.showInfoURL(project, GithubNotificationIdsHolder.SHARE_EMPTY_REPO_CREATED, GithubBundle.message("share.process.empty.project.created"), name, url) return false } val files2add = ContainerUtil.intersection(untrackedFiles, files2commit) val files2rm = ContainerUtil.subtract(trackedFiles, files2commit) val modified = HashSet(trackedFiles) modified.addAll(files2commit) GitFileUtils.addFiles(project, root, files2add) GitFileUtils.deleteFilesFromCache(project, root, files2rm) // commit LOG.info("Performing commit") indicator.text = GithubBundle.message("share.process.performing.commit") val handler = GitLineHandler(project, root, GitCommand.COMMIT) handler.setStdoutSuppressed(false) handler.addParameters("-m", dialog.commitMessage) handler.endOptions() Git.getInstance().runCommand(handler).throwOnError() VcsFileUtil.markFilesDirty(project, modified) } catch (e: VcsException) { LOG.warn(e) GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_COMMIT_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.init.commit.failed") + GithubUtil.getErrorTextFromException( e), url) return false } LOG.info("Successfully created initial commit") return true } private fun filterOutIgnored(project: Project, files: Collection<VirtualFile>): Collection<VirtualFile> { val changeListManager = ChangeListManager.getInstance(project) val vcsManager = ProjectLevelVcsManager.getInstance(project) return ContainerUtil.filter(files) { file -> !changeListManager.isIgnoredFile(file) && !vcsManager.isIgnored(file) } } private fun pushCurrentBranch(project: Project, repository: GitRepository, remoteName: String, remoteUrl: String, name: String, url: String): Boolean { val currentBranch = repository.currentBranch if (currentBranch == null) { GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.push.no.current.branch"), url) return false } val result = git.push(repository, remoteName, remoteUrl, currentBranch.name, true) if (!result.success()) { GithubNotifications.showErrorURL(project, GithubNotificationIdsHolder.SHARE_PROJECT_INIT_PUSH_FAILED, GithubBundle.message("share.error.cannot.finish"), GithubBundle.message("share.error.created.project"), " '$name' ", GithubBundle.message("share.error.push.failed", result.errorOutputAsHtmlString), url) return false } return true } override fun onThrowable(error: Throwable) { GithubNotifications.showError(project, GithubNotificationIdsHolder.SHARE_CANNOT_CREATE_REPO, GithubBundle.message("share.error.failed.to.create.repo"), error) } }.queue() } } @TestOnly class GithubExistingRemotesDialog(project: Project, private val remotes: List<String>) : DialogWrapper(project) { init { title = GithubBundle.message("share.error.project.is.on.github") setOKButtonText(GithubBundle.message("share.anyway.button")) init() } override fun createCenterPanel(): JComponent? { val mainText = JBLabel(if (remotes.size == 1) GithubBundle.message("share.action.remote.is.on.github") else GithubBundle.message("share.action.remotes.are.on.github")) val remotesPanel = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) } for (remote in remotes) { remotesPanel.add(BrowserLink(remote, remote)) } val messagesPanel = JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToTop(mainText) .addToCenter(remotesPanel) val iconContainer = Container().apply { layout = BorderLayout() add(JLabel(Messages.getQuestionIcon()), BorderLayout.NORTH) } return JBUI.Panels.simplePanel(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP) .addToCenter(messagesPanel) .addToLeft(iconContainer) .apply { border = JBUI.Borders.emptyBottom(UIUtil.LARGE_VGAP) } } } @TestOnly class GithubUntrackedFilesDialog(private val myProject: Project, untrackedFiles: List<VirtualFile>) : SelectFilesDialog(myProject, untrackedFiles, null, null, true, false), DataProvider { private var myCommitMessagePanel: CommitMessage? = null val commitMessage: String get() = myCommitMessagePanel!!.comment init { title = GithubBundle.message("untracked.files.dialog.title") setOKButtonText(CommonBundle.getAddButtonText()) setCancelButtonText(CommonBundle.getCancelButtonText()) init() } override fun createNorthPanel(): JComponent? { return null } override fun createCenterPanel(): JComponent? { val tree = super.createCenterPanel() val commitMessage = CommitMessage(myProject) Disposer.register(disposable, commitMessage) commitMessage.setCommitMessage("Initial commit") myCommitMessagePanel = commitMessage val splitter = Splitter(true) splitter.setHonorComponentsMinimumSize(true) splitter.firstComponent = tree splitter.secondComponent = myCommitMessagePanel splitter.proportion = 0.7f return splitter } override fun getData(@NonNls dataId: String): Any? { return if (VcsDataKeys.COMMIT_MESSAGE_CONTROL.`is`(dataId)) { myCommitMessagePanel } else null } override fun getDimensionServiceKey(): String? { return "Github.UntrackedFilesDialog" } } }
apache-2.0
c32e65211a6909e7c001e737ff374931
44.450801
140
0.637833
5.631131
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/OoAdminOneTaskPage.kt
1
1217
package alraune import alraune.entity.* import pieces100.* import vgrechka.* class OoAdminOneTaskPage { companion object { val path = "/task" fun href(id: Long) = makeUrlPart(path) { it.longId.set(id) } } val css = AlCSS.tasks val task: Task init { checkUserKind_elseBailOutToSignInOrSayKissMyAss(AlUserKind.Admin) val getParams = GetParams() task = dbSelectTaskOrBailOut(getParamOrBailOut(getParams.longId)) ooPageHeaderAndSetDocumentTitle(t("TOTE", "Задача ${AlText.numString(task.id)}")) { oo(h4().add(task.title)) } oo(composeTaskParams()) } fun composeTaskParams() = div().with { oo(Row().with { oo(composeCreatedAtCol(3, task.createdAt, Gender.Feminine)) ooUpdatedAtColIfDiffersFromCreatedAt(task.updatedAt, task.createdAt) oo(col(3, AlText.status, task.status.title)) }) if (task.status == Task.Status.Open) { val href = task.data.href(task) if (href != null) oo(composeTagaProgressy(href).add(t("TOTE", "Пойти порешать задачу"))) } } }
apache-2.0
60d7a483c0a559e0adc206d478d77844
24.361702
91
0.597315
3.612121
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/tests/testData/weighers/smart/BooleanExpected.kt
9
524
// WITH_STDLIB var nonNullable: Boolean = true var nullableX: Boolean? = null var nullableFoo: Boolean? = null fun foo(pFoo: Boolean, s: String) { val local = true foo(<caret>) } // ORDER: pFoo // ORDER: nullableFoo // ORDER: nullableFoo // ORDER: "pFoo, s" // ORDER: true // ORDER: false // ORDER: "pFoo = true" // ORDER: "pFoo = false" // ORDER: local // ORDER: nonNullable // ORDER: maxOf // ORDER: maxOf // ORDER: maxOf // ORDER: minOf // ORDER: minOf // ORDER: minOf // ORDER: nullableX // ORDER: nullableX
apache-2.0
cf54c355ddd4f85bd9d83754f2502147
16.466667
35
0.645038
3.082353
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Button.kt
3
44660
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.VectorConverter import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.interaction.FocusInteraction import androidx.compose.foundation.interaction.HoverInteraction import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ButtonDefaults.ContentPadding import androidx.compose.material3.ButtonDefaults.IconSize import androidx.compose.material3.ButtonDefaults.IconSpacing import androidx.compose.material3.ButtonDefaults.MinHeight import androidx.compose.material3.ButtonDefaults.MinWidth import androidx.compose.material3.ButtonDefaults.TextButtonContentPadding import androidx.compose.material3.ButtonDefaults.buttonColors import androidx.compose.material3.ButtonDefaults.buttonElevation import androidx.compose.material3.ButtonDefaults.elevatedButtonColors import androidx.compose.material3.ButtonDefaults.elevatedButtonElevation import androidx.compose.material3.ButtonDefaults.filledTonalButtonColors import androidx.compose.material3.ButtonDefaults.filledTonalButtonElevation import androidx.compose.material3.ButtonDefaults.outlinedButtonColors import androidx.compose.material3.ButtonDefaults.textButtonColors import androidx.compose.material3.tokens.ElevatedButtonTokens import androidx.compose.material3.tokens.FilledButtonTokens import androidx.compose.material3.tokens.FilledTonalButtonTokens import androidx.compose.material3.tokens.OutlinedButtonTokens import androidx.compose.material3.tokens.TextButtonTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp /** * <a href="https://m3.material.io/components/buttons/overview" class="external" target="_blank">Material Design button</a>. * * Buttons help people initiate actions, from sending an email, to sharing a document, to liking a * post. * * ![Filled button image](https://developer.android.com/images/reference/androidx/compose/material3/filled-button.png) * * Filled buttons are high-emphasis buttons. Filled buttons have the most visual impact after the * [FloatingActionButton], and should be used for important, final actions that complete a flow, * like "Save", "Join now", or "Confirm". * * @sample androidx.compose.material3.samples.ButtonSample * @sample androidx.compose.material3.samples.ButtonWithIconSample * * Choose the best button for an action based on the amount of emphasis it needs. The more important * an action is, the higher emphasis its button should be. * * - See [OutlinedButton] for a medium-emphasis button with a border. * - See [ElevatedButton] for an [OutlinedButton] with a shadow. * - See [TextButton] for a low-emphasis button with no border. * - See [FilledTonalButton] for a middle ground between [OutlinedButton] and [Button]. * * The default text style for internal [Text] components will be set to [Typography.labelLarge]. * * @param onClick called when this button is clicked * @param modifier the [Modifier] to be applied to this button * @param enabled controls the enabled state of this button. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this button's container, border (when [border] is not null), * and shadow (when using [elevation]) * @param colors [ButtonColors] that will be used to resolve the colors for this button in different * states. See [ButtonDefaults.buttonColors]. * @param elevation [ButtonElevation] used to resolve the elevation for this button in different * states. This controls the size of the shadow below the button. Additionally, when the container * color is [ColorScheme.surface], this controls the amount of primary color applied as an overlay. * See [ButtonElevation.shadowElevation] and [ButtonElevation.tonalElevation]. * @param border the border to draw around the container of this button * @param contentPadding the spacing values to apply internally between the container and the * content * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this button. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this button in different states. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun Button( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.shape, colors: ButtonColors = ButtonDefaults.buttonColors(), elevation: ButtonElevation? = ButtonDefaults.buttonElevation(), border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) { val containerColor = colors.containerColor(enabled).value val contentColor = colors.contentColor(enabled).value val shadowElevation = elevation?.shadowElevation(enabled, interactionSource)?.value ?: 0.dp val tonalElevation = elevation?.tonalElevation(enabled, interactionSource)?.value ?: 0.dp Surface( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, color = containerColor, contentColor = contentColor, tonalElevation = tonalElevation, shadowElevation = shadowElevation, border = border, interactionSource = interactionSource ) { CompositionLocalProvider(LocalContentColor provides contentColor) { ProvideTextStyle(value = MaterialTheme.typography.labelLarge) { Row( Modifier .defaultMinSize( minWidth = ButtonDefaults.MinWidth, minHeight = ButtonDefaults.MinHeight ) .padding(contentPadding), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, content = content ) } } } } /** * <a href="https://m3.material.io/components/buttons/overview" class="external" target="_blank">Material Design elevated button</a>. * * Buttons help people initiate actions, from sending an email, to sharing a document, to liking a * post. * * ![Elevated button image](https://developer.android.com/images/reference/androidx/compose/material3/elevated-button.png) * * Elevated buttons are high-emphasis buttons that are essentially [FilledTonalButton]s with a * shadow. To prevent shadow creep, only use them when absolutely necessary, such as when the button * requires visual separation from patterned container. * * @sample androidx.compose.material3.samples.ElevatedButtonSample * * Choose the best button for an action based on the amount of emphasis it needs. The more important * an action is, the higher emphasis its button should be. * * - See [Button] for a high-emphasis button without a shadow, also known as a filled button. * - See [FilledTonalButton] for a middle ground between [OutlinedButton] and [Button]. * - See [OutlinedButton] for a medium-emphasis button with a border. * - See [TextButton] for a low-emphasis button with no border. * * The default text style for internal [Text] components will be set to [Typography.labelLarge]. * * @param onClick called when this button is clicked * @param modifier the [Modifier] to be applied to this button * @param enabled controls the enabled state of this button. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this button's container, border (when [border] is not null), * and shadow (when using [elevation]) * @param colors [ButtonColors] that will be used to resolve the colors for this button in different * states. See [ButtonDefaults.elevatedButtonColors]. * @param elevation [ButtonElevation] used to resolve the elevation for this button in different * states. This controls the size of the shadow below the button. Additionally, when the container * color is [ColorScheme.surface], this controls the amount of primary color applied as an overlay. * See [ButtonDefaults.elevatedButtonElevation]. * @param border the border to draw around the container of this button * @param contentPadding the spacing values to apply internally between the container and the * content * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this button. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this button in different states. */ @Composable fun ElevatedButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.elevatedShape, colors: ButtonColors = ButtonDefaults.elevatedButtonColors(), elevation: ButtonElevation? = ButtonDefaults.elevatedButtonElevation(), border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) = Button( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, contentPadding = contentPadding, interactionSource = interactionSource, content = content ) /** * <a href="https://m3.material.io/components/buttons/overview" class="external" target="_blank">Material Design filled tonal button</a>. * * Buttons help people initiate actions, from sending an email, to sharing a document, to liking a * post. * * ![Filled tonal button image](https://developer.android.com/images/reference/androidx/compose/material3/filled-tonal-button.png) * * Filled tonal buttons are medium-emphasis buttons that is an alternative middle ground between * default [Button]s (filled) and [OutlinedButton]s. They can be used in contexts where * lower-priority button requires slightly more emphasis than an outline would give, such as "Next" * in an onboarding flow. Tonal buttons use the secondary color mapping. * * @sample androidx.compose.material3.samples.FilledTonalButtonSample * * Choose the best button for an action based on the amount of emphasis it needs. The more important * an action is, the higher emphasis its button should be. * * - See [Button] for a high-emphasis button without a shadow, also known as a filled button. * - See [ElevatedButton] for a [FilledTonalButton] with a shadow. * - See [OutlinedButton] for a medium-emphasis button with a border. * - See [TextButton] for a low-emphasis button with no border. * * The default text style for internal [Text] components will be set to [Typography.labelLarge]. * * @param onClick called when this button is clicked * @param modifier the [Modifier] to be applied to this button * @param enabled controls the enabled state of this button. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this button's container, border (when [border] is not null), * and shadow (when using [elevation]) * @param colors [ButtonColors] that will be used to resolve the colors for this button in different * states. See [ButtonDefaults.filledTonalButtonColors]. * @param elevation [ButtonElevation] used to resolve the elevation for this button in different * states. This controls the size of the shadow below the button. Additionally, when the container * color is [ColorScheme.surface], this controls the amount of primary color applied as an overlay. * @param border the border to draw around the container of this button * @param contentPadding the spacing values to apply internally between the container and the * content * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this button. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this button in different states. */ @Composable fun FilledTonalButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.filledTonalShape, colors: ButtonColors = ButtonDefaults.filledTonalButtonColors(), elevation: ButtonElevation? = ButtonDefaults.filledTonalButtonElevation(), border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) = Button( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, contentPadding = contentPadding, interactionSource = interactionSource, content = content ) /** * <a href="https://m3.material.io/components/buttons/overview" class="external" target="_blank">Material Design outlined button</a>. * * Buttons help people initiate actions, from sending an email, to sharing a document, to liking a * post. * * ![Outlined button image](https://developer.android.com/images/reference/androidx/compose/material3/outlined-button.png) * * Outlined buttons are medium-emphasis buttons. They contain actions that are important, but are * not the primary action in an app. Outlined buttons pair well with [Button]s to indicate an * alternative, secondary action. * * @sample androidx.compose.material3.samples.OutlinedButtonSample * * Choose the best button for an action based on the amount of emphasis it needs. The more important * an action is, the higher emphasis its button should be. * * - See [Button] for a high-emphasis button without a shadow, also known as a filled button. * - See [FilledTonalButton] for a middle ground between [OutlinedButton] and [Button]. * - See [OutlinedButton] for a medium-emphasis button with a border. * - See [TextButton] for a low-emphasis button with no border. * * The default text style for internal [Text] components will be set to [Typography.labelLarge]. * * @param onClick called when this button is clicked * @param modifier the [Modifier] to be applied to this button * @param enabled controls the enabled state of this button. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this button's container, border (when [border] is not null), * and shadow (when using [elevation]). * @param colors [ButtonColors] that will be used to resolve the colors for this button in different * states. See [ButtonDefaults.outlinedButtonColors]. * @param elevation [ButtonElevation] used to resolve the elevation for this button in different * states. This controls the size of the shadow below the button. Additionally, when the container * color is [ColorScheme.surface], this controls the amount of primary color applied as an overlay. * @param border the border to draw around the container of this button. Pass `null` for no border. * @param contentPadding the spacing values to apply internally between the container and the * content * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this button. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this button in different states. */ @Composable fun OutlinedButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.outlinedShape, colors: ButtonColors = ButtonDefaults.outlinedButtonColors(), elevation: ButtonElevation? = null, border: BorderStroke? = ButtonDefaults.outlinedButtonBorder, contentPadding: PaddingValues = ButtonDefaults.ContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) = Button( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, contentPadding = contentPadding, interactionSource = interactionSource, content = content ) /** * <a href="https://m3.material.io/components/buttons/overview" class="external" target="_blank">Material Design text button</a>. * * Buttons help people initiate actions, from sending an email, to sharing a document, to liking a * post. * * ![Text button image](https://developer.android.com/images/reference/androidx/compose/material3/text-button.png) * * Text buttons are typically used for less-pronounced actions, including those located in dialogs * and cards. In cards, text buttons help maintain an emphasis on card content. Text buttons are * used for the lowest priority actions, especially when presenting multiple options. * * @sample androidx.compose.material3.samples.TextButtonSample * * Choose the best button for an action based on the amount of emphasis it needs. The more important * an action is, the higher emphasis its button should be. * * - See [Button] for a high-emphasis button without a shadow, also known as a filled button. * - See [ElevatedButton] for a [FilledTonalButton] with a shadow. * - See [FilledTonalButton] for a middle ground between [OutlinedButton] and [Button]. * - See [OutlinedButton] for a medium-emphasis button with a border. * * The default text style for internal [Text] components will be set to [Typography.labelLarge]. * * @param onClick called when this button is clicked * @param modifier the [Modifier] to be applied to this button * @param enabled controls the enabled state of this button. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param shape defines the shape of this button's container, border (when [border] is not null), * and shadow (when using [elevation]) * @param colors [ButtonColors] that will be used to resolve the colors for this button in different * states. See [ButtonDefaults.textButtonColors]. * @param elevation [ButtonElevation] used to resolve the elevation for this button in different * states. This controls the size of the shadow below the button. Additionally, when the container * color is [ColorScheme.surface], this controls the amount of primary color applied as an overlay. * A TextButton typically has no elevation, and the default value is `null`. See [ElevatedButton] * for a button with elevation. * @param border the border to draw around the container of this button * @param contentPadding the spacing values to apply internally between the container and the * content * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this button. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this button in different states. */ @Composable fun TextButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, shape: Shape = ButtonDefaults.textShape, colors: ButtonColors = ButtonDefaults.textButtonColors(), elevation: ButtonElevation? = null, border: BorderStroke? = null, contentPadding: PaddingValues = ButtonDefaults.TextButtonContentPadding, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable RowScope.() -> Unit ) = Button( onClick = onClick, modifier = modifier, enabled = enabled, shape = shape, colors = colors, elevation = elevation, border = border, contentPadding = contentPadding, interactionSource = interactionSource, content = content ) // TODO(b/201341237): Use token values for 0 elevation? // TODO(b/201341237): Use token values for null border? // TODO(b/201341237): Use token values for no color (transparent)? /** * Contains the default values used by all 5 button types. * * Default values that apply to all buttons types are [MinWidth], [MinHeight], [IconSize], and * [IconSpacing]. * * A default value that applies only to [Button], [ElevatedButton], [FilledTonalButton], and * [OutlinedButton] is [ContentPadding]. * * Default values that apply only to [Button] are [buttonColors] and [buttonElevation]. * Default values that apply only to [ElevatedButton] are [elevatedButtonColors] and [elevatedButtonElevation]. * Default values that apply only to [FilledTonalButton] are [filledTonalButtonColors] and [filledTonalButtonElevation]. * A default value that applies only to [OutlinedButton] is [outlinedButtonColors]. * Default values that apply only to [TextButton] are [TextButtonContentPadding] and [textButtonColors]. */ object ButtonDefaults { private val ButtonHorizontalPadding = 24.dp private val ButtonVerticalPadding = 8.dp /** * The default content padding used by [Button], [ElevatedButton], [FilledTonalButton], and * [OutlinedButton] buttons. * * - See [TextButtonContentPadding] for content padding used by [TextButton]. * - See [ButtonWithIconContentPadding] for content padding used by [Button] that contains [Icon]. */ val ContentPadding = PaddingValues( start = ButtonHorizontalPadding, top = ButtonVerticalPadding, end = ButtonHorizontalPadding, bottom = ButtonVerticalPadding ) private val ButtonWithIconHorizontalStartPadding = 16.dp /** The default content padding used by [Button] that contains an [Icon]. */ val ButtonWithIconContentPadding = PaddingValues( start = ButtonWithIconHorizontalStartPadding, top = ButtonVerticalPadding, end = ButtonHorizontalPadding, bottom = ButtonVerticalPadding ) private val TextButtonHorizontalPadding = 12.dp /** The default content padding used by [TextButton] */ val TextButtonContentPadding = PaddingValues( start = TextButtonHorizontalPadding, top = ContentPadding.calculateTopPadding(), end = TextButtonHorizontalPadding, bottom = ContentPadding.calculateBottomPadding() ) /** * The default min width applied for all buttons. Note that you can override it by applying * Modifier.widthIn directly on the button composable. */ val MinWidth = 58.dp /** * The default min height applied for all buttons. Note that you can override it by applying * Modifier.heightIn directly on the button composable. */ val MinHeight = 40.dp /** The default size of the icon when used inside any button. */ val IconSize = FilledButtonTokens.IconSize /** * The default size of the spacing between an icon and a text when they used inside any button. */ val IconSpacing = 8.dp /** Default shape for a button. */ val shape: Shape @Composable get() = FilledButtonTokens.ContainerShape.toShape() /** Default shape for an elevated button. */ val elevatedShape: Shape @Composable get() = ElevatedButtonTokens.ContainerShape.toShape() /** Default shape for a filled tonal button. */ val filledTonalShape: Shape @Composable get() = FilledTonalButtonTokens.ContainerShape.toShape() /** Default shape for an outlined button. */ val outlinedShape: Shape @Composable get() = OutlinedButtonTokens.ContainerShape.toShape() /** Default shape for a text button. */ val textShape: Shape @Composable get() = TextButtonTokens.ContainerShape.toShape() /** * Creates a [ButtonColors] that represents the default container and content colors used in a * [Button]. * * @param containerColor the container color of this [Button] when enabled. * @param contentColor the content color of this [Button] when enabled. * @param disabledContainerColor the container color of this [Button] when not enabled. * @param disabledContentColor the content color of this [Button] when not enabled. */ @Composable fun buttonColors( containerColor: Color = FilledButtonTokens.ContainerColor.toColor(), contentColor: Color = FilledButtonTokens.LabelTextColor.toColor(), disabledContainerColor: Color = FilledButtonTokens.DisabledContainerColor.toColor() .copy(alpha = FilledButtonTokens.DisabledContainerOpacity), disabledContentColor: Color = FilledButtonTokens.DisabledLabelTextColor.toColor() .copy(alpha = FilledButtonTokens.DisabledLabelTextOpacity), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [ButtonColors] that represents the default container and content colors used in an * [ElevatedButton]. * * @param containerColor the container color of this [ElevatedButton] when enabled * @param contentColor the content color of this [ElevatedButton] when enabled * @param disabledContainerColor the container color of this [ElevatedButton] when not enabled * @param disabledContentColor the content color of this [ElevatedButton] when not enabled */ @Composable fun elevatedButtonColors( containerColor: Color = ElevatedButtonTokens.ContainerColor.toColor(), contentColor: Color = ElevatedButtonTokens.LabelTextColor.toColor(), disabledContainerColor: Color = ElevatedButtonTokens.DisabledContainerColor .toColor() .copy(alpha = ElevatedButtonTokens.DisabledContainerOpacity), disabledContentColor: Color = ElevatedButtonTokens.DisabledLabelTextColor .toColor() .copy(alpha = ElevatedButtonTokens.DisabledLabelTextOpacity), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [ButtonColors] that represents the default container and content colors used in an * [FilledTonalButton]. * * @param containerColor the container color of this [FilledTonalButton] when enabled * @param contentColor the content color of this [FilledTonalButton] when enabled * @param disabledContainerColor the container color of this [FilledTonalButton] when not enabled * @param disabledContentColor the content color of this [FilledTonalButton] when not enabled */ @Composable fun filledTonalButtonColors( containerColor: Color = FilledTonalButtonTokens.ContainerColor.toColor(), contentColor: Color = FilledTonalButtonTokens.LabelTextColor.toColor(), disabledContainerColor: Color = FilledTonalButtonTokens.DisabledContainerColor .toColor() .copy(alpha = FilledTonalButtonTokens.DisabledContainerOpacity), disabledContentColor: Color = FilledTonalButtonTokens.DisabledLabelTextColor .toColor() .copy(alpha = FilledTonalButtonTokens.DisabledLabelTextOpacity), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [ButtonColors] that represents the default container and content colors used in an * [OutlinedButton]. * * @param containerColor the container color of this [OutlinedButton] when enabled * @param contentColor the content color of this [OutlinedButton] when enabled * @param disabledContainerColor the container color of this [OutlinedButton] when not enabled * @param disabledContentColor the content color of this [OutlinedButton] when not enabled */ @Composable fun outlinedButtonColors( containerColor: Color = Color.Transparent, contentColor: Color = OutlinedButtonTokens.LabelTextColor.toColor(), disabledContainerColor: Color = Color.Transparent, disabledContentColor: Color = OutlinedButtonTokens.DisabledLabelTextColor .toColor() .copy(alpha = OutlinedButtonTokens.DisabledLabelTextOpacity), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [ButtonColors] that represents the default container and content colors used in a * [TextButton]. * * @param containerColor the container color of this [TextButton] when enabled * @param contentColor the content color of this [TextButton] when enabled * @param disabledContainerColor the container color of this [TextButton] when not enabled * @param disabledContentColor the content color of this [TextButton] when not enabled */ @Composable fun textButtonColors( containerColor: Color = Color.Transparent, contentColor: Color = TextButtonTokens.LabelTextColor.toColor(), disabledContainerColor: Color = Color.Transparent, disabledContentColor: Color = TextButtonTokens.DisabledLabelTextColor .toColor() .copy(alpha = TextButtonTokens.DisabledLabelTextOpacity), ): ButtonColors = ButtonColors( containerColor = containerColor, contentColor = contentColor, disabledContainerColor = disabledContainerColor, disabledContentColor = disabledContentColor ) /** * Creates a [ButtonElevation] that will animate between the provided values according to the * Material specification for a [Button]. * * @param defaultElevation the elevation used when the [Button] is enabled, and has no other * [Interaction]s. * @param pressedElevation the elevation used when this [Button] is enabled and pressed. * @param focusedElevation the elevation used when the [Button] is enabled and focused. * @param hoveredElevation the elevation used when the [Button] is enabled and hovered. * @param disabledElevation the elevation used when the [Button] is not enabled. */ @Composable fun buttonElevation( defaultElevation: Dp = FilledButtonTokens.ContainerElevation, pressedElevation: Dp = FilledButtonTokens.PressedContainerElevation, focusedElevation: Dp = FilledButtonTokens.FocusContainerElevation, hoveredElevation: Dp = FilledButtonTokens.HoverContainerElevation, disabledElevation: Dp = FilledButtonTokens.DisabledContainerElevation, ): ButtonElevation = ButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, disabledElevation = disabledElevation, ) /** * Creates a [ButtonElevation] that will animate between the provided values according to the * Material specification for a [ElevatedButton]. * * @param defaultElevation the elevation used when the [ElevatedButton] is enabled, and has no * other [Interaction]s. * @param pressedElevation the elevation used when this [ElevatedButton] is enabled and pressed. * @param focusedElevation the elevation used when the [ElevatedButton] is enabled and focused. * @param hoveredElevation the elevation used when the [ElevatedButton] is enabled and hovered. * @param disabledElevation the elevation used when the [ElevatedButton] is not enabled. */ @Composable fun elevatedButtonElevation( defaultElevation: Dp = ElevatedButtonTokens.ContainerElevation, pressedElevation: Dp = ElevatedButtonTokens.PressedContainerElevation, focusedElevation: Dp = ElevatedButtonTokens.FocusContainerElevation, hoveredElevation: Dp = ElevatedButtonTokens.HoverContainerElevation, disabledElevation: Dp = ElevatedButtonTokens.DisabledContainerElevation ): ButtonElevation = ButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, disabledElevation = disabledElevation ) /** * Creates a [ButtonElevation] that will animate between the provided values according to the * Material specification for a [FilledTonalButton]. * * @param defaultElevation the elevation used when the [FilledTonalButton] is enabled, and has no * other [Interaction]s. * @param pressedElevation the elevation used when this [FilledTonalButton] is enabled and * pressed. * @param focusedElevation the elevation used when the [FilledTonalButton] is enabled and focused. * @param hoveredElevation the elevation used when the [FilledTonalButton] is enabled and hovered. * @param disabledElevation the elevation used when the [FilledTonalButton] is not enabled. */ @Composable fun filledTonalButtonElevation( defaultElevation: Dp = FilledTonalButtonTokens.ContainerElevation, pressedElevation: Dp = FilledTonalButtonTokens.PressedContainerElevation, focusedElevation: Dp = FilledTonalButtonTokens.FocusContainerElevation, hoveredElevation: Dp = FilledTonalButtonTokens.HoverContainerElevation, disabledElevation: Dp = 0.dp ): ButtonElevation = ButtonElevation( defaultElevation = defaultElevation, pressedElevation = pressedElevation, focusedElevation = focusedElevation, hoveredElevation = hoveredElevation, disabledElevation = disabledElevation ) /** The default [BorderStroke] used by [OutlinedButton]. */ val outlinedButtonBorder: BorderStroke @Composable get() = BorderStroke( width = OutlinedButtonTokens.OutlineWidth, color = OutlinedButtonTokens.OutlineColor.toColor(), ) } /** * Represents the elevation for a button in different states. * * - See [ButtonDefaults.buttonElevation] for the default elevation used in a [Button]. * - See [ButtonDefaults.elevatedButtonElevation] for the default elevation used in a * [ElevatedButton]. */ @Stable class ButtonElevation internal constructor( private val defaultElevation: Dp, private val pressedElevation: Dp, private val focusedElevation: Dp, private val hoveredElevation: Dp, private val disabledElevation: Dp, ) { /** * Represents the tonal elevation used in a button, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [shadowElevation]. * * Tonal elevation is used to apply a color shift to the surface to give the it higher emphasis. * When surface's color is [ColorScheme.surface], a higher elevation will result in a darker * color in light theme and lighter color in dark theme. * * See [shadowElevation] which controls the elevation of the shadow drawn around the button. * * @param enabled whether the button is enabled * @param interactionSource the [InteractionSource] for this button */ @Composable internal fun tonalElevation(enabled: Boolean, interactionSource: InteractionSource): State<Dp> { return animateElevation(enabled = enabled, interactionSource = interactionSource) } /** * Represents the shadow elevation used in a button, depending on its [enabled] state and * [interactionSource]. This should typically be the same value as the [tonalElevation]. * * Shadow elevation is used to apply a shadow around the button to give it higher emphasis. * * See [tonalElevation] which controls the elevation with a color shift to the surface. * * @param enabled whether the button is enabled * @param interactionSource the [InteractionSource] for this button */ @Composable internal fun shadowElevation( enabled: Boolean, interactionSource: InteractionSource ): State<Dp> { return animateElevation(enabled = enabled, interactionSource = interactionSource) } @Composable private fun animateElevation( enabled: Boolean, interactionSource: InteractionSource ): State<Dp> { val interactions = remember { mutableStateListOf<Interaction>() } LaunchedEffect(interactionSource) { interactionSource.interactions.collect { interaction -> when (interaction) { is HoverInteraction.Enter -> { interactions.add(interaction) } is HoverInteraction.Exit -> { interactions.remove(interaction.enter) } is FocusInteraction.Focus -> { interactions.add(interaction) } is FocusInteraction.Unfocus -> { interactions.remove(interaction.focus) } is PressInteraction.Press -> { interactions.add(interaction) } is PressInteraction.Release -> { interactions.remove(interaction.press) } is PressInteraction.Cancel -> { interactions.remove(interaction.press) } } } } val interaction = interactions.lastOrNull() val target = if (!enabled) { disabledElevation } else { when (interaction) { is PressInteraction.Press -> pressedElevation is HoverInteraction.Enter -> hoveredElevation is FocusInteraction.Focus -> focusedElevation else -> defaultElevation } } val animatable = remember { Animatable(target, Dp.VectorConverter) } if (!enabled) { // No transition when moving to a disabled state LaunchedEffect(target) { animatable.snapTo(target) } } else { LaunchedEffect(target) { val lastInteraction = when (animatable.targetValue) { pressedElevation -> PressInteraction.Press(Offset.Zero) hoveredElevation -> HoverInteraction.Enter() focusedElevation -> FocusInteraction.Focus() else -> null } animatable.animateElevation( from = lastInteraction, to = interaction, target = target ) } } return animatable.asState() } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is ButtonElevation) return false if (defaultElevation != other.defaultElevation) return false if (pressedElevation != other.pressedElevation) return false if (focusedElevation != other.focusedElevation) return false if (hoveredElevation != other.hoveredElevation) return false if (disabledElevation != other.disabledElevation) return false return true } override fun hashCode(): Int { var result = defaultElevation.hashCode() result = 31 * result + pressedElevation.hashCode() result = 31 * result + focusedElevation.hashCode() result = 31 * result + hoveredElevation.hashCode() result = 31 * result + disabledElevation.hashCode() return result } } /** * Represents the container and content colors used in a button in different states. * * - See [ButtonDefaults.buttonColors] for the default colors used in a [Button]. * - See [ButtonDefaults.elevatedButtonColors] for the default colors used in a [ElevatedButton]. * - See [ButtonDefaults.textButtonColors] for the default colors used in a [TextButton]. */ @Immutable class ButtonColors internal constructor( private val containerColor: Color, private val contentColor: Color, private val disabledContainerColor: Color, private val disabledContentColor: Color, ) { /** * Represents the container color for this button, depending on [enabled]. * * @param enabled whether the button is enabled */ @Composable internal fun containerColor(enabled: Boolean): State<Color> { return rememberUpdatedState(if (enabled) containerColor else disabledContainerColor) } /** * Represents the content color for this button, depending on [enabled]. * * @param enabled whether the 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 ButtonColors) 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 } }
apache-2.0
7c154be984a36d69efeda7d4dde9110a
45.962145
137
0.718585
5.066364
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/XMemberName.kt
3
2682
/* * 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.room.compiler.codegen import com.squareup.kotlinpoet.MemberName.Companion.member /** * Represents the name of a member (such as a function or a property). * * @property enclosingClassName The enclosing class name or null if this is a package member, * such as a top-level function. */ class XMemberName internal constructor( val enclosingClassName: XClassName?, internal val java: JCodeBlock, internal val kotlin: KMemberName ) { val simpleName = kotlin.simpleName companion object { /** * Creates a [XMemberName] that is contained by the receiving class's companion object. * * @param isJvmStatic if the companion object member is annotated with [JvmStatic] or not. * This will cause generated code to be slightly different in Java since the member can be * referenced without the companion object's `INSTANCE`. */ fun XClassName.companionMember( simpleName: String, isJvmStatic: Boolean = false ): XMemberName { return XMemberName( enclosingClassName = this, java = if (isJvmStatic) { JCodeBlock.of("$T.$L", this.java, simpleName) } else { JCodeBlock.of("$T.INSTANCE.$L", this.java.nestedClass("Companion"), simpleName) }, kotlin = this.kotlin.nestedClass("Companion").member(simpleName) ) } /** * Creates a [XMemberName] is that is contained by the receiving class's package, i.e. * a top-level function or property. * * @see [androidx.room.compiler.processing.XMemberContainer.asClassName] */ fun XClassName.packageMember(simpleName: String): XMemberName { return XMemberName( enclosingClassName = null, java = JCodeBlock.of("$T.$L", this.java, simpleName), kotlin = KMemberName(this.packageName, simpleName) ) } } }
apache-2.0
5b75d2f45ad747cb23a4e4a4eca53fcd
36.788732
99
0.639448
4.797853
false
false
false
false
androidx/androidx
lint-checks/src/main/java/androidx/build/lint/IgnoreClassLevelDetector.kt
3
4678
/* * 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. */ @file:Suppress("UnstableApiUsage") 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.LintFix import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.intellij.psi.PsiMethod import java.util.EnumSet import org.jetbrains.uast.UAnnotation import org.jetbrains.uast.UClass /** * Checks for usages of @org.junit.Ignore at the class level. */ class IgnoreClassLevelDetector : 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 (node.qualifiedName == "org.junit.Ignore" && node.uastParent is UClass) { val incident = Incident(context) .issue(ISSUE) .location(context.getNameLocation(node)) .message("@Ignore should not be used at the class level. Move the annotation " + "to each test individually.") .scope(node) context.report(incident) } } } /** * Creates a LintFix which removes the @Ignore annotation from the class and adds it to each * individual test method. * * TODO(b/235340679): This is currently unused because of issues described in the method body. */ @Suppress("unused") private fun createFix(testClass: UClass, context: JavaContext, annotation: String): LintFix { val fix = fix() .name("Annotate each test method and remove the class-level annotation") .composite() for (method in testClass.allMethods) { if (method.isTestMethod()) { val methodFix = fix() // The replace param on annotate doesn't work: if @Ignore is already present on // the method, the annotation is added again instead of being replaced. .annotate("org.junit.Ignore", true) .range(context.getLocation(method)) .build() fix.add(methodFix) } } val classFix = fix().replace() // This requires the exact text of the class annotation to be passed to this function. // This can be gotten with `node.sourcePsi?.node?.text!!`, but `text`'s doc says using // it should be avoided, so this isn't the best solution. .text(annotation) .with("") .reformat(true) .build() fix.add(classFix) return fix.build() } /** * Checks if this PsiMethod has a @org.junit.Test annotation */ private fun PsiMethod.isTestMethod(): Boolean { for (annotation in this.annotations) { if (annotation.qualifiedName == "org.junit.Test") { return true } } return false } companion object { val ISSUE = Issue.create( "IgnoreClassLevelDetector", "@Ignore should not be used at the class level.", "Using @Ignore at the class level instead of annotating each individual " + "test causes errors in Android Test Hub.", Category.CORRECTNESS, 5, Severity.ERROR, Implementation( IgnoreClassLevelDetector::class.java, EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES) ) ) } }
apache-2.0
5517c734a21e047d1a6f91887f888b36
37.03252
100
0.638093
4.595285
false
true
false
false
androidx/androidx
wear/watchface/watchface/src/main/java/androidx/wear/watchface/BroadcastsObserver.kt
3
5069
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface import android.app.KeyguardManager import android.content.ContentResolver import android.content.Context import android.content.Intent import android.provider.Settings import androidx.annotation.RestrictTo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch /** @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public class BroadcastsObserver( private val watchState: WatchState, private val watchFaceHostApi: WatchFaceHostApi, private val deferredWatchFaceImpl: Deferred<WatchFaceImpl>, private val uiThreadCoroutineScope: CoroutineScope, private val contentResolver: ContentResolver, private val ambientSettingAvailable: Boolean ) : BroadcastsReceiver.BroadcastEventObserver { private var batteryLow: Boolean? = null private var charging: Boolean? = null private var sysUiHasSentWatchUiState: Boolean = false internal companion object { internal const val AMBIENT_ENABLED_PATH = "ambient_enabled" } override fun onActionTimeTick() { // android.intent.action.TIME_TICK is sent by the system at the top of every minute watchFaceHostApi.onActionTimeTick() } override fun onActionTimeZoneChanged() { uiThreadCoroutineScope.launch { deferredWatchFaceImpl.await().onActionTimeZoneChanged() } } override fun onActionTimeChanged() { uiThreadCoroutineScope.launch { deferredWatchFaceImpl.await().onActionTimeChanged() } } override fun onActionBatteryLow() { batteryLow = true if (charging == false) { updateBatteryLowAndNotChargingStatus(true) } } override fun onActionBatteryOkay() { batteryLow = false updateBatteryLowAndNotChargingStatus(false) } override fun onActionPowerConnected() { charging = true updateBatteryLowAndNotChargingStatus(false) } override fun onActionPowerDisconnected() { charging = false if (batteryLow == true) { updateBatteryLowAndNotChargingStatus(true) } } override fun onMockTime(intent: Intent) { uiThreadCoroutineScope.launch { deferredWatchFaceImpl.await().onMockTime(intent) } } private fun updateBatteryLowAndNotChargingStatus(value: Boolean) { val isBatteryLowAndNotCharging = watchState.isBatteryLowAndNotCharging as MutableStateFlow if (!isBatteryLowAndNotCharging.hasValue() || value != isBatteryLowAndNotCharging.value) { isBatteryLowAndNotCharging.value = value watchFaceHostApi.invalidate() } } fun onSysUiHasSentWatchUiState() { sysUiHasSentWatchUiState = true } override fun onActionScreenOff() { val keyguardManager = watchFaceHostApi.getContext().getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager (watchState.isLocked as MutableStateFlow).value = keyguardManager.isDeviceLocked // Before SysUI has connected, we use ActionScreenOn/ActionScreenOff as a trigger to query // AMBIENT_ENABLED_PATH in order to determine if the device os ambient or not. if (sysUiHasSentWatchUiState) { return } val isAmbient = watchState.isAmbient as MutableStateFlow // This is a backup signal for when SysUI is unable to deliver the ambient state (e.g. in // direct boot mode). We need to distinguish between ACTION_SCREEN_OFF for entering ambient // and the screen turning off. This is only possible from R. isAmbient.value = if (ambientSettingAvailable) { Settings.Global.getInt(contentResolver, AMBIENT_ENABLED_PATH, 0) == 1 } else { // On P and below we just have to assume we're not ambient. false } } override fun onActionScreenOn() { (watchState.isLocked as MutableStateFlow).value = false // Before SysUI has connected, we use ActionScreenOn/ActionScreenOff as a trigger to query // AMBIENT_ENABLED_PATH in order to determine if the device os ambient or not. if (sysUiHasSentWatchUiState) { return } val isAmbient = watchState.isAmbient as MutableStateFlow isAmbient.value = false } }
apache-2.0
01d57f10ded7d19314ddea5689c98e62
33.726027
99
0.698954
4.823026
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/refactoring/suggested/PySuggestedRefactoringUI.kt
7
4636
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.jetbrains.python.refactoring.suggested import com.intellij.openapi.ui.ValidationInfo import com.intellij.psi.PsiCodeFragment import com.intellij.refactoring.suggested.* import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Parameter import com.jetbrains.python.PyBundle import com.jetbrains.python.psi.PyExpressionStatement import com.jetbrains.python.psi.impl.ParamHelper import com.jetbrains.python.refactoring.changeSignature.PyExpressionCodeFragment import com.jetbrains.python.refactoring.suggested.PySuggestedRefactoringSupport.Companion.defaultValue import org.jetbrains.annotations.Nls import javax.swing.JComponent internal object PySuggestedRefactoringUI : SuggestedRefactoringUI() { override fun createSignaturePresentationBuilder(signature: SuggestedRefactoringSupport.Signature, otherSignature: SuggestedRefactoringSupport.Signature, isOldSignature: Boolean): SignaturePresentationBuilder { return PySignaturePresentationBuilder(signature, otherSignature, isOldSignature) } override fun extractNewParameterData(data: SuggestedChangeSignatureData): List<NewParameterData> { val project = data.declaration.project return data.newSignature.parameters .map { it to data.oldSignature.parameterById(it.id) } .filter { (parameter, oldParameter) -> if (oldParameter == null) { ParamHelper.couldHaveDefaultValue(parameter.name) } else { defaultValue(oldParameter) != null && defaultValue(parameter) == null } } .map { (parameter, oldParameter) -> val valueFragment = PyExpressionCodeFragment(project, parameter.name, "") val shouldHaveDefaultValue = shouldHaveDefaultValue(parameter, oldParameter) NewParameterData( parameter.name, valueFragment, false, placeholderText(shouldHaveDefaultValue), ParameterData(shouldHaveDefaultValue) ) } } override fun validateValue(data: NewParameterData, component: JComponent?): ValidationInfo? { if (data.valueFragment.text.isNotBlank()) return null val shouldHaveDefaultValue = (data.additionalData as? ParameterData)?.shouldHaveDefaultValue return when { shouldHaveDefaultValue == null || !shouldHaveDefaultValue -> null else -> ValidationInfo(PyBundle.message("refactoring.change.signature.dialog.validation.default.missing"), component) } } override fun extractValue(fragment: PsiCodeFragment): SuggestedRefactoringExecution.NewParameterValue.Expression? { val expression = (fragment.firstChild as? PyExpressionStatement)?.expression ?: return null return SuggestedRefactoringExecution.NewParameterValue.Expression(expression) } @Nls(capitalization = Nls.Capitalization.Sentence) private fun placeholderText(shouldHaveDefaultValue: Boolean): String { return if (shouldHaveDefaultValue) PyBundle.message("refactoring.change.signature.suggested.callSite.value") else PyBundle.message("refactoring.change.signature.suggested.callSite.value.optional") } private fun shouldHaveDefaultValue(newParameter: Parameter, oldParameter: Parameter?): Boolean { return ParamHelper.couldHaveDefaultValue(newParameter.name) && defaultValue(newParameter) == null && oldParameter?.let { defaultValue(it) } == null } private class PySignaturePresentationBuilder( signature: SuggestedRefactoringSupport.Signature, otherSignature: SuggestedRefactoringSupport.Signature, isOldSignature: Boolean ) : SignaturePresentationBuilder(signature, otherSignature, isOldSignature) { override fun buildPresentation() { fragments += leaf(signature.name, otherSignature.name) buildParameterList { fragments, parameter, correspondingParameter -> fragments += leaf(parameter.name, correspondingParameter?.name ?: parameter.name) val defaultValuePart = defaultValuePartInSignature(parameter) if (defaultValuePart != null) { fragments += leaf(defaultValuePart, correspondingParameter?.let { defaultValuePartInSignature(it) }) } } } private fun defaultValuePartInSignature(parameter: Parameter): String? { return ParamHelper.getDefaultValuePartInSignature(defaultValue(parameter), false) } } private data class ParameterData(val shouldHaveDefaultValue: Boolean) : NewParameterAdditionalData }
apache-2.0
7d49da88afd4bd69db43ce12f8769cc2
44.019417
123
0.749353
5.428571
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/diff/CombinedDiffPreview.kt
4
7696
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.actions.diff import com.intellij.diff.chains.DiffRequestProducer import com.intellij.diff.tools.combined.* import com.intellij.openapi.Disposable import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.changes.ChangeViewDiffRequestProcessor.Wrapper import com.intellij.openapi.vcs.changes.DiffPreviewUpdateProcessor import com.intellij.openapi.vcs.changes.DiffRequestProcessorWithProducers import com.intellij.openapi.vcs.changes.EditorTabPreviewBase import com.intellij.openapi.vcs.changes.actions.diff.CombinedDiffPreviewModel.Companion.prepareCombinedDiffModelRequests import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.ExpandableItemsHandler import com.intellij.util.ui.UIUtil import com.intellij.vcsUtil.Delegates import org.jetbrains.annotations.NonNls import javax.swing.JComponent import javax.swing.JTree.TREE_MODEL_PROPERTY @JvmField internal val COMBINED_DIFF_PREVIEW_TAB_NAME = Key.create<() -> @NlsContexts.TabTitle String>("combined_diff_preview_tab_name") class CombinedDiffPreviewVirtualFile(sourceId: String) : CombinedDiffVirtualFile(sourceId, "") abstract class CombinedDiffPreview(protected val tree: ChangesTree, targetComponent: JComponent, isOpenEditorDiffPreviewWithSingleClick: Boolean, needSetupOpenPreviewListeners: Boolean, parentDisposable: Disposable) : EditorTabPreviewBase(tree.project, parentDisposable) { constructor(tree: ChangesTree, parentDisposable: Disposable) : this(tree, tree, false, true, parentDisposable) override val previewFile: VirtualFile by lazy { CombinedDiffPreviewVirtualFile(tree.id) } override val updatePreviewProcessor get() = model protected val model by lazy { createModel().also { model -> model.context.putUserData(COMBINED_DIFF_PREVIEW_TAB_NAME, ::getCombinedDiffTabTitle) project.service<CombinedDiffModelRepository>().registerModel(tree.id, model) } } override fun updatePreview(fromModelRefresh: Boolean) { super.updatePreview(fromModelRefresh) if (isPreviewOpen()) { FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(previewFile) } } init { escapeHandler = Runnable { closePreview() returnFocusToTree() } if (needSetupOpenPreviewListeners) { installListeners(tree, isOpenEditorDiffPreviewWithSingleClick) installNextDiffActionOn(targetComponent) } UIUtil.putClientProperty(tree, ExpandableItemsHandler.IGNORE_ITEM_SELECTION, true) installCombinedDiffModelListener() } private fun installCombinedDiffModelListener() { tree.addPropertyChangeListener(TREE_MODEL_PROPERTY) { if (model.ourDisposable.isDisposed) return@addPropertyChangeListener val changes = model.iterateSelectedOrAllChanges().toList() if (changes.isNotEmpty()) { model.refresh(true) model.reset(prepareCombinedDiffModelRequests(project, changes)) } } } open fun returnFocusToTree() = Unit override fun isPreviewOnDoubleClickAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnDoubleClickAllowed() override fun isPreviewOnEnterAllowed(): Boolean = isCombinedPreviewAllowed() && super.isPreviewOnEnterAllowed() protected abstract fun createModel(): CombinedDiffPreviewModel protected abstract fun getCombinedDiffTabTitle(): String override fun updateDiffAction(event: AnActionEvent) { event.presentation.isVisible = event.isFromActionToolbar || event.presentation.isEnabled } override fun getCurrentName(): String? = model.selected?.presentableName override fun hasContent(): Boolean = model.requests.isNotEmpty() internal fun getFileSize(): Int = model.requests.size protected val ChangesTree.id: @NonNls String get() = javaClass.name + "@" + Integer.toHexString(hashCode()) private fun isCombinedPreviewAllowed() = Registry.`is`("enable.combined.diff") } abstract class CombinedDiffPreviewModel(protected val tree: ChangesTree, requests: Map<CombinedBlockId, DiffRequestProducer>, parentDisposable: Disposable) : CombinedDiffModelImpl(tree.project, requests, parentDisposable), DiffPreviewUpdateProcessor, DiffRequestProcessorWithProducers { var selected by Delegates.equalVetoingObservable<Wrapper?>(null) { change -> if (change != null) { selectChangeInTree(change) scrollToChange(change) } } companion object { @JvmStatic fun prepareCombinedDiffModelRequests(project: Project, changes: List<Wrapper>): Map<CombinedBlockId, DiffRequestProducer> { return changes .asSequence() .mapNotNull { wrapper -> wrapper.createProducer(project) ?.let { CombinedPathBlockId(wrapper.filePath, wrapper.fileStatus, wrapper.tag) to it } }.toMap() } } override fun collectDiffProducers(selectedOnly: Boolean): ListSelection<DiffRequestProducer> { return ListSelection.create(requests.values.toList(), selected?.createProducer(project)) } abstract fun iterateAllChanges(): Iterable<Wrapper> protected abstract fun iterateSelectedChanges(): Iterable<Wrapper> protected open fun showAllChangesForEmptySelection(): Boolean { return true } override fun clear() { init() } override fun refresh(fromModelRefresh: Boolean) { if (ourDisposable.isDisposed) return val selectedChanges = iterateSelectedOrAllChanges().toList() val selectedChange = selected?.let { prevSelected -> selectedChanges.find { it == prevSelected } } if (fromModelRefresh && selectedChange == null && selected != null && context.isWindowFocused && context.isFocusedInWindow) { // Do not automatically switch focused viewer if (selectedChanges.size == 1 && iterateAllChanges().any { it: Wrapper -> selected == it }) { selected?.run(::selectChangeInTree) // Restore selection if necessary } return } val newSelected = when { selectedChanges.isEmpty() -> null selectedChange == null -> selectedChanges[0] else -> selectedChange } newSelected?.let { context.putUserData(COMBINED_DIFF_SCROLL_TO_BLOCK, CombinedPathBlockId(it.filePath, it.fileStatus, it.tag)) } selected = newSelected } internal fun iterateSelectedOrAllChanges(): Iterable<Wrapper> { return if (iterateSelectedChanges().none() && showAllChangesForEmptySelection()) iterateAllChanges() else iterateSelectedChanges() } private fun scrollToChange(change: Wrapper) { context.getUserData(COMBINED_DIFF_VIEWER_KEY) ?.selectDiffBlock(CombinedPathBlockId(change.filePath, change.fileStatus, change.tag), ScrollPolicy.DIFF_BLOCK, false) } open fun selectChangeInTree(change: Wrapper) { ChangesBrowserBase.selectObjectWithTag(tree, change.userObject, change.tag) } override fun getComponent(): JComponent = throw UnsupportedOperationException() //only for splitter preview }
apache-2.0
79ef167c45a4862df9215c019ce76fb6
38.875648
134
0.747921
4.800998
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/MacToolbarFrameHeader.kt
1
3996
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.customFrameDecorations.header import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.impl.IdeMenuBar import com.intellij.openapi.wm.impl.ToolbarHolder import com.intellij.openapi.wm.impl.customFrameDecorations.CustomFrameTitleButtons import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar import com.intellij.ui.awt.RelativeRectangle import com.intellij.ui.mac.MacMainFrameDecorator import com.intellij.util.ui.JBUI import com.jetbrains.CustomWindowDecoration import com.jetbrains.JBR import java.awt.BorderLayout import java.awt.Component import java.awt.Rectangle import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.beans.PropertyChangeListener import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JRootPane private const val GAP_FOR_BUTTONS = 80 private const val DEFAULT_HEADER_HEIGHT = 40 internal class MacToolbarFrameHeader(private val frame: JFrame, private val root: JRootPane, private val ideMenu: IdeMenuBar) : CustomHeader(frame), MainFrameCustomHeader, ToolbarHolder { private var toolbar: MainToolbar? init { layout = BorderLayout() root.addPropertyChangeListener(MacMainFrameDecorator.FULL_SCREEN, PropertyChangeListener { updateBorders() }) add(ideMenu, BorderLayout.NORTH) toolbar = createToolBar() } private fun createToolBar(): MainToolbar { val toolbar = MainToolbar() toolbar.isOpaque = false toolbar.addComponentListener(object: ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { updateCustomDecorationHitTestSpots() super.componentResized(e) } }) add(toolbar, BorderLayout.CENTER) return toolbar } override fun initToolbar() { var tb = toolbar if (tb == null) { tb = createToolBar() toolbar = tb } tb.init((frame as? IdeFrame)?.project) } override fun updateToolbar() { removeToolbar() val toolbar = createToolBar() this.toolbar = toolbar toolbar.init((frame as? IdeFrame)?.project) revalidate() updateCustomDecorationHitTestSpots() } override fun removeToolbar() { val toolbar = toolbar ?: return this.toolbar = null remove(toolbar) revalidate() } override fun windowStateChanged() { super.windowStateChanged() updateBorders() } override fun addNotify() { super.addNotify() updateBorders() val decor = JBR.getCustomWindowDecoration() decor.setCustomDecorationTitleBarHeight(frame, DEFAULT_HEADER_HEIGHT) } override fun createButtonsPane(): CustomFrameTitleButtons = CustomFrameTitleButtons.create(myCloseAction) override fun getHitTestSpots(): Sequence<Pair<RelativeRectangle, Int>> { return (toolbar ?: return emptySequence()) .components .asSequence() .filter { it.isVisible } .map { Pair(getElementRect(it), CustomWindowDecoration.MENU_BAR) } } override fun updateMenuActions(forceRebuild: Boolean) = ideMenu.updateMenuActions(forceRebuild) override fun getComponent(): JComponent = this override fun dispose() {} private fun getElementRect(comp: Component): RelativeRectangle { val rect = Rectangle(comp.size) return RelativeRectangle(comp, rect) } override fun getHeaderBackground(active: Boolean) = JBUI.CurrentTheme.CustomFrameDecorations.mainToolbarBackground(active) private fun updateBorders() { val isFullscreen = root.getClientProperty(MacMainFrameDecorator.FULL_SCREEN) != null border = if (isFullscreen) JBUI.Borders.empty() else JBUI.Borders.emptyLeft(GAP_FOR_BUTTONS) toolbar?.let { it.border = JBUI.Borders.empty() } } override fun updateActive() { super.updateActive() toolbar?.background = getHeaderBackground(myActive) } }
apache-2.0
476fbc1be4771cc8e61d9e45426a5c27
30.722222
131
0.737237
4.561644
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadManager.kt
1
17137
package eu.kanade.tachiyomi.data.download import android.content.Context import android.net.Uri import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.download.model.Download import eu.kanade.tachiyomi.data.download.model.DownloadQueue import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.source.Source import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.data.source.model.Page import eu.kanade.tachiyomi.data.source.online.OnlineSource import eu.kanade.tachiyomi.util.* import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import timber.log.Timber import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.io.File import java.io.FileReader import java.util.* class DownloadManager( private val context: Context, private val sourceManager: SourceManager = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get() ) { private val gson = Gson() private val downloadsQueueSubject = PublishSubject.create<List<Download>>() val runningSubject = BehaviorSubject.create<Boolean>() private var downloadsSubscription: Subscription? = null val downloadNotifier by lazy { DownloadNotifier(context) } private val threadsSubject = BehaviorSubject.create<Int>() private var threadsSubscription: Subscription? = null val queue = DownloadQueue() val imageFilenameRegex = "[^\\sa-zA-Z0-9.-]".toRegex() val PAGE_LIST_FILE = "index.json" @Volatile var isRunning: Boolean = false private set private fun initializeSubscriptions() { downloadsSubscription?.unsubscribe() threadsSubscription = preferences.downloadThreads().asObservable() .subscribe { threadsSubject.onNext(it) downloadNotifier.multipleDownloadThreads = it > 1 } downloadsSubscription = downloadsQueueSubject.flatMap { Observable.from(it) } .lift(DynamicConcurrentMergeOperator<Download, Download>({ downloadChapter(it) }, threadsSubject)) .onBackpressureBuffer() .observeOn(AndroidSchedulers.mainThread()) .subscribe({ // Delete successful downloads from queue if (it.status == Download.DOWNLOADED) { // remove downloaded chapter from queue queue.del(it) downloadNotifier.onProgressChange(queue) } if (areAllDownloadsFinished()) { DownloadService.stop(context) } }, { error -> DownloadService.stop(context) Timber.e(error) downloadNotifier.onError(error.message) }) if (!isRunning) { isRunning = true runningSubject.onNext(true) } } fun destroySubscriptions() { if (isRunning) { isRunning = false runningSubject.onNext(false) } if (downloadsSubscription != null) { downloadsSubscription?.unsubscribe() downloadsSubscription = null } if (threadsSubscription != null) { threadsSubscription?.unsubscribe() } } // Create a download object for every chapter and add them to the downloads queue fun downloadChapters(manga: Manga, chapters: List<Chapter>) { val source = sourceManager.get(manga.source) as? OnlineSource ?: return // Add chapters to queue from the start val sortedChapters = chapters.sortedByDescending { it.source_order } // Used to avoid downloading chapters with the same name val addedChapters = ArrayList<String>() val pending = ArrayList<Download>() for (chapter in sortedChapters) { if (addedChapters.contains(chapter.name)) continue addedChapters.add(chapter.name) val download = Download(source, manga, chapter) if (!prepareDownload(download)) { queue.add(download) pending.add(download) } } // Initialize queue size downloadNotifier.initialQueueSize = queue.size // Show notification downloadNotifier.onProgressChange(queue) if (isRunning) downloadsQueueSubject.onNext(pending) } // Public method to check if a chapter is downloaded fun isChapterDownloaded(source: Source, manga: Manga, chapter: Chapter): Boolean { val directory = getAbsoluteChapterDirectory(source, manga, chapter) if (!directory.exists()) return false val pages = getSavedPageList(source, manga, chapter) return isChapterDownloaded(directory, pages) } // Prepare the download. Returns true if the chapter is already downloaded private fun prepareDownload(download: Download): Boolean { // If the chapter is already queued, don't add it again for (queuedDownload in queue) { if (download.chapter.id == queuedDownload.chapter.id) return true } // Add the directory to the download object for future access download.directory = getAbsoluteChapterDirectory(download) // If the directory doesn't exist, the chapter isn't downloaded. if (!download.directory.exists()) { return false } // If the page list doesn't exist, the chapter isn't downloaded val savedPages = getSavedPageList(download) ?: return false // Add the page list to the download object for future access download.pages = savedPages // If the number of files matches the number of pages, the chapter is downloaded. // We have the index file, so we check one file more return isChapterDownloaded(download.directory, download.pages) } // Check that all the images are downloaded private fun isChapterDownloaded(directory: File, pages: List<Page>?): Boolean { return pages != null && !pages.isEmpty() && pages.size + 1 == directory.listFiles().size } // Download the entire chapter private fun downloadChapter(download: Download): Observable<Download> { DiskUtils.createDirectory(download.directory) val pageListObservable: Observable<List<Page>> = if (download.pages == null) // Pull page list from network and add them to download object download.source.fetchPageListFromNetwork(download.chapter) .doOnNext { pages -> download.pages = pages savePageList(download) } else // Or if the page list already exists, start from the file Observable.just(download.pages) return Observable.defer { pageListObservable .doOnNext { pages -> download.downloadedImages = 0 download.status = Download.DOWNLOADING } // Get all the URLs to the source images, fetch pages if necessary .flatMap { download.source.fetchAllImageUrlsFromPageList(it) } // Start downloading images, consider we can have downloaded images already .concatMap { page -> getOrDownloadImage(page, download) } // Do when page is downloaded. .doOnNext { downloadNotifier.onProgressChange(download, queue) } // Do after download completes .doOnCompleted { onDownloadCompleted(download) } .toList() .map { pages -> download } // If the page list threw, it will resume here .onErrorResumeNext { error -> download.status = Download.ERROR downloadNotifier.onError(error.message, download.chapter.name) Observable.just(download) } }.subscribeOn(Schedulers.io()) } // Get the image from the filesystem if it exists or download from network private fun getOrDownloadImage(page: Page, download: Download): Observable<Page> { // If the image URL is empty, do nothing if (page.imageUrl == null) return Observable.just(page) val filename = getImageFilename(page) val imagePath = File(download.directory, filename) // If the image is already downloaded, do nothing. Otherwise download from network val pageObservable = if (isImageDownloaded(imagePath)) Observable.just(page) else downloadImage(page, download.source, download.directory, filename) return pageObservable // When the image is ready, set image path, progress (just in case) and status .doOnNext { page.imagePath = imagePath.absolutePath page.progress = 100 download.downloadedImages++ page.status = Page.READY } // Mark this page as error and allow to download the remaining .onErrorResumeNext { page.progress = 0 page.status = Page.ERROR Observable.just(page) } } // Save image on disk private fun downloadImage(page: Page, source: OnlineSource, directory: File, filename: String): Observable<Page> { page.status = Page.DOWNLOAD_IMAGE return source.imageResponse(page) .map { val file = File(directory, filename) try { file.parentFile.mkdirs() it.body().source().saveImageTo(file.outputStream(), preferences.reencodeImage()) } catch (e: Exception) { it.close() file.delete() throw e } page } // Retry 3 times, waiting 2, 4 and 8 seconds between attempts. .retryWhen(RetryWithDelay(3, { (2 shl it - 1) * 1000 }, Schedulers.trampoline())) } // Public method to get the image from the filesystem. It does NOT provide any way to download the image fun getDownloadedImage(page: Page, chapterDir: File): Observable<Page> { if (page.imageUrl == null) { page.status = Page.ERROR return Observable.just(page) } val imagePath = File(chapterDir, getImageFilename(page)) // When the image is ready, set image path, progress (just in case) and status if (isImageDownloaded(imagePath)) { page.imagePath = imagePath.absolutePath page.progress = 100 page.status = Page.READY } else { page.status = Page.ERROR } return Observable.just(page) } // Get the filename for an image given the page private fun getImageFilename(page: Page): String { val url = page.imageUrl val number = String.format("%03d", page.pageNumber + 1) // Try to preserve file extension return when { UrlUtil.isJpg(url) -> "$number.jpg" UrlUtil.isPng(url) -> "$number.png" UrlUtil.isGif(url) -> "$number.gif" else -> Uri.parse(url).lastPathSegment.replace(imageFilenameRegex, "_") } } private fun isImageDownloaded(imagePath: File): Boolean { return imagePath.exists() } // Called when a download finishes. This doesn't mean the download was successful, so we check it private fun onDownloadCompleted(download: Download) { checkDownloadIsSuccessful(download) savePageList(download) } private fun checkDownloadIsSuccessful(download: Download) { var actualProgress = 0 var status = Download.DOWNLOADED // If any page has an error, the download result will be error for (page in download.pages!!) { actualProgress += page.progress if (page.status != Page.READY) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_ready_error), download.chapter.name) } } // Ensure that the chapter folder has all the images if (!isChapterDownloaded(download.directory, download.pages)) { status = Download.ERROR downloadNotifier.onError(context.getString(R.string.download_notifier_page_error), download.chapter.name) } download.totalProgress = actualProgress download.status = status } // Return the page list from the chapter's directory if it exists, null otherwise fun getSavedPageList(source: Source, manga: Manga, chapter: Chapter): List<Page>? { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) return try { JsonReader(FileReader(pagesFile)).use { val collectionType = object : TypeToken<List<Page>>() {}.type gson.fromJson(it, collectionType) } } catch (e: Exception) { null } } // Shortcut for the method above private fun getSavedPageList(download: Download): List<Page>? { return getSavedPageList(download.source, download.manga, download.chapter) } // Save the page list to the chapter's directory fun savePageList(source: Source, manga: Manga, chapter: Chapter, pages: List<Page>) { val chapterDir = getAbsoluteChapterDirectory(source, manga, chapter) val pagesFile = File(chapterDir, PAGE_LIST_FILE) pagesFile.outputStream().use { try { it.write(gson.toJson(pages).toByteArray()) it.flush() } catch (error: Exception) { Timber.e(error) } } } // Shortcut for the method above private fun savePageList(download: Download) { savePageList(download.source, download.manga, download.chapter, download.pages!!) } fun getAbsoluteMangaDirectory(source: Source, manga: Manga): File { val mangaRelativePath = source.toString() + File.separator + manga.title.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(preferences.downloadsDirectory().getOrDefault(), mangaRelativePath) } // Get the absolute path to the chapter directory fun getAbsoluteChapterDirectory(source: Source, manga: Manga, chapter: Chapter): File { val chapterRelativePath = chapter.name.replace("[^\\sa-zA-Z0-9.-]".toRegex(), "_") return File(getAbsoluteMangaDirectory(source, manga), chapterRelativePath) } // Shortcut for the method above private fun getAbsoluteChapterDirectory(download: Download): File { return getAbsoluteChapterDirectory(download.source, download.manga, download.chapter) } fun deleteChapter(source: Source, manga: Manga, chapter: Chapter) { val path = getAbsoluteChapterDirectory(source, manga, chapter) DiskUtils.deleteFiles(path) } fun areAllDownloadsFinished(): Boolean { for (download in queue) { if (download.status <= Download.DOWNLOADING) return false } return true } fun startDownloads(): Boolean { if (queue.isEmpty()) return false if (downloadsSubscription == null || downloadsSubscription!!.isUnsubscribed) initializeSubscriptions() val pending = ArrayList<Download>() for (download in queue) { if (download.status != Download.DOWNLOADED) { if (download.status != Download.QUEUE) download.status = Download.QUEUE pending.add(download) } } downloadsQueueSubject.onNext(pending) return !pending.isEmpty() } fun stopDownloads(errorMessage: String? = null) { destroySubscriptions() for (download in queue) { if (download.status == Download.DOWNLOADING) { download.status = Download.ERROR } } errorMessage?.let { downloadNotifier.onError(it) } } fun clearQueue() { queue.clear() downloadNotifier.onClear() } }
gpl-3.0
74b010049b7dd64ea023744d40aae9a6
37.082222
127
0.612126
5.089694
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-common/src/org/jetbrains/kotlin/config/KotlinFacetSettings.kt
1
11029
// 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.config import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import org.jetbrains.kotlin.cli.common.arguments.Argument import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments import org.jetbrains.kotlin.cli.common.arguments.copyBean import org.jetbrains.kotlin.cli.common.arguments.parseCommandLineArguments import org.jetbrains.kotlin.platform.IdePlatformKind import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.TargetPlatformVersion import org.jetbrains.kotlin.platform.compat.toIdePlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.utils.DescriptionAware import org.jetbrains.kotlin.utils.addToStdlib.safeAs import kotlin.reflect.KProperty1 import kotlin.reflect.full.findAnnotation @Deprecated("Use IdePlatformKind instead.", level = DeprecationLevel.ERROR) sealed class TargetPlatformKind<out Version : TargetPlatformVersion>( val version: Version, val name: String ) : DescriptionAware { override val description = "$name ${version.description}" class Jvm(version: JvmTarget) : @Suppress("DEPRECATION_ERROR") TargetPlatformKind<JvmTarget>(version, "JVM") { companion object { private val JVM_PLATFORMS by lazy { JvmTarget.values().map(::Jvm) } operator fun get(version: JvmTarget) = JVM_PLATFORMS[version.ordinal] } } object JavaScript : @Suppress("DEPRECATION_ERROR") TargetPlatformKind<TargetPlatformVersion.NoVersion>( TargetPlatformVersion.NoVersion, "JavaScript" ) object Common : @Suppress("DEPRECATION_ERROR") TargetPlatformKind<TargetPlatformVersion.NoVersion>( TargetPlatformVersion.NoVersion, "Common (experimental)" ) } sealed class VersionView : DescriptionAware { abstract val version: LanguageVersion object LatestStable : VersionView() { override val version: LanguageVersion = RELEASED_VERSION override val description: String get() = "Latest stable (${version.versionString})" } class Specific(override val version: LanguageVersion) : VersionView() { override val description: String get() = version.description override fun equals(other: Any?) = other is Specific && version == other.version override fun hashCode() = version.hashCode() } companion object { val RELEASED_VERSION = LanguageVersion.LATEST_STABLE fun deserialize(value: String?, isAutoAdvance: Boolean): VersionView { if (isAutoAdvance) return LatestStable val languageVersion = LanguageVersion.fromVersionString(value) return if (languageVersion != null) Specific(languageVersion) else LatestStable } } } var CommonCompilerArguments.languageVersionView: VersionView get() = VersionView.deserialize(languageVersion, autoAdvanceLanguageVersion) set(value) { languageVersion = value.version.versionString autoAdvanceLanguageVersion = value == VersionView.LatestStable } var CommonCompilerArguments.apiVersionView: VersionView get() = VersionView.deserialize(apiVersion, autoAdvanceApiVersion) set(value) { apiVersion = value.version.versionString autoAdvanceApiVersion = value == VersionView.LatestStable } enum class KotlinModuleKind { DEFAULT, SOURCE_SET_HOLDER, COMPILATION_AND_SOURCE_SET_HOLDER; @Deprecated("Use KotlinFacetSettings.mppVersion.isNewMpp") val isNewMPP: Boolean get() = this != DEFAULT } enum class KotlinMultiplatformVersion(val version: Int) { M1(1), // the first implementation of MPP. Aka 1.2.0 MPP M2(2), // the "New" MPP. Aka 1.3.0 MPP M3(3) // the "Hierarchical" MPP. } val KotlinMultiplatformVersion?.isOldMpp: Boolean get() = this == KotlinMultiplatformVersion.M1 val KotlinMultiplatformVersion?.isNewMPP: Boolean get() = this == KotlinMultiplatformVersion.M2 val KotlinMultiplatformVersion?.isHmpp: Boolean get() = this == KotlinMultiplatformVersion.M3 interface ExternalSystemRunTask { val taskName: String val externalSystemProjectId: String val targetName: String? } data class ExternalSystemTestRunTask( override val taskName: String, override val externalSystemProjectId: String, override val targetName: String? ) : ExternalSystemRunTask { fun toStringRepresentation() = "$taskName|$externalSystemProjectId|$targetName" companion object { fun fromStringRepresentation(line: String) = line.split("|").let { if (it.size == 3) ExternalSystemTestRunTask(it[0], it[1], it[2]) else null } } override fun toString() = "$taskName@$externalSystemProjectId [$targetName]" } data class ExternalSystemNativeMainRunTask( override val taskName: String, override val externalSystemProjectId: String, override val targetName: String?, val entryPoint: String, val debuggable: Boolean, ) : ExternalSystemRunTask { fun toStringRepresentation() = "$taskName|$externalSystemProjectId|$targetName|$entryPoint|$debuggable" companion object { fun fromStringRepresentation(line: String): ExternalSystemNativeMainRunTask? = line.split("|").let { if (it.size == 5) ExternalSystemNativeMainRunTask(it[0], it[1], it[2], it[3], it[4].toBoolean()) else null } } } class KotlinFacetSettings { companion object { // Increment this when making serialization-incompatible changes to configuration data val CURRENT_VERSION = 4 val DEFAULT_VERSION = 0 } var version = CURRENT_VERSION var useProjectSettings: Boolean = true var mergedCompilerArguments: CommonCompilerArguments? = null private set // TODO: Workaround for unwanted facet settings modification on code analysis // To be replaced with proper API for settings update (see BaseKotlinCompilerSettings as an example) fun updateMergedArguments() { val compilerArguments = compilerArguments val compilerSettings = compilerSettings mergedCompilerArguments = if (compilerArguments != null) { copyBean(compilerArguments).apply { if (compilerSettings != null) { parseCommandLineArguments(compilerSettings.additionalArgumentsAsList, this) } } } else null } var compilerArguments: CommonCompilerArguments? = null set(value) { field = value?.unfrozen() as CommonCompilerArguments? updateMergedArguments() } var compilerSettings: CompilerSettings? = null set(value) { field = value?.unfrozen() as CompilerSettings? updateMergedArguments() } /* This function is needed as some setting values may not be present in compilerArguments but present in additional arguments instead, so we have to check both cases manually */ inline fun <reified A : CommonCompilerArguments> isCompilerSettingPresent(settingReference: KProperty1<A, Boolean>): Boolean { val isEnabledByCompilerArgument = compilerArguments?.safeAs<A>()?.let(settingReference::get) if (isEnabledByCompilerArgument == true) return true val isEnabledByAdditionalSettings = run { val stringArgumentName = settingReference.findAnnotation<Argument>()?.value ?: return@run null compilerSettings?.additionalArguments?.contains(stringArgumentName, ignoreCase = true) } return isEnabledByAdditionalSettings ?: false } var languageLevel: LanguageVersion? get() = compilerArguments?.languageVersion?.let { LanguageVersion.fromFullVersionString(it) } set(value) { compilerArguments?.apply { languageVersion = value?.versionString } } var apiLevel: LanguageVersion? get() = compilerArguments?.apiVersion?.let { LanguageVersion.fromFullVersionString(it) } set(value) { compilerArguments?.apply { apiVersion = value?.versionString } } var targetPlatform: TargetPlatform? = null get() { // This work-around is required in order to fix importing of the proper JVM target version and works only // for fully actualized JVM target platform //TODO(auskov): this hack should be removed after fixing equals in SimplePlatform val args = compilerArguments val singleSimplePlatform = field?.componentPlatforms?.singleOrNull() if (singleSimplePlatform == JvmPlatforms.defaultJvmPlatform.singleOrNull() && args != null) { return IdePlatformKind.platformByCompilerArguments(args) } return field } var externalSystemRunTasks: List<ExternalSystemRunTask> = emptyList() @Suppress("DEPRECATION_ERROR") @Deprecated( message = "This accessor is deprecated and will be removed soon, use API from 'org.jetbrains.kotlin.platform.*' packages instead", replaceWith = ReplaceWith("targetPlatform"), level = DeprecationLevel.ERROR ) fun getPlatform(): org.jetbrains.kotlin.platform.IdePlatform<*, *>? { return targetPlatform?.toIdePlatform() } var implementedModuleNames: List<String> = emptyList() // used for first implementation of MPP, aka 'old' MPP var dependsOnModuleNames: List<String> = emptyList() // used for New MPP and later implementations var productionOutputPath: String? = null var testOutputPath: String? = null var kind: KotlinModuleKind = KotlinModuleKind.DEFAULT var sourceSetNames: List<String> = emptyList() var isTestModule: Boolean = false var externalProjectId: String = "" var isHmppEnabled: Boolean = false @Deprecated(message = "Use mppVersion.isHmppEnabled", ReplaceWith("mppVersion.isHmpp")) get val mppVersion: KotlinMultiplatformVersion? @Suppress("DEPRECATION") get() = when { isHmppEnabled -> KotlinMultiplatformVersion.M3 kind.isNewMPP -> KotlinMultiplatformVersion.M2 targetPlatform.isCommon() || implementedModuleNames.isNotEmpty() -> KotlinMultiplatformVersion.M1 else -> null } var pureKotlinSourceFolders: List<String> = emptyList() } interface KotlinFacetSettingsProvider { fun getSettings(module: Module): KotlinFacetSettings? fun getInitializedSettings(module: Module): KotlinFacetSettings companion object { fun getInstance(project: Project): KotlinFacetSettingsProvider? = project.takeUnless(Project::isDisposed) ?.getService(KotlinFacetSettingsProvider::class.java) } }
apache-2.0
24c844df619f791bf57e41fac357b9ba
37.428571
158
0.704325
5.125
false
false
false
false
K0zka/kerub
src/test/kotlin/com/github/kerubistan/kerub/utils/junix/ifconfig/IfConfigTest.kt
2
1740
package com.github.kerubistan.kerub.utils.junix.ifconfig import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.whenever import io.github.kerubistan.kroki.io.resource import org.apache.commons.io.input.NullInputStream import org.apache.sshd.client.channel.ChannelExec import org.apache.sshd.client.future.OpenFuture import org.apache.sshd.client.session.ClientSession import org.junit.Assert.assertEquals import org.junit.Test class IfConfigTest { val session: ClientSession = mock() private val exec: ChannelExec = mock() val future: OpenFuture = mock() @Test fun listWithLinux() { whenever(session.createExecChannel(any())).thenReturn(exec) whenever(exec.open()).thenReturn(future) whenever(exec.invertedErr).thenReturn(NullInputStream(0)) whenever(exec.invertedOut).thenAnswer { resource("com/github/kerubistan/kerub/utils/junix/ifconfig/linuxsample.txt") } val list = IfConfig.list(session) assertEquals(3, list.size) assertEquals("enp2s0", list[0].name) assertEquals(1500, list[0].mtu) assertEquals("68:f7:28:e2:29:e5", list[0].mac) assertEquals("lo", list[1].name) assertEquals(65536, list[1].mtu) assertEquals("virbr0", list[2].name) assertEquals(1500, list[2].mtu) } @Test fun listWithBsd() { whenever(session.createExecChannel(any())).thenReturn(exec) whenever(exec.open()).thenReturn(future) whenever(exec.invertedErr).thenReturn(NullInputStream(0)) whenever(exec.invertedOut).thenAnswer { resource("com/github/kerubistan/kerub/utils/junix/ifconfig/bsdsample.txt") } val list = IfConfig.list(session) assertEquals(2, list.size) assertEquals("vtnet0", list[0].name) assertEquals(1500, list[0].mtu) } }
apache-2.0
d86e16ccd60385e83aad1ca12a5e1e77
29.54386
79
0.763793
3.276836
false
true
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/CheckSuggestedPluginsAction.kt
5
1014
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.intellij.ide.IdeBundle import com.intellij.ide.impl.runBlockingUnderModalProgress import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction internal class CheckSuggestedPluginsAction : DumbAwareAction() { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return runBlockingUnderModalProgress(title = IdeBundle.message("plugins.advertiser.check.progress"), project = project) { PluginsAdvertiserStartupActivity().checkSuggestedPlugins(project = project, includeIgnored = true) } } override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.project != null } override fun getActionUpdateThread() = ActionUpdateThread.BGT }
apache-2.0
5ba7e6f3f586cc0673d6fef50cbb61a0
41.291667
120
0.801775
4.92233
false
false
false
false
Phakx/AdventOfCode
2016/kotlin/src/advent/8.kt
1
2085
package advent import java.io.File /** * Created by bkeucher on 12/27/16. */ fun main(args: Array<String>) { val resource = 8.javaClass.getResource("advent/inputs/input_8") val lines = File(resource.toURI()).readLines() var grid = Array(6, {IntArray(50,{i -> 0})}) lines.forEach { instruction -> val instruction_set = instruction.split(" ") val kind = instruction_set[0] if (kind == "rect"){ val size = instruction_set[1].split("x") val width = size[0].toInt() val height = size[1].toInt() for (i in 0..height -1){ for(j in 0..width -1){ grid[i][j] = 1 } } } if (kind == "rotate"){ val direction = instruction_set[1] val row_or_column = instruction_set[2].split("=")[1].toInt() val distance = instruction_set[4].toInt() if (direction =="row"){ val grid_row = grid[row_or_column] grid[row_or_column] = grid_row.rotate(distance) } if (direction == "column"){ val arrayOfIntArrays = transposeMatrix(grid) arrayOfIntArrays[row_or_column] = arrayOfIntArrays[row_or_column].rotate(distance) grid = transposeMatrix(arrayOfIntArrays) } } } var counter =0 grid.forEach { inner -> inner.filter{int -> int == 1}.forEach { counter++ } } println(counter) grid.forEach { row -> println() row.forEach { element -> if(element == 0){ print(" ") }else{ print(element) } } } } fun IntArray.rotate(n: Int) = (drop(size - n) + take(size - n)).toIntArray() fun transposeMatrix(m: Array<IntArray>): Array<IntArray> { val transposed = Array(m[0].size, {c -> IntArray(m.size, {v -> 0})}) for (i in m.indices) { for (j in m[0].indices) { transposed[j][i] = m[i][j] } } return transposed }
mit
fad608a5abcbebfa6420f37af9512e8c
27.972222
98
0.504077
3.804745
false
false
false
false
perqin/daily-wallpapers
app/src/main/java/com/perqin/dailywallpapers/pages/wallpaperssources/editingwallpaperssource/EditingWallpapersSourceFragment.kt
1
4344
package com.perqin.dailywallpapers.pages.wallpaperssources.editingwallpaperssource import android.annotation.SuppressLint import android.app.Dialog import android.arch.lifecycle.Observer import android.arch.lifecycle.ViewModelProviders import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import com.perqin.dailywallpapers.R import com.perqin.dailywallpapers.viewmodels.EditingWallpapersSourceViewModel import kotlinx.android.synthetic.main.fragment_editing_wallpapers_source.view.* private const val ARG_WALLPAPERS_SOURCE_UID = "WALLPAPERS_SOURCE_UID" class EditingWallpapersSourceFragment : DialogFragment() { private var wallpapersSourceUid: Long? = null private lateinit var editingWallpapersSourceViewModel: EditingWallpapersSourceViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) wallpapersSourceUid = arguments?.getLong(ARG_WALLPAPERS_SOURCE_UID) editingWallpapersSourceViewModel = ViewModelProviders.of(activity).get(EditingWallpapersSourceViewModel::class.java) editingWallpapersSourceViewModel.init(wallpapersSourceUid) } @SuppressLint("InflateParams") override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // Setup contentView val contentView = LayoutInflater.from(activity).inflate(R.layout.fragment_editing_wallpapers_source, null) contentView.editText_url.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { s?.toString()?.let { editingWallpapersSourceViewModel.changeUrl(it) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) contentView.editText_title.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { s?.toString()?.let { editingWallpapersSourceViewModel.changeTitle(it) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) contentView.editText_version.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { s?.toString()?.toIntOrNull()?.let { editingWallpapersSourceViewModel.changeVersion(it) } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) // Observe ViewModel changes editingWallpapersSourceViewModel.getEditingWallpapersSource().observe(this, Observer { if (it?.url != contentView.editText_url.text.toString()) contentView.editText_url.setText(it?.url) if (it?.title != contentView.editText_title.text.toString()) contentView.editText_title.setText(it?.title) if (it?.version.toString() != contentView.editText_version.text.toString()) contentView.editText_version.setText(it?.version.toString()) }) return AlertDialog.Builder(context, theme) .setTitle(if (wallpapersSourceUid == null) R.string.dialogTitle_newWallpapersSource else R.string.dialogTitle_editWallpapersSource) .setView(contentView) .setPositiveButton(R.string.buttonText_save, { _, _ -> editingWallpapersSourceViewModel.saveNewWallpapersSource() }) .setNegativeButton(R.string.buttonText_discard, null) .create() } companion object { @JvmStatic fun newInstance(wallpapersSourceUid: Long?): EditingWallpapersSourceFragment { return EditingWallpapersSourceFragment().apply { if (wallpapersSourceUid != null) { arguments = Bundle().apply { putLong(ARG_WALLPAPERS_SOURCE_UID, wallpapersSourceUid) } } } } } }
apache-2.0
0b1b7e99197effa0ed0df3ee90b4e693
48.363636
148
0.696133
4.726877
false
false
false
false
intrigus/jtransc
jtransc-utils/src/com/jtransc/template/Minitemplate.kt
1
15417
package com.jtransc.template import com.jtransc.ds.ListReader import com.jtransc.error.invalidOp import com.jtransc.lang.Dynamic import com.jtransc.text.* import java.io.File class Minitemplate(val template: String, val config: Config = Config()) { val templateTokens = Token.tokenize(template) val node = BlockNode.parse(templateTokens, config) class Config( private val extraTags: List<Tag> = listOf(), private val extraFilters: List<Filter> = listOf() ) { val integratedFilters = listOf( Filter("length") { subject, args -> Dynamic.length(subject) }, Filter("capitalize") { subject, args -> Dynamic.toString(subject).toLowerCase().capitalize() }, Filter("upper") { subject, args -> Dynamic.toString(subject).toUpperCase() }, Filter("lower") { subject, args -> Dynamic.toString(subject).toLowerCase() }, Filter("trim") { subject, args -> Dynamic.toString(subject).trim() }, Filter("quote") { subject, args -> Dynamic.toString(subject).quote() }, Filter("escape") { subject, args -> Dynamic.toString(subject).escape() }, Filter("join") { subject, args -> Dynamic.toIterable(subject).map { Dynamic.toString(it) }.joinToString(Dynamic.toString(args[0])) }, Filter("file_exists") { subject, args -> File(Dynamic.toString(subject)).exists() } ) private val allTags = listOf(Tag.EMPTY, Tag.IF, Tag.FOR, Tag.SET, Tag.DEBUG) + extraTags private val allFilters = integratedFilters + extraFilters val tags = hashMapOf<String, Tag>().apply { for (tag in allTags) { this[tag.name] = tag for (alias in tag.aliases) this[alias] = tag } } val filters = hashMapOf<String, Filter>().apply { for (filter in allFilters) this[filter.name] = filter } } data class Filter(val name: String, val eval: (subject: Any?, args: List<Any?>) -> Any?) class Scope(val map: Any?, val parent: Scope? = null) { operator fun get(key: Any?): Any? { return Dynamic.accessAny(map, key) ?: parent?.get(key) } operator fun set(key: Any?, value: Any?) { Dynamic.setAny(map, key, value) } } operator fun invoke(args: Any?): String { val str = StringBuilder() val context = Context(Scope(args), config) { str.append(it) } context.createScope { node.eval(context) } return str.toString() } class Context(var scope: Scope, val config: Config, val write: (str: String) -> Unit) { inline fun createScope(callback: () -> Unit) = this.apply { val old = this.scope this.scope = Scope(hashMapOf<Any?, Any?>(), old) callback() this.scope = old } } interface ExprNode { fun eval(context: Context): Any? data class VAR(val name: String) : ExprNode { override fun eval(context: Context): Any? = context.scope[name] } data class LIT(val value: Any?) : ExprNode { override fun eval(context: Context): Any? = value } data class ARRAY_LIT(val items: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? = items.map { it.eval(context) } } data class FILTER(val name: String, val expr: ExprNode, val params: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? { val filter = context.config.filters[name] ?: invalidOp("Unknown filter '$name'") return filter.eval(expr.eval(context), params.map { it.eval(context) }) } } data class ACCESS(val expr: ExprNode, val name: ExprNode) : ExprNode { override fun eval(context: Context): Any? { val obj = expr.eval(context) val key = name.eval(context) try { return Dynamic.accessAny(obj, key) } catch (t: Throwable) { try { return Dynamic.callAny(obj, key, listOf()) } catch (t: Throwable) { return null } } } } data class CALL(val method: ExprNode, val args: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? { if (method !is ACCESS) { return Dynamic.callAny(method.eval(context), args.map { it.eval(context) }) } else { return Dynamic.callAny(method.expr.eval(context), method.name.eval(context), args.map { it.eval(context) }) } } } data class BINOP(val l: ExprNode, val r: ExprNode, val op: String) : ExprNode { override fun eval(context: Context): Any? = Dynamic.binop(l.eval(context), r.eval(context), op) } data class UNOP(val r: ExprNode, val op: String) : ExprNode { override fun eval(context: Context): Any? = Dynamic.unop(r.eval(context), op) } companion object { fun ListReader<Token>.expectPeek(vararg types: String): Token { val token = this.peek() if (token.text !in types) throw RuntimeException("Expected ${types.joinToString(", ")}") return token } fun ListReader<Token>.expect(vararg types: String): Token { val token = this.read() if (token.text !in types) throw RuntimeException("Expected ${types.joinToString(", ")}") return token } fun parse(str: String): ExprNode { return parseFullExpr(Token.tokenize(str)) } fun parseId(r: ListReader<ExprNode.Token>): String { return r.read().text } fun expect(r: ListReader<ExprNode.Token>, vararg tokens: String) { val token = r.read() if (token.text !in tokens) invalidOp("Expected ${tokens.joinToString(", ")} but found $token") } fun parseFullExpr(r: ListReader<Token>): ExprNode { val result = parseExpr(r) if (r.hasMore && r.peek() !is Token.TEnd) { invalidOp("Expected expression at " + r.peek() + " :: " + r.list.map { it.text }.joinToString("")) } return result } private val BINOPS = setOf( "+", "-", "*", "/", "%", "==", "!=", "<", ">", "<=", ">=", "<=>", "&&", "||" ) fun parseExpr(r: ListReader<Token>): ExprNode { var result = parseFinal(r) while (r.hasMore) { if (r.peek() !is Token.TOperator || r.peek().text !in BINOPS) break val operator = r.read().text val right = parseFinal(r) result = ExprNode.BINOP(result, right, operator) } // @TODO: Fix order! return result } private fun parseFinal(r: ListReader<Token>): ExprNode { var construct: ExprNode = when (r.peek().text) { "!", "~", "-", "+" -> { val op = r.read().text ExprNode.UNOP(parseFinal(r), op) } "(" -> { r.read() val result = parseExpr(r) if (r.read().text != ")") throw RuntimeException("Expected ')'") result } // Array literal "[" -> { val items = arrayListOf<ExprNode>() r.read() loop@ while (r.hasMore && r.peek().text != "]") { items += parseExpr(r) when (r.peek().text) { "," -> r.read() "]" -> continue@loop else -> invalidOp("Expected , or ]") } } r.expect("]") ExprNode.ARRAY_LIT(items) } else -> { if (r.peek() is Token.TNumber) { ExprNode.LIT(r.read().text.toDouble()) } else if (r.peek() is Token.TString) { ExprNode.LIT((r.read() as Token.TString).processedValue) } else { ExprNode.VAR(r.read().text) } } } loop@ while (r.hasMore) { when (r.peek().text) { "." -> { r.read() val id = r.read().text construct = ExprNode.ACCESS(construct, ExprNode.LIT(id)) continue@loop } "[" -> { r.read() val expr = parseExpr(r) construct = ExprNode.ACCESS(construct, expr) val end = r.read() if (end.text != "]") throw RuntimeException("Expected ']' but found $end") } "|" -> { r.read() val name = r.read().text val args = arrayListOf<ExprNode>() if (r.peek().text == "(") { r.read() callargsloop@ while (r.hasMore && r.peek().text != ")") { args += parseExpr(r) when (r.expectPeek(",", ")").text) { "," -> r.read() ")" -> break@callargsloop } } r.expect(")") } construct = ExprNode.FILTER(name, construct, args) } "(" -> { r.read() val args = arrayListOf<ExprNode>() callargsloop@ while (r.hasMore && r.peek().text != ")") { args += parseExpr(r) when (r.expectPeek(",", ")").text) { "," -> r.read() ")" -> break@callargsloop } } r.expect(")") construct = ExprNode.CALL(construct, args) } else -> break@loop } } return construct } } interface Token { val text: String data class TId(override val text: String) : Token data class TNumber(override val text: String) : Token data class TString(override val text: String, val processedValue: String) : Token data class TOperator(override val text: String) : Token data class TEnd(override val text: String = "") : Token companion object { private val OPERATORS = setOf( "(", ")", "[", "]", "{", "}", "&&", "||", "&", "|", "^", "==", "!=", "<", ">", "<=", ">=", "<=>", "+", "-", "*", "/", "%", "**", "!", "~", ".", ",", ";", ":", "=" ) fun tokenize(str: String): ListReader<Token> { val r = StrReader(str) val out = arrayListOf<Token>() fun emit(str: Token) { out += str } while (r.hasMore) { val start = r.offset r.skipSpaces() val id = r.readWhile { it.isLetterDigitOrUnderscore() } if (id != null) { if (id[0].isDigit()) emit(TNumber(id)) else emit(TId(id)) } r.skipSpaces() if (r.peek(3) in OPERATORS) emit(TOperator(r.read(3))) if (r.peek(2) in OPERATORS) emit(TOperator(r.read(2))) if (r.peek(1) in OPERATORS) emit(TOperator(r.read(1))) if (r.peekch() == '\'' || r.peekch() == '"') { val strStart = r.readch() val strBody = r.readUntil { it == strStart } ?: "" val strEnd = r.readch() emit(TString(strStart + strBody + strEnd, strBody)) } val end = r.offset if (end == start) invalidOp("Don't know how to handle '${r.peekch()}'") } emit(TEnd()) return ListReader(out) } } } } interface BlockNode { fun eval(context: Context): Unit data class GROUP(val children: List<BlockNode>) : BlockNode { override fun eval(context: Context) = Unit.apply { for (n in children) n.eval(context) } } data class TEXT(val content: String) : BlockNode { override fun eval(context: Context) = Unit.apply { context.write(content) } } data class EXPR(val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.write(Dynamic.toString(expr.eval(context))) } } data class IF(val cond: ExprNode, val trueContent: BlockNode, val falseContent: BlockNode?) : BlockNode { override fun eval(context: Context) = Unit.apply { if (Dynamic.toBool(cond.eval(context))) { trueContent.eval(context) } else { falseContent?.eval(context) } } } data class FOR(val varname: String, val expr: ExprNode, val loop: BlockNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.createScope { for (v in Dynamic.toIterable(expr.eval(context))) { context.scope[varname] = v loop.eval(context) } } } } data class SET(val varname: String, val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.scope[varname] = expr.eval(context) } } data class DEBUG(val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { println(expr.eval(context)) } } companion object { fun group(children: List<BlockNode>): BlockNode = if (children.size == 1) children[0] else GROUP(children) fun parse(tokens: List<Token>, config: Config): BlockNode { val tr = ListReader(tokens) fun handle(tag: Tag, token: Token.TTag): BlockNode { val parts = arrayListOf<TagPart>() var currentToken = token val children = arrayListOf<BlockNode>() fun emitPart() { parts += TagPart(currentToken, BlockNode.group(children)) } loop@ while (!tr.eof) { val it = tr.read() when (it) { is Token.TLiteral -> children += BlockNode.TEXT(it.content) is Token.TExpr -> children += BlockNode.EXPR(ExprNode.parse(it.content)) is Token.TTag -> { when (it.name) { tag.end -> break@loop in tag.nextList -> { emitPart() currentToken = it children.clear() } else -> { val newtag = config.tags[it.name] ?: invalidOp("Can't find tag ${it.name}") if (newtag.end != null) { children += handle(newtag, it) } else { children += newtag.buildNode(listOf(TagPart(it, BlockNode.TEXT("")))) } } } } else -> break@loop } } emitPart() return tag.buildNode(parts) } return handle(Tag.EMPTY, Token.TTag("", "")) } } } data class TagPart(val token: Token.TTag, val body: BlockNode) data class Tag(val name: String, val nextList: Set<String>, val end: String?, val aliases: List<String> = listOf(), val buildNode: (parts: List<TagPart>) -> BlockNode) { companion object { val EMPTY = Tag("", setOf(""), "") { parts -> BlockNode.group(parts.map { it.body }) } val IF = Tag("if", setOf("else"), "end") { parts -> val main = parts[0] val elseBlock = parts.getOrNull(1) BlockNode.IF(ExprNode.parse(main.token.content), main.body, elseBlock?.body) } val FOR = Tag("for", setOf(), "end") { parts -> val main = parts[0] val tr = ExprNode.Token.tokenize(main.token.content) val varname = ExprNode.parseId(tr) ExprNode.expect(tr, "in") val expr = ExprNode.parseExpr(tr) BlockNode.FOR(varname, expr, main.body) } val DEBUG = Tag("debug", setOf(), null) { parts -> BlockNode.DEBUG(ExprNode.parse(parts[0].token.content)) } val SET = Tag("set", setOf(), null) { parts -> val main = parts[0] val tr = ExprNode.Token.tokenize(main.token.content) val varname = ExprNode.parseId(tr) ExprNode.expect(tr, "=") val expr = ExprNode.parseExpr(tr) BlockNode.SET(varname, expr) } } } interface Token { data class TLiteral(val content: String) : Token data class TExpr(val content: String) : Token data class TTag(val name: String, val content: String) : Token companion object { fun tokenize(str: String): List<Token> { val out = arrayListOf<Token>() var lastPos = 0 fun emit(token: Token) { if (token is TLiteral && token.content.isEmpty()) return out += token } var pos = 0 while (pos < str.length) { val c = str[pos++] if (c == '{') { if (pos >= str.length) break val c2 = str[pos++] if (c2 == '{' || c2 == '%') { val startPos = pos - 2 val pos2 = if (c2 == '{') str.indexOf("}}", pos) else str.indexOf("%}", pos) if (pos2 < 0) break val content = str.substring(pos, pos2).trim() if (lastPos != startPos) { emit(TLiteral(str.substring(lastPos until startPos))) } if (c2 == '{') { //println("expr: '$content'") emit(TExpr(content)) } else { val parts = content.split(' ', limit = 2) //println("tag: '$content'") emit(TTag(parts[0], parts.getOrElse(1) { "" })) } pos = pos2 + 2 lastPos = pos } } } emit(TLiteral(str.substring(lastPos, str.length))) return out } } } }
apache-2.0
594b2b5c1ec60d21b44d0cf615ca332a
29.348425
170
0.587079
3.225314
false
false
false
false
chiken88/passnotes
app/src/main/kotlin/com/ivanovsky/passnotes/domain/SyncStrategyResolver.kt
1
2215
package com.ivanovsky.passnotes.domain import com.ivanovsky.passnotes.data.entity.SyncResolution import com.ivanovsky.passnotes.data.repository.file.SyncStrategy import com.ivanovsky.passnotes.util.isNewerThan class SyncStrategyResolver { fun resolve( localModified: Long?, cachedRemoteModified: Long?, remoteModified: Long?, syncStrategy: SyncStrategy ): SyncResolution { return when (syncStrategy) { SyncStrategy.LAST_MODIFICATION_WINS -> resolveForLastModificationWins( localModified, remoteModified ) SyncStrategy.LAST_REMOTE_MODIFICATION_WINS -> resolveForLastRemoteModificationWind( localModified, cachedRemoteModified, remoteModified ) } } private fun resolveForLastModificationWins( localModified: Long?, remoteModified: Long? ): SyncResolution { return when { remoteModified.isNewerThan(localModified) -> { SyncResolution.REMOTE } localModified.isNewerThan(remoteModified) -> { SyncResolution.LOCAL } localModified == remoteModified -> { SyncResolution.EQUALS } else -> { SyncResolution.ERROR } } } private fun resolveForLastRemoteModificationWind( localModified: Long?, cachedRemoteModified: Long?, remoteModified: Long? ): SyncResolution { return when { remoteModified.isNewerThan(localModified) && localModified == cachedRemoteModified -> { SyncResolution.REMOTE } localModified.isNewerThan(remoteModified) -> { if (remoteModified.isNewerThan(cachedRemoteModified)) { SyncResolution.ERROR } else { SyncResolution.LOCAL } } localModified == remoteModified -> { SyncResolution.EQUALS } else -> { SyncResolution.ERROR } } } }
gpl-2.0
21089879511a02fcb113607d632a248f
29.777778
99
0.563883
5.50995
false
false
false
false
JiangKlijna/framework-learning
java/vertx-kotlin/src/main/java/com/jiangklijna/vertx/Handle.kt
1
1112
package com.jiangklijna.vertx import io.vertx.core.AsyncResult import io.vertx.ext.web.RoutingContext import io.vertx.core.json.JsonArray val check = { it: AsyncResult<out Any> -> if (it.failed()) throw RuntimeException(it.cause()) else Unit } val index = fun(ctx: RoutingContext) { val sess = ctx.session() val count: Int = (sess.get("count") ?: 0) + 1 sess.put("count", count) ctx.put("count", count) ctx.put("title", "vertx-kotlin") engine.render(ctx, "templates/", "index.html", { res -> if (res.succeeded()) ctx.response().end(res.result()) else ctx.fail(res.cause()) }) } val getUser: (RoutingContext) -> Unit = { ctx -> val userid = ctx.request().getParam("userid").toInt() val response = ctx.response() client.getConnection { check(it) val conn = it.result() conn.queryWithParams("select * from public.user where id=?", JsonArray().add(userid), { select -> check(select) response.putHeader("content-type", "application/json").end(select.result().toJson().encodePrettily()) }) } }
apache-2.0
8df34cc96f3bb4d17164c6eb4c746dc9
31.705882
113
0.627698
3.62215
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/presenter/quran/ayahtracker/AyahTrackerPresenter.kt
2
15875
package com.quran.labs.androidquran.presenter.quran.ayahtracker import android.app.Activity import android.graphics.RectF import android.view.MotionEvent import android.widget.ImageView import com.quran.data.core.QuranInfo import com.quran.data.di.QuranPageScope import com.quran.data.model.AyahGlyph.AyahEndGlyph import com.quran.data.model.AyahGlyph.WordGlyph import com.quran.data.model.AyahWord import com.quran.data.model.SuraAyah import com.quran.data.model.bookmark.Bookmark import com.quran.data.model.highlight.HighlightInfo import com.quran.data.model.highlight.HighlightType import com.quran.data.model.selection.AyahSelection import com.quran.data.model.selection.SelectionIndicator import com.quran.data.model.selection.startSuraAyah import com.quran.labs.androidquran.common.LocalTranslation import com.quran.labs.androidquran.common.QuranAyahInfo import com.quran.labs.androidquran.data.QuranDisplayData import com.quran.labs.androidquran.data.SuraAyahIterator import com.quran.labs.androidquran.presenter.Presenter import com.quran.labs.androidquran.presenter.quran.ayahtracker.AyahTrackerPresenter.AyahInteractionHandler import com.quran.labs.androidquran.ui.PagerActivity import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener.EventType import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener.EventType.DOUBLE_TAP import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener.EventType.LONG_PRESS import com.quran.labs.androidquran.ui.helpers.AyahSelectedListener.EventType.SINGLE_TAP import com.quran.labs.androidquran.ui.helpers.AyahTracker import com.quran.labs.androidquran.ui.helpers.HighlightTypes import com.quran.labs.androidquran.util.QuranFileUtils import com.quran.labs.androidquran.util.QuranSettings import com.quran.mobile.bookmark.model.BookmarkModel import com.quran.page.common.data.AyahCoordinates import com.quran.page.common.data.PageCoordinates import com.quran.reading.common.AudioEventPresenter import com.quran.reading.common.ReadingEventPresenter import com.quran.recitation.events.RecitationEventPresenter import com.quran.recitation.presenter.RecitationHighlightsPresenter import com.quran.recitation.presenter.RecitationHighlightsPresenter.HighlightAction import com.quran.recitation.presenter.RecitationHighlightsPresenter.RecitationPage import com.quran.recitation.presenter.RecitationPopupPresenter import com.quran.recitation.presenter.RecitationPopupPresenter.PopupContainer import com.quran.recitation.presenter.RecitationPresenter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.inject.Inject @QuranPageScope class AyahTrackerPresenter @Inject constructor( private val quranInfo: QuranInfo, private val quranFileUtils: QuranFileUtils, private val quranDisplayData: QuranDisplayData, private val quranSettings: QuranSettings, private val readingEventPresenter: ReadingEventPresenter, private val bookmarkModel: BookmarkModel, private val audioEventPresenter: AudioEventPresenter, private val recitationPresenter: RecitationPresenter, private val recitationEventPresenter: RecitationEventPresenter, private val recitationPopupPresenter: RecitationPopupPresenter, private val recitationHighlightsPresenter: RecitationHighlightsPresenter, ) : AyahTracker, Presenter<AyahInteractionHandler>, PopupContainer, RecitationPage { // we may bind and unbind several times, and each time we unbind, we cancel // the scope, which means we can't launch new coroutines in that same scope. // thus, leave this as a var so we replace it every time. private lateinit var scope: CoroutineScope private var items: Array<AyahTrackerItem> = emptyArray() private var pendingHighlightInfo: HighlightInfo? = null private var lastHighlightedAyah: SuraAyah? = null private var lastHighlightedAudioAyah: SuraAyah? = null private val isRecitationEnabled = recitationPresenter.isRecitationEnabled() private fun subscribe() { readingEventPresenter.ayahSelectionFlow .onEach { onAyahSelectionChanged(it) } .launchIn(scope) audioEventPresenter.audioPlaybackAyahFlow .onEach { onAudioSelectionChanged(it) } .launchIn(scope) items.forEach { trackerItem -> bookmarkModel.bookmarksForPage(trackerItem.page) .onEach { bookmarks -> onBookmarksChanged(bookmarks) } .launchIn(scope) } } fun setPageBounds(pageCoordinates: PageCoordinates) { for (item in items) { item.onSetPageBounds(pageCoordinates) } } fun setAyahCoordinates(ayahCoordinates: AyahCoordinates) { for (item in items) { item.onSetAyahCoordinates(ayahCoordinates) } val pendingHighlightInfo = pendingHighlightInfo if (pendingHighlightInfo != null && ayahCoordinates.ayahCoordinates.isNotEmpty()) { highlightAyah( pendingHighlightInfo.sura, pendingHighlightInfo.ayah, pendingHighlightInfo.word, pendingHighlightInfo.highlightType, pendingHighlightInfo.scrollToAyah ) } if (isRecitationEnabled) { recitationHighlightsPresenter.refresh() } } private fun onAyahSelectionChanged(ayahSelection: AyahSelection) { val startSuraAyah = ayahSelection.startSuraAyah() // optimization - if the current ayah is still highlighted, don't issue a request // to unhighlight. if (startSuraAyah != lastHighlightedAyah) { unHighlightAyahs(HighlightTypes.SELECTION) lastHighlightedAyah = startSuraAyah } when (ayahSelection) { is AyahSelection.Ayah -> { val suraAyah = ayahSelection.suraAyah val scrollToAyah = ayahSelection.selectionIndicator == SelectionIndicator.ScrollOnly highlightAyah(suraAyah.sura, suraAyah.ayah, -1, HighlightTypes.SELECTION, scrollToAyah) } is AyahSelection.AyahRange -> { val highlightAyatIterator = SuraAyahIterator(quranInfo, ayahSelection.startSuraAyah, ayahSelection.endSuraAyah) val highlightedAyat = highlightAyatIterator.asSet() items.forEach { val pageAyat = quranDisplayData.getAyahKeysOnPage(it.page) val elements = pageAyat.intersect(highlightedAyat) if (elements.isNotEmpty()) { it.onHighlightAyat(it.page, elements, HighlightTypes.SELECTION) } } } else -> { /* nothing is selected, and we already cleared */ } } } private fun onAudioSelectionChanged(suraAyah: SuraAyah?) { val currentLastHighlightAudioAyah = lastHighlightedAudioAyah // if there is no currently highlighted audio ayah, go ahead and clear all if (currentLastHighlightAudioAyah == null) { unHighlightAyahs(HighlightTypes.AUDIO) } // either way, whether we unhighlighted all or not, highlight the new ayah if (suraAyah != null) { highlightAyah(suraAyah.sura, suraAyah.ayah, -1, HighlightTypes.AUDIO, true) } // if we had a highlighted ayah before, unhighlight it now. // we do this *after* highlighting the new ayah so that the animations continue working. if (suraAyah != currentLastHighlightAudioAyah && currentLastHighlightAudioAyah != null) { val sura = currentLastHighlightAudioAyah.sura val ayah = currentLastHighlightAudioAyah.ayah val page = quranInfo.getPageFromSuraAyah(sura, ayah) items.filter { it.page == page } .onEach { it.onUnHighlightAyah(page, sura, ayah, -1, HighlightTypes.AUDIO) } } // and keep track of the last highlighted audio ayah lastHighlightedAudioAyah = suraAyah } private fun onBookmarksChanged(bookmarks: List<Bookmark>) { unHighlightAyahs(HighlightTypes.BOOKMARK) if (quranSettings.shouldHighlightBookmarks()) { items.forEach { tracker -> val elements = bookmarks .filter { it.page == tracker.page } .map { "${it.sura}:${it.ayah}" } .toSet() if (elements.isNotEmpty()) { tracker.onHighlightAyat(tracker.page, elements, HighlightTypes.BOOKMARK) } } } } private fun highlightAyah(sura: Int, ayah: Int, word: Int, type: HighlightType, scrollToAyah: Boolean) { val page = quranInfo.getPageFromSuraAyah(sura, ayah) val handled = items.any { it.page == page && it.onHighlightAyah(page, sura, ayah, word, type, scrollToAyah) } pendingHighlightInfo = if (!handled) { HighlightInfo(sura, ayah, word, type, scrollToAyah) } else { null } } private fun unHighlightAyahs(type: HighlightType) { for (item in items) { item.onUnHighlightAyahType(type) } } override fun getToolBarPosition(sura: Int, ayah: Int): SelectionIndicator { val page = quranInfo.getPageFromSuraAyah(sura, ayah) for (item in items) { val position = item.getToolBarPosition(page, sura, ayah) if (position != SelectionIndicator.None && position != SelectionIndicator.ScrollOnly) { return position } } return SelectionIndicator.None } override fun getQuranAyahInfo(sura: Int, ayah: Int): QuranAyahInfo? { for (item in items) { val quranAyahInfo = item.getQuranAyahInfo(sura, ayah) if (quranAyahInfo != null) { return quranAyahInfo } } return null } override fun getLocalTranslations(): Array<LocalTranslation>? { for (item in items) { val localTranslations = item.getLocalTranslations() if (localTranslations != null) { return localTranslations } } return null } fun onPressIgnoringSelectionState() { readingEventPresenter.onClick() } fun onLongPress(suraAyah: SuraAyah) { handleLongPress(suraAyah) } fun endAyahMode() { readingEventPresenter.onAyahSelection(AyahSelection.None) } fun handleTouchEvent( activity: Activity, event: MotionEvent, eventType: EventType, page: Int, ayahCoordinatesError: Boolean ): Boolean { if (eventType === DOUBLE_TAP) { readingEventPresenter.onAyahSelection(AyahSelection.None) } else if (eventType == LONG_PRESS || readingEventPresenter.currentAyahSelection() != AyahSelection.None ) { // press or long press when an ayah is selected if (ayahCoordinatesError) { checkCoordinateData(activity) } else { // either a press or a long press, but we're in selection mode handleAyahSelection(event, eventType, page) } } else if (eventType == SINGLE_TAP && recitationEventPresenter.hasRecitationSession()) { handleTap(event, eventType, page) } else { // normal click readingEventPresenter.onClick() } return true } private fun handleAyahSelection( ev: MotionEvent, eventType: EventType, page: Int ) { val result = getAyahForPosition(page, ev.x, ev.y) if (result != null) { if (eventType == SINGLE_TAP) { readingEventPresenter.onAyahSelection( AyahSelection.Ayah(result, getToolBarPosition(result.sura, result.ayah)) ) } else if (eventType == LONG_PRESS) { handleLongPress(result) } } } private fun handleTap( ev: MotionEvent, eventType: EventType, page: Int ) { for (item in items) { val glyph = item.getGlyphForPosition(page, ev.x, ev.y) ?: continue val portion = when (glyph) { is WordGlyph -> glyph.toAyahWord() is AyahEndGlyph -> glyph.ayah else -> glyph.ayah } readingEventPresenter.onClick(portion) } } private fun handleLongPress(selectedSuraAyah: SuraAyah) { val current = readingEventPresenter.currentAyahSelection() val updatedAyahSelection = updateAyahRange(selectedSuraAyah, current) readingEventPresenter.onAyahSelection(updatedAyahSelection) } private fun updateAyahRange(selectedAyah: SuraAyah, ayahSelection: AyahSelection): AyahSelection { val (startAyah, endAyah) = when (ayahSelection) { is AyahSelection.None -> selectedAyah to null is AyahSelection.Ayah -> { if (selectedAyah > ayahSelection.suraAyah) { ayahSelection.suraAyah to selectedAyah } else { selectedAyah to ayahSelection.suraAyah } } is AyahSelection.AyahRange -> { if (selectedAyah > ayahSelection.startSuraAyah) { ayahSelection.startSuraAyah to selectedAyah } else { selectedAyah to ayahSelection.startSuraAyah } } } val toolBarPosition = getToolBarPosition(selectedAyah.sura, selectedAyah.ayah) return if (endAyah == null) { AyahSelection.Ayah(startAyah, toolBarPosition) } else { AyahSelection.AyahRange(startAyah, endAyah, toolBarPosition) } } private fun getAyahForPosition(page: Int, x: Float, y: Float): SuraAyah? { for (item in items) { val ayah = item.getAyahForPosition(page, x, y) if (ayah != null) { return ayah } } return null } private fun checkCoordinateData(activity: Activity) { if (activity is PagerActivity && (!quranFileUtils.haveAyaPositionFile(activity) || !quranFileUtils.hasArabicSearchDatabase()) ) { activity.showGetRequiredFilesDialog() } } override fun bind(what: AyahInteractionHandler) { items = what.ayahTrackerItems scope = MainScope() if (isRecitationEnabled) { recitationPopupPresenter.bind(this) recitationHighlightsPresenter.bind(this) } subscribe() } override fun unbind(what: AyahInteractionHandler) { if (isRecitationEnabled) { recitationHighlightsPresenter.unbind(this) recitationPopupPresenter.unbind(this) } items = emptyArray() scope.cancel() } interface AyahInteractionHandler { val ayahTrackerItems: Array<AyahTrackerItem> } // PopupContainer <--> AyahTrackerItem adapter override fun getQuranPageImageView(page: Int): ImageView? { val item = items.firstOrNull { it.page == page } ?: return null val ayahView = item.getAyahView() ?: return null return ayahView as? ImageView ?: return null } override fun getSelectionBoundsForWord( page: Int, word: AyahWord ): SelectionIndicator.SelectedItemPosition? { val item = items.firstOrNull { it.page == page } ?: return null val selection = item.getToolBarPosition(item.page, word) as? SelectionIndicator.SelectedItemPosition ?: return null return selection } override fun getBoundsForWord(word: AyahWord): List<RectF>? { return (items[0] as? AyahImageTrackerItem)?.pageGlyphsCoords?.getBoundsForWord(word) } // RecitationPage <--> AyahTrackerItem adapter override val pageNumbers: Set<Int> get() = items.map { it.page }.toSet() override fun applyHighlights(highlights: List<HighlightAction>) { highlights.forEach { when (it) { is HighlightAction.Highlight -> highlight(it.highlightInfo) is HighlightAction.Unhighlight -> unhighlight(it.highlightInfo) is HighlightAction.UnhighlightAll -> unHighlightAyahs(it.highlightType, it.page) } } } private fun highlight(highlightInfo: HighlightInfo) { val page = quranInfo.getPageFromSuraAyah(highlightInfo.sura, highlightInfo.ayah) items.asSequence() .filter { it.page == page } .forEach { it.onHighlight(page, highlightInfo) } } private fun unhighlight(highlightInfo: HighlightInfo) { val page = quranInfo.getPageFromSuraAyah(highlightInfo.sura, highlightInfo.ayah) items.asSequence() .filter { it.page == page } .forEach { it.onUnhighlight(page, highlightInfo) } } private fun unHighlightAyahs(type: HighlightType, page: Int? = null) { items.asSequence() .filter { page == null || page == it.page } .forEach { it.onUnHighlightAyahType(type) } } }
gpl-3.0
bfac3b12d49e996e1c8a8609b38a2d28
34.121681
119
0.72378
4.354087
false
false
false
false
fossasia/rp15
app/src/main/java/org/fossasia/openevent/general/speakercall/SpeakersCallProposalViewModel.kt
1
4886
package org.fossasia.openevent.general.speakercall import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.R import org.fossasia.openevent.general.auth.AuthHolder import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.EventService import org.fossasia.openevent.general.sessions.Session import org.fossasia.openevent.general.sessions.SessionService import org.fossasia.openevent.general.sessions.track.Track import org.fossasia.openevent.general.speakers.Speaker import org.fossasia.openevent.general.speakers.SpeakerService import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import timber.log.Timber class SpeakersCallProposalViewModel( private val resource: Resource, private val speakerService: SpeakerService, private val authHolder: AuthHolder, private val eventService: EventService, private val sessionService: SessionService ) : ViewModel() { private val compositeDisposable = CompositeDisposable() private val mutableMessage = SingleLiveEvent<String>() val message: LiveData<String> = mutableMessage private val mutableSpeakerProgress = MutableLiveData(false) private val mutableProgress = MutableLiveData(false) val progress: LiveData<Boolean> = mutableProgress private val mutableSubmitSuccess = MutableLiveData(false) val submitSuccess: LiveData<Boolean> = mutableSubmitSuccess val speakerProgress: LiveData<Boolean> = mutableSpeakerProgress private val mutableSpeaker = MutableLiveData<Speaker>() val speaker: LiveData<Speaker> = mutableSpeaker private val mutableSession = MutableLiveData<Session>() val session: LiveData<Session> = mutableSession private val mutableTracks = MutableLiveData<List<Track>>() val tracks: LiveData<List<Track>> = mutableTracks var trackPosition = 0 fun submitProposal(proposal: Proposal) { compositeDisposable += sessionService.createSession(proposal) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.subscribe({ mutableProgress.value = false mutableSubmitSuccess.value = true }, { mutableProgress.value = false mutableMessage.value = resource.getString(R.string.fail_create_proposal_message) Timber.e(it, "Fail on creating new session") }) } fun loadSession(sessionId: Long) { if (sessionId == -1L) return compositeDisposable += sessionService.fetchSession(sessionId) .withDefaultSchedulers() .subscribe({ mutableSession.value = it }, { mutableMessage.value = resource.getString(R.string.fail_getting_current_proposal_message) Timber.e("Fail on fetching session $sessionId") }) } fun editProposal(sessionId: Long, proposal: Proposal) { compositeDisposable += sessionService.updateSession(sessionId, proposal) .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.subscribe({ mutableProgress.value = false mutableSubmitSuccess.value = true }, { mutableProgress.value = false mutableMessage.value = resource.getString(R.string.fail_update_proposal_message) Timber.e(it, "Fail on updating session $sessionId") }) } fun getId(): Long = authHolder.getId() fun loadTracks(eventId: Long) { if (eventId == -1L) return compositeDisposable += eventService.fetchTracksUnderEvent(eventId) .withDefaultSchedulers() .subscribe({ mutableTracks.value = it }, { mutableMessage.value = resource.getString(R.string.error_fetching_tracks_message) Timber.e(it, "Fail on fetching tracks for event $eventId") }) } var isSpeakerInfoShown = true fun loadSpeaker(speakerId: Long) { if (speakerId == -1L) { return } compositeDisposable += speakerService.fetchSpeaker(speakerId) .withDefaultSchedulers() .doOnSubscribe { mutableSpeakerProgress.value = true }.subscribe({ mutableSpeaker.value = it mutableSpeakerProgress.value = false }, { Timber.e(it, "Fail on fetching speaker id $speakerId") mutableSpeakerProgress.value = false }) } }
apache-2.0
fdf51aa8da43c98755229915f04cfa49
38.403226
105
0.672329
5.23687
false
false
false
false
AlmasB/Zephyria
src/main/kotlin/com/almasb/zeph/ZephyriaApp.kt
1
8157
package com.almasb.zeph import com.almasb.fxgl.app.ApplicationMode import com.almasb.fxgl.app.GameApplication import com.almasb.fxgl.app.GameSettings import com.almasb.fxgl.app.scene.LoadingScene import com.almasb.fxgl.app.scene.SceneFactory import com.almasb.fxgl.dsl.* import com.almasb.fxgl.dsl.FXGL.Companion.getSceneService import com.almasb.fxgl.dsl.FXGL.Companion.getService import com.almasb.fxgl.dsl.FXGL.Companion.onCollisionCollectible import com.almasb.fxgl.logging.Logger import com.almasb.fxgl.logging.LoggerLevel import com.almasb.fxgl.logging.LoggerOutput import com.almasb.zeph.EntityType.* import com.almasb.zeph.Gameplay.currentMap import com.almasb.zeph.Gameplay.gotoMap import com.almasb.zeph.Gameplay.player import com.almasb.zeph.Gameplay.spawnTextBox import com.almasb.zeph.Gameplay.startDialogue import com.almasb.zeph.Vars.IS_SELECTING_SKILL_TARGET_AREA import com.almasb.zeph.Vars.IS_SELECTING_SKILL_TARGET_CHAR import com.almasb.zeph.Vars.SELECTED_SKILL_INDEX import com.almasb.zeph.character.CharacterEntity import com.almasb.zeph.events.EventHandlers import com.almasb.zeph.gameplay.ClockService import com.almasb.zeph.gameplay.TextClockView import com.almasb.zeph.skill.SkillTargetType import com.almasb.zeph.skill.SkillType import com.almasb.zeph.ui.* import javafx.geometry.Point2D import javafx.scene.input.KeyCode.* import javafx.scene.paint.Color import java.util.function.Consumer import kotlin.collections.set /** * * @author Almas Baimagambetov ([email protected]) */ class ZephyriaApp : GameApplication() { private var devScene: DevScene? = null override fun initSettings(settings: GameSettings) { settings.width = 1800 settings.setHeightFromRatio(16 / 9.0) settings.title = "Zephyria RPG" settings.version = "0.1 Pre-alpha" settings.cssList += "zephyria.css" settings.addEngineService(ClockService::class.java) settings.sceneFactory = object : SceneFactory() { override fun newLoadingScene(): LoadingScene { return ZephLoadingScene() } } settings.applicationMode = ApplicationMode.DEVELOPER } override fun onPreInit() { EventHandlers.initialize() if (isReleaseMode()) { loopBGM("BGM_Foggy_Woods.mp3") } } override fun initInput() { for (i in 1..9) { val key = getKeyCode(i.toString() + "") val index = i - 1 onKeyDown(key, "Hotbar Skill $i") { onHotbarSkill(index) } } onKeyDown(C) { getGameScene().uiNodes .filterIsInstance(BasicInfoView::class.java) .forEach { it.minBtn.onClick() } } onKeyDown(I) { getGameScene().uiNodes .filterIsInstance(PlayerInventoryView::class.java) .forEach { it.minBtn.onClick() } } onKeyDown(S) { getGameScene().uiNodes .filterIsInstance(HotbarView::class.java) .forEach { it.minBtn.onClick() } } onKeyDown(V) { getGameScene().uiNodes .filterIsInstance(MessagesView::class.java) .forEach { it.minBtn.onClick() } } if (!isReleaseMode()) { onKeyDown(ENTER) { getSceneService().pushSubScene(devScene!!) } onKeyDown(F) { //val quest = com.almasb.zeph.quest.Quest(Data.Quests.TUTORIAL_KILLS) //println(quest.data.description) //Gameplay.openStorage() val clockService = getService(ClockService::class.java) clockService.clock.runAt(12, 0) { pushMessage("It's 12:00!") } addUINode(TextClockView(clockService.clock), 300.0, 300.0) } // // onKeyDown(T) { // Gameplay.spawn("treasureChest", player.cellX, player.cellY) // } // // onKeyDown(L) { // fire(OnLevelUpEvent(player)) // } // // onKeyDown(Y) { // val scene = CharSelectSubScene(WARRIOR, SCOUT, MAGE) // scene.onSelected = { // println(it) // } // // getSceneService().pushSubScene(scene) // } } } override fun initGameVars(vars: MutableMap<String?, Any?>) { vars[IS_SELECTING_SKILL_TARGET_AREA] = false vars[IS_SELECTING_SKILL_TARGET_CHAR] = false vars[SELECTED_SKILL_INDEX] = -1 } private fun onHotbarSkill(index: Int) { val pc = player.characterComponent if (index < pc.skills.size) { val skill = pc.skills[index] if (skill.level == 0) { // skill not learned yet return } if (skill.isOnCooldown) { return } if (skill.manaCost.value > pc.sp.value) { // no mana return } if (skill.data.type === SkillType.PASSIVE) { // skill is passive and is always on return } if (skill.data.targetTypes.contains(SkillTargetType.SELF)) { // use skill immediately since player is the target val result = pc.useSelfSkill(index) } else if (skill.data.targetTypes.contains(SkillTargetType.AREA)) { // let player select the area set(IS_SELECTING_SKILL_TARGET_AREA, true) set(SELECTED_SKILL_INDEX, index) } else { // let player select the target character set(IS_SELECTING_SKILL_TARGET_CHAR, true) set(SELECTED_SKILL_INDEX, index) } } } override fun initGame() { devScene = DevScene() getGameScene().setBackgroundColor(Color.BLACK) getGameWorld().addEntityFactory(ZephFactory()) val player = spawn("player") as CharacterEntity spawn("cellSelection") getGameScene().viewport.bindToEntity(player, getAppWidth() / 2.toDouble(), getAppHeight() / 2.toDouble()) getGameScene().viewport.setZoom(1.5) gotoMap("dev_world.tmx", 8, 6) //gotoMap("tutorial.tmx", 8, 6) //gotoMap("test_map.tmx", 2, 6) } override fun initPhysics() { onCollisionBegin(SKILL_PROJECTILE, MONSTER) { proj, target -> if (proj.getObject<Any>("target") !== target) { return@onCollisionBegin } proj.removeFromWorld() player.characterComponent.useTargetSkill(geti(SELECTED_SKILL_INDEX), (target as CharacterEntity)) } onCollisionCollectible(PLAYER, TEXT_TRIGGER_BOX, Consumer { spawnTextBox(it.getString("text"), it.x, it.y) }) onCollisionCollectible(PLAYER, DIALOGUE, Consumer { startDialogue(it.getString("text")) }) } override fun initUI() { getGameScene().setUIMouseTransparent(false) getGameScene().setCursor(image("ui/cursors/main.png"), Point2D(52.0, 10.0)) getGameScene().addUINodes( BasicInfoView(player), PlayerInventoryView(player), HotbarView(player), MessagesView() ) // add visual output to logger Logger.addOutput(object : LoggerOutput { override fun append(message: String) { getExecutor().startAsyncFX { getGameScene().uiNodes .filterIsInstance(MessagesView::class.java) .forEach { it.appendMessage(message.drop(70)) } } } override fun close() { } }, LoggerLevel.INFO) } override fun onUpdate(tpf: Double) { currentMap.onUpdate(tpf) } } fun main(args: Array<String>) { GameApplication.launch(ZephyriaApp::class.java, args) }
gpl-2.0
1d1e8fe1a7e75a60c6619b0a57056950
30.494208
113
0.583548
4.213326
false
false
false
false
cretz/asmble
compiler/src/test/kotlin/asmble/run/jvm/RunTest.kt
1
1488
package asmble.run.jvm import asmble.SpecTestUnit import asmble.annotation.WasmModule import asmble.io.AstToBinary import asmble.io.ByteWriter import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.io.ByteArrayOutputStream import kotlin.test.assertEquals @RunWith(Parameterized::class) class RunTest(unit: SpecTestUnit) : TestRunner<SpecTestUnit>(unit) { override val builder get() = ModuleBuilder.Compiled( packageName = unit.packageName, logger = this, adjustContext = { it.copy(eagerFailLargeMemOffset = false) }, // Include the binary data so we can check it later includeBinaryInCompiledClass = true, defaultMaxMemPages = unit.defaultMaxMemPages ) override fun run() = super.run().also { scriptContext -> // Check annotations scriptContext.modules.forEach { mod -> mod as Module.Compiled val expectedBinaryString = ByteArrayOutputStream().also { ByteWriter.OutputStream(it).also { AstToBinary.fromModule(it, mod.mod) } }.toByteArray().toString(Charsets.ISO_8859_1) val actualBinaryString = mod.cls.getDeclaredAnnotation(WasmModule::class.java)?.binary ?: error("No annotation") assertEquals(expectedBinaryString, actualBinaryString) } } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = SpecTestUnit.allUnits } }
mit
1ccf6dd47a5808053febe6dd5da5c86b
35.292683
103
0.688172
4.564417
false
true
false
false
UnderMybrella/Visi
src/main/kotlin/org/abimon/visi/lang/VLang.kt
1
2715
package org.abimon.visi.lang import org.abimon.visi.collections.ArraySet fun Runtime.usedMemory(): Long = (totalMemory() - freeMemory()) fun setHeadless() = System.setProperty("java.awt.headless", "true") //val String.variations: Set<String> // get() { // val variants = hashSetOf(this) // val charPool = this.map { c -> charVariations[c] ?: arrayOf("$c") } // val word = IntArray(length) // val lastIndex = length - 1 // // loop@while(word.filterIndexed { index, i -> i + 1 == charPool[index].size }.count() < length) { // word[lastIndex] += 1 // if(word[lastIndex] >= charPool[lastIndex].size) { // word[lastIndex] = 0 // // for(i in lastIndex - 1 downTo 0) { // word[i] += 1 // if (word[i] >= charPool[i].size) { // word[i] = 0 // continue // } // variants.add(word.mapIndexed { index, i -> charPool[index][i] }.joinToString("")) // continue@loop // } // } // else // variants.add(word.mapIndexed { index, i -> charPool[index][i] }.joinToString("")) // } // // return variants // } fun bruteForce(length: Int, charPool: Array<String>): List<String> = bruteForce(length, (0 until length).map { charPool }.toTypedArray()) fun bruteForce(length: Int, charPool: Array<Array<String>>): List<String> { val strs = ArraySet<String>() bruteForce(length, charPool) { word -> strs.add(word) } return strs } fun bruteForce(length: Int, charPool: Array<String>, operate: (String) -> Unit) = bruteForce(length, (0 until length).map { charPool }.toTypedArray(), operate) fun bruteForce(length: Int, charPool: Array<Array<String>>, operate: (String) -> Unit) = bruteForce(length, charPool.map { it.size }.toIntArray()) { word -> operate(word.mapIndexed { index, i -> charPool[index][i] }.joinToString("")) } fun bruteForce(length: Int, charPool: IntArray, operate: (IntArray) -> Unit) { val word = IntArray(length) val lastIndex = length - 1 operate(word) loop@ while (word.filterIndexed { index, i -> i + 1 == charPool[index] }.count() < length) { word[lastIndex] += 1 if (word[lastIndex] >= charPool[lastIndex]) { word[lastIndex] = 0 for (i in lastIndex - 1 downTo 0) { word[i] += 1 if (word[i] >= charPool[i]) { word[i] = 0 continue } operate(word) continue@loop } } else operate(word) } }
mit
9c22f7dae65e6385fe012e6f1e8e7401
36.205479
235
0.536648
3.834746
false
false
false
false
BenoitDuffez/AndroidCupsPrint
app/src/main/java/io/github/benoitduffez/cupsprint/app/ManageManualPrintersActivity.kt
1
3946
package io.github.benoitduffez.cupsprint.app import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.TextView import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import io.github.benoitduffez.cupsprint.R import kotlinx.android.synthetic.main.activity_manage_manual_printers.* import kotlinx.android.synthetic.main.manage_printers_list_item.view.* import java.util.ArrayList class ManageManualPrintersActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_manual_printers) // Build adapter val prefs = getSharedPreferences(AddPrintersActivity.SHARED_PREFS_MANUAL_PRINTERS, Context.MODE_PRIVATE) val numPrinters = prefs.getInt(AddPrintersActivity.PREF_NUM_PRINTERS, 0) val printers = getPrinters(prefs, numPrinters) val adapter = ManualPrintersAdapter(this, R.layout.manage_printers_list_item, printers) // Setup adapter with click to remove manage_printers_list.adapter = adapter manage_printers_list.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> val editor = prefs.edit() val actualNumPrinters = prefs.getInt(AddPrintersActivity.PREF_NUM_PRINTERS, 0) editor.putInt(AddPrintersActivity.PREF_NUM_PRINTERS, actualNumPrinters - 1) editor.remove(AddPrintersActivity.PREF_NAME + position) editor.remove(AddPrintersActivity.PREF_URL + position) editor.apply() adapter.removeItem(position) } manage_printers_empty.visibility = if (numPrinters <= 0) View.VISIBLE else View.GONE } private fun getPrinters(prefs: SharedPreferences, numPrinters: Int): List<ManualPrinterInfo> { if (numPrinters <= 0) { return ArrayList() } val printers = ArrayList<ManualPrinterInfo>(numPrinters) var url: String? var name: String? for (i in 0 until numPrinters) { name = prefs.getString(AddPrintersActivity.PREF_NAME + i, null) url = prefs.getString(AddPrintersActivity.PREF_URL + i, null) if (name != null && url != null) { printers.add(ManualPrinterInfo(name, url)) } } return printers } private class ManualPrinterInfo(internal var name: String, internal var url: String) private class ManualPrinterInfoViews internal constructor(internal var name: TextView, internal var url: TextView) private class ManualPrintersAdapter(context: Context, @LayoutRes resource: Int, objects: List<ManualPrinterInfo>) : ArrayAdapter<ManualPrinterInfo>(context, resource, objects) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view = when (convertView) { null -> { val inflate = LayoutInflater.from(parent.context).inflate(R.layout.manage_printers_list_item, parent, false) inflate.tag = ManualPrinterInfoViews(inflate.manual_printer_name, inflate.manual_printer_url) inflate } else -> convertView } val views = view.tag as ManualPrinterInfoViews val info = getItem(position) if (info != null) { views.name.text = info.name views.url.text = info.url } else { throw IllegalStateException("Manual printers list can't have invalid items") } return view } fun removeItem(position: Int) = remove(getItem(position)) } }
lgpl-3.0
bb7da3bf45e97bbeeffe6302c80e2d8c
42.362637
181
0.674607
4.642353
false
false
false
false
FantAsylum/Floor--13
core/src/com/floor13/game/core/map/TyrantLikeMapGenerator.kt
1
1371
package com.floor13.game.core.map /** * @see <a href="http://www.roguebasin.com/index.php?title=Dungeon-Building_Algorithm">Dungeon-Building Algorithm</a> */ class TyrantLikeMapGanerator( val width: Int, val height: Int, val roomWidth: IntRange, val roomHeight: IntRange ): MapGenerator { override fun generate(): Map { // 1. Fill the whole map with solid earth val map = Map(width, height) // 2. Dig out a single room in the centre of the map map.fillRect( width / 2, height / 2, roomWidth.random, roomHeight.random, { Ground() }) // 3. Pick a wall of any room throw NotImplementedError() } // private val features = arrayOf( // { x: Int, y: Int, direction: Direction -> // Room // data class Measurements( // val xs: IntRange, // val ys: IntRange) // val measurments = when direction { // Direction.UP -> Measurements( // Math.max(0, x - roomWidth.endInclusive) .. // Math.min(width - 1, x + roomWidth.endInclusive), // 0, // } // } // ) }
mit
c20a8d094e00813137b25615d599b64b
32.439024
117
0.475565
4.380192
false
false
false
false
nickthecoder/tickle
tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/FontParameter.kt
1
2994
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.editor.util import uk.co.nickthecoder.paratask.ParameterException import uk.co.nickthecoder.paratask.parameters.* import uk.co.nickthecoder.tickle.resources.FontResource import java.awt.Font class FontParameter(name: String) : SimpleGroupParameter(name) { val fontNameP = StringParameter("fontName", label = "", value = Font.SANS_SERIF, columns = 20) val fontStyleP = ChoiceParameter<FontResource.FontStyle>("fontStyle", label = "", value = FontResource.FontStyle.PLAIN).enumChoices(mixCase = true) val fontNameAndStyleP = SimpleGroupParameter("fontNameAndStyle", label = "") .addParameters(fontNameP, fontStyleP).asHorizontal() val fontFileP = FileParameter("fontFile", label = "", extensions = listOf("ttf", "otf")) val fontOneOfP = OneOfParameter("fontChoice", label = "Font", value = fontNameAndStyleP, choiceLabel = "") .addChoices("Named" to fontNameAndStyleP, "From File" to fontFileP) val fontSizeP = DoubleParameter("fontSize", label = "Size", value = 22.0) init { addParameters(fontOneOfP, fontNameAndStyleP, fontFileP, fontSizeP) } fun update(fontResource: FontResource) { if (fontOneOfP.value == fontNameAndStyleP) { fontResource.fontName = fontNameP.value fontResource.style = fontStyleP.value!! fontResource.file = null } else { fontResource.fontName = "" fontResource.style = FontResource.FontStyle.PLAIN fontResource.file = fontFileP.value } fontResource.size = fontSizeP.value!! try { fontResource.fontTexture } catch(e: Exception) { throw ParameterException(fontOneOfP, "Could not load/create the font.") } } fun from(fontResource: FontResource) { if (fontResource.file == null) { fontOneOfP.value = fontNameAndStyleP fontNameP.value = fontResource.fontName fontStyleP.value = fontResource.style fontFileP.value = null } else { fontOneOfP.value = fontFileP fontNameP.value = "" fontStyleP.value = FontResource.FontStyle.PLAIN fontFileP.value = fontResource.file } fontSizeP.value = fontResource.size } }
gpl-3.0
2cee1c99cfa4cd20b03160c0aa6109c5
35.512195
151
0.684035
4.25889
false
false
false
false
luxons/seven-wonders
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/resources/Production.kt
1
2522
package org.luxons.sevenwonders.engine.resources import org.luxons.sevenwonders.model.resources.ResourceType import java.util.EnumSet data class Production internal constructor( private val fixedResources: MutableResources = mutableResourcesOf(), // cannot be a Set because the same choices can be there multiple times private val alternativeResources: MutableList<Set<ResourceType>> = mutableListOf(), ) { fun getFixedResources(): Resources = fixedResources fun getAlternativeResources(): List<Set<ResourceType>> = alternativeResources fun addFixedResource(type: ResourceType, quantity: Int) = fixedResources.add(type, quantity) fun addChoice(vararg options: ResourceType) { val optionSet = EnumSet.copyOf(options.toList()) alternativeResources.add(optionSet) } fun addAll(resources: Resources) = fixedResources.add(resources) fun addAll(production: Production) { fixedResources.add(production.fixedResources) alternativeResources.addAll(production.getAlternativeResources()) } internal fun asChoices(): List<Set<ResourceType>> { val fixedAsChoices = fixedResources.toList().map { EnumSet.of(it) } return fixedAsChoices + alternativeResources } operator fun contains(resources: Resources): Boolean { if (fixedResources.containsAll(resources)) { return true } return containedInAlternatives(resources - fixedResources) } private fun containedInAlternatives(resources: Resources): Boolean = containedInAlternatives(resources.toMutableResources(), alternativeResources) private fun containedInAlternatives( resources: MutableResources, alternatives: MutableList<Set<ResourceType>>, ): Boolean { if (resources.isEmpty()) { return true } for (type in ResourceType.values()) { if (resources[type] <= 0) { continue } // return if no alternative produces the resource of this entry val candidate = alternatives.firstOrNull { a -> a.contains(type) } ?: return false resources.remove(type, 1) alternatives.remove(candidate) val remainingAreContainedToo = containedInAlternatives(resources, alternatives) resources.add(type, 1) alternatives.add(candidate) if (remainingAreContainedToo) { return true } } return false } }
mit
cbf223851e5a7441873bc812e3afedc5
36.088235
96
0.677637
5.136456
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/anime/AnimeActivity.kt
1
4701
package me.proxer.app.anime import android.app.Activity import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.core.app.ShareCompat import androidx.fragment.app.commitNow import com.jakewharton.rxbinding3.view.clicks import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import me.proxer.app.R import me.proxer.app.base.DrawerActivity import me.proxer.app.media.MediaActivity import me.proxer.app.util.extension.getSafeStringExtra import me.proxer.app.util.extension.startActivity import me.proxer.app.util.extension.toEpisodeAppString import me.proxer.library.enums.AnimeLanguage import me.proxer.library.enums.Category import me.proxer.library.util.ProxerUrls import me.proxer.library.util.ProxerUtils /** * @author Ruben Gees */ class AnimeActivity : DrawerActivity() { companion object { private const val ID_EXTRA = "id" private const val EPISODE_EXTRA = "episode" private const val LANGUAGE_EXTRA = "language" private const val NAME_EXTRA = "name" private const val EPISODE_AMOUNT_EXTRA = "episode_amount" fun navigateTo( context: Activity, id: String, episode: Int, language: AnimeLanguage, name: String? = null, episodeAmount: Int? = null ) { context.startActivity<AnimeActivity>( ID_EXTRA to id, EPISODE_EXTRA to episode, LANGUAGE_EXTRA to language, NAME_EXTRA to name, EPISODE_AMOUNT_EXTRA to episodeAmount ) } } val id: String get() = when (intent.hasExtra(ID_EXTRA)) { true -> intent.getSafeStringExtra(ID_EXTRA) false -> intent?.data?.pathSegments?.getOrNull(1) ?: "-1" } var episode: Int get() = when (intent.hasExtra(EPISODE_EXTRA)) { true -> intent.getIntExtra(EPISODE_EXTRA, 1) false -> intent?.data?.pathSegments?.getOrNull(2)?.toIntOrNull() ?: 1 } set(value) { intent.putExtra(EPISODE_EXTRA, value) updateTitle() } val language: AnimeLanguage get() = when (intent.hasExtra(LANGUAGE_EXTRA)) { true -> intent.getSerializableExtra(LANGUAGE_EXTRA) as AnimeLanguage false -> intent?.data?.pathSegments?.getOrNull(3)?.let { ProxerUtils.toApiEnum<AnimeLanguage>(it) } ?: AnimeLanguage.ENGLISH_SUB } var name: String? get() = intent.getStringExtra(NAME_EXTRA) set(value) { intent.putExtra(NAME_EXTRA, value) updateTitle() } var episodeAmount: Int? get() = when (intent.hasExtra(EPISODE_AMOUNT_EXTRA)) { true -> intent.getIntExtra(EPISODE_AMOUNT_EXTRA, 1) false -> null } set(value) { if (value == null) { intent.removeExtra(EPISODE_AMOUNT_EXTRA) } else { intent.putExtra(EPISODE_AMOUNT_EXTRA, value) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setupToolbar() updateTitle() if (savedInstanceState == null) { supportFragmentManager.commitNow { replace(R.id.container, AnimeFragment.newInstance()) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_share -> name?.let { ShareCompat.IntentBuilder(this) .setText(getString(R.string.share_anime, episode, it, ProxerUrls.animeWeb(id, episode, language))) .setType("text/plain") .setChooserTitle(getString(R.string.share_title)) .startChooser() } } return super.onOptionsItemSelected(item) } private fun setupToolbar() { toolbar.clicks() .autoDisposable(this.scope()) .subscribe { name?.let { MediaActivity.navigateTo(this, id, it, Category.ANIME) } } } private fun updateTitle() { title = name supportActionBar?.subtitle = Category.ANIME.toEpisodeAppString(this, episode) } }
gpl-3.0
47da667a4495acf7b08bc9270683f6e9
30.979592
118
0.605829
4.645257
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/features/weapons/list/WeaponListViewModel.kt
1
2585
package com.ghstudios.android.features.weapons.list import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import com.ghstudios.android.components.WeaponListEntry import com.ghstudios.android.data.DataManager /** * An immutable class used to represent the WeaponListViewModel's state. * Kotlin classes implement equals() */ private data class ViewModelState(val weaponType : String?, val filterFinal: Boolean) /** * A viewmodel that stores state data for the WeaponListFragment */ class WeaponListViewModel(app: Application) : AndroidViewModel(app) { private val dataManager = DataManager.get() /** * Private variable that stores the internal state of the view model. * If a new state is not equal to this, data needs to be reloaded. */ private var currentState = ViewModelState(null, false) /** * Returns the currently selected weapon type */ val weaponType get() = currentState.weaponType /** * LiveData that contains the list of weapon entries. * Updates when the list of weapon entries changes */ val weaponListData = MutableLiveData<List<WeaponListEntry>>() /** * Collapsed UI groups. Used to restore collapsed weapons on configuration change */ var collapsedGroups : List<Int>? = null /** * Sets whether the weapon list should only contain final upgrades or not. * The livedata is immediately updated when changing this value */ var filterFinal: Boolean get() = currentState.filterFinal set(value) { setState(currentState.copy(filterFinal=value)) } /** * Sets the weapon type and begins loading. * Once weapon type is set, update the filterFinal property to update the list. */ fun loadWeaponType(weaponType : String) { val newState = currentState.copy(weaponType=weaponType) setState(newState) } private fun setState(newState : ViewModelState) { if (this.currentState == newState) { return // nothing changed } this.currentState = newState val weaponType = newState.weaponType if (weaponType == null || weaponType == "") { return // nothing to load } Thread { weaponListData.postValue(when (newState.filterFinal) { true -> dataManager.queryWeaponTreeArrayFinal(weaponType) false -> dataManager.queryWeaponTreeArray(weaponType) }) }.start() } }
mit
c3a4ad072447651d17a1f44e4ccdfa12
30.925926
85
0.668859
4.868173
false
false
false
false
rectangle-dbmi/Realtime-Port-Authority
pat-static/src/main/java/com/rectanglel/patstatic/model/RetrofitPatApi.kt
1
2203
package com.rectanglel.patstatic.model import com.rectanglel.patstatic.patterns.response.PatternResponse import com.rectanglel.patstatic.predictions.response.PredictionResponse import com.rectanglel.patstatic.routes.response.BusRouteResponse import com.rectanglel.patstatic.vehicles.response.VehicleResponse import io.reactivex.Flowable import io.reactivex.Single import retrofit2.http.GET import retrofit2.http.Query /** * This is the general api that sets the retrofit api. You must have the class * and the pat_api key before using the api in the gradle.properties file * * @author Jeremy Jao * @since 46 */ interface RetrofitPatApi { /** * Generates a response to get routes from the API * @return the list of routes available from the TrueTime API */ @get:GET("getroutes?format=json") val routes: Single<BusRouteResponse> /** * generates a response for patters * @param rt - the route */ @GET("getpatterns?format=json&rtpidatafeed=Port%20Authority%20Bus") fun getPatterns(@Query("rt") rt: String): Flowable<PatternResponse> /** * Generates a response to get vehicles * @param routes - the routes */ @GET("getvehicles?format=json") fun getVehicles(@Query("rt") routes: String): Flowable<VehicleResponse> /** * Generates a response to get the predictions using the stop id * @param stpid - the stop id */ @GET("getpredictions?format=json&rtpidatafeed=Port%20Authority%20Bus") fun getStopPredictions(@Query("stpid") stpid: Int): Flowable<PredictionResponse> /** * Generates a response to get the predictions using the stop id * @param stpid - the stop id * @param rts - the routes */ @GET("getpredictions?format=json&top=10&rtpidatafeed=Port%20Authority%20Bus") fun getStopPredictions(@Query("stpid") stpid: Int, @Query("rt") rts: String): Single<PredictionResponse> /** * Generates a response to get the predictions using the bus id * @param vid - the bus id */ @GET("getpredictions?format=json&top=10&rtpidatafeed=Port%20Authority%20Bus") fun getBusPredictions(@Query("vid") vid: Int): Single<PredictionResponse> }
gpl-3.0
8dfb3246a5fe21d2bdd12b56c9bb5660
32.378788
108
0.711757
3.818024
false
false
false
false
tronalddump-io/tronald-app
src/main/kotlin/io/tronalddump/app/privacy/PrivacyController.kt
1
802
package io.tronalddump.app.privacy import io.swagger.v3.oas.annotations.Operation import io.tronalddump.app.Url import org.springframework.http.HttpHeaders import org.springframework.http.MediaType import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.servlet.ModelAndView @Controller class PrivacyController { @Operation(hidden = true) @RequestMapping( headers = [HttpHeaders.ACCEPT + "=" + MediaType.TEXT_HTML_VALUE], method = [RequestMethod.GET], produces = [MediaType.TEXT_HTML_VALUE], value = [Url.PRIVACY] ) fun get(): ModelAndView { return ModelAndView("privacy") } }
gpl-3.0
495903d986ef447bfd81ea0f496e84bd
31.12
77
0.736908
4.430939
false
false
false
false
jitsi/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/version/JvbVersionService.kt
2
2015
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.videobridge.version import org.jitsi.utils.version.Version import org.jitsi.utils.version.VersionImpl import org.jitsi.utils.version.VersionService import java.util.regex.Matcher import java.util.regex.Pattern class JvbVersionService : VersionService { private val versionString: String? by lazy { JvbVersionService::class.java.`package`.implementationVersion } private val version: Version by lazy { parseVersionString(versionString) } override fun getCurrentVersion(): Version = version override fun parseVersionString(version: String?): Version { val matcher = Pattern.compile("(\\d*)\\.(\\d*)-(.*)").matcher(version ?: "").apply { find() } val majorVersion = matcher.groupOrNull(1)?.toInt() ?: defaultMajorVersion val minorVersion = matcher.groupOrNull(2)?.toInt() ?: defaultMinorVersion val buildId = matcher.groupOrNull(3) ?: defaultBuildId return VersionImpl( "JVB", majorVersion, minorVersion, buildId ) } companion object { private const val defaultMajorVersion = 2 private const val defaultMinorVersion = 1 private val defaultBuildId: String? = null } } private fun Matcher.groupOrNull(groupId: Int): String? { return try { group(groupId) } catch (t: Throwable) { null } }
apache-2.0
fc707f2ca23c05f52f8afe02e091dc15
30.984127
101
0.682878
4.41886
false
false
false
false
alondero/nestlin
src/main/kotlin/com/github/alondero/nestlin/ui/Application.kt
1
2653
package com.github.alondero.nestlin.ui import com.github.alondero.nestlin.Nestlin import com.github.alondero.nestlin.ppu.Frame import com.github.alondero.nestlin.ppu.RESOLUTION_HEIGHT import com.github.alondero.nestlin.ppu.RESOLUTION_WIDTH import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.canvas.Canvas import javafx.scene.image.PixelFormat import javafx.scene.layout.StackPane import javafx.stage.Stage import tornadofx.App import java.nio.file.Paths import kotlin.concurrent.thread fun main(args: Array<String>) { when { args.size == 0 -> throw IllegalStateException("Please provide a rom file as an argument") else -> Application.launch(NestlinApplication::class.java, *args) } } class NestlinApplication : FrameListener, App() { private lateinit var stage: Stage private var canvas = Canvas(RESOLUTION_HEIGHT.toDouble(), RESOLUTION_WIDTH.toDouble()) private var nestlin = Nestlin().also { it.addFrameListener(this) } private var running = false private var nextFrame = ByteArray(RESOLUTION_HEIGHT * RESOLUTION_WIDTH * 3) override fun start(stage: Stage) { this.stage = stage.apply { title = "Nestlin" scene = Scene(StackPane().apply { children.add(canvas) }) show() } object: AnimationTimer() { override fun handle(now: Long) { val pixelWriter = canvas.graphicsContext2D.pixelWriter val pixelFormat = PixelFormat.getByteRgbInstance() pixelWriter.setPixels(0, 0, RESOLUTION_WIDTH, RESOLUTION_HEIGHT, pixelFormat, nextFrame, 0, RESOLUTION_WIDTH*3) } }.start() thread { with(nestlin) { if (!parameters.named["debug"].isNullOrEmpty()) { enableLogging() } load(Paths.get(parameters.unnamed[0])) powerReset() start() } } running = true } override fun stop() { nestlin.stop() running = false } override fun frameUpdated(frame: Frame) { frame.scanlines.withIndex().forEach { (y, scanline) -> scanline.withIndex().forEach { (x, pixel) -> val r = (pixel shr 16).toByte() val g = (pixel shr 8).toByte() val b = pixel.toByte() val pixIdx = (y * RESOLUTION_WIDTH + x) * 3 nextFrame[pixIdx] = r nextFrame[pixIdx + 1] = g nextFrame[pixIdx + 2] = b } } } }
gpl-3.0
b276d7b104c4c36b5a2d97a261cb6026
31.765432
127
0.609876
4.238019
false
false
false
false
k0shk0sh/FastHub
app/src/main/java/com/fastaccess/ui/modules/repos/projects/details/ProjectPagerPresenter.kt
1
3381
package com.fastaccess.ui.modules.repos.projects.details import android.content.Intent import com.fastaccess.R import com.fastaccess.data.dao.Pageable import com.fastaccess.data.dao.ProjectColumnModel import com.fastaccess.data.dao.model.Login import com.fastaccess.helper.BundleConstant import com.fastaccess.provider.rest.RestProvider import com.fastaccess.ui.base.mvp.presenter.BasePresenter import io.reactivex.Observable import io.reactivex.functions.BiFunction import retrofit2.Response /** * Created by Hashemsergani on 11.09.17. */ class ProjectPagerPresenter : BasePresenter<ProjectPagerMvp.View>(), ProjectPagerMvp.Presenter { private val columns = arrayListOf<ProjectColumnModel>() @com.evernote.android.state.State var projectId: Long = -1 @com.evernote.android.state.State var repoId: String? = null @com.evernote.android.state.State var login: String = "" @com.evernote.android.state.State var viewerCanUpdate: Boolean = false override fun onError(throwable: Throwable) { val code = RestProvider.getErrorCode(throwable) if (code == 404) { sendToView { it.onOpenUrlInBrowser() } } super.onError(throwable) } override fun getColumns(): ArrayList<ProjectColumnModel> = columns override fun onRetrieveColumns() { val repoId = repoId if (repoId != null && !repoId.isNullOrBlank()) { makeRestCall(Observable.zip(RestProvider.getProjectsService(isEnterprise).getProjectColumns(projectId), RestProvider.getRepoService(isEnterprise).isCollaborator(login, repoId, Login.getUser().login), BiFunction { items: Pageable<ProjectColumnModel>, response: Response<Boolean> -> viewerCanUpdate = response.code() == 204 return@BiFunction items }) .flatMap { if (it.items != null) { return@flatMap Observable.just(it.items) } return@flatMap Observable.just(listOf<ProjectColumnModel>()) }) { t -> columns.clear() columns.addAll(t) sendToView { it.onInitPager(columns) } } } else { makeRestCall(RestProvider.getProjectsService(isEnterprise).getProjectColumns(projectId) .flatMap { if (it.items != null) { return@flatMap Observable.just(it.items) } return@flatMap Observable.just(listOf<ProjectColumnModel>()) }) { t -> columns.clear() columns.addAll(t) sendToView { it.onInitPager(columns) } } } } override fun onActivityCreated(intent: Intent?) { intent?.let { it.extras?.let { projectId = it.getLong(BundleConstant.ID) repoId = it.getString(BundleConstant.ITEM) login = it.getString(BundleConstant.EXTRA) ?: "" } } if (columns.isEmpty()) { if (projectId > 0) onRetrieveColumns() else sendToView { it.showMessage(R.string.error, R.string.unexpected_error) } } else { sendToView { it.onInitPager(columns) } } } }
gpl-3.0
0b118f3a6f6e5295a45cb1e3ed923602
37.873563
115
0.603963
4.755274
false
false
false
false