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
ZhuoKeTeam/JueDiQiuSheng
app/src/main/java/cc/zkteam/juediqiusheng/module/category/BaseCategoryListActivity.kt
1
2928
package cc.zkteam.juediqiusheng.module.category import android.graphics.Color import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import android.view.MenuItem import android.view.Window import cc.zkteam.juediqiusheng.R import cc.zkteam.juediqiusheng.activity.BaseActivity import com.alibaba.android.arouter.facade.annotation.Route import com.blankj.utilcode.util.ToastUtils import com.google.gson.Gson import okhttp3.* import java.io.IOException @Route(path = "/module/category") class BaseCategoryListActivity : BaseActivity() { override fun getLayoutId(): Int { return R.layout.activity_base_category_list } override fun initViews() {//function } override fun initListener() {//function } override fun initData() {//function } private var toolbar: Toolbar? = null private var list: RecyclerView? = null private var adapter: CategoryAdapter? = null private var datas: List<BeanCategory.ResultBean>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportRequestWindowFeature(Window.FEATURE_NO_TITLE) toolbar = findViewById(R.id.toolbar_category) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) initView() requestData() } private fun initView() { toolbar!!.setTitleTextColor(Color.WHITE) toolbar!!.title = getString(R.string.category_list) list = findViewById(R.id.list_category) list!!.layoutManager = LinearLayoutManager(this) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item?.itemId){ android.R.id.home -> finish() } return super.onOptionsItemSelected(item) } private fun requestData() { val client = OkHttpClient() val request: Request = Request.Builder().url("http://www.zkteam.cc/JueDiQiuSheng/categoryJson?PAGE_COUNT=20").build() val call: Call = client.newCall(request) call.enqueue(object : Callback { override fun onFailure(var1: Call, var2: IOException) { ToastUtils.showShort(var2.message) } override fun onResponse(var1: Call, var2: Response) { val str = var2.body()!!.string() callbackOnSuccess(str) } }) } private fun callbackOnSuccess(str: String) { val result: BeanCategory = Gson().fromJson(str, BeanCategory::class.java) if (result.result != null && !result.result.isEmpty()) { datas = result.result adapter = CategoryAdapter(this, datas) list?.post({ run { list?.adapter = adapter } }) } } }
bsd-3-clause
7fabec37a317e66da2af7cd9f0f15f58
29.185567
125
0.653347
4.456621
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/flow/Timers.kt
1
2518
package be.digitalia.fosdem.flow import be.digitalia.fosdem.utils.ElapsedRealTimeSource import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.flow import java.util.Arrays import kotlin.time.Duration import kotlin.time.ExperimentalTime import kotlin.time.TimeMark import kotlin.time.TimeSource fun tickerFlow(period: Duration): Flow<Unit> = flow { while (true) { emit(Unit) delay(period) } } @OptIn(ExperimentalTime::class) fun synchronizedTickerFlow(period: Duration, subscriptionCount: StateFlow<Int>): Flow<Unit> { return synchronizedTickerFlow(period, subscriptionCount, ElapsedRealTimeSource) } /** * Creates a ticker Flow which delays emitting a value until there is at least one subscription. * timeSource needs to be monotonic. */ @ExperimentalTime fun synchronizedTickerFlow( period: Duration, subscriptionCount: StateFlow<Int>, timeSource: TimeSource ): Flow<Unit> { return flow { var nextEmissionTimeMark: TimeMark? = null flow { nextEmissionTimeMark?.let { delay(-it.elapsedNow()) } while (true) { emit(Unit) nextEmissionTimeMark = timeSource.markNow() + period delay(period) } } .flowWhileShared(subscriptionCount, SharingStarted.WhileSubscribed()) .collect(this) } } /** * Builds a Flow whose value is true during scheduled periods. * * @param startEndTimestamps a list of timestamps in milliseconds, sorted in chronological order. * Odd and even values represent beginnings and ends of periods, respectively. */ fun schedulerFlow(vararg startEndTimestamps: Long): Flow<Boolean> { return flow { var now = System.currentTimeMillis() var pos = Arrays.binarySearch(startEndTimestamps, now) while (true) { val size = startEndTimestamps.size if (pos >= 0) { do { pos++ } while (pos < size && startEndTimestamps[pos] == now) } else { pos = pos.inv() } emit(pos % 2 != 0) if (pos == size) { break } // Readjust current time after suspending emit() delay(startEndTimestamps[pos] - System.currentTimeMillis()) now = startEndTimestamps[pos] } } }
apache-2.0
098aa63b13913b4b887a5d36896c980a
30.4875
97
0.644559
4.496429
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/ResumeStageHandlerSpec.kt
1
2406
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.spek.shouldEqual import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek object ResumeStageHandlerSpec : SubjectSpek<ResumeStageHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject { ResumeStageHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("resuming a paused execution") { val pipeline = pipeline { application = "spinnaker" status = RUNNING stage { refId = "1" status = PAUSED task { id = "1" status = SUCCEEDED } task { id = "2" status = PAUSED } task { id = "3" status = NOT_STARTED } } } val message = ResumeStage(Pipeline::class.java, pipeline.id, pipeline.application, pipeline.stages.first().id) beforeGroup { whenever(repository.retrievePipeline(pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("sets the stage status to running") { verify(repository).storeStage(check { it.getId() shouldEqual message.stageId it.getStatus() shouldEqual RUNNING }) } it("resumes all paused tasks") { verify(queue).push(ResumeTask(message, "2")) verifyNoMoreInteractions(queue) } } })
apache-2.0
ab2bb0ae02420de98beb3f54bb37516e
27.305882
114
0.679551
4.273535
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/fragment/SetupCommentSectionTask.kt
1
17642
package com.newsblur.fragment import android.content.Context import android.content.Intent import android.text.TextUtils import android.util.Log import android.view.LayoutInflater import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.lifecycleScope import com.google.android.material.imageview.ShapeableImageView import com.newsblur.R import com.newsblur.activity.Profile import com.newsblur.domain.Comment import com.newsblur.domain.Story import com.newsblur.domain.UserDetails import com.newsblur.util.* import com.newsblur.view.FlowLayout import java.lang.ref.WeakReference import java.util.* class SetupCommentSectionTask(private val fragment: ReadingItemFragment, view: View, inflater: LayoutInflater, story: Story?, iconLoader: ImageLoader) { private var topCommentViews: ArrayList<View>? = null private var topShareViews: ArrayList<View>? = null private var publicCommentViews: ArrayList<View>? = null private var friendCommentViews: ArrayList<View>? = null private var friendShareViews: ArrayList<View>? = null private val story: Story? private val inflater: LayoutInflater private val viewHolder: WeakReference<View> private val context: Context? private val user: UserDetails private val manager: FragmentManager private val iconLoader: ImageLoader private var comments: MutableList<Comment>? = null /** * Do all the DB access and image view creation in the async portion of the task, saving the views in local members. */ fun execute() { fragment.lifecycleScope.executeAsyncTask( doInBackground = { doInBackground() }, onPostExecute = { onPostExecute() } ) } private fun doInBackground() { if (context == null || story == null) return comments = fragment.dbHelper.getComments(story.id) topCommentViews = ArrayList() topShareViews = ArrayList() publicCommentViews = ArrayList() friendCommentViews = ArrayList() friendShareViews = ArrayList() // users by whom we saw non-pseudo comments val commentingUserIds: MutableSet<String> = HashSet() // users by whom we saw shares val sharingUserIds: MutableSet<String> = HashSet() for (comment in comments!!) { // skip public comments if they are disabled if (!comment.byFriend && !PrefsUtils.showPublicComments(context)) { continue } val commentUser = fragment.dbHelper.getUserProfile(comment.userId) // rarely, we get a comment but never got the user's profile, so we can't display it if (commentUser == null) { Log.w(this.javaClass.name, "cannot display comment from missing user ID: " + comment.userId) continue } val commentView = inflater.inflate(R.layout.include_comment, null) val commentText = commentView.findViewById<View>(R.id.comment_text) as TextView commentText.text = UIUtils.fromHtml(comment.commentText) val commentImage = commentView.findViewById<View>(R.id.comment_user_image) as ShapeableImageView val commentSharedDate = commentView.findViewById<View>(R.id.comment_shareddate) as TextView // TODO: this uses hard-coded "ago" values, which will be wrong when reading prefetched stories if (comment.sharedDate != null) { commentSharedDate.text = comment.sharedDate + " ago" } val favouriteContainer = commentView.findViewById<View>(R.id.comment_favourite_avatars) as FlowLayout val favouriteIcon = commentView.findViewById<View>(R.id.comment_favourite_icon) as ImageView val replyIcon = commentView.findViewById<View>(R.id.comment_reply_icon) as ImageView if (comment.likingUsers != null) { if (mutableListOf<String>(*comment.likingUsers).contains(user.id)) { favouriteIcon.setImageResource(R.drawable.ic_star_active) } for (id in comment.likingUsers) { val favouriteImage = ShapeableImageView(context) val user = fragment.dbHelper.getUserProfile(id) if (user != null) { fragment.iconLoader.displayImage(user.photoUrl, favouriteImage) favouriteContainer.addView(favouriteImage) } } // users cannot fave their own comments. attempting to do so will actually queue a fatally invalid API call if (TextUtils.equals(comment.userId, user.id)) { favouriteIcon.visibility = View.GONE } else { favouriteIcon.setOnClickListener { if (!mutableListOf<String>(*comment.likingUsers).contains(user.id)) { fragment.feedUtils.likeComment(story, comment.userId, context) } else { fragment.feedUtils.unlikeComment(story, comment.userId, context) } } } } if (comment.isPlaceholder) { replyIcon.visibility = View.INVISIBLE } else { replyIcon.setOnClickListener { val user = fragment.dbHelper.getUserProfile(comment.userId) if (user != null) { val newFragment: DialogFragment = ReplyDialogFragment.newInstance(story, comment.userId, user.username) newFragment.show(manager, "dialog") } } } val replies = fragment.dbHelper.getCommentReplies(comment.id) for (reply in replies) { val replyView = inflater.inflate(R.layout.include_reply, null) val replyText = replyView.findViewById<View>(R.id.reply_text) as TextView replyText.text = UIUtils.fromHtml(reply.text) val replyImage = replyView.findViewById<View>(R.id.reply_user_image) as ShapeableImageView val replyUser = fragment.dbHelper.getUserProfile(reply.userId) if (replyUser != null) { fragment.iconLoader.displayImage(replyUser.photoUrl, replyImage) replyImage.setOnClickListener { val i = Intent(context, Profile::class.java) i.putExtra(Profile.USER_ID, replyUser.userId) context.startActivity(i) } val replyUsername = replyView.findViewById<View>(R.id.reply_username) as TextView replyUsername.text = replyUser.username } else { val replyUsername = replyView.findViewById<View>(R.id.reply_username) as TextView replyUsername.setText(R.string.unknown_user) } if (reply.shortDate != null) { val replySharedDate = replyView.findViewById<View>(R.id.reply_shareddate) as TextView replySharedDate.text = reply.shortDate + " ago" } val editIcon = replyView.findViewById<View>(R.id.reply_edit_icon) as ImageView if (TextUtils.equals(reply.userId, user.id)) { editIcon.setOnClickListener { val newFragment: DialogFragment = EditReplyDialogFragment.newInstance(story, comment.userId, reply.id, reply.text) newFragment.show(manager, "dialog") } } else { editIcon.visibility = View.INVISIBLE } (commentView.findViewById<View>(R.id.comment_replies_container) as LinearLayout).addView(replyView) } val commentUsername = commentView.findViewById<View>(R.id.comment_username) as TextView commentUsername.text = commentUser.username val userPhoto = commentUser.photoUrl val commentLocation = commentView.findViewById<View>(R.id.comment_location) as TextView if (!TextUtils.isEmpty(commentUser.location)) { commentLocation.text = commentUser.location } else { commentLocation.visibility = View.GONE } if (!TextUtils.isEmpty(comment.sourceUserId)) { commentImage.visibility = View.INVISIBLE val usershareImage = commentView.findViewById<View>(R.id.comment_user_reshare_image) as ShapeableImageView val sourceUserImage = commentView.findViewById<View>(R.id.comment_sharesource_image) as ShapeableImageView sourceUserImage.visibility = View.VISIBLE usershareImage.visibility = View.VISIBLE commentImage.visibility = View.INVISIBLE val sourceUser = fragment.dbHelper.getUserProfile(comment.sourceUserId) if (sourceUser != null) { fragment.iconLoader.displayImage(sourceUser.photoUrl, sourceUserImage) fragment.iconLoader.displayImage(userPhoto, usershareImage) } } else { fragment.iconLoader.displayImage(userPhoto, commentImage) } commentImage.setOnClickListener { val i = Intent(context, Profile::class.java) i.putExtra(Profile.USER_ID, comment.userId) context.startActivity(i) } if (comment.isPseudo) { friendShareViews!!.add(commentView) sharingUserIds.add(comment.userId) } else if (comment.byFriend) { friendCommentViews!!.add(commentView) } else { publicCommentViews!!.add(commentView) } // for actual comments, also populate the upper icon bar if (!comment.isPseudo) { val image = ViewUtils.createSharebarImage(context, commentUser.photoUrl, commentUser.userId, iconLoader) topCommentViews!!.add(image) commentingUserIds.add(comment.userId) } } // the story object supplements the pseudo-comment share list for (userId in story.sharedUserIds) { // for the purpose of this top-line share list, exclude non-pseudo comments if (!commentingUserIds.contains(userId)) { sharingUserIds.add(userId) } } // now that we have all shares from the comments table and story object, populate the shares row for (userId in sharingUserIds) { val user = fragment.dbHelper.getUserProfile(userId) if (user == null) { Log.w(this.javaClass.name, "cannot display share from missing user ID: $userId") continue } val image = ViewUtils.createSharebarImage(context, user.photoUrl, user.userId, iconLoader) topShareViews!!.add(image) } } /** * Push all the pre-created views into the actual UI. */ private fun onPostExecute() { if (context == null) return val view = viewHolder.get() ?: return // fragment was dismissed before we rendered val headerCommentTotal = view.findViewById<View>(R.id.comment_by) as TextView val headerShareTotal = view.findViewById<View>(R.id.shared_by) as TextView val sharedGrid = view.findViewById<View>(R.id.reading_social_shareimages) as FlowLayout val commentGrid = view.findViewById<View>(R.id.reading_social_commentimages) as FlowLayout val friendCommentTotal = view.findViewById<View>(R.id.reading_friend_comment_total) as TextView val friendShareTotal = view.findViewById<View>(R.id.reading_friend_emptyshare_total) as TextView val publicCommentTotal = view.findViewById<View>(R.id.reading_public_comment_total) as TextView val publicCommentCount = publicCommentViews!!.size val friendCommentCount = friendCommentViews!!.size val friendShareCount = friendShareViews!!.size val allCommentCount = topCommentViews!!.size val allShareCount = topShareViews!!.size if (allCommentCount > 0 || allShareCount > 0) { view.findViewById<View>(R.id.reading_share_bar).visibility = View.VISIBLE view.findViewById<View>(R.id.share_bar_underline).visibility = View.VISIBLE } else { view.findViewById<View>(R.id.reading_share_bar).visibility = View.GONE view.findViewById<View>(R.id.share_bar_underline).visibility = View.GONE } sharedGrid.removeAllViews() for (image in topShareViews!!) { sharedGrid.addView(image) } commentGrid.removeAllViews() for (image in topCommentViews!!) { commentGrid.addView(image) } if (allCommentCount > 0) { var countText = context.getString(R.string.friends_comments_count) if (allCommentCount == 1) { countText = countText.substring(0, countText.length - 1) } headerCommentTotal.text = String.format(countText, allCommentCount) headerCommentTotal.visibility = View.VISIBLE } else { headerCommentTotal.visibility = View.GONE } if (allShareCount > 0) { var countText = context.getString(R.string.friends_shares_count) if (allShareCount == 1) { countText = countText.substring(0, countText.length - 1) } headerShareTotal.text = String.format(countText, allShareCount) headerShareTotal.visibility = View.VISIBLE } else { headerShareTotal.visibility = View.GONE } if (publicCommentCount > 0) { var commentCount = context.getString(R.string.public_comment_count) if (publicCommentCount == 1) { commentCount = commentCount.substring(0, commentCount.length - 1) } publicCommentTotal.text = String.format(commentCount, publicCommentCount) view.findViewById<View>(R.id.reading_public_comment_header).visibility = View.VISIBLE } else { view.findViewById<View>(R.id.reading_public_comment_header).visibility = View.GONE } if (friendCommentCount > 0) { var commentCount = context.getString(R.string.friends_comments_count) if (friendCommentCount == 1) { commentCount = commentCount.substring(0, commentCount.length - 1) } friendCommentTotal.text = String.format(commentCount, friendCommentCount) view.findViewById<View>(R.id.reading_friend_comment_header).visibility = View.VISIBLE } else { view.findViewById<View>(R.id.reading_friend_comment_header).visibility = View.GONE } if (friendShareCount > 0) { var commentCount = context.getString(R.string.friends_shares_count) if (friendShareCount == 1) { commentCount = commentCount.substring(0, commentCount.length - 1) } friendShareTotal.text = String.format(commentCount, friendShareCount) view.findViewById<View>(R.id.reading_friend_emptyshare_header).visibility = View.VISIBLE } else { view.findViewById<View>(R.id.reading_friend_emptyshare_header).visibility = View.GONE } val publicCommentListContainer = view.findViewById<View>(R.id.reading_public_comment_container) as LinearLayout publicCommentListContainer.removeAllViews() for (i in publicCommentViews!!.indices) { if (i == publicCommentViews!!.size - 1) { publicCommentViews!![i].findViewById<View>(R.id.comment_divider).visibility = View.GONE } publicCommentListContainer.addView(publicCommentViews!![i]) } val friendCommentListContainer = view.findViewById<View>(R.id.reading_friend_comment_container) as LinearLayout friendCommentListContainer.removeAllViews() for (i in friendCommentViews!!.indices) { if (i == friendCommentViews!!.size - 1) { friendCommentViews!![i].findViewById<View>(R.id.comment_divider).visibility = View.GONE } friendCommentListContainer.addView(friendCommentViews!![i]) } val friendShareListContainer = view.findViewById<View>(R.id.reading_friend_emptyshare_container) as LinearLayout friendShareListContainer.removeAllViews() for (i in friendShareViews!!.indices) { if (i == friendShareViews!!.size - 1) { friendShareViews!![i].findViewById<View>(R.id.comment_divider).visibility = View.GONE } friendShareListContainer.addView(friendShareViews!![i]) } fragment.onSocialLoadFinished() } init { context = fragment.requireContext() manager = fragment.parentFragmentManager this.inflater = inflater this.story = story viewHolder = WeakReference(view) user = PrefsUtils.getUserDetails(context) this.iconLoader = iconLoader } }
mit
6c78be42e20dc9e1c2a578e85c258d87
49.408571
152
0.621415
4.777146
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/common/grpc/DefaultDeadlineInterceptor.kt
1
1916
/* * Copyright 2022 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.common.grpc import io.grpc.CallOptions import io.grpc.Channel import io.grpc.ClientCall import io.grpc.ClientInterceptor import io.grpc.ClientInterceptors import io.grpc.MethodDescriptor import java.time.Duration import java.util.concurrent.TimeUnit /** * [ClientInterceptor] which sets a deadline after [duration] for any call that does not already * have a deadline set. */ class DefaultDeadlineInterceptor(private val duration: Long, private val timeUnit: TimeUnit) : ClientInterceptor { override fun <ReqT : Any, RespT : Any> interceptCall( method: MethodDescriptor<ReqT, RespT>, callOptions: CallOptions, next: Channel, ): ClientCall<ReqT, RespT> { val subCallOptions = if (callOptions.deadline == null) { callOptions.withDeadlineAfter(duration, timeUnit) } else { callOptions } return next.newCall(method, subCallOptions) } } fun Channel.withDefaultDeadline(duration: Long, timeUnit: TimeUnit): Channel = ClientInterceptors.interceptForward(this, DefaultDeadlineInterceptor(duration, timeUnit)) fun Channel.withDefaultDeadline(duration: Duration): Channel = ClientInterceptors.interceptForward( this, DefaultDeadlineInterceptor(duration.toMillis(), TimeUnit.MILLISECONDS) )
apache-2.0
5e29ab2c4bb8c541b7fd6cdf8ae0bd54
32.614035
96
0.754697
4.286353
false
false
false
false
wireapp/wire-android
storage/src/main/kotlin/com/waz/zclient/storage/db/folders/FoldersEntity.kt
1
405
package com.waz.zclient.storage.db.folders import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "Folders") data class FoldersEntity( @PrimaryKey @ColumnInfo(name = "_id") val id: String, @ColumnInfo(name = "name", defaultValue = "") val name: String, @ColumnInfo(name = "type", defaultValue = "0") val type: Int )
gpl-3.0
919b21fdba2dd7647bfb80d0bc0db07d
21.5
50
0.693827
3.75
false
false
false
false
EyeBody/EyeBody
EyeBody2/app/src/main/java/com/example/android/eyebody/camera/CameraActivity.kt
1
8825
package com.example.android.eyebody.camera import android.app.Activity import android.content.Intent import android.graphics.PixelFormat import android.hardware.Camera import android.hardware.Camera.PictureCallback import android.hardware.Camera.ShutterCallback import android.net.Uri import android.os.Bundle import android.support.v4.view.GestureDetectorCompat import android.util.Log import android.view.* import android.view.ViewGroup.LayoutParams import android.widget.Toast import com.example.android.eyebody.MainActivity import com.example.android.eyebody.R import com.example.android.eyebody.management.ManagementActivity import com.example.android.eyebody.management.main.MainManagementFragment import kotlinx.android.synthetic.main.activity_camera.* import java.io.File import java.io.FileOutputStream import java.io.IOException import java.util.* /* * ์นด๋ฉ”๋ผ(์‚ฌ์ง„์ดฌ์˜, ์นด๋ฉ”๋ผ๊ฐ€์ด๋“œ) * ์นด๋ฉ”๋ผ, ์™ธ์žฅ๋ฉ”๋ชจ๋ฆฌ ์ €์žฅ ๊ถŒํ•œ * camera preview์—์„œ SurfaceView ํด๋ž˜์Šค ์‚ฌ์šฉํ•˜๋ฉด ์ด๋ฏธ์ง€๋ฅผ ์˜ค๋ฒ„๋ ˆ์ด ํ•  ์ˆ˜ ์žˆ์Œ */ class CameraActivity : Activity(), SurfaceHolder.Callback { var TAG: String = "CameraActivity" private var rootPath: String? = null private var surfaceHolder: SurfaceHolder? = null private var camera: Camera? = null private var previewing: Boolean = false private var count: Int = 0 private var frontImageUri: Uri? = null private var sideImageUri: Uri? = null private var frontImage: ByteArray? = null private var sideImage: ByteArray? = null private var frontImageName: String? = null private var sideImageName: String? = null private var controlInflater: LayoutInflater? = null private var viewControl: View ?=null var timeStamp:String="" var gestureObject:GestureDetectorCompat?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_camera) init() shutterButtonClicked() setLayout() gestureObject = GestureDetectorCompat(this, LearnGesture()) } override fun onTouchEvent(event: MotionEvent): Boolean { this.gestureObject!!.onTouchEvent(event) return super.onTouchEvent(event) } private fun init() { window.setFormat(PixelFormat.UNKNOWN) surfaceHolder = cameraScreen.holder surfaceHolder?.addCallback(this) surfaceHolder?.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS) }//์ดˆ๊ธฐํ™”ํ•จ์ˆ˜ private fun setLayout() { controlInflater = LayoutInflater.from(baseContext) viewControl = controlInflater?.inflate(R.layout.front_guide_pic, null) var layoutParamsControl = LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) this.addContentView(viewControl, layoutParamsControl) } //์ด๋ฏธ์ง€ ๊ฐ€์ด๋“œ ํ‘œ์‹œ ํ•จ์ˆ˜ private fun setTextView() { textView_setOrder.text = "์˜†๋ฉด์„ ์ฐ์–ด์ฃผ์„ธ์š”" }//์•ž์„ ์ฐ์„์ง€ ์˜†์„ ์ฐ์„์ง€ ๋งํ•ด์ฃผ๋Š” ํ•จ์ˆ˜ private fun changeImage() { (viewControl?.parent as ViewManager).removeView(viewControl) controlInflater = LayoutInflater.from(baseContext) viewControl = controlInflater?.inflate(R.layout.side_guide_pic, null) var layoutParamsControl = LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) this.addContentView(viewControl, layoutParamsControl) }//์ด๋ฏธ์ง€ ๊ฐ€์ด๋“œ ๋ณ€๊ฒฝ ํ•จ์ˆ˜ //TODO : ์ด๋ฏธ์ง€ ์œ„์— ์˜ฌ๋ฆฌ๋Š” ๊ฐ€์ด๋“œ๋ฅผ ์ „์— ์ฐ์€ ์‚ฌ์ง„์œผ๋กœ ํ•œ๋‹ค. private fun shutterButtonClicked() { btn_shutter.setOnClickListener { try { camera?.takePicture(null, null, jpegCallback) } catch (e: RuntimeException) { Log.d(TAG, "take picture failed") } } }//์…”ํ„ฐ ๋ฒ„ํŠผ ๋ˆŒ๋ฆฌ๋ฉด ์‹คํ–‰๋˜๋Š” ํ•จ์ˆ˜ private fun goConfirmActivity() { var confirmIntent = Intent(this, ConfirmActivity::class.java) confirmIntent.putExtra("frontUri", frontImageUri.toString()) confirmIntent.putExtra("sideUri", sideImageUri.toString()) confirmIntent.putExtra("frontName", frontImageName) confirmIntent.putExtra("sideName", sideImageName) confirmIntent.putExtra("time",timeStamp) startActivity(confirmIntent) }//ํ™•์ธ์ฐฝ์œผ๋กœ ๋„˜์–ด๊ฐ€๋Š” ํ•จ์ˆ˜ //์ด๋ฏธ ์•ฑ์„ ์‹คํ–‰์‹œํ‚จ ์ „์ ์ด ์žˆ์œผ๋ฉด ๊ทธ๋ƒฅ ํŒจ์Šค, ์•„๋‹ˆ๋ฉด ํด๋”๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. private fun makeFolder() { rootPath = getExternalFilesDir(null).toString() + "/gallery_body" var file = File(rootPath) file.mkdirs() } //TODO : ์‚ฌ์ง„ ์ €์žฅ์‹œ ์šฉ๋Ÿ‰์ด ํ„ฐ์งˆ ๊ฒฝ์šฐ ์˜ˆ์™ธ์ฒ˜๋ฆฌ. private var jpegCallback = PictureCallback { bytes: ByteArray?, camera: Camera? -> makeFolder() Toast.makeText(baseContext, "make file success", Toast.LENGTH_SHORT) showPreview()//์ด๋ฏธ์ง€ ํ”„๋ฆฌ๋ทฐ์‹คํ–‰ changeImage()//๊ฐ€์ด๋“œ ์ด๋ฏธ์ง€ ๋ณ€๊ฒฝ //TODO : ์—ฌ๊ธฐ์— preview ๋“ค์–ด๊ฐ€์•ผํ•จ setTextView()//์œ„ ๋ฌธ๊ตฌ ๋ณ€๊ฒฝ timeStamp= java.text.SimpleDateFormat("yyyyMMddHHmmss").format(Date())//ํŒŒ์ผ ์ด๋ฆ„ ๋…„์›”๋‚ ์‹œ๊ฐ„๋ถ„์ดˆ๋กœ ์„ค์ •ํ•˜๊ธฐ ์œ„ํ•œ ๋ณ€์ˆ˜ var fileName: String? = null//ํŒŒ์ผ ์ด๋ฆ„ ์„ค์ • if (count == 0) { fileName = String.format("front_$timeStamp.jpg") frontImageName = rootPath + "/" + fileName//front ์ด๋ฏธ์ง€ ํŒŒ์ผ ๊ฒฝ๋กœ + ์ด๋ฆ„ frontImageUri = Uri.fromFile(File(rootPath, fileName)) } else { fileName = String.format("side_$timeStamp.jpg") sideImageName = rootPath + "/" + fileName//side ์ด๋ฏธ์ง€ ํŒŒ์ผ ๊ฒฝ๋กœ + ์ด๋ฆ„ sideImageUri = Uri.fromFile(File(rootPath, fileName)) } var path: String = rootPath + "/" + fileName var file = File(path) try { var fos = FileOutputStream(file) fos.write(bytes) fos.flush() fos.close() } catch (e: Exception) { e.printStackTrace() } /* var intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) var uri = Uri.parse("file://" + path) intent.data = uri sendBroadcast(intent)*/ count++ if (count == 2) { sideImage = bytes count = 0 goConfirmActivity() } else { frontImage = bytes camera?.startPreview() } } private fun showPreview(){ image_preview.setImageURI(frontImageUri) } //TODO : ์ „์— ์ฐ์€ ์ด๋ฏธ์ง€๊ฐ€ ์˜ฌ๋ผ์™€์•ผ ํ•œ๋‹ค. override fun surfaceChanged(p0: SurfaceHolder?, p1: Int, p2: Int, p3: Int) { if (previewing) { camera?.stopPreview() previewing = false } if (camera != null) { try { camera?.setPreviewDisplay(surfaceHolder) camera?.startPreview() previewing = true } catch (e: IOException) { e.printStackTrace() } } } override fun surfaceCreated(holder: SurfaceHolder) { camera = Camera.open() camera!!.setDisplayOrientation(90) try{ var width:Int?=0 var height:Int?=0 var rotation=90 val parameters=camera?.parameters width=640 height=480 parameters?.setPictureSize(width,height) parameters?.setRotation(rotation) camera?.parameters=parameters }catch (e:IOException){ camera?.release() camera=null } } override fun surfaceDestroyed(holder: SurfaceHolder) { camera?.stopPreview() camera?.release() camera = null previewing = false } private fun gobackHomeActivity() { var homeIntent = Intent(this, ManagementActivity::class.java) startActivity(homeIntent) finish() } override fun onDestroy() { super.onDestroy() } override fun onBackPressed() { super.onBackPressed() gobackHomeActivity() } internal inner class LearnGesture : GestureDetector.SimpleOnGestureListener() { override fun onFling(event1: MotionEvent, event2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { if (event2.x < event1.x || event1.x == event2.x) { val intent = Intent(this@CameraActivity, ManagementActivity::class.java) startActivity(intent) overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_left) finish() } return true } }//์–ด๋–ป๊ฒŒ ๋ฐ€์–ด์„œ ๋‹ค๋ฅธ ์•กํ‹ฐ๋น„ํ‹ฐ๋กœ ๊ฐˆ๊ฒƒ์ธ์ง€ ๊ฒฐ์ • }
mit
836f007a65b895c1970233a5e618de7b
33.493724
117
0.637753
4.138052
false
false
false
false
droibit/chopsticks
chopstick-resource/src/main/kotlin/com/github/droibit/chopstick/resource/ChopstickResource.kt
1
5715
package com.github.droibit.chopstick.resource import android.app.Activity import android.app.Fragment import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.view.View import androidx.annotation.ArrayRes import androidx.annotation.BoolRes import androidx.annotation.ColorRes import androidx.annotation.DimenRes import androidx.annotation.DrawableRes import androidx.annotation.IntegerRes import androidx.annotation.StringRes import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView.ViewHolder import kotlin.LazyThreadSafetyMode.NONE import androidx.fragment.app.Fragment as SupportFragment fun Activity.bindDrawable(@DrawableRes resId: Int): Lazy<Drawable> = lazy(NONE) { requireNotNull(ContextCompat.getDrawable(this, resId)) } fun SupportFragment.bindDrawable(@DrawableRes resId: Int): Lazy<Drawable> = lazy(NONE) { requireNotNull(ContextCompat.getDrawable(requireContext(), resId)) } fun Fragment.bindDrawable(@DrawableRes resId: Int): Lazy<Drawable> = lazy(NONE) { requireNotNull( ContextCompat.getDrawable(if (isAtLeastM()) context!! else activity!!, resId) ) } fun View.bindDrawable(@DrawableRes resId: Int): Lazy<Drawable> = lazy(NONE) { requireNotNull(ContextCompat.getDrawable(context, resId)) } fun ViewHolder.bindDrawable(@DrawableRes resId: Int): Lazy<Drawable> = lazy(NONE) { requireNotNull(ContextCompat.getDrawable(context, resId)) } fun Activity.bindString(@StringRes resId: Int) = lazy(NONE) { getString(resId) } fun SupportFragment.bindString(@StringRes resId: Int) = lazy(NONE) { getString(resId) } fun Fragment.bindString(@StringRes resId: Int): Lazy<String> = lazy(NONE) { getString(resId) } fun View.bindString(@StringRes resId: Int) = lazy(NONE) { context.getString(resId) } fun ViewHolder.bindString(@StringRes resId: Int) = lazy(NONE) { context.getString(resId) } fun Activity.bindColor(@ColorRes resId: Int) = lazy(NONE) { ContextCompat.getColor(this, resId) } fun SupportFragment.bindColor(@ColorRes resId: Int) = lazy(NONE) { ContextCompat.getColor(requireContext(), resId) } fun Fragment.bindColor(@ColorRes resId: Int) = lazy(NONE) { ContextCompat.getColor(if (isAtLeastM()) context!! else activity!!, resId) } fun View.bindColor(@ColorRes resId: Int) = lazy(NONE) { ContextCompat.getColor(context, resId) } fun ViewHolder.bindColor(@ColorRes resId: Int) = lazy(NONE) { ContextCompat.getColor(context, resId) } fun Activity.bindBoolean(@BoolRes resId: Int) = lazy(NONE) { resources.getBoolean(resId) } fun SupportFragment.bindBoolean(@BoolRes resId: Int) = lazy(NONE) { resources.getBoolean(resId) } fun Fragment.bindBoolean(@BoolRes resId: Int) = lazy(NONE) { resources.getBoolean(resId) } fun View.bindBoolean(@BoolRes resId: Int) = lazy(NONE) { context.resources.getBoolean(resId) } fun ViewHolder.bindBoolean(@BoolRes resId: Int) = lazy(NONE) { context.resources.getBoolean(resId) } fun Activity.bindInt(@IntegerRes resId: Int) = lazy(NONE) { resources.getInteger(resId) } fun SupportFragment.bindInt(@IntegerRes resId: Int) = lazy(NONE) { resources.getInteger(resId) } fun Fragment.bindInt(@IntegerRes resId: Int) = lazy(NONE) { resources.getInteger(resId) } fun View.bindInt(@IntegerRes resId: Int) = lazy(NONE) { resources.getInteger(resId) } fun ViewHolder.bindInt(@IntegerRes resId: Int) = lazy(NONE) { context.resources.getInteger(resId) } fun Activity.bindStringArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getStringArray(resId) } fun SupportFragment.bindStringArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getStringArray(resId) } fun Fragment.bindStringArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getStringArray(resId) } fun View.bindStringArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getStringArray(resId) } fun ViewHolder.bindStringArray(@ArrayRes resId: Int) = lazy(NONE) { context.resources.getStringArray(resId) } fun Activity.bindIntArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getIntArray(resId) } fun SupportFragment.bindIntArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getIntArray(resId) } fun Fragment.bindIntArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getIntArray(resId) } fun View.bindIntArray(@ArrayRes resId: Int) = lazy(NONE) { resources.getIntArray(resId) } fun ViewHolder.bindIntArray(@ArrayRes resId: Int) = lazy(NONE) { context.resources.getIntArray(resId) } fun Activity.bindDimension(@DimenRes resId: Int) = lazy(NONE) { resources.getDimension(resId) } fun SupportFragment.bindDimension(@DimenRes resId: Int) = lazy(NONE) { resources.getDimension(resId) } fun Fragment.bindDimension(@DimenRes resId: Int) = lazy(NONE) { resources.getDimension(resId) } fun View.bindDimension(@DimenRes resId: Int) = lazy(NONE) { resources.getDimension(resId) } fun ViewHolder.bindDimension(@DimenRes resId: Int) = lazy(NONE) { context.resources.getDimension(resId) } fun Activity.bindDimensionPixel(@DimenRes resId: Int) = lazy(NONE) { resources.getDimensionPixelSize(resId) } fun SupportFragment.bindDimensionPixel(@DimenRes resId: Int) = lazy(NONE) { resources.getDimensionPixelSize(resId) } fun Fragment.bindDimensionPixel(@DimenRes resId: Int) = lazy(NONE) { resources.getDimensionPixelSize(resId) } fun View.bindDimensionPixel(@DimenRes resId: Int) = lazy(NONE) { resources.getDimensionPixelSize(resId) } fun ViewHolder.bindDimensionPixel(@DimenRes resId: Int) = lazy(NONE) { context.resources.getDimensionPixelSize(resId) } private val ViewHolder.context: Context inline get() = itemView.context private fun Fragment.isAtLeastM(): Boolean = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
apache-2.0
7c7e6774fd98d9be93b972546791c994
50.486486
100
0.768679
3.9993
false
false
false
false
angryziber/picasa-gallery
src/web/Renderer.kt
1
458
package web import javax.servlet.http.HttpServletResponse open class Renderer { open operator fun invoke(response: HttpServletResponse, lastModified: Long? = null, html: () -> String) { if (response.contentType == null) response.contentType = "text/html; charset=utf8" response.setHeader("Cache-Control", "public") if (lastModified != null) response.setDateHeader("Last-Modified", lastModified) response.writer.write(html()) } }
gpl-3.0
f7f8e32bdc3bdbe8ccef096fe882f489
29.6
107
0.720524
4.201835
false
false
false
false
Reyurnible/gitsalad-android
app/src/main/kotlin/com/hosshan/android/salad/ext/ImageExtention.kt
1
5852
package com.hosshan.android.salad.ext import android.content.ContentValues import android.content.Context import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Matrix import android.net.Uri import android.os.Environment import android.provider.MediaStore import android.util.Base64 import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.* object ImageUtil { fun photoUri(context: Context): Uri { val currentTimeMillis = System.currentTimeMillis() val today = Date(currentTimeMillis) val title = SimpleDateFormat("yyyyMMdd_HHmmss").format(today) val dirPath = dirPath(context) val fileName = "img_capture_$title.jpg" val path = dirPath + "/" + fileName val file = File(path) val values = ContentValues().apply { put(MediaStore.Images.Media.TITLE, title) put(MediaStore.Images.Media.DISPLAY_NAME, fileName) put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") put(MediaStore.Images.Media.DATA, path) put(MediaStore.Images.Media.DATE_TAKEN, currentTimeMillis) } if (file.exists()) { values.put(MediaStore.Images.Media.SIZE, file.length()) } return context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) } /** * ็”ปๅƒใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใƒ‘ใ‚นใ‚’ๅ–ๅพ—ใ™ใ‚‹ * @return */ fun dirPath(context: Context): String { var dirPath = "" var photoDir: File? = null val extStorageDir = Environment.getExternalStorageDirectory() if (extStorageDir.canWrite()) { photoDir = File(extStorageDir.path + "/" + context.packageName) } photoDir?.let { if (!it.exists()) { it.mkdirs() } if (it.canWrite()) { dirPath = it.path } } return dirPath } fun resize(bitmap: Bitmap, percent: Float): Bitmap? { if (percent < 0) { return null } return resize(bitmap, (bitmap.width * percent).toInt(), (bitmap.height * percent).toInt()) } fun resize(bitmap: Bitmap, targetWidth: Int, targetHeight: Int): Bitmap? { if (targetWidth < 0 || targetHeight < 0) { return null } val pictureWidth = bitmap.width val pictureHeight = bitmap.height val scale = Math.min(targetWidth.toFloat() / pictureWidth, targetHeight.toFloat() / pictureHeight) val matrix = Matrix() matrix.postScale(scale, scale) return Bitmap.createBitmap(bitmap, 0, 0, pictureWidth, pictureHeight, matrix, true) } fun writeImage(file: File, bitmap: Bitmap, format: Bitmap.CompressFormat = CompressFormat.JPEG) { val outputStream = FileOutputStream(file) bitmap.compress(format, 100, outputStream) outputStream.flush() outputStream.close() } @Throws(IOException::class) fun loadImage(context: Context, uri: Uri, isLandscape: Boolean = false): Bitmap { //็”ป้ขใฎๅ‘ใใ‚’็ฎก็†ใ™ใ‚‹ใ€‚ var landscape = false var bm: Bitmap val options = BitmapFactory.Options() options.inJustDecodeBounds = true context.contentResolver.openInputStream(uri)?.let { BitmapFactory.decodeStream(it, null, options) it.close() } var ow = options.outWidth var oh = options.outHeight //็”ป้ขใŒๆจชใซใชใฃใฆใ„ใŸใ‚‰ใ€‚ if (ow > oh && isLandscape) { landscape = true //็ธฆใจๆจชใ‚’้€†ใซใ™ใ‚‹ใ€‚ oh = options.outWidth ow = options.outHeight } val width = (ow * 0.6).toInt() val height = (oh * 0.6).toInt() options.inJustDecodeBounds = false options.inSampleSize = Math.max(ow / width, oh / height) val is2 = context.contentResolver.openInputStream(uri) bm = BitmapFactory.decodeStream(is2, null, options) is2.close() if (landscape) { val matrix = Matrix() matrix.setRotate(90.0f) bm = Bitmap.createBitmap(bm, 0, 0, bm.width, bm.height, matrix, false) } bm = Bitmap.createScaledBitmap(bm, width, (width * (oh.toDouble() / ow.toDouble())).toInt(), false) val offBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) val offCanvas = Canvas(offBitmap) offCanvas.drawBitmap(bm, 0f, ((height - bm.height) / 2).toFloat(), null) bm = offBitmap return bm } fun encodeImageBase64(bitmap: Bitmap): String { val outputStream = ByteArrayOutputStream() bitmap.compress(CompressFormat.PNG, 100, outputStream) return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT) } fun decodeImageBase64(bitmapString: String): Bitmap { val bytes = Base64.decode(bitmapString.toByteArray(), Base64.DEFAULT) return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } } fun Bitmap.resize(percent: Float): Bitmap? = ImageUtil.resize(this, percent) fun Bitmap.resize(width: Int, height: Int): Bitmap? = ImageUtil.resize(this, width, height) fun Bitmap.write(file: File, format: Bitmap.CompressFormat = CompressFormat.JPEG) { ImageUtil.writeImage(file, this, format) } fun Uri.loadImage(context: Context, isLandscape: Boolean = false): Bitmap = ImageUtil.loadImage(context, this, isLandscape) fun Bitmap.encodeToBase64(): String = ImageUtil.encodeImageBase64(this) fun String.decodeFromBase64(): Bitmap = ImageUtil.decodeImageBase64(this)
mit
2cc54951a140bbbfaac38934edffcfde
34.751553
107
0.643329
4.260548
false
false
false
false
mg6maciej/fluffy-octo-rotary-phone
app/src/main/java/pl/mg6/likeornot/grid/LikesRepository.kt
1
1251
package pl.mg6.likeornot.grid import android.content.Context import io.reactivex.Completable import io.reactivex.Single import pl.mg6.likeornot.grid.entity.Likable import pl.mg6.likeornot.grid.entity.Status import java.io.File typealias LikableIdToStatus = Map<String, Status> fun loadLocalLikes(context: Context): Single<LikableIdToStatus> { return Single.fromCallable { readLikesFile(context) } .map(::toUuidToStatusMap) .onErrorReturnItem(emptyMap()) } private fun readLikesFile(context: Context) = likesFile(context).readLines() private fun toUuidToStatusMap(lines: List<String>) = lines.associateBy(::extractUuid, ::extractStatus) private fun extractUuid(line: String) = line.substringBefore(' ') private fun extractStatus(line: String) = Status.valueOf(line.substringAfter(' ')) fun saveLocalLike(context: Context, likable: Likable, status: Status): Completable { return Completable.fromCallable { appendStatusToLikesFile(context, likable, status) } } private fun appendStatusToLikesFile(context: Context, likable: Likable, status: Status) { val line = "${likable.uuid} ${status}\n" likesFile(context).appendText(line) } private fun likesFile(context: Context) = File(context.filesDir, "likes")
apache-2.0
4307f7f4b8d684ceedd38c04d226fb35
34.742857
102
0.765787
3.690265
false
false
false
false
outadoc/Twistoast-android
keolisprovider/src/test/java/fr/outadev/android/transport/timeo/TimeStepDefinitions.kt
1
2169
/* * Twistoast - TimeStepDefinitions.kt * Copyright (C) 2013-2016 Baptiste Candellier * * Twistoast is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Twistoast is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package fr.outadev.android.transport.timeo import cucumber.api.CucumberOptions import cucumber.api.java.en.Given import cucumber.api.java.en.Then import cucumber.api.java.en.When import fr.outadev.android.transport.getNextDateForTime import org.joda.time.LocalTime import org.junit.Assert /** * Created by outadoc on 27/08/16. */ @CucumberOptions class TimeStepDefinitions { var localTime: String? = null var busTime: String? = null @Given("^it's ([0-9]{2}:[0-9]{2})$") fun itsTime(time: String) { localTime = time } @When("^a bus is coming at ([0-9]{2}:[0-9]{2})$") fun aBusIsComingAtTime(time: String) { busTime = time } @Then("^the bus is coming in (\\d+) minutes$") fun theBusIsComingInNMinutes(min: Long) { Assert.assertEquals(min, getMinuteDiffBetweenTwoStringTimes(busTime!!, localTime!!)) } @Then("^the bus is late by (\\d+) minutes$") fun theBusIsLateByNMinutes(min: Long) { Assert.assertEquals(-min, getMinuteDiffBetweenTwoStringTimes(busTime!!, localTime!!)) } fun getMinuteDiffBetweenTwoStringTimes(busTime: String, localTime: String): Long { val localArray = localTime.split(":") val localDate = LocalTime(localArray[0].toInt(), localArray[1].toInt()).toDateTimeToday() val busDate = busTime.getNextDateForTime(localDate) return (busDate.millis - localDate.millis) / 1000 / 60 } }
gpl-3.0
8bb2baa406ebe7ce29ad3998a2d0bd4b
31.878788
97
0.701706
3.746114
false
false
false
false
kidchenko/playground
kotlin-koans/Introduction/Nothing type/test/Tests.kt
1
499
import org.junit.Assert import org.junit.Test class Test { fun testAge(age: Int) { val e: IllegalArgumentException? = try { checkAge(age) null } catch (e: IllegalArgumentException) { e } Assert.assertNotNull( "Expected IllegalArgumentException for 'checkAge($age)'", e) } @Test(timeout = 1000) fun testNegative() = testAge(-10) @Test(timeout = 1000) fun testLargeNumber() = testAge(200) }
mit
294aa5119c5804aed0d7b0b101d7220f
22.809524
76
0.577154
4.158333
false
true
false
false
nithia/xkotlin
exercises/robot-name/src/example/kotlin/Robot.kt
1
615
import java.util.* class Robot { companion object { private val alphabet = ('A'..'Z').toList() private val numbers = (0..9).toList() private val random = Random() private fun <T : Any> random(list: List<T>): Sequence<T> = generateSequence { list[random.nextInt(list.size)] } } var name: String = makeName() private set fun reset() { name = makeName() } private fun makeName() = prefix() + suffix() private fun prefix() = random(alphabet).take(2).joinToString("") private fun suffix() = random(numbers).take(3).joinToString("") }
mit
7be677e254b08505661e9f3c26762aa7
25.73913
119
0.593496
4.019608
false
false
false
false
openhab/openhab.android
mobile/src/foss/java/org/openhab/habdroid/ui/MapViewHelper.kt
1
9104
/* * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.ui import android.location.Location import android.os.Handler import android.os.Looper import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.FrameLayout import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import java.util.Locale import kotlin.math.max import kotlin.math.min import org.openhab.habdroid.R import org.openhab.habdroid.core.connection.Connection import org.openhab.habdroid.model.Item import org.openhab.habdroid.model.Widget import org.openhab.habdroid.util.dpToPixel import org.openhab.habdroid.util.isDarkModeActive import org.osmdroid.config.Configuration import org.osmdroid.events.MapEventsReceiver import org.osmdroid.tileprovider.tilesource.TileSourceFactory import org.osmdroid.util.BoundingBox import org.osmdroid.util.GeoPoint import org.osmdroid.views.CustomZoomButtonsController.Visibility import org.osmdroid.views.MapView import org.osmdroid.views.overlay.CopyrightOverlay import org.osmdroid.views.overlay.MapEventsOverlay import org.osmdroid.views.overlay.Marker import org.osmdroid.views.overlay.TilesOverlay object MapViewHelper { internal val TAG = MapViewHelper::class.java.simpleName fun createViewHolder( inflater: LayoutInflater, parent: ViewGroup, connection: Connection, colorMapper: WidgetAdapter.ColorMapper ): WidgetAdapter.ViewHolder { val context = inflater.context Configuration.getInstance().load(context, PreferenceManager.getDefaultSharedPreferences(context)) return OsmViewHolder(inflater, parent, connection, colorMapper) } private class OsmViewHolder( inflater: LayoutInflater, parent: ViewGroup, connection: Connection, colorMapper: WidgetAdapter.ColorMapper ) : WidgetAdapter.AbstractMapViewHolder(inflater, parent, connection, colorMapper), Marker.OnMarkerDragListener { private val mapView = baseMapView as MapView private val handler: Handler = Handler(Looper.getMainLooper()) override val dialogManager = WidgetAdapter.DialogManager() init { with(mapView) { setTileSource(TileSourceFactory.MAPNIK) isVerticalMapRepetitionEnabled = false zoomController.setVisibility(Visibility.NEVER) setMultiTouchControls(false) setDestroyMode(false) overlays.add(CopyrightOverlay(itemView.context)) overlays.add(MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { openPopup() return true } override fun longPressHelper(p: GeoPoint): Boolean { return false } })) mapOverlay.setColorFilter(if (context.isDarkModeActive()) TilesOverlay.INVERT_COLORS else null) } } override fun bindAfterDataSaverCheck(widget: Widget) { handler.post { mapView.applyPositionAndLabel(boundItem, labelView.text, 15.0f, allowDrag = false, allowScroll = false, markerDragListener = this) } } override fun onStart() { mapView.onResume() } override fun onStop() { mapView.onPause() } override fun onMarkerDragStart(marker: Marker) { // no-op, we're interested in drag end only } override fun onMarkerDrag(marker: Marker) { // no-op, we're interested in drag end only } override fun onMarkerDragEnd(marker: Marker) { val newState = String.format(Locale.US, "%f,%f", marker.position.latitude, marker.position.longitude) val item = if (marker.id == boundItem?.name) { boundItem } else { boundItem?.members?.firstOrNull { i -> i.name == marker.id } } connection.httpClient.sendItemCommand(item, newState) } override fun openPopup() { val mapView = MapView(itemView.context) val dialog = AlertDialog.Builder(itemView.context) .setView(mapView) .setCancelable(true) .setNegativeButton(R.string.close, null) .create() dialogManager.manage(dialog) with(dialog) { setOnDismissListener { mapView.onPause() } setCanceledOnTouchOutside(true) show() window?.setLayout(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT) } with(mapView) { zoomController.setVisibility(Visibility.SHOW_AND_FADEOUT) setMultiTouchControls(true) isVerticalMapRepetitionEnabled = false overlays.add(CopyrightOverlay(itemView.context)) mapOverlay.setColorFilter(if (context.isDarkModeActive()) TilesOverlay.INVERT_COLORS else null) onResume() } handler.post { mapView.applyPositionAndLabel(boundItem, labelView.text, 16.0f, allowDrag = true, allowScroll = true, markerDragListener = this@OsmViewHolder) } } } } fun MapView.applyPositionAndLabel( item: Item?, itemLabel: CharSequence?, zoomLevel: Float, allowDrag: Boolean, allowScroll: Boolean, markerDragListener: Marker.OnMarkerDragListener ) { if (item == null) { return } val canDragMarker = allowDrag && !item.readOnly if (item.members.isNotEmpty()) { val positions = ArrayList<GeoPoint>() for (member in item.members) { val position = member.state?.asLocation?.toGeoPoint() if (position != null) { setMarker(position, member, member.label, canDragMarker, markerDragListener) positions.add(position) } } if (positions.isNotEmpty()) { var north = -90.0 var south = 90.0 var west = 180.0 var east = -180.0 for (position in positions) { north = max(position.latitude, north) south = min(position.latitude, south) west = min(position.longitude, west) east = max(position.longitude, east) } Log.d(MapViewHelper.TAG, "North $north, south $south, west $west, east $east") val boundingBox = BoundingBox(north, east, south, west) val extraPixel = context.resources.dpToPixel(24f).toInt() try { zoomToBoundingBox(boundingBox, false, extraPixel) } catch (e: Exception) { Log.d(MapViewHelper.TAG, "Error applying markers", e) } if (!allowScroll) { setScrollableAreaLimitLongitude(west, east, extraPixel) setScrollableAreaLimitLatitude(north, south, extraPixel) } } } else { val position = item.state?.asLocation?.toGeoPoint() if (position != null) { setMarker(position, item, itemLabel, canDragMarker, markerDragListener) controller.setZoom(zoomLevel.toDouble()) controller.setCenter(position) if (!allowScroll) { setScrollableAreaLimitLatitude(position.latitude, position.latitude, 0) setScrollableAreaLimitLongitude(position.longitude, position.longitude, 0) } } else if (!allowScroll) { setScrollableAreaLimitLatitude(0.0, 0.0, 0) setScrollableAreaLimitLongitude(0.0, 0.0, 0) } } } fun MapView.setMarker( pos: GeoPoint, item: Item, label: CharSequence?, canDrag: Boolean, onMarkerDragListener: Marker.OnMarkerDragListener ) { val marker = Marker(this).apply { setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) isDraggable = canDrag position = pos title = label?.toString() id = item.name setOnMarkerDragListener(onMarkerDragListener) icon = ContextCompat.getDrawable(context, R.drawable.ic_location_on_red_24dp) } overlays.add(marker) } fun Location.toGeoPoint(): GeoPoint { return GeoPoint(this) } fun Location.toMapsUrl(): String { return "https://www.openstreetmap.org/#map=16/$latitude/$longitude" }
epl-1.0
89c859766e9460f1ff032d89010e0666
34.98419
111
0.629284
4.773991
false
false
false
false
weiweiwitch/third-lab
src/main/kotlin/com/ariane/thirdlab/domains/Summary.kt
1
374
package com.ariane.thirdlab.domains import javax.persistence.* @Entity class Summary { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) var id: Long = 0L @Version @Column(nullable = false, name = "v") var v: Long = 0 @Column(nullable = false, length = 256000) var summary: String = "" }
mit
db66c9779aad23d31aab474f9292d81d
17.75
55
0.641711
3.596154
false
false
false
false
mehulsbhatt/emv-bertlv
src/main/java/io/github/binaryfoo/bit/EmvBit.kt
1
1431
package io.github.binaryfoo.bit import io.github.binaryfoo.tlv.ISOUtil import org.apache.commons.lang.builder.EqualsBuilder import org.apache.commons.lang.builder.HashCodeBuilder import java.util.TreeSet /** * EMV specs seem to follow the convention: bytes are numbered left to right, bits are numbered byte right to left, * both start at 1. */ public data class EmvBit(public val byteNumber: Int, public val bitNumber: Int, public val set: Boolean) : Comparable<EmvBit> { public val value: String get() = if (set) "1" else "0" override fun toString(): String = toString(true) public fun toString(includeComma: Boolean, includeValue: Boolean = true): String { val separator = if (includeComma) "," else "" if (includeValue) { return "Byte ${byteNumber}${separator} Bit ${bitNumber} = ${value}" } return "Byte ${byteNumber}${separator} Bit ${bitNumber}" } override fun compareTo(other: EmvBit): Int { val byteOrder = byteNumber.compareTo(other.byteNumber) if (byteOrder != 0) { return byteOrder } val bitOrder = other.bitNumber.compareTo(bitNumber) if (bitOrder != 0) { return bitOrder } return set.compareTo(other.set) } } /** * Label set bits (those = 1) in hex. */ public fun labelFor(hex: String): String { return fromHex(hex).toString(includeValue = false) }
mit
a31b8b19eccffb99f4cc211af3cee1c8
30.8
127
0.656883
3.867568
false
false
false
false
ekager/focus-android
app/src/main/java/org/mozilla/focus/exceptions/ExceptionsListFragment.kt
1
10353
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.exceptions import android.support.v4.app.Fragment import android.content.Context import android.graphics.Color import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.support.v7.widget.helper.ItemTouchHelper.SimpleCallback import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import android.widget.TextView import kotlinx.android.synthetic.main.fragment_exceptions_domains.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.launch import org.mozilla.focus.R import org.mozilla.focus.autocomplete.AutocompleteDomainFormatter import org.mozilla.focus.settings.BaseSettingsFragment import org.mozilla.focus.telemetry.TelemetryWrapper import java.util.Collections import org.mozilla.focus.utils.ViewUtils import kotlin.coroutines.CoroutineContext typealias DomainFormatter = (String) -> String /** * Fragment showing settings UI listing all exception domains. */ open class ExceptionsListFragment : Fragment(), CoroutineScope { private var job = Job() override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main /** * ItemTouchHelper for reordering items in the domain list. */ val itemTouchHelper: ItemTouchHelper = ItemTouchHelper( object : SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val from = viewHolder.adapterPosition val to = target.adapterPosition (recyclerView.adapter as DomainListAdapter).move(from, to) return true } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {} override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) { super.onSelectedChanged(viewHolder, actionState) if (viewHolder is DomainViewHolder) { viewHolder.onSelected() } } override fun clearView( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder ) { super.clearView(recyclerView, viewHolder) if (viewHolder is DomainViewHolder) { viewHolder.onCleared() } } }) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } /** * In selection mode the user can select and remove items. In non-selection mode the list can * be reordered by the user. */ open fun isSelectionMode() = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View = inflater.inflate(R.layout.fragment_exceptions_domains, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { exceptionList.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) exceptionList.adapter = DomainListAdapter() exceptionList.setHasFixedSize(true) if (!isSelectionMode()) { itemTouchHelper.attachToRecyclerView(exceptionList) } removeAllExceptions.setOnClickListener { val domains = ExceptionDomains.load(context!!) TelemetryWrapper.removeAllExceptionDomains(domains.size) ExceptionDomains.remove(context!!, domains) fragmentManager!!.popBackStack() } } override fun onResume() { super.onResume() job = Job() (activity as BaseSettingsFragment.ActionBarUpdater).apply { updateTitle(R.string.preference_exceptions) updateIcon(R.drawable.ic_back) } (exceptionList.adapter as DomainListAdapter).refresh(activity!!) { if ((exceptionList.adapter as DomainListAdapter).itemCount == 0) { fragmentManager!!.popBackStack() } activity?.invalidateOptionsMenu() } } override fun onStop() { job.cancel() super.onStop() } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { inflater?.inflate(R.menu.menu_exceptions_list, menu) } override fun onPrepareOptionsMenu(menu: Menu?) { val removeItem = menu?.findItem(R.id.remove) removeItem?.let { it.isVisible = isSelectionMode() || exceptionList.adapter!!.itemCount > 0 val isEnabled = !isSelectionMode() || (exceptionList.adapter as DomainListAdapter).selection().isNotEmpty() ViewUtils.setMenuItemEnabled(it, isEnabled) } } override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) { R.id.remove -> { fragmentManager!! .beginTransaction() .replace(R.id.container, ExceptionsRemoveFragment()) .addToBackStack(null) .commit() true } else -> super.onOptionsItemSelected(item) } /** * Adapter implementation for the list of exception domains. */ inner class DomainListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val domains: MutableList<String> = mutableListOf() private val selectedDomains: MutableList<String> = mutableListOf() fun refresh(context: Context, body: (() -> Unit)? = null) { [email protected](Main) { val updatedDomains = async { ExceptionDomains.load(context) }.await() domains.clear() domains.addAll(updatedDomains) notifyDataSetChanged() body?.invoke() } } override fun getItemViewType(position: Int) = DomainViewHolder.LAYOUT_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) { DomainViewHolder.LAYOUT_ID -> DomainViewHolder( LayoutInflater.from(parent.context).inflate(viewType, parent, false), { AutocompleteDomainFormatter.format(it) }) else -> throw IllegalArgumentException("Unknown view type: $viewType") } override fun getItemCount(): Int = domains.size override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is DomainViewHolder) { holder.bind( domains[position], isSelectionMode(), selectedDomains, itemTouchHelper, this@ExceptionsListFragment ) } } override fun onViewRecycled(holder: RecyclerView.ViewHolder) { if (holder is DomainViewHolder) { holder.checkBoxView.setOnCheckedChangeListener(null) } } fun selection(): List<String> = selectedDomains fun move(from: Int, to: Int) { Collections.swap(domains, from, to) notifyItemMoved(from, to) launch(IO) { ExceptionDomains.save(activity!!.applicationContext, domains) } } } /** * ViewHolder implementation for a domain item in the list. */ private class DomainViewHolder( itemView: View, val domainFormatter: DomainFormatter? = null ) : RecyclerView.ViewHolder(itemView) { val domainView: TextView = itemView.findViewById(R.id.domainView) val checkBoxView: CheckBox = itemView.findViewById(R.id.checkbox) val handleView: View = itemView.findViewById(R.id.handleView) companion object { val LAYOUT_ID = R.layout.item_custom_domain } fun bind( domain: String, isSelectionMode: Boolean, selectedDomains: MutableList<String>, itemTouchHelper: ItemTouchHelper, fragment: ExceptionsListFragment ) { domainView.text = domainFormatter?.invoke(domain) ?: domain checkBoxView.visibility = if (isSelectionMode) View.VISIBLE else View.GONE checkBoxView.isChecked = selectedDomains.contains(domain) checkBoxView.setOnCheckedChangeListener { _: CompoundButton, isChecked: Boolean -> if (isChecked) { selectedDomains.add(domain) } else { selectedDomains.remove(domain) } fragment.activity?.invalidateOptionsMenu() } handleView.visibility = if (isSelectionMode) View.GONE else View.VISIBLE handleView.setOnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { itemTouchHelper.startDrag(this) } false } if (isSelectionMode) { itemView.setOnClickListener { checkBoxView.isChecked = !checkBoxView.isChecked } } } fun onSelected() { itemView.setBackgroundColor(Color.DKGRAY) } fun onCleared() { itemView.setBackgroundColor(0) } } }
mpl-2.0
9055ad29f8e17162a5df66b80e8c0f69
33.858586
107
0.627065
5.403445
false
false
false
false
SerCeMan/franky
franky-intellij/src/test/kotlin/me/serce/franky/ui/flame/FrameComponentTest.kt
1
2228
package me.serce.franky.ui.flame import com.google.protobuf.CodedInputStream import com.intellij.testFramework.IdeaTestCase import me.serce.franky.Protocol import java.awt.AWTEvent import java.awt.Dimension import java.awt.Toolkit import java.io.FileInputStream import javax.swing.JFrame import javax.swing.JScrollPane import javax.swing.ScrollPaneConstants import javax.swing.SwingUtilities /** * Created by Sergey.Tselovalnikov on 7/15/16. */ class FrameComponentTest : IdeaTestCase() { fun testEmpty() { } fun itestComponent() { try { SwingUtilities.invokeLater { val result = Protocol.Response.parseFrom(CodedInputStream.newInstance(FileInputStream("/home/serce/tmp/ResultData"))) val profInfo = result.profInfo val samples = profInfo.samplesList val methods: Map<Long, Protocol.MethodInfo> = profInfo.methodInfosList.associateBy({ it.jMethodId }, { it }) val tree = FlameTree(samples) val panel = JFrame().apply { defaultCloseOperation = JFrame.EXIT_ON_CLOSE pack() size = Dimension(800, 600) contentPane.apply { add(JScrollPane(FlameComponent(tree, { methods[it] }).apply { size = Dimension(800, 600) methodInfoSubject.subscribe { println("CLICK $it") } }).apply { verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS verticalScrollBar.unitIncrement = 16 }) } isVisible = true repaint() } } val eventQueue = Toolkit.getDefaultToolkit().systemEventQueue while (true) { val event = eventQueue.nextEvent eventQueue.javaClass.getDeclaredMethod("dispatchEvent", AWTEvent::class.java).invoke(eventQueue, event) } } catch (e: Exception) { println(e.message) } } }
apache-2.0
168ac7df8ccf80ac58d1d9fe1078cbe5
36.15
133
0.561939
5.279621
false
true
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/registry/type/potion/PotionEffectTypeRegistry.kt
1
2195
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.registry.type.potion import org.lanternpowered.api.effect.potion.PotionEffectType import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.api.key.resolveNamespacedKey import org.lanternpowered.server.effect.potion.LanternPotionEffectType import org.lanternpowered.server.game.registry.InternalRegistries import org.lanternpowered.server.registry.internalCatalogTypeRegistry val PotionEffectTypeRegistry = internalCatalogTypeRegistry<PotionEffectType> { val internalIds = mutableMapOf<NamespacedKey, Int>() InternalRegistries.visitElements("mob_effect") { id, element -> internalIds[resolveNamespacedKey(id)] = element.asJsonObject["internal_id"].asInt } fun register(id: String): LanternPotionEffectType { val key = minecraftKey(id) val internalId = internalIds[key]!! return register(internalId, LanternPotionEffectType(key)) } register("speed") register("slowness") register("haste") register("mining_fatigue") register("strength") register("instant_health").instant() register("instant_damage").instant() register("jump_boost") register("nausea") register("regeneration") register("resistance") register("fire_resistance") register("water_breathing") register("invisibility") register("blindness") register("night_vision") register("hunger") register("weakness") register("poison") register("wither") register("health_boost") register("absorption") register("saturation") register("glowing") register("levitation") register("luck") register("unluck") register("bad_omen") register("conduit_power") register("dolphins_grace") register("hero_of_the_village") register("slow_falling") }
mit
83dd0604c974b99a7d862a27fe5511f4
32.257576
89
0.723918
4.278752
false
false
false
false
cempo/SimpleTodoList
app/src/main/java/com/makeevapps/simpletodolist/utils/DeviceInfo.kt
1
1280
package com.makeevapps.simpletodolist.utils import android.content.Context import android.os.Build import android.provider.Settings import android.text.TextUtils class DeviceInfo(val context: Context) { val sdkVersion: Int get() = Build.VERSION.SDK_INT val androidVersion: String get() = Build.VERSION.RELEASE val deviceId: String get() = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) val deviceManufacturer: String get() { val manufacturer = Build.MANUFACTURER return capitalize(manufacturer) } val deviceModel: String get() { val manufacturer = Build.MANUFACTURER val model = Build.MODEL if (model != manufacturer && model.startsWith(manufacturer)) { return model.substring(manufacturer.length + 1, model.length) } else { return model } } private fun capitalize(s: String): String { if (TextUtils.isEmpty(s)) { return "" } val first = s[0] if (Character.isUpperCase(first)) { return s } else { return Character.toUpperCase(first) + s.substring(1) } } }
mit
b9449a11e40f2051220e4ffc6edf5ea5
26.234043
94
0.597656
4.776119
false
false
false
false
i7c/cfm
server/mbservice/src/main/kotlin/org/rliz/mbs/artist/data/ArtistCreditName.kt
1
278
package org.rliz.mbs.artist.data import java.io.Serializable class ArtistCreditName : Serializable { var artistCredit: ArtistCredit? = null var position: Int? = null var artist: Artist? = null var name: String? = null var joinPhrase: String? = null }
gpl-3.0
3f46f99f964d0492d595852fa4dcd75f
16.375
42
0.690647
3.808219
false
false
false
false
Finnerale/FileBase
src/main/kotlin/de/leopoldluley/filebase/view/LoadingView.kt
1
1225
package de.leopoldluley.filebase.view import de.leopoldluley.filebase.Setup import javafx.geometry.Pos import tornadofx.* import java.nio.file.Files import java.nio.file.Paths class LoadingView : View() { override val root = vbox { alignment = Pos.CENTER label("FileBase").style { fontSize = 40.0.px } label(messages["headline"]) { style { fontSize = 24.0.px } } } override fun onDock() { super.onDock() runAsync { Thread.sleep(1000) } ui { if (Files.exists(Paths.get("./portable.info"))) { Setup.isPortable = true replaceWith(MainView::class) } else if (Files.exists(Paths.get(System.getProperty("user.home")).resolve(".filebase/installed.info"))) { Setup.isPortable = false val path = Paths.get(Setup.rootBasePath).resolve("installed.info") val directory = String(Files.readAllBytes(path)) Setup.rootPath = directory replaceWith(MainView::class) } else { replaceWith(InitView::class) } } } }
mit
c7d34b20394fbd6a0f4a062da97a7ba0
28.190476
118
0.54449
4.503676
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/fragments/feed/ScrollRef.kt
1
399
package com.pr0gramm.app.ui.fragments.feed import com.pr0gramm.app.feed.Feed import com.pr0gramm.app.ui.fragments.CommentRef data class ScrollRef(val ref: CommentRef, val feed: Feed? = null, val autoOpen: Boolean = false, val smoothScroll: Boolean = false, val keepScroll: Boolean = false) { val itemId: Long get() = ref.itemId }
mit
1d5cb4f737c79de041bbcd2631ac8e32
32.333333
65
0.636591
3.764151
false
false
false
false
jingcai-wei/android-news
app/src/main/java/com/sky/android/news/ui/main/story/StoryListViewModel.kt
1
3737
/* * Copyright (c) 2021 The sky Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sky.android.news.ui.main.story import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.sky.android.news.data.model.BaseViewType import com.sky.android.news.data.model.NodeItemModel import com.sky.android.news.data.model.TopStoryListModel import com.sky.android.news.data.source.IStorySource import com.sky.android.news.ext.doFailure import com.sky.android.news.ext.doSuccess import com.sky.android.news.ui.base.NewsViewModel import com.sky.android.news.ui.helper.PageHelper import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onCompletion import kotlinx.coroutines.flow.onStart import javax.inject.Inject /** * Created by sky on 2021-01-25. */ @HiltViewModel class StoryListViewModel @Inject constructor( application: Application, private val source: IStorySource ) : NewsViewModel(application) { private val mLoading = MutableLiveData<Boolean>() val loading: LiveData<Boolean> = mLoading private val mFailure = MutableLiveData<String>() val failure: LiveData<String> = mFailure private val mStoryList = MutableLiveData<List<BaseViewType>>() val storyList: LiveData<List<BaseViewType>> = mStoryList private val mPageHelper = PageHelper<BaseViewType>() private var mDate = "" init { mPageHelper.notFixed = true } fun loadLastStories() { launchOnUI { source.getLatestStories() .onStart { mLoading.value = true } .onCompletion { mLoading.value = false } .collect { it.doFailure { mFailure.value = "ๅŠ ่ฝฝๅˆ—่กจไฟกๆฏๅคฑ่ดฅ" }.doSuccess { // ไฟๅญ˜ๆ—ถ้—ด mDate = it.date // ่ฎพ็ฝฎๆ•ฐๆฎ mPageHelper.setData(listOf(TopStoryListModel(it.topStories))) mPageHelper.appendData(listOf(NodeItemModel(it.date, "ไปŠๆ—ฅ็ƒญ้—ป"))) mPageHelper.appendData(it.stories) mStoryList.value = mPageHelper.getData() } } } } fun loadMoreStories() { launchOnUI { source.getLatestStories() .onStart { mLoading.value = true } .onCompletion { mLoading.value = false } .collect { it.doFailure { mFailure.value = "ๅŠ ่ฝฝๅˆ—่กจไฟกๆฏๅคฑ่ดฅ" }.doSuccess { // ไฟๅญ˜ๆ—ถ้—ด mDate = it.date // ่ฟฝๅŠ ๆ•ฐๆฎ mPageHelper.appendData(listOf(NodeItemModel(it.date))) mPageHelper.appendData(it.stories) mStoryList.value = mPageHelper.getData() } } } } }
apache-2.0
2b1070a2f6d0a6b57cac39bfe9baa260
33.261682
90
0.593997
4.70475
false
false
false
false
FHannes/intellij-community
platform/configuration-store-impl/src/ExportSettingsAction.kt
6
11761
/* * 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 com.intellij.configurationStore import com.intellij.AbstractBundle import com.intellij.CommonBundle import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ImportSettingsFilenameFilter import com.intellij.ide.actions.ShowFilePathAction import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManager import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.application.impl.ApplicationImpl import com.intellij.openapi.components.* import com.intellij.openapi.components.impl.ServiceManagerImpl import com.intellij.openapi.components.impl.stores.StoreUtil import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.options.OptionsBundle import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.PlatformUtils import com.intellij.util.ReflectionUtil import com.intellij.util.containers.putValue import com.intellij.util.io.* import gnu.trove.THashMap import gnu.trove.THashSet import java.io.IOException import java.io.OutputStream import java.io.OutputStreamWriter import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream private class ExportSettingsAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent?) { ApplicationManager.getApplication().saveSettings() val dialog = ChooseComponentsToExportDialog(getExportableComponentsMap(true, true), true, IdeBundle.message("title.select.components.to.export"), IdeBundle.message( "prompt.please.check.all.components.to.export")) if (!dialog.showAndGet()) { return } val markedComponents = dialog.exportableComponents if (markedComponents.isEmpty()) { return } val exportFiles = markedComponents.mapTo(THashSet()) { it.file } val saveFile = dialog.exportFile try { if (saveFile.exists() && Messages.showOkCancelDialog( IdeBundle.message("prompt.overwrite.settings.file", saveFile.toString()), IdeBundle.message("title.file.already.exists"), Messages.getWarningIcon()) != Messages.OK) { return } exportSettings(exportFiles, saveFile.outputStream(), FileUtilRt.toSystemIndependentName(PathManager.getConfigPath())) ShowFilePathAction.showDialog(getEventProject(e), IdeBundle.message("message.settings.exported.successfully"), IdeBundle.message("title.export.successful"), saveFile.toFile(), null) } catch (e1: IOException) { Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e1.toString()), IdeBundle.message("title.error.writing.file")) } } } // not internal only to test fun exportSettings(exportFiles: Set<Path>, out: OutputStream, configPath: String) { val zipOut = MyZipOutputStream(out) try { val writtenItemRelativePaths = THashSet<String>() for (file in exportFiles) { if (file.exists()) { val relativePath = FileUtilRt.getRelativePath(configPath, file.toAbsolutePath().systemIndependentPath, '/')!! ZipUtil.addFileOrDirRecursively(zipOut, null, file.toFile(), relativePath, null, writtenItemRelativePaths) } } exportInstalledPlugins(zipOut) val zipEntry = ZipEntry(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER) zipOut.putNextEntry(zipEntry) zipOut.closeEntry() } finally { zipOut.doClose() } } private class MyZipOutputStream(out: OutputStream) : ZipOutputStream(out) { override fun close() { } fun doClose() { super.close() } } data class ExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT) private fun exportInstalledPlugins(zipOut: MyZipOutputStream) { val plugins = ArrayList<String>() for (descriptor in PluginManagerCore.getPlugins()) { if (!descriptor.isBundled && descriptor.isEnabled) { plugins.add(descriptor.pluginId.idString) } } if (plugins.isEmpty()) { return } val e = ZipEntry(PluginManager.INSTALLED_TXT) zipOut.putNextEntry(e) try { PluginManagerCore.writePluginsList(plugins, OutputStreamWriter(zipOut, CharsetToolkit.UTF8_CHARSET)) } finally { zipOut.closeEntry() } } // onlyPaths - include only specified paths (relative to config dir, ends with "/" if directory) fun getExportableComponentsMap(onlyExisting: Boolean, computePresentableNames: Boolean, storageManager: StateStorageManager = ApplicationManager.getApplication().stateStore.stateStorageManager, onlyPaths: Set<String>? = null): Map<Path, List<ExportableItem>> { val result = LinkedHashMap<Path, MutableList<ExportableItem>>() @Suppress("DEPRECATION") val processor = { component: ExportableComponent -> for (file in component.exportFiles) { val item = ExportableItem(file.toPath(), component.presentableName, RoamingType.DEFAULT) result.putValue(item.file, item) } } @Suppress("DEPRECATION") ApplicationManager.getApplication().getComponents(ExportableApplicationComponent::class.java).forEach(processor) @Suppress("DEPRECATION") ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor) val configPath = storageManager.expandMacros(ROOT_CONFIG) fun isSkipFile(file: Path): Boolean { if (onlyPaths != null) { var relativePath = FileUtilRt.getRelativePath(configPath, file.systemIndependentPath, '/')!! if (!file.fileName.toString().contains('.') && !file.isFile()) { relativePath += '/' } if (!onlyPaths.contains(relativePath)) { return true } } return onlyExisting && !file.exists() } if (onlyExisting || onlyPaths != null) { result.keys.removeAll(::isSkipFile) } val fileToContent = THashMap<Path, String>() ServiceManagerImpl.processAllImplementationClasses(ApplicationManager.getApplication() as ApplicationImpl, { aClass, pluginDescriptor -> val stateAnnotation = StoreUtil.getStateSpec(aClass) @Suppress("DEPRECATION") if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) { return@processAllImplementationClasses true } val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@processAllImplementationClasses true if (!(storage.roamingType != RoamingType.DISABLED && storage.storageClass == StateStorage::class && !storage.path.isNullOrEmpty())) { return@processAllImplementationClasses true } var additionalExportFile: Path? = null val additionalExportPath = stateAnnotation.additionalExportFile if (additionalExportPath.isNotEmpty()) { // backward compatibility - path can contain macro if (additionalExportPath[0] == '$') { additionalExportFile = Paths.get(storageManager.expandMacros(additionalExportPath)) } else { additionalExportFile = Paths.get(storageManager.expandMacros(ROOT_CONFIG), additionalExportPath) } if (isSkipFile(additionalExportFile)) { additionalExportFile = null } } val file = Paths.get(storageManager.expandMacros(storage.path)) val isFileIncluded = !isSkipFile(file) if (isFileIncluded || additionalExportFile != null) { if (computePresentableNames && onlyExisting && additionalExportFile == null && file.fileName.toString().endsWith(".xml")) { val content = fileToContent.getOrPut(file) { file.readText() } if (!content.contains("""<component name="${stateAnnotation.name}">""")) { return@processAllImplementationClasses true } } val presentableName = if (computePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else "" if (isFileIncluded) { result.putValue(file, ExportableItem(file, presentableName, storage.roamingType)) } if (additionalExportFile != null) { result.putValue(additionalExportFile, ExportableItem(additionalExportFile, "$presentableName (schemes)", RoamingType.DEFAULT)) } } true }) // must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec (SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process { if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') { val file = Paths.get(storageManager.expandMacros(ROOT_CONFIG), it.fileSpec) if (!result.containsKey(file) && !isSkipFile(file)) { result.putValue(file, ExportableItem(file, it.presentableName ?: "", it.roamingType)) } } } return result } private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String { val presentableName = state.presentableName.java if (presentableName != State.NameGetter::class.java) { try { return ReflectionUtil.newInstance(presentableName).get() } catch (e: Exception) { LOG.error(e) } } val defaultName = state.name fun trimDefaultName() = defaultName.removeSuffix("Settings") var resourceBundleName: String? if (pluginDescriptor is IdeaPluginDescriptor && "com.intellij" != pluginDescriptor.pluginId.idString) { resourceBundleName = pluginDescriptor.resourceBundleBaseName if (resourceBundleName == null) { if (pluginDescriptor.vendor == "JetBrains") { resourceBundleName = OptionsBundle.PATH_TO_BUNDLE } else { return trimDefaultName() } } } else { resourceBundleName = OptionsBundle.PATH_TO_BUNDLE } val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader if (classLoader != null) { val message = messageOrDefault(classLoader, resourceBundleName, defaultName) if (message !== defaultName) { return message } if (PlatformUtils.isRubyMine()) { // ruby plugin in RubyMine has id "com.intellij", so, we cannot set "resource-bundle" in plugin.xml return messageOrDefault(classLoader, "org.jetbrains.plugins.ruby.RBundle", defaultName) } } return trimDefaultName() } private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, defaultName: String): String { val bundle = AbstractBundle.getResourceBundle(bundleName, classLoader) ?: return defaultName return CommonBundle.messageOrDefault(bundle, "exportable.$defaultName.presentable.name", defaultName) }
apache-2.0
c2d200f593bc17196cdf92f29fb7a612
38.334448
138
0.722388
4.964542
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/utils/Constants.kt
1
569
package com.quickblox.sample.conference.kotlin.presentation.utils /* * Created by Injoit in 2021-09-30. * Copyright ยฉ 2021 Quickblox. All rights reserved. */ object Constants { var EXTRA_DIALOG_ID = "dialog_id" var EXTRA_ROLE= "role" var EXTRA_CERTAIN_DIALOG_ID = "certain_dialog_id" var EXTRA_ROOM_TITLE = "room_title" var EXTRA_DIALOG_OCCUPANTS = "dialog_occupants" var EXTRA_AS_LISTENER = "as_listener" var EXTRA_SETTINGS_TYPE = "extra_settings_type" var MEDIA_PROJECT = "media_projection" var FACING_FRONT = "Facing front" }
bsd-3-clause
4fde0cc03b329acbc7ccd163fee8b2f5
32.470588
65
0.702465
3.442424
false
false
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/BaseQuickAdapter.kt
1
44734
package com.didichuxing.doraemonkit.widget.brvah import android.animation.Animator import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.view.ViewParent import android.widget.FrameLayout import android.widget.LinearLayout import androidx.annotation.IdRes import androidx.annotation.IntRange import androidx.annotation.LayoutRes import androidx.annotation.NonNull import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.didichuxing.doraemonkit.widget.brvah.animation.* import com.didichuxing.doraemonkit.widget.brvah.diff.BrvahAsyncDiffer import com.didichuxing.doraemonkit.widget.brvah.diff.BrvahAsyncDifferConfig import com.didichuxing.doraemonkit.widget.brvah.diff.BrvahListUpdateCallback import com.didichuxing.doraemonkit.widget.brvah.listener.* import com.didichuxing.doraemonkit.widget.brvah.module.* import com.didichuxing.doraemonkit.widget.brvah.util.getItemView import com.didichuxing.doraemonkit.widget.brvah.viewholder.BaseViewHolder import java.lang.ref.WeakReference import java.lang.reflect.Constructor import java.lang.reflect.InvocationTargetException import java.lang.reflect.Modifier import java.lang.reflect.ParameterizedType import java.util.* import kotlin.collections.ArrayList /** * ่Žทๅ–ๆจกๅ— */ private interface BaseQuickAdapterModuleImp { /** * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›ž่‡ชๅฎšไน‰ๆจกๅ— * @param baseQuickAdapter BaseQuickAdapter<*, *> * @return BaseLoadMoreModule */ fun addLoadMoreModule(baseQuickAdapter: BaseQuickAdapter<*, *>): BaseLoadMoreModule { return BaseLoadMoreModule(baseQuickAdapter) } /** * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›ž่‡ชๅฎšไน‰ๆจกๅ— * @param baseQuickAdapter BaseQuickAdapter<*, *> * @return BaseUpFetchModule */ fun addUpFetchModule(baseQuickAdapter: BaseQuickAdapter<*, *>): BaseUpFetchModule { return BaseUpFetchModule(baseQuickAdapter) } /** * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›ž่‡ชๅฎšไน‰ๆจกๅ— * @param baseQuickAdapter BaseQuickAdapter<*, *> * @return BaseExpandableModule */ fun addDraggableModule(baseQuickAdapter: BaseQuickAdapter<*, *>): BaseDraggableModule { return BaseDraggableModule(baseQuickAdapter) } } /** * Base Class * @param T : type of data, ๆ•ฐๆฎ็ฑปๅž‹ * @param VH : BaseViewHolder * @constructor layoutId, data(Can null parameters, the default is empty data) */ abstract class BaseQuickAdapter<T, VH : BaseViewHolder> @JvmOverloads constructor(@LayoutRes private val layoutResId: Int, data: MutableList<T>? = null) : RecyclerView.Adapter<VH>(), BaseQuickAdapterModuleImp, BaseListenerImp { companion object { const val HEADER_VIEW = 0x10000111 const val LOAD_MORE_VIEW = 0x10000222 const val FOOTER_VIEW = 0x10000333 const val EMPTY_VIEW = 0x10000555 } /***************************** Public property settings *************************************/ /** * data, Only allowed to get. * ๆ•ฐๆฎ, ๅชๅ…่ฎธ getใ€‚ */ var data: MutableList<T> = data ?: arrayListOf() internal set /** * ๅฝ“ๆ˜พ็คบ็ฉบๅธƒๅฑ€ๆ—ถ๏ผŒๆ˜ฏๅฆๆ˜พ็คบ Header */ var headerWithEmptyEnable = false /** ๅฝ“ๆ˜พ็คบ็ฉบๅธƒๅฑ€ๆ—ถ๏ผŒๆ˜ฏๅฆๆ˜พ็คบ Foot */ var footerWithEmptyEnable = false /** ๆ˜ฏๅฆไฝฟ็”จ็ฉบๅธƒๅฑ€ */ var isUseEmpty = true /** * if asFlow is true, footer/header will arrange like normal item view. * only works when use [GridLayoutManager],and it will ignore span size. */ var headerViewAsFlow: Boolean = false var footerViewAsFlow: Boolean = false /** * ๆ˜ฏๅฆๆ‰“ๅผ€ๅŠจ็”ป */ var animationEnable: Boolean = false /** * ๅŠจ็”ปๆ˜ฏๅฆไป…็ฌฌไธ€ๆฌกๆ‰ง่กŒ */ var isAnimationFirstOnly = true /** * ่ฎพ็ฝฎ่‡ชๅฎšไน‰ๅŠจ็”ป */ var adapterAnimation: BaseAnimation? = null set(value) { animationEnable = true field = value } /** * ๅŠ ่ฝฝๆ›ดๅคšๆจกๅ— */ val loadMoreModule: BaseLoadMoreModule get() { checkNotNull(mLoadMoreModule) { "Please first implements LoadMoreModule" } return mLoadMoreModule!! } /** * ๅ‘ไธŠๅŠ ่ฝฝๆจกๅ— */ val upFetchModule: BaseUpFetchModule get() { checkNotNull(mUpFetchModule) { "Please first implements UpFetchModule" } return mUpFetchModule!! } /** * ๆ‹–ๆ‹ฝๆจกๅ— */ val draggableModule: BaseDraggableModule get() { checkNotNull(mDraggableModule) { "Please first implements DraggableModule" } return mDraggableModule!! } /********************************* Private property *****************************************/ private var mDiffHelper: BrvahAsyncDiffer<T>? = null private lateinit var mHeaderLayout: LinearLayout private lateinit var mFooterLayout: LinearLayout private lateinit var mEmptyLayout: FrameLayout private var mLastPosition = -1 private var mSpanSizeLookup: GridSpanSizeLookup? = null private var mOnItemClickListener: OnItemClickListener? = null private var mOnItemLongClickListener: OnItemLongClickListener? = null private var mOnItemChildClickListener: OnItemChildClickListener? = null private var mOnItemChildLongClickListener: OnItemChildLongClickListener? = null private var mLoadMoreModule: BaseLoadMoreModule? = null private var mUpFetchModule: BaseUpFetchModule? = null private var mDraggableModule: BaseDraggableModule? = null public var context: Context? = null lateinit var weakRecyclerView: WeakReference<RecyclerView> /******************************* RecyclerView Method ****************************************/ init { checkModule() } /** * ๆฃ€ๆŸฅๆจกๅ— */ private fun checkModule() { if (this is LoadMoreModule) { mLoadMoreModule = this.addLoadMoreModule(this) } if (this is UpFetchModule) { mUpFetchModule = this.addUpFetchModule(this) } if (this is DraggableModule) { mDraggableModule = this.addDraggableModule(this) } } /** * Implement this method and use the helper to adapt the view to the given item. * * ๅฎž็Žฐๆญคๆ–นๆณ•๏ผŒๅนถไฝฟ็”จ helper ๅฎŒๆˆ item ่ง†ๅ›พ็š„ๆ“ไฝœ * * @param helper A fully initialized helper. * @param item The item that needs to be displayed. */ protected abstract fun convert(holder: VH, item: T) /** * Optional implementation this method and use the helper to adapt the view to the given item. * If use [payloads], will perform this method, Please implement this method for partial refresh. * If use [RecyclerView.Adapter.notifyItemChanged(Int, Object)] with payload, * Will execute this method. * * ๅฏ้€‰ๅฎž็Žฐ๏ผŒๅฆ‚ๆžœไฝ ๆ˜ฏ็”จไบ†[payloads]ๅˆทๆ–ฐitem๏ผŒ่ฏทๅฎž็Žฐๆญคๆ–นๆณ•๏ผŒ่ฟ›่กŒๅฑ€้ƒจๅˆทๆ–ฐ * * @param helper A fully initialized helper. * @param item The item that needs to be displayed. * @param payloads payload info. */ protected open fun convert(holder: VH, item: T, payloads: List<Any>) {} override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH { val baseViewHolder: VH when (viewType) { LOAD_MORE_VIEW -> { val view = mLoadMoreModule!!.loadMoreView.getRootView(parent) baseViewHolder = createBaseViewHolder(view) mLoadMoreModule!!.setupViewHolder(baseViewHolder) } HEADER_VIEW -> { val headerLayoutVp: ViewParent? = mHeaderLayout.parent if (headerLayoutVp is ViewGroup) { headerLayoutVp.removeView(mHeaderLayout) } baseViewHolder = createBaseViewHolder(mHeaderLayout) } EMPTY_VIEW -> { val emptyLayoutVp: ViewParent? = mEmptyLayout.parent if (emptyLayoutVp is ViewGroup) { emptyLayoutVp.removeView(mEmptyLayout) } baseViewHolder = createBaseViewHolder(mEmptyLayout) } FOOTER_VIEW -> { val footerLayoutVp: ViewParent? = mFooterLayout.parent if (footerLayoutVp is ViewGroup) { footerLayoutVp.removeView(mFooterLayout) } baseViewHolder = createBaseViewHolder(mFooterLayout) } else -> { val viewHolder = onCreateDefViewHolder(parent, viewType) bindViewClickListener(viewHolder, viewType) mDraggableModule?.initView(viewHolder) onItemViewHolderCreated(viewHolder, viewType) baseViewHolder = viewHolder } } return baseViewHolder } /** * Don't override this method. If need, please override [getItemCount] * ไธ่ฆ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒๅฆ‚ๆžœๆœ‰้œ€่ฆ๏ผŒ่ฏท้‡ๅ†™[getDefItemViewType] * @return Int */ override fun getItemCount(): Int { if (hasEmptyView()) { var count = 1 if (headerWithEmptyEnable && hasHeaderLayout()) { count++ } if (footerWithEmptyEnable && hasFooterLayout()) { count++ } return count } else { val loadMoreCount = if (mLoadMoreModule?.hasLoadMoreView() == true) { 1 } else { 0 } return headerLayoutCount + getDefItemCount() + footerLayoutCount + loadMoreCount } } /** * Don't override this method. If need, please override [getDefItemViewType] * ไธ่ฆ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒๅฆ‚ๆžœๆœ‰้œ€่ฆ๏ผŒ่ฏท้‡ๅ†™[getDefItemViewType] * * @param position Int * @return Int */ override fun getItemViewType(position: Int): Int { if (hasEmptyView()) { val header = headerWithEmptyEnable && hasHeaderLayout() return when (position) { 0 -> if (header) { HEADER_VIEW } else { EMPTY_VIEW } 1 -> if (header) { EMPTY_VIEW } else { FOOTER_VIEW } 2 -> FOOTER_VIEW else -> EMPTY_VIEW } } val hasHeader = hasHeaderLayout() if (hasHeader && position == 0) { return HEADER_VIEW } else { var adjPosition = if (hasHeader) { position - 1 } else { position } val dataSize = data.size return if (adjPosition < dataSize) { getDefItemViewType(adjPosition) } else { adjPosition -= dataSize val numFooters = if (hasFooterLayout()) { 1 } else { 0 } if (adjPosition < numFooters) { FOOTER_VIEW } else { LOAD_MORE_VIEW } } } } override fun onBindViewHolder(holder: VH, position: Int) { //Add up fetch logic, almost like load more, but simpler. mUpFetchModule?.autoUpFetch(position) //Do not move position, need to change before LoadMoreView binding mLoadMoreModule?.autoLoadMore(position) when (holder.itemViewType) { LOAD_MORE_VIEW -> { mLoadMoreModule?.let { it.loadMoreView.convert(holder, position, it.loadMoreStatus) } } HEADER_VIEW, EMPTY_VIEW, FOOTER_VIEW -> return else -> convert(holder, getItem(position - headerLayoutCount)) } } override fun onBindViewHolder(holder: VH, position: Int, payloads: MutableList<Any>) { if (payloads.isEmpty()) { onBindViewHolder(holder, position) return } //Add up fetch logic, almost like load more, but simpler. mUpFetchModule?.autoUpFetch(position) //Do not move position, need to change before LoadMoreView binding mLoadMoreModule?.autoLoadMore(position) when (holder.itemViewType) { LOAD_MORE_VIEW -> { mLoadMoreModule?.let { it.loadMoreView.convert(holder, position, it.loadMoreStatus) } } HEADER_VIEW, EMPTY_VIEW, FOOTER_VIEW -> return else -> convert(holder, getItem(position - headerLayoutCount), payloads) } } override fun getItemId(position: Int): Long { return position.toLong() } /** * Called when a view created by this holder has been attached to a window. * simple to solve item will layout using all * [setFullSpan] * * @param holder */ override fun onViewAttachedToWindow(holder: VH) { super.onViewAttachedToWindow(holder) val type = holder.itemViewType if (isFixedViewType(type)) { setFullSpan(holder) } else { addAnimation(holder) } } override fun onAttachedToRecyclerView(recyclerView: RecyclerView) { super.onAttachedToRecyclerView(recyclerView) weakRecyclerView = WeakReference(recyclerView) this.context = recyclerView.context mDraggableModule?.attachToRecyclerView(recyclerView) val manager = recyclerView.layoutManager if (manager is GridLayoutManager) { val defSpanSizeLookup = manager.spanSizeLookup manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val type = getItemViewType(position) if (type == HEADER_VIEW && headerViewAsFlow) { return 1 } if (type == FOOTER_VIEW && footerViewAsFlow) { return 1 } return if (mSpanSizeLookup == null) { if (isFixedViewType(type)) manager.spanCount else defSpanSizeLookup.getSpanSize(position) } else { if (isFixedViewType(type)) { manager.spanCount } else { mSpanSizeLookup!!.getSpanSize(manager, type, position - headerLayoutCount) } } } } } } protected open fun isFixedViewType(type: Int): Boolean { return type == EMPTY_VIEW || type == HEADER_VIEW || type == FOOTER_VIEW || type == LOAD_MORE_VIEW } /** * Get the data item associated with the specified position in the data set. * * @param position Position of the item whose data we want within the adapter's * data set. * @return The data at the specified position. */ open fun getItem(@IntRange(from = 0) position: Int): T { return data[position] } open fun getItemOrNull(@IntRange(from = 0) position: Int): T? { return data.getOrNull(position) } /** * ๅฆ‚ๆžœ่ฟ”ๅ›ž -1๏ผŒ่กจ็คบไธๅญ˜ๅœจ * @param item T? * @return Int */ open fun getItemPosition(item: T?): Int { return if (item != null && data.isNotEmpty()) data.indexOf(item) else -1 } /** * ็”จไบŽไฟๅญ˜้œ€่ฆ่ฎพ็ฝฎ็‚นๅ‡ปไบ‹ไปถ็š„ item */ private val childClickViewIds = LinkedHashSet<Int>() fun getChildClickViewIds(): LinkedHashSet<Int> { return childClickViewIds } /** * ่ฎพ็ฝฎ้œ€่ฆ็‚นๅ‡ปไบ‹ไปถ็š„ๅญview * @param viewIds IntArray */ fun addChildClickViewIds(@IdRes vararg viewIds: Int) { for (viewId in viewIds) { childClickViewIds.add(viewId) } } /** * ็”จไบŽไฟๅญ˜้œ€่ฆ่ฎพ็ฝฎ้•ฟๆŒ‰็‚นๅ‡ปไบ‹ไปถ็š„ item */ private val childLongClickViewIds = LinkedHashSet<Int>() fun getChildLongClickViewIds(): LinkedHashSet<Int> { return childLongClickViewIds } /** * ่ฎพ็ฝฎ้œ€่ฆ้•ฟๆŒ‰็‚นๅ‡ปไบ‹ไปถ็š„ๅญview * @param viewIds IntArray */ fun addChildLongClickViewIds(@IdRes vararg viewIds: Int) { for (viewId in viewIds) { childLongClickViewIds.add(viewId) } } /** * ็ป‘ๅฎš item ็‚นๅ‡ปไบ‹ไปถ * @param viewHolder VH */ protected open fun bindViewClickListener(viewHolder: VH, viewType: Int) { mOnItemClickListener?.let { viewHolder.itemView.setOnClickListener { v -> var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnClickListener } position -= headerLayoutCount setOnItemClick(v, position) } } mOnItemLongClickListener?.let { viewHolder.itemView.setOnLongClickListener { v -> var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnLongClickListener false } position -= headerLayoutCount setOnItemLongClick(v, position) } } mOnItemChildClickListener?.let { for (id in getChildClickViewIds()) { viewHolder.itemView.findViewById<View>(id)?.let { childView -> if (!childView.isClickable) { childView.isClickable = true } childView.setOnClickListener { v -> var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnClickListener } position -= headerLayoutCount setOnItemChildClick(v, position) } } } } mOnItemChildLongClickListener?.let { for (id in getChildLongClickViewIds()) { viewHolder.itemView.findViewById<View>(id)?.let { childView -> if (!childView.isLongClickable) { childView.isLongClickable = true } childView.setOnLongClickListener { v -> var position = viewHolder.adapterPosition if (position == RecyclerView.NO_POSITION) { return@setOnLongClickListener false } position -= headerLayoutCount setOnItemChildLongClick(v, position) } } } } } /** * override this method if you want to override click event logic * * ๅฆ‚ๆžœไฝ ๆƒณ้‡ๆ–ฐๅฎž็Žฐ item ็‚นๅ‡ปไบ‹ไปถ้€ป่พ‘๏ผŒ่ฏท้‡ๅ†™ๆญคๆ–นๆณ• * @param v * @param position */ protected open fun setOnItemClick(v: View, position: Int) { mOnItemClickListener?.onItemClick(this, v, position) } /** * override this method if you want to override longClick event logic * * ๅฆ‚ๆžœไฝ ๆƒณ้‡ๆ–ฐๅฎž็Žฐ item ้•ฟๆŒ‰ไบ‹ไปถ้€ป่พ‘๏ผŒ่ฏท้‡ๅ†™ๆญคๆ–นๆณ• * @param v * @param position * @return */ protected open fun setOnItemLongClick(v: View, position: Int): Boolean { return mOnItemLongClickListener?.onItemLongClick(this, v, position) ?: false } protected open fun setOnItemChildClick(v: View, position: Int) { mOnItemChildClickListener?.onItemChildClick(this, v, position) } protected open fun setOnItemChildLongClick(v: View, position: Int): Boolean { return mOnItemChildLongClickListener?.onItemChildLongClick(this, v, position) ?: false } /** * ๏ผˆๅฏ้€‰้‡ๅ†™๏ผ‰ๅฝ“ item ็š„ ViewHolderๅˆ›ๅปบๅฎŒๆฏ•ๅŽ๏ผŒๆ‰ง่กŒๆญคๆ–นๆณ•ใ€‚ * ๅฏๅœจๆญคๅฏน ViewHolder ่ฟ›่กŒๅค„็†๏ผŒไพ‹ๅฆ‚่ฟ›่กŒ DataBinding ็ป‘ๅฎš view * * @param viewHolder VH * @param viewType Int */ protected open fun onItemViewHolderCreated(viewHolder: VH, viewType: Int) {} /** * Override this method and return your data size. * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›žไฝ ็š„ๆ•ฐๆฎๆ•ฐ้‡ใ€‚ */ protected open fun getDefItemCount(): Int { return data.size } /** * Override this method and return your ViewType. * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›žไฝ ็š„ViewTypeใ€‚ */ protected open fun getDefItemViewType(position: Int): Int { return super.getItemViewType(position) } /** * Override this method and return your ViewHolder. * ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒ่ฟ”ๅ›žไฝ ็š„ViewHolderใ€‚ */ protected open fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): VH { return createBaseViewHolder(parent, layoutResId) } protected open fun createBaseViewHolder(parent: ViewGroup, @LayoutRes layoutResId: Int): VH { return createBaseViewHolder(parent.getItemView(layoutResId)) } /** * ๅˆ›ๅปบ ViewHolderใ€‚ๅฏไปฅ้‡ๅ†™ * * @param view View * @return VH */ @Suppress("UNCHECKED_CAST") protected open fun createBaseViewHolder(view: View): VH { var temp: Class<*>? = javaClass var z: Class<*>? = null while (z == null && null != temp) { z = getInstancedGenericKClass(temp) temp = temp.superclass } // ๆณ›ๅž‹ๆ“ฆ้™คไผšๅฏผ่‡ดzไธบnull val vh: VH? = if (z == null) { BaseViewHolder(view) as VH } else { createBaseGenericKInstance(z, view) } return vh ?: BaseViewHolder(view) as VH } /** * get generic parameter VH * * @param z * @return */ private fun getInstancedGenericKClass(z: Class<*>): Class<*>? { try { val type = z.genericSuperclass if (type is ParameterizedType) { val types = type.actualTypeArguments for (temp in types) { if (temp is Class<*>) { if (BaseViewHolder::class.java.isAssignableFrom(temp)) { return temp } } else if (temp is ParameterizedType) { val rawType = temp.rawType if (rawType is Class<*> && BaseViewHolder::class.java.isAssignableFrom(rawType)) { return rawType } } } } } catch (e: java.lang.reflect.GenericSignatureFormatError) { e.printStackTrace() } catch (e: TypeNotPresentException) { e.printStackTrace() } catch (e: java.lang.reflect.MalformedParameterizedTypeException) { e.printStackTrace() } return null } /** * try to create Generic VH instance * * @param z * @param view * @return */ @Suppress("UNCHECKED_CAST") private fun createBaseGenericKInstance(z: Class<*>, view: View): VH? { try { val constructor: Constructor<*> // inner and unstatic class return if (z.isMemberClass && !Modifier.isStatic(z.modifiers)) { constructor = z.getDeclaredConstructor(javaClass, View::class.java) constructor.isAccessible = true constructor.newInstance(this, view) as VH } else { constructor = z.getDeclaredConstructor(View::class.java) constructor.isAccessible = true constructor.newInstance(view) as VH } } catch (e: NoSuchMethodException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: InvocationTargetException) { e.printStackTrace() } return null } /** * When set to true, the item will layout using all span area. That means, if orientation * is vertical, the view will have full width; if orientation is horizontal, the view will * have full height. * if the hold view use StaggeredGridLayoutManager they should using all span area * * @param holder True if this item should traverse all spans. */ protected open fun setFullSpan(holder: RecyclerView.ViewHolder) { val layoutParams = holder.itemView.layoutParams if (layoutParams is StaggeredGridLayoutManager.LayoutParams) { layoutParams.isFullSpan = true } } /** * get the specific view by position,e.g. getViewByPosition(2, R.id.textView) * * bind [RecyclerView.setAdapter] before use! */ fun getViewByPosition(position: Int, @IdRes viewId: Int): View? { val recyclerView = weakRecyclerView.get() ?: return null val viewHolder = recyclerView.findViewHolderForLayoutPosition(position) as BaseViewHolder? ?: return null return viewHolder.getViewOrNull(viewId) } /********************************************************************************************/ /********************************* HeaderView Method ****************************************/ /********************************************************************************************/ @JvmOverloads fun addHeaderView(view: View, index: Int = -1, orientation: Int = LinearLayout.VERTICAL): Int { if (!this::mHeaderLayout.isInitialized) { mHeaderLayout = LinearLayout(view.context) mHeaderLayout.orientation = orientation mHeaderLayout.layoutParams = if (orientation == LinearLayout.VERTICAL) { RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT) } else { RecyclerView.LayoutParams(WRAP_CONTENT, MATCH_PARENT) } } val childCount = mHeaderLayout.childCount var mIndex = index if (index < 0 || index > childCount) { mIndex = childCount } mHeaderLayout.addView(view, mIndex) if (mHeaderLayout.childCount == 1) { val position = headerViewPosition if (position != -1) { notifyItemInserted(position) } } return mIndex } @JvmOverloads fun setHeaderView(view: View, index: Int = 0, orientation: Int = LinearLayout.VERTICAL): Int { return if (!this::mHeaderLayout.isInitialized || mHeaderLayout.childCount <= index) { addHeaderView(view, index, orientation) } else { mHeaderLayout.removeViewAt(index) mHeaderLayout.addView(view, index) index } } /** * ๆ˜ฏๅฆๆœ‰ HeaderLayout * @return Boolean */ fun hasHeaderLayout(): Boolean { if (this::mHeaderLayout.isInitialized && mHeaderLayout.childCount > 0) { return true } return false } fun removeHeaderView(header: View) { if (!hasHeaderLayout()) return mHeaderLayout.removeView(header) if (mHeaderLayout.childCount == 0) { val position = headerViewPosition if (position != -1) { notifyItemRemoved(position) } } } fun removeAllHeaderView() { if (!hasHeaderLayout()) return mHeaderLayout.removeAllViews() val position = headerViewPosition if (position != -1) { notifyItemRemoved(position) } } val headerViewPosition: Int get() { if (hasEmptyView()) { if (headerWithEmptyEnable) { return 0 } } else { return 0 } return -1 } /** * if addHeaderView will be return 1, if not will be return 0 */ val headerLayoutCount: Int get() { return if (hasHeaderLayout()) { 1 } else { 0 } } /** * ่Žทๅ–ๅคดๅธƒๅฑ€ */ val headerLayout: LinearLayout? get() { return if (this::mHeaderLayout.isInitialized) { mHeaderLayout } else { null } } /********************************************************************************************/ /********************************* FooterView Method ****************************************/ /********************************************************************************************/ @JvmOverloads fun addFooterView(view: View, index: Int = -1, orientation: Int = LinearLayout.VERTICAL): Int { if (!this::mFooterLayout.isInitialized) { mFooterLayout = LinearLayout(view.context) mFooterLayout.orientation = orientation mFooterLayout.layoutParams = if (orientation == LinearLayout.VERTICAL) { RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT) } else { RecyclerView.LayoutParams(WRAP_CONTENT, MATCH_PARENT) } } val childCount = mFooterLayout.childCount var mIndex = index if (index < 0 || index > childCount) { mIndex = childCount } mFooterLayout.addView(view, mIndex) if (mFooterLayout.childCount == 1) { val position = footerViewPosition if (position != -1) { notifyItemInserted(position) } } return mIndex } @JvmOverloads fun setFooterView(view: View, index: Int = 0, orientation: Int = LinearLayout.VERTICAL): Int { return if (!this::mFooterLayout.isInitialized || mFooterLayout.childCount <= index) { addFooterView(view, index, orientation) } else { mFooterLayout.removeViewAt(index) mFooterLayout.addView(view, index) index } } fun removeFooterView(footer: View) { if (!hasFooterLayout()) return mFooterLayout.removeView(footer) if (mFooterLayout.childCount == 0) { val position = footerViewPosition if (position != -1) { notifyItemRemoved(position) } } } fun removeAllFooterView() { if (!hasFooterLayout()) return mFooterLayout.removeAllViews() val position = footerViewPosition if (position != -1) { notifyItemRemoved(position) } } fun hasFooterLayout(): Boolean { if (this::mFooterLayout.isInitialized && mFooterLayout.childCount > 0) { return true } return false } val footerViewPosition: Int get() { if (hasEmptyView()) { var position = 1 if (headerWithEmptyEnable && hasHeaderLayout()) { position++ } if (footerWithEmptyEnable) { return position } } else { return headerLayoutCount + data.size } return -1 } /** * if addHeaderView will be return 1, if not will be return 0 */ val footerLayoutCount: Int get() { return if (hasFooterLayout()) { 1 } else { 0 } } /** * ่Žทๅ–่„šๅธƒๅฑ€ * @return LinearLayout? */ val footerLayout: LinearLayout? get() { return if (this::mFooterLayout.isInitialized) { mFooterLayout } else { null } } /********************************************************************************************/ /********************************** EmptyView Method ****************************************/ /********************************************************************************************/ /** * ่ฎพ็ฝฎ็ฉบๅธƒๅฑ€่ง†ๅ›พ๏ผŒๆณจๆ„๏ผš[data]ๅฟ…้กปไธบ็ฉบๆ•ฐ็ป„ * @param emptyView View */ fun setEmptyView(emptyView: View) { val oldItemCount = itemCount var insert = false if (!this::mEmptyLayout.isInitialized) { mEmptyLayout = FrameLayout(emptyView.context) mEmptyLayout.layoutParams = emptyView.layoutParams?.let { return@let ViewGroup.LayoutParams(it.width, it.height) } ?: ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT) insert = true } else { emptyView.layoutParams?.let { val lp = mEmptyLayout.layoutParams lp.width = it.width lp.height = it.height mEmptyLayout.layoutParams = lp } } mEmptyLayout.removeAllViews() mEmptyLayout.addView(emptyView) isUseEmpty = true if (insert && hasEmptyView()) { var position = 0 if (headerWithEmptyEnable && hasHeaderLayout()) { position++ } if (itemCount > oldItemCount) { notifyItemInserted(position) } else { notifyDataSetChanged() } } } fun setEmptyView(layoutResId: Int) { weakRecyclerView.get()?.let { val view = LayoutInflater.from(it.context).inflate(layoutResId, it, false) setEmptyView(view) } } fun removeEmptyView() { if (this::mEmptyLayout.isInitialized) { mEmptyLayout.removeAllViews() } } fun hasEmptyView(): Boolean { if (!this::mEmptyLayout.isInitialized || mEmptyLayout.childCount == 0) { return false } if (!isUseEmpty) { return false } return data.isEmpty() } /** * When the current adapter is empty, the BaseQuickAdapter can display a special view * called the empty view. The empty view is used to provide feedback to the user * that no data is available in this AdapterView. * * @return The view to show if the adapter is empty. */ val emptyLayout: FrameLayout? get() { return if (this::mEmptyLayout.isInitialized) { mEmptyLayout } else { null } } /*************************** Animation ******************************************/ /** * add animation when you want to show time * * @param holder */ private fun addAnimation(holder: RecyclerView.ViewHolder) { if (animationEnable) { if (!isAnimationFirstOnly || holder.layoutPosition > mLastPosition) { val animation: BaseAnimation = adapterAnimation?.let { it } ?: AlphaInAnimation() animation.animators(holder.itemView).forEach { startAnim(it, holder.layoutPosition) } mLastPosition = holder.layoutPosition } } } /** * ๅผ€ๅง‹ๆ‰ง่กŒๅŠจ็”ปๆ–นๆณ• * ๅฏไปฅ้‡ๅ†™ๆญคๆ–นๆณ•๏ผŒๅฎž่กŒๆ›ดๅคš่กŒไธบ * * @param anim * @param index */ protected open fun startAnim(anim: Animator, index: Int) { anim.start() } /** * ๅ†…็ฝฎ้ป˜่ฎคๅŠจ็”ป็ฑปๅž‹ */ enum class AnimationType { AlphaIn, ScaleIn, SlideInBottom, SlideInLeft, SlideInRight } /** * ไฝฟ็”จๅ†…็ฝฎ้ป˜่ฎคๅŠจ็”ป่ฎพ็ฝฎ * @param animationType AnimationType */ fun setAnimationWithDefault(animationType: AnimationType) { adapterAnimation = when (animationType) { AnimationType.AlphaIn -> AlphaInAnimation() AnimationType.ScaleIn -> ScaleInAnimation() AnimationType.SlideInBottom -> SlideInBottomAnimation() AnimationType.SlideInLeft -> SlideInLeftAnimation() AnimationType.SlideInRight -> SlideInRightAnimation() } } /*************************** ่ฎพ็ฝฎๆ•ฐๆฎ็›ธๅ…ณ ******************************************/ /** * setting up a new instance to data; * ่ฎพ็ฝฎๆ–ฐ็š„ๆ•ฐๆฎๅฎžไพ‹ * * @param data */ @Deprecated("Please use setNewInstance(), This method will be removed in the next version", replaceWith = ReplaceWith("setNewInstance(data)")) open fun setNewData(data: MutableList<T>?) { setNewInstance(data) } /** * setting up a new instance to data; * ่ฎพ็ฝฎๆ–ฐ็š„ๆ•ฐๆฎๅฎžไพ‹๏ผŒๆ›ฟๆขๅŽŸๆœ‰ๅ†…ๅญ˜ๅผ•็”จใ€‚ * ้€šๅธธๆƒ…ๅ†ตไธ‹๏ผŒๅฆ‚้žๅฟ…่ฆ๏ผŒ่ฏทไฝฟ็”จ[setList]ไฟฎๆ”นๅ†…ๅฎน * * @param data */ open fun setNewInstance(list: MutableList<T>?) { if (list === this.data) { return } this.data = list ?: arrayListOf() mLoadMoreModule?.reset() mLastPosition = -1 notifyDataSetChanged() mLoadMoreModule?.checkDisableLoadMoreIfNotFullPage() } /** * use data to replace all item in mData. this method is different [setList], * it doesn't change the [BaseQuickAdapter.data] reference * Deprecated, Please use [setList] * * @param newData data collection */ @Deprecated("Please use setData()", replaceWith = ReplaceWith("setData(newData)")) open fun replaceData(newData: Collection<T>) { setList(newData) } /** * ไฝฟ็”จๆ–ฐ็š„ๆ•ฐๆฎ้›†ๅˆ๏ผŒๆ”นๅ˜ๅŽŸๆœ‰ๆ•ฐๆฎ้›†ๅˆๅ†…ๅฎนใ€‚ * ๆณจๆ„๏ผšไธไผšๆ›ฟๆขๅŽŸๆœ‰็š„ๅ†…ๅญ˜ๅผ•็”จ๏ผŒๅชๆ˜ฏๆ›ฟๆขๅ†…ๅฎน * * @param list Collection<T>? */ open fun setList(list: Collection<T>?) { if (list !== this.data) { this.data.clear() if (!list.isNullOrEmpty()) { this.data.addAll(list) } } else { if (!list.isNullOrEmpty()) { val newList = ArrayList(list) this.data.clear() this.data.addAll(newList) } else { this.data.clear() } } mLoadMoreModule?.reset() mLastPosition = -1 notifyDataSetChanged() mLoadMoreModule?.checkDisableLoadMoreIfNotFullPage() } /** * change data * ๆ”นๅ˜ๆŸไธ€ไฝ็ฝฎๆ•ฐๆฎ */ open fun setData(@IntRange(from = 0) index: Int, data: T) { if (index >= this.data.size) { return } this.data[index] = data notifyItemChanged(index + headerLayoutCount) } /** * add one new data in to certain location * ๅœจๆŒ‡ๅฎšไฝ็ฝฎๆทปๅŠ ไธ€ๆกๆ–ฐๆ•ฐๆฎ * * @param position */ open fun addData(@IntRange(from = 0) position: Int, data: T) { this.data.add(position, data) notifyItemInserted(position + headerLayoutCount) compatibilityDataSizeChanged(1) } /** * add one new data * ๆทปๅŠ ไธ€ๆกๆ–ฐๆ•ฐๆฎ */ open fun addData(@NonNull data: T) { this.data.add(data) notifyItemInserted(this.data.size + headerLayoutCount) compatibilityDataSizeChanged(1) } /** * add new data in to certain location * ๅœจๆŒ‡ๅฎšไฝ็ฝฎๆทปๅŠ ๆ•ฐๆฎ * * @param position the insert position * @param newData the new data collection */ open fun addData(@IntRange(from = 0) position: Int, newData: Collection<T>) { this.data.addAll(position, newData) notifyItemRangeInserted(position + headerLayoutCount, newData.size) compatibilityDataSizeChanged(newData.size) } open fun addData(@NonNull newData: Collection<T>) { this.data.addAll(newData) notifyItemRangeInserted(this.data.size - newData.size + headerLayoutCount, newData.size) compatibilityDataSizeChanged(newData.size) } /** * remove the item associated with the specified position of adapter * ๅˆ ้™คๆŒ‡ๅฎšไฝ็ฝฎ็š„ๆ•ฐๆฎ * * @param position */ open fun remove(@IntRange(from = 0) position: Int) { if (position >= data.size) { return } this.data.removeAt(position) val internalPosition = position + headerLayoutCount notifyItemRemoved(internalPosition) compatibilityDataSizeChanged(0) notifyItemRangeChanged(internalPosition, this.data.size - internalPosition) } open fun remove(data: T) { val index = this.data.indexOf(data) if (index == -1) { return } remove(index) } /** * compatible getLoadMoreViewCount and getEmptyViewCount may change * * @param size Need compatible data size */ protected fun compatibilityDataSizeChanged(size: Int) { if (this.data.size == size) { notifyDataSetChanged() } } /** * ่ฎพ็ฝฎDiff Callback๏ผŒ็”จไบŽๅฟซ้€Ÿ็”Ÿๆˆ Diff Configใ€‚ * * @param diffCallback ItemCallback<T> */ fun setDiffCallback(diffCallback: DiffUtil.ItemCallback<T>) { this.setDiffConfig(BrvahAsyncDifferConfig.Builder(diffCallback).build()) } /** * ่ฎพ็ฝฎDiff Configใ€‚ๅฆ‚้œ€่‡ชๅฎšไน‰็บฟ็จ‹๏ผŒ่ฏทไฝฟ็”จๆญคๆ–นๆณ•ใ€‚ * ๅœจไฝฟ็”จ [setDiffNewData] ๅ‰๏ผŒๅฟ…้กป่ฎพ็ฝฎๆญคๆ–นๆณ• * @param config BrvahAsyncDifferConfig<T> */ fun setDiffConfig(config: BrvahAsyncDifferConfig<T>) { mDiffHelper = BrvahAsyncDiffer(this, config) } fun getDiffHelper(): BrvahAsyncDiffer<T> { checkNotNull(mDiffHelper) { "Please use setDiffCallback() or setDiffConfig() first!" } return mDiffHelper!! } /** * ไฝฟ็”จ Diff ่ฎพ็ฝฎๆ–ฐๅฎžไพ‹. * ๆญคๆ–นๆณ•ไธบๅผ‚ๆญฅDiff๏ผŒๆ— ้œ€่€ƒ่™‘ๆ€ง่ƒฝ้—ฎ้ข˜. * ไฝฟ็”จไน‹ๅ‰่ฏทๅ…ˆ่ฎพ็ฝฎ [setDiffCallback] ๆˆ–่€… [setDiffConfig]. * * Use Diff setting up a new instance to data. * This method is asynchronous. * * @param newData MutableList<T>? */ open fun setDiffNewData(list: MutableList<T>?) { if (hasEmptyView()) { // If the current view is an empty view, set the new data directly without diff setNewInstance(list) return } mDiffHelper?.submitList(list) } /** * ไฝฟ็”จ DiffResult ่ฎพ็ฝฎๆ–ฐๅฎžไพ‹. * Use DiffResult setting up a new instance to data. * * @param diffResult DiffResult * @param newData New Data */ open fun setDiffNewData(@NonNull diffResult: DiffUtil.DiffResult, list: MutableList<T>) { if (hasEmptyView()) { // If the current view is an empty view, set the new data directly without diff setNewInstance(list) return } diffResult.dispatchUpdatesTo(BrvahListUpdateCallback(this)) this.data = list } /************************************** Set Listener ****************************************/ override fun setGridSpanSizeLookup(spanSizeLookup: GridSpanSizeLookup?) { this.mSpanSizeLookup = spanSizeLookup } override fun setOnItemClickListener(listener: OnItemClickListener?) { this.mOnItemClickListener = listener } override fun setOnItemLongClickListener(listener: OnItemLongClickListener?) { this.mOnItemLongClickListener = listener } override fun setOnItemChildClickListener(listener: OnItemChildClickListener?) { this.mOnItemChildClickListener = listener } override fun setOnItemChildLongClickListener(listener: OnItemChildLongClickListener?) { this.mOnItemChildLongClickListener = listener } fun getOnItemClickListener(): OnItemClickListener? = mOnItemClickListener fun getOnItemLongClickListener(): OnItemLongClickListener? = mOnItemLongClickListener fun getOnItemChildClickListener(): OnItemChildClickListener? = mOnItemChildClickListener fun getOnItemChildLongClickListener(): OnItemChildLongClickListener? = mOnItemChildLongClickListener }
apache-2.0
005d044b879c1a05f298c19abd48e519
30.839941
146
0.563437
4.971455
false
false
false
false
lambdasoup/watchlater
app/src/main/java/com/lambdasoup/watchlater/ui/add/Playlist.kt
1
1882
/* * Copyright (c) 2015 - 2022 * * Maximilian Hille <[email protected]> * Juliane Lehmann <[email protected]> * * This file is part of Watch Later. * * Watch Later is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Watch Later 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 Watch Later. If not, see <http://www.gnu.org/licenses/>. */ package com.lambdasoup.watchlater.ui.add import androidx.compose.foundation.layout.Row import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.lambdasoup.watchlater.R import com.lambdasoup.watchlater.data.YoutubeRepository.Playlists.Playlist import com.lambdasoup.watchlater.ui.WatchLaterTextButton @Composable fun Playlist( modifier: Modifier = Modifier, playlist: Playlist?, onSetPlaylist: () -> Unit, ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically ) { Text( modifier = Modifier.weight(1f, fill = true), text = playlist?.snippet?.title ?: stringResource(id = R.string.playlist_empty), style = MaterialTheme.typography.body2 ) WatchLaterTextButton( onClick = onSetPlaylist, label = R.string.account_set ) } }
gpl-3.0
7303f61019f7d6c1dd7cb17a702fd36d
32.017544
92
0.719979
4.229213
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/AcctMgrInfoParser.kt
2
3433
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.util.Xml import edu.berkeley.boinc.utils.Logging import org.xml.sax.Attributes import org.xml.sax.SAXException class AcctMgrInfoParser : BaseParser() { lateinit var accountMgrInfo: AcctMgrInfo private set @Throws(SAXException::class) override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) { super.startElement(uri, localName, qName, attributes) if (localName.equals(ACCT_MGR_INFO_TAG, ignoreCase = true)) { accountMgrInfo = AcctMgrInfo() } else { mElementStarted = true mCurrentElement.setLength(0) } } @Throws(SAXException::class) override fun endElement(uri: String?, localName: String, qName: String?) { super.endElement(uri, localName, qName) try { if (localName.equals(ACCT_MGR_INFO_TAG, ignoreCase = true)) { // closing tag if (arrayOf(accountMgrInfo.acctMgrName, accountMgrInfo.acctMgrUrl) .none { it.isEmpty() } && accountMgrInfo.isHavingCredentials) { accountMgrInfo.isPresent = true } } else { // decode inner tags when { localName.equals(AcctMgrInfo.Fields.ACCT_MGR_NAME, ignoreCase = true) -> { accountMgrInfo.acctMgrName = mCurrentElement.toString() } localName.equals(AcctMgrInfo.Fields.ACCT_MGR_URL, ignoreCase = true) -> { accountMgrInfo.acctMgrUrl = mCurrentElement.toString() } localName.equals(AcctMgrInfo.Fields.HAVING_CREDENTIALS, ignoreCase = true) -> { accountMgrInfo.isHavingCredentials = true } } } } catch (e: Exception) { Logging.logException(Logging.Category.XML, "AcctMgrInfoParser.endElement error: ", e) } mElementStarted = false } companion object { const val ACCT_MGR_INFO_TAG = "acct_mgr_info" @JvmStatic fun parse(rpcResult: String?): AcctMgrInfo? { return try { val parser = AcctMgrInfoParser() Xml.parse(rpcResult, parser) parser.accountMgrInfo } catch (e: SAXException) { Logging.logException(Logging.Category.RPC, "AcctMgrInfoParser: malformed XML ", e) Logging.logDebug(Logging.Category.XML, "AcctMgrInfoParser: $rpcResult") null } } } }
lgpl-3.0
5521b874a41dfaa7a065283f20f39f88
38.918605
105
0.608506
4.481723
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/inspection/StaticMemberInspection.kt
1
2587
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.ACCESSOR import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.INVOKER import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.OVERWRITE import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW import com.demonwav.mcdev.platform.mixin.util.isMixin import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.JavaElementVisitor import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiField import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier class StaticMemberInspection : MixinInspection() { override fun getStaticDescription() = "A mixin class does not exist at runtime, and thus having them public does not make sense. " + "Make the field/method private instead." override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder) private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() { override fun visitMethod(method: PsiMethod) { visitMember(method) } override fun visitField(field: PsiField) { visitMember(field) } private fun visitMember(member: PsiMember) { if (isProblematic(member)) { holder.registerProblem( member, "Public static members are not allowed in Mixin classes", QuickFixFactory.getInstance().createModifierListFix(member, PsiModifier.PRIVATE, true, false) ) } } private fun isProblematic(member: PsiMember): Boolean { val containingClass = member.containingClass ?: return false if (!containingClass.isMixin) { return false } val modifiers = member.modifierList!! return modifiers.hasModifierProperty(PsiModifier.PUBLIC) && modifiers.hasModifierProperty(PsiModifier.STATIC) && modifiers.findAnnotation(SHADOW) == null && modifiers.findAnnotation(OVERWRITE) == null && modifiers.findAnnotation(ACCESSOR) == null && modifiers.findAnnotation(INVOKER) == null } } }
mit
4b8bb1aed9ab1f22f3173e7785b2bcab
35.43662
113
0.68419
5.082515
false
false
false
false
alaminopu/IST-Syllabus
app/src/main/java/org/istbd/IST_Syllabus/SemesterComponent.kt
1
5460
package org.istbd.IST_Syllabus import android.graphics.Color import android.widget.TextView import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import org.istbd.IST_Syllabus.db.CourseEntity import org.istbd.IST_Syllabus.ui.theme.WHITE import org.istbd.IST_Syllabus.ui.theme.ISTTheme @Composable fun SemesterComponent( tab: Pair<String, String>, courses: List<CourseEntity>, department: String ) { val filteredCourses = courses.filter { courseEntity -> courseEntity.department == department && courseEntity.semester==tab.second } ISTTheme { Surface(color = MaterialTheme.colors.background) { LazyColumn(modifier = Modifier .fillMaxHeight() .fillMaxWidth()) { items(items = filteredCourses) { course -> Surface(color = colorResource(id = R.color.ist)) { Card(modifier = Modifier .fillMaxWidth() .padding(5.dp)) { Column(modifier = Modifier.padding(5.dp)) { if (course.major != null && course.major != "") { Text( buildAnnotatedString { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append("Major: ") } append(course.major!!) } ) } Text( buildAnnotatedString { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append("Title: ") } append(course.title?:"") } ) Text( buildAnnotatedString { if (course.code != "0") { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append("Code: ") } append(course.code?:"") append(" ") } withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append("Credit: ") } append(course.credit?:"") if (course.hour != "0") { withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) { append(" Hour: ") } append(course.hour?:"") } } ) if (!course.content.isNullOrBlank()) { Text(text = "Content: ", fontWeight = FontWeight.Bold) AndroidView(factory = { TextView(it).apply { text = course.content setTextColor(Color.parseColor("#000000")) } }) } if (!course.book.isNullOrBlank()) { Text(text = "Books: ", fontWeight = FontWeight.Bold) AndroidView(factory = { TextView(it).apply { text = course.book setTextColor(Color.parseColor("#000000")) } }) } } } } } } } } }
gpl-2.0
edbdaabf814a57e59c9341c5df24763d
47.327434
135
0.406227
6.732429
false
false
false
false
Ribesg/anko
dsl/static/src/sqlite/sqlTypes.kt
1
2122
/* * Copyright 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.anko.db interface SqlType { open val name: String open val modifier: String? } interface SqlTypeModifier { open val modifier: String } operator fun SqlType.plus(m: SqlTypeModifier) : SqlType { return SqlTypeImpl(name, if (modifier == null) m.toString() else "$modifier $m") } val NULL: SqlType = SqlTypeImpl("NULL") val INTEGER: SqlType = SqlTypeImpl("INTEGER") val REAL: SqlType = SqlTypeImpl("REAL") val TEXT: SqlType = SqlTypeImpl("TEXT") val BLOB: SqlType = SqlTypeImpl("BLOB") fun FOREIGN_KEY(columnName: String, referenceTable: String, referenceColumn: String): SqlType { return SqlTypeImpl("FOREIGN KEY($columnName) REFERENCES $referenceTable($referenceColumn)") } val PRIMARY_KEY: SqlTypeModifier = SqlTypeModifierImpl("PRIMARY KEY") val NOT_NULL: SqlTypeModifier = SqlTypeModifierImpl("NOT_NULL") val AUTOINCREMENT: SqlTypeModifier = SqlTypeModifierImpl("AUTOINCREMENT") val UNIQUE: SqlTypeModifier = SqlTypeModifierImpl("UNIQUE") fun DEFAULT(value: String): SqlTypeModifier = SqlTypeModifierImpl("DEFAULT $value") private open class SqlTypeImpl(name: String, modifier: String? = null) : SqlType { override val name: String = name override val modifier: String? = modifier override fun toString(): String { return if (modifier == null) name else "$name $modifier" } } private open class SqlTypeModifierImpl(modifier: String) : SqlTypeModifier { override val modifier: String = modifier override fun toString(): String = modifier }
apache-2.0
579025e92003bcc8c8b551712c00a3ab
33.225806
95
0.741282
3.922366
false
false
false
false
pennlabs/penn-mobile-android
PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/VenueInterval.kt
1
3817
package com.pennapps.labs.pennmobile.classes import android.util.Log import org.joda.time.DateTime import org.joda.time.IllegalInstantException import org.joda.time.Interval import org.joda.time.format.DateTimeFormat import org.joda.time.format.DateTimeFormatter import java.util.* /** * Interval for venues with meal name and Joda Intervals * Created by Adel on 7/13/15. */ class VenueInterval { var date: String? = null //@SerializedName("meal") var meals: List<MealInterval> = arrayListOf() /** * Get all the open hour time intervals for this dining hall in a given date * @return HashMap of meal name (lunch, dinner) to open hours expressed as a Joda Interval */ val intervals: HashMap<String?, Interval> get() { val openHours = HashMap<String?, Interval>() for (mI in meals) { val mealOpenInterval = mI.getInterval(date) openHours[mI.type] = mealOpenInterval } return openHours } class MealInterval { var open: String? = null var close: String? = null var type: String? = null /** * Put together the date given with the hours to create a POJO for the time interval in * which the dining hall is open. * Any time before 6:00am is assumed to be from the next day rather than the given date. * @param date Date string in yyyy-MM-dd format * @return Time interval in which meal is open represented as a Joda Interval */ fun getInterval(date: String?): Interval { var openTime = "$date $open" var closeTime = "$date $close" // Avoid midnight hour confusion as API returns both 00:00 and 24:00 // Switch it to more comprehensible 23:59 / 11:59PM if (close == "00:00:00" || close == "24:00:00") { closeTime = "$date 23:59:59" } Log.i("VenueInterval", "$openTime") if (open == "" && close == "") { open ="00:00:00" close ="00:00:00" openTime = "$date $open" closeTime = "$date $close" } val openInstant = DateTime.parse(openTime, dateFormat) var closeInstant: DateTime try { closeInstant = DateTime.parse(closeTime, dateFormat) } catch (e: IllegalInstantException) { closeTime = "$date 01:00:00" closeInstant = DateTime.parse(closeTime, dateFormat) } // Close hours sometimes given in AM hours of next day // Cutoff for "early morning" hours was decided to be 6AM if (closeInstant.hourOfDay < 6) { closeInstant = closeInstant.plusDays(1) } return Interval(openInstant, closeInstant) } fun getFormattedHour(hours: String): String { try { var newHours = hours.substring(0, 5) val hour = hours.substring(0, 2).toInt() if (hour > 12) { newHours = "" + (hour - 12) + hours.substring(2, 5) } newHours += if (hour >= 12) { "pm" } else { "am" } return newHours } catch (exception: Exception) { Log.d("Time Formatting Error", exception.message ?: "") return hours } } companion object { /** * Date format used by dining API. * Example: "2015-08-10 15:00:00" */ val dateFormat: DateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") } } }
mit
65431929764c5b278c498895af64f781
34.351852
96
0.540477
4.417824
false
false
false
false
Ribesg/anko
dsl/static/src/platform/CustomViews.kt
1
2662
/* * Copyright 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. */ @file:Suppress("NOTHING_TO_INLINE") package org.jetbrains.anko import android.app.Activity import android.app.Fragment import android.content.Context import android.view.View import android.view.ViewManager import android.widget.LinearLayout import org.jetbrains.anko.custom.ankoView object `$$Anko$Factories$CustomViews` { val VERTICAL_LAYOUT_FACTORY = { ctx: Context -> val view = _LinearLayout(ctx) view.orientation = LinearLayout.VERTICAL view } } inline fun ViewManager.verticalLayout(): LinearLayout = verticalLayout({}) inline fun ViewManager.verticalLayout(init: _LinearLayout.() -> Unit): LinearLayout { return ankoView(`$$Anko$Factories$CustomViews`.VERTICAL_LAYOUT_FACTORY, init) } inline fun Context.verticalLayout(): LinearLayout = verticalLayout({}) inline fun Context.verticalLayout(init: _LinearLayout.() -> Unit): LinearLayout { return ankoView(`$$Anko$Factories$CustomViews`.VERTICAL_LAYOUT_FACTORY, init) } inline fun Activity.verticalLayout(): LinearLayout = verticalLayout({}) inline fun Activity.verticalLayout(init: _LinearLayout.() -> Unit): LinearLayout { return ankoView(`$$Anko$Factories$CustomViews`.VERTICAL_LAYOUT_FACTORY, init) } inline fun <T: View> ViewManager.include(layoutId: Int): T = include(layoutId, {}) inline fun <T: View> ViewManager.include(layoutId: Int, init: T.() -> Unit): T { @Suppress("UNCHECKED_CAST") return ankoView({ ctx -> ctx.layoutInflater.inflate(layoutId, null) as T }) { init() } } inline fun <T: View> Context.include(layoutId: Int): T = include(layoutId, {}) inline fun <T: View> Context.include(layoutId: Int, init: T.() -> Unit): T { @Suppress("UNCHECKED_CAST") return ankoView({ ctx -> ctx.layoutInflater.inflate(layoutId, null) as T }) { init() } } inline fun <T: View> Activity.include(layoutId: Int): T = include(layoutId, {}) inline fun <T: View> Activity.include(layoutId: Int, init: T.() -> Unit): T { @Suppress("UNCHECKED_CAST") return ankoView({ ctx -> ctx.layoutInflater.inflate(layoutId, null) as T }) { init() } }
apache-2.0
123b19880ba04fd944c5f11847229575
38.746269
90
0.72314
3.979073
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/PaymentRelayStarter.kt
1
4684
package com.stripe.android import android.os.Parcel import android.os.Parcelable import androidx.activity.result.ActivityResultLauncher import com.stripe.android.core.exception.StripeException import com.stripe.android.model.PaymentIntent import com.stripe.android.model.SetupIntent import com.stripe.android.model.Source import com.stripe.android.model.StripeIntent import com.stripe.android.payments.PaymentFlowResult import com.stripe.android.view.AuthActivityStarter import com.stripe.android.view.AuthActivityStarterHost import com.stripe.android.view.PaymentRelayActivity import kotlinx.parcelize.Parceler import kotlinx.parcelize.Parcelize /** * Starts an instance of [PaymentRelayStarter]. * Should only be called from [StripePaymentController]. */ internal interface PaymentRelayStarter : AuthActivityStarter<PaymentRelayStarter.Args> { class Legacy( private val host: AuthActivityStarterHost ) : PaymentRelayStarter { override fun start(args: Args) { host.startActivityForResult( PaymentRelayActivity::class.java, args.toResult().toBundle(), args.requestCode ) } } class Modern( private val launcher: ActivityResultLauncher<Args> ) : PaymentRelayStarter { override fun start(args: Args) { launcher.launch(args) } } sealed class Args : Parcelable { abstract val requestCode: Int abstract fun toResult(): PaymentFlowResult.Unvalidated @Parcelize data class PaymentIntentArgs( internal val paymentIntent: PaymentIntent, internal val stripeAccountId: String? = null ) : Args() { override val requestCode: Int get() = StripePaymentController.PAYMENT_REQUEST_CODE override fun toResult(): PaymentFlowResult.Unvalidated { return PaymentFlowResult.Unvalidated( clientSecret = paymentIntent.clientSecret, stripeAccountId = stripeAccountId ) } } @Parcelize data class SetupIntentArgs( internal val setupIntent: SetupIntent, internal val stripeAccountId: String? = null ) : Args() { override val requestCode: Int get() = StripePaymentController.SETUP_REQUEST_CODE override fun toResult(): PaymentFlowResult.Unvalidated { return PaymentFlowResult.Unvalidated( clientSecret = setupIntent.clientSecret, stripeAccountId = stripeAccountId ) } } @Parcelize data class SourceArgs( internal val source: Source, internal val stripeAccountId: String? = null ) : Args() { override val requestCode: Int get() = StripePaymentController.SOURCE_REQUEST_CODE override fun toResult(): PaymentFlowResult.Unvalidated { return PaymentFlowResult.Unvalidated( source = source, stripeAccountId = stripeAccountId ) } } @Parcelize data class ErrorArgs( internal val exception: StripeException, override val requestCode: Int ) : Args() { override fun toResult(): PaymentFlowResult.Unvalidated { return PaymentFlowResult.Unvalidated( exception = exception ) } internal companion object : Parceler<ErrorArgs> { override fun create(parcel: Parcel): ErrorArgs { return ErrorArgs( exception = parcel.readSerializable() as StripeException, requestCode = parcel.readInt() ) } override fun ErrorArgs.write(parcel: Parcel, flags: Int) { parcel.writeSerializable(exception) parcel.writeInt(requestCode) } } } companion object { fun create( stripeIntent: StripeIntent, stripeAccountId: String? = null ): Args { return when (stripeIntent) { is PaymentIntent -> { PaymentIntentArgs(stripeIntent, stripeAccountId) } is SetupIntent -> { SetupIntentArgs(stripeIntent, stripeAccountId) } } } } } }
mit
8c72381811642c3b77586528581bd2e9
32.942029
88
0.580914
5.761378
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/ml/CardDetect.kt
1
4281
package com.stripe.android.stripecardscan.payment.ml import android.content.Context import android.graphics.Bitmap import android.graphics.Rect import android.util.Size import com.stripe.android.camera.framework.image.cropCameraPreviewToSquare import com.stripe.android.camera.framework.image.hasOpenGl31 import com.stripe.android.camera.framework.image.scale import com.stripe.android.stripecardscan.framework.FetchedData import com.stripe.android.stripecardscan.framework.image.MLImage import com.stripe.android.stripecardscan.framework.image.toMLImage import com.stripe.android.stripecardscan.framework.ml.TFLAnalyzerFactory import com.stripe.android.stripecardscan.framework.ml.TensorFlowLiteAnalyzer import com.stripe.android.stripecardscan.framework.util.indexOfMax import org.tensorflow.lite.Interpreter import java.nio.ByteBuffer import kotlin.math.max private val TRAINED_IMAGE_SIZE = Size(224, 224) /** model returns whether or not there is a card present */ private const val NUM_CLASS = 3 internal class CardDetect private constructor(interpreter: Interpreter) : TensorFlowLiteAnalyzer< CardDetect.Input, ByteBuffer, CardDetect.Prediction, Array<FloatArray> >(interpreter) { companion object { /** * Convert a camera preview image into a CardDetect input */ fun cameraPreviewToInput( cameraPreviewImage: Bitmap, previewBounds: Rect, cardFinder: Rect ) = Input( cropCameraPreviewToSquare(cameraPreviewImage, previewBounds, cardFinder) .scale(TRAINED_IMAGE_SIZE) .toMLImage() ) } data class Input(val cardDetectImage: MLImage) /** * A prediction returned by this analyzer. */ data class Prediction( val side: Side, val noCardProbability: Float, val noPanProbability: Float, val panProbability: Float ) { val maxConfidence = max(max(noCardProbability, noPanProbability), panProbability) /** * Force a generic toString method to prevent leaking information about this class' * parameters after R8. Without this method, this `data class` will automatically generate a * toString which retains the original names of the parameters even after obfuscation. */ override fun toString(): String { return "Prediction" } enum class Side { NO_CARD, NO_PAN, PAN } } override suspend fun interpretMLOutput(data: Input, mlOutput: Array<FloatArray>): Prediction { val side = when (val index = mlOutput[0].indexOfMax()) { 0 -> Prediction.Side.NO_PAN 1 -> Prediction.Side.NO_CARD 2 -> Prediction.Side.PAN else -> throw EnumConstantNotPresentException( Prediction.Side::class.java, index.toString() ) } return Prediction( side = side, noPanProbability = mlOutput[0][0], noCardProbability = mlOutput[0][1], panProbability = mlOutput[0][2] ) } override suspend fun transformData(data: Input): ByteBuffer = data.cardDetectImage.getData() override suspend fun executeInference( tfInterpreter: Interpreter, data: ByteBuffer ): Array<FloatArray> { val mlOutput = arrayOf(FloatArray(NUM_CLASS)) tfInterpreter.run(data, mlOutput) return mlOutput } /** * A factory for creating instances of this analyzer. */ class Factory( context: Context, fetchedModel: FetchedData, threads: Int = DEFAULT_THREADS ) : TFLAnalyzerFactory<Input, Prediction, CardDetect>(context, fetchedModel) { companion object { private const val USE_GPU = false private const val DEFAULT_THREADS = 4 } override val tfOptions: Interpreter.Options = Interpreter .Options() .setUseNNAPI(USE_GPU && hasOpenGl31(context)) .setNumThreads(threads) override suspend fun newInstance(): CardDetect? = createInterpreter()?.let { CardDetect(it) } } }
mit
08a40196044addefe5091a8208629878
32.186047
100
0.653352
4.618123
false
false
false
false
stripe/stripe-android
financial-connections/src/test/java/com/stripe/android/financialconnections/PascalCase.kt
1
2209
package com.stripe.android.financialconnections import com.stripe.android.financialconnections.model.FinancialConnectionsAccountFixtures import com.stripe.android.financialconnections.model.FinancialConnectionsAccountList import com.stripe.android.financialconnections.model.FinancialConnectionsSession import com.stripe.android.model.BankAccount import com.stripe.android.model.Token import java.util.Date val financialConnectionsSessionWithNoMoreAccounts = FinancialConnectionsSession( id = "las_no_more", clientSecret = ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET, accountsNew = FinancialConnectionsAccountList( listOf( FinancialConnectionsAccountFixtures.CREDIT_CARD, FinancialConnectionsAccountFixtures.CHECKING_ACCOUNT ), false, "url", 2 ), livemode = true ) val financialConnectionsSessionWithMoreAccounts = FinancialConnectionsSession( id = "las_has_more", clientSecret = ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET, accountsNew = FinancialConnectionsAccountList( data = listOf( FinancialConnectionsAccountFixtures.CREDIT_CARD, FinancialConnectionsAccountFixtures.CHECKING_ACCOUNT ), hasMore = true, url = "url", count = 2, totalCount = 3 ), livemode = true ) val moreFinancialConnectionsAccountList = FinancialConnectionsAccountList( data = listOf(FinancialConnectionsAccountFixtures.SAVINGS_ACCOUNT), hasMore = false, url = "url", count = 1, totalCount = 3 ) val bankAccountToken = Token( id = "tok_189fi32eZvKYlo2Ct0KZvU5Y", livemode = false, created = Date(1462905355L * 1000L), used = false, type = Token.Type.BankAccount, bankAccount = BankAccount( id = "ba_1H3NOMCRMbs6FrXfahj", accountHolderName = "Test Bank Account", accountHolderType = BankAccount.Type.Individual, bankName = "STRIPE TEST BANK", countryCode = "US", currency = "usd", fingerprint = "wxXSAD5idPUzgBEz", last4 = "6789", routingNumber = "110000000", status = BankAccount.Status.New ) )
mit
5aed63ebc38a9e5d9544abcd72d705b8
31.970149
88
0.70756
4.631027
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Split.kt
1
4115
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDIndex import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.linalg.api.buffer.DataType import org.nd4j.linalg.factory.Nd4j import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.guava.primitives.Ints import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of split.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/split.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["Split"],frameworkName = "onnx") class Split : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { var inputVariable = sd.getVariable(op.inputsToOp[0]) val splitDim = if(attributes.containsKey("axis")) { attributes["axis"] as Long } else { 0 as Long } if(op.inputsToOp.size > 1) { val split = sd.getVariable(op.inputsToOp[1]) val splitOutput = sd.split(outputNames.toTypedArray(),inputVariable,split,splitDim.toInt()) return retOutput(splitOutput) } else if(attributes.containsKey("split")) { val numSplits = attributes["split"] as List<Long> val splitConst = sd.constant(Nd4j.create(Nd4j.createBuffer(Ints.toArray(numSplits)))).castTo(DataType.INT64) val splitOutput = sd.splitV(outputNames.toTypedArray(),inputVariable,splitConst,numSplits.size,splitDim.toInt()) return retOutput(splitOutput) } else { val inputShape = sd.shape(inputVariable) val numSplits = inputShape.get(SDIndex.point(splitDim)).div(outputNames.size.toDouble()).castTo( DataType.INT64) val splitOutput = sd.split(outputNames.toTypedArray(),inputVariable,numSplits,splitDim.toInt()) val retMap = mutableMapOf<String,List<SDVariable>>() splitOutput.toList().forEach { retMap[it.name()] = listOf(it) } return retMap } } fun retOutput(vars: Array<SDVariable>): Map<String,List<SDVariable>> { val ret = HashMap<String,List<SDVariable>>() for(sdVar in vars) { ret[sdVar.name()] = listOf(sdVar) } return ret } }
apache-2.0
4d3d73a221c48b495cca00bf02986e7c
44.230769
184
0.679708
4.148185
false
false
false
false
AndroidX/androidx
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/ProgressIndicatorSamples.kt
3
4149
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.samples import androidx.annotation.Sampled import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.OutlinedButton import androidx.compose.material3.ProgressIndicatorDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Preview @Sampled @Composable fun LinearProgressIndicatorSample() { var progress by remember { mutableStateOf(0.1f) } val animatedProgress by animateFloatAsState( targetValue = progress, animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec ) Column(horizontalAlignment = Alignment.CenterHorizontally) { LinearProgressIndicator( modifier = Modifier.semantics(mergeDescendants = true) {}.padding(10.dp), progress = animatedProgress, ) Spacer(Modifier.requiredHeight(30.dp)) OutlinedButton( modifier = Modifier.semantics { val progressPercent = (progress * 100).toInt() if (progressPercent in progressBreakpoints) { stateDescription = "Progress $progressPercent%" } }, onClick = { if (progress < 1f) progress += 0.1f } ) { Text("Increase") } } } @Preview @Sampled @Composable fun IndeterminateLinearProgressIndicatorSample() { Column(horizontalAlignment = Alignment.CenterHorizontally) { LinearProgressIndicator( modifier = Modifier.semantics(mergeDescendants = true) {}.padding(10.dp) ) } } @Preview @Sampled @Composable fun CircularProgressIndicatorSample() { var progress by remember { mutableStateOf(0.1f) } val animatedProgress by animateFloatAsState( targetValue = progress, animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec ) Column(horizontalAlignment = Alignment.CenterHorizontally) { CircularProgressIndicator(progress = animatedProgress) Spacer(Modifier.requiredHeight(30.dp)) OutlinedButton( modifier = Modifier.semantics { val progressPercent = (progress * 100).toInt() if (progressPercent in progressBreakpoints) { stateDescription = "Progress $progressPercent%" } }, onClick = { if (progress < 1f) progress += 0.1f } ) { Text("Increase") } } } @Preview @Sampled @Composable fun IndeterminateCircularProgressIndicatorSample() { Column(horizontalAlignment = Alignment.CenterHorizontally) { CircularProgressIndicator() } } private val progressBreakpoints = listOf(20, 40, 60, 80, 100)
apache-2.0
a8eaf2c9e390e24bc7fbfe24904e7850
32.731707
85
0.707881
4.99278
false
false
false
false
colesadam/hill-lists
app/src/main/java/uk/colessoft/android/hilllist/ui/activity/HillDetailActivity.kt
1
3162
package uk.colessoft.android.hilllist.ui.activity import android.app.DatePickerDialog import android.app.Dialog import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.widget.DatePicker import android.widget.TextView import androidx.lifecycle.ViewModelProviders import uk.colessoft.android.hilllist.R import uk.colessoft.android.hilllist.ui.activity.dialogs.BaseActivity import uk.colessoft.android.hilllist.ui.fragment.HillDetailFragment import uk.colessoft.android.hilllist.domain.HillDetail import uk.colessoft.android.hilllist.ui.viewmodel.HillDetailViewModel import uk.colessoft.android.hilllist.ui.viewmodel.HillListViewModel import uk.colessoft.android.hilllist.ui.viewmodel.ViewModelFactory import java.util.* import javax.inject.Inject class HillDetailActivity : BaseActivity() { private val osLink: String? = null private val hillDetail: HillDetail? = null private var mYear: Int = 0 private var mMonth: Int = 0 private var mDay: Int = 0 private val mDateSetListener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth -> mYear = year mMonth = monthOfYear mDay = dayOfMonth updateDisplay() } private val dateClimbed: TextView? = null private val realDate = Date() private val calendar = GregorianCalendar() private val hillnameView: TextView? = null private val hillheight: TextView? = null @Inject lateinit var vmFactory: ViewModelFactory<HillDetailViewModel> lateinit var vm: HillDetailViewModel override fun onCreateDialog(id: Int): Dialog? { calendar.setTime(realDate) when (id) { DATE_DIALOG_ID -> { mYear = calendar.get(Calendar.YEAR) mMonth = calendar.get(Calendar.MONTH) mDay = calendar.get(Calendar.DAY_OF_MONTH) return DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay) } MARK_HILL_CLIMBED_DIALOG -> { } } return null } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) vm = ViewModelProviders.of(this, vmFactory)[HillDetailViewModel::class.java] updateFromPreferences() setContentView(R.layout.hill_detail_fragment) val fragment = supportFragmentManager .findFragmentById(R.id.hill_detail_fragment) as HillDetailFragment? } private fun updateDisplay() { dateClimbed!!.text = StringBuilder().append(mDay).append("/") .append(mMonth + 1).append("/").append(mYear) } private fun updateFromPreferences() { val context = applicationContext val prefs = PreferenceManager .getDefaultSharedPreferences(context) val useMetricHeights = prefs.getBoolean( PreferencesActivity.PREF_METRIC_HEIGHTS, false) } companion object { private val DATE_DIALOG_ID = 0 private val MARK_HILL_CLIMBED_DIALOG = 1 } }
mit
4299d58071b4e332131a50f3045e7405
28.830189
110
0.690702
4.622807
false
false
false
false
twilio/video-quickstart-android
exampleCustomVideoCapturer/src/main/java/com/twilio/video/examples/customcapturer/ViewCapturer.kt
1
4156
package com.twilio.video.examples.customcapturer import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.os.Handler import android.os.Looper import android.os.SystemClock import android.view.View import com.twilio.video.Rgba8888Buffer import com.twilio.video.VideoCapturer import com.twilio.video.VideoDimensions import com.twilio.video.VideoFormat import java.nio.ByteBuffer import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean import tvi.webrtc.CapturerObserver import tvi.webrtc.SurfaceTextureHelper import tvi.webrtc.VideoFrame /** * ViewCapturer demonstrates how to implement a custom [VideoCapturer]. This class * captures the contents of a provided view and signals the [tvi.webrtc.CapturerObserver] when * the frame is available. */ class ViewCapturer(private val view: View) : VideoCapturer { private val handler = Handler(Looper.getMainLooper()) private var capturerObserver: CapturerObserver? = null private val started = AtomicBoolean(false) private val viewCapturer = { val dropFrame = view.width == 0 || view.height == 0 // Only capture the view if the dimensions have been established if (!dropFrame) { // Draw view into bitmap backed canvas val measuredWidth = View.MeasureSpec.makeMeasureSpec( view.width, View.MeasureSpec.EXACTLY ) val measuredHeight = View.MeasureSpec.makeMeasureSpec( view.height, View.MeasureSpec.EXACTLY ) view.measure(measuredWidth, measuredHeight) view.layout(0, 0, view.measuredWidth, view.measuredHeight) val viewBitmap = Bitmap.createBitmap( view.width, view.height, Bitmap.Config.ARGB_8888 ) val viewCanvas = Canvas(viewBitmap) view.draw(viewCanvas) // Extract the frame from the bitmap val bytes = viewBitmap.byteCount val buffer = ByteBuffer.allocate(bytes) viewBitmap.copyPixelsToBuffer(buffer) // Create video frame val captureTimeNs = TimeUnit.MILLISECONDS.toNanos(SystemClock.elapsedRealtime()) val videoBuffer: VideoFrame.Buffer = Rgba8888Buffer(buffer, view.width, view.height) val videoFrame = VideoFrame(videoBuffer, 0, captureTimeNs) // Notify the observer if (started.get()) { capturerObserver?.onFrameCaptured(videoFrame) videoFrame.release() } } // Schedule the next capture if (started.get()) { scheduleNextCapture() } } override fun getCaptureFormat(): VideoFormat { val videoDimensions = VideoDimensions(view.width, view.height) return VideoFormat(videoDimensions, 30) } /** * Returns true because we are capturing screen content. */ override fun isScreencast(): Boolean { return true } override fun initialize( surfaceTextureHelper: SurfaceTextureHelper, context: Context, capturerObserver: CapturerObserver ) { this.capturerObserver = capturerObserver } override fun startCapture(width: Int, height: Int, framerate: Int) { started.set(true) // Notify capturer API that the capturer has started val capturerStarted = handler.postDelayed(viewCapturer, VIEW_CAPTURER_FRAMERATE_MS.toLong()) capturerObserver?.onCapturerStarted(capturerStarted) } /** * Stop capturing frames. Note that the SDK cannot receive frames once this has been invoked. */ override fun stopCapture() { started.set(false) handler.removeCallbacks(viewCapturer) capturerObserver?.onCapturerStopped() } private fun scheduleNextCapture() { handler.postDelayed(viewCapturer, VIEW_CAPTURER_FRAMERATE_MS.toLong()) } companion object { private const val VIEW_CAPTURER_FRAMERATE_MS = 100 } }
mit
14bff00f59f97e7560fa60b405fc1a7f
32.516129
100
0.660731
4.755149
false
false
false
false
androidx/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/input/ScrollContainerInfo.kt
3
4559
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.modifier.ModifierLocalConsumer import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ModifierLocalReadScope import androidx.compose.ui.modifier.ProvidableModifierLocal import androidx.compose.ui.modifier.modifierLocalConsumer import androidx.compose.ui.modifier.modifierLocalOf import androidx.compose.ui.platform.debugInspectorInfo /** * Represents a component that handles scroll events, so that other components in the hierarchy * can adjust their behaviour. * @See [provideScrollContainerInfo] and [consumeScrollContainerInfo] */ interface ScrollContainerInfo { /** @return whether this component handles horizontal scroll events */ fun canScrollHorizontally(): Boolean /** @return whether this component handles vertical scroll events */ fun canScrollVertically(): Boolean } /** @return whether this container handles either horizontal or vertical scroll events */ fun ScrollContainerInfo.canScroll() = canScrollVertically() || canScrollHorizontally() /** * A modifier to query whether there are any parents in the hierarchy that handle scroll events. * The [ScrollContainerInfo] provided in [consumer] will recursively look for ancestors if the * nearest parent does not handle scroll events in the queried direction. * This can be used to delay UI changes in cases where a pointer event may later become a scroll, * cancelling any existing press or other gesture. * * @sample androidx.compose.ui.samples.ScrollableContainerSample */ @OptIn(ExperimentalComposeUiApi::class) fun Modifier.consumeScrollContainerInfo(consumer: (ScrollContainerInfo?) -> Unit): Modifier = modifierLocalConsumer { consumer(ModifierLocalScrollContainerInfo.current) } /** * A Modifier that indicates that this component handles scroll events. Use * [consumeScrollContainerInfo] to query whether there is a parent in the hierarchy that is * a [ScrollContainerInfo]. */ fun Modifier.provideScrollContainerInfo(scrollContainerInfo: ScrollContainerInfo): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "provideScrollContainerInfo" value = scrollContainerInfo }) { remember(scrollContainerInfo) { ScrollContainerInfoModifierLocal(scrollContainerInfo) } } /** * ModifierLocal to propagate ScrollableContainer throughout the hierarchy. * This Modifier will recursively check for ancestor ScrollableContainers, * if the current ScrollableContainer does not handle scroll events in a particular direction. */ private class ScrollContainerInfoModifierLocal( private val scrollContainerInfo: ScrollContainerInfo, ) : ScrollContainerInfo, ModifierLocalProvider<ScrollContainerInfo?>, ModifierLocalConsumer { private var parent: ScrollContainerInfo? by mutableStateOf(null) override val key: ProvidableModifierLocal<ScrollContainerInfo?> = ModifierLocalScrollContainerInfo override val value: ScrollContainerInfoModifierLocal = this override fun onModifierLocalsUpdated(scope: ModifierLocalReadScope) = with(scope) { parent = ModifierLocalScrollContainerInfo.current } override fun canScrollHorizontally(): Boolean { return scrollContainerInfo.canScrollHorizontally() || parent?.canScrollHorizontally() == true } override fun canScrollVertically(): Boolean { return scrollContainerInfo.canScrollVertically() || parent?.canScrollVertically() == true } } internal val ModifierLocalScrollContainerInfo = modifierLocalOf<ScrollContainerInfo?> { null }
apache-2.0
bd72fb7b3770a98e0d03fb2a8483fcd0
40.081081
97
0.781531
5.258362
false
false
false
false
androidx/androidx
biometric/integration-tests/testapp/src/main/java/androidx/biometric/integration/testapp/LoggingUtils.kt
3
2626
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.biometric.integration.testapp import android.annotation.SuppressLint import android.widget.TextView import androidx.biometric.BiometricManager import androidx.biometric.BiometricPrompt /** * A bundle key used to save and restore the log text for a test activity. */ internal const val KEY_LOG_TEXT = "key_log_text" /** * Converts an authentication status code to a string that represents the status. */ internal fun Int.toAuthenticationStatusString(): String = when (this) { BiometricManager.BIOMETRIC_SUCCESS -> "SUCCESS" BiometricManager.BIOMETRIC_STATUS_UNKNOWN -> "STATUS_UNKNOWN" BiometricManager.BIOMETRIC_ERROR_UNSUPPORTED -> "ERROR_UNSUPPORTED" BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> "ERROR_HW_UNAVAILABLE" BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> "ERROR_NONE_ENROLLED" BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> "ERROR_NO_HARDWARE" BiometricManager.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED -> "ERROR_SECURITY_UPDATE_REQUIRED" else -> "Unrecognized error: $this" } /** * Converts an authentication result object to a string that represents its contents. */ internal fun BiometricPrompt.AuthenticationResult.toDataString(): String { val typeString = authenticationType.toAuthenticationTypeString() return "crypto = $cryptoObject, type = $typeString" } /** * Converts an authentication result type to a string that represents the authentication method. */ private fun Int.toAuthenticationTypeString(): String = when (this) { BiometricPrompt.AUTHENTICATION_RESULT_TYPE_UNKNOWN -> "UNKNOWN" BiometricPrompt.AUTHENTICATION_RESULT_TYPE_BIOMETRIC -> "BIOMETRIC" BiometricPrompt.AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL -> "DEVICE_CREDENTIAL" else -> "Unrecognized type: $this" } /** * Adds a new line with the given [message] to the beginning of this text view. */ @SuppressLint("SetTextI18n") internal fun TextView.prependLogMessage(message: CharSequence) { text = "$message\n$text" }
apache-2.0
f4ad2279f55c858da80d96785b2c24b2
38.208955
97
0.760472
4.319079
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/selection/TextFieldSelectionManager.kt
3
34686
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text.selection import androidx.compose.foundation.text.DefaultCursorThickness import androidx.compose.foundation.text.Handle import androidx.compose.foundation.text.HandleState import androidx.compose.foundation.text.InternalFoundationTextApi import androidx.compose.foundation.text.TextDragObserver import androidx.compose.foundation.text.TextFieldState import androidx.compose.foundation.text.UndoManager import androidx.compose.foundation.text.ValidatingEmptyOffsetMappingIdentity import androidx.compose.foundation.text.detectDownAndDragGesturesWithObserver import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.hapticfeedback.HapticFeedback import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.ClipboardManager import androidx.compose.ui.platform.TextToolbar import androidx.compose.ui.platform.TextToolbarStatus import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.input.getSelectedText import androidx.compose.ui.text.input.getTextAfterSelection import androidx.compose.ui.text.input.getTextBeforeSelection import androidx.compose.ui.text.style.ResolvedTextDirection import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import kotlin.math.absoluteValue import kotlin.math.max import kotlin.math.min /** * A bridge class between user interaction to the text field selection. */ internal class TextFieldSelectionManager( val undoManager: UndoManager? = null ) { /** * The current [OffsetMapping] for text field. */ internal var offsetMapping: OffsetMapping = ValidatingEmptyOffsetMappingIdentity /** * Called when the input service updates the values in [TextFieldValue]. */ internal var onValueChange: (TextFieldValue) -> Unit = {} /** * The current [TextFieldState]. */ internal var state: TextFieldState? = null /** * The current [TextFieldValue]. */ internal var value: TextFieldValue by mutableStateOf(TextFieldValue()) /** * Visual transformation of the text field's text. Used to check if certain toolbar options * are permitted. For example, 'cut' will not be available is it is password transformation. */ internal var visualTransformation: VisualTransformation = VisualTransformation.None /** * [ClipboardManager] to perform clipboard features. */ internal var clipboardManager: ClipboardManager? = null /** * [TextToolbar] to show floating toolbar(post-M) or primary toolbar(pre-M). */ var textToolbar: TextToolbar? = null /** * [HapticFeedback] handle to perform haptic feedback. */ var hapticFeedBack: HapticFeedback? = null /** * [FocusRequester] used to request focus for the TextField. */ var focusRequester: FocusRequester? = null /** * Defines if paste and cut toolbar menu actions should be shown */ var editable by mutableStateOf(true) /** * The beginning position of the drag gesture. Every time a new drag gesture starts, it wil be * recalculated. */ private var dragBeginPosition = Offset.Zero /** * The beginning offset of the drag gesture translated into position in text. Every time a * new drag gesture starts, it wil be recalculated. * Unlike [dragBeginPosition] that is relative to the decoration box, * [dragBeginOffsetInText] represents index in text. Essentially, it is equal to * `layoutResult.getOffsetForPosition(dragBeginPosition)`. */ private var dragBeginOffsetInText: Int? = null /** * The total distance being dragged of the drag gesture. Every time a new drag gesture starts, * it will be zeroed out. */ private var dragTotalDistance = Offset.Zero /** * A flag to check if a selection or cursor handle is being dragged, and which handle is being * dragged. * If this value is non-null, then onPress will not select any text. * This value will be set to non-null when either handle is being dragged, and be reset to null * when the dragging is stopped. */ var draggingHandle: Handle? by mutableStateOf(null) private set var currentDragPosition: Offset? by mutableStateOf(null) private set /** * The old [TextFieldValue] before entering the selection mode on long press. Used to exit * the selection mode. */ private var oldValue: TextFieldValue = TextFieldValue() /** * [TextDragObserver] for long press and drag to select in TextField. */ internal val touchSelectionObserver = object : TextDragObserver { override fun onDown(point: Offset) { // Not supported for long-press-drag. } override fun onUp() { // Nothing to do. } override fun onStart(startPoint: Offset) { if (draggingHandle != null) return // While selecting by long-press-dragging, the "end" of the selection is always the one // being controlled by the drag. draggingHandle = Handle.SelectionEnd // ensuring that current action mode (selection toolbar) is invalidated hideSelectionToolbar() // Long Press at the blank area, the cursor should show up at the end of the line. if (state?.layoutResult?.isPositionOnText(startPoint) != true) { state?.layoutResult?.let { layoutResult -> val offset = offsetMapping.transformedToOriginal( layoutResult.getLineEnd( layoutResult.getLineForVerticalPosition(startPoint.y) ) ) hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove) val newValue = createTextFieldValue( annotatedString = value.annotatedString, selection = TextRange(offset, offset) ) enterSelectionMode() onValueChange(newValue) return } } // selection never started if (value.text.isEmpty()) return enterSelectionMode() state?.layoutResult?.let { layoutResult -> val offset = layoutResult.getOffsetForPosition(startPoint) updateSelection( value = value, transformedStartOffset = offset, transformedEndOffset = offset, isStartHandle = false, adjustment = SelectionAdjustment.Word ) dragBeginOffsetInText = offset } dragBeginPosition = startPoint currentDragPosition = dragBeginPosition dragTotalDistance = Offset.Zero } override fun onDrag(delta: Offset) { // selection never started, did not consume any drag if (value.text.isEmpty()) return dragTotalDistance += delta state?.layoutResult?.let { layoutResult -> currentDragPosition = dragBeginPosition + dragTotalDistance val startOffset = dragBeginOffsetInText ?: layoutResult.getOffsetForPosition( position = dragBeginPosition, coerceInVisibleBounds = false ) val endOffset = layoutResult.getOffsetForPosition( position = currentDragPosition!!, coerceInVisibleBounds = false ) updateSelection( value = value, transformedStartOffset = startOffset, transformedEndOffset = endOffset, isStartHandle = false, adjustment = SelectionAdjustment.Word ) } state?.showFloatingToolbar = false } override fun onStop() { draggingHandle = null currentDragPosition = null state?.showFloatingToolbar = true if (textToolbar?.status == TextToolbarStatus.Hidden) showSelectionToolbar() dragBeginOffsetInText = null } override fun onCancel() {} } internal val mouseSelectionObserver = object : MouseSelectionObserver { override fun onExtend(downPosition: Offset): Boolean { state?.layoutResult?.let { layoutResult -> val startOffset = offsetMapping.originalToTransformed(value.selection.start) val clickOffset = layoutResult.getOffsetForPosition(downPosition) updateSelection( value = value, transformedStartOffset = startOffset, transformedEndOffset = clickOffset, isStartHandle = false, adjustment = SelectionAdjustment.None ) return true } return false } override fun onExtendDrag(dragPosition: Offset): Boolean { if (value.text.isEmpty()) return false state?.layoutResult?.let { layoutResult -> val startOffset = offsetMapping.originalToTransformed(value.selection.start) val dragOffset = layoutResult.getOffsetForPosition( position = dragPosition, coerceInVisibleBounds = false ) updateSelection( value = value, transformedStartOffset = startOffset, transformedEndOffset = dragOffset, isStartHandle = false, adjustment = SelectionAdjustment.None ) return true } return false } override fun onStart( downPosition: Offset, adjustment: SelectionAdjustment ): Boolean { focusRequester?.requestFocus() dragBeginPosition = downPosition state?.layoutResult?.let { layoutResult -> dragBeginOffsetInText = layoutResult.getOffsetForPosition(downPosition) val clickOffset = layoutResult.getOffsetForPosition(dragBeginPosition) updateSelection( value = value, transformedStartOffset = clickOffset, transformedEndOffset = clickOffset, isStartHandle = false, adjustment = adjustment ) return true } return false } override fun onDrag(dragPosition: Offset, adjustment: SelectionAdjustment): Boolean { if (value.text.isEmpty()) return false state?.layoutResult?.let { layoutResult -> val dragOffset = layoutResult.getOffsetForPosition( position = dragPosition, coerceInVisibleBounds = false ) updateSelection( value = value, transformedStartOffset = dragBeginOffsetInText!!, transformedEndOffset = dragOffset, isStartHandle = false, adjustment = adjustment ) return true } return false } } /** * [TextDragObserver] for dragging the selection handles to change the selection in TextField. */ internal fun handleDragObserver(isStartHandle: Boolean): TextDragObserver = object : TextDragObserver { override fun onDown(point: Offset) { draggingHandle = if (isStartHandle) Handle.SelectionStart else Handle.SelectionEnd currentDragPosition = getAdjustedCoordinates(getHandlePosition(isStartHandle)) } override fun onUp() { draggingHandle = null currentDragPosition = null } override fun onStart(startPoint: Offset) { // The position of the character where the drag gesture should begin. This is in // the composable coordinates. dragBeginPosition = getAdjustedCoordinates(getHandlePosition(isStartHandle)) currentDragPosition = dragBeginPosition // Zero out the total distance that being dragged. dragTotalDistance = Offset.Zero draggingHandle = if (isStartHandle) Handle.SelectionStart else Handle.SelectionEnd state?.showFloatingToolbar = false } override fun onDrag(delta: Offset) { dragTotalDistance += delta state?.layoutResult?.value?.let { layoutResult -> currentDragPosition = dragBeginPosition + dragTotalDistance val startOffset = if (isStartHandle) { layoutResult.getOffsetForPosition(currentDragPosition!!) } else { offsetMapping.originalToTransformed(value.selection.start) } val endOffset = if (isStartHandle) { offsetMapping.originalToTransformed(value.selection.end) } else { layoutResult.getOffsetForPosition(currentDragPosition!!) } updateSelection( value = value, transformedStartOffset = startOffset, transformedEndOffset = endOffset, isStartHandle = isStartHandle, adjustment = SelectionAdjustment.Character ) } state?.showFloatingToolbar = false } override fun onStop() { draggingHandle = null currentDragPosition = null state?.showFloatingToolbar = true if (textToolbar?.status == TextToolbarStatus.Hidden) showSelectionToolbar() } override fun onCancel() {} } /** * [TextDragObserver] for dragging the cursor to change the selection in TextField. */ internal fun cursorDragObserver(): TextDragObserver = object : TextDragObserver { override fun onDown(point: Offset) { draggingHandle = Handle.Cursor currentDragPosition = getAdjustedCoordinates(getHandlePosition(true)) } override fun onUp() { draggingHandle = null currentDragPosition = null } override fun onStart(startPoint: Offset) { // The position of the character where the drag gesture should begin. This is in // the composable coordinates. dragBeginPosition = getAdjustedCoordinates(getHandlePosition(true)) currentDragPosition = dragBeginPosition // Zero out the total distance that being dragged. dragTotalDistance = Offset.Zero draggingHandle = Handle.Cursor } override fun onDrag(delta: Offset) { dragTotalDistance += delta state?.layoutResult?.value?.let { layoutResult -> currentDragPosition = dragBeginPosition + dragTotalDistance val offset = offsetMapping.transformedToOriginal( layoutResult.getOffsetForPosition(currentDragPosition!!) ) val newSelection = TextRange(offset, offset) // Nothing changed, skip onValueChange hand hapticFeedback. if (newSelection == value.selection) return hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove) onValueChange( createTextFieldValue( annotatedString = value.annotatedString, selection = newSelection ) ) } } override fun onStop() { draggingHandle = null currentDragPosition = null } override fun onCancel() {} } /** * The method to record the required state values on entering the selection mode. * * Is triggered on long press or accessibility action. */ internal fun enterSelectionMode() { if (state?.hasFocus == false) { focusRequester?.requestFocus() } oldValue = value state?.showFloatingToolbar = true setHandleState(HandleState.Selection) } /** * The method to record the corresponding state values on exiting the selection mode. * * Is triggered on accessibility action. */ internal fun exitSelectionMode() { state?.showFloatingToolbar = false setHandleState(HandleState.None) } internal fun deselect(position: Offset? = null) { if (!value.selection.collapsed) { // if selection was not collapsed, set a default cursor location, otherwise // don't change the location of the cursor. val layoutResult = state?.layoutResult val newCursorOffset = if (position != null && layoutResult != null) { offsetMapping.transformedToOriginal( layoutResult.getOffsetForPosition(position) ) } else { value.selection.max } val newValue = value.copy(selection = TextRange(newCursorOffset)) onValueChange(newValue) } // If a new cursor position is given and the text is not empty, enter the // HandleState.Cursor state. val selectionMode = if (position != null && value.text.isNotEmpty()) { HandleState.Cursor } else { HandleState.None } setHandleState(selectionMode) hideSelectionToolbar() } /** * The method for copying text. * * If there is no selection, return. * Put the selected text into the [ClipboardManager], and cancel the selection, if * [cancelSelection] is true. * The text in the text field should be unchanged. * If [cancelSelection] is true, the new cursor offset should be at the end of the previous * selected text. */ internal fun copy(cancelSelection: Boolean = true) { if (value.selection.collapsed) return // TODO(b/171947959) check if original or transformed should be copied clipboardManager?.setText(value.getSelectedText()) if (!cancelSelection) return val newCursorOffset = value.selection.max val newValue = createTextFieldValue( annotatedString = value.annotatedString, selection = TextRange(newCursorOffset, newCursorOffset) ) onValueChange(newValue) setHandleState(HandleState.None) } /** * The method for pasting text. * * Get the text from [ClipboardManager]. If it's null, return. * The new text should be the text before the selected text, plus the text from the * [ClipboardManager], and plus the text after the selected text. * Then the selection should collapse, and the new cursor offset should be the end of the * newly added text. */ internal fun paste() { val text = clipboardManager?.getText() ?: return val newText = value.getTextBeforeSelection(value.text.length) + text + value.getTextAfterSelection(value.text.length) val newCursorOffset = value.selection.min + text.length val newValue = createTextFieldValue( annotatedString = newText, selection = TextRange(newCursorOffset, newCursorOffset) ) onValueChange(newValue) setHandleState(HandleState.None) undoManager?.forceNextSnapshot() } /** * The method for cutting text. * * If there is no selection, return. * Put the selected text into the [ClipboardManager]. * The new text should be the text before the selection plus the text after the selection. * And the new cursor offset should be between the text before the selection, and the text * after the selection. */ internal fun cut() { if (value.selection.collapsed) return // TODO(b/171947959) check if original or transformed should be cut clipboardManager?.setText(value.getSelectedText()) val newText = value.getTextBeforeSelection(value.text.length) + value.getTextAfterSelection(value.text.length) val newCursorOffset = value.selection.min val newValue = createTextFieldValue( annotatedString = newText, selection = TextRange(newCursorOffset, newCursorOffset) ) onValueChange(newValue) setHandleState(HandleState.None) undoManager?.forceNextSnapshot() } /*@VisibleForTesting*/ internal fun selectAll() { val newValue = createTextFieldValue( annotatedString = value.annotatedString, selection = TextRange(0, value.text.length) ) onValueChange(newValue) oldValue = oldValue.copy(selection = newValue.selection) state?.showFloatingToolbar = true } internal fun getHandlePosition(isStartHandle: Boolean): Offset { val offset = if (isStartHandle) value.selection.start else value.selection.end return getSelectionHandleCoordinates( textLayoutResult = state?.layoutResult!!.value, offset = offsetMapping.originalToTransformed(offset), isStart = isStartHandle, areHandlesCrossed = value.selection.reversed ) } internal fun getCursorPosition(density: Density): Offset { val offset = offsetMapping.originalToTransformed(value.selection.start) val layoutResult = state?.layoutResult!!.value val cursorRect = layoutResult.getCursorRect( offset.coerceIn(0, layoutResult.layoutInput.text.length) ) val x = with(density) { cursorRect.left + DefaultCursorThickness.toPx() / 2 } return Offset(x, cursorRect.bottom) } /** * This function get the selected region as a Rectangle region, and pass it to [TextToolbar] * to make the FloatingToolbar show up in the proper place. In addition, this function passes * the copy, paste and cut method as callbacks when "copy", "cut" or "paste" is clicked. */ internal fun showSelectionToolbar() { val isPassword = visualTransformation is PasswordVisualTransformation val copy: (() -> Unit)? = if (!value.selection.collapsed && !isPassword) { { copy() hideSelectionToolbar() } } else null val cut: (() -> Unit)? = if (!value.selection.collapsed && editable && !isPassword) { { cut() hideSelectionToolbar() } } else null val paste: (() -> Unit)? = if (editable && clipboardManager?.hasText() == true) { { paste() hideSelectionToolbar() } } else null val selectAll: (() -> Unit)? = if (value.selection.length != value.text.length) { { selectAll() } } else null textToolbar?.showMenu( rect = getContentRect(), onCopyRequested = copy, onPasteRequested = paste, onCutRequested = cut, onSelectAllRequested = selectAll ) } internal fun hideSelectionToolbar() { if (textToolbar?.status == TextToolbarStatus.Shown) { textToolbar?.hide() } } fun contextMenuOpenAdjustment(position: Offset) { state?.layoutResult?.let { layoutResult -> val offset = layoutResult.getOffsetForPosition(position) if (!value.selection.contains(offset)) { updateSelection( value = value, transformedStartOffset = offset, transformedEndOffset = offset, isStartHandle = false, adjustment = SelectionAdjustment.Word ) } } } /** * Check if the text in the text field changed. * When the content in the text field is modified, this method returns true. */ internal fun isTextChanged(): Boolean { return oldValue.text != value.text } /** * Calculate selected region as [Rect]. The top is the top of the first selected * line, and the bottom is the bottom of the last selected line. The left is the leftmost * handle's horizontal coordinates, and the right is the rightmost handle's coordinates. */ @OptIn(InternalFoundationTextApi::class) private fun getContentRect(): Rect { state?.let { val startOffset = state?.layoutCoordinates?.localToRoot(getHandlePosition(true)) ?: Offset.Zero val endOffset = state?.layoutCoordinates?.localToRoot(getHandlePosition(false)) ?: Offset.Zero val startTop = state?.layoutCoordinates?.localToRoot( Offset( 0f, it.layoutResult?.value?.getCursorRect( value.selection.start.coerceIn( 0, max(0, value.text.length - 1) ) )?.top ?: 0f ) )?.y ?: 0f val endTop = state?.layoutCoordinates?.localToRoot( Offset( 0f, it.layoutResult?.value?.getCursorRect( value.selection.end.coerceIn( 0, max(0, value.text.length - 1) ) )?.top ?: 0f ) )?.y ?: 0f val left = min(startOffset.x, endOffset.x) val right = max(startOffset.x, endOffset.x) val top = min(startTop, endTop) val bottom = max(startOffset.y, endOffset.y) + 25.dp.value * it.textDelegate.density.density return Rect(left, top, right, bottom) } return Rect.Zero } private fun updateSelection( value: TextFieldValue, transformedStartOffset: Int, transformedEndOffset: Int, isStartHandle: Boolean, adjustment: SelectionAdjustment ) { val transformedSelection = TextRange( offsetMapping.originalToTransformed(value.selection.start), offsetMapping.originalToTransformed(value.selection.end) ) val newTransformedSelection = getTextFieldSelection( textLayoutResult = state?.layoutResult?.value, rawStartOffset = transformedStartOffset, rawEndOffset = transformedEndOffset, previousSelection = if (transformedSelection.collapsed) null else transformedSelection, isStartHandle = isStartHandle, adjustment = adjustment ) val originalSelection = TextRange( start = offsetMapping.transformedToOriginal(newTransformedSelection.start), end = offsetMapping.transformedToOriginal(newTransformedSelection.end) ) if (originalSelection == value.selection) return hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove) val newValue = createTextFieldValue( annotatedString = value.annotatedString, selection = originalSelection ) onValueChange(newValue) // showSelectionHandleStart/End might be set to false when scrolled out of the view. // When the selection is updated, they must also be updated so that handles will be shown // or hidden correctly. state?.showSelectionHandleStart = isSelectionHandleInVisibleBound(true) state?.showSelectionHandleEnd = isSelectionHandleInVisibleBound(false) } private fun setHandleState(handleState: HandleState) { state?.let { it.handleState = handleState } } private fun createTextFieldValue( annotatedString: AnnotatedString, selection: TextRange ): TextFieldValue { return TextFieldValue( annotatedString = annotatedString, selection = selection ) } } @Composable internal fun TextFieldSelectionHandle( isStartHandle: Boolean, direction: ResolvedTextDirection, manager: TextFieldSelectionManager ) { val observer = remember(isStartHandle, manager) { manager.handleDragObserver(isStartHandle) } val position = manager.getHandlePosition(isStartHandle) SelectionHandle( position = position, isStartHandle = isStartHandle, direction = direction, handlesCrossed = manager.value.selection.reversed, modifier = Modifier.pointerInput(observer) { detectDownAndDragGesturesWithObserver(observer) }, content = null ) } /** * Whether the selection handle is in the visible bound of the TextField. */ internal fun TextFieldSelectionManager.isSelectionHandleInVisibleBound( isStartHandle: Boolean ): Boolean = state?.layoutCoordinates?.visibleBounds()?.containsInclusive( getHandlePosition(isStartHandle) ) ?: false // TODO(b/180075467) it should be part of PointerEvent API in one way or another internal expect val PointerEvent.isShiftPressed: Boolean /** * Optionally shows a magnifier widget, if the current platform supports it, for the current state * of a [TextFieldSelectionManager]. Should check [TextFieldSelectionManager.draggingHandle] to see * which handle is being dragged and then calculate the magnifier position for that handle. * * Actual implementations should as much as possible actually live in this common source set, _not_ * the platform-specific source sets. The actual implementations of this function should then just * delegate to those functions. */ internal expect fun Modifier.textFieldMagnifier(manager: TextFieldSelectionManager): Modifier internal fun calculateSelectionMagnifierCenterAndroid( manager: TextFieldSelectionManager, magnifierSize: IntSize ): Offset { // Never show the magnifier in an empty text field. if (manager.value.text.isEmpty()) return Offset.Unspecified val rawTextOffset = when (manager.draggingHandle) { null -> return Offset.Unspecified Handle.Cursor, Handle.SelectionStart -> manager.value.selection.start Handle.SelectionEnd -> manager.value.selection.end } val textOffset = manager.offsetMapping.originalToTransformed(rawTextOffset) .coerceIn(manager.value.text.indices) val layoutResult = manager.state?.layoutResult?.value ?: return Offset.Unspecified // Center vertically on the current line. // If the text hasn't been laid out yet, don't show the modifier. val offsetCenter = layoutResult.getBoundingBox(textOffset).center val containerCoordinates = manager.state?.layoutCoordinates ?: return Offset.Unspecified val fieldCoordinates = manager.state?.layoutResult?.innerTextFieldCoordinates ?: return Offset.Unspecified val localDragPosition = manager.currentDragPosition?.let { fieldCoordinates.localPositionOf(containerCoordinates, it) } ?: return Offset.Unspecified val dragX = localDragPosition.x val line = layoutResult.getLineForOffset(textOffset) val lineStartOffset = layoutResult.getLineStart(line) val lineEndOffset = layoutResult.getLineEnd(line, visibleEnd = true) val areHandlesCrossed = manager.value.selection.start > manager.value.selection.end val lineStart = layoutResult.getHorizontalPosition( lineStartOffset, isStart = true, areHandlesCrossed = areHandlesCrossed ) val lineEnd = layoutResult.getHorizontalPosition( lineEndOffset, isStart = false, areHandlesCrossed = areHandlesCrossed ) val lineMin = minOf(lineStart, lineEnd) val lineMax = maxOf(lineStart, lineEnd) val centerX = dragX.coerceIn(lineMin, lineMax) // Hide the magnifier when dragged too far (outside the horizontal bounds of how big the // magnifier actually is). See // https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/widget/Editor.java;l=5228-5231;drc=2fdb6bd709be078b72f011334362456bb758922c if ((dragX - centerX).absoluteValue > magnifierSize.width / 2) { return Offset.Unspecified } return containerCoordinates.localPositionOf( fieldCoordinates, Offset(centerX, offsetCenter.y) ) }
apache-2.0
4f8fce5dc8bc8739744d9f3f02a47f20
37.24366
178
0.624575
5.42732
false
false
false
false
solkin/drawa-android
app/src/main/java/com/tomclaw/drawa/util/CircleProgressView.kt
1
5591
package com.tomclaw.drawa.util import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import android.view.animation.LinearInterpolator import com.tomclaw.drawa.R import kotlin.math.min import kotlin.math.roundToInt /** * A subclass of [android.view.View] class for creating a custom circular progressBar * * * Created by Pedram on 2015-01-06. */ @Suppress("unused", "MemberVisibilityCanBePrivate") class CircleProgressView(context: Context, attrs: AttributeSet) : View(context, attrs) { /** * ProgressBar's line thickness */ var strokeWidth = 4f set(value) { field = value backgroundPaint.strokeWidth = value foregroundPaint.strokeWidth = value invalidate() requestLayout() //Because it should recalculate its bounds } @SuppressLint("AnimatorKeep") var progress = 0f set(value) { field = value invalidate() } var min = 0 set(value) { field = value invalidate() } var max = 100 set(value) { field = value invalidate() } /** * Start the progress at 12 o'clock */ private val startAngle = -90 var color = Color.DKGRAY set(value) { field = value backgroundPaint.color = adjustAlpha(value, 0.3f) foregroundPaint.color = value invalidate() requestLayout() } private val rectF: RectF = RectF() private val backgroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private val foregroundPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG) init { init(context, attrs) } private fun init(context: Context, attrs: AttributeSet) { val typedArray = context.theme.obtainStyledAttributes( attrs, R.styleable.CircleProgressView, 0, 0) //Reading values from the XML layout try { strokeWidth = typedArray.getDimension(R.styleable.CircleProgressView_progressBarThickness, strokeWidth) progress = typedArray.getFloat(R.styleable.CircleProgressView_progress, progress) color = typedArray.getInt(R.styleable.CircleProgressView_progressbarColor, color) min = typedArray.getInt(R.styleable.CircleProgressView_min, min) max = typedArray.getInt(R.styleable.CircleProgressView_max, max) } finally { typedArray.recycle() } backgroundPaint.color = adjustAlpha(color, 0.3f) backgroundPaint.style = Paint.Style.STROKE backgroundPaint.strokeWidth = strokeWidth foregroundPaint.color = color foregroundPaint.style = Paint.Style.STROKE foregroundPaint.strokeWidth = strokeWidth } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawOval(rectF, backgroundPaint) val angle = 360 * progress / max canvas.drawArc(rectF, startAngle.toFloat(), angle, false, foregroundPaint) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val height = getDefaultSize(suggestedMinimumHeight, heightMeasureSpec) val width = getDefaultSize(suggestedMinimumWidth, widthMeasureSpec) val min = min(width, height) setMeasuredDimension(min, min) rectF.set( 0 + strokeWidth / 2, 0 + strokeWidth / 2, min - strokeWidth / 2, min - strokeWidth / 2 ) } /** * Lighten the given color by the factor * * @param color The color to lighten * @param factor 0 to 4 * @return A brighter color */ fun lightenColor(color: Int, factor: Float): Int { val r = Color.red(color) * factor val g = Color.green(color) * factor val b = Color.blue(color) * factor val ir = min(255, r.toInt()) val ig = min(255, g.toInt()) val ib = min(255, b.toInt()) val ia = Color.alpha(color) return Color.argb(ia, ir, ig, ib) } /** * Transparent the given color by the factor * The more the factor closer to zero the more the color gets transparent * * @param color The color to transparent * @param factor 1.0f to 0.0f * @return int - A transplanted color */ fun adjustAlpha(color: Int, factor: Float): Int { val alpha = (Color.alpha(color) * factor).roundToInt() val red = Color.red(color) val green = Color.green(color) val blue = Color.blue(color) return Color.argb(alpha, red, green, blue) } /** * Set the progress with an animation. * Note that the [android.animation.ObjectAnimator] Class automatically set the progress * so don't call the [CircleProgressView.progress] directly within this method. * * @param progress The progress it should animate to it. * @param duration Progress animation time. */ @SuppressLint("AnimatorKeep") fun setProgressWithAnimation(progress: Float, duration: Long = 1500) { val objectAnimator = ObjectAnimator.ofFloat(this, "progress", progress) objectAnimator.duration = duration objectAnimator.interpolator = LinearInterpolator() objectAnimator.start() } }
apache-2.0
7078e928b577b7d0336a8828980e6075
31.695906
115
0.630656
4.601646
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/feedback/content/FeedbackContentPresenter.kt
1
1052
package com.intfocus.template.dashboard.feedback.content import com.intfocus.template.dashboard.feedback.FeedbackModelImpl import com.intfocus.template.model.callback.LoadDataCallback import com.intfocus.template.model.response.mine_page.FeedbackContent /** * @author liuruilin * @data 2017/12/6 * @describe */ class FeedbackContentPresenter : FeedbackContentContract.Presenter { private var mView: FeedbackContentContract.View? = null private var mModel: FeedbackModelImpl? = null constructor(model: FeedbackModelImpl, view: FeedbackContentContract.View) { this.mView = view this.mModel = model } override fun start() = Unit override fun getContent(id: Int) { mModel!!.getContent(id, callback = object : LoadDataCallback<FeedbackContent> { override fun onSuccess(data: FeedbackContent) { mView!!.showContent(data) } override fun onError(e: Throwable) { } override fun onComplete() { } }) } }
gpl-3.0
5bae92846429e40401a91da621c65e83
28.222222
87
0.675856
4.534483
false
false
false
false
tommykw/WalkThroughAnimation
app/src/main/java/com/github/tommykw/walkthrough/ViewPagerIndicator.kt
1
3222
package com.github.tommykw.walkthrough import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.support.v4.content.ContextCompat import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.View /** * Created by tommy on 2016/03/28. */ class ViewPagerIndicator @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { init { prepare(context) } private var radius = 0.0f private var distance = 0.0f private var wholeViewCount = 0 private var position = 0 private lateinit var viewPager: ViewPager private var indicatorCount = 5 private var defaultColor= ContextCompat.getColor(context, R.color.viewpager_indicator_default) private var selectorColor = ContextCompat.getColor(context, R.color.viewpager_indicator_selector) fun setIndicatorCount(count: Int) { indicatorCount = count } fun setIndicatorColor(defaultColorId: Int, selectorColorId: Int) { defaultColor = ContextCompat.getColor(context, defaultColorId) selectorColor = ContextCompat.getColor(context, selectorColorId) } fun setPosition(currentPosition: Int) { if (currentPosition < wholeViewCount) { position = currentPosition viewPager.let { it.currentItem = currentPosition } invalidate() } } fun setViewPager(vp: ViewPager) { viewPager = vp wholeViewCount = viewPager.adapter.let { it.count } viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageSelected(position: Int) { wholeViewCount = viewPager.adapter.let { it.count } setPosition(position) } override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} }) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val paint = Paint().apply { strokeWidth = 1.0f strokeCap = Paint.Cap.ROUND isAntiAlias = true } for (i in 0..wholeViewCount-1) { canvas.drawCircle( (width - (wholeViewCount - 1) * distance) / 2 + i * distance, height / 2.0f, radius, paint.apply { color = if (position == i) selectorColor else defaultColor style = Paint.Style.FILL_AND_STROKE } ) } } private fun prepare(context: Context) { radius = DisplayUtil.dipToPixcelFloat( context, resources.getInteger(R.integer.indicator_cirlce_diameter).toFloat() ) distance = DisplayUtil.dipToPixcelFloat( context, (resources.getInteger(R.integer.indicator_cirlce_diameter) * indicatorCount).toFloat() ) } }
apache-2.0
825b4643c941587c36b78978f89efe1e
32.915789
107
0.606766
4.889226
false
false
false
false
google/cross-device-sdk
crossdevice/src/main/kotlin/com/google/ambient/crossdevice/wakeup/StartComponentRequest.kt
1
4285
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ambient.crossdevice.wakeup import android.os.Build import androidx.annotation.RequiresApi import com.google.android.gms.dtdi.core.Extra import com.google.android.gms.dtdi.core.ExtraType import kotlin.collections.mutableListOf /** * A request to wake up a specified component on another device, and optionally deliver additional * information to it. Currently the only supported component type is Android Activities. */ @RequiresApi(Build.VERSION_CODES.O) class StartComponentRequest private constructor( internal val action: String, internal val reason: String, internal val extras: List<Extra>, ) { fun toBuilder() = Builder(this) class Builder() { @set:JvmSynthetic // Prefer the method that returns Builder below to allow chaining in Java var action: String? = null @set:JvmSynthetic // Prefer the method that returns Builder below to allow chaining in Java var reason: String? = null private val extras = mutableListOf<Extra>() internal constructor(startComponentRequest: StartComponentRequest) : this() { action = startComponentRequest.action reason = startComponentRequest.reason extras.addAll(startComponentRequest.extras) } /** * (Required) Sets the intent action used to determine the target of the wakeup request. * * This intent action is used to resolve the target component (only Activity targets are * currently supported) on the receiving device. */ fun setAction(action: String) = apply { this.action = action } /** (Required) Sets the user-visible reason for this request. */ fun setReason(reason: String) = apply { this.reason = reason } @SuppressWarnings("GmsCoreFirstPartyApiChecker") /** Adds an extra string to the wakeup request that will be provided to the targeted app. */ fun addExtra(key: String, value: String): Builder { extras.add(Extra(key, type = ExtraType.TYPE_STRING, stringExtra = value)) return this } @SuppressWarnings("GmsCoreFirstPartyApiChecker") /** Adds an extra boolean to the wakeup request that will be provided to the targeted app. */ fun addExtra(key: String, value: Boolean): Builder { extras.add(Extra(key, type = ExtraType.TYPE_BOOLEAN, booleanExtra = value)) return this } @SuppressWarnings("GmsCoreFirstPartyApiChecker") /** Adds an extra int to the wakeup request that will be provided to the targeted app. */ fun addExtra(key: String, value: Int): Builder { extras.add(Extra(key, type = ExtraType.TYPE_INT, intExtra = value)) return this } @SuppressWarnings("GmsCoreFirstPartyApiChecker") /** Adds an extra ByteArray to the wakeup request that will be provided to the targeted app. */ fun addExtra(key: String, value: ByteArray): Builder { extras.add(Extra(key, type = ExtraType.TYPE_BYTE_ARRAY, byteArrayExtra = value)) return this } /** * Builds the [StartComponentRequest] from this builder. * * @throws IllegalArgumentException if required parameters are not specified. */ @Throws(IllegalArgumentException::class) fun build(): StartComponentRequest { val action: String = requireNotNull(action) { "No action specified for request" } val reason: String = requireNotNull(reason) { "No reason specified for request" } return StartComponentRequest(action, reason, extras) } } } /** Convenience function for building a [StartComponentRequest]. */ @JvmSynthetic @RequiresApi(Build.VERSION_CODES.O) inline fun startComponentRequest(block: StartComponentRequest.Builder.() -> Unit) = StartComponentRequest.Builder().apply(block).build()
apache-2.0
e96f443bde7bdf323ee63bc79f5f8ddf
38.311927
99
0.723221
4.422085
false
false
false
false
mobapptuts/kotlin-webview
app/src/main/java/com/mobapptuts/kotlinwebview/ForwardHistoryAdapter.kt
2
1757
package com.mobapptuts.kotlinwebview import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebView import kotlinx.android.synthetic.main.web_item_history.view.* /** * Created by nigelhenshaw on 2017/09/07. */ class ForwardHistoryAdapter(val dialog: HistoryDialogFragment, val webview: WebView): RecyclerView.Adapter<ForwardHistoryAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val layoutInflator = LayoutInflater.from(parent.context) val webHistoryView = layoutInflator.inflate(R.layout.web_item_history, parent, false) return ViewHolder(webHistoryView) } override fun getItemCount() = webview.copyBackForwardList().size - webview.copyBackForwardList().currentIndex - 1 override fun onBindViewHolder(holder: ViewHolder, position: Int) { val webHistory = webview.copyBackForwardList() holder.title.text = webHistory.getItemAtIndex(webHistory.currentIndex + position + 1).title holder.favicon.setImageBitmap(webHistory.getItemAtIndex(webHistory.currentIndex + position + 1).favicon) holder.itemView.setOnClickListener { for (i in webHistory.currentIndex+1 until webHistory.size) { if (holder.title.text.equals(webHistory.getItemAtIndex(i).title)) { webview.goBackOrForward(i - webHistory.currentIndex) dialog.dismiss() break } } } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title = itemView.title val favicon = itemView.favicon } }
mit
4c885e8836429e12cc86cac2792d120d
39.883721
144
0.707456
4.493606
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/TutorialView.kt
1
3188
package com.habitrpg.android.habitica.ui import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import com.habitrpg.android.habitica.databinding.OverlayTutorialBinding import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.models.TutorialStep class TutorialView( context: Context, val step: TutorialStep, private val onReaction: OnTutorialReaction ) : FrameLayout(context) { private val binding = OverlayTutorialBinding.inflate(context.layoutInflater, this, true) private var tutorialTexts: List<String> = emptyList() private var currentTextIndex: Int = 0 private val isDisplayingLastStep: Boolean get() = currentTextIndex == tutorialTexts.size - 1 init { binding.speechBubbleView.setConfirmationButtonVisibility(View.GONE) binding.speechBubbleView.setShowNextListener(object : SpeechBubbleView.ShowNextListener { override fun showNextStep() { displayNextTutorialText() } }) binding.speechBubbleView.binding.completeButton.setOnClickListener { completeButtonClicked() } binding.speechBubbleView.binding.dismissButton.setOnClickListener { dismissButtonClicked() } binding.background.setOnClickListener { backgroundClicked() } } fun setTutorialText(text: String) { binding.speechBubbleView.animateText(text) binding.speechBubbleView.setConfirmationButtonVisibility(View.VISIBLE) } fun setTutorialTexts(texts: List<String>) { if (texts.size == 1) { setTutorialText(texts.first()) return } tutorialTexts = texts currentTextIndex = -1 displayNextTutorialText() } fun setCanBeDeferred(canBeDeferred: Boolean) { binding.speechBubbleView.binding.dismissButton.visibility = if (canBeDeferred) View.VISIBLE else View.GONE } private fun displayNextTutorialText() { currentTextIndex++ if (currentTextIndex < tutorialTexts.size) { binding.speechBubbleView.animateText(tutorialTexts[currentTextIndex]) if (isDisplayingLastStep) { binding.speechBubbleView.setConfirmationButtonVisibility(View.VISIBLE) binding.speechBubbleView.setHasMoreContent(false) } else { binding.speechBubbleView.setHasMoreContent(true) } } else { onReaction.onTutorialCompleted(step) } } private fun completeButtonClicked() { onReaction.onTutorialCompleted(step) (parent as? ViewGroup)?.removeView(this) } private fun dismissButtonClicked() { onReaction.onTutorialDeferred(step) (parent as? ViewGroup)?.removeView(this) } private fun backgroundClicked() { binding.speechBubbleView.onClick(binding.speechBubbleView) } interface OnTutorialReaction { fun onTutorialCompleted(step: TutorialStep) fun onTutorialDeferred(step: TutorialStep) } }
gpl-3.0
f7bc8f40eea1e460c363f3ff7aa6cb99
34.227273
114
0.681932
5.036335
false
false
false
false
kazhida/kotos2d
src/jp/kazhida/kotos2d/kotos2dEditBoxDialog.kt
1
8050
package jp.kazhida.kotos2d import android.content.Context import android.app.Dialog import android.graphics.drawable.ColorDrawable import android.widget.EditText import android.widget.TextView import android.widget.LinearLayout import android.view.inputmethod.InputMethodManager import android.os.Bundle import android.view.ViewGroup import android.util.TypedValue import android.view.WindowManager import android.view.inputmethod.EditorInfo import android.text.InputType import com.vlad.android.kotlin.* import android.text.InputFilter import android.os.Handler import android.widget.TextView.OnEditorActionListener import android.view.KeyEvent /** * Created by kazhida on 2013/07/29. */ public class Kotos2dEditBoxDialog(val context: Context, val title: String, val message: String, val inputMode: Int, val inputFlag: Int, val returnType: Int, val maxLength: Int): Dialog(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen) { class object { private val kEditBoxInputModeAny = 0 private val kEditBoxInputModeEmailAddr = 1 private val kEditBoxInputModeNumeric = 2 private val kEditBoxInputModePhoneNumber = 3 private val kEditBoxInputModeUrl = 4 private val kEditBoxInputModeDecimal = 5 private val kEditBoxInputModeSingleLine = 6 private val kEditBoxInputFlagPassword = 0 private val kEditBoxInputFlagSensitive = 1 private val kEditBoxInputFlagInitialCapsWord = 2 private val kEditBoxInputFlagInitialCapsSentence = 3 private val kEditBoxInputFlagInitialCapsAllCharacters = 4 private val kKeyboardReturnTypeDefault = 0 private val kKeyboardReturnTypeDone = 1 private val kKeyboardReturnTypeSend = 2 private val kKeyboardReturnTypeSearch = 3 private val kKeyboardReturnTypeGo = 4 } private var inputEditText: EditText? = null private var textViewTitle: TextView? = null private var inputFlagConstraints = 0 private var inputModeConstraints = 0 private var isMultiline = false protected fun onCreate(pSavedInstanceState: Bundle) { super.onCreate(pSavedInstanceState) getWindow()?.setBackgroundDrawable(ColorDrawable(0x80000000.toInt())) getWindow()?.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN) val MP = ViewGroup.LayoutParams.MATCH_PARENT val WC = ViewGroup.LayoutParams.WRAP_CONTENT inputModeConstraints = inputModeToConstraints(inputMode, isMultiline) inputFlagConstraints = inputFlagToConstraints(inputFlag) val layout = LinearLayout(getContext()) layout.setOrientation(LinearLayout.VERTICAL) textViewTitle = TextView(getContext()) textViewTitle?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20.f) textViewTitle?.setText(title) layout.addView(textViewTitle, layoutParams(WC, WC)) inputEditText: EditText = EditText(getContext()) inputEditText?.setText(message) layout.addView(inputEditText, layoutParams(MP, WC)) // ใ“ใฎ้ †็•ชใฏ้‡่ฆใชใฎใ‹๏ผŸ inputEditText?.addImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI) inputEditText?.setInputType(inputFlagConstraints or inputModeConstraints) inputEditText?.addImeOptions(returnTypeToImeOption(returnType)) inputEditText?.setOnEditorActionListener(ActionListener(inputEditText!!)) if (maxLength > 0) { inputEditText?.setFilters(array<InputFilter>(InputFilter.LengthFilter(maxLength))) } Handler().postDelayed(DoDelayed(inputEditText), 200.l) setContentView(layout, LinearLayout.LayoutParams(MP, MP)) } private fun layoutParams(w: Int, h: Int): LinearLayout.LayoutParams { val result = LinearLayout.LayoutParams(w, h) result.leftMargin = convertDipsToPixels(10.f) result.rightMargin = convertDipsToPixels(10.f) return result } private fun EditText.addImeOptions(option: Int): Int { setImeOptions(getImeOptions() or option) return getImeOptions() } private fun inputModeToConstraints(mode: Int, multiline: Boolean): Int { var constraints = when (mode) { kEditBoxInputModeAny -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE kEditBoxInputModeEmailAddr -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS kEditBoxInputModeNumeric -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_SIGNED kEditBoxInputModePhoneNumber -> InputType.TYPE_CLASS_PHONE kEditBoxInputModeUrl -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI kEditBoxInputModeDecimal -> InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED kEditBoxInputModeSingleLine -> InputType.TYPE_CLASS_TEXT else -> 0 } if (multiline) { constraints = constraints or InputType.TYPE_TEXT_FLAG_MULTI_LINE } return constraints } private fun inputFlagToConstraints(inputFlag: Int): Int { return when (inputFlag) { kEditBoxInputFlagPassword -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD kEditBoxInputFlagSensitive -> InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS kEditBoxInputFlagInitialCapsWord -> InputType.TYPE_TEXT_FLAG_CAP_WORDS kEditBoxInputFlagInitialCapsSentence -> InputType.TYPE_TEXT_FLAG_CAP_SENTENCES kEditBoxInputFlagInitialCapsAllCharacters -> InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS else -> 0 } } private fun returnTypeToImeOption(returnType: Int): Int { return when (returnType) { kKeyboardReturnTypeDefault -> EditorInfo.IME_ACTION_NONE kKeyboardReturnTypeDone -> EditorInfo.IME_ACTION_DONE kKeyboardReturnTypeSend -> EditorInfo.IME_ACTION_SEND kKeyboardReturnTypeSearch -> EditorInfo.IME_ACTION_SEARCH kKeyboardReturnTypeGo -> EditorInfo.IME_ACTION_GO else -> EditorInfo.IME_ACTION_NONE } } private inner class DoDelayed(val editText: EditText?): Runnable { public override fun run() { if (editText != null) { editText.requestFocus() editText.setSelection(editText.length()) openKeyboard() } } } private inner class ActionListener(val editText: EditText): OnEditorActionListener { private fun actionDown(actionId: Int, event: KeyEvent?): Boolean { if (actionId != EditorInfo.IME_NULL) { return true } else if (event?.getAction() == KeyEvent.ACTION_DOWN) { return true } else { return false } } public override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean { if (actionDown(actionId, event)) { Kotos2dHelper.sharedInstance().setEditTextDialogResult(editText.getText().toString()) closeKeyboard() dismiss() return true } return false } } private fun convertDipsToPixels(dpis: Float): Int { val scale = getContext().getResources()?.getDisplayMetrics()?.density!! return Math.round(dpis * scale) } private val inputManager: InputMethodManager? get() { return getContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? } private fun openKeyboard() { inputManager?.showSoftInput(inputEditText, 0) } private fun closeKeyboard() { inputManager?.hideSoftInputFromWindow(inputEditText?.getWindowToken(), 0) } }
mit
89a9d8d4b099c709de7a8c54cc6808b3
38.747525
142
0.674016
4.865455
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz/ui/factory/StepQuizFragmentFactoryImpl.kt
2
3880
package org.stepik.android.view.step_quiz.ui.factory import androidx.fragment.app.Fragment import org.stepic.droid.persistence.model.StepPersistentWrapper import org.stepic.droid.util.AppConstants import org.stepik.android.domain.lesson.model.LessonData import org.stepik.android.view.step_quiz_choice.ui.fragment.ChoiceStepQuizFragment import org.stepik.android.view.step_quiz_code.ui.fragment.CodeStepQuizFragment import org.stepik.android.view.step_quiz_fill_blanks.ui.fragment.FillBlanksStepQuizFragment import org.stepik.android.view.step_quiz_matching.ui.fragment.MatchingStepQuizFragment import org.stepik.android.view.step_quiz_pycharm.ui.fragment.PyCharmStepQuizFragment import org.stepik.android.view.step_quiz_review.ui.fragment.StepQuizReviewFragment import org.stepik.android.view.step_quiz_review.ui.fragment.StepQuizReviewTeacherFragment import org.stepik.android.view.step_quiz_sorting.ui.fragment.SortingStepQuizFragment import org.stepik.android.view.step_quiz_sql.ui.fragment.SqlStepQuizFragment import org.stepik.android.view.step_quiz_table.ui.fragment.TableStepQuizFragment import org.stepik.android.view.step_quiz_text.ui.fragment.TextStepQuizFragment import org.stepik.android.view.step_quiz_unsupported.ui.fragment.UnsupportedStepQuizFragment import javax.inject.Inject class StepQuizFragmentFactoryImpl @Inject constructor() : StepQuizFragmentFactory { override fun createStepQuizFragment(stepPersistentWrapper: StepPersistentWrapper, lessonData: LessonData): Fragment { val instructionType = stepPersistentWrapper.step.instructionType.takeIf { stepPersistentWrapper.step.actions?.doReview != null } val blockName = stepPersistentWrapper.step.block?.name return if (instructionType != null) { when { lessonData.lesson.isTeacher && blockName in StepQuizReviewTeacherFragment.supportedQuizTypes -> StepQuizReviewTeacherFragment.newInstance(stepPersistentWrapper.step.id, instructionType) !lessonData.lesson.isTeacher && blockName in StepQuizReviewFragment.supportedQuizTypes -> StepQuizReviewFragment.newInstance(stepPersistentWrapper.step.id, instructionType) else -> getDefaultQuizFragment(stepPersistentWrapper) } } else { getDefaultQuizFragment(stepPersistentWrapper) } } private fun getDefaultQuizFragment(stepPersistentWrapper: StepPersistentWrapper): Fragment = when (stepPersistentWrapper.step.block?.name) { AppConstants.TYPE_STRING, AppConstants.TYPE_NUMBER, AppConstants.TYPE_MATH, AppConstants.TYPE_FREE_ANSWER -> TextStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_CHOICE -> ChoiceStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_CODE -> CodeStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_SORTING -> SortingStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_MATCHING -> MatchingStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_PYCHARM -> PyCharmStepQuizFragment.newInstance() AppConstants.TYPE_SQL -> SqlStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_FILL_BLANKS -> FillBlanksStepQuizFragment.newInstance(stepPersistentWrapper.step.id) AppConstants.TYPE_TABLE -> TableStepQuizFragment.newInstance(stepPersistentWrapper.step.id) else -> UnsupportedStepQuizFragment.newInstance(stepPersistentWrapper.step.id) } }
apache-2.0
ab7597501d5c938ba6a0b35a26df4239
46.91358
121
0.737887
5.05867
false
false
false
false
Archinamon/GradleAspectJ-Android
android-gradle-aspectj/src/main/kotlin/com/archinamon/api/jars/JarMerger.kt
1
6711
package com.archinamon.api.jars import com.android.SdkConstants import com.android.utils.PathUtils import com.google.common.collect.ImmutableSortedMap import java.io.* import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.Path import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.nio.file.attribute.FileTime import java.util.function.Predicate import java.util.jar.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream /** Jar Merger class. */ class JarMerger @Throws(IOException::class) @JvmOverloads constructor( jarFile: Path, private val filter: Predicate<String>? = null ) : Closeable { private val buffer = ByteArray(8192) private val jarOutputStream: JarOutputStream init { Files.createDirectories(jarFile.parent) jarOutputStream = JarOutputStream(BufferedOutputStream(Files.newOutputStream(jarFile))) } @Throws(IOException::class) @JvmOverloads fun addDirectory( directory: Path, filterOverride: Predicate<String>? = filter, transformer: Transformer? = null, relocator: Relocator? = null) { val candidateFiles = ImmutableSortedMap.naturalOrder<String, Path>() Files.walkFileTree( directory, object : SimpleFileVisitor<Path>() { override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult { var entryPath = PathUtils.toSystemIndependentPath(directory.relativize(file)) if (filterOverride != null && !filterOverride.test(entryPath)) { return FileVisitResult.CONTINUE } if (relocator != null) { entryPath = relocator.relocate(entryPath) } candidateFiles.put(entryPath, file) return FileVisitResult.CONTINUE } }) val sortedFiles = candidateFiles.build() for ((entryPath, value) in sortedFiles) { BufferedInputStream(Files.newInputStream(value)).use { `is` -> if (transformer != null) { val is2 = transformer.filter(entryPath, `is`) if (is2 != null) { write(JarEntry(entryPath), is2) } } else { write(JarEntry(entryPath), `is`) } } } } @Throws(IOException::class) @JvmOverloads fun addJar( file: Path, filterOverride: Predicate<String>? = filter, relocator: Relocator? = null) { ZipInputStream(BufferedInputStream(Files.newInputStream(file))).use { zis -> // loop on the entries of the jar file package and put them in the final jar while (true) { val entry = zis.nextEntry ?: break // do not take directories if (entry.isDirectory) { continue } // Filter out files, e.g. META-INF folder, not classes. var name = entry.name if (filterOverride != null && !filterOverride.test(name)) { continue } if (relocator != null) { name = relocator.relocate(name) } val newEntry = JarEntry(name) newEntry.method = entry.method if (newEntry.method == ZipEntry.STORED) { newEntry.size = entry.size newEntry.compressedSize = entry.compressedSize newEntry.crc = entry.crc } newEntry.lastModifiedTime = FileTime.fromMillis(0) // read the content of the entry from the input stream, and write it into the // archive. write(newEntry, zis) } } } @Throws(IOException::class) fun addFile(entryPath: String, file: Path) { BufferedInputStream(Files.newInputStream(file)).use { `is` -> write(JarEntry(entryPath), `is`) } } @Throws(IOException::class) fun addEntry(entryPath: String, input: InputStream) { BufferedInputStream(input).use { `is` -> write(JarEntry(entryPath), `is`) } } @Throws(IOException::class) override fun close() { jarOutputStream.close() } @Throws(IOException::class) fun setManifestProperties(properties: Map<String, String>) { val manifest = Manifest() val global = manifest.mainAttributes global[Attributes.Name.MANIFEST_VERSION] = "1.0.0" properties.forEach( { attributeName, attributeValue -> global[Attributes.Name(attributeName)] = attributeValue }) val manifestEntry = JarEntry(JarFile.MANIFEST_NAME) setEntryAttributes(manifestEntry) jarOutputStream.putNextEntry(manifestEntry) try { manifest.write(jarOutputStream) } finally { jarOutputStream.closeEntry() } } @Throws(IOException::class) private fun write(entry: JarEntry, from: InputStream) { setEntryAttributes(entry) jarOutputStream.putNextEntry(entry) while (true) { val count = from.read(buffer) if (count == -1) break jarOutputStream.write(buffer, 0, count) } jarOutputStream.closeEntry() } private fun setEntryAttributes(entry: JarEntry) { entry.lastModifiedTime = fileTime entry.lastAccessTime = fileTime entry.creationTime = fileTime } interface Transformer { /** * Transforms the given file. * * @param entryPath the path within the jar file * @param input an input stream of the contents of the file * @return a new input stream if the file is transformed in some way, the same input stream * if the file is to be kept as is and null if the file should not be packaged. */ fun filter(entryPath: String, input: InputStream): InputStream? } interface Relocator { fun relocate(entryPath: String): String } companion object { val CLASSES_ONLY = { archivePath: String -> archivePath.endsWith(SdkConstants.DOT_CLASS) } val EXCLUDE_CLASSES = { archivePath: String -> !archivePath.endsWith(SdkConstants.DOT_CLASS) } val fileTime: FileTime = FileTime.fromMillis(0) } }
apache-2.0
814f9030a0edd3a9622c37ff435d549d
33.772021
109
0.581582
4.985884
false
false
false
false
da1z/intellij-community
platform/external-system-api/src/com/intellij/openapi/externalSystem/ExternalSystemModulePropertyManager.kt
4
7160
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.externalSystem.model.ProjectSystemId import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleServiceManager import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ExternalProjectSystemRegistry import com.intellij.openapi.roots.ProjectModelElement import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Transient import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty val EMPTY_STATE = ExternalStateComponent() @Suppress("DEPRECATION") @State(name = "ExternalSystem") class ExternalSystemModulePropertyManager(private val module: Module) : PersistentStateComponent<ExternalStateComponent>, ProjectModelElement { override fun getExternalSource() = store.externalSystem?.let { ExternalProjectSystemRegistry.getInstance().getSourceById(it) } private var store = if (module.project.isExternalStorageEnabled) ExternalStateComponent() else ExternalStateModule(module) override fun getState() = store as? ExternalStateComponent ?: EMPTY_STATE override fun loadState(state: ExternalStateComponent) { store = state } companion object { @JvmStatic fun getInstance(module: Module) = ModuleServiceManager.getService(module, ExternalSystemModulePropertyManager::class.java)!! } @Suppress("DEPRECATION") fun getExternalSystemId() = store.externalSystem fun getExternalModuleType() = store.externalSystemModuleType fun getExternalModuleVersion() = store.externalSystemModuleVersion fun getExternalModuleGroup() = store.externalSystemModuleGroup fun getLinkedProjectId() = store.linkedProjectId fun getRootProjectPath() = store.rootProjectPath fun getLinkedProjectPath() = store.linkedProjectPath @Suppress("DEPRECATION") fun isMavenized() = store.isMavenized @Suppress("DEPRECATION") fun setMavenized(mavenized: Boolean) { if (mavenized) { // clear external system API options // see com.intellij.openapi.externalSystem.service.project.manage.ModuleDataService#setModuleOptions unlinkExternalOptions() } // must be after unlinkExternalOptions store.isMavenized = mavenized } fun swapStore() { val oldStore = store val isMaven = oldStore.isMavenized if (oldStore is ExternalStateModule) { store = ExternalStateComponent() } else { store = ExternalStateModule(module) } store.externalSystem = if (store is ExternalStateModule && isMaven) null else oldStore.externalSystem if (store !is ExternalStateComponent) { // do not set isMavenized for ExternalStateComponent it just set externalSystem store.isMavenized = isMaven } store.linkedProjectId = oldStore.linkedProjectId store.linkedProjectPath = oldStore.linkedProjectPath store.rootProjectPath = oldStore.rootProjectPath store.externalSystemModuleGroup = oldStore.externalSystemModuleGroup store.externalSystemModuleVersion = oldStore.externalSystemModuleVersion if (oldStore is ExternalStateModule) { oldStore.isMavenized = false oldStore.unlinkExternalOptions() } } fun unlinkExternalOptions() { store.unlinkExternalOptions() } fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) { // clear maven option, must be first store.isMavenized = false store.externalSystem = id.toString() store.linkedProjectId = moduleData.id store.linkedProjectPath = moduleData.linkedExternalProjectPath store.rootProjectPath = projectData?.linkedExternalProjectPath ?: "" store.externalSystemModuleGroup = moduleData.group store.externalSystemModuleVersion = moduleData.version } fun setExternalId(id: ProjectSystemId) { store.externalSystem = id.id } fun setExternalModuleType(type: String?) { store.externalSystemModuleType = type } } private interface ExternalOptionState { var externalSystem: String? var externalSystemModuleVersion: String? var linkedProjectPath: String? var linkedProjectId: String? var rootProjectPath: String? var externalSystemModuleGroup: String? var externalSystemModuleType: String? var isMavenized: Boolean } private fun ExternalOptionState.unlinkExternalOptions() { externalSystem = null linkedProjectId = null linkedProjectPath = null rootProjectPath = null externalSystemModuleGroup = null externalSystemModuleVersion = null } @Suppress("DEPRECATION") private class ModuleOptionDelegate(private val key: String) : ReadWriteProperty<ExternalStateModule, String?> { override operator fun getValue(thisRef: ExternalStateModule, property: KProperty<*>) = thisRef.module.getOptionValue(key) override operator fun setValue(thisRef: ExternalStateModule, property: KProperty<*>, value: String?) { thisRef.module.setOption(key, value) } } @Suppress("DEPRECATION") private class ExternalStateModule(internal val module: Module) : ExternalOptionState { override var externalSystem by ModuleOptionDelegate(ExternalProjectSystemRegistry.EXTERNAL_SYSTEM_ID_KEY) override var externalSystemModuleVersion by ModuleOptionDelegate("external.system.module.version") override var externalSystemModuleGroup by ModuleOptionDelegate("external.system.module.group") override var externalSystemModuleType by ModuleOptionDelegate("external.system.module.type") override var linkedProjectPath by ModuleOptionDelegate("external.linked.project.path") override var linkedProjectId by ModuleOptionDelegate("external.linked.project.id") override var rootProjectPath by ModuleOptionDelegate("external.root.project.path") override var isMavenized: Boolean get() = "true" == module.getOptionValue(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY) set(value) { module.setOption(ExternalProjectSystemRegistry.IS_MAVEN_MODULE_KEY, if (value) "true" else null) } } class ExternalStateComponent : ExternalOptionState { @get:Attribute override var externalSystem: String? = null @get:Attribute override var externalSystemModuleVersion: String? = null @get:Attribute override var externalSystemModuleGroup: String? = null @get:Attribute override var externalSystemModuleType: String? = null @get:Attribute override var linkedProjectPath: String? = null @get:Attribute override var linkedProjectId: String? = null @get:Attribute override var rootProjectPath: String? = null @get:Transient override var isMavenized: Boolean get() = externalSystem == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID set(value) { externalSystem = if (value) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null } }
apache-2.0
8c6364ed262d8880d1baaa0fc6daeeaa
35.535714
143
0.786732
5.343284
false
false
false
false
kvakil/venus
src/main/kotlin/venus/riscv/insts/sll.kt
1
460
package venus.riscv.insts import venus.riscv.insts.dsl.RTypeInstruction val sll = RTypeInstruction( name = "sll", opcode = 0b0110011, funct3 = 0b001, funct7 = 0b0000000, eval32 = { a, b -> val shift = b and 0b11111 if (shift == 0) a else a shl shift }, eval64 = { a, b -> val shift = b.toInt() and 0b111111 if (shift == 0) a else a shl shift } )
mit
72bcd9c41a3fee80f7ed1b0c055e1451
24.555556
46
0.513043
3.484848
false
false
false
false
kronenpj/iqtimesheet
IQTimeSheet/src/main/com/github/kronenpj/iqtimesheet/IQTimeSheet/TimeSheetDbAdapter.kt
1
53035
package com.github.kronenpj.iqtimesheet.IQTimeSheet import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.SQLException import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteException import android.util.Log import com.github.kronenpj.iqtimesheet.IQTimeSheet.ITimeSheetDbAdapter.Companion.DB_FALSE import com.github.kronenpj.iqtimesheet.IQTimeSheet.ITimeSheetDbAdapter.Companion.DB_TRUE import com.github.kronenpj.iqtimesheet.TimeHelpers import org.jetbrains.anko.db.* import java.util.* /** * Replacement for direct-converted Kotlin code. * Created by kronenpj on 6/22/17. */ class TimeSheetDbAdapter /** * Primary Constructor - takes the context to allow the database to be * opened/created */ @JvmOverloads constructor(private val mCtx: Context, private var instance: MySqlHelper = MySqlHelper.getInstance(mCtx)) : ITimeSheetDbAdapter { companion object { private const val TAG = "TimeSheetDbAdapter" } /* From Anko README fun getUsers(db: ManagedSQLiteOpenHelper): List<User> = db.use { db.select("Users") .whereSimple("family_name = ?", "John") .doExec() .parseList(UserParser) } */ val timeTotalParser = rowParser { id: Long, task: String, total: Float -> ITimeSheetDbAdapter.timeTotalTuple(id, task, total) } val timeEntryParser = rowParser { id: Long, task: String, timein: Long, timeout: Long -> ITimeSheetDbAdapter.timeEntryTuple(id, task, timein, timeout) } val chargeNoParser = rowParser { id: Long, chargeno: Long, timein: Long, timeout: Long -> ITimeSheetDbAdapter.chargeNoTuple(id, chargeno, timein, timeout) } // TODO: active should be: Boolean val tasksParser = rowParser { id: Long, task: String, active: Long, usage: Long, oldusage: Long, lastused: Long -> ITimeSheetDbAdapter.tasksTuple(id, task, active, usage, oldusage, lastused) } val taskUsageParser = rowParser { id: Long, usage: Long, oldusage: Long, lastused: Long -> ITimeSheetDbAdapter.taskUsageTuple(id, usage, oldusage, lastused) } /** * Create a new time entry using the charge number provided. If the entry is * successfully created return the new rowId for that note, otherwise return * a -1 to indicate failure. * * @param chargeno the charge number for the entry * * @param timeInP the time in milliseconds of the clock-in * * @return rowId or -1 if failed */ override fun createEntry(chargeno: Long, timeInP: Long): Long { var timeIn = timeInP if (TimeSheetActivity.prefs!!.alignMinutesAuto) { timeIn = TimeHelpers.millisToAlignMinutes(timeIn, TimeSheetActivity.prefs!!.alignMinutes) } incrementTaskUsage(chargeno) var result: Long = 0L Log.d(TAG, "createEntry: $chargeno at $timeIn (${TimeHelpers.millisToTimeDate(timeIn)})") instance.use { result = insert("TimeSheet", "chargeno" to chargeno, "timein" to timeIn) } return result } /** * Close an existing time entry using the charge number provided. If the * entry is successfully created return the new rowId for that note, * otherwise return a -1 to indicate failure. * * @param chargeno the charge number for the entry * * @param timeOutP the time in milliseconds of the clock-out * * @return rowId or -1 if failed */ override fun closeEntry(chargeno: Long, timeOutP: Long): Int { var timeOut = timeOutP if (TimeSheetActivity.prefs!!.alignMinutesAuto) { timeOut = TimeHelpers.millisToAlignMinutes(timeOut, TimeSheetActivity.prefs!!.alignMinutes) // TODO: Fix in a more sensible way. // Hack to account for a cross-day automatic clock out. // if (timeOut - origTimeOut == 1) // timeOut = origTimeOut; } // Stop the time closed from landing on a day boundary. val timeIn = getTimeEntryTuple(lastClockEntry())?.timein ?: -1L // TODO: Maybe need a boolean preference to enable / disable this? // long boundary = TimeHelpers.millisToEoDBoundary(timeIn, // TimeSheetActivity.prefs.getTimeZone()); val boundary = TimeHelpers.millisToEoDBoundary(timeIn, TimeSheetActivity.prefs!!.timeZone) Log.d(TAG, "Boundary: $boundary") if (timeOut > boundary) timeOut = boundary - 1000 Log.d(TAG, "closeEntry: $chargeno at $timeOut (${TimeHelpers.millisToTimeDate(timeOut)})") var result = 0 // TODO: Figure out how to get the Long return code here. try { instance.use { result = update("TimeSheet", "timeout" to timeOut) .whereArgs("_id = ${lastClockEntry()} and chargeno = $chargeno") .exec() } } catch (e: SQLiteConstraintException) { result = -1 } return result } /** * Delete the entry with the given rowId * * @param rowId code id of note to delete * * @return true if deleted, false otherwise */ override fun deleteEntry(rowId: Long): Boolean { Log.i("Delete called", "value__ $rowId") var retcode = 0 instance.use { retcode = delete("TimeSheet", "_id = $rowId") } return retcode > 0 } /** * Return a Cursor over the list of all entries in the database * * @return Cursor over all database entries */ override fun fetchAllTimeEntries(): Cursor? { val c: Cursor? = null instance.readableDatabase .query("TimeSheet", arrayOf("_id", "chargeno", "timein", "timeout"), null, null, null, null, null) return c } /** * Return a Cursor positioned at the entry that matches the given rowId * * @param rowId id of entry to retrieve * * @return Cursor positioned to matching entry, if found * * @throws SQLException if entry could not be found/retrieved */ @Throws(SQLException::class) override fun fetchEntry(rowId: Long): Cursor? { val mCursor = instance.readableDatabase .query("TimeSheet", arrayOf("_id", "chargeno", "timein", "timeout"), "_id = $rowId", null, null, null, null) mCursor?.moveToFirst() return mCursor } /** * Return a Cursor positioned at the entry that matches the given rowId * * @param rowId id of entry to retrieve * * @return Cursor positioned to matching entry, if found * * @throws SQLException if entry could not be found/retrieved */ @Throws(SQLException::class) override fun fetchEntry(rowId: Long, column: String): Cursor? { val mCursor = instance.readableDatabase .query("TimeSheet", arrayOf(column), "_id = $rowId", null, null, null, null) mCursor?.moveToFirst() return mCursor } /** * Update the note using the details provided. The entry to be updated is * specified using the rowId, and it is altered to use the date and time * values passed in * * @param rowIdP id of entry to update * * @param chargeno change number to update * * @param date the date of the entry * * @param timein the time work started on the task * * @param timeout the time work stopped on the task * * @return true if the entry was successfully updated, false otherwise */ override fun updateEntry(rowIdP: Long, chargeno: Long, date: String?, timein: Long, timeout: Long): Boolean { var rowId = rowIdP val args = ContentValues() // Only change items that aren't null or -1. if (timein != -1L) args.put("timein", timein) if (chargeno != -1L) args.put("chargeno", chargeno) if (timeout != -1L) args.put("timeout", timeout) if (rowId == -1L) rowId = lastClockEntry() var retbool = false instance.use { retbool = update("TimeSheet", args, "_id = ?", arrayOf("$rowId")) > 0 } return retbool } /** * Retrieve the taskID of the last entry in the clock table. * * @return rowId or -1 if failed */ override fun taskIDForLastClockEntry(): Long { val lastClockID = lastClockEntry() var retval: Long? = null instance.use { retval = select("TimeSheet", "chargeno") .whereArgs("_id = $lastClockID") .parseOpt(LongParser) } return retval ?: -1L } /** * Retrieve the timeIn of the last entry in the clock table. * * @return time in in milliseconds or -1 if failed */ override fun timeInForLastClockEntry(): Long { val lastClockID = lastClockEntry() var retval: Long? = -1L instance.use { retval = select("TimeSheet", "timein") .whereArgs("_id = $lastClockID") .parseOpt(LongParser) } return retval ?: -1L } /** * Retrieve the time out of the last entry in the clock table. * * @return time out in milliseconds or -1 if failed */ override fun timeOutForLastClockEntry(): Long { val lastClockID = lastClockEntry() var retval: Long? = -1 instance.use { retval = select("TimeSheet", "timeout") .whereArgs("_id = $lastClockID") .parseOpt(LongParser) } return retval ?: -1L } /** * Retrieve the row of the last entry in the tasks table. * * @return rowId or -1 if failed */ override fun lastTaskEntry(): Long { var retval: Long? = -1 instance.use { retval = select("Tasks", "max(_id)") .parseOpt(LongParser) } return retval ?: -1L } /** * Return a timeEntryTuple of the entry that matches the given rowId * * @param rowId id of entry to retrieve * * @return timeEntryTuple of the matching entry, if found. null if not. * * @throws SQLException if entry could not be found/retrieved */ @Throws(SQLException::class) override fun getTimeEntryTuple(rowId: Long): ITimeSheetDbAdapter.timeEntryTuple? { var retval: ITimeSheetDbAdapter.timeEntryTuple? = null instance.use { retval = select("EntryItems", "_id", "task", "timein", "timeout") .whereArgs("_id = $rowId") .parseOpt(parser = timeEntryParser) } return retval } /** * Return a getChargeNoTuple of the entry that matches the given rowId * * @param rowId id of entry to retrieve * * @return timeEntryTuple of the matching entry, if found. null if not. * * @throws SQLException if entry could not be found/retrieved */ @Throws(SQLException::class) override fun getChargeNoTuple(rowId: Long): ITimeSheetDbAdapter.chargeNoTuple? { var retval: ITimeSheetDbAdapter.chargeNoTuple? = null instance.use { retval = select("TimeSheet", "_id", "chargeno", "timein", "timeout") .whereArgs("_id = $rowId") .parseOpt(parser = chargeNoParser) } return retval } /** * Retrieve the entry in the timesheet table immediately prior to the * supplied entry. * * @return rowId or -1 if failed */ override fun getPreviousClocking(rowID: Long): Long { var thisTimeIn: Long = -1 var prevTimeOut: Long = -1 Log.d(TAG, "getPreviousClocking for row: $rowID") // Get the tuple from the provided row var mCurrent: ITimeSheetDbAdapter.timeEntryTuple? = getTimeEntryTuple(rowID) // KEY_ROWID, KEY_TASK, KEY_TIMEIN, KEY_TIMEOUT thisTimeIn = mCurrent?.timein ?: return -1L Log.d(TAG, "timeIn for current: $thisTimeIn") var retval: ITimeSheetDbAdapter.timeEntryTuple? = null instance.use { retval = select("EntryItems", "_id", "task", "timein", "timeout") .whereArgs("_id < $rowID") .orderBy("_id", SqlOrderDirection.DESC) .limit(1) .parseOpt(parser = timeEntryParser) } var prevRowID = retval?.id ?: return -1L Log.d(TAG, "rowID for previous: $prevRowID") // Get the tuple from the just-retrieved row mCurrent = getTimeEntryTuple(prevRowID) // KEY_ROWID, KEY_TASK, KEY_TIMEIN, KEY_TIMEOUT prevTimeOut = mCurrent?.timeout ?: return -1L Log.d(TAG, "timeOut for previous: $prevTimeOut") // If the two tasks don't flow from one to another, don't allow the // entry to be adjusted. if (thisTimeIn != prevTimeOut) prevRowID = -1 return prevRowID } /** * Retrieve the entry in the timesheet table immediately following the * supplied entry. * * @return rowId or -1 if failed */ // TODO: Should this be chronological or ordered by _id? as it is now? // And, if it should be chronological by time in or time out or both... :( override fun getNextClocking(rowID: Long): Long { var thisTimeOut: Long = -1L var nextTimeIn: Long = -1L Log.d(TAG, "getNextClocking for row: $rowID") // Get the tuple from the provided row var mCurrent: ITimeSheetDbAdapter.timeEntryTuple? = getTimeEntryTuple(rowID) // KEY_ROWID, KEY_TASK, KEY_TIMEIN, KEY_TIMEOUT thisTimeOut = mCurrent?.timeout ?: return -1L Log.d(TAG, "timeOut for current: $thisTimeOut") var retval: ITimeSheetDbAdapter.timeEntryTuple? = null instance.use { retval = select("EntryItems", "_id", "task", "timein", "timeout") .whereArgs("_id > $rowID") .orderBy("_id") .limit(1) .parseOpt(parser = timeEntryParser) } var nextRowID = retval?.id ?: return -1 Log.d(TAG, "rowID for next: $nextRowID") // Get the tuple from the just-retrieved row mCurrent = getTimeEntryTuple(nextRowID) // KEY_ROWID, KEY_TASK, KEY_TIMEIN, KEY_TIMEOUT nextTimeIn = mCurrent?.timein ?: return -1L Log.d(TAG, "timeIn for next: $nextTimeIn") // If the two tasks don't flow from one to another, don't allow the // entry to be adjusted. if (thisTimeOut != nextTimeIn) nextRowID = -1 return nextRowID } /** * Retrieve the row of the last entry in the clock table. * * @return rowId or -1 if failed */ override fun lastClockEntry(): Long { var response: Long = -1 instance.use { select("TimeSheet", "max(_id)").exec { response = parseOpt(LongParser) ?: -1L } } return response } /** * Retrieve an array of rows for today's entry in the clock table. * * @return array of rowId's or null if failed */ override fun todaysEntries(): LongArray? { val now = TimeHelpers.millisNow() val todayStart = TimeHelpers.millisToStartOfDay(now) val todayEnd = TimeHelpers.millisToEndOfDay(now) val rows: LongArray // public Cursor query(boolean distinct, String table, String[] columns, // String selection, String[] selectionArgs, String groupBy, String // having, String orderBy) { // cursor.asSequence() var tmp: List<Long>? = null instance.use { tmp = select("TimeSheet", "_id") .whereArgs("timein >= $todayStart and (timeout <= $todayEnd or timeout = 0") .parseList(LongParser) } if (tmp == null || (tmp as List<Long>).count() == 0) { // TODO: Figure out how to get a context into this class... // toast("No entries in the database for today." as CharSequence) return null } rows = LongArray((tmp as List<Long>).count()) var count = 0 (tmp as List<Long>).forEach { rows[count++] = it } return rows } /** * Retrieve list of entries for the day surrounding the supplied time. * * @return rowId or -1 if failed */ override fun getEntryReportCursor(distinct: Boolean, columns: Array<String>, groupBy: String?, orderBy: String?, start: Long, end: Long): Cursor? { // public Cursor query(boolean distinct, String table, String[] columns, // String selection, String[] selectionArgs, String groupBy, String // having, String orderBy, String limit) { val selection: String val endDay = TimeHelpers.millisToDayOfMonth(end - 1000) val now = TimeHelpers.millisNow() selection = if (TimeHelpers.millisToDayOfMonth(now - 1000) == endDay || TimeHelpers.millisToDayOfMonth(TimeHelpers.millisToEndOfWeek(now - 1000, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour)) == endDay) { Log.d(TAG, "getEntryReportCursor: Allowing selection of zero-end-hour entries.") "timein >=? and timeout <= ? and (timeout >= timein or timeout = 0)" } else { "timein >=? and timeout <= ? and timeout >= timein" } Log.d(TAG, "getEntryReportCursor: Selection criteria: $selection") Log.d(TAG, "getEntryReportCursor: Selection arguments: $start, $end") Log.d(TAG, "getEntryReportCursor: Selection arguments: ${TimeHelpers.millisToTimeDate(start)}, ${TimeHelpers.millisToTimeDate(end)}") val mCursor = instance.readableDatabase.query(distinct, "EntryReport", columns, selection, arrayOf(start.toString(), end.toString()), groupBy, null, orderBy, null) mCursor?.moveToLast() ?: Log.e(TAG, "getEntryReportCursor: mCursor for range is null.") if (mCursor?.isAfterLast != false) { Log.d(TAG, "getEntryReportCursor: mCursor for range is empty.") // Toast.makeText(mCtx, // "No entries in the database for supplied range.", // Toast.LENGTH_SHORT).show(); return null } return mCursor } /** * Given a task ID, close the task and, if the ID differs, open a new task. * Refresh the data displayed. * * @return true if a new task was started, false if the old task was * stopped. */ override fun processChange(taskID: Long): Boolean { Log.d(TAG, "processChange for task ID: $taskID") var lastRowID = lastClockEntry() val lastTaskID = taskIDForLastClockEntry() Log.d(TAG, "Last Task Entry Row: $lastRowID") val timeOut = getTimeEntryTuple(lastRowID)?.timeout ?: -1L // Determine if the task has already been chosen and is now being // closed. if (timeOut == 0L && lastTaskID == taskID) { closeEntry(taskID) Log.d(TAG, "Closed task ID: $taskID") return false } else { if (timeOut == 0L) closeEntry() createEntry(taskID) lastRowID = lastClockEntry() val tempClockCursor = fetchEntry(lastRowID) tempClockCursor?.close() Log.d(TAG, "processChange ID from $lastTaskID to $taskID") return true } } /** * Retrieve list of entries for the day surrounding the supplied time. * * @return rowId or -1 if failed */ override fun getSummaryCursor(distinct: Boolean, columns: Array<String>, groupBy: String?, orderBy: String?, start: Long, end: Long): Cursor? { // public Cursor query(boolean distinct, String table, String[] columns, // String selection, String[] selectionArgs, String groupBy, String // having, String orderBy, String limit) { // String selection; // Log.d(TAG, "getSummaryCursor: Selection criteria: " + // selection); try { Log.d(TAG, "getSummaryCursor: Columns: ${columns[0]}, ${columns[1]} and ${columns[2]}") } catch (e: Exception) { Log.d(TAG, "getSummaryCursor has fewer than 3 columns.") } Log.d(TAG, "getSummaryCursor: Selection arguments: $start, $end") Log.d(TAG, "getSummaryCursor: Selection arguments: ${TimeHelpers.millisToTimeDate(start)}, ${TimeHelpers.millisToTimeDate(end)}") // Cursor mCursor = mDb.query(distinct, SUMMARY_DATABASE_TABLE, columns, // selection, new String[] { String.valueOf(start).toString(), // String.valueOf(end).toString() }, groupBy, null, orderBy, null); // TODO: Below KEY_STOTAL was KEY_TOTAL // Cursor mCursor = mDb.query(distinct, SUMMARY_DATABASE_TABLE, // columns, // KEY_STOTAL + " > 0", // new String[] { String.valueOf(0).toString(), // String.valueOf(end).toString() }, groupBy, null, // orderBy, null); var select = "SELECT " if (distinct) select += "DISTINCT " for (c in columns.indices) { select += if (c == 0) { columns[c] } else { (", " + columns[c]) } } select += " FROM Summary WHERE total > 0" if (groupBy != null) select += " GROUP BY $groupBy" if (orderBy != null) select += " ORDER BY $orderBy" Log.d(TAG, "getSummaryCursor: query: $select") val mCursor = instance.readableDatabase.rawQuery(select, null) mCursor?.moveToLast() ?: Log.e(TAG, "entryReport mCursor for range is null.") if (mCursor?.isAfterLast != false) { Log.d(TAG, "entryReport mCursor for range is empty.") // Toast.makeText(mCtx, // "No entries in the database for supplied range.", // Toast.LENGTH_SHORT).show(); return null } mCursor.moveToFirst() return mCursor } /** * Retrieve list of entries for the day surrounding the supplied time. * * @return rowId or -1 if failed */ override fun dayEntryReport(timeP: Long): Cursor? { var time = timeP if (time <= 0) time = TimeHelpers.millisNow() val todayStart = TimeHelpers.millisToStartOfDay(time) val todayEnd = TimeHelpers.millisToEndOfDay(time) Log.d(TAG, "dayEntryReport start: ${TimeHelpers.millisToTimeDate(todayStart)}") Log.d(TAG, "dayEntryReport end: ${TimeHelpers.millisToTimeDate(todayEnd)}") val columns = arrayOf("_id", "task", "range", "timein", "timeout") return getEntryReportCursor(false, columns, null, "timein", todayStart, todayEnd) } /** * Method that populates a temporary table for a single specified day from * the entry view. * * @param timeP The time around which to report * * @param omitOpen Include an open task in the result * * @return Cursor over the results. */ // TODO: Finish and replace the other routines with it. override fun daySummary(timeP: Long, omitOpen: Boolean): Cursor? { var time = timeP Log.d(TAG, "In daySummary.") if (time <= 0) time = TimeHelpers.millisNow() var todayStart = TimeHelpers.millisToStartOfDay(time) var todayEnd = TimeHelpers.millisToEndOfDay(time) // TODO: This is a first attempt and is likely to be convoluted. // If today is the split day for a 9/80-style week, adjust the start/end times appropriately. if (TimeHelpers.millisToDayOfWeek(todayStart) == TimeSheetActivity.prefs!!.weekStartDay && TimeSheetActivity.prefs!!.weekStartHour > 0) { val splitMillis = (TimeSheetActivity.prefs!!.weekStartHour * 3600 * 1000).toLong() // This is the partial day where the week splits, only for schedules like a 9/80. if (time < todayStart + splitMillis) // Move the end of the day to the split time. todayEnd = todayStart + splitMillis else todayStart += splitMillis // Move the start of the day to the split time. } Log.d(TAG, "daySummary start: ${TimeHelpers.millisToTimeDate(todayStart)}") Log.d(TAG, "daySummary end: ${TimeHelpers.millisToTimeDate(todayEnd)}") populateSummary(todayStart, todayEnd, omitOpen) val columns = arrayOf("_id", "task", "total") val groupBy = "task" val orderBy = "total DESC" return try { getSummaryCursor(true, columns, groupBy, orderBy, todayStart, todayEnd) } catch (e: SQLiteException) { Log.e(TAG, "getSummaryCursor: $e") null } } /** * Retrieve list of entries for the week surrounding the supplied time. * * @return Cursor over the entries */ override fun weekEntryReport(timeP: Long): Cursor? { var time = timeP if (time <= 0) time = TimeHelpers.millisNow() val todayStart = TimeHelpers.millisToStartOfWeek(time, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) val todayEnd = TimeHelpers.millisToEndOfWeek(time, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) // public Cursor query(boolean distinct, String table, String[] columns, // String selection, String[] selectionArgs, String groupBy, String // having, String orderBy) { Log.d(TAG, "weekEntryReport start: ${TimeHelpers.millisToTimeDate(todayStart)}") Log.d(TAG, "weekEntryReport end: ${TimeHelpers.millisToTimeDate(todayEnd)}") val columns = arrayOf("_id", "task", "range", "timein", "timeout") return getEntryReportCursor(false, columns, todayStart, todayEnd) } /** * Method that populates a temporary table for a single specified day from * the entry view. * * @return Cursor over the results. */ // TODO: Finish and replace the other routines with it. override fun weekSummary(timeP: Long, omitOpen: Boolean): Cursor? { var time = timeP Log.d(TAG, "In weekSummary.") if (time <= 0) time = TimeHelpers.millisNow() Log.d(TAG, "weekSummary time arg: ${TimeHelpers.millisToTimeDate(time)}") val weekStart = TimeHelpers.millisToStartOfWeek(time, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) val weekEnd = TimeHelpers.millisToEndOfWeek(weekStart + 86400000, TimeSheetActivity.prefs!!.weekStartDay, TimeSheetActivity.prefs!!.weekStartHour) Log.d(TAG, "weekSummary start: ${TimeHelpers.millisToTimeDate(weekStart)}") Log.d(TAG, "weekSummary end: ${TimeHelpers.millisToTimeDate(weekEnd)}") populateSummary(weekStart, weekEnd, omitOpen) // String[] columns = { KEY_TASK, KEY_HOURS }; // String groupBy = KEY_TASK; // String orderBy = KEY_TASK; val columns = arrayOf("_id", "task", "total") val groupBy = "task" val orderBy = "total DESC" return try { getSummaryCursor(true, columns, groupBy, orderBy, weekStart, weekEnd) } catch (e: SQLiteException) { Log.e(TAG, "getSummaryCursor: ${e.localizedMessage}") null } } /** * * @param summaryStart The start time for the summary * * * @param summaryEnd The end time for the summary * * * @param omitOpen Whether the summary should omit an open task */ override fun populateSummary(summaryStart: Long, summaryEnd: Long, omitOpen: Boolean) { Log.v(TAG, "populateSummary: Creating summary table.") instance.readableDatabase.execSQL("""CREATE TEMP TABLE IF NOT EXISTS Summary ('_id' INTEGER PRIMARY KEY AUTOINCREMENT, 'task' TEXT NOT NULL, 'total' REAL DEFAULT 0);""") Log.v(TAG, "populateSummary: Cleaning summary table.") instance.readableDatabase.execSQL("DELETE from Summary") instance.readableDatabase.execSQL("VACUUM") var omitOpenQuery = "" if (omitOpen) omitOpenQuery = "TimeSheet.timeout > 0 AND " val populateTemp1 = """INSERT INTO Summary ( task, total ) SELECT Tasks.task, SUM((CASE WHEN TimeSheet.timeout = 0 THEN ${TimeHelpers.millisNow()} ELSE TimeSheet.timeout END - TimeSheet.timein )/3600000.0) AS total FROM TimeSheet, Tasks WHERE TimeSheet.timeout <= $summaryEnd AND $omitOpenQuery TimeSheet.timein >= $summaryStart AND TimeSheet.chargeno = Tasks._id AND Tasks.split = 0 GROUP BY task""" Log.v(TAG, "populateTemp1\n$populateTemp1") instance.readableDatabase.execSQL(populateTemp1) val populateTemp2 = """INSERT INTO Summary (task,total) SELECT TaskSplitReport.taskdesc, (SUM((CASE WHEN TimeSheet.timeout = 0 THEN ${TimeHelpers.millisNow()} ELSE TimeSheet.timeout END - TimeSheet.timein )/3600000.0) * (TaskSplit.percentage /100.0)) AS total FROM TimeSheet, TaskSplit, Tasks, TaskSplitReport WHERE TimeSheet.timeout <= $summaryEnd AND $omitOpenQuery TimeSheet.timein >= $summaryStart AND TimeSheet.chargeno = Tasks._id AND Tasks._id = TaskSplit.chargeno AND Tasks._id = TaskSplitReport.parenttask AND TaskSplit.task || TaskSplit.percentage = TaskSplitReport._id || TaskSplitReport.percentage GROUP BY TaskSplit.task""" // TODO: Figure out why the second-to-last line above makes no sense. Log.v(TAG, "populateTemp2\n$populateTemp2") instance.readableDatabase.execSQL(populateTemp2) } /** * Create a new time entry using the charge number provided. If the entry is * successfully created return the new rowId for that number, otherwise * return a -1 to indicate failure. * * @param task the charge number text for the entry * * @return rowId or -1 if failed */ override fun createTask(task: String): Long { Log.d(TAG, "createTask: $task") val tempDate = System.currentTimeMillis() // Local time... var retval: Long = -1L // Do some rudimentary checks/fixes on the input. task.replace(oldValue = "'", newValue = "") task.replace(oldValue = ";", newValue = "") instance.use { retval = insert("Tasks", "task" to task, "lastused" to tempDate) } return retval } /** * Create a new split time entry using the information provided. If the * entry is successfully created return the new rowId for that number, * otherwise return a -1 to indicate failure. * * @param task the charge number text for the entry * * @param parent The parent for the split task * * @param percentage The amount this task contributes to the task. * * @return rowId or -1 if failed */ override fun createTask(task: String, parent: String, percentage: Int): Long { Log.d(TAG, "createTask: $task") Log.d(TAG, " parent: $parent") Log.d(TAG, "percentage: $percentage") val tempDate = System.currentTimeMillis() // Local time... val parentId = getTaskIDByName(parent) var newRow: Long = -1L var retval: Long = -1L // Do some rudimentary checks/fixes on the input. task.replace(oldValue = "'", newValue = "") task.replace(oldValue = ";", newValue = "") instance.use { newRow = insert("Tasks", "task" to task, "lastused" to tempDate, "split" to 1) Log.d(TAG, "new row : $newRow") update("Tasks", "split" to 2).whereArgs("_id = $parentId").exec() retval = insert("TaskSplit", "task" to newRow, "chargeno" to parentId, "percentage" to percentage) } return retval } /** * Return a Cursor over the list of all tasks in the database eligible to be * split task parents. * * @return Cursor over all database entries */ override fun fetchParentTasks(): Array<String>? { Log.d(TAG, "fetchParentTasks: Issuing DB query.") var retval: Array<String>? = null instance.use { retval = select("Tasks", "task") .whereArgs("active = '$DB_TRUE' and split != 1") .parseList(StringParser).toTypedArray() } return retval } /** * Return an array over the list of all tasks in the database that are children * of the supplied split task parent. * * @return Array over all matching database entries */ /* CREATE TABLE TaskSplit ( _id INTEGER PRIMARY KEY AUTOINCREMENT, chargeno INTEGER NOT NULL REFERENCES Tasks(_id), task INTEGER NOT NULL REFERENCES Tasks(_id), percentage INTEGER NOT NULL DEFAULT 100 CHECK(percentage>=0 AND percentage<=100) ); */ override fun fetchChildTasks(parentID: Long): Array<Long> { var retval: Array<Long>? = null instance.use { retval = select("TaskSplit", "task") .whereArgs("chargeno = '$parentID'") .parseList(LongParser).toTypedArray() } return retval ?: emptyArray() } /** * Return an Array of all Tasks entries in the database * * @return Array of all Tasks database entries */ override fun fetchAllTaskEntries(): Array<ITimeSheetDbAdapter.tasksTuple>? { Log.d(TAG, "fetchAllTaskEntries: Issuing DB query.") var retval: Array<ITimeSheetDbAdapter.tasksTuple>? = null instance.use { retval = select("Tasks", "_id", "task", "active", "usage", "oldusage", "lastused") .whereArgs("active = '$DB_TRUE'") .orderBy("usage + oldusage / 2", SqlOrderDirection.DESC) .parseList(tasksParser).toTypedArray() } return retval } /** * Return a Cursor over the list of all entries in the database * * @return Cursor over all database entries */ override fun fetchAllDisabledTasks(): Array<ITimeSheetDbAdapter.tasksTuple>? { Log.d(TAG, "fetchAllDisabledTasks: Issuing DB query.") var retval: Array<ITimeSheetDbAdapter.tasksTuple>? = null instance.use { retval = select("Tasks", "_id", "task", "active", "usage", "oldusage", "lastused") .whereArgs("active='$DB_FALSE'") .orderBy("task") .parseList(tasksParser).toTypedArray() } Log.i(TAG, "Fetched ${retval!!.size} disabled tasks.") return retval } /** * Return a Cursor positioned at the entry that matches the given rowId * * @param rowId id of entry to retrieve * * @return Cursor positioned to matching entry, if found * * @throws SQLException if entry could not be found/retrieved */ @Throws(SQLException::class) override fun fetchTask(rowId: Long): Cursor { Log.d(TAG, "fetchTask: Issuing DB query.") val mCursor = instance.readableDatabase.query(true, "Tasks", arrayOf("_id", "task", "active", "usage", "oldusage", "lastused"), "_id = $rowId", null, null, null, null, null) mCursor?.moveToFirst() return mCursor } /** * Retrieve the task ID of the supplied task name. * * @return rowId or -1 if failed */ override fun getTaskIDByName(name: String): Long { Log.d(TAG, "getTaskIDByName: Issuing DB query.") var response: Long = -1L instance.use { response = select("Tasks", "_id") .whereArgs("task = '$name'") .parseSingle(LongParser) } Log.d(TAG, "getTaskIDByName: $response") return response } /** * Retrieve the task name for the supplied task ID. * * @param taskID The identifier of the desired task * * @return Name of the task identified by the taskID */ override fun getTaskNameByID(taskID: Long): String? { Log.d(TAG, "getTaskNameByID: Issuing DB query for ID: $taskID") var response = "" if (taskID < 0) { Log.d(TAG, "getTaskNameByID: $taskID is less than 0, returning empty string.") return response } try { instance.use { response = select("Tasks", "task") .whereArgs("_id = '$taskID'") .parseSingle(StringParser) } } catch (e: SQLException) { Log.d(TAG, "getTaskNameByID: Task ID '$taskID' doesn't have an entry.") Log.d(TAG, "getTaskNameByID: Ignoring SQLException: $e") } return response } /** * Return the entry that matches the given rowId * * @param splitTask id of task to retrieve * * @return parent's task ID, if found, 0 if not */ override fun getSplitTaskParent(splitTask: String): Long { Log.d(TAG, "getSplitTaskParent: $splitTask") return getSplitTaskParent(getTaskIDByName(splitTask)) } /** * Return the entry that matches the given rowId * * @param rowId id of task to retrieve * * @return parent's task ID, if found, 0 if not */ override fun getSplitTaskParent(rowId: Long): Long { Log.d(TAG, "getSplitTaskParent: Issuing DB query. requesting rrrow ID: $rowId") var retval: Long = -1L if (rowId < 0) { Log.d(TAG, "getSplitTaskParent: $rowId is less than 0, returning -1.") return retval } try { instance.use { retval = select("TaskSplit", "chargeno") .whereArgs("task = $rowId") .parseSingle(LongParser) } } catch (e: SQLException) { Log.d(TAG, "getSplitTaskParent: '${getTaskNameByID(rowId)}' doesn't have a parent.") Log.d(TAG, "getSplitTaskParent: Ignoring SQLException: $e") } Log.d(TAG, "getSplitTaskParent: $retval / ${getTaskNameByID(retval)}") return retval } /** * Return the entry that matches the given rowId * * @param rowId id of task to retrieve * * @return parent's task ID, if found, 0 if not */ override fun getSplitTaskPercentage(rowId: Long): Int { Log.d(TAG, "getSplitTaskPercentage: Issuing DB query.") var retval: Int = -1 if (rowId < 0) { Log.d(TAG, "getSplitTaskPercentage: $rowId is less than 0, returning -1.") return retval } try { instance.use { retval = select("tasksplit", "percentage") .whereArgs("task = $rowId") .parseSingle(IntParser) } } catch (e: SQLException) { Log.d(TAG, "getSplitTaskPercentage: '${getTaskNameByID(rowId)}' doesn't have a percentage.") Log.d(TAG, "getSplitTaskPercentage: Ignoring SQLException: $e") } Log.d(TAG, "getSplitTaskPercentage: $retval") return retval } /** * Return the flag whether the task that matches the given rowId is a split * task. * * @param rowId id of task to retrieve * * @return 1 if the task is part of a split, and if found, 0 otherwise */ override fun getSplitTaskFlag(rowId: Long): Int { Log.d(TAG, "getSplitTaskFlag: Issuing DB query.") var retval: Int = 0 if (rowId < 0) { Log.d(TAG, "getSplitTaskFlag: $rowId is less than 0, returning 0 (False).") return retval } try { instance.use { retval = select("Tasks", "split") .whereArgs("_id = $rowId") .parseSingle(IntParser) } } catch (e: SQLException) { Log.d(TAG, "getSplitTaskFlag: '${getTaskNameByID(rowId)}' isn't part of a split.") Log.d(TAG, "getSplitTaskFlag: Ignoring SQLException: $e") } Log.d(TAG, "getSplitTaskFlag: $retval") return retval } /** * Return the number of children whose parent matches the given rowId * * @param rowId id of task to retrieve * * @return Number of "children" of this task, 0 if none. */ override fun getQuantityOfSplits(rowId: Long): Long { Log.d(TAG, "getQuantityOfSplits: Issuing DB query.") var retval: Long = 0 try { instance.use { retval = select("taskSplit", "count(task)") .whereArgs("chargeno = $rowId") .parseSingle(LongParser) } } catch (e: SQLException) { Log.d(TAG, "getQuantityOfSplits: '${getTaskNameByID(rowId)}' isn't part of a split.") Log.d(TAG, "getQuantityOfSplits: Ignoring SQLException: $e") } Log.d(TAG, "getQuantityOfSplits: $retval") return retval } /** * Rename specified task * * @param origName Old task name * * @param newName New task name */ override fun renameTask(origName: String, newName: String) { Log.d(TAG, "renameTask: Issuing DB query.") val taskID = getTaskIDByName(origName) newName.replace(oldValue = "'", newValue = "") newName.replace(oldValue = ";", newValue = "") instance.use { update("Tasks", "task" to newName) .whereArgs("_id = $taskID") .exec() } } /** * Alter specified split task * * @param rowID Task ID to change * * @param parentIDP New parent ID * * @param percentage New percentage * * @param split New split flag state */ override fun alterSplitTask(rowID: Long, parentIDP: Long, percentage: Int, split: Int) { var parentID = parentIDP Log.d(TAG, "alterSplitTask: Issuing DB query.") val currentParent = getSplitTaskParent(rowID) val currentSplit = getSplitTaskFlag(rowID) if (split == 0 && currentSplit == 1) parentID = -1 // If the number of sub-splits under the parent task is 1 (<2) and we // are changing the parent, set the split flag to 0. if (getQuantityOfSplits(currentParent) < 2 && currentParent != parentID) { val i = instance.use { update("Tasks", "split" to 0).whereArgs( "_id = $currentParent").exec() } Log.d(TAG, "Reverting task $currentParent to standard task returned $i") } // Set the flag on the new parent if (currentParent != parentID && parentID > 0) { val initialValues = ContentValues(1) initialValues.put("split", 2) val i = instance.use { update("Tasks", "split" to 2) .whereArgs("_id = $parentID").exec() } Log.d(TAG, "Converting task $parentID to parent task returned: $i") } // If the new split state is 1, a child, set the appropriate values if (split == 1) { Log.d(TAG, "alterSplitTask: Setting up child") var i: Int = -1 var j: Long = -1L instance.use { i = update("TaskSplit", "chargeno" to parentID, "percentage" to percentage) .whereArgs("task = $rowID").exec() } Log.d(TAG, "Setting child task $rowID details returned: $i") if (i == 0) { instance.use { j = insert("TaskSplit", "chargeno" to parentID, "percentage" to percentage, "task" to rowID) } Log.d(TAG, "Inserting child task $rowID details returned: $j") } instance.use { i = update("Tasks", "split" to 1).whereArgs("_id = $rowID").exec() } Log.d(TAG, "Converting task $rowID to child task returned: $i") } // Delete the record in tasksplit if the new split state is 0 if (currentSplit == 1 && split == 0) { var i: Int = -1 Log.d(TAG, "alterSplitTask: Tearing down child") try { instance.use { i = delete("TaskSplit", "task = $rowID") } Log.d(TAG, "Setting child task $rowID details returned: $i") } catch (e: RuntimeException) { Log.e(TAG, e.localizedMessage) } val newData = ContentValues(1) newData.put("split", 0) i = -1 try { instance.use { i = update("Tasks", "split" to 0) .whereArgs("_id = $rowID").exec() } Log.d(TAG, "Converting child task $rowID to standard task returned: $i") } catch (e: RuntimeException) { Log.e(TAG, e.localizedMessage) } } } /** * Deactivate / retire the task supplied. * * @param taskID The ID of the task to be deactivated. */ override fun deactivateTask(taskID: Long) { Log.d(TAG, "deactivateTask: Issuing DB query.") instance.use { update("Tasks", "active" to DB_FALSE).whereArgs("_id = $taskID").exec() } } /** * Activate the task supplied. * * @param taskID The ID of the task to be activated. */ override fun activateTask(taskID: Long) { Log.d(TAG, "activateTask: Issuing DB query.") instance.use { update("Tasks", "active" to DB_TRUE).whereArgs("_id = $taskID").exec() } } /** * Increment the usage counter of the supplied task. * * @param taskID The ID of the task's usage to be incremented. */ override fun incrementTaskUsage(taskID: Long) { Log.d(TAG, "incrementTaskUsage: Issuing DB query.") val usageTuple: ITimeSheetDbAdapter.taskUsageTuple? = getTaskUsageTuple(taskID) var usage = usageTuple?.usage ?: 0 var oldUsage = usageTuple?.oldusage ?: 0 val lastUsed = usageTuple?.lastused ?: 0 val now = System.currentTimeMillis() val todayCal = GregorianCalendar.getInstance() val dateLastUsedCal = GregorianCalendar.getInstance() todayCal.timeInMillis = now dateLastUsedCal.timeInMillis = lastUsed // Roll-over the old usage when transitioning into a new month. if (todayCal.get(Calendar.MONTH) != dateLastUsedCal.get(Calendar.MONTH)) { oldUsage = usage usage = if (usage >= 0) 0 else -1 } instance.use { update("Tasks", "lastused" to now, "usage" to usage + 1, "oldusage" to oldUsage) .whereArgs("_id = $taskID").exec() } } override fun getTaskUsageTuple(taskID: Long): ITimeSheetDbAdapter.taskUsageTuple? { var usageTuple: ITimeSheetDbAdapter.taskUsageTuple? = null instance.use { usageTuple = select("Tasks", "_id", "usage", "oldusage", "lastused") .whereArgs("_id = $taskID").parseOpt(taskUsageParser) } return usageTuple } // TODO: Is there a better way of doing this? override fun getTasksList(): Array<String> { Log.d(TAG, "getTasksList") val taskArray = fetchAllTaskEntries() val items = mutableListOf<String>() taskArray?.forEach { items.add(it.task) } return items.toTypedArray() } // TODO: Is there a better way of doing this? override fun getDayReportList(): Array<String?> { Log.d(TAG, "getDayReportList") val reportCursor = daySummary() try { val items = arrayOfNulls<String?>(reportCursor!!.count) reportCursor.moveToFirst() var i = 0 while (reportCursor.isAfterLast) { items[i] = reportCursor.getString(reportCursor.getColumnIndex("task")) reportCursor.moveToNext() i++ } try { reportCursor.close() } catch (e: Exception) { Log.i(TAG, "reportCursor close getDayReportList: $e") } return items } catch (e: NullPointerException) { Log.i(TAG, "getDayReportList: $e") } return arrayOfNulls(1) } /** * Return a Cursor positioned at the note that matches the given rowId * * @return Cursor positioned to matching note, if found * * @throws SQLException if note could not be found/retrieved */ @Throws(SQLException::class) override fun fetchVersion(): Int { Log.d(TAG, "fetchVersion: Issuing DB query.") var response = -1 instance.use { response = select("TimeSheetMeta", "max(version)").parseSingle(IntParser) } return response } /** * Generic SQL exec wrapper, for use with statements which do not return * values. */ override fun runSQL(sqlTorun: String) { instance.use { execSQL(sqlTorun) } } /** * Generic SQL update wrapper, Exposes the update method for testing. * * @param table the table being updated * * @param values the ContentValues being updated * * @param whereClause clause to limit updates * * @param whereArgs arguments to fill any ? in the whereClause. * * @return The number of rows affected */ override fun runUpdate(table: String, values: ContentValues, whereClause: String, whereArgs: Array<String>): Int { Log.d(TAG, "Running update on '$table'...") var retval: Int = -1 instance.use { retval = update(table, values, whereClause, whereArgs) } return retval } /** * Generic SQL insert wrapper, Exposes the insert method for testing. * * @param table the table being updated * * @param nullColHack Null column hack. * * @param values the ContentValues being updated * * @return The rowID is the just-inserted row */ override fun runInsert(table: String, nullColHack: String, values: ContentValues): Long { Log.d(TAG, "Running update on '$table'...") var retval: Long = -1L instance.use { retval = insert(table, nullColHack, values) } return retval } /** * Dumps the contents of the tasks table to logcat, for testing. */ override fun dumpTasks() { Log.d(TAG, "Dumping tasks table") data class taskDumpTuple(val id: Long, val task: String) val taskDumpParser = rowParser { id: Long, task: String -> taskDumpTuple(id, task) } var taskDump: List<taskDumpTuple>? = null instance.use { taskDump = select("Tasks", "_id", "task") .parseList(taskDumpParser) } taskDump?.forEach { Log.d(TAG, "$it.id / $it.task") } } /** * Dumps the contents of the tasks table to logcat, for testing. */ override fun dumpClockings() { Log.d(TAG, "Dumping clock table") data class clockingDumpTuple(val id: Long, val chargeno: Long) val clockingDumpParser = rowParser { id: Long, chargeno: Long -> clockingDumpTuple(id, chargeno) } var clockingDump: List<clockingDumpTuple>? = null instance.use { clockingDump = select("Tasks", "_id", "chargeno") .parseList(clockingDumpParser) } clockingDump?.forEach { Log.d(TAG, "$it.id / $it.task") } } }
apache-2.0
9eb7bda0bf083dd74651acc36b05872e
34.451203
141
0.580334
4.274259
false
false
false
false
ouattararomuald/kotlin-experiment
src/main/kotlin/com/ouattararomuald/datastructures/Stack.kt
1
1947
/* * Copyright 2017 Romuald OUATTARA * * 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.ouattararomuald.datastructures /** Simple Last-In-First-Out (LIFO) data structures. */ internal class Stack<T> { /** Checks whether or not the stack is empty. */ val isEmpty: Boolean get() = size == 0 /** Returns the number of items currently in the stack. */ var size: Int = 0 private set /** Top item of the stack. */ private var top: Node<T>? = null /** * Returns but does not retrieve the item at the top of the stack. * * @return The item at the top of the stack. * @exception UnderflowException If the stack is empty. */ fun peek(): T? { if (isEmpty) { throw UnderflowException() } else { return top?.data } } /** * Retrieves and returns the item at the top of the stack. * * @return The item at the top of the stack. * @exception UnderflowException If the stack is empty. */ fun pop(): T? { if (isEmpty) { throw UnderflowException() } else { val data = top?.data top = top?.next size-- return data } } /** * Adds the given item at the top of the stack. * @param data Item to add in the stack. */ fun push(data: T) { val newNode = Node(data, null) newNode.next = top top = newNode size++ } private data class Node<T>(val data: T, var next: Node<T>?) }
apache-2.0
d37860d78bb9d5750c28c10f90620883
24.631579
76
0.640473
3.758687
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MemberVisibilityCanBePrivateInspection.kt
1
8028
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.ex.EntryPointsManager import com.intellij.codeInspection.ex.EntryPointsManagerBase import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.util.Processor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility import org.jetbrains.kotlin.descriptors.EffectiveVisibility import org.jetbrains.kotlin.descriptors.effectiveVisibility import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.canBePrivate import org.jetbrains.kotlin.idea.core.isInheritable import org.jetbrains.kotlin.idea.core.isOverridable import org.jetbrains.kotlin.idea.core.toDescriptor import org.jetbrains.kotlin.idea.quickfix.AddModifierFixFE10 import org.jetbrains.kotlin.idea.refactoring.isConstructorDeclaredProperty import org.jetbrains.kotlin.idea.search.isCheapEnoughToSearchConsideringOperators import org.jetbrains.kotlin.idea.search.usagesSearch.dataClassComponentFunction import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.base.projectStructure.scope.KotlinSourceFilterScope import org.jetbrains.kotlin.idea.util.hasNonSuppressAnnotation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* class MemberVisibilityCanBePrivateInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return object : KtVisitorVoid() { override fun visitProperty(property: KtProperty) { super.visitProperty(property) if (!property.isLocal && canBePrivate(property)) { registerProblem(holder, property) } } override fun visitNamedFunction(function: KtNamedFunction) { super.visitNamedFunction(function) if (canBePrivate(function)) { registerProblem(holder, function) } } override fun visitParameter(parameter: KtParameter) { super.visitParameter(parameter) if (parameter.isConstructorDeclaredProperty() && canBePrivate(parameter)) { registerProblem(holder, parameter) } } } } private fun canBePrivate(declaration: KtNamedDeclaration): Boolean { if (declaration.hasModifier(KtTokens.PRIVATE_KEYWORD) || declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) return false if (declaration.hasNonSuppressAnnotation) return false val classOrObject = declaration.containingClassOrObject ?: return false val inheritable = classOrObject is KtClass && classOrObject.isInheritable() if (!inheritable && declaration.hasModifier(KtTokens.PROTECTED_KEYWORD)) return false //reported by ProtectedInFinalInspection if (declaration.isOverridable()) return false val descriptor = (declaration.toDescriptor() as? DeclarationDescriptorWithVisibility) ?: return false when (descriptor.effectiveVisibility()) { EffectiveVisibility.PrivateInClass, EffectiveVisibility.PrivateInFile, EffectiveVisibility.Local -> return false else -> {} } val entryPointsManager = EntryPointsManager.getInstance(declaration.project) as EntryPointsManagerBase if (UnusedSymbolInspection.checkAnnotatedUsingPatterns( declaration, with(entryPointsManager) { additionalAnnotations + ADDITIONAL_ANNOTATIONS } ) ) return false if (!declaration.canBePrivate()) return false // properties can be referred by component1/component2, which is too expensive to search, don't analyze them if (declaration is KtParameter && declaration.dataClassComponentFunction() != null) return false val psiSearchHelper = PsiSearchHelper.getInstance(declaration.project) val useScope = declaration.useScope val name = declaration.name ?: return false val restrictedScope = if (useScope is GlobalSearchScope) { when (psiSearchHelper.isCheapEnoughToSearchConsideringOperators(name, useScope, null, null)) { PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES -> return false PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES -> return false PsiSearchHelper.SearchCostResult.FEW_OCCURRENCES -> KotlinSourceFilterScope.projectSources(useScope, declaration.project) } } else useScope var otherUsageFound = false var inClassUsageFound = false ReferencesSearch.search(declaration, restrictedScope).forEach(Processor { val usage = it.element if (usage.isOutside(classOrObject)) { otherUsageFound = true return@Processor false } val classOrObjectDescriptor = classOrObject.descriptor as? ClassDescriptor if (classOrObjectDescriptor != null) { val receiverType = (usage as? KtElement)?.resolveToCall()?.dispatchReceiver?.type val receiverDescriptor = receiverType?.constructor?.declarationDescriptor if (receiverDescriptor != null && receiverDescriptor != classOrObjectDescriptor) { otherUsageFound = true return@Processor false } } val function = usage.getParentOfTypesAndPredicate<KtDeclarationWithBody>( true, KtNamedFunction::class.java, KtPropertyAccessor::class.java ) { true } val insideInlineFun = function.insideInline() || (function as? KtPropertyAccessor)?.property.insideInline() if (insideInlineFun) { otherUsageFound = true false } else { inClassUsageFound = true true } }) return inClassUsageFound && !otherUsageFound } private fun PsiElement.isOutside(classOrObject: KtClassOrObject): Boolean { if (classOrObject != getParentOfType<KtClassOrObject>(false)) return true val annotationEntry = getStrictParentOfType<KtAnnotationEntry>() ?: return false return classOrObject.annotationEntries.any { it == annotationEntry } } private fun KtModifierListOwner?.insideInline() = this?.let { it.hasModifier(KtTokens.INLINE_KEYWORD) && !it.isPrivate() } ?: false private fun registerProblem(holder: ProblemsHolder, declaration: KtDeclaration) { val modifierListOwner = declaration.getParentOfType<KtModifierListOwner>(false) ?: return val member = when (declaration) { is KtNamedFunction -> KotlinBundle.message("text.Function") else -> KotlinBundle.message("text.Property") } val nameElement = (declaration as? PsiNameIdentifierOwner)?.nameIdentifier ?: return holder.registerProblem( declaration.visibilityModifier() ?: nameElement, KotlinBundle.message("0.1.could.be.private", member, declaration.getName().toString()), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(AddModifierFixFE10(modifierListOwner, KtTokens.PRIVATE_KEYWORD)) ) } }
apache-2.0
465627cdabc53ae9225624332aefff93
48.863354
137
0.707025
5.681529
false
false
false
false
android/renderscript-intrinsics-replacement-toolkit
test-app/src/main/java/com/google/android/renderscript_test/IntrinsicResize.kt
1
4029
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.renderscript_test import android.graphics.Bitmap import android.renderscript.Allocation import android.renderscript.RenderScript import android.renderscript.Script import android.renderscript.ScriptIntrinsicResize import android.renderscript.Type import com.google.android.renderscript.Range2d /** * Does a Resize operation using the RenderScript Intrinsics. */ fun intrinsicResize( context: RenderScript, inputArray: ByteArray, vectorSize: Int, inSizeX: Int, inSizeY: Int, outSizeX: Int, outSizeY: Int, restriction: Range2d? ): ByteArray { val scriptResize = ScriptIntrinsicResize.create(context) val builder = Type.Builder( context, renderScriptVectorElementForU8(context, vectorSize) ) builder.setX(inSizeX) builder.setY(inSizeY) val inputArrayType = builder.create() val inputAllocation = Allocation.createTyped(context, inputArrayType) builder.setX(outSizeX) builder.setY(outSizeY) val outputArrayType = builder.create() val outAllocation = Allocation.createTyped(context, outputArrayType) val intrinsicOutArray = ByteArray(outSizeX * outSizeY * paddedSize(vectorSize)) inputAllocation.copyFrom(inputArray) scriptResize.setInput(inputAllocation) if (restriction != null) { outAllocation.copyFrom(intrinsicOutArray) // To initialize to zero val options = Script.LaunchOptions() options.setX(restriction.startX, restriction.endX) options.setY(restriction.startY, restriction.endY) scriptResize.forEach_bicubic(outAllocation, options) } else { scriptResize.forEach_bicubic(outAllocation) } outAllocation.copyTo(intrinsicOutArray) inputAllocation.destroy() outAllocation.destroy() scriptResize.destroy() inputArrayType.destroy() outputArrayType.destroy() return intrinsicOutArray } fun intrinsicResize( context: RenderScript, bitmap: Bitmap, outSizeX: Int, outSizeY: Int, restriction: Range2d? ): ByteArray { val scriptResize = ScriptIntrinsicResize.create(context) val inputAllocation = Allocation.createFromBitmap(context, bitmap) inputAllocation.copyFrom(bitmap) val vectorSize = when (bitmap.config) { Bitmap.Config.ARGB_8888 -> 4 Bitmap.Config.ALPHA_8 -> 1 else -> error("Unrecognized bitmap config $bitmap.config") } val builder = Type.Builder( context, renderScriptVectorElementForU8(context, vectorSize) ) builder.setX(outSizeX) builder.setY(outSizeY) val outputArrayType = builder.create() val outAllocation = Allocation.createTyped(context, outputArrayType) val intrinsicOutArray = ByteArray(outSizeX * outSizeY * vectorSize) scriptResize.setInput(inputAllocation) if (restriction != null) { outAllocation.copyFrom(intrinsicOutArray) // To initialize to zero val options = Script.LaunchOptions() options.setX(restriction.startX, restriction.endX) options.setY(restriction.startY, restriction.endY) scriptResize.forEach_bicubic(outAllocation, options) } else { scriptResize.forEach_bicubic(outAllocation) } outAllocation.copyTo(intrinsicOutArray) inputAllocation.destroy() outAllocation.destroy() outputArrayType.destroy() scriptResize.destroy() return intrinsicOutArray }
apache-2.0
9a1fba68beff6ea92b76deefab1f8a2d
32.857143
83
0.72971
4.408096
false
false
false
false
duncte123/SkyBot
src/main/kotlin/ml/duncte123/skybot/adapters/WebDatabaseAdapter.kt
1
14896
/* * Skybot, a multipurpose discord bot * Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32" * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package ml.duncte123.skybot.adapters import com.dunctebot.models.settings.GuildSetting import com.dunctebot.models.settings.WarnAction import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import gnu.trove.map.TLongLongMap import gnu.trove.map.hash.TLongLongHashMap import ml.duncte123.skybot.objects.Tag import ml.duncte123.skybot.objects.api.* import ml.duncte123.skybot.objects.command.custom.CustomCommand import ml.duncte123.skybot.objects.command.custom.CustomCommandImpl import ml.duncte123.skybot.utils.AirUtils import java.time.OffsetDateTime class WebDatabaseAdapter(private val apis: DuncteApis, private val jackson: ObjectMapper) : DatabaseAdapter() { override fun getCustomCommands(callback: (List<CustomCommand>) -> Unit) { runOnThread { val array = apis.getCustomCommands() val customCommands: List<CustomCommand> = jackson.readValue(array.traverse(), object : TypeReference<List<CustomCommandImpl>>() {}) callback(customCommands) } } override fun createCustomCommand(guildId: Long, invoke: String, message: String, callback: (Triple<Boolean, Boolean, Boolean>?) -> Unit) { runOnThread { callback( apis.createCustomCommand(guildId, invoke, message) ) } } override fun updateCustomCommand(guildId: Long, invoke: String, message: String, autoresponse: Boolean, callback: (Triple<Boolean, Boolean, Boolean>?) -> Unit) { runOnThread { callback( apis.updateCustomCommand(guildId, invoke, message, autoresponse) ) } } override fun deleteCustomCommand(guildId: Long, invoke: String, callback: (Boolean) -> Any?) { runOnThread { callback(apis.deleteCustomCommand(guildId, invoke)) } } override fun getGuildSettings(callback: (List<GuildSetting>) -> Unit) { runOnThread { val array = apis.getGuildSettings() val settings: List<GuildSetting> = jackson.readValue(array.traverse(), object : TypeReference<List<GuildSetting>>() {}) callback(settings) } } override fun loadGuildSetting(guildId: Long, callback: (GuildSetting?) -> Unit) { runOnThread { val item = apis.getGuildSetting(guildId) if (item == null) { callback(null) return@runOnThread } val setting = jackson.readValue(item.traverse(), GuildSetting::class.java) callback(setting) } } override fun updateGuildSetting(guildSettings: GuildSetting, callback: (Boolean) -> Unit) { runOnThread { callback( apis.updateGuildSettings(guildSettings) ) } } override fun deleteGuildSetting(guildId: Long) { runOnThread { apis.deleteGuildSetting(guildId) } } override fun purgeGuildSettings(guildIds: List<Long>) { runOnThread { apis.purgeGuildSettings(guildIds) } } override fun registerNewGuild(guildSettings: GuildSetting, callback: (Boolean) -> Unit) { runOnThread { callback( apis.registerNewGuildSettings(guildSettings) ) } } override fun addWordToBlacklist(guildId: Long, word: String) { runOnThread { apis.addWordToBlacklist(guildId, word) } } override fun addWordsToBlacklist(guildId: Long, words: List<String>) { runOnThread { apis.addBatchToBlacklist(guildId, words) } } override fun removeWordFromBlacklist(guildId: Long, word: String) { runOnThread { apis.removeWordFromBlacklist(guildId, word) } } override fun clearBlacklist(guildId: Long) { runOnThread { apis.clearBlacklist(guildId) } } override fun updateOrCreateEmbedColor(guildId: Long, color: Int) { runOnThread { apis.updateOrCreateEmbedColor(guildId, color) } } override fun loadAllPatrons(callback: (AllPatronsData) -> Unit) { runOnThread { val patrons = arrayListOf<Patron>() val tagPatrons = arrayListOf<Patron>() val oneGuildPatrons = arrayListOf<Patron>() val guildPatrons = arrayListOf<Patron>() apis.loadAllPatrons() .map { jackson.readValue(it.traverse(), Patron::class.java) } .forEach { patron -> when (patron.type) { Patron.Type.NORMAL -> patrons.add(patron) Patron.Type.TAG -> tagPatrons.add(patron) Patron.Type.ONE_GUILD -> oneGuildPatrons.add(patron) Patron.Type.ALL_GUILD -> guildPatrons.add(patron) } } callback(AllPatronsData(patrons, tagPatrons, oneGuildPatrons, guildPatrons)) } } override fun removePatron(userId: Long) { runOnThread { apis.deletePatron(userId) } } override fun createOrUpdatePatron(patron: Patron) { runOnThread { apis.createOrUpdatePatron(patron) } } override fun addOneGuildPatrons(userId: Long, guildId: Long, callback: (Long, Long) -> Unit) { runOnThread { val status = apis.updateOrCreateOneGuildPatron(userId, guildId) if (status) { callback(userId, guildId) } } } override fun getOneGuildPatron(userId: Long, callback: (TLongLongMap) -> Unit) { runOnThread { val map = TLongLongHashMap() val patron = apis.getOneGuildPatron(userId) ?: return@runOnThread map.put(patron["user_id"].asLong(), patron["guild_id"].asLong()) callback(map) } } override fun createBan(modId: Long, userName: String, userDiscriminator: String, userId: Long, unbanDate: String, guildId: Long) { runOnThread { val json = jackson.createObjectNode() .put("modUserId", modId.toString()) .put("Username", userName) .put("discriminator", userDiscriminator) .put("userId", userId.toString()) .put("guildId", guildId.toString()) .put("unban_date", unbanDate) apis.createBan(json) } } override fun createWarning(modId: Long, userId: Long, guildId: Long, reason: String, callback: () -> Unit) { runOnThread { apis.createWarning(modId, userId, guildId, reason) // invoke callback here as the apis request is sync callback() } } override fun createMute(modId: Long, userId: Long, userTag: String, unmuteDate: String, guildId: Long, callback: (Mute?) -> Unit) { runOnThread { val json = jackson.createObjectNode() .put("mod_id", modId.toString()) .put("user_id", userId.toString()) .put("user_tag", userTag) .put("guild_id", guildId.toString()) .put("unmute_date", unmuteDate) val muteData = apis.createMute(json) if (muteData.isEmpty) { callback(null) return@runOnThread } val mute: Mute = jackson.readValue(muteData.traverse(), Mute::class.java) callback(mute) } } override fun deleteLatestWarningForUser(userId: Long, guildId: Long, callback: (Warning?) -> Unit) { runOnThread { val json = apis.removeLatestWarningForUser(userId, guildId) if (json == null) { callback(null) return@runOnThread } callback( Warning( json["id"].asInt(), json["warn_date"].asText(), json["mod_id"].asText(), json["reason"].asText(), json["guild_id"].asText() ) ) } } override fun getWarningsForUser(userId: Long, guildId: Long, callback: (List<Warning>) -> Unit) { runOnThread { val data = apis.getWarningsForUser(userId, guildId) val items = arrayListOf<Warning>() val regex = "\\s+".toRegex() data.forEach { json -> items.add( Warning( json["id"].asInt(), json["warn_date"].asText().split(regex)[0], json["mod_id"].asText(), json["reason"].asText(), json["guild_id"].asText() ) ) } callback(items) } } override fun getWarningCountForUser(userId: Long, guildId: Long, callback: (Int) -> Unit) { runOnThread { callback( apis.getWarningCountForUser(userId, guildId) ) } } override fun purgeBansSync(ids: List<Int>) = apis.purgeBans(ids) override fun purgeMutesSync(ids: List<Int>) = apis.purgeMutes(ids) override fun getExpiredBansAndMutes(callback: (List<Ban>, List<Mute>) -> Unit) { throw UnsupportedOperationException("Not used anymore") } override fun getVcAutoRoles(callback: (List<VcAutoRole>) -> Unit) { runOnThread { val storedData = apis.getVcAutoRoles() val converted = arrayListOf<VcAutoRole>() for (item in storedData) { converted.add( VcAutoRole( item["guild_id"].asLong(), item["voice_channel_id"].asLong(), item["role_id"].asLong() ) ) } callback(converted) } } override fun setVcAutoRole(guildId: Long, voiceChannelId: Long, roleId: Long) { runOnThread { apis.setVcAutoRole(guildId, voiceChannelId, roleId) } } override fun setVcAutoRoleBatch(guildId: Long, voiceChannelIds: List<Long>, roleId: Long) { runOnThread { apis.setVcAutoRoleBatch(guildId, voiceChannelIds, roleId) } } override fun removeVcAutoRole(voiceChannelId: Long) { runOnThread { apis.removeVcAutoRole(voiceChannelId) } } override fun removeVcAutoRoleForGuild(guildId: Long) { runOnThread { apis.removeVcAutoRoleForGuild(guildId) } } override fun loadTags(callback: (List<Tag>) -> Unit) { runOnThread { val allTags = apis.getAllTags() callback( jackson.readValue(allTags.traverse(), object : TypeReference<List<Tag>>() {}) ) } } override fun createTag(tag: Tag, callback: (Boolean, String) -> Unit) { runOnThread { val json = jackson.valueToTree(tag) as ObjectNode json.put("owner_id", json["owner_id"].asText()) val response = apis.createTag(json) callback(response.first, response.second) } } override fun deleteTag(tag: Tag, callback: (Boolean, String) -> Unit) { runOnThread { val response = apis.deleteTag(tag.name) callback(response.first, response.second) } } override fun createReminder( userId: Long, reminder: String, expireDate: OffsetDateTime, channelId: Long, messageId: Long, guildId: Long, inChannel: Boolean, callback: (Boolean, Int) -> Unit ) { runOnThread { val date = AirUtils.getDatabaseDateFormat(expireDate) val (res, reminderId) = apis.createReminder(userId, reminder, date, channelId, messageId, guildId, inChannel) callback(res, reminderId) } } override fun removeReminder(reminderId: Int, userId: Long, callback: (Boolean) -> Unit) { runOnThread { callback( apis.deleteReminder(userId, reminderId) ) } } override fun showReminder(reminderId: Int, userId: Long, callback: (Reminder?) -> Unit) { runOnThread { val reminderJson = apis.showReminder(userId, reminderId) val reminder: Reminder? = jackson.readValue(reminderJson.traverse(), Reminder::class.java) callback(reminder) } } override fun listReminders(userId: Long, callback: (List<Reminder>) -> Unit) { runOnThread { val remindersJson = apis.listReminders(userId) val reminders = jackson.readValue(remindersJson.traverse(), object : TypeReference<List<Reminder>>() {}) callback(reminders) } } override fun purgeRemindersSync(ids: List<Int>) = apis.purgeReminders(ids) override fun getExpiredReminders(callback: (List<Reminder>) -> Unit) { throw UnsupportedOperationException("Not used anymore") } override fun setWarnActions(guildId: Long, actions: List<WarnAction>) { runOnThread { apis.setWarnActions(guildId, actions) } } override fun createBanBypass(guildId: Long, userId: Long) { runOnThread { apis.createBanBypass(guildId, userId) } } override fun getBanBypass(guildId: Long, userId: Long, callback: (BanBypas?) -> Unit) { runOnThread { val bypassJson = apis.getBanBypass(guildId, userId) val bypass: BanBypas? = jackson.readValue(bypassJson.traverse(), BanBypas::class.java) callback(bypass) } } override fun deleteBanBypass(banBypass: BanBypas) { runOnThread { apis.deleteBanBypass(banBypass.guildId, banBypass.userId) } } }
agpl-3.0
f4149b18476a0f90738835d89281f7a5
31.524017
165
0.585392
4.466567
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/services/discover/ReaderDiscoverLogic.kt
1
13607
package org.wordpress.android.ui.reader.services.discover import android.app.job.JobParameters import com.wordpress.rest.RestRequest.ErrorListener import com.wordpress.rest.RestRequest.Listener import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import org.greenrobot.eventbus.EventBus import org.json.JSONArray import org.json.JSONObject import org.wordpress.android.WordPress import org.wordpress.android.datasets.ReaderBlogTable import org.wordpress.android.datasets.ReaderBlogTableWrapper import org.wordpress.android.datasets.ReaderDiscoverCardsTable import org.wordpress.android.datasets.ReaderPostTable import org.wordpress.android.datasets.wrappers.ReaderTagTableWrapper import org.wordpress.android.models.ReaderBlog import org.wordpress.android.models.ReaderPost import org.wordpress.android.models.ReaderPostList import org.wordpress.android.models.ReaderTag import org.wordpress.android.models.discover.ReaderDiscoverCard import org.wordpress.android.models.discover.ReaderDiscoverCard.InterestsYouMayLikeCard import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderPostCard import org.wordpress.android.models.discover.ReaderDiscoverCard.ReaderRecommendedBlogsCard import org.wordpress.android.modules.AppComponent import org.wordpress.android.ui.prefs.AppPrefsWrapper import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARDS import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARD_DATA import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARD_INTERESTS_YOU_MAY_LIKE import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARD_POST import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARD_RECOMMENDED_BLOGS import org.wordpress.android.ui.reader.ReaderConstants.JSON_CARD_TYPE import org.wordpress.android.ui.reader.ReaderConstants.POST_ID import org.wordpress.android.ui.reader.ReaderConstants.POST_PSEUDO_ID import org.wordpress.android.ui.reader.ReaderConstants.POST_SITE_ID import org.wordpress.android.ui.reader.ReaderConstants.RECOMMENDED_BLOG_ID import org.wordpress.android.ui.reader.ReaderConstants.RECOMMENDED_FEED_ID import org.wordpress.android.ui.reader.ReaderEvents.FetchDiscoverCardsEnded import org.wordpress.android.ui.reader.actions.ReaderActions.UpdateResult.FAILED import org.wordpress.android.ui.reader.actions.ReaderActions.UpdateResult.HAS_NEW import org.wordpress.android.ui.reader.actions.ReaderActions.UpdateResult.UNCHANGED import org.wordpress.android.ui.reader.actions.ReaderActions.UpdateResultListener import org.wordpress.android.ui.reader.repository.usecases.GetDiscoverCardsUseCase import org.wordpress.android.ui.reader.repository.usecases.ParseDiscoverCardsJsonUseCase import org.wordpress.android.ui.reader.repository.usecases.tags.GetFollowedTagsUseCase import org.wordpress.android.ui.reader.services.ServiceCompletionListener import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverLogic.DiscoverTasks.REQUEST_FIRST_PAGE import org.wordpress.android.ui.reader.services.discover.ReaderDiscoverLogic.DiscoverTasks.REQUEST_MORE import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T.READER import java.util.HashMap import javax.inject.Inject /** * This class contains logic related to fetching data for the discover tab in the Reader. */ class ReaderDiscoverLogic( private val completionListener: ServiceCompletionListener, private val coroutineScope: CoroutineScope, appComponent: AppComponent ) { init { appComponent.inject(this) } @Inject lateinit var parseDiscoverCardsJsonUseCase: ParseDiscoverCardsJsonUseCase @Inject lateinit var appPrefsWrapper: AppPrefsWrapper @Inject lateinit var readerTagTableWrapper: ReaderTagTableWrapper @Inject lateinit var getFollowedTagsUseCase: GetFollowedTagsUseCase @Inject lateinit var readerBlogTableWrapper: ReaderBlogTableWrapper @Inject lateinit var getDiscoverCardsUseCase: GetDiscoverCardsUseCase enum class DiscoverTasks { REQUEST_MORE, REQUEST_FIRST_PAGE } private var listenerCompanion: JobParameters? = null fun performTasks(task: DiscoverTasks, companion: JobParameters?) { listenerCompanion = companion requestDataForDiscover(task, UpdateResultListener { EventBus.getDefault().post(FetchDiscoverCardsEnded(task, it)) completionListener.onCompleted(listenerCompanion) }) } private fun requestDataForDiscover(taskType: DiscoverTasks, resultListener: UpdateResultListener) { coroutineScope.launch { val params = HashMap<String, String>() params["tags"] = getFollowedTagsUseCase.get().joinToString { it.tagSlug } when (taskType) { REQUEST_FIRST_PAGE -> { appPrefsWrapper.readerCardsPageHandle = null /* "refresh" parameter is used to tell the server to return a different set of data so we don't present a static content to the user. We need to include it only for the first page (when page_handle is empty). The server will take care of including the "refresh" parameter within the page_handle so the user will stay on the same shard while theyโ€™re paging through the cards. */ params["refresh"] = appPrefsWrapper.getReaderCardsRefreshCounter().toString() appPrefsWrapper.incrementReaderCardsRefreshCounter() } REQUEST_MORE -> { val pageHandle = appPrefsWrapper.readerCardsPageHandle if (pageHandle?.isNotEmpty() == true) { params["page_handle"] = pageHandle } else { // there are no more pages to load resultListener.onUpdateResult(UNCHANGED) return@launch } } } val listener = Listener { jsonObject -> coroutineScope.launch { handleRequestDiscoverDataResponse(taskType, jsonObject, resultListener) } } val errorListener = ErrorListener { volleyError -> AppLog.e(READER, volleyError) resultListener.onUpdateResult(FAILED) } WordPress.getRestClientUtilsV2()["read/tags/cards", params, null, listener, errorListener] } } private suspend fun handleRequestDiscoverDataResponse( taskType: DiscoverTasks, json: JSONObject?, resultListener: UpdateResultListener ) { if (json == null) { resultListener.onUpdateResult(FAILED) return } if (taskType == REQUEST_FIRST_PAGE) { clearCache() } json.optJSONArray(JSON_CARDS)?.let { fullCardsJson -> // Parse the json into cards model objects val cards = parseCards(fullCardsJson) insertPostsIntoDb(cards.filterIsInstance<ReaderPostCard>().map { it.post }) insertBlogsIntoDb(cards.filterIsInstance<ReaderRecommendedBlogsCard>().map { it.blogs }.flatten()) // Simplify the json. The simplified version is used in the upper layers to load the data from the db. val simplifiedCardsJson = createSimplifiedJson(fullCardsJson) insertCardsJsonIntoDb(simplifiedCardsJson) val nextPageHandle = parseDiscoverCardsJsonUseCase.parseNextPageHandle(json) appPrefsWrapper.readerCardsPageHandle = nextPageHandle if (cards.isEmpty()) { readerTagTableWrapper.clearTagLastUpdated(ReaderTag.createDiscoverPostCardsTag()) } else { readerTagTableWrapper.setTagLastUpdated(ReaderTag.createDiscoverPostCardsTag()) } resultListener.onUpdateResult(HAS_NEW) } } private fun parseCards(cardsJsonArray: JSONArray): ArrayList<ReaderDiscoverCard> { val cards: ArrayList<ReaderDiscoverCard> = arrayListOf() for (i in 0 until cardsJsonArray.length()) { val cardJson = cardsJsonArray.getJSONObject(i) when (cardJson.getString(JSON_CARD_TYPE)) { JSON_CARD_INTERESTS_YOU_MAY_LIKE -> { val interests = parseDiscoverCardsJsonUseCase.parseInterestCard(cardJson) cards.add(InterestsYouMayLikeCard(interests)) } JSON_CARD_POST -> { val post = parseDiscoverCardsJsonUseCase.parsePostCard(cardJson) cards.add(ReaderPostCard(post)) } JSON_CARD_RECOMMENDED_BLOGS -> { cardJson?.let { val recommendedBlogs = parseDiscoverCardsJsonUseCase.parseRecommendedBlogsCard(it) cards.add(ReaderRecommendedBlogsCard(recommendedBlogs)) } } } } return cards } private fun insertPostsIntoDb(posts: List<ReaderPost>) { val postList = ReaderPostList() postList.addAll(posts) ReaderPostTable.addOrUpdatePosts(ReaderTag.createDiscoverPostCardsTag(), postList) } private fun insertBlogsIntoDb(blogs: List<ReaderBlog>) { blogs.forEach { blog -> ReaderBlogTable.addOrUpdateBlog(blog) } } /** * This method creates a simplified version of the provided json. * * It for example copies only ids from post object as we don't need to store the gigantic post in the json * as it's already stored in the db. */ @Suppress("NestedBlockDepth") private fun createSimplifiedJson(cardsJsonArray: JSONArray): JSONArray { var index = 0 val simplifiedJson = JSONArray() for (i in 0 until cardsJsonArray.length()) { val cardJson = cardsJsonArray.getJSONObject(i) when (cardJson.getString(JSON_CARD_TYPE)) { JSON_CARD_RECOMMENDED_BLOGS -> { cardJson.optJSONArray(JSON_CARD_DATA)?.let { recommendedBlogsCardJson -> if (recommendedBlogsCardJson.length() > 0) { simplifiedJson.put(index++, createSimplifiedRecommendedBlogsCardJson(cardJson)) } } } JSON_CARD_INTERESTS_YOU_MAY_LIKE -> { simplifiedJson.put(index++, cardJson) } JSON_CARD_POST -> { simplifiedJson.put(index++, createSimplifiedPostJson(cardJson)) } } } return simplifiedJson } /** * Create a simplified copy of the json - keeps only postId, siteId and pseudoId. */ private fun createSimplifiedPostJson(originalCardJson: JSONObject): JSONObject { val originalPostData = originalCardJson.getJSONObject(JSON_CARD_DATA) val simplifiedPostData = JSONObject() // copy only fields which uniquely identify this post simplifiedPostData.put(POST_ID, originalPostData.get(POST_ID)) simplifiedPostData.put(POST_SITE_ID, originalPostData.get(POST_SITE_ID)) simplifiedPostData.put(POST_PSEUDO_ID, originalPostData.get(POST_PSEUDO_ID)) val simplifiedCardJson = JSONObject() simplifiedCardJson.put(JSON_CARD_TYPE, originalCardJson.getString(JSON_CARD_TYPE)) simplifiedCardJson.put(JSON_CARD_DATA, simplifiedPostData) return simplifiedCardJson } @Suppress("NestedBlockDepth") private fun createSimplifiedRecommendedBlogsCardJson(originalCardJson: JSONObject): JSONObject { return JSONObject().apply { JSONArray().apply { originalCardJson.optJSONArray(JSON_CARD_DATA)?.let { jsonRecommendedBlogs -> for (i in 0 until jsonRecommendedBlogs.length()) { JSONObject().apply { val jsonRecommendedBlog = jsonRecommendedBlogs.getJSONObject(i) put(RECOMMENDED_BLOG_ID, jsonRecommendedBlog.optLong(RECOMMENDED_BLOG_ID)) put(RECOMMENDED_FEED_ID, jsonRecommendedBlog.optLong(RECOMMENDED_FEED_ID)) }.let { put(it) } } } }.let { simplifiedRecommendedBlogsJson -> put(JSON_CARD_TYPE, originalCardJson.getString(JSON_CARD_TYPE)) put(JSON_CARD_DATA, simplifiedRecommendedBlogsJson) } } } private fun insertCardsJsonIntoDb(simplifiedCardsJson: JSONArray) { ReaderDiscoverCardsTable.addCardsPage(simplifiedCardsJson.toString()) } private suspend fun clearCache() { val blogIds = getRecommendedBlogsToBeDeleted().map { it.blogId } ReaderBlogTable.deleteBlogsWithIds(blogIds) ReaderDiscoverCardsTable.clear() ReaderPostTable.deletePostsWithTag(ReaderTag.createDiscoverPostCardsTag()) } private suspend fun getRecommendedBlogsToBeDeleted(): List<ReaderBlog> { val discoverCards = getDiscoverCardsUseCase.get() val blogsToBeDeleted = ArrayList<ReaderBlog>() discoverCards.cards.filterIsInstance<ReaderRecommendedBlogsCard>().forEach { it.blogs.forEach { blog -> if (!blog.isFollowing) { blogsToBeDeleted.add(blog) } } } return blogsToBeDeleted } }
gpl-2.0
786d8fc0d30e8a889818928441944202
45.118644
116
0.678868
4.978046
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/tests/testData/script/definition/complex/errorResolver/template/template.kt
5
945
package custom.scriptDefinition import java.io.File import kotlin.script.dependencies.* import kotlin.script.experimental.dependencies.* import kotlin.script.templates.ScriptTemplateDefinition import kotlin.script.experimental.location.ScriptExpectedLocation import kotlin.script.experimental.location.ScriptExpectedLocations var count = 0 class TestDependenciesResolver : DependenciesResolver { override fun resolve( scriptContents: ScriptContents, environment: Environment ): DependenciesResolver.ResolveResult { if (count == 0) { count++ return ScriptDependencies.Empty.asSuccess() } return ScriptDependencies(classpath = environment["lib-classes"] as List<File>).asSuccess() } } @ScriptExpectedLocations([ScriptExpectedLocation.Everywhere]) @ScriptTemplateDefinition(TestDependenciesResolver::class, scriptFilePattern = "script.kts") open class Template
apache-2.0
a8e2f3fe4a0c77617cef3430610f6cc0
34.037037
99
0.765079
5.431034
false
true
false
false
spinnaker/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RunTaskHandler.kt
1
18941
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.BasicTag import com.netflix.spectator.api.Registry import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService import com.netflix.spinnaker.kork.exceptions.UserException import com.netflix.spinnaker.orca.api.pipeline.TaskExecutionInterceptor import com.netflix.spinnaker.orca.TaskResolver import com.netflix.spinnaker.orca.api.pipeline.OverridableTimeoutRetryableTask import com.netflix.spinnaker.orca.api.pipeline.RetryableTask import com.netflix.spinnaker.orca.api.pipeline.Task import com.netflix.spinnaker.orca.api.pipeline.TaskResult import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.CANCELED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.FAILED_CONTINUE import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.PAUSED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.REDIRECT import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SKIPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.STOPPED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.TERMINAL import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware import com.netflix.spinnaker.orca.exceptions.ExceptionHandler import com.netflix.spinnaker.orca.exceptions.TimeoutException import com.netflix.spinnaker.orca.ext.beforeStages import com.netflix.spinnaker.orca.ext.failureStatus import com.netflix.spinnaker.orca.ext.isManuallySkipped import com.netflix.spinnaker.orca.pipeline.RestrictExecutionDuringTimeWindow import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.pipeline.util.StageNavigator import com.netflix.spinnaker.orca.q.CompleteTask import com.netflix.spinnaker.orca.q.InvalidTaskType import com.netflix.spinnaker.orca.q.PauseTask import com.netflix.spinnaker.orca.q.RunTask import com.netflix.spinnaker.orca.q.metrics.MetricsTagHelper import com.netflix.spinnaker.orca.time.toDuration import com.netflix.spinnaker.orca.time.toInstant import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import java.lang.Deprecated import java.time.Clock import java.time.Duration import java.time.Duration.ZERO import java.time.Instant import java.time.temporal.TemporalAmount import java.util.concurrent.TimeUnit import kotlin.collections.set import org.apache.commons.lang3.time.DurationFormatUtils import org.slf4j.MDC import org.springframework.stereotype.Component @Component class RunTaskHandler( override val queue: Queue, override val repository: ExecutionRepository, override val stageNavigator: StageNavigator, override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory, override val contextParameterProcessor: ContextParameterProcessor, private val taskResolver: TaskResolver, private val clock: Clock, private val exceptionHandlers: List<ExceptionHandler>, private val taskExecutionInterceptors: List<TaskExecutionInterceptor>, private val registry: Registry, private val dynamicConfigService: DynamicConfigService ) : OrcaMessageHandler<RunTask>, ExpressionAware, AuthenticationAware { /** * If a task takes longer than this number of ms to run, we will print a warning. * This is an indication that the task might eventually hit the dreaded message ack timeout and might end * running multiple times cause unintended side-effects. */ private val warningInvocationTimeMs: Int = dynamicConfigService.getConfig( Int::class.java, "tasks.warningInvocationTimeMs", 30000 ) override fun handle(message: RunTask) { message.withTask { origStage, taskModel, task -> var stage = origStage stage.withAuth { stage.withLoggingContext(taskModel) { if (task.javaClass.isAnnotationPresent(Deprecated::class.java)) { log.warn("deprecated-task-run ${task.javaClass.simpleName}") } val thisInvocationStartTimeMs = clock.millis() val execution = stage.execution var taskResult: TaskResult? = null var taskException: Exception? = null try { taskExecutionInterceptors.forEach { t -> stage = t.beforeTaskExecution(task, stage) } if (execution.isCanceled) { task.onCancelWithResult(stage)?.run { stage.processTaskOutput(this) } queue.push(CompleteTask(message, CANCELED)) } else if (execution.status.isComplete) { queue.push(CompleteTask(message, CANCELED)) } else if (execution.status == PAUSED) { queue.push(PauseTask(message)) } else if (stage.isManuallySkipped()) { queue.push(CompleteTask(message, SKIPPED)) } else { try { task.checkForTimeout(stage, taskModel, message) } catch (e: TimeoutException) { registry .timeoutCounter(stage.execution.type, stage.execution.application, stage.type, taskModel.name) .increment() taskResult = task.onTimeout(stage) if (taskResult == null) { // This means this task doesn't care to alter the timeout flow, just throw throw e } if (!setOf(TERMINAL, FAILED_CONTINUE).contains(taskResult.status)) { log.error("Task ${task.javaClass.name} returned invalid status (${taskResult.status}) for onTimeout") throw e } } if (taskResult == null) { taskResult = task.execute(stage.withMergedContext()) taskExecutionInterceptors.forEach { t -> taskResult = t.afterTaskExecution(task, stage, taskResult) } } taskResult!!.let { result: TaskResult -> when (result.status) { RUNNING -> { stage.processTaskOutput(result) queue.push(message, task.backoffPeriod(taskModel, stage)) trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status) } SUCCEEDED, REDIRECT, SKIPPED, FAILED_CONTINUE, STOPPED -> { stage.processTaskOutput(result) queue.push(CompleteTask(message, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, result.status) } CANCELED -> { stage.processTaskOutput(result.mergeOutputs(task.onCancelWithResult(stage))) val status = stage.failureStatus(default = result.status) queue.push(CompleteTask(message, status, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, status) } TERMINAL -> { stage.processTaskOutput(result) val status = stage.failureStatus(default = result.status) queue.push(CompleteTask(message, status, result.status)) trackResult(stage, thisInvocationStartTimeMs, taskModel, status) } else -> { stage.processTaskOutput(result) TODO("Unhandled task status ${result.status}") } } } } } catch (e: Exception) { taskException = e; val exceptionDetails = exceptionHandlers.shouldRetry(e, taskModel.name) if (exceptionDetails?.shouldRetry == true) { log.warn("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]") queue.push(message, task.backoffPeriod(taskModel, stage)) trackResult(stage, thisInvocationStartTimeMs, taskModel, RUNNING) } else if (e is TimeoutException && stage.context["markSuccessfulOnTimeout"] == true) { trackResult(stage, thisInvocationStartTimeMs, taskModel, SUCCEEDED) queue.push(CompleteTask(message, SUCCEEDED)) } else { if (e !is TimeoutException) { if (e is UserException) { log.warn("${message.taskType.simpleName} for ${message.executionType}[${message.executionId}] failed, likely due to user error", e) } else { log.error("Error running ${message.taskType.simpleName} for ${message.executionType}[${message.executionId}]", e) } } val status = stage.failureStatus(default = TERMINAL) stage.context["exception"] = exceptionDetails taskModel.taskExceptionDetails["exception"] = exceptionDetails repository.storeStage(stage) queue.push(CompleteTask(message, status, TERMINAL)) trackResult(stage, thisInvocationStartTimeMs, taskModel, status) } } finally { taskExecutionInterceptors.forEach { t -> t.finallyAfterTaskExecution(task, stage, taskResult, taskException) } } } } } } private fun trackResult(stage: StageExecution, thisInvocationStartTimeMs: Long, taskModel: TaskExecution, status: ExecutionStatus) { try { val commonTags = MetricsTagHelper.commonTags(stage, taskModel, status) val detailedTags = MetricsTagHelper.detailedTaskTags(stage, taskModel, status) val elapsedMillis = clock.millis() - thisInvocationStartTimeMs hashMapOf( "task.invocations.duration" to commonTags + BasicTag("application", stage.execution.application), "task.invocations.duration.withType" to commonTags + detailedTags ).forEach { name, tags -> registry.timer(name, tags).record(elapsedMillis, TimeUnit.MILLISECONDS) } if (elapsedMillis >= warningInvocationTimeMs) { log.info( "Task invocation took over ${warningInvocationTimeMs}ms " + "(taskType: ${taskModel.implementingClass}, stageType: ${stage.type}, stageId: ${stage.id})" ) } } catch (e: java.lang.Exception) { log.warn("Failed to track result for stage: ${stage.id}, task: ${taskModel.id}", e) } } override val messageType = RunTask::class.java private fun RunTask.withTask(block: (StageExecution, TaskExecution, Task) -> Unit) = withTask { stage, taskModel -> try { taskResolver.getTask(taskModel.implementingClass) } catch (e: TaskResolver.NoSuchTaskException) { try { taskResolver.getTask(taskType) } catch (e: TaskResolver.NoSuchTaskException) { queue.push(InvalidTaskType(this, taskType.name)) null } }?.let { block.invoke(stage, taskModel, it) } } private fun Task.backoffPeriod(taskModel: TaskExecution, stage: StageExecution): TemporalAmount = when (this) { is RetryableTask -> Duration.ofMillis( retryableBackOffPeriod(taskModel, stage).coerceAtMost(taskExecutionInterceptors.maxBackoff()) ) else -> Duration.ofMillis(1000) } /** * The max back off value always wins. For example, given the following dynamic configs: * `tasks.global.backOffPeriod = 5000` * `tasks.aws.backOffPeriod = 80000` * `tasks.aws.someAccount.backoffPeriod = 60000` * `tasks.aws.backoffPeriod` will be used (given the criteria matches and unless the default dynamicBackOffPeriod is greater). */ private fun RetryableTask.retryableBackOffPeriod( taskModel: TaskExecution, stage: StageExecution ): Long { val dynamicBackOffPeriod = getDynamicBackoffPeriod( stage, Duration.ofMillis(System.currentTimeMillis() - (taskModel.startTime ?: 0)) ) val backOffs: MutableList<Long> = mutableListOf( dynamicBackOffPeriod, dynamicConfigService.getConfig( Long::class.java, "tasks.global.backOffPeriod", dynamicBackOffPeriod ) ) if (this is CloudProviderAware && hasCloudProvider(stage)) { backOffs.add( dynamicConfigService.getConfig( Long::class.java, "tasks.${getCloudProvider(stage)}.backOffPeriod", dynamicBackOffPeriod ) ) if (hasCredentials(stage)) { backOffs.add( dynamicConfigService.getConfig( Long::class.java, "tasks.${getCloudProvider(stage)}.${getCredentials(stage)}.backOffPeriod", dynamicBackOffPeriod ) ) } } return backOffs.max() ?: dynamicBackOffPeriod } private fun List<TaskExecutionInterceptor>.maxBackoff(): Long = this.fold(Long.MAX_VALUE) { backoff, interceptor -> backoff.coerceAtMost(interceptor.maxTaskBackoff()) } private fun formatTimeout(timeout: Long): String { return DurationFormatUtils.formatDurationWords(timeout, true, true) } private fun Task.checkForTimeout(stage: StageExecution, taskModel: TaskExecution, message: Message) { if (stage.type == RestrictExecutionDuringTimeWindow.TYPE) { return } else { checkForStageTimeout(stage) checkForTaskTimeout(taskModel, stage, message) } } private fun Task.checkForTaskTimeout(taskModel: TaskExecution, stage: StageExecution, message: Message) { if (this is RetryableTask) { val startTime = taskModel.startTime.toInstant() if (startTime != null) { val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime) val elapsedTime = Duration.between(startTime, clock.instant()) val actualTimeout = ( if (this is OverridableTimeoutRetryableTask && stage.parentWithTimeout.isPresent) stage.parentWithTimeout.get().timeout.get().toDuration() else getDynamicTimeout(stage).toDuration() ) if (elapsedTime.minus(pausedDuration) > actualTimeout) { val durationString = formatTimeout(elapsedTime.toMillis()) val msg = StringBuilder("${javaClass.simpleName} of stage ${stage.name} timed out after $durationString. ") msg.append("pausedDuration: ${formatTimeout(pausedDuration.toMillis())}, ") msg.append("elapsedTime: ${formatTimeout(elapsedTime.toMillis())}, ") msg.append("timeoutValue: ${formatTimeout(actualTimeout.toMillis())}") log.info(msg.toString()) throw TimeoutException(msg.toString()) } } } } private fun checkForStageTimeout(stage: StageExecution) { stage.parentWithTimeout.ifPresent { val startTime = it.startTime.toInstant() if (startTime != null) { val elapsedTime = Duration.between(startTime, clock.instant()) val pausedDuration = stage.execution.pausedDurationRelativeTo(startTime) val executionWindowDuration = stage.executionWindow?.duration ?: ZERO val timeout = Duration.ofMillis(it.timeout.get()) if (elapsedTime.minus(pausedDuration).minus(executionWindowDuration) > timeout) { throw TimeoutException("Stage ${stage.name} timed out after ${formatTimeout(elapsedTime.toMillis())}") } } } } private val StageExecution.executionWindow: StageExecution? get() = beforeStages() .firstOrNull { it.type == RestrictExecutionDuringTimeWindow.TYPE } private val StageExecution.duration: Duration get() = run { if (startTime == null || endTime == null) { throw IllegalStateException("Only valid on completed stages") } Duration.between(startTime.toInstant(), endTime.toInstant()) } private fun Registry.timeoutCounter( executionType: ExecutionType, application: String, stageType: String, taskType: String ) = counter( createId("queue.task.timeouts") .withTags( mapOf( "executionType" to executionType.toString(), "application" to application, "stageType" to stageType, "taskType" to taskType ) ) ) private fun PipelineExecution.pausedDurationRelativeTo(instant: Instant?): Duration { val pausedDetails = paused return if (pausedDetails != null) { if (pausedDetails.pauseTime.toInstant()?.isAfter(instant) == true) { Duration.ofMillis(pausedDetails.pausedMs) } else ZERO } else ZERO } private fun StageExecution.processTaskOutput(result: TaskResult) { val filteredOutputs = result.outputs.filterKeys { it != "stageTimeoutMs" } if (result.context.isNotEmpty() || filteredOutputs.isNotEmpty()) { context.putAll(result.context) outputs.putAll(filteredOutputs) repository.storeStage(this) } } private fun StageExecution.withLoggingContext(taskModel: TaskExecution, block: () -> Unit) { try { MDC.put("stageType", type) MDC.put("taskType", taskModel.implementingClass) if (taskModel.startTime != null) { MDC.put("taskStartTime", taskModel.startTime.toString()) } block.invoke() } finally { MDC.remove("stageType") MDC.remove("taskType") MDC.remove("taskStartTime") } } private fun TaskResult.mergeOutputs(taskResult: TaskResult?): TaskResult { if (taskResult == null) { return this } return TaskResult.builder(this.status) .outputs( this.outputs.toMutableMap().also { it.putAll(taskResult.outputs) } ) .context( this.context.toMutableMap().also { it.putAll(taskResult.context) } ) .build() } }
apache-2.0
da61667f97b3ddcd3a114caf807b7914
40.628571
149
0.676786
4.888
false
false
false
false
sat2707/aicups
clients/kotlin_client/client/src/main/kotlin/core/API/Debug.kt
1
711
package core.API import org.json.simple.JSONObject import java.util.* class Debug : MessagesInterface { private var messages = ArrayList<JSONObject>() fun log(obj: Any) { val jo = JSONObject() jo.put("command", "log") val args = JSONObject() args.put("text", obj.toString()) jo.put("args", args) this.messages.add(jo) } fun exception(obj: Any) { val jo = JSONObject() jo.put("command", "exception") val args = JSONObject() args.put("text", obj.toString()) jo.put("args", args) this.messages.add(jo) } override fun getMessages(): List<JSONObject> { val result = ArrayList(this.messages) this.messages.clear() return result } }
apache-2.0
384f1cfed49e566dc8889c8b3c59fe2b
17.25641
48
0.632911
3.627551
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/handlers/SmartCompletionTailOffsetProviderFE10Impl.kt
4
1146
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.handlers import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.Lookup import com.intellij.codeInsight.lookup.LookupElement import org.jetbrains.kotlin.idea.completion.KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY import org.jetbrains.kotlin.idea.completion.smart.SmartCompletion import org.jetbrains.kotlin.idea.completion.tryGetOffset class SmartCompletionTailOffsetProviderFE10Impl: SmartCompletionTailOffsetProvider() { override fun getTailOffset(context: InsertionContext, item: LookupElement): Int { val completionChar = context.completionChar var tailOffset = context.tailOffset if (completionChar == Lookup.REPLACE_SELECT_CHAR && item.getUserData(KEEP_OLD_ARGUMENT_LIST_ON_TAB_KEY) != null) { context.offsetMap.tryGetOffset(SmartCompletion.OLD_ARGUMENTS_REPLACEMENT_OFFSET) ?.let { tailOffset = it } } return tailOffset } }
apache-2.0
899b28f86703d693c038eb1cf02a647e
51.136364
158
0.773124
4.324528
false
false
false
false
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUQualifiedReferenceExpression.kt
4
1545
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.uast.kotlin import com.intellij.psi.PsiElement import com.intellij.psi.PsiNamedElement import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.uast.* import org.jetbrains.uast.kotlin.internal.DelegatedMultiResolve @ApiStatus.Internal class KotlinUQualifiedReferenceExpression( override val sourcePsi: KtDotQualifiedExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UQualifiedReferenceExpression, DelegatedMultiResolve, KotlinUElementWithType, KotlinEvaluatableUElement { override val receiver by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.receiverExpression, this) } override val selector by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.selectorExpression, this) } override val accessType = UastQualifiedExpressionAccessType.SIMPLE override fun resolve(): PsiElement? = sourcePsi.selectorExpression?.let { baseResolveProviderService.resolveToDeclaration(it) } override val resolvedName: String? get() = (resolve() as? PsiNamedElement)?.name override val referenceNameElement: UElement? get() = when (val selector = selector) { is UCallExpression -> selector.methodIdentifier else -> super.referenceNameElement } }
apache-2.0
ce1c2204d8ff3e224c15acce25ba77fc
47.28125
158
0.79288
5.478723
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/sheet/BaseBottomSheetDialog.kt
3
2167
package eu.kanade.tachiyomi.widget.sheet import android.content.Context import android.os.Build import android.os.Bundle import android.util.DisplayMetrics import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.android.material.bottomsheet.getElevation import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.util.system.displayCompat import eu.kanade.tachiyomi.util.system.isNightMode import eu.kanade.tachiyomi.util.view.setNavigationBarTransparentCompat abstract class BaseBottomSheetDialog(context: Context) : BottomSheetDialog(context) { abstract fun createView(inflater: LayoutInflater): View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val rootView = createView(layoutInflater) setContentView(rootView) // Enforce max width for tablets val width = context.resources.getDimensionPixelSize(R.dimen.bottom_sheet_width) if (width > 0) { behavior.maxWidth = width } // Set peek height to 50% display height context.displayCompat?.let { val metrics = DisplayMetrics() it.getRealMetrics(metrics) behavior.peekHeight = metrics.heightPixels / 2 } // Set navbar color to transparent for edge-to-edge bottom sheet if we can use light navigation bar // TODO Replace deprecated systemUiVisibility when material-components uses new API to modify status bar icons @Suppress("DEPRECATION") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { window?.setNavigationBarTransparentCompat(context, behavior.getElevation()) val bottomSheet = rootView.parent as ViewGroup var flags = bottomSheet.systemUiVisibility flags = if (context.isNightMode()) { flags and View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR.inv() } else { flags or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } bottomSheet.systemUiVisibility = flags } } }
apache-2.0
fa96307f778b2e68a1d0f8836e24693e
38.4
118
0.706045
4.869663
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/browse/migration/search/SourceSearchController.kt
2
1577
package eu.kanade.tachiyomi.ui.browse.migration.search import android.os.Bundle import android.view.View import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.source.CatalogueSource import eu.kanade.tachiyomi.ui.browse.source.browse.BrowseSourceController import eu.kanade.tachiyomi.ui.browse.source.browse.SourceItem class SourceSearchController( bundle: Bundle ) : BrowseSourceController(bundle) { constructor(manga: Manga? = null, source: CatalogueSource, searchQuery: String? = null) : this( Bundle().apply { putLong(SOURCE_ID_KEY, source.id) putSerializable(MANGA_KEY, manga) if (searchQuery != null) { putString(SEARCH_QUERY_KEY, searchQuery) } } ) private var oldManga: Manga? = args.getSerializable(MANGA_KEY) as Manga? private var newManga: Manga? = null override fun onItemClick(view: View, position: Int): Boolean { val item = adapter?.getItem(position) as? SourceItem ?: return false newManga = item.manga val searchController = router.backstack.findLast { it.controller.javaClass == SearchController::class.java }?.controller as SearchController? val dialog = SearchController.MigrationDialog(oldManga, newManga, this) dialog.targetController = searchController dialog.showDialog(router) return true } override fun onItemLongClick(position: Int) { view?.let { super.onItemClick(it, position) } } } private const val MANGA_KEY = "oldManga"
apache-2.0
aeaeb6febc1c99735d97c90b9cbcac93
36.547619
149
0.696893
4.405028
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/controls/behaviours/EnumCycleCommand.kt
2
2243
package graphics.scenery.controls.behaviours import graphics.scenery.utils.LazyLogger import org.scijava.ui.behaviour.ClickBehaviour import java.lang.reflect.InvocationTargetException /** * Enum advance command class. Enables to call a single-parameter method with a successive list of * enum [values] by the press of a button. The value used for calling is incremented with each call * and wrapped upon arriving at the end of the list. The [method] called should provide the user some * feedback about the change made, as this command does not (although a debug message is emitted, * containing the receiver, method, and current value). * * @author Ulrik Gรผnther <[email protected]> * @property[values] The enum properties to use. * @property[receiver] The receiving object. * @property[method] The name of the single-parameter method to invoke. */ class EnumCycleCommand<T: Enum<*>>(private val enumClass: Class<T>, private val receiver: Any, private val method: String) : ClickBehaviour { private val logger by LazyLogger() private var currentIndex = 0 /** * This function is called upon arrival of an event that concerns * this behaviour. It will execute the given method on the given object instance. * * @param[x] x position in window (unused) * @param[y] y position in window (unused) */ override fun click(x: Int, y: Int) { val values = enumClass.enumConstants if(values.isEmpty()) { return } try { val clazz = values.get(0)::class.java val m = receiver.javaClass.getMethod(method, clazz) m.invoke(receiver, values[currentIndex]) logger.debug("Ran ${receiver.javaClass.simpleName}.$method(${values[currentIndex].name})") currentIndex = (currentIndex + 1) % values.size } catch(e: NoSuchMethodException) { logger.warn("Method $method not found for ${receiver.javaClass.simpleName}") } catch(e: InvocationTargetException) { logger.warn("Method $method for ${receiver.javaClass.simpleName} threw an error: $e:") e.printStackTrace() } } }
lgpl-3.0
137cdf987129d09767b4ba72a693b9be
40.518519
102
0.662355
4.566191
false
false
false
false
mikhalchenko-alexander/nirvana-player
src/main/kotlin/com/anahoret/nirvanaplayer/components/medialibrary/MediaLibrary.kt
1
2148
package com.anahoret.nirvanaplayer.components.medialibrary import com.anahoret.nirvanaplayer.components.AbstractComponent import com.anahoret.nirvanaplayer.components.appendChild import com.anahoret.nirvanaplayer.model.FolderDto import kotlinx.html.* import kotlinx.html.dom.create import org.w3c.xhr.XMLHttpRequest import kotlin.browser.document class MediaLibrary(mediaLibraryUrl: String): AbstractComponent() { override val element = document.create.div("player-media-library") private val trackPlaylistButtonClickListeners = ArrayList<(Track.TrackPlaylistButtonClickEvent) -> Unit>() private val folderPlaylistButtonClickListeners = ArrayList<(Folder.FolderPlaylistButtonClickEvent) -> Unit>() init { loadMediaLibrary(mediaLibraryUrl) { val folder = Folder(it, 0) folder.addTrackPlaylistButtonClickListener(this::fireTrackPlaylistButtonClickEvent) folder.addFolderPlaylistButtonClickListener(this::fireFolderPlaylistButtonClickEvent) element.appendChild(folder) } } private fun loadMediaLibrary(mediaLibraryUrl: String, onSuccess: (FolderDto) -> Unit) { val xhr = XMLHttpRequest() xhr.open("GET", mediaLibraryUrl, true) xhr.send() xhr.onreadystatechange = { if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.status == 200.toShort()) { val folder = JSON.parse<FolderDto>(xhr.responseText) onSuccess(folder) } else { println("Error loading media library. Status ${xhr.status}.") } } } } fun addFolderPlaylistButtonClickListener(l: (Folder.FolderPlaylistButtonClickEvent) -> Unit) { folderPlaylistButtonClickListeners.add(l) } private fun fireFolderPlaylistButtonClickEvent(event: Folder.FolderPlaylistButtonClickEvent) { folderPlaylistButtonClickListeners.forEach { it(event) } } fun addTrackPlaylistButtonClickListener(l: (Track.TrackPlaylistButtonClickEvent) -> Unit) { trackPlaylistButtonClickListeners.add(l) } private fun fireTrackPlaylistButtonClickEvent(event: Track.TrackPlaylistButtonClickEvent) { trackPlaylistButtonClickListeners.forEach { it(event) } } }
apache-2.0
1a72394b32097b8af7b996da2f6597b2
34.8
111
0.759311
4.287425
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/bottom-mpp/src/jvmWithJavaiOSMain/kotlin/transitiveStory/midActual/sourceCalls/intemediateCall/SecondModCaller.kt
4
2157
package transitiveStory.midActual.sourceCalls.intemediateCall import transitiveStory.bottomActual.mppBeginning.BottomActualDeclarations import transitiveStory.bottomActual.mppBeginning.regularTLfunInTheBottomActualCommmon // https://youtrack.jetbrains.com/issue/KT-33731 import transitiveStory.bottomActual.intermediateSrc.* class SecondModCaller { // ========= api calls (attempt to) ========== // java val jApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JavaApiContainer'")!>JavaApiContainer<!>() // kotlin val kApiOne = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: KotlinApiContainer'")!>KotlinApiContainer<!>() // ========= mpp-bottom-actual calls ========== // common source set val interCallOne = regularTLfunInTheBottomActualCommmon("Some string from `mpp-mid-actual` module") val interCallTwo = BottomActualDeclarations.inTheCompanionOfBottomActualDeclarations val interCallThree = BottomActualDeclarations().simpleVal // https://youtrack.jetbrains.com/issue/KT-33731 // intermediate source set val interCallFour = InBottomActualIntermediate().p val interCallFive = IntermediateMPPClassInBottomActual() // ========= jvm18 source set (attempt to) ========== // java val interCallSix = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: JApiCallerInJVM18'")!>JApiCallerInJVM18<!>() // kotlin val interCallSeven = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18KApiInheritor'")!>Jvm18KApiInheritor<!>() val interCallEight = <!HIGHLIGHTING("severity='ERROR'; descr='[UNRESOLVED_REFERENCE] Unresolved reference: Jvm18JApiInheritor'")!>Jvm18JApiInheritor<!>() val interCallNine = IntermediateMPPClassInBottomActual() } // experiments with intermod inheritance class BottomActualCommonInheritor : BottomActualDeclarations() expect class <!LINE_MARKER("descr='Has actuals in [multimod-hmpp.bottom-mpp.iosSimLibMain, bottom-mpp] module'")!>BottomActualMPPInheritor<!> : BottomActualDeclarations
apache-2.0
2fcf21fee8cb71c06839f2533f1b5cb2
51.609756
168
0.754752
4.804009
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/util/PostImpl.kt
1
23054
package jp.juggler.subwaytooter.util import android.os.SystemClock import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.Styler import jp.juggler.subwaytooter.api.* import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.dialog.DlgConfirm.confirm import jp.juggler.subwaytooter.emoji.CustomEmoji import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.span.MyClickableSpan import jp.juggler.subwaytooter.table.AcctColor import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.table.TagSet import jp.juggler.util.* import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import java.util.* import java.util.concurrent.atomic.AtomicBoolean sealed class PostResult { class Normal( val targetAccount: SavedAccount, val status: TootStatus, ) : PostResult() class Scheduled( val targetAccount: SavedAccount, ) : PostResult() } @Suppress("LongParameterList") class PostImpl( val activity: AppCompatActivity, val account: SavedAccount, val content: String, // nullใฏCWใƒใ‚งใƒƒใ‚ฏใชใ—ใ‚’็คบใ™ // nullใ˜ใ‚ƒใชใใฆใ‚ซใƒฉใชใ‚‰ใ‚จใƒฉใƒผ val spoilerText: String?, val visibilityArg: TootVisibility, val bNSFW: Boolean, val inReplyToId: EntityId?, val attachmentListArg: List<PostAttachment>?, enqueteItemsArg: List<String>?, val pollType: TootPollsType?, val pollExpireSeconds: Int, val pollHideTotals: Boolean, val pollMultipleChoice: Boolean, val scheduledAt: Long, val scheduledId: EntityId?, val redraftStatusId: EntityId?, val editStatusId: EntityId?, val emojiMapCustom: HashMap<String, CustomEmoji>?, var useQuoteToot: Boolean, var lang: String, ) { companion object { private val log = LogCategory("PostImpl") private val reAscii = """[\x00-\x7f]""".asciiPattern() private val reNotAscii = """[^\x00-\x7f]""".asciiPattern() private var lastPostTapped: Long = 0L private val isPosting = AtomicBoolean(false) } private val attachmentList = attachmentListArg?.mapNotNull { it.attachment }?.notEmpty() // null ใ ใจๆŠ•็ฅจใ‚’ไฝœๆˆใ—ใชใ„ใ€‚็ฉบใƒชใ‚นใƒˆใฏใ‚จใƒฉใƒผ private val enqueteItems = enqueteItemsArg?.filter { it.isNotEmpty() } private var visibilityChecked: TootVisibility? = null private val choiceMaxChars = when { account.isMisskey -> 15 pollType == TootPollsType.FriendsNico -> 15 else -> 40 // TootPollsType.Mastodon } private fun preCheckPollItemOne(list: List<String>, idx: Int, item: String) { // ้ธๆŠž่‚ขใŒ้•ทใ™ใŽใ‚‹ val cpCount = item.codePointCount(0, item.length) if (cpCount > choiceMaxChars) { val over = cpCount - choiceMaxChars activity.errorString(R.string.enquete_item_too_long, idx + 1, over) } // ไป–ใฎ้ …็›ฎใจ้‡่ค‡ใ—ใฆใ„ใ‚‹ if ((0 until idx).any { list[it] == item }) { activity.errorString(R.string.enquete_item_duplicate, idx + 1) } } private var resultStatus: TootStatus? = null private var resultCredentialTmp: TootAccount? = null private var resultScheduledStatusSucceeded = false private suspend fun getCredential( client: TootApiClient, parser: TootParser, ): TootApiResult? { return client.request("/api/v1/accounts/verify_credentials")?.also { result -> resultCredentialTmp = parser.account(result.jsonObject) } } private suspend fun getWebVisibility( client: TootApiClient, parser: TootParser, instance: TootInstance, ): TootVisibility? { if (account.isMisskey || instance.versionGE(TootInstance.VERSION_1_6)) return null val r2 = getCredential(client, parser) val credentialTmp = resultCredentialTmp ?: errorApiResult(r2) val privacy = credentialTmp.source?.privacy ?: errorApiResult(activity.getString(R.string.cant_get_web_setting_visibility)) return TootVisibility.parseMastodon(privacy) // may null, not error } private fun checkServerHasVisibility( actual: TootVisibility?, extra: TootVisibility, instance: TootInstance, checkFun: (TootInstance) -> Boolean, ) { if (actual != extra || checkFun(instance)) return val strVisibility = Styler.getVisibilityString(activity, account.isMisskey, extra) errorApiResult( activity.getString( R.string.server_has_no_support_of_visibility, strVisibility ) ) } private suspend fun checkVisibility( client: TootApiClient, parser: TootParser, instance: TootInstance, ): TootVisibility? { val v = when (visibilityArg) { TootVisibility.WebSetting -> getWebVisibility(client, parser, instance) else -> visibilityArg } checkServerHasVisibility( v, TootVisibility.Mutual, instance, InstanceCapability::visibilityMutual ) checkServerHasVisibility( v, TootVisibility.Limited, instance, InstanceCapability::visibilityLimited ) return v } private suspend fun deleteStatus(client: TootApiClient) { val result = if (account.isMisskey) { client.request( "/api/notes/delete", account.putMisskeyApiToken(JsonObject()).apply { put("noteId", redraftStatusId) }.toPostRequestBuilder() ) } else { client.request( "/api/v1/statuses/$redraftStatusId", Request.Builder().delete() ) } log.d("delete redraft. result=$result") delay(2000L) } private suspend fun deleteScheduledStatus(client: TootApiClient) { val result = client.request( "/api/v1/scheduled_statuses/$scheduledId", Request.Builder().delete() ) log.d("delete old scheduled status. result=$result") delay(2000L) } private suspend fun encodeParamsMisskey(json: JsonObject, client: TootApiClient) { account.putMisskeyApiToken(json) json["viaMobile"] = true json["text"] = EmojiDecoder.decodeShortCode(content, emojiMapCustom = emojiMapCustom) spoilerText?.notEmpty()?.let { json["cw"] = EmojiDecoder.decodeShortCode(it, emojiMapCustom = emojiMapCustom) } inReplyToId?.toString()?.let { json[if (useQuoteToot) "renoteId" else "replyId"] = it } when (val visibility = visibilityChecked) { null -> Unit TootVisibility.DirectSpecified, TootVisibility.DirectPrivate -> { val userIds = JsonArray() val m = TootAccount.reMisskeyMentionPost.matcher(content) while (m.find()) { val username = m.groupEx(1) val host = m.groupEx(2) // may null client.request( "/api/users/show", account.putMisskeyApiToken().apply { username.notEmpty()?.let { put("username", it) } host.notEmpty()?.let { put("host", it) } }.toPostRequestBuilder() )?.let { result -> result.jsonObject?.string("id").notEmpty()?.let { userIds.add(it) } } } json["visibility"] = when { userIds.isNotEmpty() -> { json["visibleUserIds"] = userIds "specified" } account.misskeyVersion >= 11 -> "specified" else -> "private" } } else -> { val localVis = visibility.strMisskey.replace("^local-".toRegex(), "") if (localVis != visibility.strMisskey) json["localOnly"] = true json["visibility"] = localVis } } if (attachmentList != null) { val array = JsonArray() for (a in attachmentList) { // Misskeyใฏ็”ปๅƒใฎๅ†ๅˆฉ็”จใซๅ•้กŒใŒใชใ„ใฎใง redraftใจใƒใƒผใ‚ธใƒงใƒณใฎใƒใ‚งใƒƒใ‚ฏใฏ่กŒใ‚ใชใ„ array.add(a.id.toString()) // Misskeyใฎๅ ดๅˆใ€NSFWใ™ใ‚‹ใซใฏใ‚ขใƒƒใƒ—ใƒญใƒผใƒ‰ๆธˆใฟใฎ็”ปๅƒใ‚’ drive/files/update ใงๆ›ดๆ–ฐใ™ใ‚‹ if (bNSFW) { val r = client.request( "/api/drive/files/update", account.putMisskeyApiToken().apply { put("fileId", a.id.toString()) put("isSensitive", true) } .toPostRequestBuilder() ) if (r == null || r.error != null) errorApiResult(r) } } if (array.isNotEmpty()) json["mediaIds"] = array } if (enqueteItems?.isNotEmpty() == true) { val choices = JsonArray().apply { for (item in enqueteItems) { val text = EmojiDecoder.decodeShortCode(item, emojiMapCustom = emojiMapCustom) if (text.isEmpty()) continue add(text) } } if (choices.isNotEmpty()) { json["poll"] = jsonObjectOf("choices" to choices) } } } private fun encodeParamsMastodon(json: JsonObject, instance: TootInstance) { when (val lang = lang.trim()) { // Web่จญๅฎšใซๅพ“ใ†ใชใ‚‰ๆŒ‡ๅฎšใ—ใชใ„ SavedAccount.LANG_WEB, "" -> Unit // ็ซฏๆœซใฎ่จ€่ชžใ‚ณใƒผใƒ‰ SavedAccount.LANG_DEVICE -> json["language"] = Locale.getDefault().language // ใใฎไป– else -> json["language"] = lang } visibilityChecked?.let { json["visibility"] = it.strMastodon } json["status"] = EmojiDecoder.decodeShortCode(content, emojiMapCustom = emojiMapCustom) json["sensitive"] = bNSFW json["spoiler_text"] = EmojiDecoder.decodeShortCode(spoilerText ?: "", emojiMapCustom = emojiMapCustom) inReplyToId?.toString() ?.let { json[if (useQuoteToot) "quote_id" else "in_reply_to_id"] = it } if (attachmentList != null) { json["media_ids"] = jsonArray { for (a in attachmentList) { if (a.redraft && !instance.versionGE(TootInstance.VERSION_2_4_1)) continue add(a.id.toString()) } } } if (enqueteItems != null) { if (pollType == TootPollsType.Mastodon) { json["poll"] = jsonObject { put("multiple", pollMultipleChoice) put("hide_totals", pollHideTotals) put("expires_in", pollExpireSeconds) put("options", enqueteItems.map { EmojiDecoder.decodeShortCode(it, emojiMapCustom = emojiMapCustom) }.toJsonArray()) } } else { json["isEnquete"] = true json["enquete_items"] = enqueteItems.map { EmojiDecoder.decodeShortCode(it, emojiMapCustom = emojiMapCustom) }.toJsonArray() } } if (scheduledAt != 0L) { if (!instance.versionGE(TootInstance.VERSION_2_7_0_rc1)) { errorApiResult(activity.getString(R.string.scheduled_status_requires_mastodon_2_7_0)) } // UTCใฎๆ—ฅๆ™‚ใ‚’ๆธกใ™ val c = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC")) c.timeInMillis = scheduledAt val sv = String.format( Locale.JAPANESE, "%d-%02d-%02dT%02d:%02d:%02d.%03dZ", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND), c.get(Calendar.MILLISECOND) ) json["scheduled_at"] = sv } } private fun saveStatusTag(status: TootStatus?) { status ?: return val s = status.decoded_content val spanList = s.getSpans(0, s.length, MyClickableSpan::class.java) if (spanList != null) { val tagList = ArrayList<String?>(spanList.size) for (span in spanList) { val start = s.getSpanStart(span) val end = s.getSpanEnd(span) val text = s.subSequence(start, end).toString() if (text.startsWith("#")) { tagList.add(text.substring(1)) } } val count = tagList.size if (count > 0) { TagSet.saveList(System.currentTimeMillis(), tagList, 0, count) } } } suspend fun runSuspend(): PostResult { if (account.isMisskey) { attachmentList ?.notEmpty() ?.map { it.id.toString() } ?.takeIf { it != it.distinct() } ?.let { activity.errorString(R.string.post_error_attachments_duplicated) } } if (content.isEmpty() && attachmentList == null) { activity.errorString(R.string.post_error_contents_empty) } // nullใฏCWใƒใ‚งใƒƒใ‚ฏใชใ—ใ‚’็คบใ™ // nullใ˜ใ‚ƒใชใใฆใ‚ซใƒฉใชใ‚‰ใ‚จใƒฉใƒผ if (spoilerText != null && spoilerText.isEmpty()) { activity.errorString(R.string.post_error_contents_warning_empty) } if (!enqueteItems.isNullOrEmpty()) { if (enqueteItems.size < 2) { activity.errorString(R.string.enquete_item_is_empty, enqueteItems.size + 1) } enqueteItems.forEachIndexed { i, v -> preCheckPollItemOne(enqueteItems, i, v) } } if (scheduledAt != 0L && account.isMisskey) { error("misskey has no scheduled status API") } if (PrefB.bpWarnHashtagAsciiAndNonAscii()) { TootTag.findHashtags(content, account.isMisskey) ?.filter { val hasAscii = reAscii.matcher(it).find() val hasNotAscii = reNotAscii.matcher(it).find() hasAscii && hasNotAscii }?.map { "#$it" } ?.notEmpty() ?.let { badTags -> activity.confirm( R.string.hashtag_contains_ascii_and_not_ascii, badTags.joinToString(", ") ) } } val isMisskey = account.isMisskey if (!visibilityArg.isTagAllowed(isMisskey)) { TootTag.findHashtags(content, isMisskey) ?.notEmpty() ?.let { tags -> log.d("findHashtags ${tags.joinToString(",")}") activity.confirm( R.string.hashtag_and_visibility_not_match ) } } if (redraftStatusId != null) { activity.confirm(R.string.delete_base_status_before_toot) } if (scheduledId != null) { activity.confirm(R.string.delete_scheduled_status_before_update) } activity.confirm( activity.getString(R.string.confirm_post_from, AcctColor.getNickname(account)), account.confirm_post ) { newConfirmEnabled -> account.confirm_post = newConfirmEnabled account.saveSetting() } // ใƒœใ‚ฟใƒณ้€ฃๆ‰“ๅˆคๅฎš val now = SystemClock.elapsedRealtime() val delta = now - lastPostTapped lastPostTapped = now if (delta < 1000L) { log.e("lastPostTapped within 1 sec!") activity.showToast(false, R.string.post_button_tapped_repeatly) throw CancellationException("post_button_tapped_repeatly") } // ๆŠ•็จฟไธญใซๅ†ๅบฆๆŠ•็จฟใƒœใ‚ฟใƒณใŒๆŠผใ•ใ‚ŒใŸ if (isPosting.get()) { log.e("other postJob is active!") activity.showToast(false, R.string.post_button_tapped_repeatly) throw CancellationException("preCheck failed.") } // ๅ…จใฆใฎ็ขบ่ชใ‚’็ต‚ใˆใŸใ‚‰ใƒใƒƒใ‚ฏใ‚ฐใƒฉใ‚ฆใƒณใƒ‰ใงใฎๅ‡ฆ็†ใ‚’้–‹ๅง‹ใ™ใ‚‹ isPosting.set(true) return try { withContext(Dispatchers.Main) { activity.runApiTask( account, progressSetup = { it.setCanceledOnTouchOutside(false) }, ) { client -> val (instance, ri) = TootInstance.get(client) instance ?: return@runApiTask ri if (instance.instanceType == InstanceType.Pixelfed) { // Pixelfedใฏ่ฟ”ไฟกใซ็”ปๅƒใ‚’ๆทปไป˜ใงใใชใ„ if (inReplyToId != null && attachmentList != null) { return@runApiTask TootApiResult(getString(R.string.pixelfed_does_not_allow_reply_with_media)) } // Pixelfedใฎ่ฟ”ไฟกใงใฏใชใ„ๆŠ•็จฟใฏ็”ปๅƒๆทปไป˜ใŒๅฟ…้ ˆ if (inReplyToId == null && attachmentList == null) { return@runApiTask TootApiResult(getString(R.string.pixelfed_does_not_allow_post_without_media)) } } val parser = TootParser(this, account) [email protected] = try { checkVisibility(client, parser, instance) // may null } catch (ex: TootApiResultException) { return@runApiTask ex.result } if (redraftStatusId != null) { // ๅ…ƒใฎๆŠ•็จฟใ‚’ๅ‰Š้™คใ™ใ‚‹ deleteStatus(client) } else if (scheduledId != null) { deleteScheduledStatus(client) } val json = JsonObject() try { if (account.isMisskey) { encodeParamsMisskey(json, client) } else { encodeParamsMastodon(json, instance) } } catch (ex: TootApiResultException) { return@runApiTask ex.result } catch (ex: JsonException) { log.trace(ex) log.e(ex, "status encoding failed.") } val bodyString = json.toString() fun createRequestBuilder(isPut: Boolean = false): Request.Builder { val requestBody = bodyString.toRequestBody(MEDIA_TYPE_JSON) return when { isPut -> Request.Builder().put(requestBody) else -> Request.Builder().post(requestBody) }.also { if (!PrefB.bpDontDuplicationCheck()) { val digest = (bodyString + account.acct.ascii).digestSHA256Hex() it.header("Idempotency-Key", digest) } } } when { account.isMisskey -> client.request( "/api/notes/create", createRequestBuilder() ) editStatusId != null -> client.request( "/api/v1/statuses/$editStatusId", createRequestBuilder(isPut = true) ) else -> client.request( "/api/v1/statuses", createRequestBuilder() ) }?.also { result -> val jsonObject = result.jsonObject if (scheduledAt != 0L && jsonObject != null) { // {"id":"3","scheduled_at":"2019-01-06T07:08:00.000Z","media_attachments":[]} resultScheduledStatusSucceeded = true return@runApiTask result } else { val status = parser.status( when { account.isMisskey -> jsonObject?.jsonObject("createdNote") ?: jsonObject else -> jsonObject } ) resultStatus = status saveStatusTag(status) } } }.let { result -> if (result == null) throw CancellationException() val status = resultStatus when { resultScheduledStatusSucceeded -> PostResult.Scheduled(account) // ้€ฃๆŠ•ใ—ใฆIdempotency ใŒๅŒใ˜ใ ใฃใŸๅ ดๅˆใ‚‚ใ‚จใƒฉใƒผใซใฏใชใ‚‰ใšใ€ใ“ใ“ใ‚’้€šใ‚‹ status != null -> PostResult.Normal(account, status) else -> error(result.error ?: "(result.error is null)") } } } } finally { isPosting.set(false) } } }
apache-2.0
7ce8ef2d084de0c378b754f536c2007c
35.605351
123
0.504891
4.888696
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/ExtensionFlags.kt
1
63915
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengles.templates import org.lwjgl.generator.* import opengles.* val EXT = "EXT" val KHR = "KHR" val AMD = "AMD" val ANDROID = "ANDROID" val ANGLE = "ANGLE" val APPLE = "APPLE" val ARM = "ARM" val DMP = "DMP" val FJ = "FJ" val IMG = "IMG" val INTEL = "INTEL" val MESA = "MESA" val NV = "NV" val NVX = "NVX" val OES = "OES" val OVR = "OVR" val QCOM = "QCOM" val VIV = "VIV" private val NativeClass.cap: String get() = "{@link \\#$capName $templateName}" val ANDROID_extension_pack_es31a = EXT_FLAG.nativeClassGLES("ANDROID_extension_pack_es31a", postfix = ANDROID) { documentation = """ When true, the $registryLink extension is supported. This extension changes little functionality directly. Instead it serves to roll up the 20 extensions it requires, allowing applications to check for all of them at once, and enable all of their shading language features with a single \#extension statement. The Android platform provides special support outside of OpenGL ES to help applications target this set of extensions. In addition, this extension ensures support for images, shader storage buffers, and atomic counters in fragment shaders. In unextended OpenGL ES the minimum value of the relevant implementation-defined limits is zero; this extension raises these minimums to match the minimums for compute shaders. Requires ${GLES31.core}. """ } val APPLE_color_buffer_packed_float = EXT_FLAG.nativeClassGLES("APPLE_color_buffer_packed_float", postfix = APPLE) { documentation = """ When true, the $registryLink extension is supported. This extension allows two packed floating point formats R11F_G11F_B10F and as RGB9_E5 defined in APPLE_texture_packed_float or OpenGL ES 3.0 or to be rendered to via framebuffer objects. Requires ${EXT_color_buffer_half_float.link} and ${GLES30.core} or ${APPLE_texture_packed_float.link}. """ } val ARM_rgba8 = EXT_FLAG.nativeClassGLES("ARM_rgba8", postfix = ARM) { documentation = """ When true, the $registryLink extension is supported. This extension enables a RGBA8 renderbuffer storage format. It is similar to OES_rgb8_rgba8, but only exposes RGBA8. Requires ${GLES20.core}. """ } val ARM_shader_framebuffer_fetch_depth_stencil = EXT_FLAG.nativeClassGLES("ARM_shader_framebuffer_fetch_depth_stencil", postfix = ARM) { documentation = """ When true, the $registryLink extension is supported. Existing extensions, such as EXT_shader_framebuffer_fetch, allow fragment shaders to read existing framebuffer color data as input. This enables use-cases such as programmable blending, and other operations that may not be possible to implement with fixed-function blending. This extension adds similar capabilities for depth and stencil values. One use-case for this is soft depth-blending of particles. Normally, this would require two render passes: one that writes out the depth values of the background geometry to a depth texture, and one that renders the particles while reading from the depth texture to do the blending. This extension allows this to be done in a single pass. Requires ${GLES20.core}. """ } val EXT_color_buffer_float = EXT_FLAG.nativeClassGLES("EXT_color_buffer_float", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension allows a variety of floating point formats to be rendered to via framebuffer objects. Requires ${GLES30.core}. """ } val EXT_compressed_ETC1_RGB8_sub_texture = EXT_FLAG.nativeClassGLES("EXT_compressed_ETC1_RGB8_sub_texture", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. """ } val EXT_conservative_depth = EXT_FLAG.nativeClassGLES("EXT_conservative_depth", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. There is a common optimization for hardware accelerated implementation of OpenGL ES which relies on an early depth test to be run before the fragment shader so that the shader evaluation can be skipped if the fragment ends up being discarded because it is occluded. This optimization does not affect the final rendering, and is typically possible when the fragment does not change the depth programmatically. (i.e.: it does not write to the built-in {@code gl_FragDepth} output). There are, however a class of operations on the depth in the shader which could still be performed while allowing the early depth test to operate. This extension allows the application to pass enough information to the GL implementation to activate such optimizations safely. Requires ${GLES30.core}. """ } val EXT_EGL_image_array = EXT_FLAG.nativeClassGLES("EXT_EGL_image_array", postfix = EXT) { documentation = """ This extension adds functionality to that provided by ${OES_EGL_image.link} in order to support EGLImage 2D arrays. It extends the existing {@code EGLImageTargetTexture2DOES} entry point from {@code OES_EGL_image}. Render buffers are not extended to include array support. {@code EGLImage} 2D arrays can be created using extended versions of {@code eglCreateImageKHR}. For example, {@code EGL_ANDROID_image_native_buffer} can import image array native buffers on devices where such native buffers can be created. """ } val EXT_EGL_image_external_wrap_modes = EXT_FLAG.nativeClassGLES("EXT_EGL_image_external_wrap_modes", postfix = EXT) { documentation = """ This extension builds on ${OES_EGL_image_external.link}, which only allows a external images to use a single clamping wrap mode: #CLAMP_TO_EDGE. This extension relaxes that restriction, allowing wrap modes #REPEAT and #MIRRORED_REPEAT. If ${OES_texture_border_clamp.link} is supported, then #CLAMP_TO_BORDER is also allowed. This extension similarly adds to the capabilities of {@code OES_EGL_image_external_essl3}, allowing the same additional wrap modes. Since external images can be non-RGB, this extension clarifies how border color values are specified for non-RGB external images. """ } val EXT_float_blend = EXT_FLAG.nativeClassGLES("EXT_float_blend", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension expands upon the EXT_color_buffer_float extension to allow support for blending with 32-bit floating-point color buffers. Requires ${EXT_color_buffer_float.cap}. """ } val EXT_gpu_shader5 = EXT_FLAG.nativeClassGLES("EXT_gpu_shader5", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension provides a set of new features to the OpenGL ES Shading Language and related APIs to support capabilities of new GPUs, extending the capabilities of version 3.10 of the OpenGL ES Shading Language. Shaders using the new functionality provided by this extension should enable this functionality via the construct ${codeBlock(""" \#extension GL_EXT_gpu_shader5 : require (or enable)""")} This extension provides a variety of new features for all shader types, including: ${ul( "support for indexing into arrays of opaque types (samplers, and atomic counters) using dynamically uniform integer expressions;", "support for indexing into arrays of images and shader storage blocks using only constant integral expressions;", "extending the uniform block capability to allow shaders to index into an array of uniform blocks;", """ a "precise" qualifier allowing computations to be carried out exactly as specified in the shader source to avoid optimization-induced invariance issues (which might cause cracking in tessellation); """, """ new built-in functions supporting: ${ul( "fused floating-point multiply-add operations;" )} """, """ extending the textureGather() built-in functions provided by OpenGL ES Shading Language 3.10: ${ul( "allowing shaders to use arbitrary offsets computed at run-time to select a 2x2 footprint to gather from; and", "allowing shaders to use separate independent offsets for each of the four texels returned, instead of requiring a fixed 2x2 footprint." )} """ )} Requires ${GLES31.core}. """ } val EXT_multisampled_render_to_texture2 = EXT_FLAG.nativeClassGLES("EXT_multisampled_render_to_texture2", postfix = EXT) { documentation = """ The {@code attachment} parameters for #FramebufferTexture2DMultisampleEXT() is no longer required to be #COLOR_ATTACHMENT0. The attachment parameter now matches what is allowed in #FramebufferTexture2D(). This means values like {@code GL_COLOR_ATTACHMENTi}, #DEPTH_ATTACHMENT, #STENCIL_ATTACHMENT, or #DEPTH_STENCIL_ATTACHMENT may be used. After the application has rendered into the mutisampled buffer, the application should be careful to not trigger an implicit flush by performing a client side read of the buffer (readpixels, copyteximage, blitframebuffer, etc) before any subsequent rendering which uses the contents of the buffer. This may cause the attachment to be downsampled before the following draw, which would potentially cause corruption. """ } val EXT_multiview_timer_query = EXT_FLAG.nativeClassGLES("EXT_multiview_timer_query", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension removes one of the limitations of the {@code OVR_multiview} extension by allowing the use of timer queries during multiview rendering. {@code OVR_multiview} does not specify defined behavior for such usage (if ${EXT_disjoint_timer_query.link} is present). Requires ${GLES32.core} and ${OVR_multiview.link}. """ } val EXT_multiview_texture_multisample = EXT_FLAG.nativeClassGLES("EXT_multiview_texture_multisample", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension removes one of the limitations of the {@code OVR_multiview} extension by allowing the use of multisample textures during multiview rendering. This is one of two extensions that allow multisampling when using {@code OVR_multiview}. Each supports one of the two different approaches to multisampling in OpenGL ES: OpenGL ES 3.1+ has explicit support for multisample texture types, such as #TEXTURE_2D_MULTISAMPLE. Applications can access the values of individual samples and can explicitly "resolve" the samples of each pixel down to a single color. The extension ${EXT_multisampled_render_to_texture.link} provides support for multisampled rendering to non-multisample texture types, such as #TEXTURE_2D. The individual samples for each pixel are maintained internally by the implementation and can not be accessed directly by applications. These samples are eventually resolved implicitly to a single color for each pixel. This extension supports the first multisampling style with multiview rendering; the ${OVR_multiview_multisampled_render_to_texture.link} extension supports the second style. Note that support for one of these multiview extensions does not imply support for the other. Requires ${GLES32.core} and ${OVR_multiview.link}. """ } val EXT_multiview_tessellation_geometry_shader = EXT_FLAG.nativeClassGLES("EXT_multiview_tessellation_geometry_shader", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension removes one of the limitations of the {@code OVR_multiview} extension by allowing the use of tessellation control, tessellation evaluation, and geometry shaders during multiview rendering. {@code OVR_multiview} by itself forbids the use of any of these shader types. When using tessellation control, tessellation evaluation, and geometry shaders during multiview rendering, any such shader must use the "{@code num_views}" layout qualifier provided by the matching shading language extension to specify a view count. The view count specified in these shaders must match the count specified in the vertex shader. Additionally, the shading language extension allows these shaders to use the {@code gl_ViewID_OVR} built-in to handle tessellation or geometry shader processing differently for each view. {@code OVR_multiview2} extends {@code OVR_multiview} by allowing view-dependent values for any vertex attributes instead of just the position. This new extension does not imply the availability of {@code OVR_multiview2}, but if both are available, view-dependent values for any vertex attributes are also allowed in tessellation control, tessellation evaluation, and geometry shaders. Requires ${GLES32.core} and ${OVR_multiview.link}. """ } val EXT_post_depth_coverage = EXT_FLAG.nativeClassGLES("EXT_post_depth_coverage", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension allows the fragment shader to control whether values in gl_SampleMaskIn[] reflect the coverage after application of the early depth and stencil tests. This feature can be enabled with the following layout qualifier in the fragment shader: ${codeBlock(""" layout(post_depth_coverage) in;""")} To use this feature, early fragment tests must also be enabled in the fragment shader via: ${codeBlock(""" layout(early_fragment_tests) in;""")} Requires {@link \#GL_OES_sample_variables OES_sample_variables}. """ } val EXT_shader_group_vote = EXT_FLAG.nativeClassGLES("EXT_shader_group_vote", postfix = EXT) { documentation = """ This extension provides new built-in functions to compute the composite of a set of boolean conditions across a group of shader invocations. These composite results may be used to execute shaders more efficiently on a single-instruction multiple-data (SIMD) processor. The set of shader invocations across which boolean conditions are evaluated is implementation-dependent, and this extension provides no guarantee over how individual shader invocations are assigned to such sets. In particular, the set of shader invocations has no necessary relationship with the compute shader local work group -- a pair of shader invocations in a single compute shader work group may end up in different sets used by these built-ins. Compute shaders operate on an explicitly specified group of threads (a local work group), but many implementations of OpenGL ES 3.0 will even group non-compute shader invocations and execute them in a SIMD fashion. When executing code like ${codeBlock(""" if (condition) { result = do_fast_path(); } else { result = do_general_path(); }""")} where {@code condition} diverges between invocations, a SIMD implementation might first call do_fast_path() for the invocations where {@code condition} is true and leave the other invocations dormant. Once do_fast_path() returns, it might call do_general_path() for invocations where {@code condition} is false and leave the other invocations dormant. In this case, the shader executes *both* the fast and the general path and might be better off just using the general path for all invocations. This extension provides the ability to avoid divergent execution by evaluting a condition across an entire SIMD invocation group using code like: ${codeBlock(""" if (allInvocationsEXT(condition)) { result = do_fast_path(); } else { result = do_general_path(); }""")} The built-in function allInvocationsEXT() will return the same value for all invocations in the group, so the group will either execute do_fast_path() or do_general_path(), but never both. For example, shader code might want to evaluate a complex function iteratively by starting with an approximation of the result and then refining the approximation. Some input values may require a small number of iterations to generate an accurate result (do_fast_path) while others require a larger number (do_general_path). In another example, shader code might want to evaluate a complex function (do_general_path) that can be greatly simplified when assuming a specific value for one of its inputs (do_fast_path). """ } val EXT_shader_implicit_conversions = EXT_FLAG.nativeClassGLES("EXT_shader_implicit_conversions", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension provides support for implicitly converting signed integer types to unsigned types, as well as more general implicit conversion and function overloading infrastructure to support new data types introduced by other extensions. Requires ${GLES31.core}. """ } val EXT_shader_integer_mix = EXT_FLAG.nativeClassGLES("EXT_shader_integer_mix", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. GLSL 1.30 (and GLSL ES 3.00) expanded the mix() built-in function to operate on a boolean third argument that does not interpolate but selects. This extension extends mix() to select between int, uint, and bool components. Requires ${GLES30.core}. """ } val EXT_shader_io_blocks = EXT_FLAG.nativeClassGLES("EXT_shader_io_blocks", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension extends the functionality of interface blocks to support input and output interfaces in the OpenGL ES Shading Language. Input and output interface blocks are used for forming the interfaces between vertex, tessellation control, tessellation evaluation, geometry and fragment shaders. This accommodates passing arrays between stages, which otherwise would require multi-dimensional array support for tessellation control outputs and for tessellation control, tessellation evaluation, and geometry shader inputs. This extension provides support for application defined interface blocks which are used for passing application-specific information between shader stages. This extension moves the built-in "per-vertex" in/out variables to a new built-in gl_PerVertex block. This is necessary for tessellation and geometry shaders which require a separate instance for each vertex, but it can also be useful for vertex shaders. Finally, this extension allows the redeclaration of the gl_PerVertex block in order to reduce the set of variables that must be passed between shaders. Requires ${GLES31.core}. """ } val EXT_shader_non_constant_global_initializers = EXT_FLAG.nativeClassGLES("EXT_shader_non_constant_global_initializers", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension adds the ability to use non-constant initializers for global variables in the OpenGL ES Shading Language specifications. This functionality is already present in the OpenGL Shading language specification. """ } val EXT_shader_texture_lod = EXT_FLAG.nativeClassGLES("EXT_shader_texture_lod", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension adds additional texture functions to the OpenGL ES Shading Language which provide the shader writer with explicit control of LOD. Mipmap texture fetches and anisotropic texture fetches require implicit derivatives to calculate rho, lambda and/or the line of anisotropy. These implicit derivatives will be undefined for texture fetches occurring inside non-uniform control flow or for vertex shader texture fetches, resulting in undefined texels. The additional texture functions introduced with this extension provide explicit control of LOD (isotropic texture functions) or provide explicit derivatives (anisotropic texture functions). Anisotropic texture functions return defined texels for mipmap texture fetches or anisotropic texture fetches, even inside non-uniform control flow. Isotropic texture functions return defined texels for mipmap texture fetches, even inside non-uniform control flow. However, isotropic texture functions return undefined texels for anisotropic texture fetches. The existing isotropic vertex texture functions: ${codeBlock(""" vec4 texture2DLodEXT(sampler2D sampler, vec2 coord, float lod); vec4 texture2DProjLodEXT(sampler2D sampler, vec3 coord, float lod); vec4 texture2DProjLodEXT(sampler2D sampler, vec4 coord, float lod); vec4 textureCubeLodEXT(samplerCube sampler, vec3 coord, float lod);""")} are added to the built-in functions for fragment shaders with "EXT" suffix appended. New anisotropic texture functions, providing explicit derivatives: ${codeBlock(""" vec4 texture2DGradEXT(sampler2D sampler, vec2 P, vec2 dPdx, vec2 dPdy); vec4 texture2DProjGradEXT(sampler2D sampler, vec3 P, vec2 dPdx, vec2 dPdy); vec4 texture2DProjGradEXT(sampler2D sampler, vec4 P, vec2 dPdx, vec2 dPdy); vec4 textureCubeGradEXT(samplerCube sampler, vec3 P, vec3 dPdx, vec3 dPdy);""")} are added to the built-in functions for vertex shaders and fragment shaders. """ } val EXT_sparse_texture2 = EXT_FLAG.nativeClassGLES("EXT_sparse_texture2", postfix = EXT) { documentation = """ This extension builds on the EXT_sparse_texture extension, providing the following new functionality: ${ul( """ New built-in GLSL texture lookup and image load functions are provided that return information on whether the texels accessed for the texture lookup accessed uncommitted texture memory. """, """ New built-in GLSL texture lookup functions are provided that specify a minimum level of detail to use for lookups where the level of detail is computed automatically. This allows shaders to avoid accessing unpopulated portions of high-resolution levels of detail when it knows that the memory accessed is unpopulated, either from a priori knowledge or from feedback provided by the return value of previously executed "sparse" texture lookup functions. """, """ Reads of uncommitted texture memory will act as though such memory were filled with zeroes; previously, the values returned by reads were undefined. """, """ Standard implementation-independent virtual page sizes for internal formats required to be supported with sparse textures. These standard sizes can be requested by leaving #VIRTUAL_PAGE_SIZE_INDEX_EXT at its initial value (0). """, """ Support for creating sparse multisample and multisample array textures is added. However, the virtual page sizes for such textures remain fully implementation-dependent. """ )} Requires ${EXT_sparse_texture.link}. """ } val EXT_texture_compression_astc_decode_mode_rgb9e5 = EXT_FLAG.nativeClassGLES("GL_EXT_texture_compression_astc_decode_mode_rgb9e5", postfix = EXT) { documentation = "See ${EXT_texture_compression_astc_decode_mode.link}." } val EXT_texture_query_lod = EXT_FLAG.nativeClassGLES("GL_EXT_texture_query_lod", postfix = EXT) { documentation = """ When true, the $registryLink extension is supported. This extension adds a new set of fragment shader texture functions ({@code textureLOD}) that return the results of automatic level-of-detail computations that would be performed if a texture lookup were performed. Requires ${GLES30.core}. """ } val EXT_texture_shadow_lod = EXT_FLAG.nativeClassGLES("EXT_texture_shadow_lod", postfix = EXT) { documentation = """ This extension adds support for various shadow sampler types with texture functions having interactions with the LOD of texture lookups. Modern shading languages support LOD queries for shadow sampler types, but until now the OpenGL Shading Language Specification has excluded multiple texture function overloads involving LOD calculations with various shadow samplers. Shading languages for other APIs do support the equivalent LOD-based texture sampling functions for these types which has made porting between those shading languages to GLSL cumbersome and has required the usage of sub-optimal workarounds. Requires ${GLES30.core} and {@code EXT_gpu_shader4} or equivalent functionality. """ } val INTEL_shader_integer_functions2 = EXT_FLAG.nativeClassGLES("INTEL_shader_integer_functions2", postfix = INTEL) { documentation = """ When true, the $registryLink extension is supported. OpenCL and other GPU programming environments provides a number of useful functions operating on integer data. Many of these functions are supported by specialized instructions various GPUs. Correct GLSL implementations for some of these functions are non-trivial. Recognizing open-coded versions of these functions is often impractical. As a result, potential performance improvements go unrealized. This extension makes available a number of functions that have specialized instruction support on Intel GPUs. Requires GLSL ES 3.00. """ } val KHR_robust_buffer_access_behavior = EXT_FLAG.nativeClassGLES("KHR_robust_buffer_access_behavior", postfix = KHR) { documentation = """ When true, the $registryLink extension is supported. This extension specifies the behavior of out-of-bounds buffer and array accesses. This is an improvement over the existing KHR_robustness extension which states that the application should not crash, but that behavior is otherwise undefined. This extension specifies the access protection provided by the GL to ensure that out-of-bounds accesses cannot read from or write to data not owned by the application. All accesses are contained within the buffer object and program area they reference. These additional robustness guarantees apply to contexts created with the robust access flag set. Requires ${GLES20.core} and ${KHR_robustness.link}. """ } val KHR_texture_compression_astc_sliced_3d = EXT_FLAG.nativeClassGLES("KHR_texture_compression_astc_sliced_3d", postfix = KHR) { documentation = """ When true, the $registryLink extension is supported. Adaptive Scalable Texture Compression (ASTC) is a new texture compression technology that offers unprecendented flexibility, while producing better or comparable results than existing texture compressions at all bit rates. It includes support for 2D and slice-based 3D textures, with low and high dynamic range, at bitrates from below 1 bit/pixel up to 8 bits/pixel in fine steps. This extension extends the functionality of ${KHR_texture_compression_astc_ldr.link} to include slice-based 3D textures for textures using the LDR profile in the same way as the HDR profile allows slice-based 3D textures. Requires ${KHR_texture_compression_astc_ldr.link}. """ } val MESA_tile_raster_order = EXT_FLAG.nativeClassGLES("MESA_tile_raster_order", postfix = MESA) { documentation = """ When true, the $registryLink extension is supported. This extension extends the sampling-from-the-framebuffer behavior provided by {@code GL_NV_texture_barrier} to allow setting the rasterization order of the scene, so that overlapping blits can be implemented. This can be used for scrolling or window movement within in 2D scenes, without first copying to a temporary. Requires ${NV_texture_barrier.link}. """ } val NV_compute_shader_derivatives = EXT_FLAG.nativeClassGLES("NV_compute_shader_derivatives", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension adds OpenGL ES API support for the OpenGL Shading Language (GLSL) extension {@code "NV_compute_shader_derivatives"}. That extension, when enabled, allows applications to use derivatives in compute shaders. It adds compute shader support for explicit derivative built-in functions like {@code dFdx()}, automatic derivative computation in texture lookup functions like {@code texture()}, use of the optional LOD bias parameter to adjust the computed level of detail values in texture lookup functions, and the texture level of detail query function {@code textureQueryLod()}. Requires ${GLES32.core}. """ } val NV_explicit_attrib_location = EXT_FLAG.nativeClassGLES("NV_explicit_attrib_location", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension provides a method to pre-assign attribute locations to named vertex shader inputs. This allows applications to globally assign a particular semantic meaning, such as diffuse color or vertex normal, to a particular attribute location without knowing how that attribute will be named in any particular shader. Requires ${GLES20.core}. """ } val NV_fragment_shader_barycentric = EXT_FLAG.nativeClassGLES("NV_fragment_shader_barycentric", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension advertises OpenGL support for the OpenGL Shading Language (GLSL) extension {@code "NV_fragment_shader_barycentric"}, which provides fragment shader built-in variables holding barycentric weight vectors that identify the location of the fragment within its primitive. Additionally, the GLSL extension allows fragment the ability to read raw attribute values for each of the vertices of the primitive that produced the fragment. Requires ${GLES32.core}. """ } val NV_fragment_shader_interlock = EXT_FLAG.nativeClassGLES("NV_fragment_shader_interlock", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. In unextended OpenGL 4.3 or OpenGL ES 3.1, applications may produce a large number of fragment shader invocations that perform loads and stores to memory using image uniforms, atomic counter uniforms, buffer variables, or pointers. The order in which loads and stores to common addresses are performed by different fragment shader invocations is largely undefined. For algorithms that use shader writes and touch the same pixels more than once, one or more of the following techniques may be required to ensure proper execution ordering: ${ul( "inserting Finish or WaitSync commands to drain the pipeline between different \"passes\" or \"layers\";", "using only atomic memory operations to write to shader memory (which may be relatively slow and limits how memory may be updated); or", "injecting spin loops into shaders to prevent multiple shader invocations from touching the same memory concurrently." )} This extension provides new GLSL built-in functions beginInvocationInterlockNV() and endInvocationInterlockNV() that delimit a critical section of fragment shader code. For pairs of shader invocations with "overlapping" coverage in a given pixel, the OpenGL implementation will guarantee that the critical section of the fragment shader will be executed for only one fragment at a time. There are four different interlock modes supported by this extension, which are identified by layout qualifiers. The qualifiers "pixel_interlock_ordered" and "pixel_interlock_unordered" provides mutual exclusion in the critical section for any pair of fragments corresponding to the same pixel. When using multisampling, the qualifiers "sample_interlock_ordered" and "sample_interlock_unordered" only provide mutual exclusion for pairs of fragments that both cover at least one common sample in the same pixel; these are recommended for performance if shaders use per-sample data structures. Additionally, when the "pixel_interlock_ordered" or "sample_interlock_ordered" layout qualifier is used, the interlock also guarantees that the critical section for multiple shader invocations with "overlapping" coverage will be executed in the order in which the primitives were processed by the GL. Such a guarantee is useful for applications like blending in the fragment shader, where an application requires that fragment values to be composited in the framebuffer in primitive order. This extension can be useful for algorithms that need to access per-pixel data structures via shader loads and stores. Such algorithms using this extension can access such data structures in the critical section without worrying about other invocations for the same pixel accessing the data structures concurrently. Additionally, the ordering guarantees are useful for cases where the API ordering of fragments is meaningful. For example, applications may be able to execute programmable blending operations in the fragment shader, where the destination buffer is read via image loads and the final value is written via image stores. Requires ${GLES31.core}. """ } val NV_generate_mipmap_sRGB = EXT_FLAG.nativeClassGLES("NV_generate_mipmap_sRGB", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. EXT_sRGB requires GenerateMipmap() to throw INVALID_OPERATION on textures with sRGB encoding. NV_generate_mipmap_sRGB lifts this restriction. Requires ${EXT_sRGB.link}. """ } val NV_geometry_shader_passthrough = EXT_FLAG.nativeClassGLES("NV_geometry_shader_passthrough", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. Geometry shaders provide the ability for applications to process each primitive sent through the GL using a programmable shader. While geometry shaders can be used to perform a number of different operations, including subdividing primitives and changing primitive type, one common use case treats geometry shaders as largely "passthrough". In this use case, the bulk of the geometry shader code simply copies inputs from each vertex of the input primitive to corresponding outputs in the vertices of the output primitive. Such shaders might also compute values for additional built-in or user-defined per-primitive attributes (e.g., gl_Layer) to be assigned to all the vertices of the output primitive. This extension provides a shading language abstraction to express such shaders without requiring explicit logic to manually copy attributes from input vertices to output vertices. For example, consider the following simple geometry shader in unextended OpenGL: ${codeBlock(""" layout(triangles) in; layout(triangle_strip) out; layout(max_vertices=3) out; in Inputs { vec2 texcoord; vec4 baseColor; } v_in[]; out Outputs { vec2 texcoord; vec4 baseColor; }; void main() { int layer = compute_layer(); for (int i = 0; i < 3; i++) { gl_Position = gl_in[i].gl_Position; texcoord = v_in[i].texcoord; baseColor = v_in[i].baseColor; gl_Layer = layer; EmitVertex(); } }""")} In this shader, the inputs "gl_Position", "Inputs.texcoord", and "Inputs.baseColor" are simply copied from the input vertex to the corresponding output vertex. The only "interesting" work done by the geometry shader is computing and emitting a gl_Layer value for the primitive. The following geometry shader, using this extension, is equivalent: ${codeBlock(""" \#extension GL_NV_geometry_shader_passthrough : require layout(triangles) in; // No output primitive layout qualifiers required. // Redeclare gl_PerVertex to pass through "gl_Position". layout(passthrough) in gl_PerVertex { vec4 gl_Position; }; // Declare "Inputs" with "passthrough" to automatically copy members. layout(passthrough) in Inputs { vec2 texcoord; vec4 baseColor; }; // No output block declaration required. void main() { // The shader simply computes and writes gl_Layer. We don't // loop over three vertices or call EmitVertex(). gl_Layer = compute_layer(); }""")} Requires ${GLES31.core}. """ } val NV_image_formats = EXT_FLAG.nativeClassGLES("NV_image_formats", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. OpenGL ES 3.1 specifies a variety of formats required to be usable with texture images. This extension introduces the texture image formats missing for parity with OpenGL 4.4. Requires ${GLES31.core}. """ } val NV_sample_mask_override_coverage = EXT_FLAG.nativeClassGLES("NV_sample_mask_override_coverage", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension allows the fragment shader to control whether the gl_SampleMask output can enable samples that were not covered by the original primitive, or that failed the early depth/stencil tests. This can be enabled by redeclaring the gl_SampleMask output with the "override_coverage" layout qualifier: ${codeBlock(""" layout(override_coverage) out int gl_SampleMask[];""")} Requires {@link \#GL_OES_sample_variables OES_sample_variables}. """ } val NV_shader_atomic_fp16_vector = EXT_FLAG.nativeClassGLES("NV_shader_atomic_fp16_vector", postfix = NV) { documentation = """ This extension provides GLSL built-in functions and assembly opcodes allowing shaders to perform a limited set of atomic read-modify-write operations to buffer or texture memory with 16-bit floating point vector surface formats. Requires ${NV_gpu_shader5.link}. """ } val NV_shader_noperspective_interpolation = EXT_FLAG.nativeClassGLES("NV_shader_noperspective_interpolation", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. In OpenGL 3.0 and later, and in other APIs, there are three types of interpolation qualifiers that are available for fragment shader inputs: flat, smooth, and noperspective. The 'flat' qualifier indicates that no interpolation should be used. This is mandatory for integer-type variables. The 'smooth' qualifier indicates that interpolation should be performed in a perspective0correct manner. This is the default for floating-point type variables. The 'noperspective' qualifier indicates that interpolation should be performed linearly in screen space. While perspective-correct (smooth) and non-interpolated (flat) are the two types of interpolation that most commonly used, there are important use cases for linear (noperspective) interpolation. In particular, in some work loads where screen-space aligned geometry is common, the use of linear interpolation can result in performance and/or power improvements. The smooth and flat interpolation qualifiers are already supported in OpenGL ES 3.0 and later. This extension adds support for noperspective interpolation to OpenGL ES. Requires ${GLES30.core}. """ } val NV_shader_texture_footprint = EXT_FLAG.nativeClassGLES("NV_shader_texture_footprint", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension adds OpenGL API support for the OpenGL Shading Language (GLSL) extension {@code "NV_shader_texture_footprint"}. That extension adds a new set of texture query functions ({@code "textureFootprint*NV"}) to GLSL. These built-in functions prepare to perform a filtered texture lookup based on coordinates and other parameters passed in by the calling code. However, instead of returning data from the provided texture image, these query functions instead return data identifying the <em>texture footprint</em> for an equivalent texture access. The texture footprint identifies a set of texels that may be accessed in order to return a filtered result for the texture access. The footprint itself is a structure that includes integer values that identify a small neighborhood of texels in the texture being accessed and a bitfield that indicates which texels in that neighborhood would be used. Each bit in the returned bitfield identifies whether any texel in a small aligned block of texels would be fetched by the texture lookup. The size of each block is specified by an access <em>granularity</em> provided by the shader. The minimum granularity supported by this extension is 2x2 (for 2D textures) and 2x2x2 (for 3D textures); the maximum granularity is 256x256 (for 2D textures) or 64x32x32 (for 3D textures). Each footprint query returns the footprint from a single texture level. When using minification filters that combine accesses from multiple mipmap levels, shaders must perform separate queries for the two levels accessed ("fine" and "coarse"). The footprint query also returns a flag indicating if the texture lookup would access texels from only one mipmap level or from two neighboring levels. This extension should be useful for multi-pass rendering operations that do an initial expensive rendering pass to produce a first image that is then used as a texture for a second pass. If the second pass ends up accessing only portions of the first image (e.g., due to visibility), the work spent rendering the non-accessed portion of the first image was wasted. With this feature, an application can limit this waste using an initial pass over the geometry in the second image that performs a footprint query for each visible pixel to determine the set of pixels that it needs from the first image. This pass would accumulate an aggregate footprint of all visible pixels into a separate "footprint texture" using shader atomics. Then, when rendering the first image, the application can kill all shading work for pixels not in this aggregate footprint. The implementation of this extension has a number of limitations. The texture footprint query functions are only supported for two- and three-dimensional textures (#TEXTURE_2D, #TEXTURE_3D). Texture footprint evaluation only supports the #CLAMP_TO_EDGE wrap mode; results are undefined for all other wrap modes. The implementation supports only a limited set of granularity values and does not support separate coverage information for each texel in the original texture. Requires ${GLES32.core}. """ } val NV_stereo_view_rendering = EXT_FLAG.nativeClassGLES("NV_stereo_view_rendering", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. Virtual reality (VR) applications often render a single logical scene from multiple views corresponding to a pair of eyes. The views (eyes) are separated by a fixed offset in the X direction. Traditionally, multiple views are rendered via multiple rendering passes. This is expensive for the GPU because the objects in the scene must be transformed, rasterized, shaded, and fragment processed redundantly. This is expensive for the CPU because the scene graph needs to be visited multiple times and driver validation happens for each view. Rendering N passes tends to take N times longer than a single pass. This extension provides a mechanism to render binocular (stereo) views from a single stream of OpenGL rendering commands. Vertex, tessellation, and geometry (VTG) shaders can output two positions for each vertex corresponding to the two eye views. A built-in "gl_SecondaryPositionNV" is added to specify the second position. The positions from each view may be sent to different viewports and/or layers. A built-in "gl_SecondaryViewportMaskNV[]" is also added to specify the viewport mask for the second view. A new layout-qualifier "secondary_view_offset" is added for built-in output "gl_Layer" which allows for the geometry from each view to be sent to different layers for rendering. Requires {@link \#GL_NV_viewport_array2 NV_viewport_array2}. """ } val NV_texture_compression_s3tc_update = EXT_FLAG.nativeClassGLES("NV_texture_compression_s3tc_update", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension allows for full or partial image updates to a compressed 2D texture from an uncompressed texel data buffer using TexImage2D and TexSubImage2D. Consquently, if a compressed internal format is used, all the restrictions associated with compressed textures will apply. These include sub-image updates aligned to 4x4 pixel blocks and the restriction on usage as render targets. Requires ${NV_texture_compression_s3tc.link}. """ } val NV_texture_npot_2D_mipmap = EXT_FLAG.nativeClassGLES("NV_texture_npot_2D_mipmap", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. Conventional OpenGL ES 2.0 allows the use of non-power-of-two (NPOT) textures with the limitation that mipmap minification filters can not be used. This extension relaxes this restriction and adds limited mipmap support for 2D NPOT textures. With this extension, NPOT textures are specified and applied identically to mipmapped power-of-two 2D textures with the following limitations: ${ul( "The texture wrap modes must be CLAMP_TO_EDGE.", """ Coordinates used for texture sampling on an NPOT texture using a mipmapped minification filter must lie within the range [0,1]. Coordinate clamping is not performed by the GL in this case, causing values outside this range to produce undefined results. """ )} """ } val NV_viewport_array2 = EXT_FLAG.nativeClassGLES("NV_viewport_array2", postfix = NV) { documentation = """ When true, the $registryLink extension is supported. This extension provides new support allowing a single primitive to be broadcast to multiple viewports and/or multiple layers. A shader output gl_ViewportMask[] is provided, allowing a single primitive to be output to multiple viewports simultaneously. Also, a new shader option is provided to control whether the effective viewport index is added into gl_Layer. These capabilities allow a single primitive to be output to multiple layers simultaneously. The gl_ViewportMask[] output is available in vertex, tessellation control, tessellation evaluation, and geometry shaders. gl_ViewportIndex and gl_Layer are also made available in all these shader stages. The actual viewport index or mask and render target layer values are taken from the last active shader stage from this set of stages. This extension is a superset of the GL_AMD_vertex_shader_layer and GL_AMD_vertex_shader_viewport_index extensions, and thus those extension strings are expected to be exported if GL_NV_viewport_array2 is supported. This extension includes the edits for those extensions, recast against the reorganized OpenGL 4.3 specification. Requires ${NV_viewport_array.link}, ${EXT_geometry_shader.link} and ${EXT_shader_io_blocks.cap}. """ } val NVX_blend_equation_advanced_multi_draw_buffers = EXT_FLAG.nativeClassGLES("NVX_blend_equation_advanced_multi_draw_buffers", postfix = NVX) { documentation = """ When true, the $registryLink extension is supported. This extension adds support for using advanced blend equations introduced with ${NV_blend_equation_advanced.link} (and standardized by ${KHR_blend_equation_advanced.link}) in conjunction with multiple draw buffers. The NV_blend_equation_advanced extension supports advanced blending equations only when rending to a single color buffer using fragment color zero and throws and #INVALID_OPERATION error when multiple draw buffers are used. This extension removes this restriction. Requires either ${NV_blend_equation_advanced.link} or ${KHR_blend_equation_advanced.link}. """ } val OES_depth_texture = EXT_FLAG.nativeClassGLES("OES_depth_texture", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension defines a new texture format that stores depth values in the texture. Depth texture images are widely used for shadow casting but can also be used for other effects such as image based rendering, displacement mapping etc. Requires ${GLES20.core}. """ } val OES_EGL_image_external_essl3 = EXT_FLAG.nativeClassGLES("OES_EGL_image_external_essl3", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. OES_EGL_image_external provides a mechanism for creating EGLImage texture targets from EGLImages, but only specified language interactions for the OpenGL ES Shading Language version 1.0. This extension adds support for versions 3.x of the OpenGL ES Shading Language. Requires ${GLES30.link} and ${OES_EGL_image_external.link}. """ } val OES_element_index_uint = EXT_FLAG.nativeClassGLES("OES_element_index_uint", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. OpenGL ES 1.0 supports DrawElements with {@code type} value of UNSIGNED_BYTE and UNSIGNED_SHORT. This extension adds support for UNSIGNED_INT {@code type} values. """ } val OES_fbo_render_mipmap = EXT_FLAG.nativeClassGLES("OES_fbo_render_mipmap", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. OES_framebuffer_object allows rendering to the base level of a texture only. This extension removes this limitation by allowing implementations to support rendering to any mip-level of a texture(s) that is attached to a framebuffer object(s). If this extension is supported, FramebufferTexture2DOES, and FramebufferTexture3DOES can be used to render directly into any mip level of a texture image """ } val OES_gpu_shader5 = EXT_FLAG.nativeClassGLES("OES_gpu_shader5", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension provides a set of new features to the OpenGL ES Shading Language and related APIs to support capabilities of new GPUs, extending the capabilities of version 3.10 of the OpenGL ES Shading Language. Shaders using the new functionality provided by this extension should enable this functionality via the construct ${codeBlock(""" \#extension GL_OES_gpu_shader5 : require (or enable)""")} This extension provides a variety of new features for all shader types, including: ${ul( "support for indexing into arrays of opaque types (samplers, and atomic counters) using dynamically uniform integer expressions;", "support for indexing into arrays of images and shader storage blocks using only constant integral expressions;", "extending the uniform block capability to allow shaders to index into an array of uniform blocks;", """ a "precise" qualifier allowing computations to be carried out exactly as specified in the shader source to avoid optimization-induced invariance issues (which might cause cracking in tessellation); """, """ new built-in functions supporting: ${ul("fused floating-point multiply-add operations;")} """, """ extending the textureGather() built-in functions provided by OpenGL ES Shading Language 3.10: ${ul( "allowing shaders to use arbitrary offsets computed at run-time to select a 2x2 footprint to gather from; and", "allowing shaders to use separate independent offsets for each of the four texels returned, instead of requiring a fixed 2x2 footprint." )} """ )} Requires ${GLES31.core}. """ } val OES_sample_variables = EXT_FLAG.nativeClassGLES("OES_sample_variables", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension allows fragment shaders more control over multisample rendering. The mask of samples covered by a fragment can be read by the shader and individual samples can be masked out. Additionally fragment shaders can be run on individual samples and the sample's ID and position read to allow better interaction with multisample resources such as textures. In multisample rendering, an implementation is allowed to assign the same sets of fragment shader input values to each sample, which then allows the optimization where the shader is only evaluated once and then distributed to the samples that have been determined to be covered by the primitive currently being rasterized. This extension does not change how values are interpolated, but it makes some details of the current sample available. This means that where these features are used (gl_SampleID and gl_SamplePosition), implementations must run the fragment shader for each sample. In order to obtain per-sample interpolation on fragment inputs, either OES_sample_shading or OES_shader_multisample_interpolation must be used in conjunction with the features from this extension. Requires ${GLES30.core}. """ } val OES_shader_image_atomic = EXT_FLAG.nativeClassGLES("OES_shader_image_atomic", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension provides built-in functions allowing shaders to perform atomic read-modify-write operations to a single level of a texture object from any shader stage. These built-in functions are named imageAtomic*(), and accept integer texel coordinates to identify the texel accessed. These built-in functions extend the Images in ESSL 3.10. Requires ${GLES31.core}. """ } val OES_shader_io_blocks = EXT_FLAG.nativeClassGLES("OES_shader_io_blocks", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension extends the functionality of interface blocks to support input and output interfaces in the OpenGL ES Shading Language. Input and output interface blocks are used for forming the interfaces between vertex, tessellation control, tessellation evaluation, geometry and fragment shaders. This accommodates passing arrays between stages, which otherwise would require multi-dimensional array support for tessellation control outputs and for tessellation control, tessellation evaluation, and geometry shader inputs. This extension provides support for application defined interface blocks which are used for passing application-specific information between shader stages. This extension moves the built-in "per-vertex" in/out variables to a new built-in gl_PerVertex block. This is necessary for tessellation and geometry shaders which require a separate instance for each vertex, but it can also be useful for vertex shaders. Finally, this extension allows the redeclaration of the gl_PerVertex block in order to reduce the set of variables that must be passed between shaders. Requires ${GLES31.core}. """ } val OES_texture_float_linear = EXT_FLAG.nativeClassGLES("OES_texture_float_linear", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. These extensions expand upon the OES_texture_half_float and OES_texture_float extensions by allowing support for LINEAR magnification filter and LINEAR, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_NEAREST and LINEAR_MIPMAP_NEAREST minification filters. When implemented against OpenGL ES 3.0 or later versions, sized 32-bit floating-point formats become texture-filterable. This should be noted by, for example, checking the ``TF'' column of table 8.13 in the ES 3.1 Specification (``Correspondence of sized internal formats to base internal formats ... and use cases ...'') for the R32F, RG32F, RGB32F, and RGBA32F formats. Requires ${OES_texture_float.cap}. """ } val OES_texture_half_float_linear = EXT_FLAG.nativeClassGLES("OES_texture_half_float_linear", postfix = OES) { documentation = """ When true, the ${registryLink("OES_texture_float_linear")} extension is supported. These extensions expand upon the OES_texture_half_float and OES_texture_float extensions by allowing support for LINEAR magnification filter and LINEAR, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_NEAREST and LINEAR_MIPMAP_NEAREST minification filters. When implemented against OpenGL ES 3.0 or later versions, sized 32-bit floating-point formats become texture-filterable. This should be noted by, for example, checking the ``TF'' column of table 8.13 in the ES 3.1 Specification (``Correspondence of sized internal formats to base internal formats ... and use cases ...'') for the R32F, RG32F, RGB32F, and RGBA32F formats. Requires ${OES_texture_half_float.link}. """ } val OES_texture_npot = EXT_FLAG.nativeClassGLES("OES_texture_npot", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension adds support for the REPEAT and MIRRORED_REPEAT texture wrap modes and the minification filters supported for non-power of two 2D textures, cubemaps and for 3D textures, if the OES_texture_3D extension is supported. Section 3.8.2 of the OpenGL ES 2.0 specification describes rules for sampling from an incomplete texture. There were specific rules added for non-power of two textures i.e. if the texture wrap mode is not CLAMP_TO_EDGE or minification filter is not NEAREST or LINEAR and the texture is a non-power-of-two texture, then sampling the texture will return (0, 0, 0, 1). These rules are no longer applied by an implementation that supports this extension. """ } val OES_texture_stencil8 = EXT_FLAG.nativeClassGLES("OES_texture_stencil8", postfix = OES) { documentation = """ When true, the $registryLink extension is supported. This extension accepts STENCIL_INDEX8 as a texture internal format, and adds STENCIL_INDEX8 to the required internal format list. This removes the need to use renderbuffers if a stencil-only format is desired. """ } val OVR_multiview2 = EXT_FLAG.nativeClassGLES("OVR_multiview2", postfix = OVR) { documentation = """ When true, the $registryLink extension is supported. This extension relaxes the restriction in OVR_multiview that only gl_Position can depend on ViewID in the vertex shader. With this change, view-dependent outputs like reflection vectors and similar are allowed. Requires ${GLES30.core} and ${OVR_multiview.link}. """ } val QCOM_shader_framebuffer_fetch_rate = EXT_FLAG.nativeClassGLES("QCOM_shader_framebuffer_fetch_rate", postfix = QCOM) { documentation = """ When certain built-ins (e.g. {@code gl_LastFragData}, {@code gl_LastFragStencilARM}) are referenced in the shader, the shader is required to execute at sample-rate if the attachments are multisampled. In some use-cases executing such shaders at fragment-rate is actually the preferred behavior. When this extension is enabled, such GLSL shaders will execute at fragment-rate and the built-in will return a per-fragment value. This avoids the significant performance penalty that would otherwise be incurred with sample-rate shading. The following built-ins are affected when the this extension is enabled: ${ul( "{@code gl_LastFragData} (from ${EXT_shader_framebuffer_fetch.link})", "{@code gl_LastFragDepthARM} (from ${ARM_shader_framebuffer_fetch_depth_stencil.cap})" )} The following built-ins are disallowed when this extension is enabled: ${ul( "gl_SampleID", "gl_SamplePosition", "interpolateAtSample()" )} """ } val QCOM_YUV_texture_gather = EXT_FLAG.nativeClassGLES("QCOM_YUV_texture_gather", postfix = QCOM) { documentation = """ Extension ${EXT_gpu_shader5.cap} introduced the texture gather built-in functions. Extension ${EXT_YUV_target.link} adds the ability to sample from YUV textures, but does not include gather functions. This extension allows gather function to be used in combination with the YUV textures exposed in {@code EXT_YUV_target}. """ }
bsd-3-clause
003c9b065b52d334f48a45fb40576519
55.066667
159
0.711992
4.881243
false
false
false
false
arturbosch/sonar-kotlin
src/main/kotlin/io/gitlab/arturbosch/detekt/sonar/foundation/Kotlin.kt
1
504
package io.gitlab.arturbosch.detekt.sonar.foundation import io.gitlab.arturbosch.detekt.sonar.DetektPlugin import org.sonar.api.utils.log.Logger import org.sonar.api.utils.log.Loggers const val LANGUAGE_KEY = "kotlin" const val REPOSITORY_KEY = "sonar-detekt" const val DETEKT_WAY = "detekt active" const val DETEKT_FAIL_FAST = "detekt all" const val DETEKT_SENSOR = "DetektSensor" const val DETEKT_ANALYZER = "Detekt-based Kotlin Analyzer" val logger: Logger = Loggers.get(DetektPlugin::class.java)
lgpl-3.0
6a184793b657416f5e35e39ab3a06376
32.6
58
0.789683
3.230769
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ModalityConversion.kt
6
2979
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.psi import org.jetbrains.kotlin.nj2k.tree.* class ModalityConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { when (element) { is JKClass -> processClass(element) is JKMethod -> processMethod(element) is JKField -> processField(element) } return recurse(element) } private fun processClass(klass: JKClass) { klass.modality = when { klass.classKind == JKClass.ClassKind.ENUM -> Modality.FINAL klass.classKind == JKClass.ClassKind.INTERFACE -> Modality.OPEN klass.modality == Modality.OPEN && context.converter.settings.openByDefault -> Modality.OPEN klass.modality == Modality.OPEN && !context.converter.converterServices.oldServices.referenceSearcher.hasInheritors(klass.psi as PsiClass) -> Modality.FINAL else -> klass.modality } } private fun processMethod(method: JKMethod) { val psi = method.psi<PsiMethod>() ?: return val containingClass = method.parentOfType<JKClass>() ?: return when { method.visibility == Visibility.PRIVATE -> { method.modality = Modality.FINAL } method.modality != Modality.ABSTRACT && psi.findSuperMethods().isNotEmpty() -> { method.modality = Modality.FINAL if (!method.hasOtherModifier(OtherModifier.OVERRIDE)) { method.otherModifierElements += JKOtherModifierElement(OtherModifier.OVERRIDE) } } method.modality == Modality.OPEN && context.converter.settings.openByDefault && containingClass.modality == Modality.OPEN && method.visibility != Visibility.PRIVATE -> { method.modality = Modality.OPEN } method.modality == Modality.OPEN && containingClass.classKind != JKClass.ClassKind.INTERFACE && !context.converter.converterServices.oldServices.referenceSearcher.hasOverrides(psi) -> { method.modality = Modality.FINAL } else -> method.modality = method.modality } } private fun processField(field: JKField) { val containingClass = field.parentOfType<JKClass>() ?: return if (containingClass.classKind == JKClass.ClassKind.INTERFACE) { field.modality = Modality.FINAL } } }
apache-2.0
16ebc171600de19c9bda23dbeb29ef0c
40.388889
129
0.620007
5.253968
false
false
false
false
google/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/KotlinLineBreakpoint.kt
2
3107
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger.core.breakpoints import com.intellij.debugger.engine.DebugProcess import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.debugger.ui.breakpoints.LineBreakpoint import com.intellij.openapi.project.Project import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.breakpoints.XBreakpoint import com.intellij.xdebugger.breakpoints.XBreakpointProperties import com.sun.jdi.ReferenceType import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties import org.jetbrains.kotlin.codegen.inline.KOTLIN_STRATA_NAME import org.jetbrains.kotlin.idea.debugger.base.util.DexDebugFacility import org.jetbrains.kotlin.idea.debugger.base.util.safeSourceName import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.util.containingNonLocalDeclaration class KotlinLineBreakpoint( project: Project?, xBreakpoint: XBreakpoint<out XBreakpointProperties<*>>? ) : LineBreakpoint<JavaLineBreakpointProperties>(project, xBreakpoint, false) { override fun processClassPrepare(debugProcess: DebugProcess?, classType: ReferenceType?) { val sourcePosition = runReadAction { xBreakpoint?.sourcePosition } if (classType != null && sourcePosition != null) { if (!hasTargetLine(classType, sourcePosition)) { return } } super.processClassPrepare(debugProcess, classType) } /** * Returns false if `classType` definitely does not contain a location for a given `sourcePosition`. */ private fun hasTargetLine(classType: ReferenceType, sourcePosition: XSourcePosition): Boolean { val allLineLocations = DebuggerUtilsEx.allLineLocations(classType) ?: return true if (DexDebugFacility.isDex(classType.virtualMachine())) { return true } val fileName = sourcePosition.file.name val lineNumber = sourcePosition.line + 1 for (location in allLineLocations) { val kotlinFileName = location.safeSourceName(KOTLIN_STRATA_NAME) val kotlinLineNumber = location.lineNumber(KOTLIN_STRATA_NAME) if (kotlinFileName != null) { if (kotlinFileName == fileName && kotlinLineNumber == lineNumber) { return true } } else { if (location.safeSourceName() == fileName && location.lineNumber() == lineNumber) { return true } } } return false } override fun getMethodName(): String? { val element = sourcePosition?.elementAt?.getNonStrictParentOfType<KtElement>() if (element is KtElement) { element.containingNonLocalDeclaration()?.name?.let { return it } } return super.getMethodName() } }
apache-2.0
4a0f73a85c40053ad40ac4a205c5c1d3
39.350649
120
0.708079
5.01129
false
false
false
false
google/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/util/DialogWithEditor.kt
2
2476
// 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.util import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsContexts import com.intellij.testFramework.LightVirtualFile import org.jetbrains.kotlin.idea.KotlinFileType import java.awt.BorderLayout import javax.swing.JComponent import javax.swing.JPanel open class DialogWithEditor( val project: Project, @NlsContexts.DialogTitle title: String, val initialText: String ) : DialogWrapper(project, true) { val editor: Editor = createEditor() init { init() setTitle(title) } final override fun init() { super.init() } private fun createEditor(): Editor { val editorFactory = EditorFactory.getInstance()!! val virtualFile = LightVirtualFile("dummy.kt", KotlinFileType.INSTANCE, initialText) val document = FileDocumentManager.getInstance().getDocument(virtualFile)!! val editor = editorFactory.createEditor(document, project, KotlinFileType.INSTANCE, false) val settings = editor.settings settings.isVirtualSpace = false settings.isLineMarkerAreaShown = false settings.isFoldingOutlineShown = false settings.isRightMarginShown = false settings.isAdditionalPageAtBottom = false settings.additionalLinesCount = 2 settings.additionalColumnsCount = 12 assert(editor is EditorEx) (editor as EditorEx).isEmbeddedIntoDialogWrapper = true editor.getColorsScheme().setColor(EditorColors.CARET_ROW_COLOR, editor.getColorsScheme().defaultBackground) return editor } override fun createCenterPanel(): JComponent { val panel = JPanel(BorderLayout()) panel.add(editor.component, BorderLayout.CENTER) return panel } override fun getPreferredFocusedComponent(): JComponent { return editor.contentComponent } override fun dispose() { super.dispose() EditorFactory.getInstance()!!.releaseEditor(editor) } }
apache-2.0
6382cb3c34e5129f621d5bc86d5f7135
33.388889
158
0.732633
4.922465
false
false
false
false
RuneSuite/client
plugins-dev/src/main/java/org/runestar/client/plugins/dev/IncreaseRenderDistance.kt
1
3665
package org.runestar.client.plugins.dev import org.runestar.client.api.plugins.DisposablePlugin import org.runestar.client.raw.CLIENT import org.runestar.client.raw.access.XScene import org.runestar.client.api.plugins.PluginSettings class IncreaseRenderDistance : DisposablePlugin<PluginSettings>() { override val defaultSettings = PluginSettings() override fun onStart() { add(XScene.draw.enter.subscribe { it.skipBody = true val scene = it.instance var camX = it.arguments[0] as Int val camY = it.arguments[1] as Int var camZ = it.arguments[2] as Int var pitch = it.arguments[3] as Int val yaw = it.arguments[4] as Int val plane = it.arguments[5] as Int camX = camX.coerceIn(0, scene.xSize * 128 - 1) camZ = camZ.coerceIn(0, scene.ySize * 128 - 1) pitch = pitch.coerceIn(128, 383) CLIENT.scene_cameraPitchSine = CLIENT.rasterizer3D_sine[pitch]; CLIENT.scene_cameraPitchCosine = CLIENT.rasterizer3D_cosine[pitch]; CLIENT.scene_cameraYawSine = CLIENT.rasterizer3D_sine[yaw]; CLIENT.scene_cameraYawCosine = CLIENT.rasterizer3D_cosine[yaw]; CLIENT.scene_cameraX = camX; CLIENT.scene_cameraY = camY; CLIENT.scene_cameraZ = camZ; CLIENT.scene_cameraXTile = camX / 128; CLIENT.scene_cameraYTile = camZ / 128; CLIENT.scene_plane = plane; CLIENT.scene_cameraXTileMin = 0 CLIENT.scene_cameraYTileMin = 0 CLIENT.scene_cameraXTileMax = scene.xSize CLIENT.scene_cameraYTileMax = scene.ySize CLIENT.scene_drawnCount++ CLIENT.scene_currentOccludersCount = 0 for (p in scene.minPlane..3) { for (x in 0..103) { for (y in 0..103) { val tile = scene.tiles[p][x][y] ?: continue val dx = x * 128 - camX val dy = CLIENT.tiles_heights[p][x][y] - camY val dz = y * 128 - camZ val var11 = (dz * CLIENT.scene_cameraYawCosine - dx * CLIENT.scene_cameraYawSine) shr 16 val var12 = (dy * CLIENT.scene_cameraPitchSine + var11 * CLIENT.scene_cameraPitchCosine) shr 16 if (tile.minPlane > plane || var12 >= 3500) { tile.drawPrimary = false tile.drawSecondary = false tile.drawSceneryEdges = 0 } else { tile.drawPrimary = true tile.drawSecondary = true tile.drawScenery = tile.sceneryCount > 0 } } } } for (p in scene.minPlane..3) { for (x in 0..103) { for (y in 0..103) { val tile = scene.tiles[p][x][y] ?: continue if (tile.drawPrimary) { scene.drawTile(tile, true) } } } } for (p in scene.minPlane..3) { for (x in 0..103) { for (y in 0..103) { val tile = scene.tiles[p][x][y] ?: continue if (tile.drawPrimary) { scene.drawTile(tile, false) } } } } }) } }
mit
9309785e58d650b04861e0e5ef3a506a
37.589474
119
0.486494
4.342417
false
false
false
false
JetBrains/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.kt
1
4826
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl import com.intellij.diagnostic.LoadingState import com.intellij.ide.ui.UISettings.Companion.setupAntialiasing import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.StatusBar import com.intellij.openapi.wm.impl.FrameInfoHelper.Companion.isMaximized import com.intellij.openapi.wm.impl.ProjectFrameHelper.Companion.getFrameHelper import com.intellij.ui.BalloonLayout import com.intellij.util.ui.EdtInvocationManager import com.intellij.util.ui.JBInsets import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import java.awt.Graphics import java.awt.Insets import java.awt.Rectangle import java.awt.Window import java.util.* import javax.accessibility.AccessibleContext import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JRootPane import javax.swing.SwingUtilities @ApiStatus.Internal class IdeFrameImpl : JFrame(), IdeFrame, DataProvider { companion object { @JvmStatic val activeFrame: Window? get() = getFrames().firstOrNull { it.isActive } } var frameHelper: FrameHelper? = null private set var normalBounds: Rectangle? = null // when this client property is true, we have to ignore 'resizing' events and not spoil 'normal bounds' value for frame var togglingFullScreenInProgress: Boolean = true override fun getData(dataId: String): Any? = frameHelper?.getData(dataId) interface FrameHelper : DataProvider { val accessibleName: @Nls String? val project: Project? val helper: IdeFrame val frameDecorator: FrameDecorator? fun dispose() } interface FrameDecorator { val isInFullScreen: Boolean fun frameInit() {} fun frameShow() {} fun appClosing() {} } override fun addNotify() { super.addNotify() frameHelper?.frameDecorator?.frameInit() } override fun createRootPane(): JRootPane? = null internal fun doSetRootPane(rootPane: JRootPane?) { super.setRootPane(rootPane) } // NB!: the root pane must be set before decorator, // which holds its own client properties in a root pane fun setFrameHelper(frameHelper: FrameHelper?) { this.frameHelper = frameHelper } override fun getAccessibleContext(): AccessibleContext { if (accessibleContext == null) { accessibleContext = AccessibleIdeFrameImpl() } return accessibleContext } override fun setExtendedState(state: Int) { // do not load FrameInfoHelper class if (LoadingState.COMPONENTS_REGISTERED.isOccurred && extendedState == NORMAL && isMaximized(state)) { normalBounds = bounds } super.setExtendedState(state) } override fun paint(g: Graphics) { if (LoadingState.COMPONENTS_REGISTERED.isOccurred) { setupAntialiasing(g) } super.paint(g) } @Suppress("OVERRIDE_DEPRECATION") override fun show() { @Suppress("DEPRECATION") super.show() SwingUtilities.invokeLater { focusableWindowState = true frameHelper?.frameDecorator?.frameShow() } } override fun getInsets(): Insets { return if (SystemInfoRt.isMac && isInFullScreen) JBInsets.emptyInsets() else super.getInsets() } override fun isInFullScreen(): Boolean = frameHelper?.frameDecorator?.isInFullScreen ?: false override fun dispose() { val frameHelper = frameHelper if (frameHelper == null) { doDispose() } else { frameHelper.dispose() } } fun doDispose() { EdtInvocationManager.invokeLaterIfNeeded { super.dispose() } } private inner class AccessibleIdeFrameImpl : AccessibleJFrame() { override fun getAccessibleName(): String { val frameHelper = frameHelper return if (frameHelper == null) super.getAccessibleName() else frameHelper.accessibleName!! } } @Deprecated("Use {@link ProjectFrameHelper#getProject()} instead.", ReplaceWith("frameHelper?.project")) override fun getProject(): Project? = frameHelper?.project // deprecated stuff - as IdeFrame must be implemented (a lot of instanceof checks for JFrame) override fun getStatusBar(): StatusBar? = frameHelper?.helper?.statusBar override fun suggestChildFrameBounds(): Rectangle = frameHelper!!.helper.suggestChildFrameBounds() override fun setFrameTitle(title: String) { frameHelper?.helper?.setFrameTitle(title) } override fun getComponent(): JComponent = getRootPane() override fun getBalloonLayout(): BalloonLayout? = frameHelper?.helper?.balloonLayout override fun notifyProjectActivation() { getFrameHelper(this)?.notifyProjectActivation() } }
apache-2.0
70fdcb92fde18fb9107bf997dd6b1b61
29.745223
121
0.743058
4.618182
false
false
false
false
customerly/Customerly-Android-SDK
customerly-android-sdk/src/main/java/io/customerly/utils/ggkext/Ext_View.kt
1
3244
@file:Suppress("unused") /* * Copyright (C) 2017 Customerly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.customerly.utils.ggkext import android.app.Activity import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.PopupWindow import io.customerly.sxdependencies.annotations.SXIntDef import java.lang.ref.WeakReference /** * Created by Gianni on 02/11/17. */ internal val PopupWindow.activity : Activity? get() = this.contentView.activity internal val View.activity : Activity? get() = this.context.tryBaseContextActivity internal infix fun View.goneFor(show: View) { viewsGone(this) viewsVisible(show) } internal infix fun View.invisibleFor(show: View) { viewsInvisible(this) viewsVisible(show) } internal infix fun View.visibleIfIsVisible(check: View) { if(check.visibility == View.VISIBLE) { viewsVisible(this) } } internal fun View.visibleIfNotVisible() { if (this.visibility != View.VISIBLE) { this.visibility = View.VISIBLE } } @SXIntDef(View.VISIBLE, View.INVISIBLE, View.GONE) @Retention(AnnotationRetention.SOURCE) internal annotation class ViewVisibility internal fun viewsVisibility(vararg views: View, @ViewVisibility visibility : Int) { views.forEach { v -> v.visibility = visibility } } internal fun viewsVisible(vararg hide : View) { viewsVisibility(*hide, visibility = View.VISIBLE) } internal fun viewsInvisible(vararg hide : View) { viewsVisibility(*hide, visibility = View.INVISIBLE) } internal fun viewsGone(vararg hide : View) { viewsVisibility(*hide, visibility = View.GONE) } internal fun <R1, VIEW : View> VIEW.setOnClickListenerWithWeak(r1 : R1, onClick : (View,R1?)->Unit) { val w1 = WeakReference(r1) this.setOnClickListener { @Suppress("UNCHECKED_CAST") onClick(it as VIEW,w1.get()) } } @ViewVisibility internal val Boolean.toViewVisibility : Int get() = if(this) View.VISIBLE else View.GONE internal fun overrideValueAnimatorDurationScale(durationScale : Float = 1f) { try { android.animation.ValueAnimator::class.java .getMethod("setDurationScale", Float::class.javaPrimitiveType!!) .invoke(null, durationScale) /* Proguard: -keepclasseswithmembers class android.animation.ValueAnimator { public static void setDurationScale(float); } */ } catch (justInCase_es_methodNameRefactoring: Throwable) { } } internal fun View.dismissKeyboard() { (this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(this.windowToken, 0) }
apache-2.0
e38c1698abf923d583cddf6a55e0d2e5
29.046296
134
0.720099
4.065163
false
false
false
false
fluidsonic/fluid-json
annotation-processor/test-cases/1/output-expected/json/encoding/AllPropertiesJsonCodec.kt
1
2217
package json.encoding import codecProvider.CustomCodingContext import io.fluidsonic.json.AbstractJsonCodec import io.fluidsonic.json.JsonCodingType import io.fluidsonic.json.JsonDecoder import io.fluidsonic.json.JsonEncoder import io.fluidsonic.json.missingPropertyError import io.fluidsonic.json.readBooleanOrNull import io.fluidsonic.json.readByteOrNull import io.fluidsonic.json.readCharOrNull import io.fluidsonic.json.readDoubleOrNull import io.fluidsonic.json.readFloatOrNull import io.fluidsonic.json.readFromMapByElementValue import io.fluidsonic.json.readIntOrNull import io.fluidsonic.json.readLongOrNull import io.fluidsonic.json.readShortOrNull import io.fluidsonic.json.readStringOrNull import io.fluidsonic.json.readValueOfType import io.fluidsonic.json.readValueOfTypeOrNull import io.fluidsonic.json.writeBooleanOrNull import io.fluidsonic.json.writeByteOrNull import io.fluidsonic.json.writeCharOrNull import io.fluidsonic.json.writeDoubleOrNull import io.fluidsonic.json.writeFloatOrNull import io.fluidsonic.json.writeIntOrNull import io.fluidsonic.json.writeIntoMap import io.fluidsonic.json.writeLongOrNull import io.fluidsonic.json.writeMapElement import io.fluidsonic.json.writeShortOrNull import io.fluidsonic.json.writeStringOrNull import io.fluidsonic.json.writeValueOrNull import json.encoding.value9 import kotlin.String import kotlin.Unit internal object AllPropertiesJsonCodec : AbstractJsonCodec<AllProperties, CustomCodingContext>() { public override fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<AllProperties>): AllProperties { var _value1: String? = null readFromMapByElementValue { key -> when (key) { "value1" -> _value1 = readString() else -> skipValue() } } return AllProperties( value1 = _value1 ?: missingPropertyError("value1") ) } public override fun JsonEncoder<CustomCodingContext>.encode(`value`: AllProperties): Unit { writeIntoMap { writeMapElement("value1", string = value.value1) writeMapElement("value2", string = value.value2) writeMapElement("value5", string = value.value5) writeMapElement("value6", string = value.value6) writeMapElement("value9", string = value.value9) } } }
apache-2.0
4d1173e9339cc0a4756360962330b2a3
33.640625
98
0.819576
4.381423
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/component/dialog/FluentDialog.kt
1
2072
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.ui.component.dialog import com.faendir.acra.i18n.Messages import com.faendir.acra.util.catching import com.vaadin.flow.component.Component import com.vaadin.flow.component.HasSize import com.vaadin.flow.component.orderedlayout.FlexLayout import org.springframework.data.util.Pair import kotlin.streams.asSequence /** * @author Lukas * @since 19.12.2017 */ class FluentDialog : AcrariumDialog() { private val fields: MutableMap<ValidatedField<*, *>, Pair<Boolean, (Boolean) -> Unit>> = mutableMapOf() fun validatedField(validatedField: ValidatedField<*, *>, isInitialValid: Boolean = false) { val listener: (Boolean) -> Unit = { updateField(validatedField, it) } validatedField.addListener(listener) fields[validatedField] = Pair.of(isInitialValid, listener) add(validatedField.field) } private fun updateField(field: ValidatedField<*, *>, value: Boolean) { fields[field] = Pair.of(value, fields[field]!!.second) checkValid() } fun show() { checkValid() if (!isOpened) { open() } } private fun checkValid() { val valid = fields.values.map { it.first }.fold(true) { a, b -> a && b } positive?.let { it.content.isEnabled = valid } } } fun showFluentDialog(initializer: FluentDialog.() -> Unit) { val dialog = FluentDialog() dialog.initializer() dialog.show() }
apache-2.0
15023c4545d6bd7e5c1fe1fcdac6ac8d
32.435484
107
0.689672
3.969349
false
false
false
false
zdary/intellij-community
python/src/com/jetbrains/extensions/QualifiedNameExt.kt
4
6709
/* * 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.jetbrains.extensions import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PyNames import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.resolve.* import com.jetbrains.python.psi.stubs.PyModuleNameIndex import com.jetbrains.python.psi.types.TypeEvalContext import com.jetbrains.python.sdk.PythonSdkType interface ContextAnchor { val sdk: Sdk? val project: Project val qualifiedNameResolveContext: PyQualifiedNameResolveContext? val scope: GlobalSearchScope fun getRoots(): Array<VirtualFile> { return sdk?.rootProvider?.getFiles(OrderRootType.CLASSES) ?: emptyArray() } } class ModuleBasedContextAnchor(val module: Module) : ContextAnchor { override val sdk: Sdk? = module.getSdk() override val project: Project = module.project override val qualifiedNameResolveContext: PyQualifiedNameResolveContext = fromModule(module) override val scope: GlobalSearchScope = module.moduleContentScope override fun getRoots(): Array<VirtualFile> { val manager = ModuleRootManager.getInstance(module) return super.getRoots() + manager.contentRoots + manager.sourceRoots } } class ProjectSdkContextAnchor(override val project: Project, override val sdk: Sdk?) : ContextAnchor { override val qualifiedNameResolveContext: PyQualifiedNameResolveContext? = sdk?.let { fromSdk(project, it) } override val scope: GlobalSearchScope = GlobalSearchScope.projectScope(project) //TODO: Check if project scope includes SDK override fun getRoots(): Array<VirtualFile> { val manager = ProjectRootManager.getInstance(project) return super.getRoots() + manager.contentRoots + manager.contentSourceRoots } } data class QNameResolveContext( val contextAnchor: ContextAnchor, /** * Used for language level etc */ val sdk: Sdk? = contextAnchor.sdk, val evalContext: TypeEvalContext, /** * If not provided resolves against roots only. Resolved also against this folder otherwise */ val folderToStart: VirtualFile? = null, /** * Use index, plain dirs with Py2 and so on. May resolve names unresolvable in other cases, but may return false results. */ val allowInaccurateResult: Boolean = false ) /** * @return qname part relative to root */ fun QualifiedName.getRelativeNameTo(root: QualifiedName): QualifiedName? { if (!toString().startsWith(root.toString())) { return null } return subQualifiedName(root.componentCount, componentCount) } /** * Resolves qname of any symbol to appropriate PSI element. * Shortcut for [getElementAndResolvableName] * @see [getElementAndResolvableName] */ fun QualifiedName.resolveToElement(context: QNameResolveContext, stopOnFirstFail: Boolean = false): PsiElement? { return getElementAndResolvableName(context, stopOnFirstFail)?.element } data class NameAndElement(val name: QualifiedName, val element: PsiElement) /** * Resolves qname of any symbol to PSI element popping tail until element becomes resolved or only one time if stopOnFirstFail * @return element and longest name that was resolved successfully. * @see [resolveToElement] */ fun QualifiedName.getElementAndResolvableName(context: QNameResolveContext, stopOnFirstFail: Boolean = false): NameAndElement? { var currentName = QualifiedName.fromComponents(this.components) var element: PsiElement? = null var lastElement: String? = null var psiDirectory: PsiDirectory? = null var resolveContext = context.contextAnchor.qualifiedNameResolveContext?.copyWithMembers() ?: return null if (PythonSdkType.getLanguageLevelForSdk(context.sdk).isPy3K || context.allowInaccurateResult) { resolveContext = resolveContext.copyWithPlainDirectories() } if (context.folderToStart != null) { psiDirectory = PsiManager.getInstance(context.contextAnchor.project).findDirectory(context.folderToStart) } // Drill as deep, as we can while (currentName.componentCount > 0 && element == null) { if (psiDirectory != null) { // Resolve against folder // There could be folder and module on the same level. Empty folder should be ignored in this case. element = resolveModuleAt(currentName, psiDirectory, resolveContext).filterNot { it is PsiDirectory && it.children.filterIsInstance<PyFile>().isEmpty() }.firstOrNull() } if (element == null) { // Resolve against roots element = resolveQualifiedName(currentName, resolveContext).firstOrNull() } if (element != null || stopOnFirstFail) { break } lastElement = currentName.lastComponent!! currentName = currentName.removeLastComponent() } if (lastElement != null && element is PyClass) { // Drill in class //TODO: Support nested classes val method = element.findMethodByName(lastElement, true, context.evalContext) if (method != null) { return NameAndElement(currentName.append(lastElement), method) } } if (element == null && this.firstComponent != null && context.allowInaccurateResult) { // If name starts with file which is not in root nor in folders -- use index. val nameToFind = this.firstComponent!! val pyFile = PyModuleNameIndex.find(nameToFind, context.contextAnchor.project, false).firstOrNull() ?: return element val folder = if (pyFile.name == PyNames.INIT_DOT_PY) { // We are in folder pyFile.virtualFile.parent.parent } else { pyFile.virtualFile.parent } return getElementAndResolvableName(context.copy(folderToStart = folder)) } return if (element != null) NameAndElement(currentName, element) else null }
apache-2.0
8057df96f7799cf57badaca3df546f5d
36.066298
128
0.756894
4.68833
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/query/property/IndexProperty.kt
1
1072
package com.dbflow5.query.property import com.dbflow5.annotation.Table import com.dbflow5.database.DatabaseWrapper import com.dbflow5.query.Index import com.dbflow5.quoteIfNeeded /** * Description: Defines an INDEX in Sqlite. It basically speeds up data retrieval over large datasets. * It gets generated from [Table.indexGroups], but also can be manually constructed. These are activated * and deactivated manually. */ class IndexProperty<T : Any>(indexName: String, private val unique: Boolean, private val table: Class<T>, vararg properties: IProperty<*>) { @Suppress("UNCHECKED_CAST") private val properties: Array<IProperty<*>> = properties as Array<IProperty<*>> val index: Index<T> get() = Index(indexName, table).on(*properties).unique(unique) val indexName = indexName.quoteIfNeeded() ?: "" fun createIfNotExists(wrapper: DatabaseWrapper) = index.createIfNotExists(wrapper) fun drop(wrapper: DatabaseWrapper) = index.drop(wrapper) }
mit
acca5a5c21bbec7bf097341f31bafe31
35.965517
104
0.689366
4.681223
false
false
false
false
yeungeek/AndroidRoad
AVSample/app/src/main/java/com/yeungeek/avsample/activities/media/MediaRecorderActivity.kt
1
8057
package com.yeungeek.avsample.activities.media import android.annotation.SuppressLint import android.content.Context import android.hardware.camera2.* import android.media.MediaRecorder import android.os.Bundle import android.os.Environment import android.os.Handler import android.os.HandlerThread import android.view.SurfaceHolder import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.yeungeek.avsample.R import com.yeungeek.avsample.databinding.ActivityMediaRecorderBinding import timber.log.Timber import java.io.File class MediaRecorderActivity : AppCompatActivity(), View.OnClickListener { private lateinit var binding: ActivityMediaRecorderBinding private val mVideoRecorderFilePath: String private lateinit var mMediaRecorder: MediaRecorder private lateinit var mCameraId: String private var isRecording = false private var videoWidth = 1280 private var videoHeight = 720 private val cameraManager: CameraManager by lazy { getSystemService(Context.CAMERA_SERVICE) as CameraManager } private val characteristics: CameraCharacteristics by lazy { cameraManager.getCameraCharacteristics(mCameraId) } private val cameraThread = HandlerThread("CameraThread").apply { start() } private val cameraHandler = Handler(cameraThread.looper) private lateinit var cameraSession: CameraCaptureSession private lateinit var cameraDevice: CameraDevice private val previewRequest: CaptureRequest by lazy { cameraSession.device.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW).apply { addTarget(binding.recorderSurfaceView.holder.surface) }.build() } private val recorderRequest: CaptureRequest by lazy { cameraSession.device.createCaptureRequest(CameraDevice.TEMPLATE_RECORD).apply { addTarget(binding.recorderSurfaceView.holder.surface) addTarget(mMediaRecorder?.surface) }.build() } init { val filePath = File( "${Environment.getExternalStorageDirectory().absolutePath}" + File.separator + "media" + File.separator + "record" ) filePath.mkdirs() mVideoRecorderFilePath = "$filePath" + File.separator + "media_recorder" + System.currentTimeMillis() + ".mp4" Timber.d("##### recorder file path $mVideoRecorderFilePath") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMediaRecorderBinding.inflate(layoutInflater) setContentView(binding.root) init() } private fun init() { binding.recorderButton.setOnClickListener(this) var cameraIdList = cameraManager.cameraIdList mCameraId = cameraIdList[0] Timber.d("##### camera id: $mCameraId") binding.recorderSurfaceView.holder.addCallback(object : SurfaceHolder.Callback2 { override fun surfaceCreated(holder: SurfaceHolder) { binding.recorderSurfaceView.setAspectRatio(videoWidth, videoHeight) initCamera() } override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { } override fun surfaceDestroyed(holder: SurfaceHolder) { } override fun surfaceRedrawNeeded(holder: SurfaceHolder) { } }) initMediaRecorder() muxer() } @SuppressLint("MissingPermission") private fun initCamera() { Timber.d("##### initCamera") cameraManager.openCamera(mCameraId, object : CameraDevice.StateCallback() { override fun onOpened(camera: CameraDevice) { Timber.e("##### camera onOpened") cameraDevice = camera createCaptureSession() } override fun onDisconnected(camera: CameraDevice) { Timber.e("##### camera onDisconnected") } override fun onError(camera: CameraDevice, error: Int) { val msg = when (error) { ERROR_CAMERA_DEVICE -> "Fatal (device)" ERROR_CAMERA_DISABLED -> "Device policy" ERROR_CAMERA_IN_USE -> "Camera in use" ERROR_CAMERA_SERVICE -> "Fatal (service)" ERROR_MAX_CAMERAS_IN_USE -> "Maximum cameras in use" else -> "Unknown" } Timber.e("##### camera onError $msg") } }, cameraHandler) } private fun createCaptureSession() { val targets = listOf(binding.recorderSurfaceView.holder.surface) cameraDevice.createCaptureSession( targets, object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { cameraSession = session updatePreview() } override fun onConfigureFailed(session: CameraCaptureSession) { } }, cameraHandler ) } private fun updatePreview() { cameraSession.setRepeatingRequest( previewRequest, object : CameraCaptureSession.CaptureCallback() { }, cameraHandler ) } private fun initMediaRecorder() { mMediaRecorder = MediaRecorder().apply { setOrientationHint(90) setAudioSource(MediaRecorder.AudioSource.MIC) setVideoSource(MediaRecorder.VideoSource.SURFACE) setOutputFormat(MediaRecorder.OutputFormat.MPEG_4) setVideoEncoder(MediaRecorder.VideoEncoder.H264) setAudioEncoder(MediaRecorder.AudioEncoder.AAC) //size setVideoSize(videoWidth, videoHeight) setVideoEncodingBitRate(1_000_000) setVideoFrameRate(30) setOutputFile(mVideoRecorderFilePath) } } private fun startRecorder() { if (isRecording) { isRecording = false if (null != mMediaRecorder) { mMediaRecorder.stop() mMediaRecorder.reset() } binding.root.postDelayed({ Toast.makeText( this, "Record Finished, File Saved $mVideoRecorderFilePath", Toast.LENGTH_LONG ).show() finish() }, 1000) return } mMediaRecorder.prepare() val targets = listOf(binding.recorderSurfaceView.holder.surface, mMediaRecorder.surface) cameraSession?.let { it.close() null } Timber.d("##### camera session $cameraSession") cameraDevice.createCaptureSession( targets, object : CameraCaptureSession.StateCallback() { override fun onConfigured(session: CameraCaptureSession) { cameraSession = session cameraSession.setRepeatingRequest(recorderRequest, null, cameraHandler) isRecording = true mMediaRecorder.apply { Timber.d("##### start recorder") start() } } override fun onConfigureFailed(session: CameraCaptureSession) { } }, cameraHandler ) } private fun muxer() { } override fun onClick(v: View?) { when (v?.id) { R.id.recorder_button -> { startRecorder() } } } override fun onDestroy() { super.onDestroy() try { cameraDevice.close() cameraThread.quitSafely() } catch (e: Throwable) { Timber.e("##### on destroy", e) } } }
apache-2.0
b0b18b5a29209460cfeb249f00c4effd
30.849802
102
0.596252
5.60682
false
false
false
false
leafclick/intellij-community
tools/index-tools/src/org/jetbrains/index/IndexGenerator.kt
1
3378
// 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.index import com.google.common.hash.HashCode import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileFilter import com.intellij.openapi.vfs.VirtualFileVisitor import com.intellij.psi.stubs.FileContentHashing import com.intellij.util.SystemProperties import com.intellij.util.indexing.FileContentImpl import com.intellij.util.io.PersistentHashMap import junit.framework.TestCase import java.util.* import java.util.concurrent.atomic.AtomicInteger abstract class IndexGenerator<Value>(private val indexStorageFilePath: String) { companion object { @Suppress("MemberVisibilityCanBePrivate") // used by GoLand const val CHECK_HASH_COLLISIONS_PROPERTY = "idea.index.generator.check.hash.collisions" val CHECK_HASH_COLLISIONS: Boolean = SystemProperties.`is`(CHECK_HASH_COLLISIONS_PROPERTY) } open val fileFilter: VirtualFileFilter get() = VirtualFileFilter { f -> !f.isDirectory } data class Stats(val indexed: AtomicInteger, val skipped: AtomicInteger) { constructor() : this(AtomicInteger(), AtomicInteger()) } protected fun buildIndexForRoots(roots: Collection<VirtualFile>) { val hashing = FileContentHashing() val storage = createStorage(indexStorageFilePath) println("Writing indices to ${storage.baseFile}") storage.use { val map = HashMap<HashCode, String>() for (file in roots) { println("Processing files in root ${file.path}") val stats = Stats() VfsUtilCore.visitChildrenRecursively(file, object : VirtualFileVisitor<Boolean>() { override fun visitFile(file: VirtualFile): Boolean { return indexFile(file, hashing, map, storage, stats) } }) println("${stats.indexed.get()} entries written, ${stats.skipped.get()} skipped") } } } private fun indexFile(file: VirtualFile, hashing: FileContentHashing, map: MutableMap<HashCode, String>, storage: PersistentHashMap<HashCode, Value>, stats: Stats): Boolean { try { if (fileFilter.accept(file)) { val fileContent = FileContentImpl.createByFile(file) as FileContentImpl val hashCode = hashing.hashString(fileContent) val value = getIndexValue(fileContent) if (value != null) { val item = map[hashCode] if (item == null) { storage.put(hashCode, value) stats.indexed.incrementAndGet() if (CHECK_HASH_COLLISIONS) { map[hashCode] = fileContent.contentAsText.toString() } } else { TestCase.assertEquals(item, fileContent.contentAsText.toString()) TestCase.assertTrue(storage.get(hashCode) == value) } } else { stats.skipped.incrementAndGet() } } } catch (e: NoSuchElementException) { return false } return true } protected abstract fun getIndexValue(fileContent: FileContentImpl): Value? protected abstract fun createStorage(stubsStorageFilePath: String): PersistentHashMap<HashCode, Value> }
apache-2.0
0019d1270512a842099656d35bd1af1c
34.568421
140
0.676436
4.811966
false
true
false
false
leafclick/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/Java9ModuleExportsPackageToItselfTest.kt
1
3498
/* * 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.java.codeInspection import com.intellij.codeInspection.InspectionsBundle import com.intellij.codeInspection.java19modules.Java9ModuleExportsPackageToItselfInspection import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor import org.intellij.lang.annotations.Language /** * @author Pavel.Dolgov */ class Java9ModuleExportsPackageToItselfTest : LightJava9ModulesCodeInsightFixtureTestCase() { private val message = InspectionsBundle.message("inspection.module.exports.package.to.itself") private val fix1 = InspectionsBundle.message("exports.to.itself.delete.statement.fix") private val fix2 = InspectionsBundle.message("exports.to.itself.delete.module.ref.fix", "M") override fun setUp() { super.setUp() myFixture.enableInspections(Java9ModuleExportsPackageToItselfInspection()) addFile("module-info.java", "module M2 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M2) addFile("module-info.java", "module M4 { }", MultiModuleJava9ProjectDescriptor.ModuleDescriptor.M4) addFile("pkg/main/C.java", "package pkg.main; public class C {}") } fun testNoSelfModule() { highlight("module M {\n exports pkg.main to M2, M4;\n opens pkg.main to M2, M4;\n}") } fun testOnlySelfExport() { highlight("module M { exports pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { exports pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfOpen() { highlight("module M { opens pkg.main to <warning descr=\"$message\">M</warning>; }") fix("module M { opens pkg.main to <caret>M; }", "module M {\n}") } fun testOnlySelfModuleWithComments() { fix("module M { exports pkg.main to /*a*/ <caret>M /*b*/; }", "module M { /*a*/ /*b*/\n}") } fun testSelfModuleInList() { highlight("module M { exports pkg.main to M2, <warning descr=\"$message\">M</warning>, M4; }") fix("module M { exports pkg.main to M2, <caret>M , M4; }", "module M { exports pkg.main to M2, M4; }") } fun testSelfModuleInListWithComments() { fix("module M { exports pkg.main to M2, /*a*/ <caret>M /*b*/,/*c*/ M4; }", "module M { exports pkg.main to M2, /*a*/ /*b*//*c*/ M4; }") } private fun highlight(text: String) { myFixture.configureByText("module-info.java", text) myFixture.checkHighlighting() } private fun fix(textBefore: String, @Language("JAVA") textAfter: String) { myFixture.configureByText("module-info.java", textBefore) val action = myFixture.filterAvailableIntentions(fix1).firstOrNull() ?: myFixture.filterAvailableIntentions(fix2).first() myFixture.launchAction(action) myFixture.checkHighlighting() // no warning myFixture.checkResult("module-info.java", textAfter, false) } }
apache-2.0
6871cd21e14a574750c210b94cc4283d
39.218391
125
0.712407
3.979522
false
true
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/classes/kt2395.kt
5
345
// TARGET_BACKEND: JVM import java.util.AbstractList class MyList(): AbstractList<String>() { public fun getModificationCount(): Int = modCount public override fun get(index: Int): String = "" public override val size: Int get() = 0 } fun box(): String { return if (MyList().getModificationCount() == 0) "OK" else "fail" }
apache-2.0
b86be004647d6ac9958c4da00be8d36d
25.538462
69
0.666667
3.876404
false
false
false
false
blokadaorg/blokada
android5/app/src/main/java/ui/home/ProtectionLevelFragment.kt
1
6659
/* * 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 android.content.Context import android.graphics.drawable.LevelListDrawable import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.TextView import androidx.lifecycle.ViewModelProvider import engine.MetricsService import org.blokada.R import repository.DnsDataSource import service.ConnectivityService import service.EnvironmentService import ui.BottomSheetFragment import ui.TunnelViewModel import ui.advanced.statusToLevel import ui.app import java.lang.Integer.max class ProtectionLevelFragment : BottomSheetFragment(skipCollapsed = false) { private lateinit var tunnelVM: TunnelViewModel companion object { fun newInstance() = ProtectionLevelFragment() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { activity?.let { tunnelVM = ViewModelProvider(it.app()).get(TunnelViewModel::class.java) } val root = inflater.inflate(R.layout.fragment_encryption_level, container, false) val back: View = root.findViewById(R.id.back) back.setOnClickListener { dismiss() } val encryptContinue: Button = root.findViewById(R.id.encryption_continue) encryptContinue.setOnClickListener { dismiss() } val encryptLevel = root.findViewById<TextView>(R.id.encryption_level) val encryptDns = root.findViewById<View>(R.id.encryption_dns) val encryptDnsIcon = root.findViewById<ImageView>(R.id.encryption_dns_icon) val encryptEverything = root.findViewById<View>(R.id.encryption_everything) val encryptEverythingIcon = root.findViewById<ImageView>(R.id.encryption_everything_icon) val encryptIcon = root.findViewById<ImageView>(R.id.encryption_icon) val detailDns = root.findViewById<TextView>(R.id.home_detail_dns) val detailDoh = root.findViewById<TextView>(R.id.home_detail_dns_doh) val detailVpn = root.findViewById<TextView>(R.id.home_detail_vpn) tunnelVM.tunnelStatus.observe(viewLifecycleOwner) { status -> val level = statusToLevel(status) val ctx = requireContext() encryptLevel.text = ctx.levelToShortText(level) encryptDns.alpha = if (level >= 1) 1.0f else 0.3f encryptEverything.alpha = if (level == 2) 1.0f else 0.3f (encryptIcon.drawable as? LevelListDrawable)?.let { it.level = max(0, level) } detailDns.text = status.dns?.label ?: ctx.getString(R.string.universal_label_none) if (DnsDataSource.network.id == status.dns?.id) { detailDns.text = "Network DNS (${ConnectivityService.getActiveNetworkDns()})" } else if (!EnvironmentService.isLibre()) { detailDns.text = "Blokada Cloud" } when (level) { 2 -> { encryptDns.alpha = 1.0f encryptEverything.alpha = 1.0f encryptDnsIcon.setImageResource(R.drawable.ic_baseline_check_24) encryptEverythingIcon.setImageResource(R.drawable.ic_baseline_check_24) detailDoh.text = ctx.getString(R.string.universal_action_yes) detailVpn.text = status.gatewayLabel // encryptContinue.text = getString(R.string.universal_action_close) // encryptContinue.setOnClickListener { // dismiss() // } } 1 -> { encryptDns.alpha = 1.0f encryptEverything.alpha = 0.3f encryptDnsIcon.setImageResource(R.drawable.ic_baseline_check_24) encryptEverythingIcon.setImageResource(R.drawable.ic_baseline_close_24) detailDoh.text = ctx.getString(R.string.universal_action_yes) detailVpn.text = ctx.getString(R.string.universal_label_none) // encryptContinue.text = getString(R.string.universal_action_upgrade).toBlokadaPlusText() // encryptContinue.setOnClickListener { // dismiss() // val nav = findNavController() // nav.navigate(R.id.navigation_home) // val fragment = PaymentFragment.newInstance() // fragment.show(parentFragmentManager, null) // } } else -> { encryptDns.alpha = 0.3f encryptEverything.alpha = 0.3f encryptDnsIcon.setImageResource(R.drawable.ic_baseline_close_24) encryptEverythingIcon.setImageResource(R.drawable.ic_baseline_close_24) detailDoh.text = ctx.getString(R.string.universal_action_no) detailVpn.text = ctx.getString(R.string.universal_label_none) // encryptContinue.text = getString(R.string.home_power_action_turn_on) // encryptContinue.setOnClickListener { // dismiss() // val nav = findNavController() // nav.navigate(R.id.navigation_home) // tunnelVM.turnOn() // } } } } detailPing = root.findViewById(R.id.home_detail_ping) pingRefresh.sendEmptyMessage(0) return root } private lateinit var detailPing: TextView private val pingRefresh = Handler { detailPing.text = MetricsService.lastRtt.run { if (this == 9999L) "-" else toString() } reschedulePingRefresh() true } private fun reschedulePingRefresh() { if (isAdded) pingRefresh.sendEmptyMessageDelayed(0, 3000) } } private fun Context.levelToShortText(level: Int): String { return when (level) { 1 -> getString(R.string.home_level_medium) 2 -> getString(R.string.home_level_high) else -> getString(R.string.home_level_low) } }
mpl-2.0
57fa5dc7a5d52c024e3be40d80d40cbf
39.108434
109
0.617002
4.432756
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/ui/OnboardingFeedbackForm.kt
1
17071
// 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 training.ui import com.intellij.feedback.FEEDBACK_REPORT_ID_KEY import com.intellij.feedback.FeedbackRequestType import com.intellij.feedback.dialog.COMMON_FEEDBACK_SYSTEM_INFO_VERSION import com.intellij.feedback.dialog.CommonFeedbackSystemInfoData import com.intellij.feedback.dialog.showFeedbackSystemInfoDialog import com.intellij.feedback.submitGeneralFeedback import com.intellij.ide.RecentProjectsManagerBase import com.intellij.internal.statistic.local.ActionsLocalSummary import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.invokeLater import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeBalloonLayoutImpl import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.ui.HyperlinkAdapter import com.intellij.ui.JBColor import com.intellij.ui.components.JBScrollPane import com.intellij.ui.components.JBTextArea import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.IconUtil import com.intellij.util.ui.* import kotlinx.serialization.encodeToString import kotlinx.serialization.json.* import org.jetbrains.annotations.Nls import training.FeaturesTrainerIcons import training.dsl.LessonUtil import training.learn.LearnBundle import training.statistic.FeedbackEntryPlace import training.statistic.FeedbackLikenessAnswer import training.statistic.StatisticBase import training.util.OnboardingFeedbackData import training.util.findLanguageSupport import training.util.iftNotificationGroup import java.awt.Color import java.awt.Dimension import java.awt.Font import java.awt.Graphics import java.awt.event.ActionEvent import javax.swing.* import javax.swing.event.HyperlinkEvent import javax.swing.text.html.HTMLDocument private const val FEEDBACK_CONTENT_WIDTH = 500 private const val SUB_OFFSET = 20 /** Increase the additional number when onboarding feedback format is changed */ private const val FEEDBACK_JSON_VERSION = COMMON_FEEDBACK_SYSTEM_INFO_VERSION + 0 fun showOnboardingFeedbackNotification(project: Project?, onboardingFeedbackData: OnboardingFeedbackData) { onboardingFeedbackData.feedbackHasBeenProposed() StatisticBase.logOnboardingFeedbackNotification(getFeedbackEntryPlace(project)) val notification = iftNotificationGroup.createNotification(LearnBundle.message("onboarding.feedback.notification.title"), LearnBundle.message("onboarding.feedback.notification.message", LessonUtil.productName), NotificationType.INFORMATION) notification.addAction(object : NotificationAction(LearnBundle.message("onboarding.feedback.notification.action")) { override fun actionPerformed(e: AnActionEvent, notification: Notification) { val feedbackHasBeenSent = showOnboardingLessonFeedbackForm(project, onboardingFeedbackData, true) notification.expire() if (feedbackHasBeenSent) { invokeLater { // It is needed to show "Thank you" notification (WelcomeFrame.getInstance()?.balloonLayout as? WelcomeBalloonLayoutImpl)?.showPopup() } } } }) notification.notify(project) } fun showOnboardingLessonFeedbackForm(project: Project?, onboardingFeedbackData: OnboardingFeedbackData, openedViaNotification: Boolean): Boolean { onboardingFeedbackData?.feedbackHasBeenProposed() val saver = mutableListOf<JsonObjectBuilder.() -> Unit>() fun feedbackTextArea(fieldName: String, optionalText: @Nls String, width: Int, height: Int): JBScrollPane { val jTextPane = JBTextArea() jTextPane.lineWrap = true jTextPane.wrapStyleWord = true jTextPane.emptyText.text = optionalText jTextPane.emptyText.setFont(JBFont.regular()) jTextPane.border = JBEmptyBorder(3, 5, 3, 5) jTextPane.font = JBFont.regular() saver.add { put(fieldName, jTextPane.text) } val scrollPane = JBScrollPane(jTextPane) scrollPane.preferredSize = Dimension(width, height) return scrollPane } fun feedbackOption(fieldName: String, text: @NlsContexts.Label String): FeedbackOption { val result = FeedbackOption(text) saver.add { put(fieldName, result.isChosen) } return result } val freeForm = feedbackTextArea("overall_experience", LearnBundle.message("onboarding.feedback.empty.text.overall.experience"), FEEDBACK_CONTENT_WIDTH, 100) val technicalIssuesArea = feedbackTextArea("other_issues", LearnBundle.message("onboarding.feedback.empty.text.other.issues"), FEEDBACK_CONTENT_WIDTH - SUB_OFFSET, 65) val technicalIssuesPanel = FormBuilder.createFormBuilder().let { builder -> builder.addComponent(feedbackOption("cannot_pass", LearnBundle.message("onboarding.feedback.option.cannot.pass.task"))) for ((id, label) in onboardingFeedbackData.possibleTechnicalIssues) { builder.addComponent(feedbackOption(id, label)) } builder.addComponent(technicalIssuesArea) builder.panel } technicalIssuesPanel.isVisible = false technicalIssuesPanel.border = JBUI.Borders.emptyLeft(SUB_OFFSET) val experiencedUserOption = feedbackOption("experienced_user", LearnBundle.message("onboarding.feedback.option.experienced.user")) val usefulPanel = FormBuilder.createFormBuilder() .addComponent(experiencedUserOption) .addComponent(feedbackOption("too_obvious", LearnBundle.message("onboarding.feedback.option.too.obvious"))) .panel usefulPanel.isVisible = false usefulPanel.border = JBUI.Borders.emptyLeft(SUB_OFFSET) val (votePanel, likenessResult) = createLikenessPanel() saver.add { "like_vote" to likenessToString(likenessResult()) } val systemInfoData = CommonFeedbackSystemInfoData.getCurrentData() val recentProjectsNumber = RecentProjectsManagerBase.instanceEx.getRecentPaths().size val actionsNumber = service<ActionsLocalSummary>().getActionsStats().keys.size val agreement = createAgreementComponent { showSystemData(project, systemInfoData, onboardingFeedbackData, recentProjectsNumber, actionsNumber) } val technicalIssuesOption = feedbackOption("technical_issues", LearnBundle.message("onboarding.feedback.option.technical.issues")) val unusefulOption = feedbackOption("useless", LearnBundle.message("onboarding.feedback.option.tour.is.useless")) val header = JLabel(LearnBundle.message("onboarding.feedback.option.form.header")).also { it.font = UISettings.instance.getFont(5).deriveFont(Font.BOLD) it.border = JBUI.Borders.empty(24 - UIUtil.DEFAULT_VGAP, 0, 20 - UIUtil.DEFAULT_VGAP, 0) } val wholePanel = FormBuilder.createFormBuilder() .addComponent(header) .addComponent(JLabel(LearnBundle.message("onboarding.feedback.question.how.did.you.like"))) .addComponent(votePanel) .addComponent(JLabel(LearnBundle.message("onboarding.feedback.question.any.problems")).also { it.border = JBUI.Borders.emptyTop(20 - UIUtil.DEFAULT_VGAP) }) .addComponent(technicalIssuesOption) .addComponent(technicalIssuesPanel) .addComponent(feedbackOption("dislike_interactive", LearnBundle.message("onboarding.feedback.option.dislike.interactive"))) .addComponent(feedbackOption("too_restrictive", LearnBundle.message("onboarding.feedback.option.too.restrictive"))) .addComponent(unusefulOption) .addComponent(usefulPanel) .addComponent(feedbackOption("very_long", LearnBundle.message("onboarding.feedback.option.too.many.steps"))) .addComponent(JLabel(LearnBundle.message("onboarding.feedback.label.overall.experience")).also { it.border = JBUI.Borders.empty(20 - UIUtil.DEFAULT_VGAP, 0, 12 - UIUtil.DEFAULT_VGAP, 0) }) .addComponent(freeForm) .addComponent(agreement.also { it.border = JBUI.Borders.emptyTop(18 - UIUtil.DEFAULT_VGAP) }) .panel val dialog = object : DialogWrapper(project) { override fun createCenterPanel(): JComponent = wholePanel init { title = LearnBundle.message("onboarding.feedback.dialog.title") setOKButtonText(LearnBundle.message("onboarding.feedback.confirm.button")) setCancelButtonText(LearnBundle.message("onboarding.feedback.reject.button")) init() } } dialog.isResizable = false installSubPanelLogic(technicalIssuesOption, technicalIssuesPanel, wholePanel, dialog) installSubPanelLogic(unusefulOption, usefulPanel, wholePanel, dialog) val maySendFeedback = dialog.showAndGet() if (maySendFeedback) { val jsonConverter = Json { } val collectedData = buildJsonObject { put(FEEDBACK_REPORT_ID_KEY, onboardingFeedbackData.feedbackReportId) put("format_version", FEEDBACK_JSON_VERSION + onboardingFeedbackData.additionalFeedbackFormatVersion) for (function in saver) { function() } put("system_info", jsonConverter.encodeToJsonElement(systemInfoData)) onboardingFeedbackData.addAdditionalSystemData.invoke(this) put("lesson_end_info", jsonConverter.encodeToJsonElement(onboardingFeedbackData.lessonEndInfo)) put("used_actions", actionsNumber) put("recent_projects", recentProjectsNumber) } val description = getShortDescription(likenessResult(), technicalIssuesOption, freeForm) submitGeneralFeedback(project, onboardingFeedbackData.reportTitle, description, onboardingFeedbackData.reportTitle, jsonConverter.encodeToString(collectedData), feedbackRequestType = getFeedbackRequestType() ) } StatisticBase.logOnboardingFeedbackDialogResult( place = getFeedbackEntryPlace(project), hasBeenSent = maySendFeedback, openedViaNotification = openedViaNotification, likenessAnswer = likenessResult(), experiencedUser = experiencedUserOption.isChosen ) return maySendFeedback } private fun getFeedbackRequestType() = when(Registry.stringValue("ift.send.onboarding.feedback")) { "production" -> FeedbackRequestType.PRODUCTION_REQUEST "staging" -> FeedbackRequestType.TEST_REQUEST else -> FeedbackRequestType.NO_REQUEST } private fun getShortDescription(likenessResult: FeedbackLikenessAnswer, technicalIssuesOption: FeedbackOption, freeForm: JBScrollPane): String { val likenessSummaryAnswer = likenessToString(likenessResult) return """ Likeness answer: $likenessSummaryAnswer Has technical problems: ${technicalIssuesOption.isChosen} Overall experience: ${(freeForm.viewport.view as? JBTextArea)?.text} """.trimIndent() } private fun likenessToString(likenessResult: FeedbackLikenessAnswer) = when (likenessResult) { FeedbackLikenessAnswer.LIKE -> "like" FeedbackLikenessAnswer.DISLIKE -> "dislike" FeedbackLikenessAnswer.NO_ANSWER -> "no answer" } private fun showSystemData(project: Project?, systemInfoData: CommonFeedbackSystemInfoData, onboardingFeedbackData: OnboardingFeedbackData?, recentProjectsNumber: Int, actionsNumber: Int) { showFeedbackSystemInfoDialog(project, systemInfoData) { if (onboardingFeedbackData != null) { onboardingFeedbackData.addRowsForUserAgreement.invoke(this) val lessonEndInfo = onboardingFeedbackData.lessonEndInfo row(LearnBundle.message("onboarding.feedback.system.recent.projects.number")) { label(recentProjectsNumber.toString()) } row(LearnBundle.message("onboarding.feedback.system.actions.used")) { label(actionsNumber.toString()) } row(LearnBundle.message("onboarding.feedback.system.lesson.completed")) { label(lessonEndInfo.lessonPassed.toString()) } row(LearnBundle.message("onboarding.feedback.system.visual.step.on.end")) { label(lessonEndInfo.currentVisualIndex.toString()) } row(LearnBundle.message("onboarding.feedback.system.technical.index.on.end")) { label(lessonEndInfo.currentTaskIndex.toString()) } } } } private fun createLikenessPanel(): Pair<NonOpaquePanel, () -> FeedbackLikenessAnswer> { val votePanel = NonOpaquePanel() val likeIcon = getLikenessIcon(FeaturesTrainerIcons.Img.Like) val dislikeIcon = getLikenessIcon(FeaturesTrainerIcons.Img.Dislike) votePanel.layout = BoxLayout(votePanel, BoxLayout.X_AXIS) val likeAnswer = FeedbackOption(likeIcon) votePanel.add(likeAnswer) val dislikeAnswer = FeedbackOption(dislikeIcon) votePanel.add(dislikeAnswer) likeAnswer.addActionListener { // the listener is triggered before the actual field change if (!likeAnswer.isChosen) { dislikeAnswer.isChosen = false dislikeAnswer.repaint() } } dislikeAnswer.addActionListener { // the listener is triggered before the actual field change if (!dislikeAnswer.isChosen) { likeAnswer.isChosen = false likeAnswer.repaint() } } val result = { when { likeAnswer.isChosen -> FeedbackLikenessAnswer.LIKE dislikeAnswer.isChosen -> FeedbackLikenessAnswer.DISLIKE else -> FeedbackLikenessAnswer.NO_ANSWER } } return votePanel to result } private fun installSubPanelLogic(feedbackOption: FeedbackOption, feedbackSubPanel: JPanel, wholePanel: JPanel, dialog: DialogWrapper) { feedbackOption.addActionListener { val needShow = !feedbackOption.isChosen if (feedbackSubPanel.isVisible == needShow) return@addActionListener val oldPreferredSize = wholePanel.preferredSize val oldSize = dialog.window.size feedbackSubPanel.isVisible = needShow val newPreferredSize = wholePanel.preferredSize dialog.window.size = Dimension(oldSize.width, oldSize.height + newPreferredSize.height - oldPreferredSize.height) } } private fun getLikenessIcon(icon: Icon): Icon { return IndentedIcon(IconUtil.scale(icon, null, 0.25f), JBUI.insets(6)) } private class FeedbackOption(@NlsContexts.Label text: String?, icon: Icon?) : JButton() { var isChosen = false constructor(@NlsContexts.Label text: String) : this(text, null) constructor(icon: Icon?) : this(null, icon) init { putClientProperty("styleTag", true) isFocusable = false action = object : AbstractAction(text, icon) { override fun actionPerformed(e: ActionEvent?) { isChosen = !isChosen } } } override fun paint(g: Graphics) { // These colors are hardcoded because there are no corresponding keys // But the feedback dialog should appear for the newcomers, and it is expected they will not significantly customize IDE at that moment val hoverBackgroundColor = JBColor(Color(0xDFDFDF), Color(0x4C5052)) val selectedBackgroundColor = JBColor(Color(0xD5D5D5), Color(0x5C6164)) val unselectedForeground = JBColor(Color(0x000000), Color(0xBBBBBB)) val selectedForeground = JBColor(Color(0x000000), Color(0xFEFEFE)) val backgroundColor = when { isChosen -> selectedBackgroundColor mousePosition != null -> hoverBackgroundColor else -> JBColor.namedColor("Panel.background", Color.WHITE) } val foregroundColor = if (isChosen) selectedForeground else unselectedForeground putClientProperty("JButton.backgroundColor", backgroundColor) foreground = foregroundColor super.paint(g) } } private fun createAgreementComponent(showSystemInfo: () -> Unit): JComponent { val htmlText = LearnBundle.message("onboarding.feedback.user.agreement") val jTextPane = JTextPane().apply { contentType = "text/html" addHyperlinkListener(object : HyperlinkAdapter() { override fun hyperlinkActivated(e: HyperlinkEvent?) { showSystemInfo() } }) editorKit = HTMLEditorKitBuilder.simple() text = htmlText val styleSheet = (document as HTMLDocument).styleSheet styleSheet.addRule("body {font-size:${JBUI.Fonts.label().lessOn(3f)}pt;}") isEditable = false } val scrollPane = JBScrollPane(jTextPane) scrollPane.preferredSize = Dimension(FEEDBACK_CONTENT_WIDTH, 100) scrollPane.border = null return scrollPane } private fun getFeedbackEntryPlace(project: Project?) = when { project == null -> FeedbackEntryPlace.WELCOME_SCREEN findLanguageSupport(project) != null -> FeedbackEntryPlace.LEARNING_PROJECT else -> FeedbackEntryPlace.ANOTHER_PROJECT }
apache-2.0
a267f4393254cd5202304089e3f7cee6
41.784461
158
0.743425
4.572998
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/main/java/io/fotoapparat/result/PendingResult.kt
1
4074
package io.fotoapparat.result import io.fotoapparat.capability.Capabilities import io.fotoapparat.concurrent.ensureBackgroundThread import io.fotoapparat.exception.UnableToDecodeBitmapException import io.fotoapparat.hardware.executeMainThread import io.fotoapparat.hardware.pendingResultExecutor import io.fotoapparat.log.Logger import io.fotoapparat.parameter.camera.CameraParameters import java.util.concurrent.* /** * Result which might not be readily available at the given moment but will be available in the * future. */ open class PendingResult<T> internal constructor( private val future: Future<T>, private val logger: Logger, private val executor: Executor ) { private val resultUnsafe: T get() { ensureBackgroundThread() return future.get() } /** * Transforms result from one type to another. * * @param transformer function which performs transformation of current result type to a new * type. * @return [PendingResult] of another type. */ fun <R> transform(transformer: (T) -> R): PendingResult<R> { val transformTask = FutureTask { transformer(future.get()) } executor.execute(transformTask) return PendingResult<R>( future = transformTask, logger = logger, executor = executor ) } /** * Blocks current thread until result is available. * * @return result of execution. * @throws ExecutionException if the result couldn't be obtained. * @throws InterruptedException if the thread has been interrupted. */ @Throws(ExecutionException::class, InterruptedException::class) fun await(): T = future.get() /** * Adapts the resulting object to a different type. * * @param adapter Function which performs transforms the current result callback to a new * type. * @return result adapted to a new type. */ fun <R> adapt(adapter: (Future<T>) -> R): R = adapter(future) /** * Notifies given callback as soon as result is available. Callback will always be notified on * a main thread. * * If the result couldn't be obtained, a null value will be returned. */ fun whenAvailable(callback: (T?) -> Unit) { executor.execute { try { val result = resultUnsafe notifyOnMainThread { callback(result) } } catch (e: UnableToDecodeBitmapException) { logger.log("Couldn't decode bitmap from byte array") notifyOnMainThread { callback(null) } } catch (e: InterruptedException) { logger.log("Couldn't deliver pending result: Camera stopped before delivering result.") } catch (e: CancellationException) { logger.log("Couldn't deliver pending result: Camera operation was cancelled.") } catch (e: ExecutionException) { logger.log("Couldn't deliver pending result: Operation failed internally.") notifyOnMainThread { callback(null) } } } } /** * Alias for [PendingResult.whenAvailable] for java. */ fun whenDone(callback: WhenDoneListener<T>) { whenAvailable(callback::whenDone) } companion object { /** * @return [PendingResult] which waits for the result of [Future]. */ internal fun <T> fromFuture( future: Future<T>, logger: Logger ): PendingResult<T> = PendingResult( future = future, logger = logger, executor = pendingResultExecutor ) } } private fun notifyOnMainThread(function: () -> Unit) { executeMainThread { function() } } typealias CapabilitiesResult = PendingResult<Capabilities> typealias ParametersResult = PendingResult<CameraParameters>
apache-2.0
8748bc830c2b6801197076d77f6c5df7
30.828125
103
0.613157
4.998773
false
false
false
false
android/compose-samples
Jetcaster/app/src/main/java/com/example/jetcaster/ui/MainActivity.kt
1
3014
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.jetcaster.ui import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.core.view.WindowCompat import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import androidx.window.layout.FoldingFeature import androidx.window.layout.WindowInfoTracker.Companion.getOrCreate import com.example.jetcaster.ui.theme.JetcasterTheme import com.example.jetcaster.util.DevicePosture import com.example.jetcaster.util.isBookPosture import com.example.jetcaster.util.isSeparatingPosture import com.example.jetcaster.util.isTableTopPosture import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // This app draws behind the system bars, so we want to handle fitting system windows WindowCompat.setDecorFitsSystemWindows(window, false) /** * Flow of [DevicePosture] that emits every time there's a change in the windowLayoutInfo */ val devicePosture = getOrCreate(this).windowLayoutInfo(this) .flowWithLifecycle(this.lifecycle) .map { layoutInfo -> val foldingFeature = layoutInfo.displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull() when { isTableTopPosture(foldingFeature) -> DevicePosture.TableTopPosture(foldingFeature.bounds) isBookPosture(foldingFeature) -> DevicePosture.BookPosture(foldingFeature.bounds) isSeparatingPosture(foldingFeature) -> DevicePosture.SeparatingPosture( foldingFeature.bounds, foldingFeature.orientation ) else -> DevicePosture.NormalPosture } } .stateIn( scope = lifecycleScope, started = SharingStarted.Eagerly, initialValue = DevicePosture.NormalPosture ) setContent { JetcasterTheme { JetcasterApp(devicePosture) } } } }
apache-2.0
9cfc4eacfc2743a1cbf75799777f65f8
38.657895
97
0.673855
5.382143
false
false
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/internal/ml/completion/CompletionRankingModelBase.kt
12
1410
// 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.internal.ml.completion import com.intellij.internal.ml.DecisionFunction import com.intellij.internal.ml.FeatureMapper import com.intellij.internal.ml.ModelMetadata abstract class CompletionRankingModelBase(private val metadata: ModelMetadata) : DecisionFunction { private val isPositionBased = metadata.checkIfPositionFeatureUsed() override fun getFeaturesOrder(): Array<FeatureMapper> { return metadata.featuresOrder } override fun version(): String? { return metadata.version } override fun getRequiredFeatures(): List<String> = emptyList() override fun getUnknownFeatures(features: Collection<String>): List<String> { if (!isPositionBased) return emptyList() var unknownFeatures: MutableList<String>? = null for (featureName in features) { if (featureName !in metadata.knownFeatures) { if (unknownFeatures == null) { unknownFeatures = mutableListOf() } unknownFeatures.add(featureName) } } return unknownFeatures ?: emptyList() } private companion object { private fun ModelMetadata.checkIfPositionFeatureUsed(): Boolean { return featuresOrder.any { it.featureName == "position" || it.featureName == "relative_position" } } } }
apache-2.0
ab379f00dc40171e03baa8b16a9613f0
32.571429
140
0.731915
4.622951
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveToSealedMatchingPackageFix.kt
1
9550
// 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.openapi.actionSystem.LangDataKeys import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.util.parentOfType import com.intellij.refactoring.PackageWrapper import com.intellij.refactoring.move.MoveCallback import com.intellij.refactoring.move.MoveHandler import org.jetbrains.kotlin.descriptors.containingPackage import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.actions.internal.refactoringTesting.cases.* import org.jetbrains.kotlin.idea.refactoring.move.getTargetPackageFqName import org.jetbrains.kotlin.idea.refactoring.move.guessNewFileName import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandler import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsHandlerActions import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.KotlinAwareMoveFilesOrDirectoriesModel import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinNestedClassesToUpperLevelModel import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.ui.MoveKotlinTopLevelDeclarationsModel import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors import org.jetbrains.kotlin.idea.util.application.executeCommand import org.jetbrains.kotlin.idea.util.projectStructure.module import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade class MoveToSealedMatchingPackageFix(element: KtTypeReference) : KotlinQuickFixAction<KtTypeReference>(element) { private val moveHandler = if (ApplicationManager.getApplication().isUnitTestMode) { MoveKotlinDeclarationsHandler(MoveKotlinDeclarationsHandlerTestActions()) } else { MoveKotlinDeclarationsHandler(false) } override fun invoke(project: Project, editor: Editor?, file: KtFile) { val typeReference = element ?: return // 'element' references sealed class/interface in extension list val classToMove = typeReference.parentOfType<KtClass>() ?: return val defaultTargetDir = typeReference.resolveToDir() ?: return val parentContext = SimpleDataContext.getProjectContext(project) val context = SimpleDataContext.getSimpleContext(LangDataKeys.TARGET_PSI_ELEMENT.name, defaultTargetDir, parentContext) moveHandler.tryToMove(classToMove, project, context, null, editor) } private fun KtTypeReference.resolveToDir(): PsiDirectory? { val ktUserType = typeElement as? KtUserType ?: return null val ktNameReferenceExpression = ktUserType.referenceExpression as? KtNameReferenceExpression ?: return null val declDescriptor = ktNameReferenceExpression.resolveMainReferenceToDescriptors().singleOrNull() ?: return null val packageName = declDescriptor.containingPackage()?.asString() ?: return null val projectFileIndex = ProjectFileIndex.getInstance(project) val ktClassInQuestion = DescriptorToSourceUtils.getSourceFromDescriptor(declDescriptor) as? KtClass ?: return null val module = projectFileIndex.getModuleForFile(ktClassInQuestion.containingFile.virtualFile) ?: return null val psiPackage = KotlinJavaPsiFacade.getInstance(project).findPackage(packageName, GlobalSearchScope.moduleScope(module)) ?: return null return psiPackage.directories.find { it.module == module } } override fun startInWriteAction(): Boolean { return false } override fun getText(): String { val typeReference = element ?: return "" val referencedName = (typeReference.typeElement as? KtUserType)?.referenceExpression?.getReferencedName() ?: return "" val classToMove = typeReference.parentOfType<KtClass>() ?: return "" return KotlinBundle.message("fix.move.to.sealed.text", classToMove.nameAsSafeName.asString(), referencedName) } override fun getFamilyName(): String { return KotlinBundle.message("fix.move.to.sealed.family") } companion object : KotlinSingleIntentionActionFactory() { override fun createAction(diagnostic: Diagnostic): MoveToSealedMatchingPackageFix? { val annotationEntry = diagnostic.psiElement as? KtTypeReference ?: return null return MoveToSealedMatchingPackageFix(annotationEntry) } } } private class MoveKotlinDeclarationsHandlerTestActions : MoveKotlinDeclarationsHandlerActions { override fun invokeMoveKotlinTopLevelDeclarationsRefactoring( project: Project, elementsToMove: Set<KtNamedDeclaration>, targetPackageName: String, targetDirectory: PsiDirectory?, targetFile: KtFile?, freezeTargets: Boolean, moveToPackage: Boolean, moveCallback: MoveCallback? ) { val sourceFiles = getSourceFiles(elementsToMove) val targetFilePath = targetFile?.virtualFile?.path ?: (sourceFiles[0].virtualFile.parent.path + "/" + guessNewFileName(elementsToMove)) val model = MoveKotlinTopLevelDeclarationsModel( project = project, elementsToMove = elementsToMove.toList(), targetPackage = targetPackageName, selectedPsiDirectory = targetDirectory, fileNameInPackage = "Derived.kt", targetFilePath = targetFilePath, isMoveToPackage = true, isSearchReferences = false, isSearchInComments = false, isSearchInNonJavaFiles = false, isDeleteEmptyFiles = false, applyMPPDeclarations = false, moveCallback = null ) model.computeModelResult(throwOnConflicts = true).processor.run() } private fun getSourceFiles(elementsToMove: Collection<KtNamedDeclaration>): List<KtFile> { return elementsToMove.map { obj: KtPureElement -> obj.containingKtFile } .distinct() } override fun invokeKotlinSelectNestedClassChooser(nestedClass: KtClassOrObject, targetContainer: PsiElement?) = doWithMoveKotlinNestedClassesToUpperLevelModel(nestedClass, targetContainer) private fun doWithMoveKotlinNestedClassesToUpperLevelModel(nestedClass: KtClassOrObject, targetContainer: PsiElement?) { val outerClass = nestedClass.containingClassOrObject ?: throw FailedToRunCaseException() val newTarget = targetContainer ?: outerClass.containingClassOrObject ?: outerClass.containingFile.let { it.containingDirectory ?: it } val packageName = getTargetPackageFqName(newTarget)?.asString() ?: "" val model = object : MoveKotlinNestedClassesToUpperLevelModel( project = nestedClass.project, innerClass = nestedClass, target = newTarget, parameter = "", className = nestedClass.name ?: "", passOuterClass = false, searchInComments = false, isSearchInNonJavaFiles = false, packageName = packageName, isOpenInEditor = false ) { override fun chooseSourceRoot( newPackage: PackageWrapper, contentSourceRoots: List<VirtualFile>, initialDir: PsiDirectory? ) = contentSourceRoots.firstOrNull() } model.computeModelResult(throwOnConflicts = true).processor.run() } override fun invokeKotlinAwareMoveFilesOrDirectoriesRefactoring( project: Project, initialDirectory: PsiDirectory?, elements: List<PsiFileSystemItem>, moveCallback: MoveCallback? ) { val targetPath = initialDirectory?.virtualFile?.path ?: elements.firstOrNull()?.containingFile?.virtualFile?.path ?: throw NotImplementedError() val model = KotlinAwareMoveFilesOrDirectoriesModel( project = project, elementsToMove = elements, targetDirectoryName = randomDirectoryPathMutator(targetPath), updatePackageDirective = randomBoolean(), searchReferences = randomBoolean(), moveCallback = null ) project.executeCommand(MoveHandler.getRefactoringName()) { model.computeModelResult().processor.run() } } override fun showErrorHint(project: Project, editor: Editor?, message: String, title: String, helpId: String?) = throw NotImplementedError() override fun invokeMoveKotlinNestedClassesRefactoring( project: Project, elementsToMove: List<KtClassOrObject>, originalClass: KtClassOrObject, targetClass: KtClassOrObject, moveCallback: MoveCallback? ) = throw NotImplementedError() }
apache-2.0
fd0457b29c9544b56b9c767ee9641437
44.480952
158
0.730471
5.681142
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/presentation/widget/graphics/RoundedTransformation.kt
1
1780
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.presentation.widget.graphics import android.graphics.* import android.graphics.Bitmap.Config import com.squareup.picasso.Transformation /** * Picassoใฎ็”ปๅƒใ‚’CircleใซใƒˆใƒชใƒŸใƒณใ‚ฐใ™ใ‚‹Transformation. */ class RoundedTransformation(private val radius: Int = 50, private val margin: Int = 0) : Transformation { override fun transform(source: Bitmap): Bitmap { val paint = Paint().apply { isAntiAlias = true shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) } val output = Bitmap.createBitmap(source.width, source.height, Config.ARGB_8888) val canvas = Canvas(output) canvas.drawRoundRect(RectF(margin.toFloat(), margin.toFloat(), (source.width - margin).toFloat(), (source.height - margin).toFloat()), 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
a7da918509bb0a4322e1c16fa64a0c8b
33.431373
112
0.655467
4.479592
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/data/source/model/Page.kt
2
1106
package eu.kanade.tachiyomi.data.source.model import eu.kanade.tachiyomi.data.network.ProgressListener import eu.kanade.tachiyomi.ui.reader.ReaderChapter import rx.subjects.Subject class Page( val pageNumber: Int, val url: String, var imageUrl: String? = null, @Transient var imagePath: String? = null ) : ProgressListener { @Transient lateinit var chapter: ReaderChapter @Transient @Volatile var status: Int = 0 set(value) { field = value statusSubject?.onNext(value) } @Transient @Volatile var progress: Int = 0 @Transient private var statusSubject: Subject<Int, Int>? = null override fun update(bytesRead: Long, contentLength: Long, done: Boolean) { progress = (100 * bytesRead / contentLength).toInt() } fun setStatusSubject(subject: Subject<Int, Int>?) { this.statusSubject = subject } companion object { const val QUEUE = 0 const val LOAD_PAGE = 1 const val DOWNLOAD_IMAGE = 2 const val READY = 3 const val ERROR = 4 } }
gpl-3.0
89c853abe70cbad5e55889851bcaa751
24.72093
78
0.641049
4.388889
false
false
false
false
siosio/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/ui/GHPRReviewThreadComponent.kt
1
11353
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.ui import com.intellij.collaboration.async.CompletableFutureUtil.handleOnEdt import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt import com.intellij.collaboration.ui.SingleValueModel import com.intellij.collaboration.ui.codereview.InlineIconButton import com.intellij.collaboration.ui.codereview.ToggleableContainer import com.intellij.icons.AllIcons import com.intellij.ide.plugins.newui.VerticalLayout import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.Project import com.intellij.ui.ClickListener import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.panels.HorizontalBox import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.scale.JBUIScale import com.intellij.util.PathUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import org.jetbrains.plugins.github.api.data.GHUser import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewCommentState import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRReviewThreadDiffComponentFactory import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRSelectInToolWindowHelper import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider import org.jetbrains.plugins.github.ui.util.GHUIUtil import java.awt.Cursor import java.awt.event.ActionListener import java.awt.event.MouseEvent import javax.swing.* object GHPRReviewThreadComponent { fun create(project: Project, thread: GHPRReviewThreadModel, reviewDataProvider: GHPRReviewDataProvider, avatarIconsProvider: GHAvatarIconsProvider, currentUser: GHUser): JComponent { val panel = JPanel(VerticalLayout(JBUIScale.scale(12))).apply { isOpaque = false } panel.add( GHPRReviewThreadCommentsPanel.create(thread, GHPRReviewCommentComponent.factory(project, reviewDataProvider, avatarIconsProvider)), VerticalLayout.FILL_HORIZONTAL) if (reviewDataProvider.canComment()) { panel.add(getThreadActionsComponent(project, reviewDataProvider, thread, avatarIconsProvider, currentUser), VerticalLayout.FILL_HORIZONTAL) } return panel } fun createWithDiff(project: Project, thread: GHPRReviewThreadModel, reviewDataProvider: GHPRReviewDataProvider, selectInToolWindowHelper: GHPRSelectInToolWindowHelper, diffComponentFactory: GHPRReviewThreadDiffComponentFactory, avatarIconsProvider: GHAvatarIconsProvider, currentUser: GHUser): JComponent { val collapseButton = InlineIconButton(AllIcons.General.CollapseComponent, AllIcons.General.CollapseComponentHover, tooltip = GithubBundle.message("pull.request.timeline.review.thread.collapse")) val expandButton = InlineIconButton(AllIcons.General.ExpandComponent, AllIcons.General.ExpandComponentHover, tooltip = GithubBundle.message("pull.request.timeline.review.thread.expand")) val panel = JPanel(VerticalLayout(JBUIScale.scale(4))).apply { isOpaque = false add(createFileName(thread, selectInToolWindowHelper, collapseButton, expandButton), VerticalLayout.FILL_HORIZONTAL) } object : CollapseController(thread, panel, collapseButton, expandButton) { override fun createThreadsPanel(): JComponent = JPanel(VerticalLayout(JBUIScale.scale(12))).apply { isOpaque = false add(diffComponentFactory.createComponent(thread.diffHunk, thread.startLine), VerticalLayout.FILL_HORIZONTAL) add(GHPRReviewThreadCommentsPanel.create(thread, GHPRReviewCommentComponent.factory(project, reviewDataProvider, avatarIconsProvider, false)), VerticalLayout.FILL_HORIZONTAL) if (reviewDataProvider.canComment()) { add(getThreadActionsComponent(project, reviewDataProvider, thread, avatarIconsProvider, currentUser), VerticalLayout.FILL_HORIZONTAL) } } } return panel } private abstract class CollapseController(private val thread: GHPRReviewThreadModel, private val panel: JPanel, private val collapseButton: InlineIconButton, private val expandButton: InlineIconButton) { private val collapseModel = SingleValueModel(true) private var threadsPanel: JComponent? = null init { collapseButton.actionListener = ActionListener { collapseModel.value = true } expandButton.actionListener = ActionListener { collapseModel.value = false } collapseModel.addListener { update() } thread.addAndInvokeStateChangeListener(::update) } private fun update() { val shouldBeVisible = !thread.isResolved || !collapseModel.value if (shouldBeVisible) { if (threadsPanel == null) { threadsPanel = createThreadsPanel() panel.add(threadsPanel!!, VerticalLayout.FILL_HORIZONTAL) panel.validate() panel.repaint() } } else { if (threadsPanel != null) { panel.remove(threadsPanel!!) panel.validate() panel.repaint() } threadsPanel = null } collapseButton.isVisible = thread.isResolved && !collapseModel.value expandButton.isVisible = thread.isResolved && collapseModel.value } protected abstract fun createThreadsPanel(): JComponent } private fun createFileName(thread: GHPRReviewThreadModel, selectInToolWindowHelper: GHPRSelectInToolWindowHelper, collapseButton: InlineIconButton, expandButton: InlineIconButton): JComponent { val name = PathUtil.getFileName(thread.filePath) val path = PathUtil.getParentPath(thread.filePath) val fileType = FileTypeRegistry.getInstance().getFileTypeByFileName(name) val nameLabel = JLabel(name, fileType.icon, SwingConstants.LEFT).apply { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) object : ClickListener() { override fun onClick(event: MouseEvent, clickCount: Int): Boolean { selectInToolWindowHelper.selectChange(thread.commit?.oid, thread.filePath) return true } }.installOn(this) } val outdatedLabel = JBLabel(" ${GithubBundle.message("pull.request.review.thread.outdated")} ", UIUtil.ComponentStyle.SMALL).apply { foreground = UIUtil.getContextHelpForeground() background = UIUtil.getPanelBackground() }.andOpaque() val resolvedLabel = JBLabel(" ${GithubBundle.message("pull.request.review.comment.resolved")} ", UIUtil.ComponentStyle.SMALL).apply { foreground = UIUtil.getContextHelpForeground() background = UIUtil.getPanelBackground() }.andOpaque() thread.addAndInvokeStateChangeListener { outdatedLabel.isVisible = thread.isOutdated resolvedLabel.isVisible = thread.isResolved } return NonOpaquePanel(MigLayout(LC().insets("0").gridGap("${JBUIScale.scale(5)}", "0").fill().noGrid())).apply { add(nameLabel) if (!path.isBlank()) add(JLabel(path).apply { foreground = UIUtil.getContextHelpForeground() }) add(outdatedLabel, CC().hideMode(3)) add(resolvedLabel, CC().hideMode(3)) add(collapseButton, CC().hideMode(3)) add(expandButton, CC().hideMode(3)) } } private fun getThreadActionsComponent( project: Project, reviewDataProvider: GHPRReviewDataProvider, thread: GHPRReviewThreadModel, avatarIconsProvider: GHAvatarIconsProvider, currentUser: GHUser ): JComponent { val toggleModel = SingleValueModel(false) val textFieldModel = GHSubmittableTextFieldModel(project) { text -> reviewDataProvider.addComment(EmptyProgressIndicator(), thread.getElementAt(0).id, text).successOnEdt { thread.addComment(GHPRReviewCommentModel.convert(it)) toggleModel.value = false } } val toggleReplyLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.reply"), null) { _, _ -> toggleModel.value = true }.apply { isFocusable = true } val resolveLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.resolve"), null).apply { isFocusable = true }.also { it.setListener({ _, _ -> it.isEnabled = false reviewDataProvider.resolveThread(EmptyProgressIndicator(), thread.id).handleOnEdt { _, _ -> it.isEnabled = true } }, null) } val unresolveLink = LinkLabel<Any>(GithubBundle.message("pull.request.review.thread.unresolve"), null).apply { isFocusable = true }.also { it.setListener({ _, _ -> it.isEnabled = false reviewDataProvider.unresolveThread(EmptyProgressIndicator(), thread.id).handleOnEdt { _, _ -> it.isEnabled = true } }, null) } val content = ToggleableContainer.create( toggleModel, { createThreadActionsComponent(thread, toggleReplyLink, resolveLink, unresolveLink) }, { GHSubmittableTextFieldFactory(textFieldModel).create(avatarIconsProvider, currentUser, GithubBundle.message( "pull.request.review.thread.reply"), onCancel = { toggleModel.value = false }) } ) return JPanel().apply { isOpaque = false layout = MigLayout(LC().insets("0")) add(content, CC().width("${GHUIUtil.getPRTimelineWidth() + JBUIScale.scale(GHUIUtil.AVATAR_SIZE)}")) } } private fun createThreadActionsComponent(model: GHPRReviewThreadModel, toggleReplyLink: LinkLabel<Any>, resolveLink: LinkLabel<Any>, unresolveLink: LinkLabel<Any>): JComponent { fun update() { resolveLink.isVisible = model.state != GHPullRequestReviewCommentState.PENDING && !model.isResolved unresolveLink.isVisible = model.state != GHPullRequestReviewCommentState.PENDING && model.isResolved } model.addAndInvokeStateChangeListener(::update) return HorizontalBox().apply { isOpaque = false border = JBUI.Borders.empty(6, 28, 6, 0) add(toggleReplyLink) add(Box.createHorizontalStrut(JBUIScale.scale(8))) add(resolveLink) add(unresolveLink) } } }
apache-2.0
dbb41ef96b722ea57b7d04808f00c7df
42.007576
142
0.684048
5.21258
false
false
false
false
jwren/intellij-community
plugins/devkit/intellij.devkit.uiDesigner/src/ConvertFormNotificationProvider.kt
4
1839
// 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.idea.devkit.uiDesigner import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiManager import com.intellij.psi.search.ProjectScope import com.intellij.ui.EditorNotificationPanel import com.intellij.ui.EditorNotifications import com.intellij.ui.LightColors import com.intellij.uiDesigner.editor.UIFormEditor import org.jetbrains.idea.devkit.util.PsiUtil class ConvertFormNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() { companion object { private val KEY = Key.create<EditorNotificationPanel>("convert.form.notification.panel") } override fun getKey(): Key<EditorNotificationPanel> = KEY override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? { if (fileEditor !is UIFormEditor) return null if (!PsiUtil.isIdeaProject(project)) return null val formPsiFile = PsiManager.getInstance(project).findFile(file) ?: return null val classToBind = fileEditor.editor.rootContainer.classToBind ?: return null val psiClass = JavaPsiFacade.getInstance(project).findClass(classToBind, ProjectScope.getProjectScope(project)) ?: return null return EditorNotificationPanel(LightColors.RED).apply { setText(DevKitUIDesignerBundle.message("convert.form.editor.notification.label")) /* todo IDEA-282478 createActionLabel(DevKitBundle.message("convert.form.editor.notification.link.convert")) { convertFormToUiDsl(psiClass, formPsiFile) } */ } } }
apache-2.0
c8339391b011b007c7ea5389a5e66b8a
42.785714
130
0.792822
4.5975
false
false
false
false
dahlstrom-g/intellij-community
python/src/com/jetbrains/python/sdk/configuration/PyProjectSdkConfiguration.kt
9
6057
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.configuration import com.intellij.ide.GeneralSettings import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.Disposable import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.Project import com.intellij.openapi.project.isNotificationSilentMode import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.jetbrains.python.PyBundle import com.jetbrains.python.PySdkBundle import com.jetbrains.python.PythonPluginDisposable import com.jetbrains.python.inspections.PyInspectionExtension import com.jetbrains.python.inspections.PyPackageRequirementsInspection import com.jetbrains.python.psi.PyFile import com.jetbrains.python.sdk.PySdkPopupFactory import com.jetbrains.python.sdk.excludeInnerVirtualEnv import com.jetbrains.python.ui.PyUiUtil object PyProjectSdkConfiguration { private val LOGGER = Logger.getInstance(PyProjectSdkConfiguration::class.java) fun configureSdkUsingExtension(module: Module, extension: PyProjectSdkConfigurationExtension, supplier: () -> Sdk?) { val lifetime = suppressTipAndInspectionsFor(module, extension) ProgressManager.getInstance().run( object : Backgroundable(module.project, PySdkBundle.message("python.configuring.interpreter.progress"), false) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true lifetime.use { setSdkUsingExtension(module, extension, supplier) } } } ) } @RequiresBackgroundThread fun setSdkUsingExtension(module: Module, extension: PyProjectSdkConfigurationExtension, supplier: () -> Sdk?) { ProgressManager.progress("") LOGGER.debug("Configuring sdk with ${extension.javaClass.canonicalName} extension") supplier()?.let { setReadyToUseSdk(module.project, module, it) } } fun setReadyToUseSdk(project: Project, module: Module, sdk: Sdk) { runInEdt { if (module.isDisposed) return@runInEdt SdkConfigurationUtil.setDirectoryProjectSdk(project, sdk) module.excludeInnerVirtualEnv(sdk) notifyAboutConfiguredSdk(project, module, sdk) } } fun suppressTipAndInspectionsFor(module: Module, extension: PyProjectSdkConfigurationExtension): Disposable { val project = module.project val lifetime = Disposer.newDisposable( PythonPluginDisposable.getInstance(project), "Configuring sdk using ${extension.javaClass.name} extension" ) TipOfTheDaySuppressor.suppress()?.let { Disposer.register(lifetime, it) } PyInterpreterInspectionSuppressor.suppress(project)?.let { Disposer.register(lifetime, it) } Disposer.register(lifetime, PyPackageRequirementsInspectionSuppressor(module)) return lifetime } private fun notifyAboutConfiguredSdk(project: Project, module: Module, sdk: Sdk) { if (isNotificationSilentMode(project)) return NotificationGroupManager.getInstance().getNotificationGroup("ConfiguredPythonInterpreter").createNotification( PyBundle.message("sdk.has.been.configured.as.the.project.interpreter", sdk.name), NotificationType.INFORMATION ).apply { val configureSdkAction = NotificationAction.createSimpleExpiring(PySdkBundle.message("python.configure.interpreter.action")) { PySdkPopupFactory.createAndShow(project, module) } addAction(configureSdkAction) notify(project) } } } private class TipOfTheDaySuppressor private constructor() : Disposable { private val savedValue: Boolean companion object { private val LOGGER = Logger.getInstance(TipOfTheDaySuppressor::class.java) fun suppress(): Disposable? { return if (!GeneralSettings.getInstance().isShowTipsOnStartup) null else TipOfTheDaySuppressor() } } init { val settings = GeneralSettings.getInstance() savedValue = settings.isShowTipsOnStartup settings.isShowTipsOnStartup = false LOGGER.info("Tip of the day has been disabled") } override fun dispose() { val settings = GeneralSettings.getInstance() if (!settings.isShowTipsOnStartup) { // nothing has been changed between init and dispose settings.isShowTipsOnStartup = savedValue LOGGER.info("Tip of the day has been enabled") } else { LOGGER.info("Tip of the day was enabled somewhere else") } } } private class PyInterpreterInspectionSuppressor : PyInspectionExtension() { companion object { private val LOGGER = Logger.getInstance(PyInterpreterInspectionSuppressor::class.java) private var suppress = false fun suppress(project: Project): Disposable? { PyUiUtil.clearFileLevelInspectionResults(project) return if (suppress) null else Suppressor() } } override fun ignoreInterpreterWarnings(file: PyFile): Boolean = suppress private class Suppressor : Disposable { init { suppress = true LOGGER.info("Interpreter warnings have been disabled") } override fun dispose() { suppress = false LOGGER.info("Interpreter warnings have been enabled") } } } private class PyPackageRequirementsInspectionSuppressor(module: Module): Disposable { private val listener = PyPackageRequirementsInspection.RunningPackagingTasksListener(module) init { listener.started() } override fun dispose() { listener.finished(emptyList()) } }
apache-2.0
11ea4b21bf8c6f8fb5ceb0b248caf9f9
34.846154
140
0.770348
4.810961
false
true
false
false