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
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/audio/AudioBrowserAdapter.kt
1
14661
/* * ************************************************************************* * BaseAdapter.java * ************************************************************************** * Copyright © 2016-2017 VLC authors and VideoLAN * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.audio import android.annotation.TargetApi import android.content.Context import android.graphics.drawable.BitmapDrawable import android.os.Build import android.os.Handler import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.view.MotionEventCompat import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.paging.PagedList import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.libvlc.util.AndroidUtil import org.videolan.medialibrary.interfaces.media.Artist import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.medialibrary.media.MediaLibraryItem.FLAG_SELECTED import org.videolan.resources.AppContextProvider import org.videolan.resources.UPDATE_SELECTION import org.videolan.resources.interfaces.FocusListener import org.videolan.tools.MultiSelectAdapter import org.videolan.tools.MultiSelectHelper import org.videolan.tools.Settings import org.videolan.vlc.R import org.videolan.vlc.databinding.AudioBrowserCardItemBinding import org.videolan.vlc.databinding.AudioBrowserItemBinding import org.videolan.vlc.gui.helpers.MarqueeViewHolder import org.videolan.vlc.gui.helpers.SelectorViewHolder import org.videolan.vlc.gui.helpers.enableMarqueeEffect import org.videolan.vlc.gui.helpers.getAudioIconDrawable import org.videolan.vlc.gui.view.FastScroller import org.videolan.vlc.interfaces.IEventsHandler import org.videolan.vlc.interfaces.IListEventsHandler import org.videolan.vlc.interfaces.SwipeDragHelperAdapter private const val SHOW_IN_LIST = -1 @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class AudioBrowserAdapter @JvmOverloads constructor( type: Int, private val eventsHandler: IEventsHandler<MediaLibraryItem>, private val listEventsHandler: IListEventsHandler? = null, private val reorder: Boolean = false, internal var cardSize: Int = SHOW_IN_LIST ) : PagedListAdapter<MediaLibraryItem, AudioBrowserAdapter.AbstractMediaItemViewHolder<ViewDataBinding>>(DIFF_CALLBACK), FastScroller.SeparatedAdapter, MultiSelectAdapter<MediaLibraryItem>, SwipeDragHelperAdapter { private var listImageWidth: Int val multiSelectHelper: MultiSelectHelper<MediaLibraryItem> = MultiSelectHelper(this, UPDATE_SELECTION) private val defaultCover: BitmapDrawable? private val defaultCoverCard: BitmapDrawable? private var focusNext = -1 private var focusListener: FocusListener? = null private lateinit var inflater: LayoutInflater private val handler by lazy(LazyThreadSafetyMode.NONE) { Handler() } val isEmpty: Boolean get() = currentList.isNullOrEmpty() init { val ctx = when (eventsHandler) { is Context -> eventsHandler is Fragment -> eventsHandler.requireContext() else -> AppContextProvider.appContext } listImageWidth = ctx.resources.getDimension(R.dimen.audio_browser_item_size).toInt() defaultCover = getAudioIconDrawable(ctx, type, false) defaultCoverCard = getAudioIconDrawable(ctx, type, true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AbstractMediaItemViewHolder<ViewDataBinding> { if (!::inflater.isInitialized) { inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } return if (displayInCard()) { val binding = AudioBrowserCardItemBinding.inflate(inflater, parent, false) MediaItemCardViewHolder(binding) as AbstractMediaItemViewHolder<ViewDataBinding> } else { val binding = AudioBrowserItemBinding.inflate(inflater, parent, false) MediaItemViewHolder(binding) as AbstractMediaItemViewHolder<ViewDataBinding> } } private fun displayInCard() = cardSize != SHOW_IN_LIST override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) if (Settings.listTitleEllipsize == 4) enableMarqueeEffect(recyclerView, handler) } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { if (Settings.listTitleEllipsize == 4) handler.removeCallbacksAndMessages(null) super.onDetachedFromRecyclerView(recyclerView) } override fun onBindViewHolder(holder: AbstractMediaItemViewHolder<ViewDataBinding>, position: Int) { if (position >= itemCount) return val item = getItem(position) holder.setItem(item) if (item is Artist) item.description = holder.binding.root.context.resources.getQuantityString(R.plurals.albums_quantity, item.albumsCount, item.albumsCount) val isSelected = multiSelectHelper.isSelected(position) holder.setCoverlay(isSelected) holder.selectView(isSelected) holder.binding.executePendingBindings() if (position == focusNext) { holder.binding.root.requestFocus() focusNext = -1 } } override fun onBindViewHolder(holder: AbstractMediaItemViewHolder<ViewDataBinding>, position: Int, payloads: List<Any>) { if (payloads.isNullOrEmpty()) onBindViewHolder(holder, position) else { val payload = payloads[0] if (payload is MediaLibraryItem) { val isSelected = payload.hasStateFlags(FLAG_SELECTED) holder.setCoverlay(isSelected) holder.selectView(isSelected) } else if (payload is Int) { if (payload == UPDATE_SELECTION) { val isSelected = multiSelectHelper.isSelected(position) holder.setCoverlay(isSelected) holder.selectView(isSelected) } } } } override fun onViewRecycled(h: AbstractMediaItemViewHolder<ViewDataBinding>) { if (Settings.listTitleEllipsize == 4) handler.removeCallbacksAndMessages(null) h.recycle() super.onViewRecycled(h) } private fun isPositionValid(position: Int): Boolean { return position in 0 until itemCount } override fun getItemId(position: Int): Long { if (!isPositionValid(position)) return -1 val item = getItem(position) return item?.id ?: -1 } override fun getItem(position: Int): MediaLibraryItem? { return if (position in 0 until itemCount) super.getItem(position) else null } override fun getItemViewType(position: Int): Int { val item = getItem(position) return item?.itemType ?: MediaLibraryItem.TYPE_MEDIA } fun clear() { // getDataset().clear(); } override fun onCurrentListChanged(previousList: PagedList<MediaLibraryItem>?, currentList: PagedList<MediaLibraryItem>?) { eventsHandler.onUpdateFinished(this@AudioBrowserAdapter) } override fun hasSections(): Boolean { return true } override fun onItemMove(fromPosition: Int, toPosition: Int) { notifyItemMoved(fromPosition, toPosition) } override fun onItemMoved(dragFrom: Int, dragTo: Int) { listEventsHandler!!.onMove(dragFrom, dragTo) preventNextAnim = true } override fun onItemDismiss(position: Int) { val item = getItem(position) listEventsHandler!!.onRemove(position, item!!) } fun setOnFocusChangeListener(focusListener: FocusListener?) { this.focusListener = focusListener } @TargetApi(Build.VERSION_CODES.M) inner class MediaItemViewHolder(binding: AudioBrowserItemBinding) : AbstractMediaItemViewHolder<AudioBrowserItemBinding>(binding) { private var coverlayResource = 0 var onTouchListener: View.OnTouchListener override val titleView: TextView? = binding.title init { binding.holder = this defaultCover?.let { binding.cover = it } if (AndroidUtil.isMarshMallowOrLater) itemView.setOnContextClickListener { v -> onMoreClick(v) true } onTouchListener = object : View.OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { if (listEventsHandler == null) { return false } if (multiSelectHelper.getSelectionCount() != 0) { return false } if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) { listEventsHandler.onStartDrag(this@MediaItemViewHolder) return true } return false } } binding.imageWidth = listImageWidth } override fun setItem(item: MediaLibraryItem?) { binding.item = item } override fun recycle() { binding.cover = if (cardSize == SHOW_IN_LIST && defaultCover != null) defaultCover else null binding.mediaCover.resetFade() binding.title.isSelected = false } override fun setCoverlay(selected: Boolean) { val resId = if (selected) R.drawable.ic_action_mode_select else 0 if (resId != coverlayResource) { binding.selectorImage.setImageResource(if (selected) R.drawable.ic_action_mode_select else 0) coverlayResource = resId } } } @TargetApi(Build.VERSION_CODES.M) inner class MediaItemCardViewHolder(binding: AudioBrowserCardItemBinding) : AbstractMediaItemViewHolder<AudioBrowserCardItemBinding>(binding) { private var coverlayResource = 0 override val titleView = binding.title init { binding.holder = this binding.scaleType = ImageView.ScaleType.CENTER_INSIDE defaultCoverCard?.let { binding.cover = it } if (AndroidUtil.isMarshMallowOrLater) itemView.setOnContextClickListener { v -> onMoreClick(v) true } binding.imageWidth = cardSize binding.container.layoutParams.width = cardSize } override fun setItem(item: MediaLibraryItem?) { binding.item = item } override fun recycle() { defaultCoverCard?.let { binding.cover = it } binding.mediaCover.resetFade() binding.title.isSelected = false } override fun setCoverlay(selected: Boolean) { val resId = if (selected) R.drawable.ic_action_mode_select else 0 if (resId != coverlayResource) { binding.selectorImage.setImageResource(if (selected) R.drawable.ic_action_mode_select else 0) coverlayResource = resId } } } @TargetApi(Build.VERSION_CODES.M) abstract inner class AbstractMediaItemViewHolder<T : ViewDataBinding>(binding: T) : SelectorViewHolder<T>(binding), MarqueeViewHolder { val canBeReordered: Boolean get() = reorder fun onClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onClick(v, layoutPosition, it) } } fun onMoreClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onCtxClick(v, layoutPosition, it) } } fun onLongClick(v: View): Boolean { return getItem(layoutPosition)?.let { eventsHandler.onLongClick(v, layoutPosition, it) } == true } fun onImageClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onImageClick(v, layoutPosition, it) } } fun onMainActionClick(v: View) { getItem(layoutPosition)?.let { eventsHandler.onMainActionClick(v, layoutPosition, it) } } override fun isSelected() = multiSelectHelper.isSelected(layoutPosition) abstract fun setItem(item: MediaLibraryItem?) abstract fun recycle() abstract fun setCoverlay(selected: Boolean) } companion object { private val TAG = "VLC/AudioBrowserAdapter" private const val UPDATE_PAYLOAD = 1 /** * Awful hack to workaround the [PagedListAdapter] not keeping track of notifyItemMoved operations */ private var preventNextAnim: Boolean = false private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<MediaLibraryItem>() { override fun areItemsTheSame( oldMedia: MediaLibraryItem, newMedia: MediaLibraryItem): Boolean { return if (preventNextAnim) { true } else oldMedia === newMedia || oldMedia.itemType == newMedia.itemType && oldMedia.equals(newMedia) } override fun areContentsTheSame( oldMedia: MediaLibraryItem, newMedia: MediaLibraryItem): Boolean { return false } override fun getChangePayload(oldItem: MediaLibraryItem, newItem: MediaLibraryItem): Any? { preventNextAnim = false return UPDATE_PAYLOAD } } } }
gpl-2.0
2a77d821220c3b7158911e9f83814f03
37.780423
165
0.660686
5.091699
false
false
false
false
ademar111190/Studies
Projects/Reddit/core/src/test/java/ademar/study/reddit/core/test/Fixture.kt
1
12395
package ademar.study.reddit.core.test import ademar.study.reddit.core.model.Error import ademar.study.reddit.core.model.Post import ademar.study.reddit.core.model.internal.* import org.mockito.Mockito.`when` as whenever object Fixture { object child { val JSON = """ { "kind": "t3", "data": ${post.JSON} } """ fun makeModel(): Child { val model = Child() model.post = post.makeModel() return model } } object comment { val AUTHOR = "pranavsharma0096" val TEXT = "Faster than Google's own devices. I'm impressed" val DOWNS = 2L val UPS = 7L val JSON = """ { "subreddit_id": "t5_2qlqh", "banned_by": null, "removal_reason": null, "link_id": "t3_5s1dkg", "likes": null, "replies": "", "user_reports": [], "saved": false, "id": "ddbppd1", "gilded": 0, "archived": false, "report_reasons": null, "author": "$AUTHOR", "parent_id": "t3_5s1dkg", "score": 1, "approved_by": null, "controversiality": 0, "body": "$TEXT", "edited": false, "author_flair_css_class": null, "downs": $DOWNS, "body_html": "&lt;div class=\"md\"&gt;&lt;p&gt;Faster than Google&amp;#39;s own devices. I&amp;#39;m impressed&lt;/p&gt;\n&lt;/div&gt;", "stickied": false, "subreddit": "Android", "score_hidden": true, "name": "t1_ddbppd1", "created": 1486254786, "author_flair_text": null, "created_utc": 1486225986, "ups": $UPS, "mod_reports": [], "num_reports": null, "distinguished": null } """ fun makeModel(): Comment { val model = Comment() model.replies = null model.author = AUTHOR model.text = TEXT model.downs = DOWNS model.ups = UPS return model } } object data { val JSON = """ { "modhash": "", "children": [${child.JSON}] } """ fun makeModel(): Data { val model = Data() model.children = listOf(child.makeModel()) return model } } object error { val CODE = 1 val MESSAGE = "Some error" val JSON = """ { "code": $CODE, "message": "$MESSAGE" } """ fun makeException(): Throwable { return Exception("Some error") } fun makeModel(): Error { val model = Error() model.code = CODE model.message = MESSAGE return model } } object post { val TITLE = "Galaxy S8 press render leak" val AUTHOR = "Idb996" val THUMBNAIL = "http://b.thumbs.redditmedia.com/4pTVmV1JFSdgaGFpXwSufG1RQFOQYy2FNoimEndxtJg.jpg" val CREATED = 1485666124L val COMMENTS = 7L val DOWNS = 1L val UPS = 3L val REFERENCE = "t3_5qpvlr" val LINK = "/r/Android/comments/5qpvlr/galaxy_s8_press_render_leak/" val JSON = """ { "contest_mode": false, "banned_by": null, "domain": "twitter.com", "subreddit": "Android", "selftext_html": null, "selftext": "", "likes": null, "suggested_sort": null, "user_reports": [], "secure_media": null, "saved": false, "id": "5qpvlr", "gilded": 0, "secure_media_embed": {}, "clicked": false, "report_reasons": null, "author": "$AUTHOR", "media": null, "name": "$REFERENCE", "score": 3, "approved_by": null, "over_18": false, "removal_reason": null, "hidden": false, "preview": { "images": [ { "source": { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?s=681b2f367bfec4c7c926f8adf6d447da", "width": 1877, "height": 1500 }, "resolutions": [ { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=108&amp;s=22e0a657ec076137e6be6e27da1c3c21", "width": 108, "height": 86 }, { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=216&amp;s=db16bdfbcf20b0b3d044359d48668298", "width": 216, "height": 172 }, { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=320&amp;s=b543be8ce95b54622c7973e327ff392b", "width": 320, "height": 255 }, { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=640&amp;s=d2e4377d780d172f0606adfed76c2f04", "width": 640, "height": 511 }, { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=960&amp;s=fc84bf032f6f2f86e58fdf705755d610", "width": 960, "height": 767 }, { "url": "https://i.redditmedia.com/dGBqg3w8oRFQosKPyGhUEkKY-ETPoV6WN1uof4P1R1o.jpg?fit=crop&amp;crop=faces%2Centropy&amp;arh=2&amp;w=1080&amp;s=e6af2907b0ca084987592f307bf9d381", "width": 1080, "height": 863 } ], "variants": {}, "id": "hQ_QkpilMBrZNb5UXVWX70P0XDrv5fWy3oBESEYjzuY" } ] }, "thumbnail": "$THUMBNAIL", "subreddit_id": "t5_2qlqh", "edited": false, "link_flair_css_class": "samsung", "author_flair_css_class": null, "downs": $DOWNS, "mod_reports": [], "archived": false, "media_embed": {}, "post_hint": "link", "is_self": false, "hide_score": true, "spoiler": false, "permalink": "$LINK", "locked": false, "stickied": false, "created": 1485637324, "url": "https://twitter.com/VenyaGeskin1/status/825329388573048833", "author_flair_text": null, "quarantine": false, "title": "$TITLE", "created_utc": $CREATED, "link_flair_text": "Samsung", "distinguished": null, "num_comments": $COMMENTS, "visited": false, "num_reports": null, "ups": $UPS } """ fun makeModel(): Post { val model = Post() model.title = TITLE model.author = AUTHOR model.thumbnail = THUMBNAIL model.link = LINK model.created = CREATED model.comments = COMMENTS model.downs = DOWNS model.ups = UPS model.reference = REFERENCE return model } } object postDetailData { val JSON = """ { "modhash": "", "children": [${postDetailDataChildren.JSON}], "after": null, "before": null } """ fun makeModel(): PostDetailData { val model = PostDetailData() model.children = listOf(postDetailDataChildren.makeModel()) return model } } object postDetailDataChildren { val KIND = "t1" val JSON = """ { "kind": "$KIND", "data": ${comment.JSON} } """ fun makeModel(): PostDetailDataChildren { val model = PostDetailDataChildren() model.kind = KIND model.comment = comment.makeModel() return model } } object postDetailDataReply { val JSON = """ { "kind": "t1", "data": ${postDetailData.JSON} } """ fun makeModel(): PostDetailDataReply { val model = PostDetailDataReply() model.data = postDetailData.makeModel() return model } } object postDetailResponse { val JSON = """ { "kind": "Listing", "data": ${postDetailData.JSON} } """ val SERVICE_JSON = """ [ { "kind": "Listing", "data": { "modhash": "", "children": [ { "kind": "t3", "data": { "contest_mode": false, "banned_by": null, "media_embed": {}, "subreddit": "Android", "selftext_html": null, "selftext": "", "likes": null, "suggested_sort": null, "user_reports": [], "secure_media": null, "saved": false, "id": "5s1dkg", "gilded": 0, "secure_media_embed": {}, "clicked": false, "report_reasons": null, "author": "shivamchatak", "media": null, "score": 26, "approved_by": null, "over_18": false, "domain": "forums.crackberry.com", "hidden": false, "num_comments": 3, "thumbnail": "default", "subreddit_id": "t5_2qlqh", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 0, "archived": false, "removal_reason": null, "stickied": false, "is_self": false, "hide_score": false, "spoiler": false, "permalink": "/r/Android/comments/5s1dkg/blackberry_priv_starts_getting_february_security/", "locked": false, "name": "t3_5s1dkg", "created": 1486253188, "url": "http://forums.crackberry.com/blackberry-priv-f440/february-5th-2017-security-patch-available-1098992/", "author_flair_text": null, "quarantine": false, "title": "BlackBerry Priv starts getting February security update (February 5, 2017)", "created_utc": 1486224388, "link_flair_text": null, "ups": 26, "upvote_ratio": 0.85, "mod_reports": [], "visited": false, "num_reports": null, "distinguished": null } } ], "after": null, "before": null } }, $JSON ] """ fun makeModel(): PostDetailResponse { val model = PostDetailResponse() model.data = postDetailData.makeModel() return model } } object postResponse { val JSON = """ { "kind": "Listing", "data": ${data.JSON} } """ fun makeModel(): PostResponse { val model = PostResponse() model.data = data.makeModel() return model } } }
mit
78fbf94675f8661b7690791ff51ca100
28.939614
197
0.445099
3.902708
false
false
false
false
soniccat/android-taskmanager
taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/ui/TaskManagerView.kt
1
4825
package com.example.alexeyglushkov.taskmanager.ui import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.widget.LinearLayout import android.widget.TextView import com.example.alexeyglushkov.taskmanager.R import com.example.alexeyglushkov.taskmanager.snapshot.SimpleTaskManagerSnapshot import com.example.alexeyglushkov.taskmanager.snapshot.TaskManagerSnapshot import java.util.Arrays import java.util.HashSet /** * Created by alexeyglushkov on 06.01.15. */ class TaskManagerView : LinearLayout { private var snapshot: TaskManagerSnapshot = SimpleTaskManagerSnapshot() private lateinit var barView: TaskBarView private lateinit var loadingTasks: TextView private lateinit var waitingTasks: TextView private lateinit var blockedTasks: TextView private var colors = mutableListOf<Int>() private var allTypes = listOf<Int>() constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {} override fun onFinishInflate() { super.onFinishInflate() colors.addAll(Arrays.asList(Color.CYAN, Color.GREEN, Color.BLUE, Color.MAGENTA)) barView = findViewById(R.id.bar) loadingTasks = findViewById(R.id.loading) waitingTasks = findViewById(R.id.waiting) blockedTasks = findViewById(R.id.blocked) } fun showSnapshot(snapshot: TaskManagerSnapshot) { this.snapshot = snapshot updateAllTypesArray() updateLoadingTasks() updateWaitingTasks() updateBlockedTasks() updateBar() } internal fun updateLoadingTasks() { val str = StringBuilder() str.append("Loading: ") str.append(snapshot.loadingTasksCount.toString() + " ") val loadingTaskInfo = snapshot.usedLoadingSpace var count: Int for (type in allTypes) { count = loadingTaskInfo.get(type, 0) str.append("$count ") } loadingTasks.text = str } internal fun updateWaitingTasks() { val str = StringBuilder() str.append("Waiting: ") str.append(snapshot.waitingTasksCount.toString() + " ") val waitingTaskInfo = snapshot.waitingTaskInfo var count: Int for (type in allTypes) { count = waitingTaskInfo.get(type, 0) str.append("$count ") } waitingTasks.text = str } internal fun updateBlockedTasks() { val str = StringBuilder() str.append("Blocked: ") str.append(snapshot.blockedTasksCount.toString() + " ") val blockedTaskInfo = snapshot.blockedTaskInfo var count: Int for (type in allTypes) { count = blockedTaskInfo.get(type, 0) str.append("$count ") } blockedTasks.text = str } internal fun updateBar() { val maxQueueSize = snapshot.maxQueueSize val loadingSpace = snapshot.usedLoadingSpace val loadingLimits = snapshot.loadingLimits barView.clearItems() var count: Int var usedSpace: Float var reachedLimit = false for (type in allTypes) { count = loadingSpace.get(type, 0) usedSpace = count.toFloat() / maxQueueSize.toFloat() reachedLimit = false if (loadingLimits.get(type, -1.0f) != -1.0f) { reachedLimit = usedSpace >= snapshot.loadingLimits.get(type, 0.0f) } val item = TaskBarView.TaskBarItem(type, count.toFloat() / maxQueueSize.toFloat(), getColor(type), reachedLimit) barView.addItem(item) } } private fun getColor(index: Int): Int { return if (index < colors.size) { colors[index] } else { Color.BLACK } } private fun updateAllTypesArray() { val allTypesSet = HashSet<Int>() val loadingTaskInfo = snapshot.usedLoadingSpace val loadingLimits = snapshot.loadingLimits val waitingTaskInfo = snapshot.waitingTaskInfo //fill types array var type: Int for (i in 0 until loadingTaskInfo.size()) { type = loadingTaskInfo.keyAt(i) allTypesSet.add(type) } for (i in 0 until loadingLimits.size()) { type = loadingLimits.keyAt(i) allTypesSet.add(type) } for (i in 0 until waitingTaskInfo.size()) { type = waitingTaskInfo.keyAt(i) allTypesSet.add(type) } val allTypesArray = allTypesSet.toTypedArray() Arrays.sort(allTypesArray) allTypes = listOf(*allTypesArray) } }
mit
326d66338c45099036826ae044e1e31c
29.345912
124
0.636062
4.582146
false
false
false
false
alpha-cross/ararat
library/src/main/java/org/akop/ararat/io/UClickFormatter.kt
2
4616
// Copyright (c) Akop Karapetyan // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package org.akop.ararat.io import org.akop.ararat.core.Crossword import org.akop.ararat.core.buildWord import org.xmlpull.v1.XmlPullParser import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.net.URLDecoder import java.util.regex.Pattern class UClickFormatter : SimpleXmlParser(), CrosswordFormatter { private var builder: Crossword.Builder? = null override fun setEncoding(encoding: String) { /* Stub */ } @Throws(IOException::class) override fun read(builder: Crossword.Builder, inputStream: InputStream) { this.builder = builder parseXml(inputStream) } @Throws(IOException::class) override fun write(crossword: Crossword, outputStream: OutputStream) { throw UnsupportedOperationException("Writing not supported") } override fun canRead(): Boolean = true override fun canWrite(): Boolean = false override fun onStartElement(path: SimpleXmlParser.SimpleXmlPath, parser: XmlPullParser) { super.onStartElement(path, parser) if (path.startsWith("crossword")) { when { path.startsWith("Title") -> builder!!.title = parser.urlDecodedValue("v") path.startsWith("Author") -> builder!!.author = parser.urlDecodedValue("v") path.startsWith("Copyright") -> builder!!.copyright = parser.urlDecodedValue("v") path.startsWith("Width") -> builder!!.setWidth(parser.intValue("v", -1)) path.startsWith("Height") -> builder!!.setHeight(parser.intValue("v", -1)) path.startsWith("across", "?") || path.startsWith("down", "?") -> builder!!.words += parseWord(parser) } } } private fun XmlPullParser.urlDecodedValue(name: String): String? = stringValue(name)?.safeUrlDecode() private fun String.safeUrlDecode(): String? { val encoded = buildString { var start = 0 val m = PERCENT_MATCHER.matcher(this@safeUrlDecode) while (m.find()) { append(this@safeUrlDecode, start, m.start()) append("%25") start = m.end() } append(this@safeUrlDecode, start, [email protected]) } return URLDecoder.decode(encoded, "UTF-8") } private fun parseWord(parser: XmlPullParser): Crossword.Word { val direction = when { parser.name.startsWith("a") -> Crossword.Word.DIR_ACROSS parser.name.startsWith("d") -> Crossword.Word.DIR_DOWN else -> throw FormatException("Unexpected word indicator: ${parser.name}") } val number = parser.intValue("cn", 0) if (number < 1) throw FormatException("Number '${parser.stringValue("cn")}' not valid") val answer = parser.stringValue("a")!! val cellIndex = parser.intValue("n", 0) - 1 return buildWord { this.direction = direction this.number = number startRow = cellIndex / builder!!.width startColumn = cellIndex % builder!!.width hint = parser.urlDecodedValue("c") answer.toCharArray().forEach { addCell(it) } } } companion object { // Matches %'s that aren't URL encoded private val PERCENT_MATCHER = Pattern.compile("%(?![0-9A-Fa-f]{2})") } }
mit
447b3f63053ce8a646d14af095cd799e
36.528455
95
0.637782
4.639196
false
false
false
false
nemerosa/ontrack
ontrack-extension-license/src/main/java/net/nemerosa/ontrack/extension/license/control/LicenseControlListener.kt
1
1198
package net.nemerosa.ontrack.extension.license.control import net.nemerosa.ontrack.extension.license.LicenseService import net.nemerosa.ontrack.model.events.Event import net.nemerosa.ontrack.model.events.EventFactory import net.nemerosa.ontrack.model.events.EventListener import org.springframework.stereotype.Component @Component class LicenseControlListener( private val licenseService: LicenseService, private val licenseControlService: LicenseControlService, ) : EventListener { override fun onEvent(event: Event) { if (event.eventType == EventFactory.NEW_PROJECT) { val license = licenseService.license val control = licenseControlService.control(license) if (license != null && !control.valid) { if (!control.active) { throw LicenseInactiveException(license) } if (control.expiration == LicenseExpiration.EXPIRED) { throw LicenseExpiredException(license) } if (control.projectCountExceeded) { throw LicenseMaxProjectExceededException(license) } } } } }
mit
8d975dba20e1e54aa692427ecb45eb23
35.333333
70
0.659432
5.033613
false
false
false
false
NyaaPantsu/NyaaPantsu-android-app
app/src/main/java/cat/pantsu/nyaapantsu/ui/fragment/UploadFragment.kt
1
14090
package cat.pantsu.nyaapantsu.ui.fragment import android.Manifest import android.app.Activity import android.app.Fragment import android.content.ContentResolver import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.util.Log import android.view.* import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.ImageButton import android.widget.TextView import cat.pantsu.nyaapantsu.R import cat.pantsu.nyaapantsu.model.FlagChip import cat.pantsu.nyaapantsu.model.User import cat.pantsu.nyaapantsu.ui.activity.TorrentActivity import com.github.kittinunf.fuel.core.FuelManager import com.nononsenseapps.filepicker.FilePickerActivity import com.nononsenseapps.filepicker.Utils import com.pchmn.materialchips.ChipsInput import com.pchmn.materialchips.model.ChipInterface import kotlinx.android.synthetic.main.app_bar_home.* import kotlinx.android.synthetic.main.fragment_upload.* import net.gotev.uploadservice.* import org.jetbrains.anko.find import org.jetbrains.anko.startActivity import org.jetbrains.anko.startActivityForResult import org.jetbrains.anko.toast import org.json.JSONObject import java.io.File class UploadFragment : Fragment() { private var mListener: OnFragmentInteractionListener? = null val categories = arrayOf("_", "3_", "3_12", "3_5", "3_13", "3_6", "2_", "2_3", "2_4", "4_", "4_7", "4_14", "4_8", "5_", "5_9", "5_10", "5_18", "5_11", "6_", "6_15", "6_16", "1_", "1_1", "1_2") val languages = arrayOf("ca", "zh", "zh-Hant", "nl", "en", "fr", "de", "hu", "is", "it", "ja", "ko", "nb", "pt", "ro", "es", "sv", "th") var c = "" var lang = "" var selectedTorrent: File? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val closeButton = activity.toolbar.find<ImageButton>(R.id.buttonClose) closeButton.visibility = View.GONE activity.fab.visibility = View.GONE activity.title = "Upload a torrent - NyaaPantsu" // Inflate the layout for this fragment return inflater!!.inflate(R.layout.fragment_upload, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val uploadTypeAdapter = ArrayAdapter.createFromResource(activity, R.array.upload_type_array, R.layout.spinner_layout) val catAdapter = ArrayAdapter.createFromResource(activity, R.array.cat_array, R.layout.spinner_layout) upload_type_spinner.adapter = uploadTypeAdapter categorySpin.adapter = catAdapter upload_type_spinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { switchUploadType(uploadTypeAdapter.getItem(p2) as String) } override fun onNothingSelected(p0: AdapterView<*>?) { } } categorySpin.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { c = categories[p2] } override fun onNothingSelected(p0: AdapterView<*>?) { c = "_" } } if (User.id > 0) { anonSwitch.visibility = View.VISIBLE } choose_text.setOnClickListener { _ -> if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { startActivityForResult<FilePickerActivity>(FILE_CODE, FilePickerActivity.EXTRA_ALLOW_MULTIPLE to false, FilePickerActivity.EXTRA_MODE to FilePickerActivity.MODE_FILE) } else { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 10) } } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { super.onCreateOptionsMenu(menu, inflater) inflater?.inflate(R.menu.menu_done, menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { R.id.menu_done -> { if (valideForm()) { upload(activity) } return true } else -> { return super.onOptionsItemSelected(item) } } } fun switchUploadType(type: String) { val arr = resources.getStringArray(R.array.upload_type_array) when (type) { arr[0] -> { magnet_edit.visibility = View.GONE choose_text.visibility = View.VISIBLE magnet_edit.text = null } arr[1] -> { choose_text.visibility = View.GONE magnet_edit.visibility = View.VISIBLE selectedTorrent = null choose_text.setText(R.string.choose) } } langsInput.addChipsListener(object: ChipsInput.ChipsListener { override fun onChipAdded(chip: ChipInterface, newSize:Int) { val langs = lang.split(";").toMutableList() langs.add(chip.info) lang = langs.joinToString(";") } override fun onChipRemoved(chip:ChipInterface, newSize:Int) { val langs = lang.split(";").toMutableList() langs.remove(chip.info) lang = langs.joinToString(";") } override fun onTextChanged(text:CharSequence) { // Do nothing } }) val langTranslation = resources.getStringArray(R.array.language_array) val flagList: ArrayList<FlagChip> = ArrayList() for ((index, lg) in languages.withIndex()) { val flagCode = lg.replace("-", "_").toLowerCase() if (resources.getIdentifier("flag_"+flagCode, "drawable", activity.packageName) > 0) { val uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + activity.packageName + "/drawable/flag_" + flagCode) flagList.add(FlagChip(index.toString(), uri, langTranslation[index], lg)) } } langsInput.filterableList = flagList } fun valideForm(): Boolean { choose_text.error = null magnet_edit.error = null name_edit.error = null (categorySpin.selectedView as TextView).error =null if (name_edit.text.isEmpty()) { name_edit.error = getString(R.string.name_required) return false } if (c == "") { (categorySpin.selectedView as TextView).error = getString(R.string.category_required) return false } if (selectedTorrent == null && magnet_edit.text.isEmpty()) { choose_text.error = getString(R.string.file_required) magnet_edit.error = getString(R.string.file_required) return false } if (lang == "") { toast(getString(R.string.lang_next_time)) } return true } fun upload(context: Context) { try { errorText.visibility = View.GONE val notificationConfig = UploadNotificationConfig() .setTitle(getString(R.string.nyaapantsu)) .setInProgressMessage(getString(R.string.upload_progress)) .setErrorMessage(getString(R.string.upload_error)) .setCompletedMessage(getString(R.string.upload_done)) MultipartUploadRequest(context, (FuelManager.instance.basePath+"/upload")) // starting from 3.1+, you can also use content:// URI string instead of absolute file .addFileToUpload(selectedTorrent?.absolutePath, "torrent") .setUtf8Charset() .addHeader("Authorization", User.token) .addParameter("username", User.name) .addParameter("name", name_edit.text.toString()) .addParameter("magnet", magnet_edit.text.toString()) .addParameter("c", c) .addParameter("remake", remakeSwitch.isChecked.toString()) .addParameter("hidden", anonSwitch.isChecked.toString()) .addArrayParameter("language", lang.split(";").toMutableList()) .addParameter("website_link", website_edit.text.toString()) .addParameter("desc", desc_edit.text.toString()) .setNotificationConfig(notificationConfig) .setMaxRetries(2) .setDelegate(object : UploadStatusDelegate { override fun onProgress(context: Context, uploadInfo: UploadInfo) { Log.d("DebugUpload", uploadInfo.toString()) } override fun onError(context: Context, uploadInfo: UploadInfo, exception: Exception) { toast(getString(R.string.try_error)) } override fun onCompleted(context: Context, uploadInfo: UploadInfo, serverResponse: ServerResponse) { // your code here // if you have mapped your server response to a POJO, you can easily get it: // YourClass obj = new Gson().fromJson(serverResponse.getBodyAsString(), YourClass.class); val json = JSONObject(serverResponse.bodyAsString) if (json.getBoolean("ok")) { startActivity<TorrentActivity>("torrent" to json.getJSONObject("data").toString(), "type" to "upload") } else { val allErrors = json.optJSONObject("all_errors") val errors = allErrors?.optJSONArray("errors") if (errors != null) { errorText.text = errors.join("\n") } name_edit.error = if (allErrors?.optString("name") != "") allErrors?.optString("name") else null (categorySpin.selectedView as TextView).error = if (allErrors?.optString("category") != "") allErrors?.optString("category") else null langLabel.error = if (allErrors?.optString("language") != "") allErrors?.optString("language") else null website_edit.error = if (allErrors?.optString("website") != "") allErrors?.optString("website") else null errorText.visibility = View.VISIBLE } } override fun onCancelled(context: Context, uploadInfo: UploadInfo) { // your code here } }) .startUpload() } catch (exc: Exception) { Log.e("AndroidUploadService", exc.message, exc) } } override fun onAttach(context: Context?) { super.onAttach(context) if (context is OnFragmentInteractionListener) { mListener = context } else { throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { super.onActivityResult(requestCode, resultCode, intent) if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) { // Use the provided utility method to parse the result val files = Utils.getSelectedFilesFromResult(intent!!) for (uri in files) { val file = Utils.getFileForUri(uri) if (name_edit.text.toString() == "") { name_edit.setText(file.name) } choose_text.text = file.nameWithoutExtension name_edit.setText(file.nameWithoutExtension) selectedTorrent = file } } } fun getTorrentName(torrent: String): String { val torrentExp = torrent.split(".") if (torrentExp.size > 1) { torrentExp.dropLast(torrentExp.size-1) } return torrentExp.joinToString(".") } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information. */ interface OnFragmentInteractionListener { fun onFragmentInteraction(uri: Uri) } companion object { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER val FILE_CODE = 13 /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment UploadFragment. */ fun newInstance(): UploadFragment { val fragment = UploadFragment() return fragment } } }// Required empty public constructor
mit
e40a1861e20b9abab709166f76e362e5
41.69697
196
0.589851
4.8536
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/ide/intentions/WrapLambdaExprIntention.kt
1
1278
package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsBlockExpr import org.rust.lang.core.psi.RsExpr import org.rust.lang.core.psi.RsLambdaExpr import org.rust.lang.core.psi.RsPsiFactory import org.rust.lang.core.psi.ext.parentOfType class WrapLambdaExprIntention : RsElementBaseIntentionAction<RsExpr>() { override fun getText() = "Add braces to lambda expression" override fun getFamilyName() = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsExpr? { val lambdaExpr = element.parentOfType<RsLambdaExpr>() ?: return null val body = lambdaExpr.expr ?: return null return if (body !is RsBlockExpr) body else null } override fun invoke(project: Project, editor: Editor, ctx: RsExpr) { val relativeCaretPosition = editor.caretModel.offset - ctx.textOffset val bodyStr = "\n${ctx.text}\n" val blockExpr = RsPsiFactory(project).createBlockExpr(bodyStr) val offset = ((ctx.replace(blockExpr)) as RsBlockExpr).block.expr?.textOffset ?: return editor.caretModel.moveToOffset(offset + relativeCaretPosition) } }
mit
a283a624aff3571b615ec085e55f5b81
40.225806
104
0.742567
4.190164
false
false
false
false
ohmae/mmupnp
mmupnp/src/test/java/net/mm2d/upnp/ControlPointFactoryTest.kt
1
2660
/* * Copyright (c) 2018 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp import io.mockk.mockk import net.mm2d.upnp.util.NetworkUtils import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @Suppress("TestFunctionName", "NonAsciiCharacters") @RunWith(JUnit4::class) class ControlPointFactoryTest { @Test fun create_引数無しでコール() { ControlPointFactory.create() } @Test @Throws(Exception::class) fun create_インターフェース指定() { ControlPointFactory.create( interfaces = NetworkUtils.getAvailableInet4Interfaces() ) ControlPointFactory.create( interfaces = emptyList() ) } @Test fun create_インターフェース選別() { ControlPointFactory.create( protocol = Protocol.IP_V4_ONLY, interfaces = NetworkUtils.getNetworkInterfaceList() ) ControlPointFactory.create( protocol = Protocol.IP_V6_ONLY, interfaces = NetworkUtils.getNetworkInterfaceList() ) ControlPointFactory.create( protocol = Protocol.DUAL_STACK, interfaces = NetworkUtils.getNetworkInterfaceList() ) } @Test fun create_プロトコルスタックのみ指定() { ControlPointFactory.create( protocol = Protocol.IP_V4_ONLY ) ControlPointFactory.create( protocol = Protocol.IP_V6_ONLY ) ControlPointFactory.create( protocol = Protocol.DUAL_STACK ) } @Test fun create_executorの指定() { ControlPointFactory.create( callbackExecutor = null, callbackHandler = null ) ControlPointFactory.create( callbackExecutor = mockk(), callbackHandler = null ) ControlPointFactory.create( callbackExecutor = null, callbackHandler = mockk() ) ControlPointFactory.create( callbackExecutor = mockk(), callbackHandler = mockk() ) } @Test fun builder() { ControlPointFactory.builder() .setProtocol(Protocol.DEFAULT) .setInterfaces(NetworkUtils.getNetworkInterfaceList()) .setNotifySegmentCheckEnabled(true) .setSubscriptionEnabled(true) .setMulticastEventingEnabled(true) .setCallbackExecutor(mockk()) .setCallbackHandler { true } .build() } }
mit
f17e4380dea7fdb68fbe0ead764a5509
25.708333
67
0.605304
4.687386
false
true
false
false
soywiz/korge
korge-swf/src/commonMain/kotlin/com/soywiz/korfl/ABC.kt
1
10547
package com.soywiz.korfl import com.soywiz.kds.* import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* // http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/actionscript/articles/avm2overview.pdf // https://github.com/imcj/as3abc/blob/master/src/com/codeazur/as3abc/ABC.as class ABC { data class Namespace(val kind: Int, val name: String) { companion object { const val NAMESPACE = 0x08 const val PACKAGE_NAMESPACE = 0x16 const val PACKAGE_INTERNAL_NAMESPACE = 0x17 const val PROTECTED_NAMESPACE = 0x18 const val EXPLICIT_NAMESPACE = 0x19 const val STATIC_PROTECTED_NAMESPACE = 0x1A const val PRIVATE_NAMESPACE = 0x05 val EMPTY = Namespace(0, "") } override fun toString(): String = name } interface AbstractMultiname { val simpleName: String } object EmptyMultiname : AbstractMultiname { override val simpleName: String = "" } data class ABCQName(val namespace: Namespace, val name: String) : AbstractMultiname { override fun toString(): String = "$namespace.$name" override val simpleName: String = name } data class QNameA(val namespace: Namespace, val name: String) : AbstractMultiname { override val simpleName: String = name } data class RTQName(val name: String) : AbstractMultiname { override val simpleName: String = name } data class RTQNameA(val name: String) : AbstractMultiname { override val simpleName: String = name } object RTQNameL : AbstractMultiname { override val simpleName: String = "" } object RTQNameLA : AbstractMultiname { override val simpleName: String = "" } data class Multiname(val name: String, val namespaceSet: List<Namespace>) : AbstractMultiname { override val simpleName: String = name } data class MultinameA(val name: String, val namespaceSet: List<Namespace>) : AbstractMultiname { override val simpleName: String = name } data class MultinameL(val namespaceSet: List<Namespace>) : AbstractMultiname { override val simpleName: String = "" } data class MultinameLA(val namespaceSet: List<Namespace>) : AbstractMultiname { override val simpleName: String = "" } data class TypeName(val qname: Int, val parameters: List<Int>) : AbstractMultiname { override val simpleName: String = "TypeName($qname)" } var methodsDesc = listOf<MethodDesc>() var instancesInfo = listOf<InstanceInfo>() var classesInfo = listOf<ClassInfo>() var typesInfo = listOf<TypeInfo>() var scriptsInfo = listOf<ScriptInfo>() var methodsBodies = listOf<MethodBody>() var metadatas = listOf<Metadata>() val cpool = AbcConstantPool() val ints: List<Int> get() = cpool.ints val uints: List<Int> get() = cpool.uints val doubles: List<Double> get() = cpool.doubles val strings: List<String> get() = cpool.strings val namespaces: List<Namespace> get() = cpool.namespaces val namespaceSets: List<List<Namespace>> get() = cpool.namespaceSets val multinames: List<AbstractMultiname> get() = cpool.multinames data class Metadata(val name: String, val values: Map<String, String>) fun readFile(s: SyncStream) = this.apply { //syncTest { // s.slice().readAll().writeToFile(File("c:/temp/demo.abc")) //} val minor = s.readU16LE() val major = s.readU16LE() //println("version: major=$major, minor=$minor") cpool.readConstantPool(s) // readMethods methodsDesc = (0 until s.readU30()).map { readMethod(s) } //println("Methods: $methodsDesc") // readMetadata metadatas = (0 until s.readU30()).map { val name = strings[s.readU30()] val items = (0 until s.readU30()).map { strings[s.readU30()] to strings[s.readU30()] } Metadata(name, items.toMap()) } //println("Metadatas: $metadatas") val typeCount = s.readU30() // readInstances instancesInfo = (0 until typeCount).map { readInstance(s) } // readClasses classesInfo = (0 until typeCount).map { readClass(s) } typesInfo = instancesInfo.zip(classesInfo).map { TypeInfo(this, it.first, it.second) } //println("Classes: $classesInfo") // readScripts scriptsInfo = (0 until s.readU30()).map { ScriptInfo(methodsDesc[s.readU30()], readTraits(s)) } //println("Scripts: $scripts") // readScripts methodsBodies = (0 until s.readU30()).map { val method = methodsDesc[s.readU30()] val maxStack = s.readU30() val localCount = s.readU30() val initScopeDepth = s.readU30() val maxScopeDepth = s.readU30() val opcodes = s.readBytes(s.readU30()) val exceptions = (0 until s.readU30()).map { ExceptionInfo( from = s.readU30(), to = s.readU30(), target = s.readU30(), type = multinames[s.readU30()], variableName = multinames[s.readU30()] ) } val traits = readTraits(s) MethodBody( method = method, maxStack = maxStack, localCount = localCount, initScopeDepth = initScopeDepth, maxScopeDepth = maxScopeDepth, opcodes = opcodes, cpool = cpool, exceptions = exceptions, traits = traits ) } //println("MethodBodies: $methodBodies") //println("Available: ${s.available}") } class MethodBody( val method: MethodDesc, val maxStack: Int, val localCount: Int, val initScopeDepth: Int, val maxScopeDepth: Int, val opcodes: ByteArray, val cpool: AbcConstantPool, val exceptions: List<ExceptionInfo>, val traits: List<Trait> ) { val ops by lazy { opcodes.openSync().run { mapWhile(cond = { !this.eof }, gen = { AbcOperation.read(cpool, this) }) } } init { method.body = this } } data class ExceptionInfo( val from: Int, val to: Int, val target: Int, val type: AbstractMultiname, val variableName: AbstractMultiname ) interface Trait { val name: AbstractMultiname } data class TraitSlot( override val name: AbstractMultiname, val slotIndex: Int, val type: AbstractMultiname, val value: Any? ) : Trait data class TraitMethod(override val name: AbstractMultiname, val dispIndex: Int, val methodIndex: Int) : Trait data class TraitClass(override val name: AbstractMultiname, val slotIndex: Int, val classIndex: Int) : Trait data class TraitFunction(override val name: AbstractMultiname, val slotIndex: Int, val functionIndex: Int) : Trait data class InstanceInfo( val name: ABCQName, val base: AbstractMultiname, val interfaces: List<AbstractMultiname>, val instanceInitializer: MethodDesc, val traits: List<Trait> ) data class ClassInfo(val initializer: MethodDesc, val traits: List<Trait>) class TypeInfo(val abc: ABC, val instanceInfo: InstanceInfo, val classInfo: ClassInfo) { val name get() = instanceInfo.name val instanceTraits get() = instanceInfo.traits val classTraits get() = classInfo.traits } data class ScriptInfo(val initializer: MethodDesc, val traits: List<Trait>) fun readClass(s: SyncStream): ClassInfo { return ClassInfo(methodsDesc[s.readU30()], readTraits(s)) } fun readInstance(s: SyncStream): InstanceInfo { val name = multinames[s.readU30()] as ABCQName val base = multinames[s.readU30()] val flags = s.readU8() val isSealed = (flags and 0x01) != 0 val isFinal = (flags and 0x02) != 0 val isInterface = (flags and 0x04) != 0 if ((flags and 0x08) != 0) { val protectedNamespace = namespaces[s.readU30()] } val interfaces = (0 until s.readU30()).map { multinames[s.readU30()] } val instanceInitializerIndex = s.readU30() val traits = readTraits(s) return InstanceInfo( name = name, base = base, interfaces = interfaces, instanceInitializer = methodsDesc[instanceInitializerIndex], traits = traits ) } fun getConstantValue(type: Int, index: Int): Any? = when (type) { 0x03 /* int */ -> ints[index] 0x04 /* uint */ -> uints[index] 0x06 /* double */ -> doubles[index] 0x01 /* UTF-8 */ -> strings[index] 0x0B /* true */ -> true 0x0A /* false */ -> false 0x0C /* null */, 0x00 /* undefined */ -> null 0x08 /* namespace */, 0x16 /* package namespace */, 0x17 /* package internal namespace */, 0x18 /* protected namespace */, 0x19 /* explicit namespace */, 0x1A /* static protected namespace */, 0x05 /* private namespace */ -> namespaces[index] else -> invalidOp("Unknown parameter type.") } fun readTraits(s: SyncStream): List<Trait> { return (0 until s.readU30()).map { val name = multinames[s.readU30()] val kind = s.readU8() val info = kind ushr 4 val hasMetadata = (info and 0x04) != 0 val traitKind = kind and 0x0f fun handleTraitSlot() = run { val slotIndex = s.readU30() val type = multinames[s.readU30()] val valueIndex = s.readU30() val value = if (valueIndex != 0) { val valueKind = s.readU8() getConstantValue(valueKind, valueIndex) } else { null } TraitSlot(name, slotIndex, type, value) } fun handleTraitMethod() = run { val dispIndex = s.readU30() val methodIndex = s.readU30() val isFinal = (info and 0x01) != 0 val isOverride = (info and 0x02) != 0 TraitMethod(name, dispIndex, methodIndex) } val trait: Trait = when (traitKind) { 0x00 -> handleTraitSlot() 0x06 -> handleTraitSlot() 0x01 -> handleTraitMethod() 0x02 -> handleTraitMethod() 0x03 -> handleTraitMethod() 0x04 -> TraitClass(name, s.readU30(), s.readU30()) 0x05 -> TraitFunction(name, s.readU30(), s.readU30()) else -> invalidOp("Unknown trait kind $traitKind") } if (hasMetadata) { val metadatas = (0 until s.readU30()).map { metadatas[s.readU30()] } } trait } } data class MethodDesc(val name: String) { var body: MethodBody? = null } fun readMethod(s: SyncStream): MethodDesc { val parameterCount = s.readU30() val returnType = multinames[s.readU30()] val parameters = (0 until parameterCount).map { multinames[s.readU30()] } val name = strings[s.readU30()] val flags = s.readU8() val needsArguments = (flags and 0x01) != 0 val needsActivation = (flags and 0x02) != 0 val needsRest = (flags and 0x04) != 0 val hasOptionalParameters = (flags and 0x08) != 0 val setsDXNS = (flags and 0x40) != 0 val hasParameterNames = (flags and 0x80) != 0 if (hasOptionalParameters) { val optionalCount = s.readU8() val optionalValues = (0 until optionalCount).map { val valueIndex = s.readU30() val optionalType = s.readU8() val value = getConstantValue(optionalType, valueIndex) } } if (hasParameterNames) { val parameterNames = (0 until parameterCount).map { strings[s.readU30()] } } //println("$name($parameters):$returnType") //TODO() return MethodDesc(name) } }
apache-2.0
59ec0296c36c736548c89bdad9e1c82c
26.18299
109
0.681616
3.227356
false
false
false
false
soywiz/korge
korge-swf/src/commonMain/kotlin/com/soywiz/korfl/AMF0.kt
1
1366
package com.soywiz.korfl import com.soywiz.klock.* import com.soywiz.korio.lang.* import com.soywiz.korio.stream.* object AMF0 { fun decode(s: SyncStream): Any? { //val chunk = s.sliceWithStart(s.position).readBytes(120) //println(chunk.toHexString()) //println(chunk.toString(Charsets.UTF_8)) return Reader(s).read() } class Reader(val i: SyncStream) { fun readObject(): Map<String, Any?> { val h = hashMapOf<String, Any?>() while (true) { val len = i.readU16BE() val name = i.readString(len) val k = i.readU8() if (k == 0x09) break h[name] = readWithCode(k) } return h } fun readWithCode(id: Int): Any? = when (id) { 0x00 -> i.readF64BE() 0x01 -> when (i.readU8()) { 0 -> false 1 -> true else -> error("Invalid AMF") } 0x02 -> i.readStringz(i.readU16BE()) 0x03 -> readObject() 0x08 -> { var size = i.readS32BE() TODO() readObject() } 0x05 -> null 0x06 -> Undefined 0x07 -> error("Not supported : Reference") 0x0A -> { val count = i.readS32BE() (0 until count).map { read() } } 0x0B -> { val time_ms = i.readF64BE() val tz_min = i.readU16BE() DateTime(time_ms.toLong() + tz_min * 60 * 1000L) } 0x0C -> i.readString(i.readS32BE()) else -> error("Unknown AMF $id") } fun read(): Any? = readWithCode(i.readU8()) } }
apache-2.0
2761f88da96a9922e5d4bac52f80a9af
21.393443
59
0.591508
2.637066
false
false
false
false
icapps/niddler-ui
client-lib/src/main/kotlin/com/icapps/niddler/lib/model/NiddlerMessageBodyParser.kt
1
3307
package com.icapps.niddler.lib.model import com.icapps.niddler.lib.connection.model.NiddlerMessage import com.icapps.niddler.lib.model.classifier.BodyFormatType import com.icapps.niddler.lib.model.classifier.BodyParser import com.icapps.niddler.lib.model.classifier.ConcreteBody import com.icapps.niddler.lib.model.classifier.SimpleBodyClassifier import com.icapps.niddler.lib.utils.error import com.icapps.niddler.lib.utils.logger /** * @author Nicola Verbeeck * @date 15/11/16. */ class NiddlerMessageBodyParser(private val classifier: SimpleBodyClassifier) { companion object { private val log = logger<NiddlerMessageBodyParser>() } fun parseBody(message: NiddlerMessage): ParsedNiddlerMessage { return parseBodyInternal(message)!! } private fun parseBodyInternal(message: NiddlerMessage?): ParsedNiddlerMessage? { if (message == null) return null try { return parseMessage(message) } catch (e: Throwable) { log.error("Message parse failure: ", e) return ParsedNiddlerMessage( bodyFormat = BodyFormat( type = BodyFormatType.FORMAT_BINARY, subtype = null, encoding = null), bodyData = message.getBodyAsBytes, message = message, parsedNetworkRequest = parseBodyInternal(message.networkRequest), parsedNetworkReply = parseBodyInternal(message.networkReply)) } } private fun parseBodyWithType(message: NiddlerMessage, content: ConcreteBody?): ParsedNiddlerMessage { return ParsedNiddlerMessage(message, asFormat(content), content?.data, parseBodyInternal(message.networkRequest), parseBodyInternal(message.networkReply)) } private fun parseMessage(message: NiddlerMessage): ParsedNiddlerMessage { val contentType = classifyFormatFromHeaders(message) if (contentType != null) { return parseBodyWithType(message, contentType) } if (message.body.isNullOrEmpty()) { return ParsedNiddlerMessage(message, BodyFormat.NONE, null, parseBodyInternal(message.networkRequest), parseBodyInternal(message.networkReply)) } return ParsedNiddlerMessage(message, BodyFormat.UNKNOWN, message.getBodyAsBytes, parseBodyInternal(message.networkRequest), parseBodyInternal(message.networkReply)) } private fun classifyFormatFromHeaders(message: NiddlerMessage): ConcreteBody? { return BodyParser(classifier.classifyFormat(message), message.getBodyAsBytes).determineBodyType() } private fun asFormat(content: ConcreteBody?): BodyFormat { content?.let { return BodyFormat(it.type, it.rawType, null) } return BodyFormat.UNKNOWN } } data class BodyFormat(val type: BodyFormatType, val subtype: String?, val encoding: String?) { companion object { val NONE = BodyFormat(BodyFormatType.FORMAT_EMPTY, null, null) val UNKNOWN = BodyFormat(BodyFormatType.FORMAT_BINARY, null, null) } override fun toString(): String { return type.verbose } }
apache-2.0
224b62be1c3d0f832d1ff2003800fc84
37.905882
106
0.669187
4.870398
false
false
false
false
chromeos/vulkanphotobooth
app/src/main/java/dev/hadrosaur/vulkanphotobooth/cameracontroller/Camera2CaptureCallback.kt
1
3101
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.hadrosaur.vulkanphotobooth.cameracontroller import android.hardware.camera2.* import android.view.Surface import dev.hadrosaur.vulkanphotobooth.CameraParams import dev.hadrosaur.vulkanphotobooth.MainActivity /** * Image capture callback for Camera 2 API. Tracks state of an image capture request. */ class Camera2CaptureCallback( internal val activity: MainActivity, internal val params: CameraParams ) : CameraCaptureSession.CaptureCallback() { override fun onCaptureSequenceAborted(session: CameraCaptureSession, sequenceId: Int) { if (session != null) super.onCaptureSequenceAborted(session, sequenceId) } override fun onCaptureFailed( session: CameraCaptureSession, request: CaptureRequest, failure: CaptureFailure ) { if (!params.isOpen) { return } MainActivity.logd("captureStillPicture captureCallback: Capture Failed. Failure: " + failure?.reason) // The session failed. Let's just try again (yay infinite loops) camera2CloseCamera(params) camera2OpenCamera(activity, params) if (session != null && request != null && failure != null) super.onCaptureFailed(session, request, failure) } override fun onCaptureStarted( session: CameraCaptureSession, request: CaptureRequest, timestamp: Long, frameNumber: Long ) { if (session != null && request != null) super.onCaptureStarted(session, request, timestamp, frameNumber) } override fun onCaptureProgressed( session: CameraCaptureSession, request: CaptureRequest, partialResult: CaptureResult ) { if (session != null && request != null && partialResult != null) super.onCaptureProgressed(session, request, partialResult) } override fun onCaptureBufferLost( session: CameraCaptureSession, request: CaptureRequest, target: Surface, frameNumber: Long ) { MainActivity.logd("captureStillPicture captureCallback: Buffer lost") if (session != null && request != null && target != null) super.onCaptureBufferLost(session, request, target, frameNumber) } override fun onCaptureCompleted( session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult ) { if (!params.isOpen) { return } } }
apache-2.0
4a42c9a1006e3fcffb3898b99242de80
30.653061
92
0.673331
4.837754
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/FamilyFolderActivity.kt
1
3367
/* * Copyright (c) 2019 NECTEC * National Electronics and Computer Technology Center, Thailand * * 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 ffc.app import android.annotation.SuppressLint import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Bundle import android.support.annotation.LayoutRes import android.support.design.widget.Snackbar import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.View import ffc.android.connectivityManager import ffc.android.onClick import ffc.app.auth.auth import ffc.entity.Organization import ffc.entity.User import org.jetbrains.anko.contentView import org.jetbrains.anko.design.indefiniteSnackbar @SuppressLint("Registered") open class FamilyFolderActivity : AppCompatActivity() { var offlineSnackbar: Snackbar? = null var isOnline = false private set(value) { field = value onConnectivityChanged(field) } val org: Organization? get() = auth(this).org ?: devOrg val currentUser: User? get() = auth(this).user ?: devUser private val devOrg = if (isDev) Organization() else null private val devUser = if (isDev) User().apply { orgId = devOrg?.id } else null protected var savedInstanceState: Bundle? = null private val connectivityChange by lazy { ConnectivityChangeReceiver { isOnline = it } } override fun setContentView(@LayoutRes layoutResID: Int) { super.setContentView(layoutResID) setupToolbar() } private fun setupToolbar() { val toolbar = findViewById<View>(R.id.toolbar) if (toolbar != null && toolbar is Toolbar) { setSupportActionBar(toolbar) } } fun onToolbarClick(block: (Toolbar) -> Unit) { findViewById<Toolbar>(R.id.toolbar).onClick(block) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) isOnline = connectivityManager.isConnected this.savedInstanceState = savedInstanceState } override fun onResume() { super.onResume() registerReceiver(connectivityChange, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) } override fun onPause() { super.onPause() unregisterReceiver(connectivityChange) } protected open fun onConnectivityChanged( isConnect: Boolean, message: String = getString(R.string.you_offline) ) { if (isConnect) { offlineSnackbar?.dismiss() } else { contentView?.let { offlineSnackbar = indefiniteSnackbar(it, message) } } } } val Fragment.familyFolderActivity: FamilyFolderActivity get() = activity as FamilyFolderActivity
apache-2.0
89b8653493c98a7449cf70f039c1fb86
31.066667
99
0.703297
4.644138
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/data/timetable/TimegridItem.kt
1
2480
package com.sapuseven.untis.data.timetable import com.sapuseven.untis.helpers.timetable.TimetableDatabaseInterface import com.sapuseven.untis.views.weekview.WeekViewEvent import org.joda.time.DateTime class TimegridItem( id: Long, val startDateTime: DateTime, val endDateTime: DateTime, contextType: String, val periodData: PeriodData, includeOrgIds: Boolean = true ) : WeekViewEvent<TimegridItem>(id, startTime = startDateTime, endTime = endDateTime) { init { periodData.setup() title = periodData.getShort(periodData.subjects, TimetableDatabaseInterface.Type.SUBJECT) top = if (contextType == TimetableDatabaseInterface.Type.TEACHER.name) periodData.getShortSpanned(periodData.classes, TimetableDatabaseInterface.Type.CLASS, includeOrgIds) else periodData.getShortSpanned(periodData.teachers, TimetableDatabaseInterface.Type.TEACHER, includeOrgIds) bottom = if (contextType == TimetableDatabaseInterface.Type.ROOM.name) periodData.getShortSpanned(periodData.classes, TimetableDatabaseInterface.Type.CLASS, includeOrgIds) else periodData.getShortSpanned(periodData.rooms, TimetableDatabaseInterface.Type.ROOM, includeOrgIds) hasIndicator = !periodData.element.homeWorks.isNullOrEmpty() || periodData.element.text.lesson.isNotEmpty() || periodData.element.text.substitution.isNotEmpty() || periodData.element.text.info.isNotEmpty() } override fun toWeekViewEvent(): WeekViewEvent<TimegridItem> { return WeekViewEvent(id, title, top, bottom, startTime, endTime, color, pastColor, this, hasIndicator) } fun mergeWith(items: MutableList<TimegridItem>): Boolean { items.toList().forEachIndexed { i, _ -> if (i >= items.size) return@forEachIndexed // Needed because the number of elements can change val candidate = items[i] if (candidate.startTime.dayOfYear != startTime.dayOfYear) return@forEachIndexed if (this.equalsIgnoreTime(candidate)) { endTime = candidate.endTime periodData.element.endDateTime = candidate.periodData.element.endDateTime items.removeAt(i) return true } } return false } fun mergeValuesWith(item: TimegridItem) { periodData.apply { classes.addAll(item.periodData.classes) teachers.addAll(item.periodData.teachers) subjects.addAll(item.periodData.subjects) rooms.addAll(item.periodData.rooms) } } fun equalsIgnoreTime(secondItem: TimegridItem) = periodData.element.equalsIgnoreTime(secondItem.periodData.element) }
gpl-3.0
4f590eac96f8119ece84091239657fa9
34.942029
116
0.775806
3.746224
false
false
false
false
pyamsoft/padlock
padlock/src/main/java/com/pyamsoft/padlock/service/pause/PauseConfirmActivity.kt
1
3652
/* * Copyright 2019 Peter Kenji Yamanaka * * 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.pyamsoft.padlock.service.pause import android.content.Context import android.content.Intent import android.os.Bundle import androidx.constraintlayout.widget.ConstraintLayout import com.pyamsoft.padlock.Injector import com.pyamsoft.padlock.PadLockComponent import com.pyamsoft.padlock.R import com.pyamsoft.padlock.pin.ConfirmPinPresenter import com.pyamsoft.padlock.pin.confirm.PinConfirmDialog import com.pyamsoft.padlock.service.ServiceActionPresenter import com.pyamsoft.pydroid.ui.app.ActivityBase import com.pyamsoft.pydroid.ui.theme.ThemeInjector import com.pyamsoft.pydroid.ui.util.show import timber.log.Timber import javax.inject.Inject class PauseConfirmActivity : ActivityBase(), ConfirmPinPresenter.Callback { @field:Inject internal lateinit var confirmPinPresenter: ConfirmPinPresenter @field:Inject internal lateinit var actionPresenter: ServiceActionPresenter override val fragmentContainerId: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { overridePendingTransition(0, 0) if (ThemeInjector.obtain(applicationContext).isDarkTheme()) { setTheme(R.style.Theme_PadLock_Dark_Transparent) } else { setTheme(R.style.Theme_PadLock_Light_Transparent) } super.onCreate(savedInstanceState) setContentView(R.layout.layout_constraint) val layoutRoot = findViewById<ConstraintLayout>(R.id.layout_constraint) Injector.obtain<PadLockComponent>(application) .plusPinComponent() .owner(this) .parent(layoutRoot) .build() .inject(this) confirmPinPresenter.bind(this) PinConfirmDialog.newInstance(finishOnDismiss = true) .show(this, PinConfirmDialog.TAG) } override fun onConfirmPinBegin() { } override fun onConfirmPinSuccess( attempt: String, checkOnly: Boolean ) { if (checkOnly) { Timber.d("Pin check succeeds!") val autoResume = intent.getBooleanExtra(EXTRA_AUTO_RESUME, false) Timber.d("Pausing service with auto resume: $autoResume") actionPresenter.requestPause(autoResume) finish() } } override fun onConfirmPinFailure( attempt: String, checkOnly: Boolean ) { } override fun onConfirmPinComplete() { } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Timber.d("New intent received: $intent") setIntent(intent) } override fun finish() { super.finish() overridePendingTransition(0, 0) } override fun onDestroy() { super.onDestroy() overridePendingTransition(0, 0) confirmPinPresenter.unbind() } companion object { private const val EXTRA_AUTO_RESUME = "extra_auto_resume" @JvmStatic fun start( context: Context, autoResume: Boolean ) { val appContext = context.applicationContext val intent = Intent(appContext, PauseConfirmActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK putExtra(EXTRA_AUTO_RESUME, autoResume) } appContext.startActivity(intent) } } }
apache-2.0
f38af6034c14dc1a9ccb6b1f1dc97937
27.984127
79
0.732749
4.271345
false
false
false
false
rwinch/spring-security
config/src/main/kotlin/org/springframework/security/config/web/server/ServerHeadersDsl.kt
2
10796
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.server import org.springframework.security.web.server.header.CacheControlServerHttpHeadersWriter import org.springframework.security.web.server.header.ContentTypeOptionsServerHttpHeadersWriter import org.springframework.security.web.server.header.ReferrerPolicyServerHttpHeadersWriter import org.springframework.security.web.server.header.StrictTransportSecurityServerHttpHeadersWriter import org.springframework.security.web.server.header.XFrameOptionsServerHttpHeadersWriter import org.springframework.security.web.server.header.XXssProtectionServerHttpHeadersWriter /** * A Kotlin DSL to configure [ServerHttpSecurity] headers using idiomatic Kotlin code. * * @author Eleftheria Stein * @since 5.4 */ @ServerSecurityMarker class ServerHeadersDsl { private var contentTypeOptions: ((ServerHttpSecurity.HeaderSpec.ContentTypeOptionsSpec) -> Unit)? = null private var xssProtection: ((ServerHttpSecurity.HeaderSpec.XssProtectionSpec) -> Unit)? = null private var cacheControl: ((ServerHttpSecurity.HeaderSpec.CacheSpec) -> Unit)? = null private var hsts: ((ServerHttpSecurity.HeaderSpec.HstsSpec) -> Unit)? = null private var frameOptions: ((ServerHttpSecurity.HeaderSpec.FrameOptionsSpec) -> Unit)? = null private var contentSecurityPolicy: ((ServerHttpSecurity.HeaderSpec.ContentSecurityPolicySpec) -> Unit)? = null private var referrerPolicy: ((ServerHttpSecurity.HeaderSpec.ReferrerPolicySpec) -> Unit)? = null private var featurePolicyDirectives: String? = null private var permissionsPolicy: ((ServerHttpSecurity.HeaderSpec.PermissionsPolicySpec) -> Unit)? = null private var crossOriginOpenerPolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginOpenerPolicySpec) -> Unit)? = null private var crossOriginEmbedderPolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginEmbedderPolicySpec) -> Unit)? = null private var crossOriginResourcePolicy: ((ServerHttpSecurity.HeaderSpec.CrossOriginResourcePolicySpec) -> Unit)? = null private var disabled = false /** * Configures the [ContentTypeOptionsServerHttpHeadersWriter] which inserts the <a href= * "https://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx" * >X-Content-Type-Options header</a> * * @param contentTypeOptionsConfig the customization to apply to the header */ fun contentTypeOptions(contentTypeOptionsConfig: ServerContentTypeOptionsDsl.() -> Unit) { this.contentTypeOptions = ServerContentTypeOptionsDsl().apply(contentTypeOptionsConfig).get() } /** * <strong>Note this is not comprehensive XSS protection!</strong> * * <p> * Allows customizing the [XXssProtectionServerHttpHeadersWriter] which adds the <a href= * "https://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx" * >X-XSS-Protection header</a> * </p> * * @param xssProtectionConfig the customization to apply to the header */ fun xssProtection(xssProtectionConfig: ServerXssProtectionDsl.() -> Unit) { this.xssProtection = ServerXssProtectionDsl().apply(xssProtectionConfig).get() } /** * Allows customizing the [CacheControlServerHttpHeadersWriter]. Specifically it adds * the following headers: * <ul> * <li>Cache-Control: no-cache, no-store, max-age=0, must-revalidate</li> * <li>Pragma: no-cache</li> * <li>Expires: 0</li> * </ul> * * @param cacheControlConfig the customization to apply to the headers */ fun cache(cacheControlConfig: ServerCacheControlDsl.() -> Unit) { this.cacheControl = ServerCacheControlDsl().apply(cacheControlConfig).get() } /** * Allows customizing the [StrictTransportSecurityServerHttpHeadersWriter] which provides support * for <a href="https://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security * (HSTS)</a>. * * @param hstsConfig the customization to apply to the header */ fun hsts(hstsConfig: ServerHttpStrictTransportSecurityDsl.() -> Unit) { this.hsts = ServerHttpStrictTransportSecurityDsl().apply(hstsConfig).get() } /** * Allows customizing the [XFrameOptionsServerHttpHeadersWriter] which add the X-Frame-Options * header. * * @param frameOptionsConfig the customization to apply to the header */ fun frameOptions(frameOptionsConfig: ServerFrameOptionsDsl.() -> Unit) { this.frameOptions = ServerFrameOptionsDsl().apply(frameOptionsConfig).get() } /** * Allows configuration for <a href="https://www.w3.org/TR/CSP2/">Content Security Policy (CSP) Level 2</a>. * * @param contentSecurityPolicyConfig the customization to apply to the header */ fun contentSecurityPolicy(contentSecurityPolicyConfig: ServerContentSecurityPolicyDsl.() -> Unit) { this.contentSecurityPolicy = ServerContentSecurityPolicyDsl().apply(contentSecurityPolicyConfig).get() } /** * Allows configuration for <a href="https://www.w3.org/TR/referrer-policy/">Referrer Policy</a>. * * <p> * Configuration is provided to the [ReferrerPolicyServerHttpHeadersWriter] which support the writing * of the header as detailed in the W3C Technical Report: * </p> * <ul> * <li>Referrer-Policy</li> * </ul> * * @param referrerPolicyConfig the customization to apply to the header */ fun referrerPolicy(referrerPolicyConfig: ServerReferrerPolicyDsl.() -> Unit) { this.referrerPolicy = ServerReferrerPolicyDsl().apply(referrerPolicyConfig).get() } /** * Allows configuration for <a href="https://wicg.github.io/feature-policy/">Feature * Policy</a>. * * <p> * Calling this method automatically enables (includes) the Feature-Policy * header in the response using the supplied policy directive(s). * <p> * * @param policyDirectives policyDirectives the security policy directive(s) */ @Deprecated("Use 'permissionsPolicy { }' instead.") fun featurePolicy(policyDirectives: String) { this.featurePolicyDirectives = policyDirectives } /** * Allows configuration for <a href="https://w3c.github.io/webappsec-permissions-policy/">Permissions * Policy</a>. * * <p> * Calling this method automatically enables (includes) the Permissions-Policy * header in the response using the supplied policy directive(s). * <p> * * @param permissionsPolicyConfig the customization to apply to the header */ fun permissionsPolicy(permissionsPolicyConfig: ServerPermissionsPolicyDsl.() -> Unit) { this.permissionsPolicy = ServerPermissionsPolicyDsl().apply(permissionsPolicyConfig).get() } /** * Allows configuration for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy"> * Cross-Origin-Opener-Policy</a> header. * * @since 5.7 * @param crossOriginOpenerPolicyConfig the customization to apply to the header */ fun crossOriginOpenerPolicy(crossOriginOpenerPolicyConfig: ServerCrossOriginOpenerPolicyDsl.() -> Unit) { this.crossOriginOpenerPolicy = ServerCrossOriginOpenerPolicyDsl().apply(crossOriginOpenerPolicyConfig).get() } /** * Allows configuration for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy"> * Cross-Origin-Embedder-Policy</a> header. * * @since 5.7 * @param crossOriginEmbedderPolicyConfig the customization to apply to the header */ fun crossOriginEmbedderPolicy(crossOriginEmbedderPolicyConfig: ServerCrossOriginEmbedderPolicyDsl.() -> Unit) { this.crossOriginEmbedderPolicy = ServerCrossOriginEmbedderPolicyDsl().apply(crossOriginEmbedderPolicyConfig).get() } /** * Allows configuration for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy"> * Cross-Origin-Resource-Policy</a> header. * * @since 5.7 * @param crossOriginResourcePolicyConfig the customization to apply to the header */ fun crossOriginResourcePolicy(crossOriginResourcePolicyConfig: ServerCrossOriginResourcePolicyDsl.() -> Unit) { this.crossOriginResourcePolicy = ServerCrossOriginResourcePolicyDsl().apply(crossOriginResourcePolicyConfig).get() } /** * Disables HTTP response headers. */ fun disable() { disabled = true } @Suppress("DEPRECATION") internal fun get(): (ServerHttpSecurity.HeaderSpec) -> Unit { return { headers -> contentTypeOptions?.also { headers.contentTypeOptions(contentTypeOptions) } xssProtection?.also { headers.xssProtection(xssProtection) } cacheControl?.also { headers.cache(cacheControl) } hsts?.also { headers.hsts(hsts) } frameOptions?.also { headers.frameOptions(frameOptions) } contentSecurityPolicy?.also { headers.contentSecurityPolicy(contentSecurityPolicy) } featurePolicyDirectives?.also { headers.featurePolicy(featurePolicyDirectives) } permissionsPolicy?.also { headers.permissionsPolicy(permissionsPolicy) } referrerPolicy?.also { headers.referrerPolicy(referrerPolicy) } crossOriginOpenerPolicy?.also { headers.crossOriginOpenerPolicy(crossOriginOpenerPolicy) } crossOriginEmbedderPolicy?.also { headers.crossOriginEmbedderPolicy(crossOriginEmbedderPolicy) } crossOriginResourcePolicy?.also { headers.crossOriginResourcePolicy(crossOriginResourcePolicy) } if (disabled) { headers.disable() } } } }
apache-2.0
d9853f2715eb8a328b623925649c42b3
41.84127
152
0.694887
4.637457
false
true
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/docker/run/ContainerIOStreamerSpec.kt
1
14750
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.docker.run import batect.docker.DockerException import batect.execution.CancellationCallback import batect.execution.CancellationContext import batect.testutils.CloseableByteArrayOutputStream import batect.testutils.createForEachTest import batect.testutils.doesNotThrow import batect.testutils.equalTo import batect.testutils.on import batect.testutils.runForEachTest import batect.testutils.withMessage import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.lessThan import com.natpryce.hamkrest.throws import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.mock import okhttp3.Response import okio.buffer import okio.sink import okio.source import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.ByteArrayInputStream import java.io.InputStream import java.util.concurrent.CountDownLatch import kotlin.system.measureTimeMillis object ContainerIOStreamerSpec : Spek({ describe("a container I/O streamer") { val streamer by createForEachTest { ContainerIOStreamer() } describe("streaming both input and output for a container") { on("all of the output being available immediately") { val stdin by createForEachTest { ByteArrayInputStream(ByteArray(0)) } val stdout by createForEachTest { CloseableByteArrayOutputStream() } val response by createForEachTest { mock<Response>() } val containerOutputStream by createForEachTest { ByteArrayInputStream("This is the output".toByteArray()) } val containerInputStream by createForEachTest { CloseableByteArrayOutputStream() } val outputStream by createForEachTest { ContainerOutputStream(response, containerOutputStream.source().buffer()) } val inputStream by createForEachTest { ContainerInputStream(response, containerInputStream.sink().buffer()) } val cancellationContext by createForEachTest { mock<CancellationContext>() } beforeEachTest { streamer.stream( OutputConnection.Connected(outputStream, stdout.sink()), InputConnection.Connected(stdin.source(), inputStream), cancellationContext ) } it("writes all of the output from the output stream to stdout") { assertThat(stdout.toString(), equalTo("This is the output")) } it("closes the container's input stream") { assertThat(containerInputStream.isClosed, equalTo(true)) } it("closes the stdout stream") { assertThat(stdout.isClosed, equalTo(true)) } } on("stdin closing before the output from the container has finished") { val stdin by createForEachTest { ByteArrayInputStream("This is the input".toByteArray()) } val stdout by createForEachTest { CloseableByteArrayOutputStream() } val response by createForEachTest { mock<Response>() } val containerOutputStream by createForEachTest { object : ByteArrayInputStream("This is the output".toByteArray()) { val allInputWritten = CountDownLatch(1) override fun read(): Int { allInputWritten.await() return super.read() } override fun read(b: ByteArray, off: Int, len: Int): Int { allInputWritten.await() return super.read(b, off, len) } override fun read(b: ByteArray): Int { allInputWritten.await() return super.read(b) } } } val containerInputStream by createForEachTest { object : CloseableByteArrayOutputStream() { override fun write(b: Int) { super.write(b) checkIfInputComplete() } override fun write(b: ByteArray, off: Int, len: Int) { super.write(b, off, len) checkIfInputComplete() } override fun write(b: ByteArray) { super.write(b) checkIfInputComplete() } private fun checkIfInputComplete() { if (this.toString() == "This is the input") { containerOutputStream.allInputWritten.countDown() } } } } val outputStream by createForEachTest { ContainerOutputStream(response, containerOutputStream.source().buffer()) } val inputStream by createForEachTest { ContainerInputStream(response, containerInputStream.sink().buffer()) } val cancellationContext by createForEachTest { mock<CancellationContext>() } beforeEachTest { streamer.stream( OutputConnection.Connected(outputStream, stdout.sink()), InputConnection.Connected(stdin.source(), inputStream), cancellationContext ) } it("writes all of the input from stdin to the input stream") { assertThat(containerInputStream.toString(), equalTo("This is the input")) } it("writes all of the output from the container to stdout") { assertThat(stdout.toString(), equalTo("This is the output")) } it("closes the container's input stream") { assertThat(containerInputStream.isClosed, equalTo(true)) } it("closes the stdout stream") { assertThat(stdout.isClosed, equalTo(true)) } } on("the output from the container finishing before stdin is closed by the user") { val stdin by createForEachTest { object : InputStream() { val readStarted = CountDownLatch(1) override fun read(): Int { readStarted.countDown() // Block forever to emulate the user not typing anything. blockForever() } } } val stdout by createForEachTest { CloseableByteArrayOutputStream() } val response by createForEachTest { mock<Response>() } val containerOutputStream by createForEachTest { object : ByteArrayInputStream("This is the output".toByteArray()) { override fun read(): Int { stdin.readStarted.await() return super.read() } override fun read(b: ByteArray, off: Int, len: Int): Int { stdin.readStarted.await() return super.read(b, off, len) } override fun read(b: ByteArray): Int { stdin.readStarted.await() return super.read(b) } } } val containerInputStream by createForEachTest { CloseableByteArrayOutputStream() } val outputStream by createForEachTest { ContainerOutputStream(response, containerOutputStream.source().buffer()) } val inputStream by createForEachTest { ContainerInputStream(response, containerInputStream.sink().buffer()) } val cancellationContext by createForEachTest { mock<CancellationContext>() } beforeEachTest { streamer.stream( OutputConnection.Connected(outputStream, stdout.sink()), InputConnection.Connected(stdin.source(), inputStream), cancellationContext ) } it("writes all of the output from the output stream to stdout") { assertThat(stdout.toString(), equalTo("This is the output")) } it("closes the container's input stream") { assertThat(containerInputStream.isClosed, equalTo(true)) } it("closes the stdout stream") { assertThat(stdout.isClosed, equalTo(true)) } } on("streaming being cancelled") { val stdin by createForEachTest { object : InputStream() { override fun read(): Int { Thread.sleep(10_000) return -1 } } } val stdout by createForEachTest { CloseableByteArrayOutputStream() } val response by createForEachTest { mock<Response>() } val containerOutputStream by createForEachTest { object : ByteArrayInputStream("This is the output".toByteArray()) { override fun read(): Int { Thread.sleep(10_000) return -1 } override fun read(b: ByteArray, off: Int, len: Int): Int = read() override fun read(b: ByteArray): Int = read() } } val containerInputStream by createForEachTest { CloseableByteArrayOutputStream() } val outputStream by createForEachTest { ContainerOutputStream(response, containerOutputStream.source().buffer()) } val inputStream by createForEachTest { ContainerInputStream(response, containerInputStream.sink().buffer()) } val cancellationContext by createForEachTest { mock<CancellationContext> { on { addCancellationCallback(any()) } doAnswer { invocation -> @Suppress("UNCHECKED_CAST") val callback = invocation.arguments[0] as CancellationCallback callback() AutoCloseable { } } } } val timeTakenToCancel by runForEachTest { measureTimeMillis { streamer.stream( OutputConnection.Connected(outputStream, stdout.sink()), InputConnection.Connected(stdin.source(), inputStream), cancellationContext ) } } it("returns quickly after being cancelled") { assertThat(timeTakenToCancel, lessThan(10_000L)) } it("closes the container's input stream") { assertThat(containerInputStream.isClosed, equalTo(true)) } it("closes the stdout stream") { assertThat(stdout.isClosed, equalTo(true)) } } } describe("streaming just output for a container") { val stdout by createForEachTest { CloseableByteArrayOutputStream() } val response by createForEachTest { mock<Response>() } val containerOutputStream by createForEachTest { ByteArrayInputStream("This is the output".toByteArray()) } val outputStream by createForEachTest { ContainerOutputStream(response, containerOutputStream.source().buffer()) } val cancellationContext by createForEachTest { mock<CancellationContext>() } beforeEachTest { streamer.stream( OutputConnection.Connected(outputStream, stdout.sink()), InputConnection.Disconnected, cancellationContext ) } it("writes all of the output from the output stream to stdout") { assertThat(stdout.toString(), equalTo("This is the output")) } it("closes the stdout stream") { assertThat(stdout.isClosed, equalTo(true)) } } describe("streaming just input for a container") { val output by createForEachTest { OutputConnection.Disconnected } val input by createForEachTest { InputConnection.Connected(mock(), mock()) } val cancellationContext by createForEachTest { mock<CancellationContext>() } it("throws an appropriate exception") { assertThat({ streamer.stream(output, input, cancellationContext) }, throws<DockerException>(withMessage("Cannot stream input to a container when output is disconnected."))) } } describe("streaming neither input nor output for a container") { val cancellationContext by createForEachTest { mock<CancellationContext>() } it("does not throw an exception") { assertThat({ streamer.stream(OutputConnection.Disconnected, InputConnection.Disconnected, cancellationContext) }, doesNotThrow()) } } } }) private fun blockForever(): Nothing { CountDownLatch(1).await() throw RuntimeException("This should never be reached") }
apache-2.0
3ebfa77664095055067a58559bb900d0
41.753623
188
0.549356
6.438237
false
true
false
false
lnds/9d9l
desafio2/kotlin/src/main/kotlin/weather/ParCollections.kt
1
2271
package weather // borrowed from https://github.com/holgerbrandl/kutils/blob/master/src/main/kotlin/kutils/ParCollections.kt import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors /** * Parallel collection mimicking scala's .par(). * * @author Holger Brandl */ /** A delegated tagging interface to allow for parallized extension functions */ class ParCol<T>(val it: Iterable<T>, val executorService: ExecutorService) : Iterable<T> by it /** Convert a stream into a parallel collection. */ fun <T> Iterable<T>.par(numThreads: Int = Runtime.getRuntime().availableProcessors(), executorService: ExecutorService = Executors.newFixedThreadPool(numThreads)): ParCol<T> { return ParCol(this, executorService); } /** De-parallelize a collection. Undos <code>par</code> */ fun <T> ParCol<T>.unpar(): Iterable<T> { return this.it; } fun <T, R> ParCol<T>.map(transform: (T) -> R): ParCol<R> { // note default size is just an inlined version of kotlin.collections.collectionSizeOrDefault val destination = ArrayList<R>(if (this is Collection<*>) this.size else 10) // http://stackoverflow.com/questions/3269445/executorservice-how-to-wait-for-all-tasks-to-finish // use futures here to allow for recycling of the executorservice val futures = this.asIterable().map { executorService.submit { destination.add(transform(it)) } } futures.map { it.get() } // this will block until all are done // executorService.shutdown() // executorService.awaitTermination(1, TimeUnit.DAYS) return ParCol(destination, executorService) } /** A parallelizable version of kotlin.collections.map * @param numThreads The number of parallel threads. Defaults to number of cores minus 2 * @param exec The executor. By exposing this as a parameter, application can share an executor among different parallel * mapping taks. */ fun <T, R> Iterable<T>.parmap(numThreads: Int = Runtime.getRuntime().availableProcessors(), exec: ExecutorService = Executors.newFixedThreadPool(numThreads), transform: (T) -> R): Iterable<R> { return this.par(executorService = exec).map(transform).unpar() }
mit
5bb69773358f5d0e402f59841de429ad
37.491525
120
0.704535
4.040925
false
false
false
false
mstream/BoardGameEngine
src/test/kotlin/io/mstream/boardgameengine/game/tictactoe/TicTacToeInitializationTest.kt
1
1123
package io.mstream.boardgameengine.game.tictactoe import io.mstream.boardgameengine.* import io.mstream.boardgameengine.game.* import org.junit.* class TicTacToeInitializationTest { @Test fun shouldCreateSizeOfThreeBoard() { val recordingEventSender = RecordingEventSender() TicTacToe(recordingEventSender) val events = recordingEventSender.receivedEvents val boardCreatedEvents = events.filterIsInstance<BoardCreated>() Assert.assertEquals("should emit only one BoardCreated event", 1, boardCreatedEvents.count()) val boardCreatedEvent = boardCreatedEvents.get(0) Assert.assertEquals("created board size should be 3", 3, boardCreatedEvent.size) } @Test fun shouldCreateEmptyBoard() { val recordingEventSender = RecordingEventSender() TicTacToe(recordingEventSender) val events = recordingEventSender.receivedEvents val pieceSetEvents = events.filterIsInstance<PieceSet>() Assert.assertTrue("shouldn't emit any PieceSet event", pieceSetEvents.isEmpty()) } }
mit
291e548ebf9834db29d90bdbf373073d
35.258065
72
0.710597
5.451456
false
true
false
false
pedroSG94/rtmp-rtsp-stream-client-java
app/src/main/java/com/pedro/rtpstreamer/backgroundexample/BackgroundActivity.kt
1
3661
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtpstreamer.backgroundexample import android.app.ActivityManager import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.view.SurfaceHolder import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import com.pedro.rtpstreamer.R import com.pedro.rtpstreamer.databinding.ActivityBackgroundBinding @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) class BackgroundActivity : AppCompatActivity(), SurfaceHolder.Callback { private lateinit var binding: ActivityBackgroundBinding private var service: RtpService? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityBackgroundBinding.inflate(layoutInflater) setContentView(binding.root) RtpService.observer.observe(this) { service = it startPreview() } binding.bStartStop.setOnClickListener { if (service?.isStreaming() != true) { if (service?.prepare() == true) { service?.startStream(binding.etRtpUrl.text.toString()) binding.bStartStop.setText(R.string.stop_button) } } else { service?.stopStream() binding.bStartStop.setText(R.string.start_button) } } binding.surfaceView.holder.addCallback(this) } override fun surfaceChanged(holder: SurfaceHolder, p1: Int, p2: Int, p3: Int) { startPreview() } override fun surfaceDestroyed(holder: SurfaceHolder) { service?.setView(this) if (service?.isOnPreview() == true) service?.stopPreview() } override fun surfaceCreated(holder: SurfaceHolder) { } override fun onResume() { super.onResume() if (!isMyServiceRunning(RtpService::class.java)) { val intent = Intent(applicationContext, RtpService::class.java) startService(intent) } if (service?.isStreaming() == true) { binding.bStartStop.setText(R.string.stop_button) } else { binding.bStartStop.setText(R.string.start_button) } } override fun onPause() { super.onPause() if (!isChangingConfigurations) { //stop if no rotation activity if (service?.isOnPreview() == true) service?.stopPreview() if (service?.isStreaming() != true) { service = null stopService(Intent(applicationContext, RtpService::class.java)) } } } @Suppress("DEPRECATION") private fun isMyServiceRunning(serviceClass: Class<*>): Boolean { val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.name == service.service.className) { return true } } return false } private fun startPreview() { if (binding.surfaceView.holder.surface.isValid) { service?.setView(binding.surfaceView) } //check if onPreview and if surface is valid if (service?.isOnPreview() != true && binding.surfaceView.holder.surface.isValid) { service?.startPreview() } } }
apache-2.0
7f6b7efe3c8761ab899f10081ed80452
30.560345
87
0.709096
4.271879
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-core/src/org/jetbrains/kotlin/core/resolve/KotlinCacheServiceImpl.kt
1
4775
/******************************************************************************* * 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.kotlin.core.resolve import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.analyzer.AnalysisResult import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.container.ComponentProvider import org.jetbrains.kotlin.core.model.KotlinAnalysisFileCache import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.TargetPlatform import org.jetbrains.kotlin.resolve.diagnostics.KotlinSuppressCache import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.analyzer.ModuleInfo public class KotlinCacheServiceImpl(val ideaProject: Project) : KotlinCacheService { override fun getResolutionFacadeByFile(file: PsiFile, platform: TargetPlatform): ResolutionFacade { throw UnsupportedOperationException() } override fun getSuppressionCache(): KotlinSuppressCache { throw UnsupportedOperationException() } override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade { return KotlinSimpleResolutionFacade(ideaProject, elements) } override fun getResolutionFacadeByModuleInfo(moduleInfo: ModuleInfo, platform: TargetPlatform): ResolutionFacade? = null } class KotlinSimpleResolutionFacade( override val project: Project, private val elements: List<KtElement>) : ResolutionFacade { override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? { return null } override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor { throw UnsupportedOperationException() } override val moduleDescriptor: ModuleDescriptor get() = throw UnsupportedOperationException() override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext { val ktFile = element.getContainingKtFile() return KotlinAnalysisFileCache.getAnalysisResult(ktFile).analysisResult.bindingContext } override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext { if (elements.isEmpty()) { return BindingContext.EMPTY } val ktFile = elements.first().getContainingKtFile() return KotlinAnalysisFileCache.getAnalysisResult(ktFile).analysisResult.bindingContext } override fun analyzeFullyAndGetResult(elements: Collection<KtElement>): AnalysisResult { throw UnsupportedOperationException() } override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T { throw UnsupportedOperationException() } override fun <T : Any> getFrontendService(serviceClass: Class<T>): T { val files = elements.map { it.getContainingKtFile() }.toSet() if (files.isEmpty()) throw IllegalStateException("Elements should not be empty") val componentProvider = KotlinAnalyzer.analyzeFiles(files).componentProvider if (componentProvider == null) { throw IllegalStateException("Trying to get service from non-initialized project") } return componentProvider.getService(serviceClass) } override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T { throw UnsupportedOperationException() } override fun <T : Any> getIdeService(serviceClass: Class<T>): T { throw UnsupportedOperationException() } } @Suppress("UNCHECKED_CAST") fun <T : Any> ComponentProvider.getService(request: Class<T>): T { return resolve(request)!!.getValue() as T }
apache-2.0
9a97e5bd07d7aeaf9088478598c6d63a
42.027027
123
0.730262
5.389391
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/ads/dto/AdsStatsFormat.kt
1
2955
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.ads.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.String /** * @param clicks - Clicks number * @param linkExternalClicks - External clicks number * @param day - Day as YYYY-MM-DD * @param impressions - Impressions number * @param joinRate - Events number * @param month - Month as YYYY-MM * @param overall - 1 if period=overall * @param reach - Reach * @param spent - Spent funds * @param videoClicksSite - Clickthoughs to the advertised site * @param videoViews - Video views number * @param videoViewsFull - Video views (full video) * @param videoViewsHalf - Video views (half of video) */ data class AdsStatsFormat( @SerializedName("clicks") val clicks: Int? = null, @SerializedName("link_external_clicks") val linkExternalClicks: Int? = null, @SerializedName("day") val day: String? = null, @SerializedName("impressions") val impressions: Int? = null, @SerializedName("join_rate") val joinRate: Int? = null, @SerializedName("month") val month: String? = null, @SerializedName("overall") val overall: Int? = null, @SerializedName("reach") val reach: Int? = null, @SerializedName("spent") val spent: Int? = null, @SerializedName("video_clicks_site") val videoClicksSite: Int? = null, @SerializedName("video_views") val videoViews: Int? = null, @SerializedName("video_views_full") val videoViewsFull: Int? = null, @SerializedName("video_views_half") val videoViewsHalf: Int? = null )
mit
b1b518409f2c01e87e5917967451c8ec
37.881579
81
0.680203
4.138655
false
false
false
false
vipulasri/Timeline-View
app/src/main/java/com/github/vipulasri/timelineview/sample/TimelineAttributesBottomSheet.kt
1
9582
package com.github.vipulasri.timelineview.sample import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import androidx.appcompat.view.ContextThemeWrapper import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.os.bundleOf import androidx.fragment.app.FragmentManager import com.github.vipulasri.timelineview.TimelineView import com.github.vipulasri.timelineview.sample.model.Orientation import com.github.vipulasri.timelineview.sample.model.TimelineAttributes import com.github.vipulasri.timelineview.sample.widgets.BorderedCircle import com.github.vipulasri.timelineview.sample.widgets.RoundedCornerBottomSheet import com.google.android.material.bottomsheet.BottomSheetBehavior import com.thebluealliance.spectrum.SpectrumDialog import kotlinx.android.synthetic.main.bottom_sheet_options.* import kotlinx.android.synthetic.main.item_bottom_sheet_line.* import kotlinx.android.synthetic.main.item_bottom_sheet_marker.* import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar @Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") class TimelineAttributesBottomSheet: RoundedCornerBottomSheet() { interface Callbacks { fun onAttributesChanged(attributes: TimelineAttributes) } companion object { private const val EXTRA_ATTRIBUTES = "EXTRA_ATTRIBUTES" fun showDialog(fragmentManager: FragmentManager, attributes: TimelineAttributes, callbacks: Callbacks) { val dialog = TimelineAttributesBottomSheet() dialog.arguments = bundleOf( EXTRA_ATTRIBUTES to attributes ) dialog.setCallback(callbacks) dialog.show(fragmentManager, "[TIMELINE_ATTRIBUTES_BOTTOM_SHEET]") } } private var mCallbacks: Callbacks? = null private lateinit var mAttributes: TimelineAttributes private var mBottomSheetBehavior: BottomSheetBehavior<*>? = null override fun onStart() { super.onStart() if (dialog != null) { val bottomSheet = dialog!!.findViewById<View>(R.id.design_bottom_sheet) bottomSheet.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT } view?.post { val parent = view?.parent as View val params = parent.layoutParams as CoordinatorLayout.LayoutParams val behavior = params.behavior mBottomSheetBehavior = behavior as BottomSheetBehavior<*>? mBottomSheetBehavior?.peekHeight = view?.measuredHeight!! } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val contextThemeWrapper = ContextThemeWrapper(activity, R.style.AppTheme) return inflater.cloneInContext(contextThemeWrapper).inflate(R.layout.bottom_sheet_options, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val attributes = (arguments!!.getParcelable(EXTRA_ATTRIBUTES) as TimelineAttributes) mAttributes = attributes.copy() text_attributes_heading.setOnClickListener { dismiss() } //orientation rg_orientation.setOnCheckedChangeListener { group, checkedId -> when(checkedId) { R.id.rb_horizontal -> { mAttributes.orientation = Orientation.HORIZONTAL } R.id.rb_vertical -> { mAttributes.orientation = Orientation.VERTICAL } } } rg_orientation.check(if(mAttributes.orientation == Orientation.VERTICAL) R.id.rb_vertical else R.id.rb_horizontal) //marker seek_marker_size.progress = mAttributes.markerSize image_marker_color.mFillColor = mAttributes.markerColor checkbox_marker_in_center.isChecked = mAttributes.markerInCenter seek_marker_left_padding.progress = mAttributes.markerLeftPadding seek_marker_top_padding.progress = mAttributes.markerTopPadding seek_marker_right_padding.progress = mAttributes.markerRightPadding seek_marker_bottom_padding.progress = mAttributes.markerBottomPadding seek_marker_line_padding.progress = mAttributes.linePadding checkbox_marker_in_center.setOnCheckedChangeListener { buttonView, isChecked -> mAttributes.markerInCenter = isChecked } image_marker_color.setOnClickListener { showColorPicker(mAttributes.markerColor, image_marker_color) } seek_marker_size.setOnProgressChangeListener(progressChangeListener) seek_marker_left_padding.setOnProgressChangeListener(progressChangeListener) seek_marker_top_padding.setOnProgressChangeListener(progressChangeListener) seek_marker_right_padding.setOnProgressChangeListener(progressChangeListener) seek_marker_bottom_padding.setOnProgressChangeListener(progressChangeListener) seek_marker_line_padding.setOnProgressChangeListener(progressChangeListener) //line Log.e(" mAttributes.lineWidth", "${ mAttributes.lineWidth}") seek_line_width.progress = mAttributes.lineWidth image_start_line_color.mFillColor = mAttributes.startLineColor image_end_line_color.mFillColor = mAttributes.endLineColor image_start_line_color.setOnClickListener { showColorPicker(mAttributes.startLineColor, image_start_line_color) } image_end_line_color.setOnClickListener { showColorPicker(mAttributes.endLineColor, image_end_line_color) } when(mAttributes.lineStyle) { TimelineView.LineStyle.NORMAL -> spinner_line_type.setSelection(0) TimelineView.LineStyle.DASHED -> spinner_line_type.setSelection(1) } spinner_line_type.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { val selectedItem = parent.getItemAtPosition(position).toString() when (selectedItem) { "Normal" -> mAttributes.lineStyle = TimelineView.LineStyle.NORMAL "Dashed" -> mAttributes.lineStyle = TimelineView.LineStyle.DASHED else -> { mAttributes.lineStyle = TimelineView.LineStyle.NORMAL } } } override fun onNothingSelected(parent: AdapterView<*>) { } } seek_line_dash_width.progress = mAttributes.lineDashWidth seek_line_dash_gap.progress = mAttributes.lineDashGap seek_line_width.setOnProgressChangeListener(progressChangeListener) seek_line_dash_width.setOnProgressChangeListener(progressChangeListener) seek_line_dash_gap.setOnProgressChangeListener(progressChangeListener) button_apply.setOnClickListener { mCallbacks?.onAttributesChanged(mAttributes) dismiss() } } private fun showColorPicker(selectedColor : Int, colorView: BorderedCircle) { SpectrumDialog.Builder(requireContext()) .setColors(R.array.colors) .setSelectedColor(selectedColor) .setDismissOnColorSelected(true) .setOutlineWidth(1) .setOnColorSelectedListener { positiveResult, color -> if (positiveResult) { colorView.mFillColor = color when(colorView.id) { R.id.image_marker_color -> { mAttributes.markerColor = color } R.id.image_start_line_color -> { mAttributes.startLineColor = color } R.id.image_end_line_color -> { mAttributes.endLineColor = color } else -> { //do nothing } } } }.build().show(childFragmentManager, "ColorPicker") } private var progressChangeListener: DiscreteSeekBar.OnProgressChangeListener = object : DiscreteSeekBar.OnProgressChangeListener { override fun onProgressChanged(discreteSeekBar: DiscreteSeekBar, value: Int, b: Boolean) { Log.d("onProgressChanged", "value->$value") when(discreteSeekBar.id) { R.id.seek_marker_size -> { mAttributes.markerSize = value } R.id.seek_marker_left_padding -> { mAttributes.markerLeftPadding = value } R.id.seek_marker_top_padding -> { mAttributes.markerTopPadding = value } R.id.seek_marker_right_padding -> { mAttributes.markerRightPadding = value } R.id.seek_marker_bottom_padding -> { mAttributes.markerBottomPadding = value } R.id.seek_marker_line_padding -> { mAttributes.linePadding = value } R.id.seek_line_width -> { mAttributes.lineWidth = value } R.id.seek_line_dash_width -> { mAttributes.lineDashWidth = value } R.id.seek_line_dash_gap -> { mAttributes.lineDashGap = value } } } override fun onStartTrackingTouch(discreteSeekBar: DiscreteSeekBar) { } override fun onStopTrackingTouch(discreteSeekBar: DiscreteSeekBar) { } } private fun setCallback(callbacks: Callbacks) { mCallbacks = callbacks } }
apache-2.0
f6fa5d39043d329f9036580b9f54c163
43.572093
134
0.67345
4.980249
false
false
false
false
bazelbuild/rules_kotlin
examples/multiplex/src/Small2.kt
1
387
package com.foo.bar class C1 { fun a1(a: Int, b: Int) = a + b fun a2(a: Int, b: Int) = a + b fun a3(a: Int, b: Int) = a + b fun a4(a: Int, b: Int) = a + b fun a5(a: Int, b: Int) = a + b fun a6(a: Int, b: Int) = a + b fun a7(a: Int, b: Int) = a + b fun a8(a: Int, b: Int) = a + b fun a9(a: Int, b: Int) = a + b fun a10(a: Int, b: Int) = a + b }
apache-2.0
25464cab1d86a1bdf6fc8c4caf60d392
23.1875
35
0.449612
2.080645
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/lang/Saxonica.kt
1
1602
/* * Copyright (C) 2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.saxon.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.saxon.resources.SaxonIcons import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSchemaFile import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmVendorType import javax.swing.Icon object Saxonica : ItemPresentation, XpmVendorType { // region ItemPresentation override fun getPresentableText(): String = "Saxonica" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = SaxonIcons.Product // endregion // region XpmVendorType override val id: String = "saxon" override val presentation: ItemPresentation get() = this // endregion // region XpmVendorType override fun isValidInstallDir(installDir: String): Boolean = false override val modulePath: String? = null override fun schemaFiles(path: String): Sequence<XpmSchemaFile> = sequenceOf() // endregion }
apache-2.0
b570bad3ef174efea089be0af4e080b7
30.411765
82
0.74407
4.32973
false
false
false
false
jeffgbutler/mybatis-dynamic-sql
src/test/kotlin/examples/kotlin/mybatis3/canonical/AddressRecord.kt
1
935
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package examples.kotlin.mybatis3.canonical data class AddressRecord( var id: Int? = null, var streetAddress: String? = null, var city: String? = null, var state: String? = null, var addressType: AddressType? = null ) enum class AddressType { HOME, BUSINESS }
apache-2.0
6c34581cf3fcef4fffaaadfec1b0d8aa
32.392857
78
0.699465
3.978723
false
false
false
false
myoffe/kotlin-koans
src/i_introduction/_2_Named_Arguments/NamedArguments.kt
1
737
package i_introduction._2_Named_Arguments import i_introduction._1_Java_To_Kotlin_Converter.task1 import util.TODO import util.doc2 // default values for arguments: fun bar(i: Int, s: String = "", b: Boolean = true) {} fun usage() { // named arguments: bar(1, b = false) } fun todoTask2(): Nothing = TODO( """ Task 2. Implement the same logic as in 'task1' again through the library method 'joinToString()'. Specify only two of the 'joinToString' arguments. """, documentation = doc2(), references = { collection: Collection<Int> -> task1(collection); collection.joinToString() }) fun task2(collection: Collection<Int>): String { return collection.joinToString(", :", "{", "}") }
mit
a307cf47ba697f261364279fdcccfe2a
27.346154
97
0.658073
3.818653
false
false
false
false
Maccimo/intellij-community
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt
4
25095
// 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. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet") package org.jetbrains.intellij.build.images import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.svg.SvgTranscoder import com.intellij.ui.svg.createSvgDocument import com.intellij.util.LineSeparator import com.intellij.util.containers.CollectionFactory import com.intellij.util.containers.ContainerUtil import com.intellij.util.diff.Diff import com.intellij.util.io.directoryStreamIfExists import com.intellij.util.io.systemIndependentPath import com.intellij.util.lang.Murmur3_32Hash import com.intellij.util.xml.dom.readXmlAsModel import org.jetbrains.jps.model.JpsSimpleElement import org.jetbrains.jps.model.java.JavaResourceRootType import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootType import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.util.JpsPathUtil import java.awt.image.BufferedImage import java.io.File import java.nio.file.* import java.util.* import java.util.concurrent.atomic.AtomicInteger import javax.imageio.ImageIO import javax.xml.stream.XMLStreamException internal data class ModifiedClass(val module: JpsModule, val file: Path, val result: CharSequence) // legacy ordering private val NAME_COMPARATOR: Comparator<String> = compareBy { it.lowercase(Locale.ENGLISH) + '.' } internal data class IconClassInfo(val customLoad: Boolean, val packageName: String, val className: String, val outFile: Path, val images: Collection<ImageInfo>) internal open class IconsClassGenerator(private val projectHome: Path, val modules: List<JpsModule>, private val writeChangesToDisk: Boolean = true) { companion object { private val deprecatedIconFieldNameMap = CollectionFactory.createCharSequenceMap<String>(true) init { deprecatedIconFieldNameMap.put("RwAccess", "Rw_access") deprecatedIconFieldNameMap.put("MenuOpen", "Menu_open") deprecatedIconFieldNameMap.put("MenuCut", "Menu_cut") deprecatedIconFieldNameMap.put("MenuPaste", "Menu_paste") @Suppress("SpellCheckingInspection") deprecatedIconFieldNameMap.put("MenuSaveall", "Menu_saveall") deprecatedIconFieldNameMap.put("PhpIcon", "Php_icon") deprecatedIconFieldNameMap.put("Emulator02", "Emulator2") } } private val processedClasses = AtomicInteger() private val processedIcons = AtomicInteger() private val processedPhantom = AtomicInteger() private val modifiedClasses = ContainerUtil.createConcurrentList<ModifiedClass>() private val obsoleteClasses = ContainerUtil.createConcurrentList<Path>() private val util: JpsModule by lazy { modules.find { it.name == "intellij.platform.util" } ?: error("Can't load module 'util'") } internal open fun getIconClassInfo(module: JpsModule, moduleConfig: IntellijIconClassGeneratorModuleConfig?): List<IconClassInfo> { val packageName: String val className: CharSequence val outFile: Path when (module.name) { "intellij.platform.icons" -> { packageName = "com.intellij.icons" className = "AllIcons" val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons" outFile = Path.of(dir, "$className.java") } "intellij.android.artwork" -> { packageName = "icons" val sourceRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).single().file.absolutePath val resourceRoot = module.getSourceRoots(JavaResourceRootType.RESOURCE).single() // avoid merge conflicts - do not transform StudioIcons to nested class of AndroidIcons var imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig) val imagesA = imageCollector.collectSubDir(resourceRoot, "icons", includePhantom = true) imageCollector.printUsedIconRobots() imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig) val imagesS = imageCollector.collectSubDir(resourceRoot, "studio/icons", includePhantom = true) imageCollector.printUsedIconRobots() imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig) val imagesI = imageCollector.collectSubDir(resourceRoot, "studio/illustrations", includePhantom = true) imageCollector.printUsedIconRobots() return listOf( IconClassInfo(true, packageName, "AndroidIcons", Path.of(sourceRoot, "icons", "AndroidIcons.java"), imagesA), IconClassInfo(true, packageName, "StudioIcons", Path.of(sourceRoot, "icons", "StudioIcons.java"), imagesS), IconClassInfo(true, packageName, "StudioIllustrations", Path.of(sourceRoot, "icons", "StudioIllustrations.java"), imagesI), ) } else -> { packageName = moduleConfig?.packageName ?: getPluginPackageIfPossible(module) ?: "icons" val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() ?: return emptyList() val firstRootDir = Path.of(JpsPathUtil.urlToPath(firstRoot.url)).resolve("icons") var oldClassName: String? // this is added to remove unneeded empty directories created by previous version of this script if (Files.isDirectory(firstRootDir)) { try { Files.delete(firstRootDir) println("deleting empty directory $firstRootDir") } catch (ignore: DirectoryNotEmptyException) { } oldClassName = findIconClass(firstRootDir) } else { oldClassName = null } val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources } val targetRoot = (generatedRoot ?: firstRoot).file.toPath().resolve(packageName.replace('.', File.separatorChar)) if (generatedRoot != null && oldClassName != null && firstRoot != generatedRoot) { val oldFile = firstRootDir.resolve("$oldClassName.java") println("deleting $oldFile from source root which isn't marked as 'generated'") Files.delete(oldFile) } if (moduleConfig?.className == null) { if (oldClassName == null) { try { oldClassName = findIconClass(targetRoot) } catch (ignored: NoSuchFileException) { } } className = oldClassName ?: directoryName(module).let { if (it.endsWith("Icons")) it else "${it}Icons" } } else { className = moduleConfig.className } outFile = targetRoot.resolve("$className.java") } } val imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig) val images = imageCollector.collect(module, includePhantom = true) imageCollector.printUsedIconRobots() return listOf(IconClassInfo(true, packageName, className.toString(), outFile, images)) } fun processModule(module: JpsModule, moduleConfig: IntellijIconClassGeneratorModuleConfig?) { val classCode = StringBuilder() for (iconsClassInfo in getIconClassInfo(module, moduleConfig)) { val outFile = iconsClassInfo.outFile val oldText = try { Files.readString(outFile) } catch (ignored: NoSuchFileException) { null } classCode.setLength(0) val newText = writeClass(getCopyrightComment(oldText), iconsClassInfo, classCode) if (newText.isNullOrEmpty()) { if (Files.exists(outFile)) { obsoleteClasses.add(outFile) } continue } processedClasses.incrementAndGet() val newLines = newText.lines() val oldLines = oldText?.lines() ?: emptyList() if (oldLines == newLines) { continue } if (writeChangesToDisk) { val separator = getSeparators(oldText) Files.createDirectories(outFile.parent) Files.writeString(outFile, newLines.joinToString(separator = separator.separatorString)) println("Updated class: ${outFile.fileName}") } else { val diff = Diff.linesDiff(oldLines.toTypedArray(), newLines.toTypedArray()) ?: "" modifiedClasses.add(ModifiedClass(module, outFile, diff)) } } } fun printStats() { println( "\nGenerated classes: ${processedClasses.get()}. " + "Processed icons: ${processedIcons.get()}. " + "Phantom icons: ${processedPhantom.get()}" ) if (obsoleteClasses.isNotEmpty()) { println("\nObsolete classes:") println(obsoleteClasses.joinToString("\n")) println("\nObsolete class it is class for icons that cannot be found anymore. Possible reasons:") println( "1. Icons not located under resources root." + "\n Solution - move icons to resources root or fix existing root type (must be \"resources\")" ) println("2. Icons were removed but not class.\n Solution - remove class.") println( "3. Icons located under resources root named \"compatibilityResources\". \"compatibilityResources\" for icons that not used externally as icon class fields, " + "but maybe referenced directly by path.\n Solution - remove class or move icons to another resources root" ) } } fun getModifiedClasses(): List<ModifiedClass> = modifiedClasses private fun findIconClass(dir: Path): String? { dir.directoryStreamIfExists { stream -> for (it in stream) { val name = it.fileName.toString() if (name.endsWith("Icons.java")) { return name.substring(0, name.length - ".java".length) } } } return null } private fun getCopyrightComment(text: String?): String { if (text == null) { return "" } val i = text.indexOf("package ") if (i == -1) { return "" } val comment = text.substring(0, i) return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else "" } private fun getSeparators(text: String?): LineSeparator { return StringUtil.detectSeparators(text ?: return LineSeparator.LF) ?: LineSeparator.LF } private fun writeClass(copyrightComment: String, info: IconClassInfo, result: StringBuilder): CharSequence? { val images = info.images if (images.isEmpty()) { return null } result.append(copyrightComment) append(result, "package ${info.packageName};\n", 0) append(result, "import com.intellij.ui.IconManager;", 0) append(result, "import org.jetbrains.annotations.NotNull;", 0) result.append('\n') append(result, "import javax.swing.*;", 0) result.append('\n') if (images.any(ImageInfo::scheduledForRemoval)) { append(result, "import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval;", 0) result.append('\n') } // IconsGeneratedSourcesFilter depends on following comment, if you are going to change the text // please do correspond changes in IconsGeneratedSourcesFilter as well result.append("/**\n") result.append(" * NOTE THIS FILE IS AUTO-GENERATED\n") result.append(" * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead\n") result.append(" */\n") result.append("public") // backward compatibility if (info.className != "AllIcons") { result.append(" final") } result.append(" class ").append(info.className).append(" {\n") if (info.customLoad) { append(result, "private static @NotNull Icon load(@NotNull String path, int cacheKey, int flags) {", 1) append(result, "return $iconLoaderCode.loadRasterizedIcon(path, ${info.className}.class.getClassLoader(), cacheKey, flags);", 2) append(result, "}", 1) val customExternalLoad = images.any { it.deprecation?.replacementContextClazz != null } if (customExternalLoad) { result.append('\n') append(result, "private static @NotNull Icon load(@NotNull String path, @NotNull Class<?> clazz) {", 1) append(result, "return $iconLoaderCode.getIcon(path, clazz);", 2) append(result, "}", 1) } } val inners = StringBuilder() processIcons(images, inners, info.customLoad, 0) if (inners.isEmpty()) { return null } result.append(inners) append(result, "}", 0) return result } private fun processIcons(images: Collection<ImageInfo>, result: StringBuilder, customLoad: Boolean, depth: Int) { val level = depth + 1 val nodeMap = HashMap<String, MutableList<ImageInfo>>(images.size / 2) val leafMap = HashMap<String, ImageInfo>(images.size) for (imageInfo in images) { val imageId = getImageId(imageInfo, depth) val index = imageId.indexOf('/') if (index >= 0) { nodeMap.computeIfAbsent(imageId.substring(0, index)) { mutableListOf() }.add(imageInfo) } else { leafMap.put(imageId, imageInfo) } } fun getWeight(key: String): Int { val image = leafMap.get(key) ?: return 0 return if (image.deprecated) 1 else 0 } val sortedKeys = ArrayList<String>(nodeMap.size + leafMap.size) sortedKeys.addAll(nodeMap.keys) sortedKeys.addAll(leafMap.keys) sortedKeys.sortWith(NAME_COMPARATOR) sortedKeys.sortWith(Comparator { o1, o2 -> getWeight(o1) - getWeight(o2) }) var innerClassWasBefore = false for (key in sortedKeys) { val group = nodeMap.get(key) if (group != null) { val oldLength = result.length val className = className(key) if (isInlineClass(className)) { processIcons(group, result, customLoad, depth + 1) } else { // if first in block, do not add yet another extra newline if (result.length < 2 || result.get(result.length - 1) != '\n' || result.get(result.length - 2) != '{') { result.append('\n') } append(result, "public static final class $className {", level) val lengthBeforeBody = result.length processIcons(group, result, customLoad, depth + 1) if (lengthBeforeBody == result.length) { result.setLength(oldLength) } else { append(result, "}", level) innerClassWasBefore = true } } } val image = leafMap.get(key) if (image != null) { if (innerClassWasBefore) { innerClassWasBefore = false result.append('\n') } appendImage(image, result, level, customLoad) } } } protected open fun isInlineClass(name: CharSequence) = false private fun appendImage(image: ImageInfo, result: StringBuilder, level: Int, customLoad: Boolean) { val file = image.basicFile ?: return if (!image.phantom && !isIcon(file)) { return } processedIcons.incrementAndGet() if (image.phantom) { processedPhantom.incrementAndGet() } if (image.used || image.deprecated) { val deprecationComment = image.deprecation?.comment if (deprecationComment != null) { // if first in block, do not add yet another extra newline if (result.get(result.length - 1) != '\n' || result.get(result.length - 2) != '\n') { result.append('\n') } append(result, "/** @deprecated $deprecationComment */", level) } append(result, "@SuppressWarnings(\"unused\")", level) } if (image.deprecated) { append(result, "@Deprecated", level) } if (image.scheduledForRemoval) { append(result, "@ScheduledForRemoval", level) } val sourceRoot = image.sourceRoot var rootPrefix = "/" if (sourceRoot.rootType == JavaSourceRootType.SOURCE) { @Suppress("UNCHECKED_CAST") val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix if (packagePrefix.isNotEmpty()) { rootPrefix += packagePrefix.replace('.', '/') + "/" } } // backward compatibility - use streaming camel case for StudioIcons val iconName = generateIconFieldName(file) val deprecation = image.deprecation if (deprecation?.replacementContextClazz != null) { val method = if (customLoad) "load" else "$iconLoaderCode.getIcon" append(result, "public static final @NotNull Icon $iconName = " + "$method(\"${deprecation.replacement}\", ${deprecation.replacementContextClazz}.class);", level) return } else if (deprecation?.replacementReference != null) { append(result, "public static final @NotNull Icon $iconName = ${deprecation.replacementReference};", level) return } val rootDir = Path.of(JpsPathUtil.urlToPath(sourceRoot.url)) val imageFile: Path if (deprecation?.replacement == null) { imageFile = file } else { imageFile = rootDir.resolve(deprecation.replacement.removePrefix("/").removePrefix(File.separator)) assert(isIcon(imageFile)) { "Invalid deprecation replacement '${deprecation.replacement}': $imageFile is not an icon" } } var javaDoc: String var key: Int try { val loadedImage: BufferedImage if (file.toString().endsWith(".svg")) { // don't mask any exception for svg file val data = loadAndNormalizeSvgFile(imageFile).toByteArray() loadedImage = SvgTranscoder.createImage(1f, createSvgDocument(null, data), null) key = getImageKey(data, file.fileName.toString()) } else { loadedImage = Files.newInputStream(file).buffered().use { ImageIO.read(it) } key = 0 } javaDoc = "/** ${loadedImage.width}x${loadedImage.height} */ " } catch (e: NoSuchFileException) { if (!image.phantom) { throw e } javaDoc = "" key = 0 } val method = if (customLoad) "load" else "$iconLoaderCode.getIcon" val relativePath = rootPrefix + rootDir.relativize(imageFile).systemIndependentPath assert(relativePath.startsWith("/")) append(result, "${javaDoc}public static final @NotNull Icon $iconName = " + "$method(\"${relativePath.removePrefix("/")}\", $key, ${image.getFlags()});", level) val oldName = deprecatedIconFieldNameMap.get(iconName) if (oldName != null) { append(result, "${javaDoc}public static final @Deprecated @NotNull Icon $oldName = $iconName;", level) } } protected fun append(result: StringBuilder, text: String, level: Int) { if (text.isNotBlank()) { for (i in 0 until level) { result.append(' ').append(' ') } } result.append(text).append('\n') } } private fun generateIconFieldName(file: Path): CharSequence { val imageFileName = file.fileName.toString() val path = file.toString() when { path.contains("$androidIcons/icons") -> { return toCamelCaseJavaIdentifier(imageFileName, imageFileName.lastIndexOf('.')) } path.contains("$androidIcons") -> { return toStreamingSnakeCaseJavaIdentifier(imageFileName, imageFileName.lastIndexOf('.')) } else -> { val id = if ((imageFileName.length - 4) == 2) { imageFileName.uppercase(Locale.ENGLISH) } else { imageFileName.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.ENGLISH) else it.toString() } } return toJavaIdentifier(id = id, endIndex = imageFileName.lastIndexOf('.')) } } } private fun getImageId(image: ImageInfo, depth: Int): String { val path = image.id.removePrefix("/").split("/") if (path.size < depth) { throw IllegalArgumentException("Can't get image id - ${image.id}, $depth") } return path.drop(depth).joinToString("/") } private fun directoryName(module: JpsModule): CharSequence { return directoryNameFromConfig(module) ?: className(module.name) } private fun directoryNameFromConfig(module: JpsModule): String? { val rootUrl = getFirstContentRootUrl(module) ?: return null val rootDir = Paths.get(JpsPathUtil.urlToPath(rootUrl)) val file = rootDir.resolve(ROBOTS_FILE_NAME) val prefix = "name:" try { Files.lines(file).use { lines -> for (line in lines) { if (line.startsWith(prefix)) { val name = line.substring(prefix.length).trim() if (name.isNotEmpty()) { return name } } } } } catch (ignore: NoSuchFileException) { } return null } private fun getFirstContentRootUrl(module: JpsModule) = module.contentRootsList.urls.firstOrNull() private fun className(name: String): CharSequence { val result = StringBuilder(name.length) name.removePrefix("intellij.vcs.").removePrefix("intellij.").split('-', '_', '.').forEach { result.append(capitalize(it)) } return toJavaIdentifier(result, result.length) } private fun toJavaIdentifier(id: CharSequence, endIndex: Int): CharSequence { var sb: StringBuilder? = null var index = 0 while (index < endIndex) { val c = id[index] if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) { sb?.append(c) } else { if (sb == null) { sb = StringBuilder(endIndex) sb.append(id, 0, index) } if (c == '-') { index++ if (index == endIndex) { break } sb.append(id[index].uppercaseChar()) } else { sb.append('_') } } index++ } return sb ?: id.subSequence(0, endIndex) } private fun toStreamingSnakeCaseJavaIdentifier(id: String, endIndex: Int): CharSequence { val sb = StringBuilder(endIndex) var index = 0 while (index < endIndex) { val c = id[index] if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) { sb.append(c.uppercaseChar()) } else { sb.append('_') } index++ } return sb } private fun toCamelCaseJavaIdentifier(id: String, endIndex: Int): CharSequence { val sb = StringBuilder(endIndex) var index = 0 var upperCase = true while (index < endIndex) { val c = id[index] if (c == '_' || c == '-') { upperCase = true } else if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) { if (upperCase) { sb.append(c.uppercaseChar()) upperCase = false } else { sb.append(c) } } else { sb.append('_') } index++ } return sb } private fun capitalize(name: String): String { return if (name.length == 2) name.uppercase(Locale.ENGLISH) else name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } } private const val iconLoaderCode = "IconManager.getInstance()" // grid-layout.svg duplicates grid-view.svg, but grid-layout_dark.svg differs from grid-view_dark.svg // so, add filename to image id to support such scenario internal fun getImageKey(fileData: ByteArray, fileName: String): Int { val h = Murmur3_32Hash.Murmur3_32Hasher(0) h.putBytes(fileData, 0, fileData.size) h.putString(fileName) return h.hash() } // remove line separators to unify line separators (\n vs \r\n), trim lines // normalization is required because cache key is based on content internal fun loadAndNormalizeSvgFile(svgFile: Path): String { val builder = StringBuilder() Files.lines(svgFile).use { lines -> for (line in lines) { for (start in line.indices) { if (line[start].isWhitespace()) { continue } var end = line.length for (j in (line.length - 1) downTo (start + 1)) { if (!line[j].isWhitespace()) { end = j + 1 break } } builder.append(line, start, end) // if tag is not closed, space must be added to ensure that code on next line is separated from previous line of code if (builder[end - 1] != '>') { builder.append(' ') } break } } } return builder.toString() } private fun getPluginPackageIfPossible(module: JpsModule): String? { for (resourceRoot in module.getSourceRoots(JavaResourceRootType.RESOURCE)) { val root = Path.of(JpsPathUtil.urlToPath(resourceRoot.url)) var pluginXml = root.resolve("META-INF/plugin.xml") if (!Files.exists(pluginXml)) { // ok, any xml file pluginXml = Files.newDirectoryStream(root).use { files -> files.find { it.toString().endsWith(".xml") } } ?: break } try { return readXmlAsModel(Files.newInputStream(pluginXml)).getAttributeValue("package") ?: "icons" } catch (ignore: NoSuchFileException) { } catch (ignore: XMLStreamException) { // ignore invalid XML } } return null }
apache-2.0
4d5209953e79ff034390c72f419df474
34.851429
168
0.652321
4.392613
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/host/WritePerson.kt
1
800
package arcs.core.host import java.lang.IllegalArgumentException import kotlinx.coroutines.CompletableDeferred open class WritePerson : AbstractWritePerson() { var wrote = false var firstStartCalled = false var shutdownCalled = false var deferred = CompletableDeferred<Boolean>() override fun onFirstStart() { firstStartCalled = true if (throws) { throw IllegalArgumentException("Boom!") } } override fun onReady() { handles.person.store(WritePerson_Person("John Wick")) wrote = true if (!deferred.isCompleted) { deferred.complete(true) } } override fun onShutdown() { shutdownCalled = true } suspend fun await() { deferred.await() } companion object { var throws = false } } class WritePerson2 : WritePerson()
bsd-3-clause
eff1a10d4899cebcda1eb2e71a93ebe4
18.512195
57
0.69125
4.494382
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/math/Rotation.kt
1
1181
/* * Copyright 2020 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.acornui.math inline class Rotation(private val value: String) { override fun toString(): String = value } val Double.deg: Rotation get() = Rotation("${this}deg") val Double.rad: Rotation get() = Rotation("${this}rad") val Double.grad: Rotation get() = Rotation("${this}grad") val Double.turn: Rotation get() = Rotation("${this}turn") val Int.deg: Rotation get() = Rotation("${this}deg") val Int.rad: Rotation get() = Rotation("${this}rad") val Int.grad: Rotation get() = Rotation("${this}grad") val Int.turn: Rotation get() = Rotation("${this}turn")
apache-2.0
a6921dfd7b76c913a4b97d2ffb2628a0
25.244444
75
0.705334
3.611621
false
false
false
false
sys1yagi/counterpoint-validator
base/src/main/java/com/sys1yagi/counterpoint/Interval.kt
1
1576
package com.sys1yagi.counterpoint class Interval(val base: Pitch, val counter: Pitch) { companion object{ const val INTERVAL_MAJOR_3TH = 4 const val INTERVAL_PERFECT_4TH = 5 const val INTERVAL_PERFECT_5TH = 7 const val INTERVAL_MAJOR_6TH = 9 const val INTERVAL_MINOR_6TH = 8 const val INTERVAL_PERFECT_8TH = 12 fun create(base:String, counter:String) = Interval( PitchConverter.stringToPitch(base), PitchConverter.stringToPitch(counter) ) } // intervale memo // Perfect 4th 5 // Perfect 5th 7 enum class Type { Consonance, Dissonance } val type: Type by lazy { when (normalizationIntervalInt) { 0, INTERVAL_MAJOR_3TH, INTERVAL_PERFECT_5TH, INTERVAL_MAJOR_6TH -> { Type.Consonance } else -> { Type.Dissonance } } } val normalizationIntervalInt by lazy { intervalInt % 12 } val intervalInt by lazy { val basePos = base.pos() val counterPos = counter.pos() Math.abs(basePos - counterPos) } val isPerfect4th by lazy { normalizationIntervalInt == INTERVAL_PERFECT_4TH } val isPerfect5th by lazy { normalizationIntervalInt == INTERVAL_PERFECT_5TH } val isPerfect8th by lazy { normalizationIntervalInt == 0 } override fun toString(): String { return "${base.name}${base.level}, ${counter.name}${counter.level}" } }
mit
3ecb3ce6f23bda643ec7e7ec359d0c5f
23.261538
80
0.581218
4.072351
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/accounts/HelpViewModel.kt
1
1431
package org.wordpress.android.ui.accounts import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.wordpress.android.WordPress import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import org.wordpress.android.viewmodel.SingleLiveEvent import javax.inject.Inject import javax.inject.Named @HiltViewModel class HelpViewModel @Inject constructor( @Named(UI_THREAD) mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher, ) : ScopedViewModel(mainDispatcher) { private val _showSigningOutDialog = MutableLiveData<Event<Boolean>>() val showSigningOutDialog: LiveData<Event<Boolean>> = _showSigningOutDialog private val _onSignOutCompleted = SingleLiveEvent<Unit>() val onSignOutCompleted: LiveData<Unit> = _onSignOutCompleted fun signOutWordPress(application: WordPress) { launch { _showSigningOutDialog.value = Event(true) withContext(bgDispatcher) { application.wordPressComSignOut() } _showSigningOutDialog.value = Event(false) _onSignOutCompleted.call() } } }
gpl-2.0
04cdb4322d8122d2e44da206d4af7c23
36.657895
78
0.767994
4.631068
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/contributors/FirPackageCompletionContributor.kt
2
1983
// 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.completion.contributors import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.symbols.KtPackageSymbol import org.jetbrains.kotlin.base.analysis.isExcludedFromAutoImport import org.jetbrains.kotlin.idea.completion.context.FirBasicCompletionContext import org.jetbrains.kotlin.idea.completion.context.FirNameReferencePositionContext import org.jetbrains.kotlin.idea.completion.context.FirRawPositionCompletionContext import org.jetbrains.kotlin.idea.completion.weighers.Weighers import org.jetbrains.kotlin.idea.completion.weighers.WeighingContext.Companion.createEmptyWeighingContext internal class FirPackageCompletionContributor( basicContext: FirBasicCompletionContext, priority: Int, ) : FirCompletionContributorBase<FirRawPositionCompletionContext>(basicContext, priority) { override fun KtAnalysisSession.complete(positionContext: FirRawPositionCompletionContext) { val rootSymbol = if (positionContext !is FirNameReferencePositionContext || positionContext.explicitReceiver == null) { ROOT_PACKAGE_SYMBOL } else { positionContext.explicitReceiver?.reference()?.resolveToSymbol() as? KtPackageSymbol } ?: return val weighingContext = createEmptyWeighingContext(basicContext.fakeKtFile) rootSymbol.getPackageScope() .getPackageSymbols(scopeNameFilter) .filterNot { it.fqName.isExcludedFromAutoImport(project, originalKtFile) } .forEach { packageSymbol -> val element = lookupElementFactory.createPackagePartLookupElement(packageSymbol.fqName) with(Weighers) { applyWeighsToLookupElement(weighingContext, element, packageSymbol) } sink.addElement(element) } } }
apache-2.0
587e1f47c0630fa65484b4c1842be67f
55.685714
158
0.778114
4.969925
false
false
false
false
MER-GROUP/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/ExecutionStackImpl.kt
3
3152
/* * Copyright 2000-2015 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.debugger.frame import com.intellij.xdebugger.frame.XExecutionStack import com.intellij.xdebugger.frame.XStackFrame import com.intellij.xdebugger.settings.XDebuggerSettingsManager import org.jetbrains.debugger.* import java.util.* internal class ExecutionStackImpl(private val suspendContext: SuspendContext<out CallFrame>, private val viewSupport: DebuggerViewSupport, private val topFrameScript: Script?, private val topFrameSourceInfo: SourceInfo? = null) : XExecutionStack("") { private var topCallFrameView: CallFrameView? = null override fun getTopFrame(): CallFrameView? { val topCallFrame = suspendContext.topFrame if (topCallFrameView == null || topCallFrameView!!.callFrame != topCallFrame) { topCallFrameView = if (topCallFrame == null) null else CallFrameView(topCallFrame, viewSupport, topFrameScript, topFrameSourceInfo) } return topCallFrameView } override fun computeStackFrames(firstFrameIndex: Int, container: XExecutionStack.XStackFrameContainer) { val suspendContext = viewSupport.vm!!.suspendContextManager.context ?: return // WipSuspendContextManager set context to null on resume _before_ vm.getDebugListener().resumed() call() (in any case, XFramesView can queue event to EDT), so, IDE state could be outdated compare to VM (our) state suspendContext.frames .done(suspendContext) { frames -> val count = frames.size - firstFrameIndex val result: List<XStackFrame> if (count < 1) { result = emptyList() } else { result = ArrayList<XStackFrame>(count) for (i in firstFrameIndex..frames.size - 1) { if (i == 0) { result.add(topFrame!!) continue } val frame = frames[i] // if script is null, it is native function (Object.forEach for example), so, skip it val script = viewSupport.vm?.scriptManager?.getScript(frame) if (script != null) { val sourceInfo = viewSupport.getSourceInfo(script, frame) val isInLibraryContent = sourceInfo != null && viewSupport.isInLibraryContent(sourceInfo, script) if (isInLibraryContent && !XDebuggerSettingsManager.getInstance().dataViewSettings.isShowLibraryStackFrames) { continue } result.add(CallFrameView(frame, viewSupport, script, sourceInfo, isInLibraryContent)) } } } container.addStackFrames(result, true) } } }
apache-2.0
96ba1501d66d9f6f932fb7f04086ef50
44.042857
251
0.695431
4.902022
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/players/PlayersFragment.kt
3
2952
package dev.mfazio.abl.players import android.os.Bundle import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.navArgs import androidx.paging.ExperimentalPagingApi import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import dev.mfazio.abl.databinding.FragmentPlayersBinding import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @ExperimentalPagingApi class PlayersFragment : Fragment() { private val playerListArgs: PlayersFragmentArgs by navArgs() private val playersListViewModel by activityViewModels<PlayerListViewModel>() private lateinit var playersAdapter: PlayersAdapter private var currentJob: Job? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentPlayersBinding.inflate(inflater) this.playersAdapter = PlayersAdapter() with(binding.playersList) { adapter = playersAdapter addItemDecoration( DividerItemDecoration( context, LinearLayoutManager.VERTICAL ) ) } with(binding.playerSearchBoxText) { setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_GO) { searchPlayers(text.toString().trim()) true } else { false } } setOnKeyListener { _, keyCode, event -> if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER ) { searchPlayers(text.toString().trim()) true } else { false } } } binding.playerSearchBox.setEndIconOnClickListener { binding.playerSearchBoxText.text?.let { text -> text.clear() searchPlayers() } } searchPlayers() return binding.root } private fun searchPlayers(nameQuery: String? = null) { currentJob?.cancel() currentJob = lifecycleScope.launch { playersListViewModel .getPlayerListItems(playerListArgs.teamId, nameQuery) .collectLatest { playerListItems -> if (::playersAdapter.isInitialized) { playersAdapter.submitData(playerListItems) } } } } }
apache-2.0
e64b74d78d75baf20413c6894380bb21
30.084211
93
0.613144
5.666027
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/redux/StateStore.kt
1
7161
package io.ipoli.android.common.redux import io.ipoli.android.common.UiAction import kotlinx.coroutines.experimental.CoroutineDispatcher import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.GlobalScope import kotlinx.coroutines.experimental.channels.Channel import kotlinx.coroutines.experimental.channels.actor import kotlinx.coroutines.experimental.launch import java.util.concurrent.CopyOnWriteArraySet /** * Created by Venelin Valkov <[email protected]> * on 01/20/2018. */ interface Action { fun toMap() = emptyMap<String, Any?>() } interface State interface SideEffectHandler<in S : State> { fun onCreate() {} suspend fun execute(action: Action, state: S, dispatcher: Dispatcher) fun canHandle(action: Action): Boolean } interface SideEffectHandlerExecutor<S : CompositeState<S>> { fun execute( sideEffectHandler: SideEffectHandler<S>, action: Action, state: S, dispatcher: Dispatcher ) } class CoroutineSideEffectHandlerExecutor<S : CompositeState<S>> : SideEffectHandlerExecutor<S> { override fun execute( sideEffectHandler: SideEffectHandler<S>, action: Action, state: S, dispatcher: Dispatcher ) { GlobalScope.launch(Dispatchers.IO) { sideEffectHandler.execute(action, state, dispatcher) } } } abstract class CompositeState<T>( private val stateData: Map<String, State> ) : State where T : CompositeState<T> { fun <S> stateFor(key: Class<S>): S { return stateFor(key.simpleName) } fun <S> stateFor(key: String): S { require(stateData.containsKey(key)) val data = stateData[key] @Suppress("unchecked_cast") return data as S } fun <S> hasState(key: Class<S>): Boolean = hasState(key.simpleName) fun hasState(key: String): Boolean = stateData.containsKey(key) fun update(stateKey: String, newState: State) = createWithData(stateData.plus(Pair(stateKey, newState))) fun update(stateData: Map<String, State>) = createWithData(stateData.plus(stateData)) fun remove(stateKey: String) = createWithData(stateData.minus(stateKey)) val keys = stateData.keys protected abstract fun createWithData(stateData: Map<String, State>): T } interface Reducer<AS : CompositeState<AS>, S : State> { fun reduce(state: AS, action: Action) = reduce(state, state.stateFor(stateKey), action) fun reduce(state: AS, subState: S, action: Action): S fun defaultState(): S val stateKey: String } interface ViewStateReducer<S : CompositeState<S>, VS : ViewState> : Reducer<S, VS> interface Dispatcher { fun <A : Action> dispatch(action: A) } class StateStore<S : CompositeState<S>>( initialState: S, reducers: Set<Reducer<S, *>>, sideEffectHandlers: Set<SideEffectHandler<S>> = setOf(), private val sideEffectHandlerExecutor: SideEffectHandlerExecutor<S>, middleware: List<MiddleWare<S>> = emptyList(), private val coroutineDispatcher: CoroutineDispatcher = Dispatchers.IO ) : Dispatcher { interface StateChangeSubscriber<in S> { suspend fun onStateChanged(newState: S) } private val middleWare = CompositeMiddleware(middleware) private val reducer = CompositeReducer() private val sideEffectHandlers = CopyOnWriteArraySet<SideEffectHandler<S>>(sideEffectHandlers) private val reducers = CopyOnWriteArraySet<Reducer<S, *>>(reducers) private val stateChangeSubscribers = CopyOnWriteArraySet<StateChangeSubscriber<S>>() private val stateActor = createStateActor() private var state = initialState @Volatile private var isInit: Boolean = false fun addSideEffectHandler(handler: SideEffectHandler<S>) { handler.onCreate() sideEffectHandlers.add(handler) } fun removeSideEffectHandler(handler: SideEffectHandler<S>) { sideEffectHandlers.remove(handler) } private fun createStateActor() = GlobalScope.actor<Action>(coroutineDispatcher, capacity = Channel.UNLIMITED) { for (action in channel) { val res = executeMiddleware(state, action) if (res == MiddleWare.Result.Continue) { state = applyReducers(state, action) notifyStateChanged(state) executeSideEffects(action, state) } } } private fun applyReducers(state: S, action: Action) = reducer.reduce(state, action) private fun executeMiddleware( state: S, action: Action ) = middleWare.execute(state, this, action) override fun <A : Action> dispatch(action: A) { if (!isInit) { for (se in sideEffectHandlers) { se.onCreate() } middleWare.onCreate() isInit = true } stateActor.offer(action) } private fun executeSideEffects(action: Action, newState: S) { sideEffectHandlers .filter { it.canHandle(action) } .forEach { sideEffectHandlerExecutor.execute(it, action, newState, this) } } private suspend fun notifyStateChanged(newState: S) { stateChangeSubscribers.forEach { it.onStateChanged(newState) } } fun subscribe(subscriber: StateChangeSubscriber<S>) { stateChangeSubscribers.add(subscriber) } fun unsubscribe(subscriber: StateChangeSubscriber<S>) { stateChangeSubscribers.remove(subscriber) } inner class CompositeReducer { fun reduce(state: S, action: Action): S { if (action is UiAction.Attach<*>) { val stateKey = action.reducer.stateKey require( !state.keys.contains(stateKey) ) { "Key $stateKey is already added to the state?!" } val reducer = action.reducer @Suppress("UNCHECKED_CAST") reducers.add(reducer as ViewStateReducer<S, *>) return state.update(stateKey, reducer.defaultState()) } if (action is UiAction.Detach<*>) { val stateKey = action.reducer.stateKey @Suppress("UNCHECKED_CAST") val reducer = action.reducer as ViewStateReducer<S, *> require( reducers.contains(reducer) ) { "Reducer $reducer not found in state reducers" } require( state.keys.contains(stateKey) ) { "State with key $stateKey not found in state" } reducers.remove(reducer) return state.remove(stateKey) } val stateToReducer = reducers.map { it.stateKey to it }.toMap() val newState = state.keys.map { val reducer = stateToReducer[it]!! val subState = reducer.reduce(state, action) it to subState }.toMap() return state.update(newState) } } }
gpl-3.0
2b1329d88209069b1f9a6ec2d2ae349a
29.219409
98
0.631616
4.552448
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/planday/PlanDayViewController.kt
1
17663
package io.ipoli.android.planday import android.Manifest import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bluelinelabs.conductor.Controller import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import io.ipoli.android.Constants import io.ipoli.android.R import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.DataLoadedAction import io.ipoli.android.common.datetime.Duration import io.ipoli.android.common.datetime.Minute import io.ipoli.android.common.datetime.Time import io.ipoli.android.common.datetime.TimeOfDay import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.text.DateFormatter import io.ipoli.android.common.view.enterFullScreen import io.ipoli.android.common.view.exitFullScreen import io.ipoli.android.common.view.inflate import io.ipoli.android.dailychallenge.data.DailyChallenge import io.ipoli.android.pet.PetAvatar import io.ipoli.android.planday.PlanDayViewController.Companion.PLAN_TODAY_INDEX import io.ipoli.android.planday.PlanDayViewState.StateType.* import io.ipoli.android.planday.data.Weather import io.ipoli.android.planday.persistence.Quote import io.ipoli.android.planday.scenes.PlanDayMotivationViewController import io.ipoli.android.planday.scenes.PlanDayTodayViewController import io.ipoli.android.player.data.Player import io.ipoli.android.quest.Quest import kotlinx.android.synthetic.main.controller_plan_day.view.* import org.threeten.bp.LocalDate import org.threeten.bp.format.TextStyle import java.util.* sealed class PlanDayAction : Action { data class RemoveQuest(val questId: String) : PlanDayAction() { override fun toMap() = mapOf("questId" to questId) } data class UndoRemoveQuest(val questId: String) : PlanDayAction() { override fun toMap() = mapOf("questId" to questId) } data class RescheduleQuest( val questId: String, val date: LocalDate?, val time: Time?, val duration: Duration<Minute>? ) : PlanDayAction() { override fun toMap() = mapOf( "questId" to questId, "date" to date, "time" to time, "duration" to duration?.intValue ) } data class AcceptSuggestion(val questId: String) : PlanDayAction() { override fun toMap() = mapOf("questId" to questId) } data class AddDailyChallengeQuest(val questId: String) : PlanDayAction() { override fun toMap() = mapOf("questId" to questId) } data class RemoveDailyChallengeQuest(val questId: String) : PlanDayAction() { override fun toMap() = mapOf("questId" to questId) } data class DailyChallengeLoaded(val dailyChallenge: DailyChallenge) : PlanDayAction() { override fun toMap() = mapOf("dailyChallenge" to dailyChallenge) } data class MoveBucketListQuestsToToday(val quests: List<Quest>) : PlanDayAction() object Load : PlanDayAction() object ShowNext : PlanDayAction() object GetWeather : PlanDayAction() object ImageLoaded : PlanDayAction() object RisingSunAnimationDone : PlanDayAction() object Done : PlanDayAction() object Back : PlanDayAction() object LoadToday : PlanDayAction() object LoadMotivation : PlanDayAction() object StartDay : PlanDayAction() } object PlanDayReducer : BaseViewStateReducer<PlanDayViewState>() { override fun reduce( state: AppState, subState: PlanDayViewState, action: Action ) = when (action) { is PlanDayAction.Load -> { val today = LocalDate.now() val weekDayText = today.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()) val player = state.dataState.player val playerName = player?.let { it.displayName?.let { n -> firstNameOf(n) } } subState.copy( type = FIRST_PAGE, playerName = playerName, dateText = "$weekDayText, ${DateFormatter.formatDayWithWeek(today)}", petAvatar = player?.pet?.avatar ?: subState.petAvatar, timeFormat = player?.preferences?.timeFormat ?: subState.timeFormat, temperatureUnit = player?.preferences?.temperatureUnit ?: subState.temperatureUnit, todayQuests = state.dataState.todayQuests ) } is PlanDayAction.ShowNext -> { if (subState.adapterPosition + 1 > PLAN_TODAY_INDEX) subState else subState.copy( type = PlanDayViewState.StateType.NEXT_PAGE, adapterPosition = subState.adapterPosition + 1 ) } is DataLoadedAction.PlayerChanged -> { val player = action.player subState.copy( type = DATA_CHANGED, playerName = player.displayName?.let { firstNameOf(it) }, petAvatar = player.pet.avatar, timeFormat = player.preferences.timeFormat, temperatureUnit = player.preferences.temperatureUnit ) } is PlanDayAction.LoadMotivation -> createNewStateIfMotivationalDataIsLoaded(subState) is DataLoadedAction.TodayQuestsChanged -> { val newState = subState.copy( type = DATA_CHANGED, todayQuests = action.quests ) createNewStateIfTodayDataIsLoaded(newState) } is DataLoadedAction.SuggestionsChanged -> { val newState = subState.copy( type = DATA_CHANGED, suggestedQuests = action.quests ) createNewStateIfTodayDataIsLoaded(newState) } is PlanDayAction.DailyChallengeLoaded -> createNewStateIfTodayDataIsLoaded( subState.copy( dailyChallengeQuestIds = action.dailyChallenge.questIds, isDailyChallengeCompleted = action.dailyChallenge.isCompleted ) ) is PlanDayAction.AcceptSuggestion -> { val suggestion = subState.suggestedQuests!!.first { it.id == action.questId } val newState = subState.copy( type = DATA_CHANGED, suggestedQuests = subState.suggestedQuests - suggestion ) createNewStateIfTodayDataIsLoaded(newState) } is DataLoadedAction.QuoteChanged -> { val newState = subState.copy( type = DATA_CHANGED, quote = action.quote, quoteLoaded = true ) createNewStateIfMotivationalDataIsLoaded(newState) } is DataLoadedAction.WeatherChanged -> { val newState = action.weather?.let { val conditions = it.conditions if (conditions.contains(Weather.Condition.UNKNOWN)) subState.copy( type = DATA_CHANGED, weatherLoaded = true ) else subState.copy( type = DATA_CHANGED, weather = action.weather, weatherLoaded = true ) } ?: subState.copy( type = DATA_CHANGED, weatherLoaded = true ) createNewStateIfMotivationalDataIsLoaded(newState) } is DataLoadedAction.MotivationalImageChanged -> { val newState = action.motivationalImage?.let { subState.copy( type = IMAGE_LOADED, imageUrl = it.url + "&fm=jpg&w=1080&crop=entropy&fit=max&q=40", imageAuthor = it.author, imageAuthorUrl = it.authorUrl, imageLoaded = true ) } ?: subState.copy( type = IMAGE_LOADED, imageAuthor = "Daniel Roe", imageAuthorUrl = "https://unsplash.com/@danielroe", imageLoaded = true ) createNewStateIfMotivationalDataIsLoaded(newState) } is PlanDayAction.ImageLoaded -> { val newState = subState.copy( type = DATA_CHANGED, imageViewLoaded = true ) createNewStateIfMotivationalDataIsLoaded(newState) } is PlanDayAction.RisingSunAnimationDone -> { val newState = subState.copy( type = DATA_CHANGED, risingSunAnimationDone = true ) createNewStateIfMotivationalDataIsLoaded(newState) } is PlanDayAction.LoadToday -> { createNewStateIfTodayDataIsLoaded( subState.copy( type = DATA_CHANGED ) ) } is PlanDayAction.Back -> if (subState.adapterPosition == 1) subState.copy( adapterPosition = 0 ) else subState.copy( type = CLOSE ) is PlanDayAction.AddDailyChallengeQuest -> { if (subState.dailyChallengeQuestIds!!.size == Constants.DAILY_CHALLENGE_QUEST_COUNT) { subState.copy( type = MAX_DAILY_CHALLENGE_QUESTS_REACHED ) } else { subState.copy( type = DAILY_CHALLENGE_QUESTS_CHANGED, dailyChallengeQuestIds = subState.dailyChallengeQuestIds + action.questId ) } } is PlanDayAction.RemoveDailyChallengeQuest -> subState.copy( type = DAILY_CHALLENGE_QUESTS_CHANGED, dailyChallengeQuestIds = subState.dailyChallengeQuestIds!! - action.questId ) PlanDayAction.StartDay -> { val count = subState.dailyChallengeQuestIds!!.size subState.copy( type = if (count == 0 || count == Constants.DAILY_CHALLENGE_QUEST_COUNT) { DAY_STARTED } else { NOT_ENOUGH_DAILY_CHALLENGE_QUESTS } ) } else -> subState } private fun firstNameOf(displayName: String) = if (displayName.isBlank()) null else displayName.split(" ")[0].capitalize() private fun createNewStateIfMotivationalDataIsLoaded(newState: PlanDayViewState) = if (hasMotivationalDataLoaded(newState)) if (newState.hasShownMotivationalData) newState.copy( type = SHOW_MOTIVATION_DATA ) else newState.copy( type = MOTIVATION_DATA_LOADED, timeOfDay = Time.now().timeOfDay, hasShownMotivationalData = true ) else newState private fun hasMotivationalDataLoaded(state: PlanDayViewState) = state.weatherLoaded && state.quoteLoaded && state.imageLoaded && state.imageViewLoaded && state.risingSunAnimationDone private fun createNewStateIfTodayDataIsLoaded(newState: PlanDayViewState) = if (hasTodayDataLoaded(newState)) newState.copy( type = TODAY_DATA_LOADED ) else newState private fun hasTodayDataLoaded(state: PlanDayViewState) = state.todayQuests != null && state.suggestedQuests != null override fun defaultState() = PlanDayViewState( type = INITIAL, dateText = null, imageUrl = null, imageAuthor = "", imageAuthorUrl = "", quote = null, todayQuests = null, dailyChallengeQuestIds = emptyList(), isDailyChallengeCompleted = false, suggestedQuests = null, adapterPosition = 0, playerName = null, weather = null, timeOfDay = null, weatherLoaded = false, quoteLoaded = false, imageLoaded = false, imageViewLoaded = false, hasShownMotivationalData = false, risingSunAnimationDone = false, petAvatar = null, temperatureUnit = Constants.DEFAULT_TEMPERATURE_UNIT, timeFormat = Constants.DEFAULT_TIME_FORMAT ) override val stateKey = key<PlanDayViewState>() } data class PlanDayViewState( val type: StateType, val dateText: String?, val imageUrl: String?, val imageAuthor: String, val imageAuthorUrl: String, val weather: Weather?, val quote: Quote?, val todayQuests: List<Quest>?, val suggestedQuests: List<Quest>?, val dailyChallengeQuestIds: List<String>?, val isDailyChallengeCompleted: Boolean, val adapterPosition: Int, val timeOfDay: TimeOfDay?, val playerName: String?, val weatherLoaded: Boolean, val quoteLoaded: Boolean, val imageLoaded: Boolean, val imageViewLoaded: Boolean, val hasShownMotivationalData: Boolean, val risingSunAnimationDone: Boolean, val petAvatar: PetAvatar?, val temperatureUnit: Player.Preferences.TemperatureUnit, val timeFormat: Player.Preferences.TimeFormat ) : BaseViewState() { enum class StateType { INITIAL, FIRST_PAGE, NEXT_PAGE, CLOSE, DATA_CHANGED, IMAGE_LOADED, MOTIVATION_DATA_LOADED, SHOW_MOTIVATION_DATA, TODAY_DATA_LOADED, MAX_DAILY_CHALLENGE_QUESTS_REACHED, DAILY_CHALLENGE_QUESTS_CHANGED, DAY_STARTED, NOT_ENOUGH_DAILY_CHALLENGE_QUESTS } } class PlanDayViewController(args: Bundle? = null) : ReduxViewController<PlanDayAction, PlanDayViewState, PlanDayReducer>(args) { override val reducer = PlanDayReducer override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { requestPermissions( mapOf(Manifest.permission.ACCESS_FINE_LOCATION to "If you want to see the weather, please give myPoli permission for your location"), Constants.RC_LOCATION_PERM ) return container.inflate(R.layout.controller_plan_day) } override fun onCreateLoadAction() = PlanDayAction.Load override fun onPermissionsGranted(requestCode: Int, permissions: List<String>) { enterFullScreen() dispatch(PlanDayAction.GetWeather) } override fun onPermissionsDenied(requestCode: Int, permissions: List<String>) { enterFullScreen() dispatch(PlanDayAction.GetWeather) } override fun handleBack(): Boolean { dispatch(PlanDayAction.Back) return true } override fun render(state: PlanDayViewState, view: View) { when (state.type) { FIRST_PAGE -> changeChildController( view = view, adapterPosition = state.adapterPosition, animate = false ) NEXT_PAGE -> changeChildController( view = view, adapterPosition = state.adapterPosition, animate = true ) CLOSE -> { exitFullScreen() navigateFromRoot().setHome() } else -> { } } } private fun changeChildController( view: View, adapterPosition: Int, animate: Boolean = true ) { val childRouter = getChildRouter(view.planDayPager) val changeHandler = if (animate) HorizontalChangeHandler() else null val transaction = RouterTransaction.with( createControllerForPosition(adapterPosition) ) .popChangeHandler(changeHandler) .pushChangeHandler(changeHandler) childRouter.pushController(transaction) } private fun createControllerForPosition(position: Int): Controller = when (position) { MOTIVATION_INDEX -> PlanDayMotivationViewController() PLAN_TODAY_INDEX -> PlanDayTodayViewController() else -> throw IllegalArgumentException("Unknown controller position $position") } companion object { const val MOTIVATION_INDEX = 0 const val PLAN_TODAY_INDEX = 1 } }
gpl-3.0
e00745b657322051abfc82c3e2035ff6
33.840237
145
0.573459
5.365431
false
false
false
false
AberrantFox/hotbot
src/main/kotlin/me/aberrantfox/hotbot/database/InfractionTransactions.kt
1
2549
package me.aberrantfox.hotbot.database import org.jetbrains.exposed.sql.Op import org.jetbrains.exposed.sql.deleteWhere import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.transactions.transaction import org.joda.time.DateTime data class StrikeRecord(val id: Int, val moderator: String, val member: String, val strikes: Int, val reason: String, val dateTime: DateTime, val isExpired: Boolean) fun insertInfraction(member: String, moderator: String, strikes: Int, reason: String) = transaction { Strikes.insert { it[Strikes.member] = member it[Strikes.moderator] = moderator it[Strikes.strikes] = strikes it[Strikes.reason] = reason it[date] = DateTime.now() } } fun getHistory(userId: String): List<StrikeRecord> = transaction { val select = Strikes.select { Op.build { Strikes.member eq userId } } val records = mutableListOf<StrikeRecord>() select.forEach { records.add(StrikeRecord( it[Strikes.id], it[Strikes.moderator], it[Strikes.member], it[Strikes.strikes], it[Strikes.reason], it[Strikes.date], isExpired(it[Strikes.id]))) } records } fun removeInfraction(infractionID: Int): Int = transaction { val amountDeleted = Strikes.deleteWhere { Op.build { Strikes.id eq infractionID } } amountDeleted } fun removeAllInfractions(userId: String): Int = transaction { val amountDeleted = Strikes.deleteWhere { Op.build { Strikes.member eq userId } } amountDeleted } fun isExpired(infractionID: Int): Boolean = transaction { val rows = Strikes.select { Op.build { Strikes.id eq infractionID } } val date = rows.first()[Strikes.date] DateTime.now().isAfter(date.plusDays(30)) } fun getMaxStrikes(userId: String) = getHistory(userId) .filter { !it.isExpired } .map { it.strikes } .sum()
mit
7ab166d63f3668ec0b33e20e419e3273
30.097561
87
0.526481
4.864504
false
false
false
false
GunoH/intellij-community
platform/webSymbols/src/com/intellij/webSymbols/completion/AsteriskAwarePrefixMatcher.kt
2
2179
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.webSymbols.completion import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.codeInsight.completion.impl.CamelHumpMatcher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementBuilder class AsteriskAwarePrefixMatcher private constructor(prefix: String, delegate: PrefixMatcher) : PrefixMatcher(prefix) { private val myDelegate: PrefixMatcher constructor(delegate: PrefixMatcher) : this(delegate.prefix, delegate) {} init { myDelegate = delegate.cloneWithPrefix(convert(prefix, true)) } override fun prefixMatches(name: String): Boolean = myDelegate.prefixMatches(convert(name)) override fun prefixMatches(element: LookupElement): Boolean = myDelegate.prefixMatches(convert(element)) override fun isStartMatch(name: String): Boolean = myDelegate.isStartMatch(convert(name)) override fun isStartMatch(element: LookupElement): Boolean = myDelegate.isStartMatch(convert(element)) override fun matchingDegree(string: String): Int = myDelegate.matchingDegree(convert(string)) override fun cloneWithPrefix(prefix: String): PrefixMatcher = if (prefix == myPrefix) this else AsteriskAwarePrefixMatcher(prefix, myDelegate) companion object { private const val ASTERISK = '*' private const val ASTERISK_REPLACEMENT = '⭐' private fun convert(element: LookupElement): LookupElement = LookupElementBuilder.create(convert(element.lookupString)) .withCaseSensitivity(element.isCaseSensitive) .withLookupStrings(element.allLookupStrings.mapTo(mutableSetOf()) { convert(it) }) private fun convert(input: String, forPattern: Boolean = false): String = if (input.isNotEmpty() && input[0] == ASTERISK) { if (forPattern) { ASTERISK_REPLACEMENT + CamelHumpMatcher.applyMiddleMatching(input.substring(1)) } else { val chars = input.toCharArray() chars[0] = ASTERISK_REPLACEMENT String(chars) } } else input } }
apache-2.0
1b1eb6b05123918d2095903e6cae84e2
40.865385
120
0.74644
4.641791
false
false
false
false
adelnizamutdinov/kotlin-either
src/main/kotlin/either/Either.kt
1
602
package either sealed class Either<out L, out R> { data class Left<out T>(val value: T) : Either<T, Nothing>() data class Right<out T>(val value: T) : Either<Nothing, T>() } inline fun <L, R, T> Either<L, R>.fold(left: (L) -> T, right: (R) -> T): T = when (this) { is Either.Left -> left(value) is Either.Right -> right(value) } inline fun <L, R, T> Either<L, R>.flatMap(f: (R) -> Either<L, T>): Either<L, T> = fold(left = { this as Either.Left }, right = f) inline fun <L, R, T> Either<L, R>.map(f: (R) -> T): Either<L, T> = flatMap { Either.Right(f(it)) }
mit
582a0a1ef88cab759b89ce251596ce45
32.444444
81
0.563123
2.699552
false
false
false
false
abertschi/ad-free
app/src/main/java/ch/abertschi/adfree/detector/SpotifyLiteDebugTracer.kt
1
646
package ch.abertschi.adfree.detector import org.jetbrains.anko.AnkoLogger import java.io.File class SpotifyLiteDebugTracer(storageFolder: File?) : AdDetectable, AnkoLogger, AbstractDebugTracer(storageFolder) { private val PACKAGE = "com.spotify.lite" private val FILENAME = "adfree-spotify-lite.txt" override fun getPackage() = PACKAGE override fun getFileName() = FILENAME override fun getMeta(): AdDetectorMeta = AdDetectorMeta( "Spotify Lite tracer", "dump spotify lite notifications to a file. This is for debugging only. ", false, category = "Developer", debugOnly = true ) }
apache-2.0
b4a6633ed1dda805b803637344216e89
29.761905
89
0.712074
4.364865
false
false
false
false
Shoebill/shoebill-common
src/main/java/net/gtaun/shoebill/common/LifecycleHolder.kt
1
3078
package net.gtaun.shoebill.common import net.gtaun.shoebill.Shoebill import net.gtaun.shoebill.entities.Destroyable import net.gtaun.util.event.EventManager import net.gtaun.util.event.EventManagerNode /** * Created by marvin on 14.11.16 in project shoebill-common. * Copyright (c) 2016 Marvin Haschker. All rights reserved. */ @AllOpen class LifecycleHolder<T> @JvmOverloads constructor(eventManager: EventManager = Shoebill.get().eventManager) : Destroyable { protected val eventManagerNode: EventManagerNode = eventManager.createChildNode() private val lifecycleObjects = mutableMapOf<T, MutableList<LifecycleObject>>() private val lifecycleFactories = mutableMapOf<Class<out LifecycleObject>, LifecycleFactory<T, LifecycleObject>>() fun <B : LifecycleObject> registerClass(lifecycleObject: Class<B>, factory: LifecycleFactory<T, B>) { lifecycleFactories.put(lifecycleObject, factory) lifecycleObjects.forEach { buildObject(it.key, lifecycleObject) } } fun <B : LifecycleObject> unregisterClass(lifecycleObject: Class<B>) { lifecycleObjects.forEach { destroyObject(it.key, lifecycleObject) } lifecycleFactories.remove(lifecycleObject) } @Suppress("UNCHECKED_CAST") fun <B : LifecycleObject> getObject(input: T, clazz: Class<B>): B? { val objects = lifecycleObjects[input] ?: return null val lifecycleObject = objects.firstOrNull { it.javaClass == clazz } ?: return null return lifecycleObject as B } fun <B : LifecycleObject> getObjects(clazz: Class<B>): List<B> { return lifecycleObjects.filter { it.value.filter { it.javaClass == clazz }.count() > 0 } .map { it.value } .first() .map { it as B } } fun buildObjects(input: T) { val list = lifecycleFactories.map { val obj = it.value.create(input) obj.init() return@map obj }.toMutableList() lifecycleObjects.put(input, list) } fun <B : LifecycleObject> buildObject(input: T, clazz: Class<B>) { val factory = lifecycleFactories.filter { it.key == clazz }.map { it.value }.firstOrNull() ?: return val playerList = lifecycleObjects[input] ?: return val obj = factory.create(input) obj.init() playerList.add(obj) } fun destroyObjects(input: T) { val list = lifecycleObjects[input] ?: return list.forEach { it.destroy() } lifecycleObjects.remove(input) } fun <B : LifecycleObject> destroyObject(input: T, clazz: Class<B>) { val playerList = lifecycleObjects[input] ?: return val obj = playerList.firstOrNull { it.javaClass == clazz } ?: return obj.destroy() playerList.remove(obj) } override val isDestroyed: Boolean get() = eventManagerNode.isDestroyed override fun destroy() = eventManagerNode.destroy() @FunctionalInterface interface LifecycleFactory<in B, out T : LifecycleObject> { fun create(input: B): T } }
apache-2.0
ec66984ab441038a4996a94f27e9a9be
34.802326
108
0.664717
4.233838
false
false
false
false
Doctoror/ParticleConstellationsLiveWallpaper
app/src/main/java/com/doctoror/particleswallpaper/framework/util/MultisamplingConfigSpecParser.kt
1
1335
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * 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.doctoror.particleswallpaper.framework.util import javax.microedition.khronos.egl.EGL10 class MultisamplingConfigSpecParser { fun extractNumSamplesFromConfigSpec(config: IntArray?) = if (config == null) { 0 } else { var returnValue = 0 val sampleBuffersIndex = config.indexOf(EGL10.EGL_SAMPLE_BUFFERS) if (sampleBuffersIndex != -1) { val sampleBuffers = config[sampleBuffersIndex + 1] == 1 if (sampleBuffers) { val samplesIndex = config.indexOf(EGL10.EGL_SAMPLES) if (samplesIndex != -1) { returnValue = config[samplesIndex + 1] } } } returnValue } }
apache-2.0
64e5a9205fc27324eb9ab81b600bc743
34.131579
82
0.658427
4.348534
false
true
false
false
dkandalov/katas
kotlin/src/katas/kotlin/leetcode/traping_rain_water/TrappingRainWater.kt
1
2220
package katas.kotlin.leetcode.traping_rain_water import datsok.* import org.junit.* import java.util.* /** * https://leetcode.com/problems/trapping-rain-water * * Given n non-negative integers representing an elevation map where the width of each bar is 1, * compute how much water it is able to trap after raining. */ class TrappingRainWater { private val trap = ::trap_with_lookback @Test fun `some examples`() { trap(listOf(0)) shouldEqual 0 trap(listOf(1)) shouldEqual 0 trap(listOf(1, 0)) shouldEqual 0 trap(listOf(0, 1)) shouldEqual 0 trap(listOf(1, 1)) shouldEqual 0 trap(listOf(0, 1, 1)) shouldEqual 0 trap(listOf(1, 1, 0)) shouldEqual 0 trap(listOf(1, 0, 1)) shouldEqual 1 trap(listOf(1, 2, 0)) shouldEqual 0 trap(listOf(0, 2, 1)) shouldEqual 0 trap(listOf(1, 0, 2)) shouldEqual 1 trap(listOf(2, 0, 1)) shouldEqual 1 trap(listOf(2, 0, 2)) shouldEqual 2 trap(listOf(2, 0, 0, 1)) shouldEqual 2 trap(listOf(1, 0, 0, 2)) shouldEqual 2 trap(listOf(2, 0, 0, 2)) shouldEqual 4 trap(listOf(0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1)) shouldEqual 6 } } private fun trap_with_lookback(elevationMap: List<Int>): Int { val prevIndexByHeight = TreeMap<Int, Int>() return elevationMap.indices.zip(elevationMap).sumBy { (index, wallHeight) -> (1..wallHeight).sumBy { height -> val prevIndex = prevIndexByHeight.ceilingEntry(height)?.value ?: index - 1 (index - prevIndex - 1).also { prevIndexByHeight[height] = index } } } } private fun trap_with_lookahead(elevationMap: List<Int>): Int { fun volumeTillNextWall(fromIndex: Int, height: Int): Int { val volume = elevationMap.subList(fromIndex + 1, elevationMap.size).takeWhile { it < height }.size val doesNotSpillFromRight = volume < elevationMap.size - (fromIndex + 1) return if (doesNotSpillFromRight) volume else 0 } return elevationMap.indices.zip(elevationMap).sumBy { (index, wallHeight) -> (1..wallHeight).sumBy { height -> volumeTillNextWall(index, height) } } }
unlicense
fbbe5fa32a589a25e32709e2a155547f
32.636364
106
0.625676
3.669421
false
false
false
false
dkandalov/katas
kotlin-native/hello-ncurses/src/main.kt
1
595
import platform.osx.* import platform.posix.exit fun main(args: Array<String>) { initscr() clear() cbreak() noecho() halfdelay(10) curs_set(0) var c = ' '.toInt() var x = 0 var y = 0 while (c != 'q'.toInt()) { box(stdscr, 0, 0) attron(A_BOLD) mvprintw(y, 10, "Hello") attroff(A_BOLD) mvprintw(5, x, "a") refresh() c = getch() mvprintw(y, 10, " ") if (c == -1) x++ if (c == 'i'.toInt()) y -= 1 if (c == 'k'.toInt()) y += 1 } endwin() exit(0) }
unlicense
415929a29b5814c8f9c311bff0c38cdf
15.108108
36
0.435294
2.931034
false
false
false
false
Pagejects/pagejects-core
src/test/kotlin/net/pagejects/core/forms/ReadFormUserActionTest.kt
1
4876
package net.pagejects.core.forms import com.codeborne.selenide.SelenideElement import net.pagejects.core.Element import net.pagejects.core.PagejectsManager import net.pagejects.core.impl.Elements import net.pagejects.core.impl.Selectors import net.pagejects.core.reflaction.findMethod import net.pagejects.core.service.SelectorService import net.pagejects.core.service.SelenideElementService import net.pagejects.core.testdata.PageObjectWithForm import net.pagejects.core.testdata.SomeFormObject import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations import org.openqa.selenium.By import org.testng.Assert.assertEquals import org.testng.annotations.* import java.lang.reflect.Method import kotlin.reflect.KClass class ReadFormUserActionTest { private lateinit var browserGetter: () -> String @Mock private lateinit var element1: SelenideElement @Mock private lateinit var element2: SelenideElement @Mock private lateinit var element3: SelenideElement @Mock private lateinit var formElement: SelenideElement private val selectorService: SelectorService = object : SelectorService { override fun contains(pageName: String, element: String): Boolean = pageName to element in Selectors override fun selector(pageName: String, elementName: String): By = Selectors[pageName, elementName].selectBy } private val selenideElementService: SelenideElementService = object : SelenideElementService { override fun get(pageName: String, elementName: String): SelenideElement = getBy(selectorService.selector(pageName, elementName)) override fun getBy(by: By): SelenideElement = when (by.toString().substringAfterLast('.')) { "test1" -> element1 "test2" -> element2 "test3" -> element3 "form" -> formElement "another-form" -> formElement else -> throw IllegalStateException("Undefined element") } } private val expected by lazy { val formObject = SomeFormObject() formObject.field1 = "test1" formObject.field2 = "test2" formObject.field3 = "test3" formObject } @BeforeClass fun beforeClass() { Selectors.dropCache() PagejectsManager.instance.selectorsFileName = "classpath://${this.javaClass.simpleName}.yaml" browserGetter = Selectors.cache.browserGetter Selectors.cache.browserGetter = { "chrome" } } @BeforeMethod fun setUp() { Elements.dropCache() MockitoAnnotations.initMocks(this) element1 = newSelenideElement(By.className(".test1")) element2 = newSelenideElement(By.className(".test2")) element3 = newSelenideElement(By.className(".test3")) formElement = newSelenideElement(By.className(".another-form")) } @AfterClass fun tearDown() { Selectors.dropCache() Elements.dropCache() Selectors.cache.browserGetter = browserGetter } private fun newSelenideElement(by: By): SelenideElement { val element = Mockito.mock(SelenideElement::class.java) Mockito.`when`(element.name()).thenReturn("${this.javaClass.simpleName}-$by") Mockito.`when`(element.tagName).thenReturn("input") Mockito.`when`(element.attr(Mockito.eq("type"))).thenReturn("input") Mockito.`when`(element.value).thenReturn(by.toString().substringAfterLast('.')) Mockito.`when`(element.find(Mockito.any(By::class.java))).then { when (it.arguments[0].toString().substringAfterLast('.')) { "test1" -> element1 "test2" -> element2 "test3" -> element3 else -> throw IllegalStateException("Undefined element") } } return element } private fun newElement(by: By): Element = Element { newSelenideElement(by) } @DataProvider(name = "dataForPerform") fun dataForPerform(): Array<Array<Any>> = arrayOf( arrayOf(PageObjectWithForm::class, PageObjectWithForm::class.findMethod("readForm"), emptyArray<Any>()), arrayOf(PageObjectWithForm::class, PageObjectWithForm::class.findMethod("readFormBy"), arrayOf(By.className(".another-form"))), arrayOf(PageObjectWithForm::class, PageObjectWithForm::class.findMethod("readFormFromElement1"), arrayOf(newSelenideElement(By.className(".test-form")))), arrayOf(PageObjectWithForm::class, PageObjectWithForm::class.findMethod("readFormFromElement2"), arrayOf(newElement(By.className(".another-form")))) ) @Test(dataProvider = "dataForPerform") fun testPerform(`interface`: KClass<*>, @NoInjection method: Method, args: Array<Any?>) { assertEquals(ReadFormUserAction(`interface`, method, selenideElementService, selectorService).perform(args), expected) } }
apache-2.0
30efc53e3b978c141d200abf15091918
42.544643
166
0.697703
4.692974
false
true
false
false
paplorinc/intellij-community
platform/projectModel-api/src/com/intellij/util/io/path.kt
1
8544
// 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.util.io import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.CharsetToolkit import java.io.File import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime import java.util.* fun Path.exists(): Boolean = Files.exists(this) fun Path.createDirectories(): Path { // symlink or existing regular file - Java SDK do this check, but with as `isDirectory(dir, LinkOption.NOFOLLOW_LINKS)`, i.e. links are not checked if (!Files.isDirectory(this)) { try { doCreateDirectories(toAbsolutePath()) } catch (ignored: FileAlreadyExistsException) { // toAbsolutePath can return resolved path or file exists now } } return this } private fun doCreateDirectories(path: Path) { path.parent?.let { if (!Files.isDirectory(it)) { doCreateDirectories(it) } } Files.createDirectory(path) } /** * Opposite to Java, parent directories will be created */ fun Path.outputStream(): OutputStream { parent?.createDirectories() return Files.newOutputStream(this) } @Throws(IOException::class) fun Path.inputStream(): InputStream = Files.newInputStream(this) @Throws(IOException::class) fun Path.inputStreamSkippingBom() = CharsetToolkit.inputStreamSkippingBOM(inputStream().buffered()) fun Path.inputStreamIfExists(): InputStream? { try { return inputStream() } catch (e: NoSuchFileException) { return null } } /** * Opposite to Java, parent directories will be created */ fun Path.createSymbolicLink(target: Path): Path { parent?.createDirectories() Files.createSymbolicLink(this, target) return this } @JvmOverloads fun Path.delete(deleteRecursively: Boolean = true) { try { if (!deleteRecursively) { // performance optimisation: try to delete regular file without any checks Files.delete(this) return } val attributes = basicAttributesIfExists() ?: return if (attributes.isDirectory) { deleteRecursively() } else { Files.delete(this) } } catch (e: Exception) { deleteAsIOFile() } } fun Path.deleteWithParentsIfEmpty(root: Path, isFile: Boolean = true): Boolean { var parent = if (isFile) this.parent else null try { delete() } catch (e: NoSuchFileException) { return false } // remove empty directories while (parent != null && parent != root) { try { // must be only Files.delete, but not our delete (Files.delete throws DirectoryNotEmptyException) Files.delete(parent) } catch (e: IOException) { break } parent = parent.parent } return true } fun Path.deleteChildrenStartingWith(prefix: String) { directoryStreamIfExists({ it.fileName.toString().startsWith(prefix) }) { it.toList() }?.forEach { it.delete() } } private fun Path.deleteRecursively() = Files.walkFileTree(this, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { try { Files.delete(file) } catch (e: Exception) { deleteAsIOFile() } return FileVisitResult.CONTINUE } override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult { try { Files.delete(dir) } catch (e: Exception) { deleteAsIOFile() } return FileVisitResult.CONTINUE } }) private fun Path.deleteAsIOFile() { try { FileUtil.delete(toFile()) } // according to specification #toFile() method may throw UnsupportedOperationException catch (ignored: UnsupportedOperationException) {} } fun Path.lastModified(): FileTime = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') val Path.parentSystemIndependentPath: String get() = parent!!.toString().replace(File.separatorChar, '/') @Throws(IOException::class) fun Path.readBytes(): ByteArray = Files.readAllBytes(this) @Throws(IOException::class) fun Path.readText(): String = readBytes().toString(Charsets.UTF_8) @Throws(IOException::class) fun Path.readChars() = inputStream().reader().readCharSequence(size().toInt()) @Throws(IOException::class) fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePath).write(data) @Throws(IOException::class) fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) @Throws(IOException::class) @JvmOverloads fun Path.write(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { outputStream().use { it.write(data, offset, size) } return this } fun Path.writeSafe(data: ByteArray, offset: Int = 0, size: Int = data.size): Path { writeSafe { it.write(data, offset, size) } return this } /** * Consider using [SafeWriteRequestor.shallUseSafeStream] along with [SafeFileOutputStream] */ fun Path.writeSafe(outConsumer: (OutputStream) -> Unit): Path { val tempFile = parent.resolve("${fileName}.${UUID.randomUUID()}.tmp") tempFile.outputStream().use(outConsumer) try { Files.move(tempFile, this, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) } catch (e: AtomicMoveNotSupportedException) { LOG.warn(e) Files.move(tempFile, this, StandardCopyOption.REPLACE_EXISTING) } return this } @JvmOverloads @Throws(IOException::class) fun Path.write(data: String, createParentDirs: Boolean = true): Path { if (createParentDirs) parent?.createDirectories() Files.write(this, data.toByteArray()) return this } fun Path.size(): Long = Files.size(this) fun Path.basicAttributesIfExists(): BasicFileAttributes? { try { return Files.readAttributes(this, BasicFileAttributes::class.java) } catch (ignored: FileSystemException) { return null } } fun Path.sizeOrNull(): Long = basicAttributesIfExists()?.size() ?: -1 fun Path.isHidden(): Boolean = Files.isHidden(this) fun Path.isDirectory(): Boolean = Files.isDirectory(this) fun Path.isFile(): Boolean = Files.isRegularFile(this) fun Path.move(target: Path): Path = Files.move(this, target, StandardCopyOption.REPLACE_EXISTING) fun Path.copy(target: Path): Path { target.parent?.createDirectories() return Files.copy(this, target, StandardCopyOption.REPLACE_EXISTING) } /** * Opposite to Java, parent directories will be created */ fun Path.createFile() { parent?.createDirectories() Files.createFile(this) } inline fun <R> Path.directoryStreamIfExists(task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this).use(task) } catch (ignored: NoSuchFileException) { } return null } inline fun <R> Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream<Path>) -> R): R? { try { return Files.newDirectoryStream(this, DirectoryStream.Filter { filter(it) }).use(task) } catch (ignored: NoSuchFileException) { } return null } private val LOG = Logger.getInstance("#com.intellij.openapi.util.io.FileUtil") private val illegalChars = setOf('/', '\\', '?', '<', '>', ':', '*', '|', '"', ':') // https://github.com/parshap/node-sanitize-filename/blob/master/index.js fun sanitizeFileName(name: String, replacement: String? = "_", isTruncate: Boolean = true): String { var result: StringBuilder? = null var last = 0 val length = name.length for (i in 0 until length) { val c = name.get(i) if (!illegalChars.contains(c) && !c.isISOControl()) { continue } if (result == null) { result = StringBuilder() } if (last < i) { result.append(name, last, i) } if (replacement != null) { result.append(replacement) } last = i + 1 } fun String.truncateFileName() = if (isTruncate) substring(0, Math.min(length, 255)) else this if (result == null) { return name.truncateFileName() } if (last < length) { result.append(name, last, length) } return result.toString().truncateFileName() } val Path.isWritable: Boolean get() = Files.isWritable(this) fun isDirectory(attributes: BasicFileAttributes?): Boolean { return attributes != null && attributes.isDirectory } fun isSymbolicLink(attributes: BasicFileAttributes?): Boolean { return attributes != null && attributes.isSymbolicLink }
apache-2.0
a8e0386ebe9d5b2d6548be5aec0c2d83
25.871069
149
0.705056
3.990659
false
false
false
false
BreakOutEvent/breakout-backend
src/main/java/backend/model/event/Event.kt
1
1449
package backend.model.event import backend.model.BasicEntity import backend.model.misc.Coord import org.javamoney.moneta.Money import java.time.LocalDateTime import java.util.* import javax.persistence.Embedded import javax.persistence.Entity import javax.persistence.OneToMany @Entity class Event : BasicEntity { lateinit var title: String lateinit var date: LocalDateTime lateinit var city: String var isCurrent: Boolean = false var isOpenForRegistration: Boolean = false var allowNewSponsoring: Boolean = false @OneToMany(mappedBy = "event") var teams: MutableList<Team> = ArrayList() @Embedded lateinit var startingLocation: Coord var duration: Int = 36 var teamFee: Money? = Money.of(60, "EUR") var brand: String? = null var bank: String? = null var iban: String? = null var bic: String? = null /** * Private constructor for JPA */ private constructor() : super() constructor(title: String, date: LocalDateTime, city: String, startingLocation: Coord, duration: Int, teamFee: Money, brand: String, bank: String, iban: String, bic: String) : this() { this.title = title this.date = date this.city = city this.startingLocation = startingLocation this.duration = duration this.teamFee = teamFee this.brand = brand this.bank = bank this.iban = iban this.bic = bic } }
agpl-3.0
79a5d9eaf326368523548feb6039c180
25.345455
188
0.675638
4.116477
false
false
false
false
ssseasonnn/RxDownload
rxdownload4/src/main/java/zlc/season/rxdownload4/storage/MemoryStorage.kt
1
638
package zlc.season.rxdownload4.storage import zlc.season.rxdownload4.task.Task open class MemoryStorage : Storage { companion object { //memory cache private val taskPool = mutableMapOf<Task, Task>() } @Synchronized override fun load(task: Task) { val result = taskPool[task] if (result != null) { task.saveName = result.saveName task.savePath = result.savePath } } @Synchronized override fun save(task: Task) { taskPool[task] = task } @Synchronized override fun delete(task: Task) { taskPool.remove(task) } }
apache-2.0
da0453e860a9f5f86c319d843d661354
21.034483
57
0.606583
4.142857
false
false
false
false
arnab/adventofcode
src/main/kotlin/aoc2016/day2/FancyLooKey.kt
1
3115
package aoc2016.day2 import java.util.logging.Level import java.util.logging.Logger data class FancyLocation(val x: Int, val y: Int) { /** * Safe builder. If x or y are out of bound, it returns null. */ companion object { fun of(x: Int, y: Int): FancyLocation? { if (x < 0 || x >= FancyNumPad.keys.size) return null if (y < 0 || y >= FancyNumPad.keys.first().size) return null if (FancyNumPad.keys[x][y].isBlank()) return null return FancyLocation(x, y) } } } object FancyNumPad { private val logger = Logger.getLogger(this.javaClass.name) /** * Keys arranged in the natural keypad order: * 1 * 2 3 4 * 5 6 7 8 9 * A B C * D */ val keys = arrayOf( arrayOf("", "", "5", "", ""), arrayOf("", "A", "6", "2", ""), arrayOf("D", "B", "7", "3", "1"), arrayOf("", "C", "8", "5", ""), arrayOf("", "", "9", "", "") ) // "5" or (1,1) val initialLocation = FancyLocation(0, 2) var latestLocation = initialLocation fun keyAt(location: FancyLocation): String = keys[location.x][location.y] fun keyAtCurrentLocation(): String = keyAt(latestLocation) /** * switches latestLocation to the next location based on the given direction. */ fun move(direction: Direction) { val nextLocation = when(direction) { Direction.U -> FancyLocation.of(latestLocation.x, latestLocation.y + 1) Direction.D -> FancyLocation.of(latestLocation.x, latestLocation.y - 1) Direction.L -> FancyLocation.of(latestLocation.x - 1, latestLocation.y) Direction.R -> FancyLocation.of(latestLocation.x + 1, latestLocation.y) } ?: latestLocation logger.fine { "$direction from ${keyAtCurrentLocation()} ($latestLocation) -> ${keyAt(nextLocation)} ($nextLocation)" } latestLocation = nextLocation } } object FancyLooKey { private val logger = Logger.getLogger(this.javaClass.name) fun decipher(data: String): String { val instructions: List<List<Direction>> = data.lines() .map(String::trim) .filter(String::isNotBlank) .map { it.split(Regex("")) } .map { it.filter(String::isNotBlank) } .map { it.map(this::parseDirection) } instructions.forEachIndexed { i, dirs -> logger.fine { "Instructions: #$i of ${instructions.size}: $dirs" } } val code: List<String> = instructions.map(this::applyDirections) logger.info { "Code: $code" } return code.joinToString("") } private fun parseDirection(s: String): Direction = Direction.valueOf(s) private fun applyDirections(directions: List<Direction>): String { logger.info { "Applying instructions: $directions" } directions.forEach { FancyNumPad.move(it) } logger.info { "Current Key: ${FancyNumPad.keyAtCurrentLocation()}" } return FancyNumPad.keyAtCurrentLocation() } }
mit
908acaf50009504132ab81ff558865ac
31.789474
117
0.582022
4.003856
false
true
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/core/aggregator/DomainTypesAggregator.kt
2
3988
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.core.aggregator import org.apache.causeway.client.kroviz.core.event.LogEntry import org.apache.causeway.client.kroviz.core.model.DiagramDM import org.apache.causeway.client.kroviz.to.* import org.apache.causeway.client.kroviz.ui.core.ViewManager class DomainTypesAggregator(val url: String) : BaseAggregator() { init { dpm = DiagramDM(url) } override fun update(logEntry: LogEntry, subType: String) { when (val obj = logEntry.getTransferObject()) { is DomainTypes -> handleDomainTypes(obj) is DomainType -> handleDomainType(obj) is Property -> handleProperty(obj) is Action -> handleAction(obj) else -> log(logEntry) } if (dpm.canBeDisplayed()) { ViewManager.getRoStatusBar().updateDiagram(dpm as DiagramDM) dpm.isRendered = true } } private fun handleProperty(obj: Property) { dpm.addData(obj) } private fun handleAction(obj: Action) { console.log("[DTA.handleAction] $obj") throw Throwable("[DomainTypesAggregator.handleAction] not implemented yet") //dsp.addData(obj) } private fun handleDomainType(obj: DomainType) { if (obj.isPrimitiveOrService()) { (dpm as DiagramDM).decNumberOfClasses() } else { dpm.addData(obj) val propertyList = obj.members.filter { it.value.isProperty() } (dpm as DiagramDM).incNumberOfProperties(propertyList.size) propertyList.forEach { invoke(it.value, this, referrer = "") } } } private fun handleDomainTypes(obj: DomainTypes) { val domainTypeLinkList = mutableListOf<Link>() obj.values.forEach { link -> val it = link.href when { it.contains("/org.apache.causeway") -> { } it.contains("/causewayApplib") -> { } it.contains("/java") -> { } it.contains("/void") -> { } it.contains("/boolean") -> { } it.contains("fixture") -> { } it.contains("service") -> { } it.contains("/homepage") -> { } it.endsWith("Menu") -> { } it.startsWith("demoapp.dom.annot") -> { } it.startsWith("demoapp.dom.types.javatime") -> { } else -> { domainTypeLinkList.add(link) } } } (dpm as DiagramDM).numberOfClasses = domainTypeLinkList.size domainTypeLinkList.forEach { invoke(it, this, referrer = "") } } private fun DomainType.isPrimitiveOrService(): Boolean { val primitives = arrayOf("void", "boolean", "double", "byte", "long", "char", "float", "short", "int") return (primitives.contains(canonicalName) || extensions.isService) } }
apache-2.0
dc48a490bc6d293c6e90dfad3a3df2e6
33.678261
110
0.574223
4.450893
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/BufferedSink.kt
1
3074
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.OrderMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Instruction2 import org.runestar.client.updater.mapper.Method2 import org.runestar.client.common.startsWith import org.objectweb.asm.Opcodes.* import org.objectweb.asm.Type.* import java.io.IOException import java.io.OutputStream class BufferedSink : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.interfaces.contains(Runnable::class.type) } .and { it.superType == Any::class.type } .and { it.instanceFields.count { it.type == OutputStream::class.type } == 1 } class thread : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Thread::class.type } } class outputStream : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == OutputStream::class.type } } class exception : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == IOException::class.type } } class buffer : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type } } @MethodParameters() class close : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.instructions.any { it.isMethod && it.methodName == "join" } } } class position : OrderMapper.InConstructor.Field(BufferedSink::class, 0) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class limit : OrderMapper.InConstructor.Field(BufferedSink::class, 1) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class capacity : OrderMapper.InConstructor.Field(BufferedSink::class, 2) { override val predicate = predicateOf<Instruction2> { it.opcode == PUTFIELD && it.fieldType == INT_TYPE } } class isClosed0 : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE } } @MethodParameters() class isClosed : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } @MethodParameters("src", "srcIndex", "length") class write : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } .and { it.arguments.startsWith(ByteArray::class.type) } } }
mit
33ae330db525e6f6f61654f75d719f9d
41.123288
112
0.709499
4.335684
false
false
false
false
google/intellij-community
platform/build-scripts/testFramework/src/org/jetbrains/intellij/build/testFramework/IdeStructureTestBase.kt
1
4699
// 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.intellij.build.testFramework import com.intellij.openapi.application.PathManager import org.assertj.core.api.SoftAssertions import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.IdeaProjectLoaderUtil import org.jetbrains.intellij.build.ProductProperties import org.jetbrains.intellij.build.ProprietaryBuildTools import org.jetbrains.intellij.build.impl.DistributionJARsBuilder import org.jetbrains.intellij.build.impl.ModuleStructureValidator import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaDependencyScope import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModuleDependency import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import java.nio.file.Path import java.util.* @ExtendWith(SoftAssertionsExtension::class) abstract class IdeStructureTestBase { protected open val projectHome: Path get() = Path.of(PathManager.getHomePathFor(javaClass)!!) protected abstract fun createProductProperties(projectHome: Path): ProductProperties protected abstract fun createBuildTools(): ProprietaryBuildTools protected open val missingModulesException: Set<MissingModuleException> get() = emptySet() data class MissingModuleException(val fromModule: String, val toModule: String, val scope: JpsJavaDependencyScope) private fun createBuildContext(): BuildContext { val productProperties = createProductProperties(projectHome) return createBuildContext(homePath = projectHome, productProperties = productProperties, buildTools = createBuildTools(), skipDependencySetup = false, communityHomePath = IdeaProjectLoaderUtil.guessCommunityHome(javaClass)) } @Test fun moduleStructureValidation(softly: SoftAssertions) { val context = createBuildContext() val jarBuilder = DistributionJARsBuilder(context, emptySet()) println("Packed modules:") val moduleToJar = jarBuilder.state.platform.jarToModules.entries.asSequence() .flatMap { it.value.map { e -> e to it.key } } .groupBy(keySelector = { it.first }, valueTransform = { it.second }) .toSortedMap() for (kv in moduleToJar) { println(" ${kv.key} ${kv.value}") } val validator = ModuleStructureValidator(context, jarBuilder.state.platform.jarToModules) val errors = validator.validate() for (error in errors) { softly.collectAssertionError(error) } } @Test fun moduleClosureValidation(softly: SoftAssertions) { val buildContext = createBuildContext() val jarBuilder = DistributionJARsBuilder(buildContext, emptySet()) val exceptions = missingModulesException val activeExceptions = mutableSetOf<MissingModuleException>() val moduleToJar = jarBuilder.state.platform.jarToModules.asSequence() .flatMap { it.value.map { e -> e to it.key } } .toMap(TreeMap()) for (kv in moduleToJar) { val module = buildContext.findRequiredModule(kv.key) for (dependency in module.dependenciesList.dependencies) { if (dependency !is JpsModuleDependency) { continue } val dependencyExtension = JpsJavaExtensionService.getInstance().getDependencyExtension(dependency)!! if (!dependencyExtension.scope.isIncludedIn(JpsJavaClasspathKind.PRODUCTION_RUNTIME)) { continue } val moduleDependency = dependency.module!! if (!moduleToJar.containsKey(moduleDependency.name)) { val missingModuleException = MissingModuleException(module.name, moduleDependency.name, dependencyExtension.scope) if (exceptions.contains(missingModuleException)) { activeExceptions.add(missingModuleException) } else { val message = "${buildContext.productProperties.productCode} (${javaClass.simpleName}): missing module from the product layout '${moduleDependency.name}' referenced from '${module.name}' scope ${dependencyExtension.scope}" softly.fail<Unit>(message) } } } } for (moduleName in exceptions.minus(activeExceptions)) { softly.fail<Unit>("${buildContext.productProperties.productCode} (${javaClass.simpleName}): module '$moduleName' is mentioned in ${::missingModulesException.name}, but it was not used. Please remove it from the list") } } }
apache-2.0
6a926734b45065956cae7d4bf0622b96
44.192308
234
0.73505
4.884615
false
false
false
false
google/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/EntityWithSoftLinksImpl.kt
1
42613
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child import org.jetbrains.deft.annotations.Open @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class EntityWithSoftLinksImpl(val dataSource: EntityWithSoftLinksData) : EntityWithSoftLinks, WorkspaceEntityBase() { companion object { internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(EntityWithSoftLinks::class.java, SoftLinkReferencedChild::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false) val connections = listOf<ConnectionId>( CHILDREN_CONNECTION_ID, ) } override val link: OnePersistentId get() = dataSource.link override val manyLinks: List<OnePersistentId> get() = dataSource.manyLinks override val optionalLink: OnePersistentId? get() = dataSource.optionalLink override val inContainer: Container get() = dataSource.inContainer override val inOptionalContainer: Container? get() = dataSource.inOptionalContainer override val inContainerList: List<Container> get() = dataSource.inContainerList override val deepContainer: List<TooDeepContainer> get() = dataSource.deepContainer override val sealedContainer: SealedContainer get() = dataSource.sealedContainer override val listSealedContainer: List<SealedContainer> get() = dataSource.listSealedContainer override val justProperty: String get() = dataSource.justProperty override val justNullableProperty: String? get() = dataSource.justNullableProperty override val justListProperty: List<String> get() = dataSource.justListProperty override val deepSealedClass: DeepSealedOne get() = dataSource.deepSealedClass override val children: List<SoftLinkReferencedChild> get() = snapshot.extractOneToManyChildren<SoftLinkReferencedChild>(CHILDREN_CONNECTION_ID, this)!!.toList() override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: EntityWithSoftLinksData?) : ModifiableWorkspaceEntityBase<EntityWithSoftLinks>(), EntityWithSoftLinks.Builder { constructor() : this(EntityWithSoftLinksData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity EntityWithSoftLinks is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isLinkInitialized()) { error("Field EntityWithSoftLinks#link should be initialized") } if (!getEntityData().isManyLinksInitialized()) { error("Field EntityWithSoftLinks#manyLinks should be initialized") } if (!getEntityData().isInContainerInitialized()) { error("Field EntityWithSoftLinks#inContainer should be initialized") } if (!getEntityData().isInContainerListInitialized()) { error("Field EntityWithSoftLinks#inContainerList should be initialized") } if (!getEntityData().isDeepContainerInitialized()) { error("Field EntityWithSoftLinks#deepContainer should be initialized") } if (!getEntityData().isSealedContainerInitialized()) { error("Field EntityWithSoftLinks#sealedContainer should be initialized") } if (!getEntityData().isListSealedContainerInitialized()) { error("Field EntityWithSoftLinks#listSealedContainer should be initialized") } if (!getEntityData().isJustPropertyInitialized()) { error("Field EntityWithSoftLinks#justProperty should be initialized") } if (!getEntityData().isJustListPropertyInitialized()) { error("Field EntityWithSoftLinks#justListProperty should be initialized") } if (!getEntityData().isDeepSealedClassInitialized()) { error("Field EntityWithSoftLinks#deepSealedClass should be initialized") } // Check initialization for list with ref type if (_diff != null) { if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) { error("Field EntityWithSoftLinks#children should be initialized") } } else { if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) { error("Field EntityWithSoftLinks#children should be initialized") } } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as EntityWithSoftLinks this.entitySource = dataSource.entitySource this.link = dataSource.link this.manyLinks = dataSource.manyLinks.toMutableList() this.optionalLink = dataSource.optionalLink this.inContainer = dataSource.inContainer this.inOptionalContainer = dataSource.inOptionalContainer this.inContainerList = dataSource.inContainerList.toMutableList() this.deepContainer = dataSource.deepContainer.toMutableList() this.sealedContainer = dataSource.sealedContainer this.listSealedContainer = dataSource.listSealedContainer.toMutableList() this.justProperty = dataSource.justProperty this.justNullableProperty = dataSource.justNullableProperty this.justListProperty = dataSource.justListProperty.toMutableList() this.deepSealedClass = dataSource.deepSealedClass if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var link: OnePersistentId get() = getEntityData().link set(value) { checkModificationAllowed() getEntityData().link = value changedProperty.add("link") } private val manyLinksUpdater: (value: List<OnePersistentId>) -> Unit = { value -> changedProperty.add("manyLinks") } override var manyLinks: MutableList<OnePersistentId> get() { val collection_manyLinks = getEntityData().manyLinks if (collection_manyLinks !is MutableWorkspaceList) return collection_manyLinks collection_manyLinks.setModificationUpdateAction(manyLinksUpdater) return collection_manyLinks } set(value) { checkModificationAllowed() getEntityData().manyLinks = value manyLinksUpdater.invoke(value) } override var optionalLink: OnePersistentId? get() = getEntityData().optionalLink set(value) { checkModificationAllowed() getEntityData().optionalLink = value changedProperty.add("optionalLink") } override var inContainer: Container get() = getEntityData().inContainer set(value) { checkModificationAllowed() getEntityData().inContainer = value changedProperty.add("inContainer") } override var inOptionalContainer: Container? get() = getEntityData().inOptionalContainer set(value) { checkModificationAllowed() getEntityData().inOptionalContainer = value changedProperty.add("inOptionalContainer") } private val inContainerListUpdater: (value: List<Container>) -> Unit = { value -> changedProperty.add("inContainerList") } override var inContainerList: MutableList<Container> get() { val collection_inContainerList = getEntityData().inContainerList if (collection_inContainerList !is MutableWorkspaceList) return collection_inContainerList collection_inContainerList.setModificationUpdateAction(inContainerListUpdater) return collection_inContainerList } set(value) { checkModificationAllowed() getEntityData().inContainerList = value inContainerListUpdater.invoke(value) } private val deepContainerUpdater: (value: List<TooDeepContainer>) -> Unit = { value -> changedProperty.add("deepContainer") } override var deepContainer: MutableList<TooDeepContainer> get() { val collection_deepContainer = getEntityData().deepContainer if (collection_deepContainer !is MutableWorkspaceList) return collection_deepContainer collection_deepContainer.setModificationUpdateAction(deepContainerUpdater) return collection_deepContainer } set(value) { checkModificationAllowed() getEntityData().deepContainer = value deepContainerUpdater.invoke(value) } override var sealedContainer: SealedContainer get() = getEntityData().sealedContainer set(value) { checkModificationAllowed() getEntityData().sealedContainer = value changedProperty.add("sealedContainer") } private val listSealedContainerUpdater: (value: List<SealedContainer>) -> Unit = { value -> changedProperty.add("listSealedContainer") } override var listSealedContainer: MutableList<SealedContainer> get() { val collection_listSealedContainer = getEntityData().listSealedContainer if (collection_listSealedContainer !is MutableWorkspaceList) return collection_listSealedContainer collection_listSealedContainer.setModificationUpdateAction(listSealedContainerUpdater) return collection_listSealedContainer } set(value) { checkModificationAllowed() getEntityData().listSealedContainer = value listSealedContainerUpdater.invoke(value) } override var justProperty: String get() = getEntityData().justProperty set(value) { checkModificationAllowed() getEntityData().justProperty = value changedProperty.add("justProperty") } override var justNullableProperty: String? get() = getEntityData().justNullableProperty set(value) { checkModificationAllowed() getEntityData().justNullableProperty = value changedProperty.add("justNullableProperty") } private val justListPropertyUpdater: (value: List<String>) -> Unit = { value -> changedProperty.add("justListProperty") } override var justListProperty: MutableList<String> get() { val collection_justListProperty = getEntityData().justListProperty if (collection_justListProperty !is MutableWorkspaceList) return collection_justListProperty collection_justListProperty.setModificationUpdateAction(justListPropertyUpdater) return collection_justListProperty } set(value) { checkModificationAllowed() getEntityData().justListProperty = value justListPropertyUpdater.invoke(value) } override var deepSealedClass: DeepSealedOne get() = getEntityData().deepSealedClass set(value) { checkModificationAllowed() getEntityData().deepSealedClass = value changedProperty.add("deepSealedClass") } // List of non-abstract referenced types var _children: List<SoftLinkReferencedChild>? = emptyList() override var children: List<SoftLinkReferencedChild> get() { // Getter of the list of non-abstract referenced types val _diff = diff return if (_diff != null) { _diff.extractOneToManyChildren<SoftLinkReferencedChild>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink( true, CHILDREN_CONNECTION_ID)] as? List<SoftLinkReferencedChild> ?: emptyList()) } else { this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<SoftLinkReferencedChild> ?: emptyList() } } set(value) { // Setter of the list of non-abstract referenced types checkModificationAllowed() val _diff = diff if (_diff != null) { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) { _diff.addEntity(item_value) } } _diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value) } else { for (item_value in value) { if (item_value is ModifiableWorkspaceEntityBase<*>) { item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable } this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value } changedProperty.add("children") } override fun getEntityData(): EntityWithSoftLinksData = result ?: super.getEntityData() as EntityWithSoftLinksData override fun getEntityClass(): Class<EntityWithSoftLinks> = EntityWithSoftLinks::class.java } } class EntityWithSoftLinksData : WorkspaceEntityData<EntityWithSoftLinks>(), SoftLinkable { lateinit var link: OnePersistentId lateinit var manyLinks: MutableList<OnePersistentId> var optionalLink: OnePersistentId? = null lateinit var inContainer: Container var inOptionalContainer: Container? = null lateinit var inContainerList: MutableList<Container> lateinit var deepContainer: MutableList<TooDeepContainer> lateinit var sealedContainer: SealedContainer lateinit var listSealedContainer: MutableList<SealedContainer> lateinit var justProperty: String var justNullableProperty: String? = null lateinit var justListProperty: MutableList<String> lateinit var deepSealedClass: DeepSealedOne fun isLinkInitialized(): Boolean = ::link.isInitialized fun isManyLinksInitialized(): Boolean = ::manyLinks.isInitialized fun isInContainerInitialized(): Boolean = ::inContainer.isInitialized fun isInContainerListInitialized(): Boolean = ::inContainerList.isInitialized fun isDeepContainerInitialized(): Boolean = ::deepContainer.isInitialized fun isSealedContainerInitialized(): Boolean = ::sealedContainer.isInitialized fun isListSealedContainerInitialized(): Boolean = ::listSealedContainer.isInitialized fun isJustPropertyInitialized(): Boolean = ::justProperty.isInitialized fun isJustListPropertyInitialized(): Boolean = ::justListProperty.isInitialized fun isDeepSealedClassInitialized(): Boolean = ::deepSealedClass.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() result.add(link) for (item in manyLinks) { result.add(item) } val optionalLink_optionalLink = optionalLink if (optionalLink_optionalLink != null) { result.add(optionalLink_optionalLink) } result.add(inContainer.id) for (item in inContainerList) { result.add(item.id) } for (item in deepContainer) { for (item in item.goDeeper) { for (item in item.goDeep) { result.add(item.id) } val optionalLink_item_optionalId = item.optionalId if (optionalLink_item_optionalId != null) { result.add(optionalLink_item_optionalId) } } } val _sealedContainer = sealedContainer when (_sealedContainer) { is SealedContainer.BigContainer -> { result.add(_sealedContainer.id) } is SealedContainer.ContainerContainer -> { for (item in _sealedContainer.container) { result.add(item.id) } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { result.add(_sealedContainer.notId) } } for (item in listSealedContainer) { when (item) { is SealedContainer.BigContainer -> { result.add(item.id) } is SealedContainer.ContainerContainer -> { for (item in item.container) { result.add(item.id) } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { result.add(item.notId) } } } for (item in justListProperty) { } val _deepSealedClass = deepSealedClass when (_deepSealedClass) { is DeepSealedOne.DeepSealedTwo -> { val __deepSealedClass = _deepSealedClass when (__deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree -> { val ___deepSealedClass = __deepSealedClass when (___deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree.DeepSealedFour -> { result.add(___deepSealedClass.id) } } } } } } return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { index.index(this, link) for (item in manyLinks) { index.index(this, item) } val optionalLink_optionalLink = optionalLink if (optionalLink_optionalLink != null) { index.index(this, optionalLink_optionalLink) } index.index(this, inContainer.id) for (item in inContainerList) { index.index(this, item.id) } for (item in deepContainer) { for (item in item.goDeeper) { for (item in item.goDeep) { index.index(this, item.id) } val optionalLink_item_optionalId = item.optionalId if (optionalLink_item_optionalId != null) { index.index(this, optionalLink_item_optionalId) } } } val _sealedContainer = sealedContainer when (_sealedContainer) { is SealedContainer.BigContainer -> { index.index(this, _sealedContainer.id) } is SealedContainer.ContainerContainer -> { for (item in _sealedContainer.container) { index.index(this, item.id) } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { index.index(this, _sealedContainer.notId) } } for (item in listSealedContainer) { when (item) { is SealedContainer.BigContainer -> { index.index(this, item.id) } is SealedContainer.ContainerContainer -> { for (item in item.container) { index.index(this, item.id) } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { index.index(this, item.notId) } } } for (item in justListProperty) { } val _deepSealedClass = deepSealedClass when (_deepSealedClass) { is DeepSealedOne.DeepSealedTwo -> { val __deepSealedClass = _deepSealedClass when (__deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree -> { val ___deepSealedClass = __deepSealedClass when (___deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree.DeepSealedFour -> { index.index(this, ___deepSealedClass.id) } } } } } } } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_link = mutablePreviousSet.remove(link) if (!removedItem_link) { index.index(this, link) } for (item in manyLinks) { val removedItem_item = mutablePreviousSet.remove(item) if (!removedItem_item) { index.index(this, item) } } val optionalLink_optionalLink = optionalLink if (optionalLink_optionalLink != null) { val removedItem_optionalLink_optionalLink = mutablePreviousSet.remove(optionalLink_optionalLink) if (!removedItem_optionalLink_optionalLink) { index.index(this, optionalLink_optionalLink) } } val removedItem_inContainer_id = mutablePreviousSet.remove(inContainer.id) if (!removedItem_inContainer_id) { index.index(this, inContainer.id) } for (item in inContainerList) { val removedItem_item_id = mutablePreviousSet.remove(item.id) if (!removedItem_item_id) { index.index(this, item.id) } } for (item in deepContainer) { for (item in item.goDeeper) { for (item in item.goDeep) { val removedItem_item_id = mutablePreviousSet.remove(item.id) if (!removedItem_item_id) { index.index(this, item.id) } } val optionalLink_item_optionalId = item.optionalId if (optionalLink_item_optionalId != null) { val removedItem_optionalLink_item_optionalId = mutablePreviousSet.remove(optionalLink_item_optionalId) if (!removedItem_optionalLink_item_optionalId) { index.index(this, optionalLink_item_optionalId) } } } } val _sealedContainer = sealedContainer when (_sealedContainer) { is SealedContainer.BigContainer -> { val removedItem__sealedContainer_id = mutablePreviousSet.remove(_sealedContainer.id) if (!removedItem__sealedContainer_id) { index.index(this, _sealedContainer.id) } } is SealedContainer.ContainerContainer -> { for (item in _sealedContainer.container) { val removedItem_item_id = mutablePreviousSet.remove(item.id) if (!removedItem_item_id) { index.index(this, item.id) } } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { val removedItem__sealedContainer_notId = mutablePreviousSet.remove(_sealedContainer.notId) if (!removedItem__sealedContainer_notId) { index.index(this, _sealedContainer.notId) } } } for (item in listSealedContainer) { when (item) { is SealedContainer.BigContainer -> { val removedItem_item_id = mutablePreviousSet.remove(item.id) if (!removedItem_item_id) { index.index(this, item.id) } } is SealedContainer.ContainerContainer -> { for (item in item.container) { val removedItem_item_id = mutablePreviousSet.remove(item.id) if (!removedItem_item_id) { index.index(this, item.id) } } } is SealedContainer.EmptyContainer -> { } is SealedContainer.SmallContainer -> { val removedItem_item_notId = mutablePreviousSet.remove(item.notId) if (!removedItem_item_notId) { index.index(this, item.notId) } } } } for (item in justListProperty) { } val _deepSealedClass = deepSealedClass when (_deepSealedClass) { is DeepSealedOne.DeepSealedTwo -> { val __deepSealedClass = _deepSealedClass when (__deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree -> { val ___deepSealedClass = __deepSealedClass when (___deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree.DeepSealedFour -> { val removedItem____deepSealedClass_id = mutablePreviousSet.remove(___deepSealedClass.id) if (!removedItem____deepSealedClass_id) { index.index(this, ___deepSealedClass.id) } } } } } } } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val link_data = if (link == oldLink) { changed = true newLink as OnePersistentId } else { null } if (link_data != null) { link = link_data } val manyLinks_data = manyLinks.map { val it_data = if (it == oldLink) { changed = true newLink as OnePersistentId } else { null } if (it_data != null) { it_data } else { it } } if (manyLinks_data != null) { manyLinks = manyLinks_data as MutableList } var optionalLink_data_optional = if (optionalLink != null) { val optionalLink___data = if (optionalLink!! == oldLink) { changed = true newLink as OnePersistentId } else { null } optionalLink___data } else { null } if (optionalLink_data_optional != null) { optionalLink = optionalLink_data_optional } val inContainer_id_data = if (inContainer.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var inContainer_data = inContainer if (inContainer_id_data != null) { inContainer_data = inContainer_data.copy(id = inContainer_id_data) } if (inContainer_data != null) { inContainer = inContainer_data } var inOptionalContainer_data_optional = if (inOptionalContainer != null) { val inOptionalContainer___id_data = if (inOptionalContainer!!.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var inOptionalContainer___data = inOptionalContainer!! if (inOptionalContainer___id_data != null) { inOptionalContainer___data = inOptionalContainer___data.copy(id = inOptionalContainer___id_data) } inOptionalContainer___data } else { null } if (inOptionalContainer_data_optional != null) { inOptionalContainer = inOptionalContainer_data_optional } val inContainerList_data = inContainerList.map { val it_id_data = if (it.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var it_data = it if (it_id_data != null) { it_data = it_data.copy(id = it_id_data) } if (it_data != null) { it_data } else { it } } if (inContainerList_data != null) { inContainerList = inContainerList_data as MutableList } val deepContainer_data = deepContainer.map { val it_goDeeper_data = it.goDeeper.map { val it_goDeep_data = it.goDeep.map { val it_id_data = if (it.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var it_data = it if (it_id_data != null) { it_data = it_data.copy(id = it_id_data) } if (it_data != null) { it_data } else { it } } var it_optionalId_data_optional = if (it.optionalId != null) { val it_optionalId___data = if (it.optionalId!! == oldLink) { changed = true newLink as OnePersistentId } else { null } it_optionalId___data } else { null } var it_data = it if (it_goDeep_data != null) { it_data = it_data.copy(goDeep = it_goDeep_data) } if (it_optionalId_data_optional != null) { it_data = it_data.copy(optionalId = it_optionalId_data_optional) } if (it_data != null) { it_data } else { it } } var it_data = it if (it_goDeeper_data != null) { it_data = it_data.copy(goDeeper = it_goDeeper_data) } if (it_data != null) { it_data } else { it } } if (deepContainer_data != null) { deepContainer = deepContainer_data as MutableList } val _sealedContainer = sealedContainer val res_sealedContainer = when (_sealedContainer) { is SealedContainer.BigContainer -> { val _sealedContainer_id_data = if (_sealedContainer.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var _sealedContainer_data = _sealedContainer if (_sealedContainer_id_data != null) { _sealedContainer_data = _sealedContainer_data.copy(id = _sealedContainer_id_data) } _sealedContainer_data } is SealedContainer.ContainerContainer -> { val _sealedContainer_container_data = _sealedContainer.container.map { val it_id_data = if (it.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var it_data = it if (it_id_data != null) { it_data = it_data.copy(id = it_id_data) } if (it_data != null) { it_data } else { it } } var _sealedContainer_data = _sealedContainer if (_sealedContainer_container_data != null) { _sealedContainer_data = _sealedContainer_data.copy(container = _sealedContainer_container_data) } _sealedContainer_data } is SealedContainer.EmptyContainer -> { _sealedContainer } is SealedContainer.SmallContainer -> { val _sealedContainer_notId_data = if (_sealedContainer.notId == oldLink) { changed = true newLink as OnePersistentId } else { null } var _sealedContainer_data = _sealedContainer if (_sealedContainer_notId_data != null) { _sealedContainer_data = _sealedContainer_data.copy(notId = _sealedContainer_notId_data) } _sealedContainer_data } } if (res_sealedContainer != null) { sealedContainer = res_sealedContainer } val listSealedContainer_data = listSealedContainer.map { val _it = it val res_it = when (_it) { is SealedContainer.BigContainer -> { val _it_id_data = if (_it.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var _it_data = _it if (_it_id_data != null) { _it_data = _it_data.copy(id = _it_id_data) } _it_data } is SealedContainer.ContainerContainer -> { val _it_container_data = _it.container.map { val it_id_data = if (it.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var it_data = it if (it_id_data != null) { it_data = it_data.copy(id = it_id_data) } if (it_data != null) { it_data } else { it } } var _it_data = _it if (_it_container_data != null) { _it_data = _it_data.copy(container = _it_container_data) } _it_data } is SealedContainer.EmptyContainer -> { _it } is SealedContainer.SmallContainer -> { val _it_notId_data = if (_it.notId == oldLink) { changed = true newLink as OnePersistentId } else { null } var _it_data = _it if (_it_notId_data != null) { _it_data = _it_data.copy(notId = _it_notId_data) } _it_data } } if (res_it != null) { res_it } else { it } } if (listSealedContainer_data != null) { listSealedContainer = listSealedContainer_data as MutableList } val _deepSealedClass = deepSealedClass val res_deepSealedClass = when (_deepSealedClass) { is DeepSealedOne.DeepSealedTwo -> { val __deepSealedClass = _deepSealedClass val res__deepSealedClass = when (__deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree -> { val ___deepSealedClass = __deepSealedClass val res___deepSealedClass = when (___deepSealedClass) { is DeepSealedOne.DeepSealedTwo.DeepSealedThree.DeepSealedFour -> { val ___deepSealedClass_id_data = if (___deepSealedClass.id == oldLink) { changed = true newLink as OnePersistentId } else { null } var ___deepSealedClass_data = ___deepSealedClass if (___deepSealedClass_id_data != null) { ___deepSealedClass_data = ___deepSealedClass_data.copy(id = ___deepSealedClass_id_data) } ___deepSealedClass_data } } res___deepSealedClass } } res__deepSealedClass } } if (res_deepSealedClass != null) { deepSealedClass = res_deepSealedClass } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<EntityWithSoftLinks> { val modifiable = EntityWithSoftLinksImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): EntityWithSoftLinks { return getCached(snapshot) { val entity = EntityWithSoftLinksImpl(this) entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun clone(): EntityWithSoftLinksData { val clonedEntity = super.clone() clonedEntity as EntityWithSoftLinksData clonedEntity.manyLinks = clonedEntity.manyLinks.toMutableWorkspaceList() clonedEntity.inContainerList = clonedEntity.inContainerList.toMutableWorkspaceList() clonedEntity.deepContainer = clonedEntity.deepContainer.toMutableWorkspaceList() clonedEntity.listSealedContainer = clonedEntity.listSealedContainer.toMutableWorkspaceList() clonedEntity.justListProperty = clonedEntity.justListProperty.toMutableWorkspaceList() return clonedEntity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return EntityWithSoftLinks::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return EntityWithSoftLinks(link, manyLinks, inContainer, inContainerList, deepContainer, sealedContainer, listSealedContainer, justProperty, justListProperty, deepSealedClass, entitySource) { this.optionalLink = [email protected] this.inOptionalContainer = [email protected] this.justNullableProperty = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as EntityWithSoftLinksData if (this.entitySource != other.entitySource) return false if (this.link != other.link) return false if (this.manyLinks != other.manyLinks) return false if (this.optionalLink != other.optionalLink) return false if (this.inContainer != other.inContainer) return false if (this.inOptionalContainer != other.inOptionalContainer) return false if (this.inContainerList != other.inContainerList) return false if (this.deepContainer != other.deepContainer) return false if (this.sealedContainer != other.sealedContainer) return false if (this.listSealedContainer != other.listSealedContainer) return false if (this.justProperty != other.justProperty) return false if (this.justNullableProperty != other.justNullableProperty) return false if (this.justListProperty != other.justListProperty) return false if (this.deepSealedClass != other.deepSealedClass) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as EntityWithSoftLinksData if (this.link != other.link) return false if (this.manyLinks != other.manyLinks) return false if (this.optionalLink != other.optionalLink) return false if (this.inContainer != other.inContainer) return false if (this.inOptionalContainer != other.inOptionalContainer) return false if (this.inContainerList != other.inContainerList) return false if (this.deepContainer != other.deepContainer) return false if (this.sealedContainer != other.sealedContainer) return false if (this.listSealedContainer != other.listSealedContainer) return false if (this.justProperty != other.justProperty) return false if (this.justNullableProperty != other.justNullableProperty) return false if (this.justListProperty != other.justListProperty) return false if (this.deepSealedClass != other.deepSealedClass) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + link.hashCode() result = 31 * result + manyLinks.hashCode() result = 31 * result + optionalLink.hashCode() result = 31 * result + inContainer.hashCode() result = 31 * result + inOptionalContainer.hashCode() result = 31 * result + inContainerList.hashCode() result = 31 * result + deepContainer.hashCode() result = 31 * result + sealedContainer.hashCode() result = 31 * result + listSealedContainer.hashCode() result = 31 * result + justProperty.hashCode() result = 31 * result + justNullableProperty.hashCode() result = 31 * result + justListProperty.hashCode() result = 31 * result + deepSealedClass.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + link.hashCode() result = 31 * result + manyLinks.hashCode() result = 31 * result + optionalLink.hashCode() result = 31 * result + inContainer.hashCode() result = 31 * result + inOptionalContainer.hashCode() result = 31 * result + inContainerList.hashCode() result = 31 * result + deepContainer.hashCode() result = 31 * result + sealedContainer.hashCode() result = 31 * result + listSealedContainer.hashCode() result = 31 * result + justProperty.hashCode() result = 31 * result + justNullableProperty.hashCode() result = 31 * result + justListProperty.hashCode() result = 31 * result + deepSealedClass.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(OnePersistentId::class.java) collector.add(DeepSealedOne::class.java) collector.add(DeepSealedOne.DeepSealedTwo.DeepSealedThree::class.java) collector.add(DeepSealedOne.DeepSealedTwo.DeepSealedThree.DeepSealedFour::class.java) collector.add(TooDeepContainer::class.java) collector.add(SealedContainer.ContainerContainer::class.java) collector.add(Container::class.java) collector.add(SealedContainer::class.java) collector.add(SealedContainer.BigContainer::class.java) collector.add(DeepContainer::class.java) collector.add(SealedContainer.EmptyContainer::class.java) collector.add(DeepSealedOne.DeepSealedTwo::class.java) collector.add(SealedContainer.SmallContainer::class.java) this.inContainerList?.let { collector.add(it::class.java) } this.sealedContainer?.let { collector.add(it::class.java) } this.justListProperty?.let { collector.add(it::class.java) } this.listSealedContainer?.let { collector.add(it::class.java) } this.manyLinks?.let { collector.add(it::class.java) } this.deepContainer?.let { collector.add(it::class.java) } collector.sameForAllEntities = false } }
apache-2.0
0982ca23b82d40cad8af7854780f6832
34.629599
139
0.649285
4.74321
false
false
false
false
vvv1559/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/runConfigurableHelper.kt
1
1939
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.impl import com.intellij.execution.Executor import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.ConfigurationType fun countSettingsOfType(allSettings: List<RunnerAndConfigurationSettings>, type: ConfigurationType) = allSettings.count { it.type == type } internal class RunConfigurationBean { val settings: RunnerAndConfigurationSettings val configurable: SingleConfigurationConfigurable<*>? constructor(settings: RunnerAndConfigurationSettings) { this.settings = settings configurable = null } constructor(configurable: SingleConfigurationConfigurable<*>) { this.configurable = configurable settings = this.configurable.settings as RunnerAndConfigurationSettings } override fun toString(): String { return settings.toString() } } enum class RunConfigurableNodeKind { CONFIGURATION_TYPE, FOLDER, CONFIGURATION, TEMPORARY_CONFIGURATION, UNKNOWN; fun supportsDnD() = this == FOLDER || this == CONFIGURATION || this == TEMPORARY_CONFIGURATION val isConfiguration: Boolean get() = (this == CONFIGURATION) or (this == TEMPORARY_CONFIGURATION) } interface RunDialogBase { fun setOKActionEnabled(isEnabled: Boolean) val executor: Executor? fun setTitle(title: String) fun clickDefaultButton() }
apache-2.0
28ee69c33ffcd6e6e823ef16759bb6bc
31.333333
139
0.769985
4.92132
false
true
false
false
tiarebalbi/okhttp
okhttp/src/test/java/okhttp3/internal/concurrent/TaskRunnerTest.kt
2
20200
/* * Copyright (C) 2019 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.concurrent import java.util.concurrent.RejectedExecutionException import okhttp3.TestLogHandler import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.RegisterExtension import org.junit.jupiter.api.fail class TaskRunnerTest { @RegisterExtension @JvmField val testLogHandler = TestLogHandler(TaskRunner::class.java) private val taskFaker = TaskFaker() private val taskRunner = taskFaker.taskRunner private val log = mutableListOf<String>() private val redQueue = taskRunner.newQueue() private val blueQueue = taskRunner.newQueue() private val greenQueue = taskRunner.newQueue() @Test fun executeDelayed() { redQueue.execute("task", 100.µs) { log += "run@${taskFaker.nanoTime}" } taskFaker.advanceUntil(0.µs) assertThat(log).containsExactly() taskFaker.advanceUntil(99.µs) assertThat(log).containsExactly() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun executeRepeated() { val delays = mutableListOf(50.µs, 150.µs, -1L) redQueue.schedule("task", 100.µs) { log += "run@${taskFaker.nanoTime}" return@schedule delays.removeAt(0) } taskFaker.advanceUntil(0.µs) assertThat(log).containsExactly() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.advanceUntil(150.µs) assertThat(log).containsExactly("run@100000", "run@150000") taskFaker.advanceUntil(299.µs) assertThat(log).containsExactly("run@100000", "run@150000") taskFaker.advanceUntil(300.µs) assertThat(log).containsExactly("run@100000", "run@150000", "run@300000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 run again after 50 µs: task", "FINE: Q10000 finished run in 0 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 run again after 150 µs: task", "FINE: Q10000 finished run in 0 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } /** Repeat with a delay of 200 but schedule with a delay of 50. The schedule wins. */ @Test fun executeScheduledEarlierReplacesRepeatedLater() { val task = object : Task("task") { val schedules = mutableListOf(50.µs) val delays = mutableListOf(200.µs, -1) override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" if (schedules.isNotEmpty()) { redQueue.schedule(this, schedules.removeAt(0)) } return delays.removeAt(0) } } redQueue.schedule(task, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.advanceUntil(150.µs) assertThat(log).containsExactly("run@100000", "run@150000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 scheduled after 50 µs: task", "FINE: Q10000 already scheduled : task", "FINE: Q10000 finished run in 0 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } /** Schedule with a delay of 200 but repeat with a delay of 50. The repeat wins. */ @Test fun executeRepeatedEarlierReplacesScheduledLater() { val task = object : Task("task") { val schedules = mutableListOf(200.µs) val delays = mutableListOf(50.µs, -1L) override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" if (schedules.isNotEmpty()) { redQueue.schedule(this, schedules.removeAt(0)) } return delays.removeAt(0) } } redQueue.schedule(task, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.advanceUntil(150.µs) assertThat(log).containsExactly("run@100000", "run@150000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 scheduled after 200 µs: task", "FINE: Q10000 run again after 50 µs: task", "FINE: Q10000 finished run in 0 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun cancelReturnsTruePreventsNextExecution() { redQueue.execute("task", 100.µs) { log += "run@${taskFaker.nanoTime}" } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() redQueue.cancelAll() taskFaker.advanceUntil(99.µs) assertThat(log).isEmpty() taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 canceled : task" ) } @Test fun cancelReturnsFalseDoesNotCancel() { redQueue.schedule(object : Task("task", cancelable = false) { override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" return -1L } }, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() redQueue.cancelAll() taskFaker.advanceUntil(99.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun cancelWhileExecutingPreventsRepeat() { redQueue.schedule("task", 100.µs) { log += "run@${taskFaker.nanoTime}" redQueue.cancelAll() return@schedule 100.µs } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun cancelWhileExecutingDoesNothingIfTaskDoesNotRepeat() { redQueue.execute("task", 100.µs) { log += "run@${taskFaker.nanoTime}" redQueue.cancelAll() } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun cancelWhileExecutingDoesNotStopUncancelableTask() { redQueue.schedule(object : Task("task", cancelable = false) { val delays = mutableListOf(50.µs, -1L) override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" redQueue.cancelAll() return delays.removeAt(0) } }, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.advanceUntil(150.µs) assertThat(log).containsExactly("run@100000", "run@150000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 run again after 50 µs: task", "FINE: Q10000 finished run in 0 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun interruptingCoordinatorAttemptsToCancelsAndSucceeds() { redQueue.execute("task", 100.µs) { log += "run@${taskFaker.nanoTime}" } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.interruptCoordinatorThread() taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 canceled : task" ) } @Test fun interruptingCoordinatorAttemptsToCancelsAndFails() { redQueue.schedule(object : Task("task", cancelable = false) { override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" return -1L } }, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.interruptCoordinatorThread() taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } /** Inspect how many runnables have been enqueued. If none then we're truly sequential. */ @Test fun singleQueueIsSerial() { redQueue.execute("task one", 100.µs) { log += "one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } redQueue.execute("task two", 100.µs) { log += "two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } redQueue.execute("task three", 100.µs) { log += "three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly( "one:run@100000 parallel=false", "two:run@100000 parallel=false", "three:run@100000 parallel=false" ) taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task one", "FINE: Q10000 scheduled after 100 µs: task two", "FINE: Q10000 scheduled after 100 µs: task three", "FINE: Q10000 starting : task one", "FINE: Q10000 finished run in 0 µs: task one", "FINE: Q10000 starting : task two", "FINE: Q10000 finished run in 0 µs: task two", "FINE: Q10000 starting : task three", "FINE: Q10000 finished run in 0 µs: task three" ) } /** Inspect how many runnables have been enqueued. If non-zero then we're truly parallel. */ @Test fun differentQueuesAreParallel() { redQueue.execute("task one", 100.µs) { log += "one:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } blueQueue.execute("task two", 100.µs) { log += "two:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } greenQueue.execute("task three", 100.µs) { log += "three:run@${taskFaker.nanoTime} parallel=${taskFaker.isParallel}" } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly( "one:run@100000 parallel=true", "two:run@100000 parallel=true", "three:run@100000 parallel=true" ) taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task one", "FINE: Q10001 scheduled after 100 µs: task two", "FINE: Q10002 scheduled after 100 µs: task three", "FINE: Q10000 starting : task one", "FINE: Q10000 finished run in 0 µs: task one", "FINE: Q10001 starting : task two", "FINE: Q10001 finished run in 0 µs: task two", "FINE: Q10002 starting : task three", "FINE: Q10002 finished run in 0 µs: task three" ) } /** Test the introspection method [TaskQueue.scheduledTasks]. */ @Test fun scheduledTasks() { redQueue.execute("task one", 100.µs) { // Do nothing. } redQueue.execute("task two", 200.µs) { // Do nothing. } assertThat(redQueue.scheduledTasks.toString()).isEqualTo("[task one, task two]") assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task one", "FINE: Q10000 scheduled after 200 µs: task two" ) } /** * We don't track the active task in scheduled tasks. This behavior might be a mistake, but it's * cumbersome to implement properly because the active task might be a cancel. */ @Test fun scheduledTasksDoesNotIncludeRunningTask() { val task = object : Task("task one") { val schedules = mutableListOf(200.µs) override fun runOnce(): Long { if (schedules.isNotEmpty()) { redQueue.schedule(this, schedules.removeAt(0)) // Add it at the end also. } log += "scheduledTasks=${redQueue.scheduledTasks}" return -1L } } redQueue.schedule(task, 100.µs) redQueue.execute("task two", 200.µs) { log += "scheduledTasks=${redQueue.scheduledTasks}" } taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly( "scheduledTasks=[task two, task one]" ) taskFaker.advanceUntil(200.µs) assertThat(log).containsExactly( "scheduledTasks=[task two, task one]", "scheduledTasks=[task one]" ) taskFaker.advanceUntil(300.µs) assertThat(log).containsExactly( "scheduledTasks=[task two, task one]", "scheduledTasks=[task one]", "scheduledTasks=[]" ) taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task one", "FINE: Q10000 scheduled after 200 µs: task two", "FINE: Q10000 starting : task one", "FINE: Q10000 scheduled after 200 µs: task one", "FINE: Q10000 finished run in 0 µs: task one", "FINE: Q10000 starting : task two", "FINE: Q10000 finished run in 0 µs: task two", "FINE: Q10000 starting : task one", "FINE: Q10000 finished run in 0 µs: task one" ) } /** * The runner doesn't hold references to its queues! Otherwise we'd need a mechanism to clean them * up when they're no longer needed and that's annoying. Instead the task runner only tracks which * queues have work scheduled. */ @Test fun activeQueuesContainsOnlyQueuesWithScheduledTasks() { redQueue.execute("task one", 100.µs) { // Do nothing. } blueQueue.execute("task two", 200.µs) { // Do nothing. } taskFaker.advanceUntil(0.µs) assertThat(taskRunner.activeQueues()).containsExactly(redQueue, blueQueue) taskFaker.advanceUntil(100.µs) assertThat(taskRunner.activeQueues()).containsExactly(blueQueue) taskFaker.advanceUntil(200.µs) assertThat(taskRunner.activeQueues()).isEmpty() taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task one", "FINE: Q10001 scheduled after 200 µs: task two", "FINE: Q10000 starting : task one", "FINE: Q10000 finished run in 0 µs: task one", "FINE: Q10001 starting : task two", "FINE: Q10001 finished run in 0 µs: task two" ) } @Test fun taskNameIsUsedForThreadNameWhenRunning() { redQueue.execute("lucky task") { log += "run threadName:${Thread.currentThread().name}" } taskFaker.advanceUntil(0.µs) assertThat(log).containsExactly("run threadName:lucky task") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 0 µs: lucky task", "FINE: Q10000 starting : lucky task", "FINE: Q10000 finished run in 0 µs: lucky task" ) } @Test fun shutdownSuccessfullyCancelsScheduledTasks() { redQueue.execute("task", 100.µs) { log += "run@${taskFaker.nanoTime}" } taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() redQueue.shutdown() taskFaker.advanceUntil(99.µs) assertThat(log).isEmpty() taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 canceled : task" ) } @Test fun shutdownFailsToCancelsScheduledTasks() { redQueue.schedule(object : Task("task", false) { override fun runOnce(): Long { log += "run@${taskFaker.nanoTime}" return 50.µs } }, 100.µs) taskFaker.advanceUntil(0.µs) assertThat(log).isEmpty() redQueue.shutdown() taskFaker.advanceUntil(99.µs) assertThat(log).isEmpty() taskFaker.advanceUntil(100.µs) assertThat(log).containsExactly("run@100000") taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 scheduled after 100 µs: task", "FINE: Q10000 starting : task", "FINE: Q10000 finished run in 0 µs: task" ) } @Test fun scheduleDiscardsTaskWhenShutdown() { redQueue.shutdown() redQueue.execute("task", 100.µs) { // Do nothing. } taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 schedule canceled (queue is shutdown): task" ) } @Test fun scheduleThrowsWhenShutdown() { redQueue.shutdown() try { redQueue.schedule(object : Task("task", cancelable = false) { override fun runOnce(): Long { return -1L } }, 100.µs) fail("") } catch (_: RejectedExecutionException) { } taskFaker.assertNoMoreTasks() assertThat(testLogHandler.takeAll()).containsExactly( "FINE: Q10000 schedule failed (queue is shutdown): task" ) } @Test fun idleLatch() { redQueue.execute("task") { log += "run@${taskFaker.nanoTime}" } val idleLatch = redQueue.idleLatch() assertThat(idleLatch.count).isEqualTo(1) taskFaker.advanceUntil(0.µs) assertThat(log).containsExactly("run@0") assertThat(idleLatch.count).isEqualTo(0) } @Test fun multipleCallsToIdleLatchReturnSameInstance() { redQueue.execute("task") { log += "run@${taskFaker.nanoTime}" } val idleLatch1 = redQueue.idleLatch() val idleLatch2 = redQueue.idleLatch() assertThat(idleLatch2).isSameAs(idleLatch1) } private val Int.µs: Long get() = this * 1_000L }
apache-2.0
5e711ae51798067814b9deda9bce849b
29.757669
100
0.642864
3.851354
false
true
false
false
allotria/intellij-community
uast/uast-common/src/org/jetbrains/uast/expressions/ULiteralExpression.kt
6
1780
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast import org.jetbrains.uast.internal.acceptList import org.jetbrains.uast.internal.log import org.jetbrains.uast.visitor.UastTypedVisitor import org.jetbrains.uast.visitor.UastVisitor /** * Represents a literal expression. */ interface ULiteralExpression : UExpression { /** * Returns the literal expression value. * This is basically a String, Number or null if the literal is a `null` literal. */ val value: Any? /** * Returns true if the literal is a `null`-literal, false otherwise. */ val isNull: Boolean get() = value == null /** * Returns true if the literal is a [String] literal, false otherwise. */ val isString: Boolean get() = evaluate() is String /** * Returns true if the literal is a [Boolean] literal, false otherwise. */ val isBoolean: Boolean get() = evaluate() is Boolean override fun accept(visitor: UastVisitor) { if (visitor.visitLiteralExpression(this)) return uAnnotations.acceptList(visitor) visitor.afterVisitLiteralExpression(this) } override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D): R = visitor.visitLiteralExpression(this, data) override fun asRenderString(): String { val value = value return when (value) { null -> "null" is Char -> "'$value'" is String -> '"' + value.replace("\\", "\\\\") .replace("\r", "\\r").replace("\n", "\\n") .replace("\t", "\\t").replace("\b", "\\b") .replace("\"", "\\\"") + '"' else -> value.toString() } } override fun asLogString(): String = log("value = ${asRenderString()}") }
apache-2.0
040fa77e3ee4c169f3296fd995dc5ffb
28.666667
140
0.650562
4.168618
false
false
false
false
lapis-mc/minecraft-versioning
src/main/kotlin/com/lapismc/minecraft/versioning/Library.kt
1
4418
package com.lapismc.minecraft.versioning import kotlin.coroutines.experimental.buildSequence /** * Package required for the game to run * and additional information regarding extraction and inclusion rules. * @param gav Maven information for the downloadable artifacts. * @param artifacts Set of artifacts included in the library. * @param exclusions Paths to exclude when extracting the library. * @param rules Rules to check whether the library should be included. */ class Library(val gav: GroupArtifactVersionId, val artifacts: List<Artifact>, val exclusions: List<String>, val rules: List<Rule>, val natives: Map<OSType, String>) { /** * Creates a string representation of the library. * @return GAV information. */ override fun toString(): String { return "Library($gav)" } /** * Checks whether the library should be included for the current OS. * @return True if the library is needed on the local OS, * or false if it can be skipped. */ fun isApplicable(): Boolean { val applicableRules = rules.filter { it.isApplicable() } if(applicableRules.isEmpty()) return true return applicableRules.all { it.allowed } } /** * Gets the list of artifacts applicable to the current platform. * @return Set of artifacts needed for the current OS. */ fun getApplicableArtifacts() = buildSequence<Artifact> { val common = commonArtifact if(common != null) yield(common) val native = nativeArtifact if(native != null) yield(native) } /** * Artifact used on all platforms needed by the library. * @return Non-native artifact. * If null, then there is no non-native artifact for this library. */ val commonArtifact: Artifact? get() = artifacts.find { it.resource.name == "artifact" } /** * Artifact used on specific platforms needed by the library. * @return Native artifact. * If null, then there is no native artifact for this library. */ val nativeArtifact: Artifact? get() { return if(natives.containsKey(OSType.current)) { val nativeKey = natives[OSType.current] artifacts.find { it.resource.name == nativeKey } } else { null } } /** * Helps construct a library. * @param gav Maven information for the downloadable artifacts. */ class Builder(val gav: GroupArtifactVersionId) { private val artifacts = ArrayList<Artifact>() private val exclusions = ArrayList<String>() private val rules = ArrayList<Rule>() private val natives = HashMap<OSType, String>() /** * Adds an artifact that is part of the library. * @param artifact Artifact to add. * @return Builder for chaining methods. */ fun addArtifact(artifact: Artifact): Builder { artifacts.add(artifact) return this } /** * Adds a path that should be excluded during extraction of the library. * @param path File path within the artifact to ignore. * @return Builder for chaining methods. */ fun excludePath(path: String): Builder { exclusions.add(path) return this } /** * Adds a rule that should be checked to determine whether the library should be included. * @param rule Rule to add. * @return Builder for chaining methods. */ fun addRule(rule: Rule): Builder { rules.add(rule) return this } /** * Specifies that an artifact is a native for an OS. * @param os Operating system the native is for. * @param artifactId Name of the native artifact. * @return Builder for chaining methods. */ fun specifyNative(os: OSType, artifactId: String): Builder { natives[os] = artifactId return this } /** * Creates the library. * @return Constructed library information. */ fun build(): Library { return Library(gav, artifacts.toList(), exclusions.toList(), rules.toList(), natives.toMap()) } } }
mit
da3ab21ee2246c07a688a888774e674c
32.732824
102
0.600045
4.833698
false
false
false
false
fluidsonic/fluid-json
coding/sources-jvm/implementations/FactoryCodecProvider.kt
1
8334
package io.fluidsonic.json import java.util.concurrent.* import kotlin.reflect.* internal class FactoryCodecProvider<out Value : Any, in Context : JsonCodingContext> internal constructor( private val valueClass: KClass<Value>, private val factory: (actualClass: KClass<out Value>) -> JsonCodecProvider<Context>? ) : JsonCodecProvider<Context> { private val codecsByClass = ConcurrentHashMap<KClass<*>, Codecs<*, Context>>() override fun <ActualValue : Any> decoderCodecForType(decodableType: JsonCodingType<ActualValue>): JsonDecoderCodec<ActualValue, Context>? = decodableType.rawClass.takeIfSubclassOf(valueClass) ?.let { codecsForClass(it).decoderCodec } override fun <ActualValue : Any> encoderCodecForClass(encodableClass: KClass<ActualValue>): JsonEncoderCodec<ActualValue, Context>? = encodableClass.takeIfSubclassOf(valueClass) ?.let { codecsForClass(it).encoderCodec } @Suppress("UNCHECKED_CAST") private fun <ActualValue : Any> codecsForClass(actualClass: KClass<ActualValue>) = codecsByClass.getOrPut(actualClass) { factory(actualClass as KClass<Value>) ?.let { provider -> Codecs( decoderCodec = provider.decoderCodecForType(jsonCodingType(actualClass)), encoderCodec = provider.encoderCodecForClass(actualClass) ) } ?: Codecs.empty<ActualValue>() } as Codecs<ActualValue, Context> private data class Codecs<Value : Any, in Context : JsonCodingContext>( val decoderCodec: JsonDecoderCodec<Value, Context>?, val encoderCodec: JsonEncoderCodec<Value, Context>? ) { companion object { private val empty: Codecs<Any, JsonCodingContext> = Codecs(decoderCodec = null, encoderCodec = null) @Suppress("UNCHECKED_CAST") fun <Value : Any> empty() = empty as Codecs<Value, JsonCodingContext> } } } @JvmName("JsonCodecProviderForDecoding") @Suppress("FunctionName") public fun JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonDecoderCodec<Any, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForDecodingWithContext") @Suppress("FunctionName") public fun <Context : JsonCodingContext> JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonDecoderCodec<Any, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForEncoding") @Suppress("FunctionName") public fun JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonEncoderCodec<Any, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForEncodingWithContext") @Suppress("FunctionName") public fun <Context : JsonCodingContext> JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonEncoderCodec<Any, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForCoding") @Suppress("FunctionName") public fun JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonCodec<Any, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForCodingWithContext") @Suppress("FunctionName") public fun <Context : JsonCodingContext> JsonCodecProvider.Companion.factory( factory: (valueClass: KClass<out Any>) -> JsonCodec<Any, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Any::class, factory = factory) @JvmName("JsonCodecProviderForDecodingSpecificValue") @Suppress("FunctionName") public inline fun <reified Value : Any> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonDecoderCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForDecodingSpecificValue") @Suppress("FunctionName") public fun <Value : Any> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonDecoderCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = FactoryCodecProvider(valueClass = valueClass, factory = factory) @JvmName("JsonCodecProviderForDecodingSpecificValueWithContext") @Suppress("FunctionName") public inline fun <reified Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonDecoderCodec<Value, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForDecodingSpecificValueWithContext") @Suppress("FunctionName") public fun <Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonDecoderCodec<Value, Context>? ): JsonCodecProvider<Context> = FactoryCodecProvider(valueClass = valueClass, factory = factory) @JvmName("JsonCodecProviderForEncodingSpecificValue") @Suppress("FunctionName") public inline fun <reified Value : Any> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonEncoderCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForEncodingSpecificValue") @Suppress("FunctionName") public fun <Value : Any> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonEncoderCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = FactoryCodecProvider(valueClass = valueClass, factory = factory) @JvmName("JsonCodecProviderForEncodingSpecificValueWithContext") @Suppress("FunctionName") public inline fun <reified Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonEncoderCodec<Value, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForEncodingSpecificValueWithContext") @Suppress("FunctionName") public fun <Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonEncoderCodec<Value, Context>? ): JsonCodecProvider<Context> = FactoryCodecProvider(valueClass = valueClass, factory = factory) @JvmName("JsonCodecProviderForCodingSpecificValue") @Suppress("FunctionName") public inline fun <reified Value : Any> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForCodingSpecificValue") @Suppress("FunctionName") public fun <Value : Any> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonCodec<Value, JsonCodingContext>? ): JsonCodecProvider<JsonCodingContext> = FactoryCodecProvider(valueClass = valueClass, factory = factory) @JvmName("JsonCodecProviderForCodingSpecificValueWithContext") @Suppress("FunctionName") public inline fun <reified Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( noinline factory: (valueClass: KClass<out Value>) -> JsonCodec<Value, Context>? ): JsonCodecProvider<Context> = JsonCodecProvider.factoryOf(valueClass = Value::class, factory = factory) @JvmName("JsonCodecProviderForCodingSpecificValueWithContext") @Suppress("FunctionName") public fun <Value : Any, Context : JsonCodingContext> JsonCodecProvider.Companion.factoryOf( valueClass: KClass<out Value>, factory: (valueClass: KClass<out Value>) -> JsonCodec<Value, Context>? ): JsonCodecProvider<Context> = FactoryCodecProvider(valueClass = valueClass, factory = factory)
apache-2.0
872b2a49e3b9689d5590f7e2363bd532
39.852941
140
0.789897
4.402536
false
false
false
false
allotria/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/actions/ShowOnDoubleClickToggleAction.kt
2
1429
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.changes.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareToggleAction import com.intellij.openapi.vcs.VcsApplicationSettings import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vcs.changes.ChangesViewManager private abstract class ShowOnDoubleClickToggleAction(private val isEditorPreview: Boolean) : DumbAwareToggleAction() { override fun update(e: AnActionEvent) { super.update(e) val changesViewManager = e.project?.let { ChangesViewManager.getInstance(it) as? ChangesViewManager } val changeListManager = e.project?.let { ChangeListManager.getInstance(it) } e.presentation.isEnabledAndVisible = changesViewManager?.isEditorPreview == true || changeListManager?.areChangeListsEnabled() == false } override fun isSelected(e: AnActionEvent): Boolean = VcsApplicationSettings.getInstance().SHOW_EDITOR_PREVIEW_ON_DOUBLE_CLICK == isEditorPreview override fun setSelected(e: AnActionEvent, state: Boolean) { VcsApplicationSettings.getInstance().SHOW_EDITOR_PREVIEW_ON_DOUBLE_CLICK = isEditorPreview } class EditorPreview : ShowOnDoubleClickToggleAction(true) class Source : ShowOnDoubleClickToggleAction(false) }
apache-2.0
7ac2e09bac8ee3515d06f5e1ed8ea0a0
45.129032
140
0.801959
4.716172
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/main/kotlin/com/aemtools/index/HtlTemplateIndex.kt
1
1424
package com.aemtools.index import com.aemtools.index.dataexternalizer.TemplateDefinitionExternalizer import com.aemtools.index.indexer.HtlTemplateIndexer import com.aemtools.index.model.TemplateDefinition import com.aemtools.lang.htl.file.HtlFileType import com.intellij.util.indexing.DataIndexer import com.intellij.util.indexing.FileBasedIndex import com.intellij.util.indexing.FileContent import com.intellij.util.indexing.ID import com.intellij.util.io.DataExternalizer import com.intellij.xml.index.XmlIndex /** * Collects Htl files containing *data-sly-template* for quick search. * * @author Dmytro_Troynikov */ class HtlTemplateIndex : XmlIndex<TemplateDefinition>() { companion object { val HTL_TEMPLATE_ID: ID<String, TemplateDefinition> = ID.create<String, TemplateDefinition>("HtlTemplateIndex") /** * Rebuild Htl template index. */ fun rebuildIndex() = FileBasedIndex.getInstance() .requestRebuild(HTL_TEMPLATE_ID) } override fun getIndexer(): DataIndexer<String, TemplateDefinition, FileContent> = HtlTemplateIndexer override fun getInputFilter(): FileBasedIndex.InputFilter = FileBasedIndex.InputFilter { it.fileType == HtlFileType } override fun getValueExternalizer(): DataExternalizer<TemplateDefinition> = TemplateDefinitionExternalizer override fun getName(): ID<String, TemplateDefinition> = HTL_TEMPLATE_ID }
gpl-3.0
6d8196cc83e39153033bad97745adc02
29.956522
81
0.77177
4.395062
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/internal/DispatchedTask.kt
1
9677
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines import kotlinx.coroutines.internal.* import kotlin.coroutines.* import kotlin.jvm.* /** * Non-cancellable dispatch mode. * * **DO NOT CHANGE THE CONSTANT VALUE**. It might be inlined into legacy user code that was calling * inline `suspendAtomicCancellableCoroutine` function and did not support reuse. */ internal const val MODE_ATOMIC = 0 /** * Cancellable dispatch mode. It is used by user-facing [suspendCancellableCoroutine]. * Note, that implementation of cancellability checks mode via [Int.isCancellableMode] extension. * * **DO NOT CHANGE THE CONSTANT VALUE**. It is being into the user code from [suspendCancellableCoroutine]. */ @PublishedApi internal const val MODE_CANCELLABLE: Int = 1 /** * Cancellable dispatch mode for [suspendCancellableCoroutineReusable]. * Note, that implementation of cancellability checks mode via [Int.isCancellableMode] extension; * implementation of reuse checks mode via [Int.isReusableMode] extension. */ internal const val MODE_CANCELLABLE_REUSABLE = 2 /** * Undispatched mode for [CancellableContinuation.resumeUndispatched]. * It is used when the thread is right, but it needs to be marked with the current coroutine. */ internal const val MODE_UNDISPATCHED = 4 /** * Initial mode for [DispatchedContinuation] implementation, should never be used for dispatch, because it is always * overwritten when continuation is resumed with the actual resume mode. */ internal const val MODE_UNINITIALIZED = -1 internal val Int.isCancellableMode get() = this == MODE_CANCELLABLE || this == MODE_CANCELLABLE_REUSABLE internal val Int.isReusableMode get() = this == MODE_CANCELLABLE_REUSABLE internal abstract class DispatchedTask<in T>( @JvmField public var resumeMode: Int ) : SchedulerTask() { internal abstract val delegate: Continuation<T> internal abstract fun takeState(): Any? /** * Called when this task was cancelled while it was being dispatched. */ internal open fun cancelCompletedResult(takenState: Any?, cause: Throwable) {} /** * There are two implementations of `DispatchedTask`: * * [DispatchedContinuation] keeps only simple values as successfully results. * * [CancellableContinuationImpl] keeps additional data with values and overrides this method to unwrap it. */ @Suppress("UNCHECKED_CAST") internal open fun <T> getSuccessfulResult(state: Any?): T = state as T /** * There are two implementations of `DispatchedTask`: * * [DispatchedContinuation] is just an intermediate storage that stores the exception that has its stack-trace * properly recovered and is ready to pass to the [delegate] continuation directly. * * [CancellableContinuationImpl] stores raw cause of the failure in its state; when it needs to be dispatched * its stack-trace has to be recovered, so it overrides this method for that purpose. */ internal open fun getExceptionalResult(state: Any?): Throwable? = (state as? CompletedExceptionally)?.cause public final override fun run() { assert { resumeMode != MODE_UNINITIALIZED } // should have been set before dispatching val taskContext = this.taskContext var fatalException: Throwable? = null try { val delegate = delegate as DispatchedContinuation<T> val continuation = delegate.continuation withContinuationContext(continuation, delegate.countOrElement) { val context = continuation.context val state = takeState() // NOTE: Must take state in any case, even if cancelled val exception = getExceptionalResult(state) /* * Check whether continuation was originally resumed with an exception. * If so, it dominates cancellation, otherwise the original exception * will be silently lost. */ val job = if (exception == null && resumeMode.isCancellableMode) context[Job] else null if (job != null && !job.isActive) { val cause = job.getCancellationException() cancelCompletedResult(state, cause) continuation.resumeWithStackTrace(cause) } else { if (exception != null) { continuation.resumeWithException(exception) } else { continuation.resume(getSuccessfulResult(state)) } } } } catch (e: Throwable) { // This instead of runCatching to have nicer stacktrace and debug experience fatalException = e } finally { val result = runCatching { taskContext.afterTask() } handleFatalException(fatalException, result.exceptionOrNull()) } } /** * Machinery that handles fatal exceptions in kotlinx.coroutines. * There are two kinds of fatal exceptions: * * 1) Exceptions from kotlinx.coroutines code. Such exceptions indicate that either * the library or the compiler has a bug that breaks internal invariants. * They usually have specific workarounds, but require careful study of the cause and should * be reported to the maintainers and fixed on the library's side anyway. * * 2) Exceptions from [ThreadContextElement.updateThreadContext] and [ThreadContextElement.restoreThreadContext]. * While a user code can trigger such exception by providing an improper implementation of [ThreadContextElement], * we can't ignore it because it may leave coroutine in the inconsistent state. * If you encounter such exception, you can either disable this context element or wrap it into * another context element that catches all exceptions and handles it in the application specific manner. * * Fatal exception handling can be intercepted with [CoroutineExceptionHandler] element in the context of * a failed coroutine, but such exceptions should be reported anyway. */ public fun handleFatalException(exception: Throwable?, finallyException: Throwable?) { if (exception === null && finallyException === null) return if (exception !== null && finallyException !== null) { exception.addSuppressedThrowable(finallyException) } val cause = exception ?: finallyException val reason = CoroutinesInternalError("Fatal exception in coroutines machinery for $this. " + "Please read KDoc to 'handleFatalException' method and report this incident to maintainers", cause!!) handleCoroutineException(this.delegate.context, reason) } } internal fun <T> DispatchedTask<T>.dispatch(mode: Int) { assert { mode != MODE_UNINITIALIZED } // invalid mode value for this method val delegate = this.delegate val undispatched = mode == MODE_UNDISPATCHED if (!undispatched && delegate is DispatchedContinuation<*> && mode.isCancellableMode == resumeMode.isCancellableMode) { // dispatch directly using this instance's Runnable implementation val dispatcher = delegate.dispatcher val context = delegate.context if (dispatcher.isDispatchNeeded(context)) { dispatcher.dispatch(context, this) } else { resumeUnconfined() } } else { // delegate is coming from 3rd-party interceptor implementation (and does not support cancellation) // or undispatched mode was requested resume(delegate, undispatched) } } @Suppress("UNCHECKED_CAST") internal fun <T> DispatchedTask<T>.resume(delegate: Continuation<T>, undispatched: Boolean) { // This resume is never cancellable. The result is always delivered to delegate continuation. val state = takeState() val exception = getExceptionalResult(state) val result = if (exception != null) Result.failure(exception) else Result.success(getSuccessfulResult<T>(state)) when { undispatched -> (delegate as DispatchedContinuation).resumeUndispatchedWith(result) else -> delegate.resumeWith(result) } } private fun DispatchedTask<*>.resumeUnconfined() { val eventLoop = ThreadLocalEventLoop.eventLoop if (eventLoop.isUnconfinedLoopActive) { // When unconfined loop is active -- dispatch continuation for execution to avoid stack overflow eventLoop.dispatchUnconfined(this) } else { // Was not active -- run event loop until all unconfined tasks are executed runUnconfinedEventLoop(eventLoop) { resume(delegate, undispatched = true) } } } internal inline fun DispatchedTask<*>.runUnconfinedEventLoop( eventLoop: EventLoop, block: () -> Unit ) { eventLoop.incrementUseCount(unconfined = true) try { block() while (true) { // break when all unconfined continuations where executed if (!eventLoop.processUnconfinedEvent()) break } } catch (e: Throwable) { /* * This exception doesn't happen normally, only if we have a bug in implementation. * Report it as a fatal exception. */ handleFatalException(e, null) } finally { eventLoop.decrementUseCount(unconfined = true) } } @Suppress("NOTHING_TO_INLINE") internal inline fun Continuation<*>.resumeWithStackTrace(exception: Throwable) { resumeWith(Result.failure(recoverStackTrace(exception, this))) }
apache-2.0
48294766a0c0f360ced2e5906dba2087
42.986364
123
0.683786
4.972765
false
false
false
false
leafclick/intellij-community
platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BasePartiallyExcludedChangesTest.kt
1
3879
// 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.openapi.vcs import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.ui.PartiallyExcludedFilesStateHolder import com.intellij.openapi.vcs.ex.ExclusionState import com.intellij.openapi.vcs.ex.PartialLocalLineStatusTracker import com.intellij.openapi.vcs.impl.PartialChangesUtil abstract class BasePartiallyExcludedChangesTest : BaseLineStatusTrackerManagerTest() { protected lateinit var stateHolder: MyStateHolder override fun setUp() { super.setUp() stateHolder = MyStateHolder() stateHolder.updateExclusionStates() } protected inner class MyStateHolder : PartiallyExcludedFilesStateHolder<FilePath>(getProject()) { val paths = HashSet<FilePath>() init { Disposer.register(testRootDisposable, this) } override val trackableElements: Sequence<FilePath> get() = paths.asSequence() override fun getChangeListId(element: FilePath): String = DEFAULT.asListNameToId() override fun findElementFor(tracker: PartialLocalLineStatusTracker, changeListId: String): FilePath? { return paths.find { it.virtualFile == tracker.virtualFile } } override fun findTrackerFor(element: FilePath): PartialLocalLineStatusTracker? { val file = element.virtualFile ?: return null return PartialChangesUtil.getPartialTracker(getProject(), file) } fun toggleElements(elements: Collection<FilePath>) { val hasExcluded = elements.any { getExclusionState(it) != ExclusionState.ALL_INCLUDED } if (hasExcluded) includeElements(elements) else excludeElements(elements) } fun waitExclusionStateUpdate() { myUpdateQueue.flush() } } protected fun setHolderPaths(vararg paths: String) { stateHolder.paths.clear() stateHolder.paths.addAll(paths.toFilePaths()) } protected fun waitExclusionStateUpdate() { stateHolder.waitExclusionStateUpdate() } protected fun toggle(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.toggleElements(paths.toFilePaths()) } protected fun include(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.includeElements(paths.toFilePaths()) } protected fun exclude(vararg paths: String) { assertContainsElements(stateHolder.paths, paths.toFilePaths()) stateHolder.excludeElements(paths.toFilePaths()) } protected fun assertIncluded(vararg paths: String) { val expected = paths.toFilePaths().toSet() val actual = stateHolder.getIncludedSet() assertSameElements(actual.map { it.name }, expected.map { it.name }) assertSameElements(actual, expected) } protected fun PartialLocalLineStatusTracker.assertExcluded(index: Int, expected: Boolean) { val range = this.getRanges()!![index] assertEquals(expected, range.isExcludedFromCommit) } protected fun String.assertExcludedState(holderState: ExclusionState, trackerState: ExclusionState = holderState) { val actual = stateHolder.getExclusionState(this.toFilePath) assertEquals(holderState, actual) val tracker = this.toFilePath.virtualFile?.tracker as? PartialLocalLineStatusTracker if (tracker != null) { tracker.assertExcludedState(trackerState, DEFAULT) } } protected fun PartialLocalLineStatusTracker.exclude(index: Int, isExcluded: Boolean) { val ranges = getRanges()!! this.setExcludedFromCommit(ranges[index], isExcluded) waitExclusionStateUpdate() } protected fun PartialLocalLineStatusTracker.moveTo(index: Int, changelistName: String) { val ranges = getRanges()!! this.moveToChangelist(ranges[index], changelistName.asListNameToList()) waitExclusionStateUpdate() } }
apache-2.0
70904600be02a573db10b2d22a397e6c
35.261682
140
0.757927
4.684783
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/diff/GitSubmoduleDiffRequestProvider.kt
1
3098
// 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 git4idea.diff import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffRequestFactoryImpl import com.intellij.diff.DiffRequestFactoryImpl.DIFF_TITLE_RENAME_SEPARATOR import com.intellij.diff.chains.DiffRequestProducerException import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.CurrentContentRevision import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer.* import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProvider import com.intellij.util.ThreeState class GitSubmoduleDiffRequestProvider : ChangeDiffRequestProvider { override fun isEquals(change1: Change, change2: Change): ThreeState { return ThreeState.UNSURE } override fun canCreate(project: Project?, change: Change): Boolean { val beforeRevision = change.beforeRevision val afterRevision = change.afterRevision return beforeRevision is GitSubmoduleContentRevision || afterRevision is GitSubmoduleContentRevision } @Throws(ProcessCanceledException::class, DiffRequestProducerException::class) override fun process(presentable: ChangeDiffRequestProducer, context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { val change = presentable.change var beforeRevision = change.beforeRevision var afterRevision = change.afterRevision if (afterRevision is CurrentContentRevision) { require(beforeRevision is GitSubmoduleContentRevision) val submodule = beforeRevision.submodule afterRevision = GitSubmoduleContentRevision.createCurrentRevision(submodule) } else if (beforeRevision is CurrentContentRevision) { require(afterRevision is GitSubmoduleContentRevision) val submodule = afterRevision.submodule beforeRevision = GitSubmoduleContentRevision.createCurrentRevision(submodule) } val factory = DiffContentFactory.getInstance() val beforeContent = beforeRevision?.content?.let { factory.create(it) } ?: factory.createEmpty() val afterContent = afterRevision?.content?.let { factory.create(it) } ?: factory.createEmpty() val title = DiffRequestFactoryImpl.getTitle(beforeRevision?.file, afterRevision?.file, DIFF_TITLE_RENAME_SEPARATOR) return SimpleDiffRequest("$title (Submodule)", beforeContent, afterContent, getRevisionTitle(beforeRevision, getBaseVersion()), getRevisionTitle(afterRevision, getYourVersion())) } }
apache-2.0
f02054dad7ab4a2bce9fc2edb62d4698
50.633333
140
0.772111
5.146179
false
false
false
false
leafclick/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/GroovyInferenceSessionBuilder.kt
1
9758
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.PsiElement import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.PsiTypeParameter import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.TypeConversionUtil import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrThrowStatement import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.* import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrIndexProperty import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.api.types.GrClassTypeElement import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter.Position.* import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses import org.jetbrains.plugins.groovy.lang.resolve.MethodResolveResult import org.jetbrains.plugins.groovy.lang.resolve.api.Argument import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument import org.jetbrains.plugins.groovy.lang.resolve.api.GroovyMethodCandidate import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getContainingCall open class GroovyInferenceSessionBuilder constructor( private val context: PsiElement, private val candidate: GroovyMethodCandidate, private val contextSubstitutor: PsiSubstitutor ) { protected var expressionFilters = mutableSetOf<ExpressionPredicate>() protected var skipClosureBlock = true fun resolveMode(skipClosureBlock: Boolean): GroovyInferenceSessionBuilder { //TODO:add explicit typed closure constraints this.skipClosureBlock = skipClosureBlock return this } fun ignoreArguments(arguments: Collection<Argument>): GroovyInferenceSessionBuilder { expressionFilters.add { ExpressionArgument(it) !in arguments } return this } fun skipClosureIn(call: GrCall): GroovyInferenceSessionBuilder { expressionFilters.add { it !is GrFunctionalExpression || call != getContainingCall(it) } return this } protected fun collectExpressionFilters() { if (skipClosureBlock) expressionFilters.add(ignoreFunctionalExpressions) } open fun build(): GroovyInferenceSession { collectExpressionFilters() val session = GroovyInferenceSession(candidate.method.typeParameters, contextSubstitutor, context, skipClosureBlock, expressionFilters) return doBuild(session) } protected fun doBuild(basicSession: GroovyInferenceSession): GroovyInferenceSession { basicSession.initArgumentConstraints(candidate.argumentMapping) return basicSession } } fun buildTopLevelSession(place: PsiElement, session: GroovyInferenceSession = constructDefaultInferenceSession(place)): GroovyInferenceSession { val expression = findExpression(place) ?: return session val startConstraint = if (expression is GrBinaryExpression || expression is GrAssignmentExpression && expression.isOperatorAssignment) { OperatorExpressionConstraint(expression as GrOperatorExpression) } else if (expression is GrSafeCastExpression && expression.operand !is GrFunctionalExpression) { val result = expression.reference.advancedResolve() as? GroovyMethodResult ?: return session MethodCallConstraint(null, result, expression) } else { val mostTopLevelExpression = getMostTopLevelExpression(expression) val typeAndPosition = getExpectedTypeAndPosition(mostTopLevelExpression) ExpressionConstraint(typeAndPosition, mostTopLevelExpression) } session.addConstraint(startConstraint) return session } private fun constructDefaultInferenceSession(place: PsiElement): GroovyInferenceSession { return GroovyInferenceSession(PsiTypeParameter.EMPTY_ARRAY, PsiSubstitutor.EMPTY, place, false) } fun findExpression(place: PsiElement): GrExpression? { val parent = place.parent return when { parent is GrAssignmentExpression && parent.lValue === place -> parent place is GrIndexProperty -> place parent is GrMethodCall -> parent parent is GrNewExpression -> parent parent is GrClassTypeElement -> parent.parent as? GrSafeCastExpression place is GrExpression -> place else -> null } } fun getMostTopLevelExpression(start: GrExpression): GrExpression { var current: GrExpression = start while (true) { val parent = current.parent current = if (parent is GrArgumentList) { val grandParent = parent.parent if (grandParent is GrCallExpression && grandParent.advancedResolve() is MethodResolveResult) { grandParent } else { return current } } else { return current } } } fun getExpectedType(expression: GrExpression): PsiType? { return getExpectedTypeAndPosition(expression)?.type } private fun getExpectedTypeAndPosition(expression: GrExpression): ExpectedType? { return getAssignmentOrReturnExpectedTypeAndPosition(expression) ?: getArgumentExpectedType(expression) } private fun getAssignmentOrReturnExpectedTypeAndPosition(expression: GrExpression): ExpectedType? { return getAssignmentExpectedType(expression)?.let { ExpectedType(it, ASSIGNMENT) } ?: getReturnExpectedType(expression)?.let { ExpectedType(it, RETURN_VALUE) } } fun getAssignmentOrReturnExpectedType(expression: GrExpression): PsiType? { return getAssignmentExpectedType(expression) ?: getReturnExpectedType(expression) } fun getAssignmentExpectedType(expression: GrExpression): PsiType? { val parent: PsiElement = expression.parent if (parent is GrAssignmentExpression && expression == parent.rValue) { val lValue: PsiElement? = skipParentheses(parent.lValue, false) return if (lValue is GrExpression && lValue !is GrIndexProperty) lValue.nominalType else null } else if (parent is GrVariable) { return parent.declaredType } else if (parent is GrListOrMap) { val pParent: PsiElement? = parent.parent if (pParent is GrVariableDeclaration && pParent.isTuple) { val index: Int = parent.initializers.indexOf(expression) return pParent.variables.getOrNull(index)?.declaredType } else if (pParent is GrTupleAssignmentExpression) { val index: Int = parent.initializers.indexOf(expression) val expressions: Array<out GrReferenceExpression> = pParent.lValue.expressions val lValue: GrReferenceExpression = expressions.getOrNull(index) ?: return null val variable: GrVariable? = lValue.staticReference.resolve() as? GrVariable return variable?.declaredType } } return null } private fun getReturnExpectedType(expression: GrExpression): PsiType? { val parent: PsiElement = expression.parent val parentMethod: GrMethod? = PsiTreeUtil.getParentOfType(parent, GrMethod::class.java, false, GrFunctionalExpression::class.java) if (parentMethod == null) { return null } if (parent is GrReturnStatement) { return parentMethod.returnType } else if (isExitPoint(expression)) { val returnType: PsiType = parentMethod.returnType ?: return null if (TypeConversionUtil.isVoidType(returnType)) return null return returnType } return null } private fun getArgumentExpectedType(expression: GrExpression): ExpectedType? { val parent = expression.parent as? GrArgumentList ?: return null val call = parent.parent as? GrCallExpression ?: return null val result = call.advancedResolve() as? GroovyMethodResult ?: return null val mapping = result.candidate?.argumentMapping ?: return null val type = result.substitutor.substitute(mapping.expectedType(ExpressionArgument(expression))) ?: return null return ExpectedType(type, METHOD_PARAMETER) } internal typealias ExpressionPredicate = (GrExpression) -> Boolean private val ignoreFunctionalExpressions: ExpressionPredicate = { it !is GrFunctionalExpression } private fun isExitPoint(place: GrExpression): Boolean { return collectExitPoints(place).contains(place) } private fun collectExitPoints(place: GrExpression): List<GrStatement> { return if (canBeExitPoint(place)) { val flowOwner = ControlFlowUtils.findControlFlowOwner(place) ControlFlowUtils.collectReturns(flowOwner) } else { emptyList() } } private fun canBeExitPoint(element: PsiElement?): Boolean { var place = element while (place != null) { if (place is GrMethod || place is GrFunctionalExpression || place is GrClassInitializer) return true if (place is GrThrowStatement || place is GrTypeDefinitionBody || place is GroovyFile) return false place = place.parent } return false }
apache-2.0
fc05e17821975dd4b1e18051c1f0f2bc
40.523404
140
0.785304
4.840278
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-serialization/src/main/kotlin/slatekit/serialization/responses/ResponseDecoder.kt
1
3405
package slatekit.serialization.responses import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser import slatekit.results.* import slatekit.results.builders.Outcomes /** * { "errs": [{ "field": "email", "type": "input", "message": "Email already exists", "value": "[email protected]" }], "code": 500004, "success": false, "meta": null, "name": "CONFLICT", "tag": null, "value": null, "desc": "Conflict" } */ object ResponseDecoder { fun <T> outcome(json: String?, cls:Class<*>, converter:(JSONObject) -> T): Outcome<T> { val parser = JSONParser() val doc = parser.parse(json) val root = doc as JSONObject val result = when(root.get("success") as Boolean) { true -> { val status = decodeStatus(root) as Passed val value = converter(root) Success(value, status) } false -> { val status = decodeStatus(root) as Failed if (root.containsKey("errs")) { val errList = decodeErrs(root) Failure<Err>(errList, status) } else { Failure<Err>(Err.of("unable to parse result"), status) } } } return result } fun decodeStatus(root:JSONObject): Status { val code = (root.get("code") as Long).toInt() val status = when(val s = Codes.toStatus(code)){ null -> { val name = root.get("name") as String val desc = root.get("desc") as String val type = root.get("type") as String when(type) { "Succeeded" -> Passed.Succeeded(name, code, desc) "Pending" -> Passed.Pending(name, code, desc) "Denied" -> Failed.Denied (name, code, desc) "Ignored" -> Failed.Ignored(name, code, desc) "Invalid" -> Failed.Invalid(name, code, desc) "Errored" -> Failed.Errored(name, code, desc) else -> Failed.Unknown(name, code, desc) } } else -> s } return status } fun decodeErrs(root:JSONObject): Err.ErrorList { val errs = when(val errs = root.get("errs")) { is JSONArray -> { errs.mapNotNull { err -> when(err) { is JSONObject -> decodeErr(err) else -> null } } } else -> listOf() } return Err.ErrorList(errs, if(errs.isNotEmpty()) errs[0].msg else "") } fun decodeErr(err:JSONObject): Err { val type = err.getValue("type") return when(type?.toString()?.trim()){ "input" -> { Err.on( field = err.getValue("field") as String, value = err.getValue("value") as String, msg = err.getValue("message") as String ) } "action" -> { Err.of(msg = err.getValue("message") as String) } else -> Err.of(msg = err.getValue("message") as String) } } }
apache-2.0
8be4d660c385744959595a3fdc6a686c
30.831776
91
0.474009
4.387887
false
false
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/run/runAnything/PyRunAnythingProvider.kt
1
2915
// 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.run.runAnything import com.intellij.execution.RunManager import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.actions.ChooseRunConfigurationPopup import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.ParametersList import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.ide.actions.runAnything.activity.RunAnythingMatchedRunConfigurationProvider import com.intellij.openapi.actionSystem.DataContext import com.jetbrains.python.run.PythonConfigurationType import com.jetbrains.python.run.PythonRunConfiguration /** * @author vlan */ class PyRunAnythingProvider : RunAnythingMatchedRunConfigurationProvider() { override fun createConfiguration(dataContext: DataContext, pattern: String): RunnerAndConfigurationSettings { val runManager = RunManager.getInstance(dataContext.project) val settings = runManager.createConfiguration(pattern, configurationFactory) val commandLine = ParametersList.parse(pattern) val arguments = commandLine.drop(1) val configuration = settings.configuration as? PythonRunConfiguration val workingDir = dataContext.virtualFile configuration?.apply { val first = arguments.getOrNull(0) when { first == "-m" -> { scriptName = arguments.getOrNull(1) scriptParameters = ParametersList.join(arguments.drop(2)) isModuleMode = true } first?.startsWith("-m") == true -> { scriptName = first.substring(2) scriptParameters = ParametersList.join(arguments.drop(1)) isModuleMode = true } else -> { scriptName = first scriptParameters = ParametersList.join(arguments.drop(1)) } } workingDir?.findPythonSdk(project)?.let { sdkHome = it.homePath } workingDir?.let { workingDirectory = it.canonicalPath } } return settings } override fun getConfigurationFactory(): ConfigurationFactory = PythonConfigurationType.getInstance().factory override fun findMatchingValue(dataContext: DataContext, pattern: String): ChooseRunConfigurationPopup.ItemWrapper<*>? { if (!pattern.startsWith("python ")) return null val configuration = createConfiguration(dataContext, pattern) try { configuration.checkSettings() } catch (e: RuntimeConfigurationException) { return null } return ChooseRunConfigurationPopup.ItemWrapper.wrap(dataContext.project, configuration) } override fun getHelpCommand() = "python" override fun getHelpGroupTitle(): String? = "Python" override fun getHelpCommandPlaceholder() = "python <file name>" }
apache-2.0
54f6904df511bfcfa97a8b0eb76b0db7
38.391892
140
0.741681
5.252252
false
true
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/home/PaymentFragment.kt
1
3406
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package ui.home import androidx.lifecycle.ViewModelProvider import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import org.blokada.R import ui.AccountViewModel import ui.BottomSheetFragment import ui.app import ui.utils.getColorFromAttr import utils.Links import utils.withBoldSections class PaymentFragment : BottomSheetFragment() { private lateinit var vm: AccountViewModel companion object { fun newInstance() = PaymentFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.let { vm = ViewModelProvider(it.app()).get(AccountViewModel::class.java) } val root = inflater.inflate(R.layout.fragment_payment, container, false) val back: View = root.findViewById(R.id.back) back.setOnClickListener { dismiss() } val slugline: TextView = root.findViewById(R.id.payment_slugline) slugline.text = getString(R.string.payment_title).withBoldSections( requireContext().getColorFromAttr(android.R.attr.textColor) ) vm.account.observe(viewLifecycleOwner, { account -> val proceed: View = root.findViewById(R.id.payment_continue) proceed.setOnClickListener { dismiss() val nav = findNavController() nav.navigate(HomeFragmentDirections.actionNavigationHomeToWebFragment( Links.manageSubscriptions(account.id), getString(R.string.universal_action_upgrade) )) } val restore: View = root.findViewById(R.id.payment_restore) restore.setOnClickListener { dismiss() val nav = findNavController() nav.navigate(HomeFragmentDirections.actionNavigationHomeToWebFragment( Links.howToRestore, getString(R.string.payment_action_restore) )) } }) val terms: View = root.findViewById(R.id.payment_terms) terms.setOnClickListener { dismiss() val fragment = PaymentTermsFragment.newInstance() fragment.show(parentFragmentManager, null) } val seeAllFeatures: View = root.findViewById(R.id.payment_allfeatures) seeAllFeatures.setOnClickListener { dismiss() val fragment = PaymentFeaturesFragment.newInstance() fragment.show(parentFragmentManager, null) } val seeLocations: View = root.findViewById(R.id.payment_locations) seeLocations.setOnClickListener { dismiss() val fragment = LocationFragment.newInstance() fragment.clickable = false fragment.show(parentFragmentManager, null) } return root } }
mpl-2.0
b4403eb3507d343525bb07d5920b6a5f
31.75
103
0.655507
4.836648
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/regressions/kt5953.kt
2
225
// WITH_RUNTIME fun box(): String { val res = (1..3).map { it -> if (it == 1) 2 }; var result = "" for (i in res) result += " " return if (result == " ") "OK" else result }
apache-2.0
4c134f65739e415cf94525109b2950b7
16.307692
48
0.408889
3.26087
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/toArray/toArrayAlreadyPresent.kt
3
1073
// TARGET_BACKEND: JVM // WITH_RUNTIME import java.util.Arrays class MyCollection<T>(val delegate: Collection<T>): Collection<T> by delegate { public fun toArray(): Array<Any?> { val a = arrayOfNulls<Any?>(3) a[0] = 0 a[1] = 1 a[2] = 2 return a } public fun <E> toArray(array: Array<E>): Array<E> { val asIntArray = array as Array<Int> asIntArray[0] = 0 asIntArray[1] = 1 asIntArray[2] = 2 return array } } fun box(): String { val collection = MyCollection(Arrays.asList(2, 3, 9)) as java.util.Collection<*> val array1 = collection.toArray() val array2 = collection.toArray(arrayOfNulls<Int>(3) as Array<Int>) if (!array1.isArrayOf<Any>()) return (array1 as Object).getClass().toString() if (!array2.isArrayOf<Int>()) return (array2 as Object).getClass().toString() val s1 = Arrays.toString(array1) val s2 = Arrays.toString(array2) if (s1 != "[0, 1, 2]") return "s1 = $s1" if (s2 != "[0, 1, 2]") return "s2 = $s2" return "OK" }
apache-2.0
4aba11443ecb17cb30b3f05d1436c628
25.825
84
0.588071
3.281346
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/primitiveTypes/comparisonWithNullCallsFun.kt
5
242
var entered = 0 fun <T> foo(t: T): T { entered++ return t } fun box(): String { if (foo(null) == null) {} if (null == foo(null)) {} if (foo(null) == foo(null)) {} return if (entered == 4) "OK" else "Fail $entered" }
apache-2.0
a0175cee3fb726b1a3afe9c075e626eb
17.615385
54
0.504132
2.781609
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/dsl/KotlinSequenceTypes.kt
6
4717
// 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.debugger.sequence.trace.dsl import com.intellij.debugger.streams.trace.dsl.Types import com.intellij.debugger.streams.trace.impl.handler.type.* import org.jetbrains.kotlin.builtins.StandardNames.FqNames object KotlinSequenceTypes : Types { override val ANY: GenericType = ClassTypeImpl(FqNames.any.asString(), "kotlin.Any()") override val BOOLEAN: GenericType = ClassTypeImpl(FqNames._boolean.asString(), "false") val BYTE: GenericType = ClassTypeImpl(FqNames._byte.asString(), "0") val SHORT: GenericType = ClassTypeImpl(FqNames._short.asString(), "0") val CHAR: GenericType = ClassTypeImpl(FqNames._char.asString(), "0.toChar()") override val INT: GenericType = ClassTypeImpl(FqNames._int.asString(), "0") override val LONG: GenericType = ClassTypeImpl(FqNames._long.asString(), "0L") val FLOAT: GenericType = ClassTypeImpl(FqNames._float.asString(), "0.0f") override val DOUBLE: GenericType = ClassTypeImpl(FqNames._double.asString(), "0.0") override val STRING: GenericType = ClassTypeImpl(FqNames.string.asString(), "\"\"") override val EXCEPTION: GenericType = ClassTypeImpl(FqNames.throwable.asString(), "kotlin.Throwable()") override val VOID: GenericType = ClassTypeImpl(FqNames.unit.asString(), "Unit") val NULLABLE_ANY: GenericType = nullable { ANY } override val TIME: GenericType = ClassTypeImpl( "java.util.concurrent.atomic.AtomicInteger", "java.util.concurrent.atomic.AtomicInteger()" ) override fun list(elementsType: GenericType): ListType = ListTypeImpl(elementsType, { "kotlin.collections.MutableList<$it>" }, "kotlin.collections.mutableListOf()") override fun array(elementType: GenericType): ArrayType = when (elementType) { BOOLEAN -> ArrayTypeImpl(BOOLEAN, { "kotlin.BooleanArray" }, { "kotlin.BooleanArray($it)" }) BYTE -> ArrayTypeImpl(BYTE, { "kotlin.ByteArray" }, { "kotlin.ByteArray($it)" }) SHORT -> ArrayTypeImpl(SHORT, { "kotlin.ShortArray" }, { "kotlin.ShortArray($it)" }) CHAR -> ArrayTypeImpl(CHAR, { "kotlin.CharArray" }, { "kotlin.CharArray($it)" }) INT -> ArrayTypeImpl(INT, { "kotlin.IntArray" }, { "kotlin.IntArray($it)" }) LONG -> ArrayTypeImpl(LONG, { "kotlin.LongArray" }, { "kotlin.LongArray($it)" }) FLOAT -> ArrayTypeImpl(FLOAT, { "kotlin.FloatArray" }, { "kotlin.FloatArray($it)" }) DOUBLE -> ArrayTypeImpl(DOUBLE, { "kotlin.DoubleArray" }, { "kotlin.DoubleArray($it)" }) else -> ArrayTypeImpl(nullable { elementType }, { "kotlin.Array<$it>" }, { "kotlin.arrayOfNulls<${elementType.genericTypeName}>($it)" }) } override fun map(keyType: GenericType, valueType: GenericType): MapType = MapTypeImpl( keyType, valueType, { keys, values -> "kotlin.collections.MutableMap<$keys, $values>" }, "kotlin.collections.mutableMapOf()" ) override fun linkedMap(keyType: GenericType, valueType: GenericType): MapType = MapTypeImpl( keyType, valueType, { keys, values -> "kotlin.collections.MutableMap<$keys, $values>" }, "kotlin.collections.linkedMapOf()" ) override fun nullable(typeSelector: Types.() -> GenericType): GenericType { val type = this.typeSelector() if (type.genericTypeName.last() == '?') return type return when (type) { is ArrayType -> ArrayTypeImpl(type.elementType, { "kotlin.Array<$it>?" }, { type.sizedDeclaration(it) }) is ListType -> ListTypeImpl(type.elementType, { "kotlin.collections.MutableList<$it>?" }, type.defaultValue) is MapType -> MapTypeImpl( type.keyType, type.valueType, { keys, values -> "kotlin.collections.MutableMap<$keys, $values>?" }, type.defaultValue ) else -> ClassTypeImpl(type.genericTypeName + '?', type.defaultValue) } } private val primitiveTypesIndex: Map<String, GenericType> = listOf( BOOLEAN, BYTE, INT, SHORT, CHAR, LONG, FLOAT, DOUBLE ).associateBy { it.genericTypeName } private val primitiveArraysIndex: Map<String, ArrayType> = primitiveTypesIndex.asSequence() .map { array(it.value) } .associateBy { it.genericTypeName } fun primitiveTypeByName(typeName: String): GenericType? = primitiveTypesIndex[typeName] fun primitiveArrayByName(typeName: String): ArrayType? = primitiveArraysIndex[typeName] }
apache-2.0
15e3594e830662d50626a55515df21bb
52
158
0.665889
4.400187
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/search/PsiBasedClassResolver.kt
4
10975
// 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.search import com.intellij.openapi.util.Key import com.intellij.psi.PsiClass import com.intellij.psi.PsiModifier import com.intellij.psi.search.PsiShortNamesCache 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.asJava.ImpreciseResolveResult import org.jetbrains.kotlin.asJava.ImpreciseResolveResult.* import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.findTypeAliasByShortName import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.getDefaultImports import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypeAndBranch import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs import java.util.concurrent.atomic.AtomicInteger /** * Can quickly check whether a short name reference in a given file can resolve to the class/interface/type alias * with the given qualified name. */ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName: String) { private val targetShortName = targetClassFqName.substringAfterLast('.') private val targetPackage = targetClassFqName.substringBeforeLast('.', "") /** * Qualified names of packages which contain classes with the same short name as the target class. */ private val conflictingPackages = mutableListOf<String>() /** * Qualified names of packages which contain typealiases with the same short name as the target class * (which may or may not resolve to the target class). */ private val packagesWithTypeAliases = mutableListOf<String>() private var forceAmbiguity: Boolean = false private var forceAmbiguityForInnerAnnotations: Boolean = false private var forceAmbiguityForNonAnnotations: Boolean = false companion object { @get:TestOnly val attempts = AtomicInteger() @get:TestOnly val trueHits = AtomicInteger() @get:TestOnly val falseHits = AtomicInteger() private val PSI_BASED_CLASS_RESOLVER_KEY = Key<CachedValue<PsiBasedClassResolver>>("PsiBasedClassResolver") fun getInstance(target: PsiClass): PsiBasedClassResolver { target.getUserData(PSI_BASED_CLASS_RESOLVER_KEY)?.let { return it.value } val cachedValue = CachedValuesManager.getManager(target.project).createCachedValue( { CachedValueProvider.Result( PsiBasedClassResolver(target), KotlinCodeBlockModificationListener.getInstance(target.project).kotlinOutOfCodeBlockTracker ) }, false ) target.putUserData(PSI_BASED_CLASS_RESOLVER_KEY, cachedValue) return cachedValue.value } } private constructor(target: PsiClass) : this(target.qualifiedName ?: "") { if (target.qualifiedName == null || target.containingClass != null || targetPackage.isEmpty()) { forceAmbiguity = true return } runReadAction { findPotentialClassConflicts(target) findPotentialTypeAliasConflicts(target) } } private fun findPotentialClassConflicts(target: PsiClass) { val candidates = PsiShortNamesCache.getInstance(target.project).getClassesByName(targetShortName, target.project.allScope()) for (candidate in candidates) { // An inner class can be referenced by short name in subclasses without an explicit import if (candidate.containingClass != null && !candidate.hasModifierProperty(PsiModifier.PRIVATE)) { if (candidate.isAnnotationType) { forceAmbiguityForInnerAnnotations = true } else { forceAmbiguityForNonAnnotations = true } break } if (candidate.qualifiedName == target.qualifiedName) { // File with same FQ name in another module, don't bother with analyzing dependencies if (candidate.navigationElement.containingFile != target.navigationElement.containingFile) { forceAmbiguity = true break } } else { candidate.qualifiedName?.substringBeforeLast('.', "")?.let { candidatePackage -> if (candidatePackage == "") forceAmbiguity = true else conflictingPackages.add(candidatePackage) } } } } private fun findPotentialTypeAliasConflicts(target: PsiClass) { val candidates = findTypeAliasByShortName(targetShortName, target.project, target.project.allScope()) for (candidate in candidates) { packagesWithTypeAliases.add(candidate.containingKtFile.packageFqName.asString()) } } @TestOnly fun addConflict(fqName: String) { conflictingPackages.add(fqName.substringBeforeLast('.')) } /** * Checks if a reference with the short name of [targetClassFqName] in the given file will resolve * to the target class. * * @return true if it will definitely resolve to that class, false if it will definitely resolve to something else, * null if full resolve is required to answer that question. */ fun canBeTargetReference(ref: KtSimpleNameExpression): ImpreciseResolveResult { attempts.incrementAndGet() // The names can be different if the target was imported via an import alias if (ref.getReferencedName() != targetShortName) { return UNSURE } // Names in expressions can conflict with local declarations and methods of implicit receivers, // so we can't find out what they refer to without a full resolve. val userType = ref.getStrictParentOfType<KtUserType>() ?: return UNSURE val parentAnnotation = userType.getParentOfTypeAndBranch<KtAnnotationEntry> { typeReference } if (forceAmbiguityForNonAnnotations && parentAnnotation == null) return UNSURE //For toplevel declarations it's fine to resolve by imports val declaration = parentAnnotation?.getParentOfType<KtDeclaration>(true) if (forceAmbiguityForInnerAnnotations && declaration?.parent !is KtFile) return UNSURE if (forceAmbiguity) return UNSURE val qualifiedCheckResult = checkQualifiedReferenceToTarget(ref) if (qualifiedCheckResult != null) return qualifiedCheckResult.returnValue val file = ref.containingKtFile var result: Result = Result.NothingFound when (file.packageFqName.asString()) { targetPackage -> result = result.changeTo(Result.Found) in conflictingPackages -> result = result.changeTo(Result.FoundOther) in packagesWithTypeAliases -> return UNSURE } for (importPath in file.getDefaultImports()) { result = analyzeSingleImport(result, importPath.fqName, importPath.isAllUnder, importPath.alias?.asString()) if (result == Result.Ambiguity) return UNSURE } for (importDirective in file.importDirectives) { result = analyzeSingleImport(result, importDirective.importedFqName, importDirective.isAllUnder, importDirective.aliasName) if (result == Result.Ambiguity) return UNSURE } if (result.returnValue == MATCH) { trueHits.incrementAndGet() } else if (result.returnValue == NO_MATCH) { falseHits.incrementAndGet() } return result.returnValue } private fun analyzeSingleImport(result: Result, importedFqName: FqName?, isAllUnder: Boolean, aliasName: String?): Result { if (!isAllUnder) { if (importedFqName?.asString() == targetClassFqName && (aliasName == null || aliasName == targetShortName) ) { return result.changeTo(Result.Found) } else if (importedFqName?.shortName()?.asString() == targetShortName && importedFqName.parent().asString() in conflictingPackages && aliasName == null ) { return result.changeTo(Result.FoundOther) } else if (importedFqName?.shortName()?.asString() == targetShortName && importedFqName.parent().asString() in packagesWithTypeAliases && aliasName == null ) { return Result.Ambiguity } else if (aliasName == targetShortName) { return result.changeTo(Result.FoundOther) } } else { when { importedFqName?.asString() == targetPackage -> return result.changeTo(Result.Found) importedFqName?.asString() in conflictingPackages -> return result.changeTo(Result.FoundOther) importedFqName?.asString() in packagesWithTypeAliases -> return Result.Ambiguity } } return result } private fun checkQualifiedReferenceToTarget(ref: KtSimpleNameExpression): Result? { // A qualified name can resolve to the target element even if it's not imported, // but it can also resolve to something else e.g. if the file defines a class with the same name // as the top-level package of the target class. ref.parent.safeAs<KtUserType>()?.qualifier?.let { qualifier -> val fqName = sequence { var q: KtUserType? = qualifier while (q?.referencedName != null) { yield(q?.referencedName ?: break) q = q?.qualifier } }.toList().reversed().joinToString(separator = ".") return if (fqName == targetPackage) { Result.Ambiguity } else { Result.FoundOther } } return null } enum class Result(val returnValue: ImpreciseResolveResult) { NothingFound(NO_MATCH), Found(MATCH), FoundOther(NO_MATCH), Ambiguity(UNSURE) } private fun Result.changeTo(newResult: Result): Result { if (this == Result.NothingFound || this.returnValue == newResult.returnValue) { return newResult } return Result.Ambiguity } }
apache-2.0
a2fabf3db18c680e8d1550b38b1d4cb3
42.729084
158
0.658861
5.379902
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/gdpr/AgreementUi.kt
5
9191
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.gdpr import com.intellij.ide.IdeBundle import com.intellij.ide.gdpr.ui.HtmlRtfPane import com.intellij.idea.Main import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.OnePixelDivider import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.text.HtmlChunk import com.intellij.ui.BrowserHyperlinkListener import com.intellij.ui.JBColor import com.intellij.ui.border.CustomLineBorder import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.HTMLEditorKitBuilder import com.intellij.util.ui.JBUI import com.intellij.util.ui.SwingHelper import java.awt.BorderLayout import java.awt.Color import java.awt.event.ActionListener import java.util.* import javax.swing.* import javax.swing.border.Border import javax.swing.border.CompoundBorder import javax.swing.text.html.HTMLDocument import kotlin.system.exitProcess class AgreementUi private constructor(@NlsSafe val htmlText: String, val exitOnCancel: Boolean, val useRtfPane: Boolean = true) { companion object { @JvmStatic fun create(htmlText: String = "", exitOnCancel: Boolean = true, useRtfPane: Boolean = true): AgreementUi { return AgreementUi(htmlText, exitOnCancel, useRtfPane).createDialog() } } private val bundle get() = ResourceBundle.getBundle("messages.AgreementsBundle") private var bottomPanel: JPanel? = null private var htmlRtfPane: HtmlRtfPane? = null private var viewer: JEditorPane? = null private var declineButton: JButton? = null private var acceptButton: JButton? = null private var acceptButtonActionListener: ActionListener? = null private var declineButtonActionListener: ActionListener? = null private val buttonsEastGap = JBUI.scale(15) private var dialog: DialogWrapper? = null private fun createDialog(): AgreementUi { val dialogWrapper = object : DialogWrapper(true) { init { init() } override fun createContentPaneBorder(): Border = JBUI.Borders.empty(0, 0, 12, 0) override fun createButtonsPanel(buttons: List<JButton?>): JPanel { val buttonsPanel = layoutButtonsPanel(buttons) buttonsPanel.border = JBUI.Borders.emptyRight(22) return buttonsPanel } override fun createCenterPanel(): JComponent { val centerPanel = JPanel(BorderLayout(0, 0)) if (useRtfPane) { htmlRtfPane = HtmlRtfPane() viewer = htmlRtfPane?.create(htmlText) viewer!!.background = Color.WHITE } else { viewer = createHtmlEditorPane() } viewer!!.caretPosition = 0 viewer!!.isEditable = false viewer!!.border = JBUI.Borders.empty(30, 30, 30, 60) val scrollPane = JBScrollPane(viewer, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) val color = UIManager.getColor("DialogWrapper.southPanelDivider") val line: Border = CustomLineBorder(color ?: OnePixelDivider.BACKGROUND, 0, 0, 1, 0) scrollPane.border = CompoundBorder(line, JBUI.Borders.empty(0)) centerPanel.add(scrollPane, BorderLayout.CENTER) bottomPanel = JPanel(BorderLayout()) JBUI.Borders.empty(16, 30, 8, 30).wrap(bottomPanel) centerPanel.add(bottomPanel!!, BorderLayout.SOUTH) scrollPane.preferredSize = JBUI.size(600, 356) return centerPanel } override fun createSouthPanel(): JComponent { val panel = JPanel(BorderLayout(0, 0)) val buttonPanel = JPanel() declineButton = JButton(IdeBundle.message("gdpr.exit.button")) acceptButton = JButton(IdeBundle.message("gdpr.continue.button")) panel.add(buttonPanel, BorderLayout.EAST) buttonPanel.layout = BoxLayout(buttonPanel, BoxLayout.X_AXIS) buttonPanel.add(Box.createHorizontalStrut(JBUI.scale(5))) buttonPanel.add(declineButton) buttonPanel.add(Box.createHorizontalStrut(JBUI.scale(5))) buttonPanel.add(acceptButton) buttonPanel.add(Box.createRigidArea(JBUI.size(buttonsEastGap, 5))) declineButton!!.isEnabled = true acceptButton!!.isEnabled = true return panel } override fun getPreferredFocusedComponent(): JComponent? { return viewer } override fun doCancelAction() { super.doCancelAction() if (exitOnCancel) { val application = ApplicationManager.getApplication() if (application == null) { exitProcess(Main.PRIVACY_POLICY_REJECTION) } else { application.exit(true, true, false) } } } } dialog = dialogWrapper return this } private fun createHtmlEditorPane(): JTextPane { return JTextPane().apply { contentType = "text/html" addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) editorKit = HTMLEditorKitBuilder().withGapsBetweenParagraphs().build() text = htmlText val styleSheet = (document as HTMLDocument).styleSheet styleSheet.addRule("body {font-family: \"Segoe UI\", Tahoma, sans-serif;}") styleSheet.addRule("body {font-size:${JBUI.Fonts.label()}pt;}") foreground = JBColor.BLACK background = JBColor.WHITE } } fun setTitle(@NlsContexts.DialogTitle title: String): AgreementUi { dialog?.title = title return this } fun addCheckBox(@NlsContexts.Checkbox checkBoxText: String, checkBoxListener: (JCheckBox) -> Unit): AgreementUi { val checkBox = JCheckBox(checkBoxText) bottomPanel?.add(JBUI.Borders.empty(14, 30, 10, 8).wrap(checkBox), BorderLayout.CENTER) JBUI.Borders.empty().wrap(bottomPanel) checkBox.addActionListener { checkBoxListener(checkBox) } return this } fun addEapPanel(isPrivacyPolicy: Boolean): AgreementUi { val eapPanel = JPanel(BorderLayout(0, 0)) val text = (if (isPrivacyPolicy) bundle.getString("userAgreement.dialog.eap.consents.privacyPolicy") else bundle.getString("userAgreement.dialog.eap.consents.noPrivacyPolicy")) + "<br/>" + bundle.getString("userAgreement.dialog.eap.consents.noPersonalData") val html: JEditorPane = SwingHelper.createHtmlLabel(text, null, null) html.border = JBUI.Borders.empty(10, 16, 10, 0) html.isOpaque = true html.background = Color(0xDCE4E8) val eapLabelStyleSheet = (html.document as HTMLDocument).styleSheet eapLabelStyleSheet.addRule("a {color:#4a78c2;}") eapLabelStyleSheet.addRule("a {text-decoration:none;}") eapPanel.add(html, BorderLayout.CENTER) bottomPanel?.add(JBUI.Borders.empty(14, 30, 0, 30).wrap(eapPanel), BorderLayout.NORTH) return this } fun clearBottomPanel(): AgreementUi { bottomPanel?.removeAll() JBUI.Borders.empty(8, 30, 8, 30).wrap(bottomPanel) return this } fun setContent(newHtml: HtmlChunk): AgreementUi { val htmlRtfPane = htmlRtfPane if (htmlRtfPane != null) { val pane = htmlRtfPane.replaceText(newHtml.toString()) pane.caretPosition = 0 } else { viewer!!.text = newHtml.toString() } return this } fun focusToText(): AgreementUi { viewer?.requestFocus() return this } fun focusToAcceptButton(): AgreementUi { acceptButton?.requestFocus() return this } fun focusToDeclineButton(): AgreementUi { declineButton?.requestFocus() return this } fun setAcceptButton(text: @NlsContexts.Button String, isEnabled: Boolean = true, action: (DialogWrapper) -> Unit): AgreementUi { acceptButton?.text = text if (acceptButtonActionListener != null) acceptButton?.removeActionListener(acceptButtonActionListener) acceptButtonActionListener = ActionListener { action(dialog!!) } acceptButton?.addActionListener(acceptButtonActionListener) if (!isEnabled) acceptButton?.isEnabled = false return this } fun enableAcceptButton(state: Boolean): AgreementUi { acceptButton?.isEnabled = state return this } fun enableDeclineButton(state: Boolean): AgreementUi { declineButton?.isEnabled = state return this } fun setDeclineButton(text: @NlsContexts.Button String, action: (DialogWrapper) -> Unit): AgreementUi { declineButton?.text = text if (declineButtonActionListener != null) declineButton?.removeActionListener(declineButtonActionListener) declineButtonActionListener = ActionListener { action(dialog!!) } declineButton?.addActionListener(declineButtonActionListener) return this } fun setCentralPanelBackground(color: Color?): AgreementUi { viewer!!.background = color return this } fun pack(): DialogWrapper { if (dialog == null) throw IllegalStateException("Dialog hasn't been created.") dialog!!.pack() dialog!!.setSize(JBUI.scale(600), JBUI.scale(460)) dialog!!.isModal = true return dialog!! } }
apache-2.0
ca2c3a8f1895a0daf23fe1479b5c92c3
34.490347
140
0.703514
4.34974
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/SoundFile.kt
1
1776
package com.habitrpg.android.habitica.helpers import android.media.AudioAttributes import android.media.AudioManager import android.media.MediaPlayer import android.os.Build import java.io.File class SoundFile(val theme: String, private val fileName: String) : MediaPlayer.OnCompletionListener { var file: File? = null private var playerPrepared: Boolean = false private var isPlaying: Boolean = false val webUrl: String get() = "https://s3.amazonaws.com/habitica-assets/mobileApp/sounds/$theme/$fileName.mp3" val filePath: String get() = theme + "_" + fileName + ".mp3" fun play() { if (isPlaying || file?.path == null) { return } val m = MediaPlayer() m.setOnCompletionListener { mp -> isPlaying = false mp.release() } try { m.setDataSource(file?.path) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val attributes = AudioAttributes.Builder() .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION) .build() m.setAudioAttributes(attributes) } else { @Suppress("Deprecation") m.setAudioStreamType(AudioManager.STREAM_NOTIFICATION) } m.prepare() playerPrepared = true m.setVolume(100f, 100f) m.isLooping = false isPlaying = true m.start() } catch (e: Exception) { e.printStackTrace() } } override fun onCompletion(mediaPlayer: MediaPlayer) { isPlaying = false } }
gpl-3.0
725f36ec12c8b4b1a4b834ba0a1e1a2b
28.114754
101
0.580518
4.839237
false
false
false
false
FTL-Lang/FTL-Compiler
src/main/kotlin/com/thomas/needham/ftl/frontend/symbols/ParameterSymbol.kt
1
4291
/* The MIT License (MIT) FTL-Lang Copyright (c) 2016 thoma Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.ftl.frontend.symbols import com.thomas.needham.ftl.frontend.symbols.* import java.util.* /** * This class represents a defined parameter within the compiler * @author Thomas Needham */ class ParameterSymbol<Type> : Symbol<Type> { /** * Unique identifier to represent this symbol */ override val id: UUID /** * The name of this symbol */ override val name: String /** * the value of this symbol */ override var value: Type? /** * The scope in which this symbol is defined */ override val scope: Scope /** * Whether this symbol is read only */ override val readOnly: Boolean /** * Whether this symbol is initialised */ override var initialised: Boolean /** * The function that this parameter is passed to */ val function : FunctionSymbol<*> /** * Constructor for parameter symbol * @param id the unique identifier of the symbol * @param name the name of this symbol * @param value the value of this symbol * @param readOnly whether this symbol is read only * @param scope the scope that this symbol is defined in * @param initialised whether this symbol has been initialised defaults to false * @param function the function this parameter is passed to */ constructor(id: UUID, name: String, value: Type?, scope: Scope, readOnly: Boolean, initialised: Boolean, function: FunctionSymbol<*>) : super() { this.id = id this.name = name this.value = value this.scope = scope this.readOnly = readOnly this.initialised = initialised this.function = function } /** * Function to generate unique symbol id * @param table the symbol table that this symbol is in * @return A unique ID to represent a symbol */ override fun generateID(table: SymbolTable): UUID { val symbols : MutableList<Symbol<*>> = table.symbols.filter { e -> e is ParameterSymbol<*> }.toMutableList() var found : Boolean = false var id : UUID = UUID.fromString("0".repeat(128)) while (!found){ id = UUID.randomUUID() for(sym: Symbol<*> in symbols){ if(sym.id == id) found = true } } return id } /** * Function to compare if two symbols are equal * @param other the symbol to compare this symbol with * @return Whether both symbols are equal */ override fun equals(other: Any?): Boolean { if(other !is ParameterSymbol<*>?) return false if (other === null) return true return this.id == other.id && this.name == other.name && this.value == other.value && this.scope == other.scope && this.readOnly == other.readOnly && this.initialised == other.initialised && this.function == other.function } /** * Generates a hashCode for this symbol * @return the generated hash code */ override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + id.hashCode() result = 31 * result + name.hashCode() result = 31 * result + (value?.hashCode() ?: 0) result = 31 * result + scope.hashCode() result = 31 * result + readOnly.hashCode() result = 31 * result + initialised.hashCode() result = 31 * result + function.hashCode() return result } }
mit
7e189105229503f4cb7338f6856d76a0
29.225352
110
0.696574
4.082778
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/viewmodels/EditProfileViewModel.kt
1
5157
package com.kickstarter.viewmodels import androidx.annotation.NonNull import com.kickstarter.libs.ActivityViewModel import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.libs.rx.transformers.Transformers.errors import com.kickstarter.libs.rx.transformers.Transformers.values import com.kickstarter.libs.utils.ListUtils import com.kickstarter.libs.utils.ObjectUtils import com.kickstarter.libs.utils.extensions.isNonZero import com.kickstarter.models.User import com.kickstarter.ui.activities.EditProfileActivity import rx.Notification import rx.Observable import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject interface EditProfileViewModel { interface Inputs { /** Call when user toggles the private profile switch. */ fun showPublicProfile(checked: Boolean) } interface Outputs { /** Emits when the user is a creator and we need to hide the private profile row. */ fun hidePrivateProfileRow(): Observable<Boolean> /** Emits current user. */ fun user(): Observable<User> /** Emits the user's avatar URL. */ fun userAvatarUrl(): Observable<String> /** Emits the user's name. */ fun userName(): Observable<String> } interface Errors { /** Emits when saving preference fails. */ fun unableToSavePreferenceError(): Observable<String> } class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<EditProfileActivity>(environment), Inputs, Outputs, Errors { private val apiClient = requireNotNull(environment.apiClient()) private val currentUser = requireNotNull(environment.currentUser()) private val userInput = PublishSubject.create<User>() private var hidePrivateProfileRow = BehaviorSubject.create<Boolean>() private val unableToSavePreferenceError = PublishSubject.create<Throwable>() private val updateSuccess = PublishSubject.create<Void>() private val user = BehaviorSubject.create<User>() private val userAvatarUrl = BehaviorSubject.create<String>() private val userName = BehaviorSubject.create<String>() val inputs: Inputs = this val outputs: Outputs = this init { val currentUser = this.currentUser.observable() this.apiClient.fetchCurrentUser() .retry(2) .compose(Transformers.neverError()) .compose(bindToLifecycle()) .subscribe { this.currentUser.refresh(it) } currentUser .take(1) .compose(bindToLifecycle()) .subscribe { this.user.onNext(it) } val updateUserNotification = this.userInput .concatMap<Notification<User>> { this.updateSettings(it) } updateUserNotification .compose(values()) .compose(bindToLifecycle()) .subscribe { this.success(it) } updateUserNotification .compose(errors()) .compose(bindToLifecycle()) .subscribe(this.unableToSavePreferenceError) this.userInput .compose(bindToLifecycle()) .subscribe(this.user) this.user .window(2, 1) .flatMap<List<User>> { it.toList() } .map<User> { ListUtils.first(it) } .compose<User>(Transformers.takeWhen<User, Throwable>(this.unableToSavePreferenceError)) .compose(bindToLifecycle()) .subscribe(this.user) currentUser .compose(bindToLifecycle()) .filter(ObjectUtils::isNotNull) .map { user -> user.createdProjectsCount().isNonZero() } .subscribe(this.hidePrivateProfileRow) currentUser .map { u -> u.avatar().medium() } .subscribe(this.userAvatarUrl) currentUser .map { it.name() } .subscribe(this.userName) } override fun userAvatarUrl(): Observable<String> = this.userAvatarUrl override fun hidePrivateProfileRow(): Observable<Boolean> = this.hidePrivateProfileRow override fun showPublicProfile(checked: Boolean) { this.userInput.onNext(this.user.value.toBuilder().showPublicProfile(!checked).build()) } override fun unableToSavePreferenceError(): Observable<String> = this.unableToSavePreferenceError .takeUntil(this.updateSuccess) .map { _ -> null } override fun user(): Observable<User> = this.user override fun userName(): Observable<String> = this.userName private fun success(user: User) { this.currentUser.refresh(user) this.updateSuccess.onNext(null) } private fun updateSettings(user: User): Observable<Notification<User>>? { return this.apiClient.updateUserSettings(user) .materialize() .share() } } }
apache-2.0
5107c168222a08c784f0f43e53476e63
34.8125
139
0.631957
5.240854
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/KtInterfaceKind.kt
1
4259
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.codegen.deft.model import org.jetbrains.deft.Obj import com.intellij.workspaceModel.codegen.deft.* import com.intellij.workspaceModel.codegen.deft.Field abstract class KtInterfaceKind { abstract fun buildField(fieldNumber: Int, field: DefField, scope: KtScope, type: DefType, diagnostics: Diagnostics, keepUnknownFields: Boolean) abstract fun buildValueType( ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation? ): ValueType<*>? } open class WsEntityInterface : KtInterfaceKind() { override fun buildField(fieldNumber: Int, field: DefField, scope: KtScope, type: DefType, diagnostics: Diagnostics, keepUnknownFields: Boolean) { field.toMemberField(scope, type, diagnostics, keepUnknownFields) if (fieldNumber == 0) { val entitySource = Field(type, "entitySource", TBlob<Any>("EntitySource")) entitySource.exDef = field entitySource.open = field.open if (field.expr) { entitySource.hasDefault = if (field.suspend) Field.Default.suspend else Field.Default.plain } entitySource.content = field.content } } override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*>? { val type = ktInterface?.objType return if (type != null) TRef<Obj>(type.id, child = childAnnotation != null).also { it.targetObjType = type } else if (ktType.classifier in listOf("VirtualFileUrl", "EntitySource", "PersistentEntityId")) TBlob<Any>(ktType.classifier) else { diagnostics.add(ktType.classifierRange, "Unsupported type: $ktType. " + "Supported: String, Int, Boolean, List, Set, Map, Serializable, Enum, Data and Sealed classes, subtypes of Obj") null } } } object WsPsiEntityInterface: WsEntityInterface() { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*>? { val type = ktInterface?.objType if (type != null) return TPsiRef<Obj>(type.id, child = childAnnotation != null).also { it.targetObjType = type } return super.buildValueType(ktInterface, diagnostics, ktType, childAnnotation) } } object WsEntityWithPersistentId: WsEntityInterface() object WsUnknownType: WsEntityInterface() { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*> { return TBlob<Any>(ktType.classifier) } } interface WsPropertyClass object WsEnum : WsEntityInterface(), WsPropertyClass { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*> { return TBlob<Any>(ktType.classifier) } } object WsData : WsEntityInterface(), WsPropertyClass { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*> { return TBlob<Any>(ktType.classifier) } } object WsSealed : WsEntityInterface(), WsPropertyClass { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*> { return TBlob<Any>(ktType.classifier) } } object WsObject : WsEntityInterface(), WsPropertyClass { override fun buildValueType(ktInterface: KtInterface?, diagnostics: Diagnostics, ktType: KtType, childAnnotation: KtAnnotation?): ValueType<*> { return TBlob<Any>(ktType.classifier) } }
apache-2.0
89f824e5a4a3e989746264e456ea379b
39.571429
158
0.65344
4.834279
false
false
false
false
chemouna/Nearby
app/src/main/kotlin/com/mounacheikhna/nearby/photo/RoundedCornersTransformation.kt
1
1034
package com.mounacheikhna.nearby.photo import android.graphics.* import com.squareup.picasso.Transformation /** * A picasso transformation to add small round corners to images. */ class RoundedCornersTransformation(val radius: Int, val margin: Int) : Transformation { val paint = Paint() override fun transform(source: Bitmap): Bitmap { paint.isAntiAlias = true paint.setShader(BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)) val output = Bitmap.createBitmap(source.width, source.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(output) canvas.drawRoundRect( RectF(margin.toFloat(), margin.toFloat(), source.width.toFloat() - margin, source.height.toFloat() - margin), radius.toFloat(), radius.toFloat(), paint) if (source != output) { source.recycle() } return output; } override fun key(): String? { return "rounded(radius=$radius, margin=$margin)"; } }
apache-2.0
4857768a934e6dc299c7beb7a9deb560
29.411765
93
0.651838
4.456897
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/InlineClassDeprecatedFix.kt
3
2322
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.platform.has import org.jetbrains.kotlin.platform.jvm.JvmPlatform import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtModifierListOwner import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.JVM_INLINE_ANNOTATION_FQ_NAME class InlineClassDeprecatedFix( element: KtModifierListOwner ) : KotlinQuickFixAction<KtModifierListOwner>(element), CleanupFix { private val text = KotlinBundle.message( "replace.with.0", (if (element.containingKtFile.hasJvmTarget()) "@JvmInline " else "") + "value" ) override fun getText() = text override fun getFamilyName() = KotlinBundle.message("replace.modifier") override fun invoke(project: Project, editor: Editor?, file: KtFile) { element?.removeModifier(KtTokens.INLINE_KEYWORD) element?.addModifier(KtTokens.VALUE_KEYWORD) if (file.hasJvmTarget()) { element?.addAnnotation(JVM_INLINE_ANNOTATION_FQ_NAME) } } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val deprecatedModifier = Errors.INLINE_CLASS_DEPRECATED.cast(diagnostic) val modifierListOwner = deprecatedModifier.psiElement.getParentOfType<KtModifierListOwner>(strict = true) ?: return null return if (deprecatedModifier != null) InlineClassDeprecatedFix(modifierListOwner) else null } } private fun KtFile.hasJvmTarget(): Boolean = TargetPlatformDetector.getPlatform(this).has<JvmPlatform>() }
apache-2.0
d37357fee1cf59e964b89b1d509d8fa7
41.236364
132
0.763997
4.690909
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeCallableReturnTypeFix.kt
1
12298
// 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.quickfix import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.findParentOfType import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors.COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DataClassDescriptorResolver import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isUnit import java.util.* abstract class ChangeCallableReturnTypeFix( element: KtCallableDeclaration, type: KotlinType ) : KotlinQuickFixAction<KtCallableDeclaration>(element) { // Not actually safe but handled especially inside invokeForPreview @SafeFieldForPreview private val changeFunctionLiteralReturnTypeFix: ChangeFunctionLiteralReturnTypeFix? private val typeContainsError = ErrorUtils.containsErrorType(type) private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type) private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type) private val isUnitType = type.isUnit() init { changeFunctionLiteralReturnTypeFix = if (element is KtFunctionLiteral) { val functionLiteralExpression = PsiTreeUtil.getParentOfType(element, KtLambdaExpression::class.java) ?: error("FunctionLiteral outside any FunctionLiteralExpression: " + element.getElementTextWithContext()) ChangeFunctionLiteralReturnTypeFix(functionLiteralExpression, type) } else { null } } open fun functionPresentation(): String? { val element = element!! if (element.name == null) return null val container = element.unsafeResolveToDescriptor().containingDeclaration as? ClassDescriptor val containerName = container?.name?.takeUnless { it.isSpecial }?.asString() return ChangeTypeFixUtils.functionOrConstructorParameterPresentation(element, containerName) } class OnType(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type), HighPriorityAction { override fun functionPresentation() = null } class ForEnclosing(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type), HighPriorityAction { override fun functionPresentation(): String? { val presentation = super.functionPresentation() ?: return KotlinBundle.message("fix.change.return.type.presentation.enclosing.function") return KotlinBundle.message("fix.change.return.type.presentation.enclosing", presentation) } } class ForCalled(element: KtCallableDeclaration, type: KotlinType) : ChangeCallableReturnTypeFix(element, type) { override fun functionPresentation(): String? { val presentation = super.functionPresentation() ?: return KotlinBundle.message("fix.change.return.type.presentation.called.function") return when (element) { is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.accessed", presentation) else -> KotlinBundle.message("fix.change.return.type.presentation.called", presentation) } } } class ForOverridden(element: KtFunction, type: KotlinType) : ChangeCallableReturnTypeFix(element, type) { override fun functionPresentation(): String? { val presentation = super.functionPresentation() ?: return null return ChangeTypeFixUtils.baseFunctionOrConstructorParameterPresentation(presentation) } } override fun getText(): String { val element = element ?: return "" if (changeFunctionLiteralReturnTypeFix != null) { return changeFunctionLiteralReturnTypeFix.text } return ChangeTypeFixUtils.getTextForQuickFix(element, functionPresentation(), isUnitType, typePresentation) } override fun getFamilyName(): String = ChangeTypeFixUtils.familyName() override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { return !typeContainsError && element !is KtConstructor<*> } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return if (changeFunctionLiteralReturnTypeFix != null) { changeFunctionLiteralReturnTypeFix.invoke(project, editor!!, file) } else { if (!(isUnitType && element is KtFunction && element.hasBlockBody())) { var newTypeRef = KtPsiFactory(project).createType(typeSourceCode) newTypeRef = element.setTypeReference(newTypeRef)!! ShortenReferences.DEFAULT.process(newTypeRef) } else { element.typeReference = null } } } override fun generatePreview(project: Project, editor: Editor, file: PsiFile): IntentionPreviewInfo { if (changeFunctionLiteralReturnTypeFix != null) { return changeFunctionLiteralReturnTypeFix.generatePreview(project, editor, file) } return super.generatePreview(project, editor, file) } object ComponentFunctionReturnTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val entry = getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic) val context = entry.analyze(BodyResolveMode.PARTIAL) val resolvedCall = context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry) ?: return null val componentFunction = DescriptorToSourceUtils.descriptorToDeclaration(resolvedCall.candidateDescriptor) as? KtCallableDeclaration ?: return null val expectedType = context[BindingContext.TYPE, entry.typeReference!!] ?: return null return ForCalled(componentFunction, expectedType) } } object HasNextFunctionTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement.findParentOfType<KtExpression>(strict = false) ?: error("HAS_NEXT_FUNCTION_TYPE_MISMATCH reported on element that is not within any expression") val context = expression.analyze(BodyResolveMode.PARTIAL) val resolvedCall = context[BindingContext.LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, expression] ?: return null val hasNextDescriptor = resolvedCall.candidateDescriptor val hasNextFunction = DescriptorToSourceUtils.descriptorToDeclaration(hasNextDescriptor) as KtFunction? ?: return null return ForCalled(hasNextFunction, hasNextDescriptor.builtIns.booleanType) } } object CompareToTypeMismatchFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val expression = diagnostic.psiElement.findParentOfType<KtBinaryExpression>(strict = false) ?: error("COMPARE_TO_TYPE_MISMATCH reported on element that is not within any expression") val resolvedCall = expression.resolveToCall() ?: return null val compareToDescriptor = resolvedCall.candidateDescriptor val compareTo = DescriptorToSourceUtils.descriptorToDeclaration(compareToDescriptor) as? KtFunction ?: return null return ForCalled(compareTo, compareToDescriptor.builtIns.intType) } } object ReturnTypeMismatchOnOverrideFactory : KotlinIntentionActionsFactory() { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return emptyList() val actions = LinkedList<IntentionAction>() val descriptor = function.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? FunctionDescriptor ?: return emptyList() val matchingReturnType = QuickFixUtil.findLowerBoundOfOverriddenCallablesReturnTypes(descriptor) if (matchingReturnType != null) { actions.add(OnType(function, matchingReturnType)) } val functionType = descriptor.returnType ?: return actions val overriddenMismatchingFunctions = LinkedList<FunctionDescriptor>() for (overriddenFunction in descriptor.overriddenDescriptors) { val overriddenFunctionType = overriddenFunction.returnType ?: continue if (!KotlinTypeChecker.DEFAULT.isSubtypeOf(functionType, overriddenFunctionType)) { overriddenMismatchingFunctions.add(overriddenFunction) } } if (overriddenMismatchingFunctions.size == 1) { val overriddenFunction = DescriptorToSourceUtils.descriptorToDeclaration(overriddenMismatchingFunctions[0]) if (overriddenFunction is KtFunction) { actions.add(ForOverridden(overriddenFunction, functionType)) } } return actions } } object ChangingReturnTypeToUnitFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return null return ForEnclosing(function, function.builtIns.unitType) } } object ChangingReturnTypeToNothingFactory : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): IntentionAction? { val function = diagnostic.psiElement.findParentOfType<KtFunction>(strict = false) ?: return null return ForEnclosing(function, function.builtIns.nothingType) } } companion object { fun getDestructuringDeclarationEntryThatTypeMismatchComponentFunction(diagnostic: Diagnostic): KtDestructuringDeclarationEntry { val componentName = COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH.cast(diagnostic).a val componentIndex = DataClassDescriptorResolver.getComponentIndex(componentName.asString()) val multiDeclaration = diagnostic.psiElement.findParentOfType<KtDestructuringDeclaration>(strict = false) ?: error("COMPONENT_FUNCTION_RETURN_TYPE_MISMATCH reported on expression that is not within any multi declaration") return multiDeclaration.entries[componentIndex - 1] } } }
apache-2.0
51ed426774034df428d6f05fb0739c5f
51.110169
158
0.731094
5.72
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/InvokeDynamic.kt
1
15890
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.builder.self import com.github.jonathanxd.kores.common.DynamicMethodSpec import com.github.jonathanxd.kores.common.MethodInvokeSpec import com.github.jonathanxd.kores.common.MethodTypeSpec import com.github.jonathanxd.kores.type.KoresType import java.lang.invoke.* import java.lang.reflect.Type import java.util.function.Supplier /** * A dynamic invocation of a method. * * Note: this class does not extends [MethodInvocation] because it is not * a normal invocation. */ interface InvokeDynamicBase : TypedInstruction { /** * Return type of dynamic invocation */ override val type: Type get() = dynamicMethod.type /** * Bootstrap method invocation specification. */ val bootstrap: MethodInvokeSpec /** * Specification of dynamic method. */ val dynamicMethod: DynamicMethodSpec /** * Bootstrap method Arguments, must be an [String], [Int], * [Long], [Float], [Double], [KoresType] or [MethodInvokeSpec]. */ val bootstrapArgs: List<Any> override fun builder(): Builder<InvokeDynamicBase, *> interface Builder<out T : InvokeDynamicBase, S : Builder<T, S>> : Typed.Builder<T, S> { override fun type(value: Type): S = self() /** * See [InvokeDynamic.bootstrap] */ fun bootstrap(value: MethodInvokeSpec): S /** * See [InvokeDynamic.dynamicMethod] */ fun dynamicMethod(value: DynamicMethodSpec): S /** * See [InvokeDynamic.bootstrapArgs] */ fun bootstrapArgs(value: List<Any>): S /** * See [InvokeDynamic.bootstrapArgs] */ fun bootstrapArgs(vararg values: Any): S = bootstrapArgs(values.toList()) } /** * Dynamic invocation of lambda method reference. */ interface LambdaMethodRefBase : InvokeDynamicBase, ArgumentsHolder { /** * Method reference to invoke */ val methodRef: MethodInvokeSpec /** * Target of method ref invocation */ val target: Instruction /** * Arguments to pass to method ref */ override val arguments: List<Instruction> override val types: List<Type> get() = this.dynamicMethod.types override val array: Boolean get() = false // Dynamic method, for lambdas, the get(InstanceType, AdditionalArgs)FunctionalInterfaceType // The InstanceType is not needed for static [methodRef] override val dynamicMethod: DynamicMethodSpec get() = DynamicMethodSpec( this.baseSam.methodName, this.baseSam.typeSpec.copy( returnType = this.baseSam.localization, parameterTypes = (if (this.needThis) listOf(methodRef.methodTypeSpec.localization) else emptyList()) + this.additionalArgumentsType ), (if (this.needThis) listOf(target) else emptyList()) + this.arguments ) override val type: Type get() = this.baseSam.localization override val bootstrap: MethodInvokeSpec get() = MethodInvokeSpec( InvokeType.INVOKE_STATIC, MethodTypeSpec( localization = LambdaMetafactory::class.java, methodName = "metafactory", typeSpec = TypeSpec( returnType = CallSite::class.java, parameterTypes = listOf( MethodHandles.Lookup::class.java, String::class.java, MethodType::class.java, MethodType::class.java, MethodHandle::class.java, MethodType::class.java ) ) ) ) override val bootstrapArgs: List<Any> get() = listOf( this.currentTypes, MethodInvokeSpec( this.methodRef.invokeType, MethodTypeSpec( this.methodRef.methodTypeSpec.localization, this.methodRef.methodTypeSpec.methodName, this.methodRef.methodTypeSpec.typeSpec ) ), this.expectedTypes ) /** * Description of base SAM method, example, if the target functional interface * is [Supplier], then the base SAM method is the [Supplier.get]. */ val baseSam: MethodTypeSpec /** * Current types of lambda sam. */ val currentTypes: TypeSpec get() = baseSam.typeSpec /** * Types expected by the caller of lambda SAM. */ val expectedTypes: TypeSpec override fun builder(): Builder<LambdaMethodRefBase, *> interface Builder<out T : LambdaMethodRefBase, S : Builder<T, S>> : InvokeDynamicBase.Builder<T, S>, ArgumentsHolder.Builder<T, S> { override fun type(value: Type): S = self() override fun bootstrap(value: MethodInvokeSpec): S = self() override fun bootstrapArgs(value: List<Any>): S = self() override fun array(value: Boolean): S = self() override fun dynamicMethod(value: DynamicMethodSpec): S = self() /** * See [LambdaMethodRefBase.methodRef] */ fun methodRef(value: MethodInvokeSpec): S /** * See [LambdaMethodRefBase.target] */ fun target(value: Instruction): S /** * See [LambdaMethodRefBase.baseSam] */ fun baseSam(value: MethodTypeSpec): S /** * See [LambdaMethodRefBase.expectedTypes] */ fun expectedTypes(value: TypeSpec): S } } /** * Invocation of lambda function. */ interface LambdaLocalCodeBase : LambdaMethodRefBase, ArgumentsHolder { override val expectedTypes: TypeSpec get() = this.localCode.description override val methodRef: MethodInvokeSpec get() = MethodInvokeSpec( this.localCode.invokeType, MethodTypeSpec( this.localCode.declaringType, this.localCode.declaration.name, this.localCode.description ) ) override val array: Boolean get() = false /** * Local method to invoke */ val localCode: LocalCode /** * Argument to capture from current context and pass to [localCode] */ override val arguments: List<Instruction> override fun builder(): Builder<LambdaLocalCodeBase, *> interface Builder<out T : LambdaLocalCodeBase, S : Builder<T, S>> : LambdaMethodRefBase.Builder<T, S>, ArgumentsHolder.Builder<T, S> { override fun type(value: Type): S = self() override fun bootstrap(value: MethodInvokeSpec): S = self() override fun bootstrapArgs(value: List<Any>): S = self() override fun dynamicMethod(value: DynamicMethodSpec): S = self() override fun methodRef(value: MethodInvokeSpec): S = self() /** * See [LambdaLocalCodeBase.localCode] */ fun localCode(value: LocalCode): S } } } data class InvokeDynamic( override val bootstrap: MethodInvokeSpec, override val dynamicMethod: DynamicMethodSpec, override val bootstrapArgs: List<Any> ) : InvokeDynamicBase { override fun builder(): InvokeDynamic.Builder = InvokeDynamic.Builder(this) class Builder() : InvokeDynamicBase.Builder<InvokeDynamic, Builder> { lateinit var bootstrap: MethodInvokeSpec lateinit var dynamic: DynamicMethodSpec var args: List<Any> = emptyList() constructor(defaults: InvokeDynamic) : this() { this.bootstrap = defaults.bootstrap this.dynamic = defaults.dynamicMethod this.args = defaults.bootstrapArgs } override fun bootstrap(value: MethodInvokeSpec): Builder { this.bootstrap = value return this } override fun dynamicMethod(value: DynamicMethodSpec): Builder { this.dynamic = value return this } override fun bootstrapArgs(value: List<Any>): Builder { this.args = value return this } override fun build(): InvokeDynamic = InvokeDynamic(this.bootstrap, this.dynamic, this.args) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: InvokeDynamic): Builder = Builder(defaults) } } data class LambdaMethodRef( override val methodRef: MethodInvokeSpec, override val target: Instruction, override val arguments: List<Instruction>, override val baseSam: MethodTypeSpec, override val expectedTypes: TypeSpec ) : InvokeDynamicBase.LambdaMethodRefBase { override fun builder(): LambdaMethodRef.Builder = LambdaMethodRef.Builder(this) class Builder() : InvokeDynamicBase.LambdaMethodRefBase.Builder<LambdaMethodRef, Builder> { lateinit var methodRef: MethodInvokeSpec lateinit var target: Instruction var arguments: List<Instruction> = emptyList() lateinit var baseSam: MethodTypeSpec lateinit var expectedTypes: TypeSpec constructor(defaults: LambdaMethodRef) : this() { this.methodRef = defaults.methodRef this.target = defaults.target this.arguments = defaults.arguments this.baseSam = defaults.baseSam this.expectedTypes = defaults.expectedTypes } override fun methodRef(value: MethodInvokeSpec): Builder { this.methodRef = value return this } override fun target(value: Instruction): Builder { this.target = value return this } override fun arguments(value: List<Instruction>): Builder { this.arguments = value return this } override fun baseSam(value: MethodTypeSpec): Builder { this.baseSam = value return this } override fun expectedTypes(value: TypeSpec): Builder { this.expectedTypes = value return this } override fun build(): LambdaMethodRef = LambdaMethodRef( this.methodRef, this.target, this.arguments, this.baseSam, this.expectedTypes ) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: LambdaMethodRef): Builder = Builder(defaults) } } } data class LambdaLocalCode( override val baseSam: MethodTypeSpec, override val expectedTypes: TypeSpec, override val localCode: LocalCode, override val arguments: List<Instruction> ) : InvokeDynamicBase.LambdaLocalCodeBase { override val target: Instruction get() = if (this.needThis) Access.THIS else Access.STATIC override val types: List<Type> = this.localCode.parameters.map(KoresParameter::type) override fun builder(): LambdaLocalCode.Builder = LambdaLocalCode.Builder(this) class Builder() : InvokeDynamicBase.LambdaLocalCodeBase.Builder<LambdaLocalCode, Builder> { lateinit var baseSam: MethodTypeSpec lateinit var localCode: LocalCode var arguments: List<Instruction> = emptyList() lateinit var expectedTypes: TypeSpec override fun array(value: Boolean): Builder = self() override fun target(value: Instruction): Builder = self() constructor(defaults: LambdaLocalCode) : this() { this.baseSam = defaults.baseSam this.localCode = defaults.localCode this.arguments = defaults.arguments this.expectedTypes = defaults.expectedTypes } override fun expectedTypes(value: TypeSpec): Builder { this.expectedTypes = value return this } override fun baseSam(value: MethodTypeSpec): Builder { this.baseSam = value return this } override fun localCode(value: LocalCode): Builder { this.localCode = value return this } override fun arguments(value: List<Instruction>): Builder { this.arguments = value return this } override fun build(): LambdaLocalCode = LambdaLocalCode(this.baseSam, this.expectedTypes, this.localCode, this.arguments) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: LambdaLocalCode): Builder = Builder(defaults) } } } } val InvokeDynamicBase.LambdaMethodRefBase.additionalArgumentsType: List<Type> get() = if (baseSam.typeSpec.parameterTypes.size != this.methodRef.methodTypeSpec.typeSpec.parameterTypes.size ) { val samSpec = baseSam.typeSpec val invkSpec = this.methodRef.methodTypeSpec.typeSpec invkSpec.parameterTypes.subList( 0, (invkSpec.parameterTypes.size - samSpec.parameterTypes.size) ) } else emptyList() private val InvokeDynamicBase.LambdaMethodRefBase.needThis get() = !methodRef.invokeType.isStatic()
mit
1cd4af5b9cc5af9e03bdceecefcf06e3
32.384454
118
0.586595
5.206422
false
false
false
false
allotria/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/JBDefaultTabPainter.kt
2
2894
// 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.ui.tabs.impl import com.intellij.openapi.rd.fill2DRect import com.intellij.openapi.rd.paint2DLine import com.intellij.ui.paint.LinePainter2D import com.intellij.ui.tabs.JBTabPainter import com.intellij.ui.tabs.JBTabsPosition import com.intellij.ui.tabs.impl.themes.DefaultTabTheme import com.intellij.ui.tabs.impl.themes.TabTheme import java.awt.Color import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle open class JBDefaultTabPainter(val theme : TabTheme = DefaultTabTheme()) : JBTabPainter { override fun getTabTheme(): TabTheme = theme override fun getBackgroundColor(): Color = theme.background ?: theme.borderColor override fun fillBackground(g: Graphics2D, rect: Rectangle) { theme.background?.let{ g.fill2DRect(rect, it) } } override fun paintTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, active: Boolean, hovered: Boolean) { tabColor?.let { g.fill2DRect(rect, it) theme.inactiveColoredTabBackground?.let { inactive -> g.fill2DRect(rect, inactive) } } if(hovered) { (if (active) theme.hoverBackground else theme.hoverInactiveBackground)?.let{ g.fill2DRect(rect, it) } } } override fun paintSelectedTab(position: JBTabsPosition, g: Graphics2D, rect: Rectangle, borderThickness: Int, tabColor: Color?, active: Boolean, hovered: Boolean) { val color = (tabColor ?: if(active) theme.underlinedTabBackground else theme.underlinedTabInactiveBackground) ?: theme.background color?.let { g.fill2DRect(rect, it) } if(hovered) { (if (active) theme.hoverBackground else theme.hoverInactiveBackground)?.let{ g.fill2DRect(rect, it) } } paintUnderline(position, rect, borderThickness, g, active) } override fun paintUnderline(position: JBTabsPosition, rect: Rectangle, borderThickness: Int, g: Graphics2D, active: Boolean) { val underline = underlineRectangle(position, rect, theme.underlineHeight) g.fill2DRect(underline, if (active) theme.underlineColor else theme.inactiveUnderlineColor) } override fun paintBorderLine(g: Graphics2D, thickness: Int, from: Point, to: Point) { g.paint2DLine(from, to, LinePainter2D.StrokeType.INSIDE, thickness.toDouble(), theme.borderColor) } protected open fun underlineRectangle(position: JBTabsPosition, rect: Rectangle, thickness: Int): Rectangle { return Rectangle(rect.x, rect.y + rect.height - thickness, rect.width, thickness) } }
apache-2.0
3eca2208d4a0c07e84d7bcdf6dfe526f
36.102564
166
0.687284
4.1402
false
false
false
false
DmytroTroynikov/aemtools
aem-intellij-core/src/test/kotlin/com/aemtools/completion/html/HtlAttributesContributorTest.kt
1
934
package com.aemtools.completion.html import com.aemtools.common.constant.const.htl.DATA_SLY_LIST import com.aemtools.common.constant.const.htl.DATA_SLY_REPEAT import com.aemtools.common.constant.const.htl.DATA_SLY_UNWRAP import com.aemtools.common.constant.const.htl.HTL_ATTRIBUTES import com.aemtools.test.BaseVariantsCheckContributorTest /** * @author Dmytro_Troynikov */ class HtlAttributesContributorTest : BaseVariantsCheckContributorTest("com/aemtools/completion/html/attributes") { fun testHtlAttributes() = assertVariantsPresent(HTL_ATTRIBUTES) fun testHtlAttributesFilterOutUnwrap() = assertVariantsAbsent(listOf(DATA_SLY_UNWRAP)) fun testHtlAttributesFilterOutUnwrap2() = assertVariantsAbsent(listOf(DATA_SLY_UNWRAP)) fun testHtlAttributesFilterOutDataSlyList() = assertVariantsAbsent(listOf(DATA_SLY_LIST)) fun testHtlAttributesFilterOutDataSlyRepeat() = assertVariantsAbsent(listOf(DATA_SLY_REPEAT)) }
gpl-3.0
4da0ace6aaec055b8dcb9deabee62f57
37.916667
114
0.827623
3.827869
false
true
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ChangeToMutableCollectionFix.kt
1
4922
// 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.quickfix import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType class ChangeToMutableCollectionFix(property: KtProperty, private val type: String) : KotlinQuickFixAction<KtProperty>(property) { override fun getText() = KotlinBundle.message("fix.change.to.mutable.type", "Mutable$type") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val property = element ?: return val context = property.analyze(BodyResolveMode.PARTIAL) val type = property.initializer?.getType(context) ?: return applyFix(property, type) editor?.caretModel?.moveToOffset(property.endOffset) } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtProperty>? { val element = Errors.NO_SET_METHOD.cast(diagnostic).psiElement as? KtArrayAccessExpression ?: return null val arrayExpr = element.arrayExpression ?: return null val context = arrayExpr.analyze(BodyResolveMode.PARTIAL) val type = arrayExpr.getType(context) ?: return null if (!type.isReadOnlyListOrMap(element.builtIns)) return null val property = arrayExpr.mainReference?.resolve() as? KtProperty ?: return null if (!isApplicable(property)) return null val typeName = type.constructor.declarationDescriptor?.name?.asString() ?: return null return ChangeToMutableCollectionFix(property, typeName) } private fun KotlinType.isReadOnlyListOrMap(builtIns: KotlinBuiltIns): Boolean { val leftDefaultType = constructor.declarationDescriptor?.defaultType ?: return false return leftDefaultType in listOf(builtIns.list.defaultType, builtIns.map.defaultType) } fun isApplicable(property: KtProperty): Boolean { return property.isLocal && property.initializer != null } fun applyFix(property: KtProperty, type: KotlinType) { val initializer = property.initializer ?: return val fqName = initializer.resolveToCall()?.resultingDescriptor?.fqNameOrNull()?.asString() val psiFactory = KtPsiFactory(property.project) val mutableOf = mutableConversionMap[fqName] if (mutableOf != null) { (initializer as? KtCallExpression)?.calleeExpression?.replaced(psiFactory.createExpression(mutableOf)) ?: return } else { val builtIns = property.builtIns val toMutable = when (type.constructor) { builtIns.list.defaultType.constructor -> "toMutableList" builtIns.set.defaultType.constructor -> "toMutableSet" builtIns.map.defaultType.constructor -> "toMutableMap" else -> null } ?: return val dotQualifiedExpression = initializer.replaced( psiFactory.createExpressionByPattern("($0).$1()", initializer, toMutable) ) as KtDotQualifiedExpression val receiver = dotQualifiedExpression.receiverExpression val deparenthesize = KtPsiUtil.deparenthesize(dotQualifiedExpression.receiverExpression) if (deparenthesize != null && receiver != deparenthesize) receiver.replace(deparenthesize) } property.typeReference?.also { it.replace(psiFactory.createType("Mutable${it.text}")) } } private const val COLLECTIONS = "kotlin.collections" private val mutableConversionMap = mapOf( "$COLLECTIONS.listOf" to "mutableListOf", "$COLLECTIONS.setOf" to "mutableSetOf", "$COLLECTIONS.mapOf" to "mutableMapOf" ) } }
apache-2.0
bf81bb43eab90977a33cd75890dd40d5
51.935484
158
0.703576
5.292473
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/like/LikeRatingRequest.kt
1
880
package data.tinder.like import com.squareup.moshi.Json internal class LikeRatingRequest( @field:Json(name = "content_hash") val contentHash: String, @field:Json(name = "super") val didRecUserSuperLike: Int = 1, @field:Json(name = "is_boosting") val isCurrentUserBoosting: Boolean = true, @field:Json(name = "rec_traveling") val isCurrentUserPassporting: Boolean = true, @field:Json(name = "fast_match") val isFastMatch: Boolean = true, @field:Json(name = "top_picks") val isTopPicks: Boolean = true, @field:Json(name = "undo") val isUndo: Boolean = false, @field:Json(name = "photoId") val photoId: String, @field:Json(name = "placeId") val placeId: String, @field:Json(name = "s_number") val sNumber: Long, @field:Json(name = "user_traveling") val wasRecUserPassporting: Boolean = false)
mit
38ea58af636dc8898b1488819359b4e3
31.592593
49
0.663636
3.29588
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/conversation/colors/ui/ChatColorPreviewView.kt
1
5647
package org.thoughtcrime.securesms.conversation.colors.ui import android.content.Context import android.content.res.TypedArray import android.graphics.PorterDuff import android.graphics.PorterDuffColorFilter import android.graphics.drawable.Drawable import android.util.AttributeSet import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import org.signal.core.util.logging.Log import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.DeliveryStatusView import org.thoughtcrime.securesms.conversation.colors.ChatColors import org.thoughtcrime.securesms.conversation.colors.Colorizer import org.thoughtcrime.securesms.conversation.colors.ColorizerView import org.thoughtcrime.securesms.util.DateUtils import org.thoughtcrime.securesms.util.Projection import org.thoughtcrime.securesms.util.ThemeUtil import org.thoughtcrime.securesms.util.ViewUtil import org.thoughtcrime.securesms.wallpaper.ChatWallpaper import java.util.Locale private val TAG = Log.tag(ChatColorPreviewView::class.java) class ChatColorPreviewView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { private val wallpaper: ImageView private val wallpaperDim: View private val colorizerView: ColorizerView private val recv1: Bubble private val sent1: Bubble private val recv2: Bubble private val sent2: Bubble private val bubbleCount: Int private val colorizer: Colorizer private var chatColors: ChatColors? = null init { inflate(context, R.layout.chat_colors_preview_view, this) var typedArray: TypedArray? = null try { typedArray = context.obtainStyledAttributes(attrs, R.styleable.ChatColorPreviewView, 0, 0) bubbleCount = typedArray.getInteger(R.styleable.ChatColorPreviewView_ccpv_chat_bubble_count, 2) assert(bubbleCount == 2 || bubbleCount == 4) { Log.e(TAG, "Bubble count must be 2 or 4") } recv1 = Bubble( findViewById(R.id.bubble_1), findViewById(R.id.bubble_1_text), findViewById(R.id.bubble_1_time), null ) sent1 = Bubble( findViewById(R.id.bubble_2), findViewById(R.id.bubble_2_text), findViewById(R.id.bubble_2_time), findViewById(R.id.bubble_2_delivery) ) recv2 = Bubble( findViewById(R.id.bubble_3), findViewById(R.id.bubble_3_text), findViewById(R.id.bubble_3_time), null ) sent2 = Bubble( findViewById(R.id.bubble_4), findViewById(R.id.bubble_4_text), findViewById(R.id.bubble_4_time), findViewById(R.id.bubble_4_delivery) ) val now: String = DateUtils.getExtendedRelativeTimeSpanString(context, Locale.getDefault(), System.currentTimeMillis()) listOf(sent1, sent2, recv1, recv2).forEach { it.time.text = now it.delivery?.setRead() } if (bubbleCount == 2) { recv2.bubble.visibility = View.GONE sent2.bubble.visibility = View.GONE } wallpaper = findViewById(R.id.wallpaper) wallpaperDim = findViewById(R.id.wallpaper_dim) colorizerView = findViewById(R.id.colorizer) colorizer = Colorizer() } finally { typedArray?.recycle() } } override fun onAttachedToWindow() { super.onAttachedToWindow() redrawChatColors() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) redrawChatColors() } private fun redrawChatColors() { if (chatColors != null) { setChatColors(requireNotNull(chatColors)) } } fun setWallpaper(chatWallpaper: ChatWallpaper?) { if (chatWallpaper != null) { chatWallpaper.loadInto(wallpaper) if (ThemeUtil.isDarkTheme(context)) { wallpaperDim.alpha = chatWallpaper.dimLevelForDarkTheme } else { wallpaperDim.alpha = 0f } } else { wallpaper.background = null wallpaperDim.alpha = 0f } val backgroundColor = if (chatWallpaper != null) { R.color.conversation_item_recv_bubble_color_wallpaper } else { R.color.signal_background_secondary } listOf(recv1, recv2).forEach { it.bubble.background.colorFilter = PorterDuffColorFilter( ContextCompat.getColor(context, backgroundColor), PorterDuff.Mode.SRC_IN ) } } fun setChatColors(chatColors: ChatColors) { this.chatColors = chatColors val sentBubbles = listOf(sent1, sent2) sentBubbles.forEach { it.bubble.background.colorFilter = chatColors.chatBubbleColorFilter } val mask: Drawable = chatColors.chatBubbleMask val bubbles = if (bubbleCount == 4) { listOf(sent1, sent2) } else { listOf(sent1) } val projections = bubbles.map { Projection.relativeToViewWithCommonRoot(it.bubble, colorizerView, Projection.Corners(ViewUtil.dpToPx(10).toFloat())) } colorizerView.setProjections(projections) colorizerView.visibility = View.VISIBLE colorizerView.background = mask sentBubbles.forEach { it.body.setTextColor(colorizer.getOutgoingBodyTextColor(context)) it.time.setTextColor(colorizer.getOutgoingFooterTextColor(context)) it.delivery?.setTint(colorizer.getOutgoingFooterIconColor(context)) } } private class Bubble(val bubble: View, val body: TextView, val time: TextView, val delivery: DeliveryStatusView?) }
gpl-3.0
6d8b01c146adb557fa73fe3d67f1e783
29.037234
125
0.711528
4.127924
false
false
false
false
androidx/androidx
compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/docs/layout/Intrinsics.kt
3
5865
// ktlint-disable indent https://github.com/pinterest/ktlint/issues/967 /* * 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. */ // Ignore lint warnings in documentation snippets @file:Suppress("unused", "UNUSED_PARAMETER", "UNUSED_VARIABLE") package androidx.compose.integration.docs.layout import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.Divider import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.IntrinsicMeasureScope import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.LayoutModifier import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp /** * This file lets DevRel track changes to snippets present in * https://developer.android.com/jetpack/compose/layouts/intrinsic-measurements * * No action required if it's modified. */ private object IntrinsicsSnippet1 { @Composable fun TwoTexts(modifier: Modifier = Modifier, text1: String, text2: String) { Row(modifier = modifier) { Text( modifier = Modifier .weight(1f) .padding(start = 4.dp) .wrapContentWidth(Alignment.Start), text = text1 ) Divider( color = Color.Black, modifier = Modifier.fillMaxHeight().width(1.dp) ) Text( modifier = Modifier .weight(1f) .padding(end = 4.dp) .wrapContentWidth(Alignment.End), text = text2 ) } } // @Preview @Composable fun TwoTextsPreview() { MaterialTheme { Surface { TwoTexts(text1 = "Hi", text2 = "there") } } } } private object IntrinsicsSnippet2 { @Composable fun TwoTexts(modifier: Modifier = Modifier, text1: String, text2: String) { Row(modifier = modifier) { Text( modifier = Modifier .weight(1f) .padding(start = 4.dp) .wrapContentWidth(Alignment.Start), text = text1 ) Divider( color = Color.Black, modifier = Modifier.fillMaxHeight().width(1.dp) ) Text( modifier = Modifier .weight(1f) .padding(end = 4.dp) .wrapContentWidth(Alignment.End), text = text2 ) } } // @Preview @Composable fun TwoTextsPreview() { MaterialTheme { Surface { TwoTexts(text1 = "Hi", text2 = "there") } } } } private object IntrinsicsSnippet3 { @Composable fun MyCustomComposable( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { Layout( content = content, modifier = modifier, measurePolicy = object : MeasurePolicy { override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult { // Measure and layout here TODO() // NOTE: Omit in the code snippets } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ): Int { // Logic here TODO() // NOTE: Omit in the code snippets } // Other intrinsics related methods have a default value, // you can override only the methods that you need. } ) } } private object IntrinsicsSnippet4 { fun Modifier.myCustomModifier(/* ... */) = this then object : LayoutModifier { override fun MeasureScope.measure( measurable: Measurable, constraints: Constraints ): MeasureResult { // Measure and layout here TODO() // NOTE: Omit in the code snippets } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurable: IntrinsicMeasurable, height: Int ): Int { // Logic here TODO() // NOTE: Omit in the code snippets } // Other intrinsics related methods have a default value, // you can override only the methods that you need. } }
apache-2.0
c65f62405a8bcddd441b5764bd4e8370
30.702703
82
0.597613
4.974555
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/app/BaseActivity.kt
1
1411
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.app import android.os.Bundle import androidx.appcompat.app.AppCompatActivity open class BaseActivity : AppCompatActivity() { private lateinit var app: PlayHvzApplication override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState); app = applicationContext as PlayHvzApplication } override fun onResume() { super.onResume() app.currentActivity = this } override fun onPause() { clearReferences() super.onPause() } override fun onDestroy() { clearReferences() super.onDestroy() } private fun clearReferences() { val currentActivity = app.currentActivity if (this == currentActivity) { app.currentActivity = null } } }
apache-2.0
aa1a758b7ed5b308e2cebddee1a463ec
26.153846
75
0.686747
4.687708
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/ui/FontSizePopup.kt
8
4749
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("FontSizePopup") @file:ApiStatus.Internal package com.intellij.ui import com.intellij.openapi.application.ApplicationBundle import com.intellij.openapi.application.EDT import com.intellij.openapi.options.FontSize import com.intellij.openapi.ui.popup.JBPopup import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.ui.popup.JBPopupListener import com.intellij.openapi.ui.popup.LightweightWindowEvent import com.intellij.openapi.util.Disposer import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.JBSlider import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.EDT import com.intellij.util.ui.UIUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.jetbrains.annotations.ApiStatus import java.awt.Component import java.awt.FlowLayout import java.awt.MouseInfo import java.awt.Point import javax.swing.* fun <T> showFontSizePopup( parentComponent: Component, initialFont: T, fontRange: List<T>, onPopupClose: () -> Unit, changeCallback: (T) -> Unit ): FontSizePopupData { val slider = JBSlider(0, fontRange.size - 1).apply { orientation = SwingConstants.HORIZONTAL isOpaque = true minorTickSpacing = 1 paintTicks = true paintTrack = true snapToTicks = true } UIUtil.setSliderIsFilled(slider, true) val initialIndex = fontRange.indexOf(initialFont) slider.setValueWithoutEvents(initialIndex) slider.addChangeListener { changeCallback(fontRange[slider.value]) } val panel = JPanel(FlowLayout(FlowLayout.RIGHT, 3, 0)) panel.isOpaque = true panel.add(JLabel(ApplicationBundle.message("label.font.size"))) panel.add(slider) panel.border = BorderFactory.createLineBorder(JBColor.border(), 1) val popup = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, slider).createPopup() popup.addListener(object : JBPopupListener { override fun onClosed(event: LightweightWindowEvent) { onPopupClose() } }) val location = MouseInfo.getPointerInfo().location popup.show( RelativePoint(Point( location.x - panel.preferredSize.width / 2, location.y - panel.preferredSize.height / 2 )).getPointOn(parentComponent) ) return FontSizePopupData(slider) } data class FontSizePopupData(val slider: JBSlider) // Basically an observable value. Can be generified to work with any values. interface FontSizeModel { var value: FontSize /** * The returned flow immediately emits [value] when collected. * The returned flow never completes. */ val updates: Flow<FontSize> } /** * Shows a popup with a slider. * * [model] is bound to the slider: * - changing the slider value will emit a new value; * - changing the value will update the slider presentation. */ @RequiresEdt fun showFontSizePopup(model: FontSizeModel, anchor: JComponent) { EDT.assertIsEdt() val popup = createFontSizePopup(model) val location = MouseInfo.getPointerInfo().location val content = popup.content val point = RelativePoint(Point( location.x - content.preferredSize.width / 2, location.y - content.preferredSize.height / 2, )) popup.show(point.getPointOn(anchor)) } // This function can be generified to work with any enums. private fun createFontSizePopup(model: FontSizeModel): JBPopup { val values = FontSize.values() val slider = JBSlider(0, values.size - 1).also { it.orientation = SwingConstants.HORIZONTAL it.isOpaque = true it.minorTickSpacing = 1 it.paintTicks = true it.paintTrack = true it.snapToTicks = true UIUtil.setSliderIsFilled(it, true) } slider.addChangeListener { model.value = values[slider.value] } val updateSliderJob = CoroutineScope(Dispatchers.EDT).launch(start = CoroutineStart.UNDISPATCHED) { // The size can be changed externally, e.g. by scrolling mouse wheel. // This coroutine reflects the model changes in the UI. model.updates.collect { slider.value = it.ordinal } } val panel = JPanel(FlowLayout(FlowLayout.RIGHT, 3, 0)).also { it.border = BorderFactory.createLineBorder(JBColor.border(), 1) it.isOpaque = true } panel.add(JLabel(ApplicationBundle.message("label.font.size"))) panel.add(slider) return JBPopupFactory.getInstance().createComponentPopupBuilder(panel, slider).createPopup().also { it.size = panel.preferredSize Disposer.register(it) { updateSliderJob.cancel() } } }
apache-2.0
86a81c2292581c6894204de78ef44efd
30.66
120
0.75279
4.072899
false
false
false
false
980f/droid
android/src/main/kotlin/pers/hal42/android/AcknowledgeActivity.kt
1
1083
package pers.hal42.android import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.TextView /** A screen that displays a string from the intent's bundle. * Copyright (C) by andyh created on 11/1/12 at 3:26 PM */ class AcknowledgeActivity : Activity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent val message = intent.getCharSequenceExtra(messageKey) val textView = TextView(this) setContentView(textView) textView.textSize = 40f//todo: configurable font attributes textView.text = message } companion object { private val messageKey = AcknowledgeActivity::class.java.canonicalName//#cached /** * basic usage: */ fun Acknowledge(message: CharSequence, someActivity: Context) { val intent = Intent(someActivity, AcknowledgeActivity::class.java) intent.putExtra(AcknowledgeActivity.messageKey, message) someActivity.startActivity(intent) } } }
mit
92c0ce4f91a60e5e8093dd6344031bb9
26.1
83
0.736842
4.402439
false
false
false
false
JetBrains/xodus
entity-store/src/main/kotlin/jetbrains/exodus/entitystore/iterate/SelectManyIterable.kt
1
6702
/** * Copyright 2010 - 2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.exodus.entitystore.iterate import jetbrains.exodus.core.dataStructures.hash.IntHashMap import jetbrains.exodus.entitystore.EntityId import jetbrains.exodus.entitystore.EntityIterableHandle import jetbrains.exodus.entitystore.EntityIterableType import jetbrains.exodus.entitystore.PersistentStoreTransaction import jetbrains.exodus.entitystore.tables.LinkValue import jetbrains.exodus.entitystore.tables.PropertyKey import jetbrains.exodus.entitystore.util.EntityIdSetFactory import jetbrains.exodus.env.Cursor import jetbrains.exodus.kotlin.notNull import jetbrains.exodus.util.LightOutputStream import java.util.* class SelectManyIterable(txn: PersistentStoreTransaction, source: EntityIterableBase, private val linkId: Int, private val distinct: Boolean = true) : EntityIterableDecoratorBase(txn, source) { override fun canBeCached() = super.canBeCached() && distinct override fun getIteratorImpl(txn: PersistentStoreTransaction): EntityIteratorBase = SelectManyDistinctIterator(txn) override fun getHandleImpl(): EntityIterableHandle { return object : EntityIterableHandleDecorator(store, type, source.handle) { private val linkIds = EntityIterableHandleBase.mergeFieldIds(intArrayOf(linkId), decorated.linkIds) override fun getLinkIds() = linkIds override fun toString(builder: StringBuilder) { super.toString(builder) applyDecoratedToBuilder(builder) builder.append('-') builder.append(linkId) builder.append('-') builder.append(distinct) } override fun hashCode(hash: EntityIterableHandleHash) { super.hashCode(hash) hash.applyDelimiter() hash.apply(linkId) hash.applyDelimiter() hash.apply((if (distinct) 1 else 0).toByte()) } override fun isMatchedLinkAdded(source: EntityId, target: EntityId, linkId: Int): Boolean { return linkId == [email protected] || decorated.isMatchedLinkAdded(source, target, linkId) } override fun isMatchedLinkDeleted(source: EntityId, target: EntityId, linkId: Int): Boolean { return linkId == [email protected] || decorated.isMatchedLinkDeleted(source, target, linkId) } } } private inner class SelectManyDistinctIterator constructor(private val txn: PersistentStoreTransaction) : EntityIteratorBase(this@SelectManyIterable), SourceMappingIterator { private val sourceIt = source.iterator() as EntityIteratorBase private val usedCursors = IntHashMap<Cursor>(6, 2f) private val ids = ArrayDeque<Pair<EntityId, EntityId?>>() private val auxStream = LightOutputStream() private val auxArray = IntArray(8) private var idsCollected = false private lateinit var srcId: EntityId override fun hasNextImpl(): Boolean { if (!idsCollected) { idsCollected = true collectIds() } return !ids.isEmpty() } public override fun nextIdImpl(): EntityId? { if (hasNextImpl()) { val pair = ids.poll() srcId = pair.first return pair.second } return null } override fun dispose(): Boolean { sourceIt.disposeIfShouldBe() return super.dispose() && usedCursors.values.forEach { it.close() }.let { true } } override fun getSourceId() = srcId private fun collectIds() { val sourceIt = this.sourceIt val linkId = [email protected] if (linkId >= 0) { var usedIds = if (distinct) EntityIdSetFactory.newSet() else EntityIdSetFactory.newImmutableSet() while (sourceIt.hasNext()) { val sourceId = sourceIt.nextId() ?: continue val typeId = sourceId.typeId val cursor = usedCursors.get(typeId) ?: store.getLinksFirstIndexCursor(txn, typeId).also { usedCursors[typeId] = it } val sourceLocalId = sourceId.localId var value = cursor.getSearchKey( PropertyKey.propertyKeyToEntry(auxStream, auxArray, sourceLocalId, linkId)) if (value == null) { if (!usedIds.contains(null)) { usedIds = usedIds.add(null) ids.add(sourceId to null) } } else { while (true) { val linkValue = LinkValue.entryToLinkValue(value.notNull) val nextId = linkValue.entityId if (!usedIds.contains(nextId)) { usedIds = usedIds.add(nextId) ids.add(sourceId to nextId) } if (!cursor.next) { break } val key = PropertyKey.entryToPropertyKey(cursor.key) if (key.propertyId != linkId || key.entityLocalId != sourceLocalId) { break } value = cursor.value } } } } } } companion object { init { EntityIterableBase.registerType(type) { txn, _, parameters -> SelectManyIterable(txn, parameters[1] as EntityIterableBase, Integer.valueOf(parameters[0] as String)) } } val type: EntityIterableType get() = EntityIterableType.SELECTMANY_DISTINCT } }
apache-2.0
9527a7fe708d1e8e5f759fcfd53a3ea7
40.8875
178
0.585198
5.391794
false
false
false
false
jwren/intellij-community
plugins/kotlin/repl/src/org/jetbrains/kotlin/console/gutter/ConsoleIndicatorRenderer.kt
5
825
// 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.console.gutter import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.openapi.util.NlsContexts import org.jetbrains.kotlin.utils.addToStdlib.safeAs class ConsoleIndicatorRenderer(private val iconWithTooltip: IconWithTooltip) : GutterIconRenderer() { private val icon = iconWithTooltip.icon private val tooltip @NlsContexts.Tooltip get() = iconWithTooltip.tooltip override fun getIcon() = icon override fun getTooltipText() = tooltip override fun hashCode() = icon.hashCode() override fun equals(other: Any?) = icon == other.safeAs<ConsoleIndicatorRenderer>()?.icon }
apache-2.0
00f2059020c99b0ebd06b8f2110683c2
40.3
158
0.767273
4.634831
false
false
false
false
jwren/intellij-community
platform/lang-impl/src/com/intellij/ide/bookmark/providers/LineBookmarkProvider.kt
1
11019
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.bookmark.providers import com.intellij.ide.bookmark.* import com.intellij.ide.bookmark.ui.tree.FileNode import com.intellij.ide.bookmark.ui.tree.LineNode import com.intellij.ide.projectView.ProjectViewNode import com.intellij.ide.projectView.impl.DirectoryUrl import com.intellij.ide.projectView.impl.PsiFileUrl import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.BulkAwareDocumentListener.Simple import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseEventArea import com.intellij.openapi.editor.event.EditorMouseListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.AsyncFileListener import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.psi.PsiCompiledElement import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.util.PsiUtilCore import com.intellij.testFramework.LightVirtualFile import com.intellij.ui.tree.project.ProjectFileNode import com.intellij.util.Alarm.ThreadToUse.POOLED_THREAD import com.intellij.util.SingleAlarm import com.intellij.util.ui.tree.TreeUtil import java.awt.event.MouseEvent import javax.swing.SwingUtilities import javax.swing.tree.TreePath class LineBookmarkProvider(private val project: Project) : BookmarkProvider, EditorMouseListener, Simple, AsyncFileListener { override fun getWeight() = Int.MIN_VALUE override fun getProject() = project override fun compare(bookmark1: Bookmark, bookmark2: Bookmark): Int { val fileBookmark1 = bookmark1 as? FileBookmark val fileBookmark2 = bookmark2 as? FileBookmark if (fileBookmark1 == null && fileBookmark2 == null) return 0 if (fileBookmark1 == null) return -1 if (fileBookmark2 == null) return 1 val file1 = fileBookmark1.file val file2 = fileBookmark2.file if (file1 == file2) { val lineBookmark1 = bookmark1 as? LineBookmark val lineBookmark2 = bookmark2 as? LineBookmark if (lineBookmark1 == null && lineBookmark2 == null) return 0 if (lineBookmark1 == null) return -1 if (lineBookmark2 == null) return 1 return lineBookmark1.line.compareTo(lineBookmark2.line) } if (file1.isDirectory && !file2.isDirectory) return -1 if (!file1.isDirectory && file2.isDirectory) return 1 return StringUtil.naturalCompare(file1.presentableName, file2.presentableName) } override fun prepareGroup(nodes: List<AbstractTreeNode<*>>): List<AbstractTreeNode<*>> { nodes.forEach { (it as? FileNode)?.ungroup() } // clean all file groups if needed val node = nodes.firstNotNullOfOrNull { it as? LineNode } ?: return nodes.filter(::isNodeVisible) // nothing to group if (node.bookmarksView?.groupLineBookmarks?.isSelected != true) return nodes.filter(::isNodeVisible) // grouping disabled val map = mutableMapOf<VirtualFile, FileNode?>() nodes.forEach { when (it) { is LineNode -> map.putIfAbsent(it.virtualFile, null) is FileNode -> map[it.virtualFile] = it } } // create fake file nodes to group corresponding line nodes map.mapNotNull { if (it.value == null) it.key else null }.forEach { map[it] = FileNode(project, FileBookmarkImpl(this, it)).apply { bookmarkGroup = node.bookmarkGroup parent = node.parent } } return nodes.mapNotNull { when { !isNodeVisible(it) -> null it is LineNode -> map[it.virtualFile]!!.grouped(it) it is FileNode -> it.grouped() else -> it } } } override fun createBookmark(map: Map<String, String>) = map["url"]?.let { createBookmark(it, StringUtil.parseInt(map["line"], -1)) } override fun createBookmark(context: Any?) = when (context) { // below // migrate old bookmarks and favorites is com.intellij.ide.bookmarks.Bookmark -> createBookmark(context.file, context.line) is DirectoryUrl -> createBookmark(context.url) is PsiFileUrl -> createBookmark(context.url) // above // migrate old bookmarks and favorites is PsiElement -> createBookmark(context) is VirtualFile -> createBookmark(context, -1) is ProjectFileNode -> createBookmark(context.virtualFile) is TreePath -> createBookmark(context) else -> null } fun createBookmark(file: VirtualFile, line: Int = -1): FileBookmark? = when { !file.isValid || file is LightVirtualFile -> null line >= 0 -> LineBookmarkImpl(this, file, line) else -> FileBookmarkImpl(this, file) } fun createBookmark(editor: Editor, line: Int? = null): FileBookmark? { if (editor.isOneLineMode) return null val file = FileDocumentManager.getInstance().getFile(editor.document) ?: return null return createBookmark(file, line ?: editor.caretModel.logicalPosition.line) } private fun createBookmark(url: String, line: Int = -1) = createValidBookmark(url, line) ?: createInvalidBookmark(url, line) private fun createValidBookmark(url: String, line: Int = -1) = VFM.findFileByUrl(url)?.let { createBookmark(it, line) } private fun createInvalidBookmark(url: String, line: Int = -1) = InvalidBookmark(this, url, line) private fun createBookmark(element: PsiElement): FileBookmark? { if (element is PsiFileSystemItem) return element.virtualFile?.let { createBookmark(it) } if (element is PsiCompiledElement) return null val file = PsiUtilCore.getVirtualFile(element) ?: return null if (file is LightVirtualFile) return null val document = FileDocumentManager.getInstance().getDocument(file) ?: return null return when (val offset = element.textOffset) { in 0..document.textLength -> createBookmark(file, document.getLineNumber(offset)) else -> null } } private fun createBookmark(path: TreePath): FileBookmark? { val file = path.asVirtualFile ?: return null val parent = path.parentPath?.asVirtualFile ?: return null // see com.intellij.ide.projectView.impl.ClassesTreeStructureProvider return if (!parent.isDirectory || file.parent != parent) null else createBookmark(file) } private val TreePath.asVirtualFile get() = TreeUtil.getLastUserObject(ProjectViewNode::class.java, this)?.virtualFile private val MouseEvent.isUnexpected // see MouseEvent.isUnexpected in ToggleBookmarkAction get() = !SwingUtilities.isLeftMouseButton(this) || isPopupTrigger || if (SystemInfo.isMac) !isMetaDown else !isControlDown private val EditorMouseEvent.isUnexpected get() = isConsumed || area != EditorMouseEventArea.LINE_MARKERS_AREA || mouseEvent.isUnexpected override fun mouseClicked(event: EditorMouseEvent) { if (event.isUnexpected) return val manager = BookmarksManager.getInstance(project) ?: return val bookmark = createBookmark(event.editor, event.logicalPosition.line) ?: return manager.getType(bookmark)?.let { manager.remove(bookmark) } ?: manager.add(bookmark, BookmarkType.DEFAULT) event.consume() } override fun afterDocumentChange(document: Document) { val file = FileDocumentManager.getInstance().getFile(document) ?: return if (file is LightVirtualFile) return val manager = BookmarksManager.getInstance(project) ?: return val map = sortedMapOf<LineBookmarkImpl, Int>(compareBy { it.line }) val set = mutableSetOf<Int>() for (bookmark in manager.bookmarks) { if (bookmark is LineBookmarkImpl && bookmark.file == file) { val rangeMarker = (manager as? BookmarksManagerImpl)?.findLineHighlighter(bookmark) ?: bookmark.descriptor.rangeMarker val line = rangeMarker?.let { if (it.isValid) it.document.getLineNumber(it.startOffset) else null } ?: -1 when (bookmark.line) { line -> set.add(line) else -> map[bookmark] = line } } } if (map.isEmpty()) return val bookmarks = mutableMapOf<Bookmark, Bookmark?>() map.forEach { (bookmark, line) -> bookmarks[bookmark] = when { line < 0 || set.contains(line) -> null else -> { set.add(line) createBookmark(file, line) } } } manager.update(bookmarks) } override fun prepareChange(events: List<VFileEvent>): AsyncFileListener.ChangeApplier? { val update = events.any { it is VFileCreateEvent || it is VFileDeleteEvent } if (update) validateAlarm.cancelAndRequest() return null } private val validateAlarm = SingleAlarm(::validateAndUpdate, 100, project, POOLED_THREAD) private fun validateAndUpdate() { val manager = BookmarksManager.getInstance(project) ?: return val bookmarks = mutableMapOf<Bookmark, Bookmark?>() manager.bookmarks.forEach { validate(it)?.run { bookmarks[it] = this } } manager.update(bookmarks) } private fun validate(bookmark: Bookmark) = when (bookmark) { is InvalidBookmark -> createValidBookmark(bookmark.url, bookmark.line) is FileBookmarkImpl -> bookmark.file.run { if (isValid) null else createBookmark(url) } is LineBookmarkImpl -> bookmark.file.run { if (isValid) null else createBookmark(url, bookmark.line) } else -> null } private fun isNodeVisible(node: AbstractTreeNode<*>) = (node.value as? InvalidBookmark)?.run { line < 0 } ?: true private val VFM get() = VirtualFileManager.getInstance() init { if (!project.isDefault) { val multicaster = EditorFactory.getInstance().eventMulticaster multicaster.addDocumentListener(this, project) multicaster.addEditorMouseListener(this, project) VFM.addAsyncFileListener(this, project) } } companion object { @JvmStatic fun find(project: Project): LineBookmarkProvider? = when { project.isDisposed -> null else -> BookmarkProvider.EP.findExtension(LineBookmarkProvider::class.java, project) } fun readLineText(bookmark: LineBookmark?) = bookmark?.let { readLineText(it.file, it.line) } fun readLineText(file: VirtualFile, line: Int): String? { val document = FileDocumentManager.getInstance().getDocument(file) ?: return null if (line < 0 || document.lineCount <= line) return null val start = document.getLineStartOffset(line) if (start < 0) return null val end = document.getLineEndOffset(line) if (end < start) return null return document.getText(TextRange.create(start, end)) } } }
apache-2.0
68fccdd302a3424e2c575e20a2175659
43.431452
134
0.728469
4.31272
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/J2KConverterExtension.kt
4
1333
// 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.j2k import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.psi.PsiJavaFile abstract class J2kConverterExtension { abstract val isNewJ2k: Boolean abstract fun createJavaToKotlinConverter( project: Project, targetModule: Module?, settings: ConverterSettings, services: JavaToKotlinConverterServices ): JavaToKotlinConverter abstract fun createPostProcessor(formatCode: Boolean): PostProcessor open fun doCheckBeforeConversion(project: Project, module: Module): Boolean = true abstract fun createWithProgressProcessor( progress: ProgressIndicator?, files: List<PsiJavaFile>?, phasesCount: Int ): WithProgressProcessor companion object { val EP_NAME = ExtensionPointName<J2kConverterExtension>("org.jetbrains.kotlin.j2kConverterExtension") fun extension(useNewJ2k: Boolean): J2kConverterExtension = EP_NAME.extensionList.first { it.isNewJ2k == useNewJ2k } } }
apache-2.0
333ab8eb836c27591cd104cfff42815f
35.027027
158
0.756939
4.82971
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateSecondaryConstructorAction.kt
1
10015
// 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.actions.generate import com.intellij.ide.util.MemberChooser import com.intellij.java.JavaBundle import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ConstructorDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.DescriptorMemberChooserObject import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.lastIsInstanceOrNull class KotlinGenerateSecondaryConstructorAction : KotlinGenerateMemberActionBase<KotlinGenerateSecondaryConstructorAction.Info>() { class Info( val propertiesToInitialize: List<PropertyDescriptor>, val superConstructors: List<ConstructorDescriptor>, val classDescriptor: ClassDescriptor ) override fun isValidForClass(targetClass: KtClassOrObject): Boolean { return targetClass is KtClass && targetClass !is KtEnumEntry && !targetClass.isInterface() && !targetClass.isAnnotation() && !targetClass.hasExplicitPrimaryConstructor() } private fun shouldPreselect(element: PsiElement) = element is KtProperty && !element.isVar private fun chooseSuperConstructors(klass: KtClassOrObject, classDescriptor: ClassDescriptor): List<DescriptorMemberChooserObject> { val project = klass.project val superClassDescriptor = classDescriptor.getSuperClassNotAny() ?: return emptyList() val candidates = superClassDescriptor.constructors .filter { it.isVisible(classDescriptor) } .map { DescriptorMemberChooserObject(DescriptorToSourceUtilsIde.getAnyDeclaration(project, it) ?: klass, it) } if (isUnitTestMode() || candidates.size <= 1) return candidates return with(MemberChooser(candidates.toTypedArray(), false, true, klass.project)) { title = JavaBundle.message("generate.constructor.super.constructor.chooser.title") setCopyJavadocVisible(false) show() selectedElements ?: emptyList() } } private fun choosePropertiesToInitialize(klass: KtClassOrObject, context: BindingContext): List<DescriptorMemberChooserObject> { val candidates = klass.declarations .asSequence() .filterIsInstance<KtProperty>() .filter { it.isVar || context.diagnostics.forElement(it).any { it.factory in Errors.MUST_BE_INITIALIZED_DIAGNOSTICS } } .map { context.get(BindingContext.VARIABLE, it) as PropertyDescriptor } .map { DescriptorMemberChooserObject(it.source.getPsi()!!, it) } .toList() if (isUnitTestMode() || candidates.isEmpty()) return candidates return with(MemberChooser(candidates.toTypedArray(), true, true, klass.project, false, null)) { title = KotlinBundle.message("action.generate.secondary.constructor.choose.properties") setCopyJavadocVisible(false) selectElements(candidates.filter { shouldPreselect(it.element) }.toTypedArray()) show() selectedElements ?: emptyList() } } override fun prepareMembersInfo(klass: KtClassOrObject, project: Project, editor: Editor?): Info? { val context = klass.analyzeWithContent() val classDescriptor = context.get(BindingContext.CLASS, klass) ?: return null val superConstructors = chooseSuperConstructors(klass, classDescriptor).map { it.descriptor as ConstructorDescriptor } val propertiesToInitialize = choosePropertiesToInitialize(klass, context).map { it.descriptor as PropertyDescriptor } return Info(propertiesToInitialize, superConstructors, classDescriptor) } override fun generateMembers(project: Project, editor: Editor?, info: Info): List<KtDeclaration> { val targetClass = info.classDescriptor.source.getPsi() as? KtClass ?: return emptyList() fun Info.findAnchor(): PsiElement? { targetClass.declarations.lastIsInstanceOrNull<KtSecondaryConstructor>()?.let { return it } val lastPropertyToInitialize = propertiesToInitialize.lastOrNull()?.source?.getPsi() val declarationsAfter = lastPropertyToInitialize?.siblings()?.filterIsInstance<KtDeclaration>() ?: targetClass.declarations.asSequence() val firstNonProperty = declarationsAfter.firstOrNull { it !is KtProperty } ?: return null return firstNonProperty.siblings(forward = false).firstIsInstanceOrNull<KtProperty>() ?: targetClass.getOrCreateBody().lBrace } return with(info) { val prototypes = if (superConstructors.isNotEmpty()) { superConstructors.mapNotNull { generateConstructor(classDescriptor, propertiesToInitialize, it) } } else { listOfNotNull(generateConstructor(classDescriptor, propertiesToInitialize, null)) } if (prototypes.isEmpty()) { val errorText = KotlinBundle.message("action.generate.secondary.constructor.error.already.exists") CommonRefactoringUtil.showErrorHint(targetClass.project, editor, errorText, commandName, null) return emptyList() } insertMembersAfter(editor, targetClass, prototypes, findAnchor()) } } private fun generateConstructor( classDescriptor: ClassDescriptor, propertiesToInitialize: List<PropertyDescriptor>, superConstructor: ConstructorDescriptor? ): KtSecondaryConstructor? { fun equalTypes(types1: Collection<KotlinType>, types2: Collection<KotlinType>): Boolean { return types1.size == types2.size && (types1.zip(types2)).all { KotlinTypeChecker.DEFAULT.equalTypes(it.first, it.second) } } val constructorParamTypes = propertiesToInitialize.map { it.type } + (superConstructor?.valueParameters?.map { it.varargElementType ?: it.type } ?: emptyList()) if (classDescriptor.constructors.any { descriptor -> descriptor.source.getPsi() is KtConstructor<*> && equalTypes(descriptor.valueParameters.map { it.varargElementType ?: it.type }, constructorParamTypes) } ) return null val targetClass = classDescriptor.source.getPsi() as KtClass val psiFactory = KtPsiFactory(targetClass) val validator = CollectingNameValidator() val constructor = psiFactory.createSecondaryConstructor("constructor()") val parameterList = constructor.valueParameterList!! if (superConstructor != null) { val substitutor = getTypeSubstitutor(superConstructor.containingDeclaration.defaultType, classDescriptor.defaultType) ?: TypeSubstitutor.EMPTY val delegationCallArguments = ArrayList<String>() for (parameter in superConstructor.valueParameters) { val isVararg = parameter.varargElementType != null val paramName = KotlinNameSuggester.suggestNameByName(parameter.name.asString(), validator) val typeToUse = parameter.varargElementType ?: parameter.type val paramType = IdeDescriptorRenderers.SOURCE_CODE.renderType( substitutor.substitute(typeToUse, Variance.INVARIANT) ?: classDescriptor.builtIns.anyType ) val modifiers = if (isVararg) "vararg " else "" parameterList.addParameter(psiFactory.createParameter("$modifiers$paramName: $paramType")) delegationCallArguments.add(if (isVararg) "*$paramName" else paramName) } val delegationCall = psiFactory.creareDelegatedSuperTypeEntry(delegationCallArguments.joinToString(prefix = "super(", postfix = ")")) constructor.replaceImplicitDelegationCallWithExplicit(false).replace(delegationCall) } if (propertiesToInitialize.isNotEmpty()) { val body = psiFactory.createEmptyBody() for (property in propertiesToInitialize) { val propertyName = property.name val paramName = KotlinNameSuggester.suggestNameByName(propertyName.asString(), validator) val paramType = IdeDescriptorRenderers.SOURCE_CODE.renderType(property.type) parameterList.addParameter(psiFactory.createParameter("$paramName: $paramType")) body.appendElement(psiFactory.createExpression("this.$propertyName = $paramName"), true) } constructor.add(body) } return constructor } }
apache-2.0
70d064734b2d1b841300c8b2b25ebaa8
50.628866
158
0.712032
5.47567
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/builders/KotlinModuleIdentifierBuilder.kt
1
2675
// 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.gradleTooling.builders import org.gradle.api.logging.Logging import org.jetbrains.kotlin.idea.gradleTooling.KotlinLocalModuleIdentifierImpl import org.jetbrains.kotlin.idea.gradleTooling.KotlinMavenModuleIdentifierImpl import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinLocalModuleIdentifierReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinMavenModuleIdentifierReflection import org.jetbrains.kotlin.idea.gradleTooling.reflect.KotlinModuleIdentifierReflection import org.jetbrains.kotlin.idea.projectModel.KotlinLocalModuleIdentifier import org.jetbrains.kotlin.idea.projectModel.KotlinMavenModuleIdentifier import org.jetbrains.kotlin.idea.projectModel.KotlinModuleIdentifier object KotlinModuleIdentifierBuilder : KotlinModelComponentBuilderBase<KotlinModuleIdentifierReflection, KotlinModuleIdentifier> { override fun buildComponent(origin: KotlinModuleIdentifierReflection): KotlinModuleIdentifier? = when (origin) { is KotlinLocalModuleIdentifierReflection -> KotlinLocalModuleIdentifierBuilder.buildComponent(origin) is KotlinMavenModuleIdentifierReflection -> KotlinMavenModuleIdentifierBuilder.buildComponent(origin) else -> { LOGGER.error("Unknown module identifier reflection: \"${origin.javaClass.name}\"") null } } private val LOGGER = Logging.getLogger(KotlinModuleIdentifierBuilder.javaClass) private object KotlinLocalModuleIdentifierBuilder : KotlinModelComponentBuilderBase<KotlinLocalModuleIdentifierReflection, KotlinLocalModuleIdentifier> { override fun buildComponent(origin: KotlinLocalModuleIdentifierReflection): KotlinLocalModuleIdentifier? { return KotlinLocalModuleIdentifierImpl( moduleClassifier = origin.moduleClassifier, buildId = origin.buildId ?: return null, projectId = origin.projectId ?: return null ) } } private object KotlinMavenModuleIdentifierBuilder : KotlinModelComponentBuilderBase<KotlinMavenModuleIdentifierReflection, KotlinMavenModuleIdentifier> { override fun buildComponent(origin: KotlinMavenModuleIdentifierReflection): KotlinMavenModuleIdentifier? { return KotlinMavenModuleIdentifierImpl( moduleClassifier = origin.moduleClassifier, group = origin.group ?: return null, name = origin.name ?: return null ) } } }
apache-2.0
d679c93b5fa2848afaa69bc10cb1b933
54.729167
158
0.775701
5.572917
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/pkg/vault/CndSync.kt
1
1856
package com.cognifide.gradle.aem.common.pkg.vault import com.cognifide.gradle.aem.AemExtension import com.cognifide.gradle.aem.common.pkg.PackageException import com.cognifide.gradle.common.CommonException class CndSync(private val aem: AemExtension) { private val common = aem.common val file = aem.obj.file() val type = aem.obj.typed<CndSyncType> { convention(aem.obj.provider { when { aem.commonOptions.offline.get() -> CndSyncType.NEVER else -> CndSyncType.PRESERVE } }) } fun type(name: String) { type.set(CndSyncType.of(name)) } fun sync() { val file = file.orNull?.asFile ?: throw PackageException("CND file to be synchronized is not specified!") when (type.get()) { CndSyncType.ALWAYS -> syncOrElse { throw PackageException("CND file '$file' cannot be synchronized as of none of AEM instances are available!") } CndSyncType.PRESERVE -> { if (!file.exists()) syncOrElse { aem.logger.warn("CND file '$file' does not exist and moreover cannot be synchronized as of none of AEM instances are available!") } } CndSyncType.NEVER -> {} null -> {} } } private fun syncOrElse(action: () -> Unit) = common.buildScope.doOnce("cndSync") { aem.availableInstance?.sync { try { file.get().asFile.apply { parentFile.mkdirs() writeText(crx.nodeTypes) } } catch (e: CommonException) { aem.logger.debug("Cannot synchronize CND file using $instance! Cause: ${e.message}", e) action() } } ?: action() } }
apache-2.0
2b686bc532a2891cd5234ba74f46b983
32.142857
149
0.556573
4.398104
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/headers/RequestHeadersViewModel.kt
1
9042
package ch.rmy.android.http_shortcuts.activities.editor.headers import android.app.Application import android.content.Context import androidx.lifecycle.viewModelScope import ch.rmy.android.framework.extensions.context import ch.rmy.android.framework.extensions.swapped import ch.rmy.android.framework.utils.localization.Localizable import ch.rmy.android.framework.utils.localization.StringResLocalizable import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.shortcuts.TemporaryShortcutRepository import ch.rmy.android.http_shortcuts.data.models.HeaderModel import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.usecases.GetKeyValueDialogUseCase import ch.rmy.android.http_shortcuts.usecases.KeepVariablePlaceholderProviderUpdatedUseCase import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import javax.inject.Inject class RequestHeadersViewModel(application: Application) : BaseViewModel<Unit, RequestHeadersViewState>(application), WithDialog { @Inject lateinit var temporaryShortcutRepository: TemporaryShortcutRepository @Inject lateinit var keepVariablePlaceholderProviderUpdated: KeepVariablePlaceholderProviderUpdatedUseCase @Inject lateinit var getKeyValueDialog: GetKeyValueDialogUseCase init { getApplicationComponent().inject(this) } private var headers: List<HeaderModel> = emptyList() set(value) { field = value updateViewState { copy( headerItems = mapHeaders(value), ) } } override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun onInitializationStarted(data: Unit) { finalizeInitialization(silent = true) } override fun initViewState() = RequestHeadersViewState() override fun onInitialized() { viewModelScope.launch { try { val temporaryShortcut = temporaryShortcutRepository.getTemporaryShortcut() initViewStateFromShortcut(temporaryShortcut) } catch (e: CancellationException) { throw e } catch (e: Exception) { onInitializationError(e) } } viewModelScope.launch { keepVariablePlaceholderProviderUpdated(::emitCurrentViewState) } } private fun initViewStateFromShortcut(shortcut: ShortcutModel) { headers = shortcut.headers } private fun onInitializationError(error: Throwable) { handleUnexpectedError(error) finish() } fun onHeaderMoved(headerId1: String, headerId2: String) { headers = headers.swapped(headerId1, headerId2) { id } launchWithProgressTracking { temporaryShortcutRepository.moveHeader(headerId1, headerId2) } } fun onAddHeaderButtonClicked() { showAddHeaderDialog() } private fun showAddHeaderDialog() { showKeyValueDialog( title = StringResLocalizable(R.string.title_custom_header_add), keyLabel = StringResLocalizable(R.string.label_custom_header_key), valueLabel = StringResLocalizable(R.string.label_custom_header_value), suggestions = SUGGESTED_KEYS, keyValidator = { validateHeaderName(context, it) }, valueValidator = { validateHeaderValue(context, it) }, onConfirm = ::onAddHeaderDialogConfirmed, ) } private fun showKeyValueDialog( title: Localizable, keyLabel: Localizable, valueLabel: Localizable, key: String? = null, value: String? = null, suggestions: Array<String>? = null, keyValidator: (CharSequence) -> String? = { _ -> null }, valueValidator: (CharSequence) -> String? = { _ -> null }, onConfirm: (key: String, value: String) -> Unit, onRemove: () -> Unit = {}, ) { dialogState = getKeyValueDialog( title = title, keyLabel = keyLabel, valueLabel = valueLabel, key = key, value = value, suggestions = suggestions, keyValidator = keyValidator, valueValidator = valueValidator, onConfirm = onConfirm, onRemove = onRemove, ) } private fun onAddHeaderDialogConfirmed(key: String, value: String) { launchWithProgressTracking { val newHeader = temporaryShortcutRepository.addHeader(key, value) headers = headers.plus(newHeader) } } private fun onEditHeaderDialogConfirmed(headerId: String, key: String, value: String) { headers = headers .map { header -> if (header.id == headerId) { HeaderModel(headerId, key, value) } else { header } } launchWithProgressTracking { temporaryShortcutRepository.updateHeader(headerId, key, value) } } private fun onRemoveHeaderButtonClicked(headerId: String) { headers = headers.filter { header -> header.id != headerId } launchWithProgressTracking { temporaryShortcutRepository.removeHeader(headerId) } } fun onHeaderClicked(id: String) { headers.firstOrNull { header -> header.id == id } ?.let { header -> showEditHeaderDialog(id, header.key, header.value) } } private fun showEditHeaderDialog(headerId: String, headerKey: String, headerValue: String) { showKeyValueDialog( title = StringResLocalizable(R.string.title_custom_header_edit), keyLabel = StringResLocalizable(R.string.label_custom_header_key), valueLabel = StringResLocalizable(R.string.label_custom_header_value), key = headerKey, value = headerValue, suggestions = SUGGESTED_KEYS, keyValidator = { validateHeaderName(context, it) }, valueValidator = { validateHeaderValue(context, it) }, onConfirm = { newKey: String, newValue: String -> onEditHeaderDialogConfirmed(headerId, newKey, newValue) }, onRemove = { onRemoveHeaderButtonClicked(headerId) }, ) } fun onBackPressed() { viewModelScope.launch { waitForOperationsToFinish() finish() } } companion object { private fun mapHeaders(headers: List<HeaderModel>): List<HeaderListItem> = headers.map { header -> HeaderListItem.Header( id = header.id, key = header.key, value = header.value, ) } .ifEmpty { listOf(HeaderListItem.EmptyState) } val SUGGESTED_KEYS = arrayOf( "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Accept-Datetime", "Authorization", "Cache-Control", "Connection", "Cookie", "Content-Length", "Content-MD5", "Content-Type", "Date", "Expect", "Forwarded", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards", "Origin", "Pragma", "Proxy-Authorization", "Range", "Referer", "TE", "User-Agent", "Upgrade", "Via", "Warning", ) private fun validateHeaderName(context: Context, name: CharSequence): String? = name .firstOrNull { c -> c <= '\u0020' || c >= '\u007f' } ?.let { invalidChar -> context.getString(R.string.error_invalid_character, invalidChar) } private fun validateHeaderValue(context: Context, value: CharSequence): String? = value .firstOrNull { c -> (c <= '\u001f' && c != '\t') || c >= '\u007f' } ?.let { invalidChar -> context.getString(R.string.error_invalid_character, invalidChar) } } }
mit
d5d4d153851987d7b06534121d2312c9
32.488889
129
0.586706
5.012195
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/authentication/AuthenticationViewModel.kt
1
7823
package ch.rmy.android.http_shortcuts.activities.editor.authentication import android.app.Application import android.net.Uri import android.text.InputType import androidx.lifecycle.viewModelScope import ch.rmy.android.framework.viewmodel.BaseViewModel import ch.rmy.android.framework.viewmodel.WithDialog import ch.rmy.android.framework.viewmodel.viewstate.DialogState import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.activities.editor.authentication.usecases.CopyCertificateFileUseCase import ch.rmy.android.http_shortcuts.activities.variables.VariablesActivity import ch.rmy.android.http_shortcuts.dagger.getApplicationComponent import ch.rmy.android.http_shortcuts.data.domains.shortcuts.TemporaryShortcutRepository import ch.rmy.android.http_shortcuts.data.dtos.VariablePlaceholder import ch.rmy.android.http_shortcuts.data.enums.ClientCertParams import ch.rmy.android.http_shortcuts.data.enums.ShortcutAuthenticationType import ch.rmy.android.http_shortcuts.data.models.ShortcutModel import ch.rmy.android.http_shortcuts.extensions.createDialogState import ch.rmy.android.http_shortcuts.usecases.GetVariablePlaceholderPickerDialogUseCase import ch.rmy.android.http_shortcuts.usecases.KeepVariablePlaceholderProviderUpdatedUseCase import kotlinx.coroutines.CancellationException import kotlinx.coroutines.launch import javax.inject.Inject class AuthenticationViewModel(application: Application) : BaseViewModel<Unit, AuthenticationViewState>(application), WithDialog { @Inject lateinit var temporaryShortcutRepository: TemporaryShortcutRepository @Inject lateinit var keepVariablePlaceholderProviderUpdated: KeepVariablePlaceholderProviderUpdatedUseCase @Inject lateinit var copyCertificateFile: CopyCertificateFileUseCase @Inject lateinit var getVariablePlaceholderPickerDialog: GetVariablePlaceholderPickerDialogUseCase init { getApplicationComponent().inject(this) } override var dialogState: DialogState? get() = currentViewState?.dialogState set(value) { updateViewState { copy(dialogState = value) } } override fun onInitializationStarted(data: Unit) { finalizeInitialization(silent = true) } override fun initViewState() = AuthenticationViewState() override fun onInitialized() { viewModelScope.launch { try { val temporaryShortcut = temporaryShortcutRepository.getTemporaryShortcut() initViewStateFromShortcut(temporaryShortcut) } catch (e: CancellationException) { throw e } catch (e: Exception) { onInitializationError(e) } } viewModelScope.launch { keepVariablePlaceholderProviderUpdated(::emitCurrentViewState) } } private fun initViewStateFromShortcut(shortcut: ShortcutModel) { updateViewState { copy( authenticationType = shortcut.authenticationType, username = shortcut.username, password = shortcut.password, token = shortcut.authToken, clientCertParams = shortcut.clientCertParams, isClientCertButtonEnabled = !shortcut.acceptAllCertificates, ) } } private fun onInitializationError(error: Throwable) { handleUnexpectedError(error) finish() } fun onAuthenticationTypeChanged(authenticationType: ShortcutAuthenticationType) { updateViewState { copy( authenticationType = authenticationType, ) } launchWithProgressTracking { temporaryShortcutRepository.setAuthenticationType(authenticationType) } } fun onUsernameChanged(username: String) { updateViewState { copy(username = username) } launchWithProgressTracking { temporaryShortcutRepository.setUsername(username) } } fun onPasswordChanged(password: String) { updateViewState { copy(password = password) } launchWithProgressTracking { temporaryShortcutRepository.setPassword(password) } } fun onTokenChanged(token: String) { updateViewState { copy(token = token) } launchWithProgressTracking { temporaryShortcutRepository.setToken(token) } } fun onClientCertParamsChanged(clientCertParams: ClientCertParams?) { updateViewState { copy(clientCertParams = clientCertParams) } launchWithProgressTracking { temporaryShortcutRepository.setClientCertParams(clientCertParams) } } fun onClientCertButtonClicked() { doWithViewState { viewState -> if (viewState.clientCertParams == null) { showClientCertDialog() } else { onClientCertParamsChanged(null) } } } private fun showClientCertDialog() { dialogState = createDialogState { title(R.string.title_client_cert) .item(R.string.label_client_cert_from_os, descriptionRes = R.string.label_client_cert_from_os_subtitle) { promptForClientCertAlias() } .item(R.string.label_client_cert_from_file, descriptionRes = R.string.label_client_cert_from_file_subtitle) { openCertificateFilePicker() } .build() } } private fun promptForClientCertAlias() { emitEvent(AuthenticationEvent.PromptForClientCertAlias) } private fun openCertificateFilePicker() { emitEvent(AuthenticationEvent.OpenCertificateFilePicker) } fun onCertificateFileSelected(file: Uri) { launchWithProgressTracking { try { val fileName = copyCertificateFile(file) promptForPassword(fileName) } catch (e: CancellationException) { throw e } catch (e: Exception) { handleUnexpectedError(e) } } } private fun promptForPassword(fileName: String) { dialogState = createDialogState { title(R.string.title_client_cert_file_password) .textInput( inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD, ) { password -> onClientCertParamsChanged( ClientCertParams.File(fileName, password) ) } .build() } } fun onBackPressed() { viewModelScope.launch { waitForOperationsToFinish() finish() } } fun onUsernameVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForUsername(it) } } fun onPasswordVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForPassword(it) } } fun onTokenVariableButtonClicked() { showVariableDialog { AuthenticationEvent.InsertVariablePlaceholderForToken(it) } } private fun showVariableDialog(onVariablePicked: (VariablePlaceholder) -> AuthenticationEvent) { dialogState = getVariablePlaceholderPickerDialog.invoke( onVariableSelected = { emitEvent(onVariablePicked(it)) }, onEditVariableButtonClicked = { openActivity( VariablesActivity.IntentBuilder() ) }, ) } }
mit
60415e7f47f5ed32d43013bdd531677e
31.869748
129
0.651668
5.428869
false
false
false
false