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
cdietze/klay
tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/DemoScreen.kt
1
2766
package tripleklay.demo.core import klay.core.* import tripleklay.game.ScreenStack import tripleklay.ui.* import tripleklay.ui.layout.AxisLayout /** * The base class for all demo screens. */ abstract class DemoScreen : ScreenStack.UIScreen(TripleDemo.game!!.plat) { lateinit var back: Button override fun game(): Game { return TripleDemo.game!! } override fun wasAdded() { super.wasAdded() val root = iface.createRoot( AxisLayout.vertical().gap(0).offStretch(), stylesheet(), layer) root.addStyles(Style.BACKGROUND.`is`(background()), Style.VALIGN.top) root.setSize(size()) val bg = Background.solid(0xFFCC99FF.toInt()).inset(0f, 0f, 5f, 0f) this.back = Button("Back") root.add(Group(AxisLayout.horizontal(), Style.HALIGN.left, Style.BACKGROUND.`is`(bg)).add( this.back, Label(title()).addStyles(Style.FONT.`is`(TITLE_FONT), Style.HALIGN.center).setConstraint(AxisLayout.stretched()))) if (subtitle() != null) root.add(Label(subtitle())) val iface = createIface(root) if (iface != null) root.add(iface.setConstraint(AxisLayout.stretched())) } override fun wasRemoved() { super.wasRemoved() iface.disposeRoots() layer.disposeAll() } /** The label to use on the button that displays this demo. */ abstract fun name(): String /** Returns the title of this demo. */ protected abstract fun title(): String /** Returns an explanatory subtitle for this demo, or null. */ protected fun subtitle(): String? { return null } /** Override this method and return a group that contains your main UI, or null. Note: `root` is provided for reference, the group returned by this call will automatically be * added to the root group. */ protected abstract fun createIface(root: Root): Group? /** Returns the stylesheet to use for this screen. */ protected fun stylesheet(): Stylesheet { return SimpleStyles.newSheet(game().plat.graphics) } /** Returns the background to use for this screen. */ protected fun background(): Background { return Background.bordered(0xFFCCCCCC.toInt(), 0xFFCC99FF.toInt(), 5f).inset(5f) } protected fun assets(): Assets { return game().plat.assets } protected fun graphics(): Graphics { return game().plat.graphics } protected fun input(): Input { return game().plat.input } protected fun json(): Json { return game().plat.json } protected fun log(): klay.core.Log { return game().plat.log } companion object { val TITLE_FONT = Font("Helvetica", 24f) } }
apache-2.0
176632e732db5a28e7b8639da8f5dfc2
29.733333
178
0.635213
4.171946
false
false
false
false
elpassion/el-mascarar-android-client
app/src/main/java/pl/elpassion/elmascarar/ConnectionHandler.kt
1
2271
package pl.elpassion.elmascarar import android.util.Log import com.fasterxml.jackson.databind.node.JsonNodeFactory import com.fasterxml.jackson.databind.node.ObjectNode import de.greenrobot.event.EventBus import org.phoenixframework.channels.Channel import org.phoenixframework.channels.Envelope import org.phoenixframework.channels.Socket class ConnectionHandler { companion object { val bus = EventBus.getDefault() val serverEndPoint = "ws://el-mascarar.herokuapp.com/socket/websocket" val playerIdKey = "player_id" val gameIdKey = "game_id" val lobbyChannelKey = "games:lobby" val gameChannelKey = "join:game" val okKey = "ok" } fun startThreadToObtainPlayerId(playerId: Int? = null) { try { obtainPlayerId(playerId) } catch (e: Exception) { bus.post(OnServerConnectionError(e)) } } fun startThreadToJoinGame(playerId: Int, gameId: Int) { try { joinGame(playerId, gameId) } catch (e: Exception) { bus.post(OnServerConnectionError(e)) } } private fun obtainPlayerId(playerId: Int?) { val payload = ObjectNode(JsonNodeFactory.instance) .put(playerIdKey, playerId) val socket: Socket = Socket(serverEndPoint) socket.connect() val channel: Channel = socket.chan(lobbyChannelKey, payload) channel.join() .receive(okKey, onConnectedToChannel) } private val onConnectedToChannel = { envelope: Envelope -> val playerId = envelope.payload.get(playerIdKey).intValue() val gameId = envelope.payload.get(gameIdKey).intValue() Log.e("Connected to channel with ID: ", playerId.toString()) bus.post(OnAssignedToGame(playerId, gameId)) } private fun joinGame(playerId: Int, gameId : Int) { val payload = ObjectNode(JsonNodeFactory.instance) .put(playerIdKey, playerId) .put(gameIdKey, gameId) val socket: Socket = Socket(serverEndPoint) socket.connect() val channel: Channel = socket.chan(gameChannelKey, payload) channel.join() .receive(okKey, { envelope -> }) } }
mit
30a5f93b2b0a3bdb00681b42d38fad85
31.457143
78
0.641127
4.350575
false
false
false
false
GunoH/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GrAnnotatorImpl.kt
8
2922
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.roots.FileIndexFacade import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.type.GroovyStaticTypeCheckVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic import org.jetbrains.plugins.groovy.lang.psi.util.isFake class GrAnnotatorImpl : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { val file = holder.currentAnnotationSession.file if (FileIndexFacade.getInstance(file.project).isInLibrarySource(file.virtualFile)) { return } if (element is GroovyPsiElement && !element.isFake()) { element.accept(GroovyAnnotator(holder)) if (isCompileStatic(element)) { element.accept(GroovyStaticTypeCheckVisitor(holder)) } } else if (element is PsiComment) { val text = element.getText() if (text.startsWith("/*") && !text.endsWith("*/")) { val range = element.getTextRange() holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("doc.end.expected")).range( TextRange.create(range.endOffset - 1, range.endOffset)).create() } } else { val parent = element.parent if (parent is GrMethod && element == parent.nameIdentifierGroovy) { val illegalCharacters = illegalJvmNameSymbols.findAll(parent.name).mapTo(HashSet()) { it.value } if (illegalCharacters.isNotEmpty() && !parent.isFake()) { val chars = illegalCharacters.joinToString { "'$it'" } holder.newAnnotation(HighlightSeverity.WARNING, GroovyBundle.message("illegal.method.name", chars)).create() } if (parent.returnTypeElementGroovy == null) { GroovyAnnotator.checkMethodReturnType(parent, element, holder) } } else if (parent is GrField) { if (element == parent.nameIdentifierGroovy) { val getters = parent.getters for (getter in getters) { GroovyAnnotator.checkMethodReturnType(getter, parent.nameIdentifierGroovy, holder) } val setter = parent.setter if (setter != null) { GroovyAnnotator.checkMethodReturnType(setter, parent.nameIdentifierGroovy, holder) } } } } } }
apache-2.0
caf48a8b8e30e26f10898f819dad78f0
42.61194
120
0.715948
4.474732
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/util/src/org/jetbrains/kotlin/idea/util/FileUtils.kt
7
720
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:JvmName("FileUtils") package org.jetbrains.kotlin.idea.util import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.KotlinFileType fun VirtualFile.isKotlinFileType(): Boolean = extension == KotlinFileType.EXTENSION || FileTypeRegistry.getInstance().isFileOfType(this, KotlinFileType.INSTANCE) fun VirtualFile.isJavaFileType(): Boolean = extension == JavaFileType.DEFAULT_EXTENSION || FileTypeRegistry.getInstance().isFileOfType(this, JavaFileType.INSTANCE)
apache-2.0
4492fda47d99e6559f33711779d26289
50.428571
123
0.815278
4.556962
false
false
false
false
Xyresic/Kaku
app/src/main/java/ca/fuwafuwa/kaku/Windows/CaptureWindow.kt
1
21559
package ca.fuwafuwa.kaku.Windows import android.content.Context import android.graphics.Bitmap import android.graphics.Color import android.graphics.drawable.Drawable import android.media.Image import android.util.Log import android.view.MotionEvent import android.view.View import android.view.ViewTreeObserver import android.view.WindowManager import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageView import java.io.FileOutputStream import java.io.IOException import androidx.core.content.ContextCompat import ca.fuwafuwa.kaku.* import ca.fuwafuwa.kaku.MainService import ca.fuwafuwa.kaku.Ocr.BoxParams import ca.fuwafuwa.kaku.Ocr.OcrParams import ca.fuwafuwa.kaku.Ocr.OcrRunnable import ca.fuwafuwa.kaku.Prefs import ca.fuwafuwa.kaku.R import ca.fuwafuwa.kaku.TextDirection import ca.fuwafuwa.kaku.Windows.Interfaces.WindowListener import ca.fuwafuwa.kaku.XmlParsers.CommonParser import com.googlecode.leptonica.android.* /** * Created by 0xbad1d3a5 on 4/13/2016. */ class CaptureWindow(context: Context, windowCoordinator: WindowCoordinator) : Window(context, windowCoordinator, R.layout.window_capture), WindowListener { private val mOcr: OcrRunnable private val mWindowBox: View private val mImageView: ImageView private val mFadeRepeat: Animation private val mBorderDefault: Drawable private val mBorderReady: Drawable private var mPrefs: Prefs? = null private var mThreshold: Int = 0 private var mLastDoubleTapTime: Long = 0 private val mLastDoubleTapIgnoreDelay: Long private var mInLongPress: Boolean = false private var mProcessingPreview: Boolean = false private var mProcessingOcr: Boolean = false private var mScreenshotForOcr: ScreenshotForOcr? = null private var mCommonParser: CommonParser? = null private val screenshotForOcr: ScreenshotForOcr? get() { val viewPos = IntArray(2) mWindowBox.getLocationOnScreen(viewPos) val box = BoxParams(viewPos[0], viewPos[1], params.width, params.height) try { return getReadyScreenshot(box) } catch (e: Exception) { e.printStackTrace() } return null } private inner class ScreenshotForOcr(val crop: Bitmap?, val orig: Bitmap?, val params: BoxParams?, private var mSetThreshold: Int) { private var mCropProcessed: Bitmap? = null val cachedScreenshot: Bitmap? get() { if (mCropProcessed == null) { mCropProcessed = getProcessedScreenshot(mSetThreshold) } return mCropProcessed } init { this.mCropProcessed = null } fun getProcessedScreenshot(threshold: Int): Bitmap { val pix = ReadFile.readBitmap(crop) val pix8 = Convert.convertTo8(pix) val pixT = GrayQuant.pixThresholdToBinary(pix8, threshold) val binarizedBitmap = WriteFile.writeBitmap(pixT) pix.recycle() pixT.recycle() if (mCropProcessed != null) mCropProcessed!!.recycle() mCropProcessed = binarizedBitmap mSetThreshold = threshold return binarizedBitmap } private fun kMeansClustering() { } private fun calculateFuriganaPosition(bitmap: Bitmap): Bitmap { val screen = bitmap.copy(bitmap.config, true) val screenHeight = screen.height val screenHeightHalf = (screenHeight / 2).toFloat() val screenWidth = screen.width val histogram = IntArray(screenWidth) val histogramBoost = FloatArray(screenWidth) for (x in 0 until screenWidth) { for (y in 0 until screenHeight) { val pixel = screen.getPixel(x, y) val R = pixel shr 16 and 0xff val G = pixel shr 8 and 0xff val B = pixel and 0xff if (!(R < 10 && G < 10 && B < 10)) { histogram[x]++ histogramBoost[x] += if (y.toFloat() / screenHeight < 0.5) (screenHeightHalf - y) / screenHeightHalf else -((y - screenHeightHalf) / screenHeightHalf) } } } // Calculate boost var boostTotal = 0f var boostAvg = 0f var boostMax = 0f // Find highest boost value for (x in 0 until screenWidth) { if (histogramBoost[x] > boostMax) boostMax = histogramBoost[x] } // Stretch boost by itself (higher boosts will be even higher), and normalize all boost values by boostMax for (x in 0 until screenWidth) { histogramBoost[x] = histogramBoost[x] * histogramBoost[x] / boostMax } // Find highest boost value for (x in 0 until screenWidth) { if (histogramBoost[x] > boostMax) boostMax = histogramBoost[x] } // Normalize all boost values by boostMax again for (x in 0 until screenWidth) { histogramBoost[x] = histogramBoost[x] / boostMax boostTotal += histogramBoost[x] } boostAvg = boostTotal / screenWidth // Calculate histogram average excluding white columns var averageTotal = 0 var averageNonZero = 0 for (i in histogram.indices) { if (histogram[i] != 0) { averageTotal += histogram[i] averageNonZero++ } } val avg = if (averageNonZero == 0) screenHeight else averageTotal / averageNonZero var avgLine = screenHeight - (screenHeight - avg) val maxBoostTimes = screenHeight - avg avgLine = if (avgLine >= screenHeight) screenHeight - 1 else avgLine // Draw histogram for (x in 0 until screenWidth) { if (histogram[x] == 0) { continue } var y: Int y = screenHeight - 1 while (y >= screenHeight - (screenHeight - histogram[x])) { screen.setPixel(x, y, screen.getPixel(x, y) and -0x3738) y-- } if (histogramBoost[x] > 0) { val timesToBoost = (histogramBoost[x] * screenHeight).toInt() for (i in 0 until timesToBoost) { if (y > 0) { screen.setPixel(x, y, screen.getPixel(x, y) and -0x373701) y-- } } } if (histogram[x] != screenHeight) { while (y > 0) { screen.setPixel(x, y, screen.getPixel(x, y) and -0x373738) y-- } } } // Draw average histogram line val avgLineM = if (avgLine - 1 < 0) 0 else avgLine - 1 val avgLineP = if (avgLine + 1 > screenHeight - 1) screenHeight - 1 else avgLine + 1 for (x in 0 until screenWidth) { screen.setPixel(x, avgLineM, Color.GREEN) screen.setPixel(x, avgLine, Color.GREEN) screen.setPixel(x, avgLineP, Color.GREEN) } return screen } } init { show() this.mCommonParser = CommonParser(context) mImageView = window.findViewById(R.id.capture_image) mFadeRepeat = AnimationUtils.loadAnimation(this.context, R.anim.fade_repeat) mBorderDefault = this.context.resources.getDrawable(R.drawable.bg_translucent_border_0_blue_blue, null) mBorderReady = this.context.resources.getDrawable(R.drawable.bg_transparent_border_0_nil_ready, null) mThreshold = 128 mLastDoubleTapTime = System.currentTimeMillis() mLastDoubleTapIgnoreDelay = 500 mInLongPress = false mProcessingPreview = false mProcessingOcr = false mScreenshotForOcr = null mPrefs = getPrefs(context) mOcr = OcrRunnable(this.context, this) val tessThread = Thread(mOcr) tessThread.name = String.format("TessThread%d", System.nanoTime()) tessThread.isDaemon = true tessThread.start() windowManager.defaultDisplay.rotation // Need to wait for the view to finish updating before we try to determine it's location mWindowBox = window.findViewById(R.id.capture_box) mWindowBox.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { (context as MainService).onCaptureWindowFinishedInitializing() mWindowBox.viewTreeObserver.removeOnGlobalLayoutListener(this) } }) //windowCoordinator.getWindow(Constants.WINDOW_HISTORY).show(); } override fun reInit(options: Window.ReinitOptions) { mPrefs = getPrefs(context) super.reInit(options) } override fun onDoubleTap(e: MotionEvent): Boolean { mLastDoubleTapTime = System.currentTimeMillis() performOcr(false) // mCommonParser!!.parseJmDict() return true } override fun onTouch(e: MotionEvent): Boolean { hideInstantWindows() if (!mInLongPress && !mProcessingOcr) { mImageView.setImageResource(0) setBorderStyle(e) } when (e.action) { MotionEvent.ACTION_MOVE -> { if (System.currentTimeMillis() > mLastDoubleTapTime + mLastDoubleTapIgnoreDelay) { mOcr.cancel() } if (mInLongPress && mPrefs!!.imageFilterSetting) { setPreviewImageForThreshold(e) } } } return super.onTouch(e) } override fun onLongPress(e: MotionEvent) { Log.d(TAG, "onLongPress") mInLongPress = true setPreviewImageForThreshold(e) } override fun onResize(e: MotionEvent): Boolean { hideInstantWindows() mOcr.cancel() mImageView.setImageResource(0) setBorderStyle(e) return super.onResize(e) } override fun onUp(e: MotionEvent): Boolean { Log.d(TAG, String.format("onUp - mImageFilterSetting: %b | mInLongPress: %b | mProcessingPreview: %b | mProcessingOcr: %b", mPrefs!!.imageFilterSetting, mInLongPress, mProcessingPreview, mProcessingOcr)) if (!mInLongPress && !mProcessingPreview && !mProcessingOcr) { Log.d(TAG, "onUp - SetPreviewImage") setBorderStyle(e) mProcessingPreview = true setCroppedScreenshot() } mInLongPress = false return true } override fun stop() { mOcr.stop() //windowCoordinator.getWindow(Constants.WINDOW_HISTORY).hide(); super.stop() } fun showLoadingAnimation() { (context as MainService).handler.post { Log.d(TAG, "showLoadingAnimation") mWindowBox.background = mBorderDefault mImageView.imageAlpha = 0 mWindowBox.animation = mFadeRepeat mWindowBox.startAnimation(mFadeRepeat) } } fun stopLoadingAnimation(instant: Boolean) { (context as MainService).handler.post { mProcessingOcr = false mWindowBox.background = mBorderReady mWindowBox.clearAnimation() Log.d(TAG, "stopLoadingAnimation - instant: $instant") if (instant) { mImageView.imageAlpha = 255 } else { mImageView.imageAlpha = 255 mImageView.setImageResource(0) mScreenshotForOcr = null } } } fun hideInstantWindows() { windowCoordinator.getWindow(WINDOW_INSTANT_KANJI).hide() } override fun getDefaultParams(): WindowManager.LayoutParams { val params = super.getDefaultParams() params.x = realDisplaySize.x / 2 - params.width / 2 params.y = realDisplaySize.y / 4 - params.height / 2 params.alpha = 0.8F return params } private fun setPreviewImageForThreshold(e: MotionEvent) { if (mPrefs!!.imageFilterSetting && mScreenshotForOcr != null) { mThreshold = (e.rawX / realDisplaySize.x * 255).toInt() val bitmap = mScreenshotForOcr!!.getProcessedScreenshot(mThreshold) mImageView.setImageBitmap(bitmap) } } private fun setCroppedScreenshot() { val thread = Thread(Runnable { val ocrScreenshot = screenshotForOcr if (ocrScreenshot == null || ocrScreenshot.crop == null || ocrScreenshot.orig == null || ocrScreenshot.params == null) { mProcessingPreview = false return@Runnable } // Generate a cached screenshot in worker thread before setting it in the UI thread ocrScreenshot.cachedScreenshot (context as MainService).handler.post { mScreenshotForOcr = ocrScreenshot if (mPrefs!!.imageFilterSetting) { mImageView.setImageBitmap(mScreenshotForOcr!!.cachedScreenshot) } if (mPrefs!!.instantModeSetting && System.currentTimeMillis() > mLastDoubleTapTime + mLastDoubleTapIgnoreDelay) { val sizeForInstant = minSize * 3 if (sizeForInstant >= mScreenshotForOcr!!.params!!.width || sizeForInstant >= mScreenshotForOcr!!.params!!.height) { performOcr(true) } } mProcessingPreview = false } }) thread.start() } private fun setBorderStyle(e: MotionEvent) { when (e.action) { MotionEvent.ACTION_DOWN -> mWindowBox.background = mBorderDefault MotionEvent.ACTION_UP -> mWindowBox.background = mBorderReady } } private fun performOcr(instant: Boolean) { mProcessingOcr = true try { if (!instant) { while (!mOcr.isReadyForOcr) { mOcr.cancel() Thread.sleep(10) } } if (mScreenshotForOcr == null) { mProcessingOcr = false return } val processedImage = if (mPrefs!!.imageFilterSetting) mScreenshotForOcr!!.cachedScreenshot else mScreenshotForOcr!!.crop var textDirection = mPrefs!!.textDirectionSetting if (textDirection === TextDirection.AUTO) { textDirection = if (mScreenshotForOcr!!.params!!.width >= mScreenshotForOcr!!.params!!.height) TextDirection.HORIZONTAL else TextDirection.VERTICAL } mOcr.runTess(OcrParams(processedImage!!, mScreenshotForOcr!!.crop!!, mScreenshotForOcr!!.params!!, textDirection, instant)) } catch (e: Exception) { e.printStackTrace() } } @Throws(Exception::class) private fun getReadyScreenshot(box: BoxParams): ScreenshotForOcr? { Log.d(TAG, String.format("X:%d Y:%d (%dx%d)", box.x, box.y, box.width, box.height)) var screenshotReady: Boolean val startTime = System.currentTimeMillis() var screenshot: Bitmap do { val rawScreenshot = (context as MainService).screenshot if (rawScreenshot == null) { Log.d(TAG, "getReadyScreenshot - rawScreenshot null") return null } screenshot = convertImageToBitmap(rawScreenshot) screenshotReady = checkScreenshotIsReady(screenshot, box) val viewPos = IntArray(2) mWindowBox.getLocationOnScreen(viewPos) box.x = viewPos[0] box.y = viewPos[1] box.width = params.width box.height = params.height } while (!screenshotReady && System.currentTimeMillis() < startTime + 2000) val croppedBitmap = getCroppedBitmap(screenshot, box) //saveBitmap(screenshot, String.format("debug_(%d,%d)_(%d,%d)", box.x, box.y, box.width, box.height)); if (!screenshotReady) { saveBitmap(screenshot, String.format("error_(%d,%d)_(%d,%d)", box.x, box.y, box.width, box.height)) saveBitmap(croppedBitmap, String.format("error_(%d,%d)_(%d,%d)", box.x, box.y, box.width, box.height)) return null } return ScreenshotForOcr(croppedBitmap, screenshot, box, mThreshold) } private fun checkScreenshotIsReady(screenshot: Bitmap, box: BoxParams): Boolean { var readyColor = ContextCompat.getColor(context, R.color.red_capture_window_ready) val screenshotColor = screenshot.getPixel(box.x, box.y) if (readyColor != screenshotColor && isAcceptableAlternateReadyColor(screenshotColor)) { readyColor = screenshotColor } for (x in box.x until box.x + box.width) { if (!isRGBWithinTolerance(readyColor, screenshot.getPixel(x, box.y))) { return false } } for (x in box.x until box.x + box.width) { if (!isRGBWithinTolerance(readyColor, screenshot.getPixel(x, box.y + box.height - 1))) { return false } } for (y in box.y until box.y + box.height) { if (!isRGBWithinTolerance(readyColor, screenshot.getPixel(box.x, y))) { return false } } for (y in box.y until box.y + box.height) { if (!isRGBWithinTolerance(readyColor, screenshot.getPixel(box.x + box.width - 1, y))) { return false } } return true } /** * Looks like sometimes the screenshot just has a color that is 100% totally wrong. Let's just accept any red that's "red enough" * @param screenshotColor * @return */ private fun isAcceptableAlternateReadyColor(screenshotColor: Int): Boolean { val R = screenshotColor shr 16 and 0xFF val G = screenshotColor shr 8 and 0xFF val B = screenshotColor and 0xFF var isValid = true if (G * 10 > R) { isValid = false } if (B * 10 > R) { isValid = false } return isValid } private fun isRGBWithinTolerance(color: Int, colorToCheck: Int): Boolean { val redRatio = (colorToCheck shr 16 and 0xFF) / 3; var isColorWithinTolerance: Boolean = ((colorToCheck and 0xFF) < redRatio) isColorWithinTolerance = isColorWithinTolerance and ((colorToCheck shr 8 and 0xFF) < redRatio) isColorWithinTolerance = isColorWithinTolerance and ((colorToCheck shr 16 and 0xFF) > 140) // Log.d("RGB", "R: ${colorToCheck shr 16 and 0xFF} G: ${colorToCheck shr 8 and 0xFF}B: ${colorToCheck and 0xFF}") return isColorWithinTolerance } @Throws(OutOfMemoryError::class) private fun convertImageToBitmap(image: Image): Bitmap { val planes = image.planes val buffer = planes[0].buffer val pixelStride = planes[0].pixelStride val rowStride = planes[0].rowStride val rowPadding = rowStride - pixelStride * image.width val bitmap = Bitmap.createBitmap(image.width + rowPadding / pixelStride, image.height, Bitmap.Config.ARGB_8888) bitmap.copyPixelsFromBuffer(buffer) image.close() return bitmap } private fun getCroppedBitmap(screenshot: Bitmap, box: BoxParams): Bitmap { val borderSize = dpToPx(context, 1) + 1 // +1 due to rounding errors return Bitmap.createBitmap(screenshot, box.x + borderSize, box.y + borderSize, box.width - 2 * borderSize, box.height - 2 * borderSize) } @Throws(IOException::class) private fun saveBitmap(bitmap: Bitmap, name: String) { val fs = String.format("%s/%s/%s_%d.png", context.filesDir.absolutePath, SCREENSHOT_FOLDER_NAME, name, System.nanoTime()) Log.d(TAG, fs) val fos = FileOutputStream(fs) bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos) fos.close() } companion object { private val TAG = CaptureWindow::class.java.name } }
bsd-3-clause
98797cd52cf01928edfba76b518eac10
30.797935
211
0.567837
4.718538
false
false
false
false
bjansen/pebble-intellij
src/main/kotlin/com/github/bjansen/intellij/pebble/psi/ExpressionTypeVisitor.kt
1
2476
package com.github.bjansen.intellij.pebble.psi import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.rules import com.github.bjansen.intellij.pebble.psi.PebbleParserDefinition.Companion.tokens import com.github.bjansen.intellij.pebble.psi.PebbleReferencesHelper.findMembersByName import com.github.bjansen.pebble.parser.PebbleLexer import com.github.bjansen.pebble.parser.PebbleParser import com.intellij.psi.* class ExpressionTypeVisitor : PsiRecursiveElementVisitor(false) { var type: PsiType? = null override fun visitElement(element: PsiElement) { if (element.node.elementType == rules[PebbleParser.RULE_qualified_expression]) { type = typeOfQualifiedExpression(element) } if (element is PebbleIdentifier) { type = typeOfIdentifier(element) return } super.visitElement(element) } private fun typeOfIdentifier(element: PebbleIdentifier): PsiType? { return typeOf(element.reference?.resolve()) } private fun typeOfQualifiedExpression(element: PsiElement): PsiType? { var qualifierType:PsiType? = null for (child in element.children) { if (qualifierType == null) {// leftmost qualifier qualifierType = if (child is PebbleIdentifier) { typeOfIdentifier(child) } else { typeOfIdentifier(child.firstChild as PebbleIdentifier) } } else if (child.node.elementType == tokens[PebbleLexer.OP_MEMBER]) { continue } else { if (qualifierType is PsiClassType) { val candidates = findMembersByName(qualifierType.resolve(), if (child is PebbleIdentifier) child.text else child.firstChild.text) qualifierType = typeOf(candidates.firstOrNull()) } } if (qualifierType == null) { break // We can't possibly determine the type of what's after the current child } } return qualifierType } private fun typeOf(element: PsiElement?): PsiType? { if (element is PebbleComment) { return PebbleComment.getImplicitVariable(element)?.type } else if (element is PsiMethod) { return element.returnType } else if (element is PsiVariable) { return element.type } return null } }
mit
fcee675307472831bced9e0788ce8763
35.411765
149
0.63853
5.115702
false
false
false
false
smmribeiro/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EclipseModuleRootsSerializer.kt
2
33568
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.eclipse.config import com.intellij.configurationStore.StorageManagerFileWriteRequestor import com.intellij.configurationStore.getOrCreateVirtualFile import com.intellij.configurationStore.runAsWriteActionIfNeeded import com.intellij.openapi.application.WriteAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.module.ModuleTypeManager import com.intellij.openapi.roots.OrderRootType import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.Function import com.intellij.util.io.exists import com.intellij.util.text.UniqueNameGenerator import com.intellij.workspaceModel.ide.JpsFileEntitySource import com.intellij.workspaceModel.ide.impl.jps.serialization.* import com.intellij.workspaceModel.ide.toPath import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.WorkspaceEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder import com.intellij.workspaceModel.storage.bridgeEntities.* import com.intellij.workspaceModel.storage.url.VirtualFileUrl import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jdom.Element import org.jdom.output.EclipseJDOMUtil import org.jetbrains.idea.eclipse.AbstractEclipseClasspathReader import org.jetbrains.idea.eclipse.AbstractEclipseClasspathReader.expandLinkedResourcesPath import org.jetbrains.idea.eclipse.EclipseXml import org.jetbrains.idea.eclipse.IdeaXml import org.jetbrains.idea.eclipse.conversion.DotProjectFileHelper import org.jetbrains.idea.eclipse.conversion.EJavadocUtil import org.jetbrains.idea.eclipse.conversion.EclipseClasspathReader import org.jetbrains.idea.eclipse.conversion.EclipseClasspathWriter import org.jetbrains.idea.eclipse.conversion.EclipseClasspathWriter.addOrderEntry import org.jetbrains.idea.eclipse.importWizard.EclipseNatureImporter import org.jetbrains.jps.eclipse.model.JpsEclipseClasspathSerializer import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID import org.jetbrains.jps.util.JpsPathUtil import java.io.IOException import java.io.OutputStreamWriter import java.nio.charset.StandardCharsets import java.nio.file.Path import java.nio.file.Paths /** * Implements loading and saving module configuration from workspace model in '.classpath' file */ class EclipseModuleRootsSerializer : CustomModuleRootsSerializer, StorageManagerFileWriteRequestor { override val id: String get() = JpsEclipseClasspathSerializer.CLASSPATH_STORAGE_ID companion object { private val LOG = logger<EclipseModuleRootsSerializer>() internal val JAVADOC_TYPE: LibraryRootTypeId = LibraryRootTypeId("JAVADOC") internal val NATIVE_TYPE: LibraryRootTypeId = LibraryRootTypeId("NATIVE") } override fun createEntitySource(imlFileUrl: VirtualFileUrl, internalEntitySource: JpsFileEntitySource, customDir: String?, virtualFileManager: VirtualFileUrlManager): EntitySource? { val storageRootUrl = getStorageRoot(imlFileUrl, customDir, virtualFileManager) val classpathUrl = storageRootUrl.append(EclipseXml.CLASSPATH_FILE) return EclipseProjectFile(classpathUrl, internalEntitySource) } override fun loadRoots(builder: WorkspaceEntityStorageBuilder, originalModuleEntity: ModuleEntity, reader: JpsFileContentReader, customDir: String?, imlFileUrl: VirtualFileUrl, internalModuleListSerializer: JpsModuleListSerializer?, errorReporter: ErrorReporter, virtualFileManager: VirtualFileUrlManager) { var moduleEntity = originalModuleEntity val storageRootUrl = getStorageRoot(imlFileUrl, customDir, virtualFileManager) val entitySource = moduleEntity.entitySource as EclipseProjectFile val contentRootEntity = builder.addContentRootEntity(storageRootUrl, emptyList(), emptyList(), moduleEntity) val classpathTag = reader.loadComponent(entitySource.classpathFile.url, "", null) if (classpathTag != null) { val relativePathResolver = ModuleRelativePathResolver(internalModuleListSerializer, reader, virtualFileManager) moduleEntity = loadClasspathTags(classpathTag, builder, contentRootEntity, storageRootUrl, reader, relativePathResolver, errorReporter, imlFileUrl, virtualFileManager) } else { builder.addJavaModuleSettingsEntity(false, true, storageRootUrl.append("bin"), null, null, moduleEntity, entitySource) } val emlUrl = getEmlFileUrl(imlFileUrl) val emlTag = reader.loadComponent(emlUrl, "", null) if (emlTag != null) { reader.getExpandMacroMap(imlFileUrl.url).substitute(emlTag, SystemInfo.isFileSystemCaseSensitive) EmlFileLoader(moduleEntity, builder, reader.getExpandMacroMap(emlUrl), virtualFileManager).loadEml(emlTag, contentRootEntity) } else { val javaSettings = moduleEntity.javaSettings if (javaSettings != null) { builder.modifyEntity(ModifiableJavaModuleSettingsEntity::class.java, javaSettings) { excludeOutput = false } } else { builder.addJavaModuleSettingsEntity(true, false, null, null, null, moduleEntity, entitySource) } } } private fun getEmlFileUrl(imlFileUrl: VirtualFileUrl) = imlFileUrl.url.removeSuffix(".iml") + EclipseXml.IDEA_SETTINGS_POSTFIX private fun loadClasspathTags(classpathTag: Element, builder: WorkspaceEntityStorageBuilder, contentRootEntity: ContentRootEntity, storageRootUrl: VirtualFileUrl, reader: JpsFileContentReader, relativePathResolver: ModuleRelativePathResolver, errorReporter: ErrorReporter, imlFileUrl: VirtualFileUrl, virtualUrlManager: VirtualFileUrlManager): ModuleEntity { fun reportError(message: String) { errorReporter.reportError(message, storageRootUrl.append(EclipseXml.CLASSPATH_FILE)) } fun getUrlByRelativePath(path: String): VirtualFileUrl { return if (path.isEmpty()) storageRootUrl else storageRootUrl.append(FileUtil.toSystemIndependentName(path)) } val moduleEntity = contentRootEntity.module fun editEclipseProperties(action: (ModifiableEclipseProjectPropertiesEntity) -> Unit) { val eclipseProperties = moduleEntity.eclipseProperties ?: builder.addEclipseProjectPropertiesEntity(moduleEntity, moduleEntity.entitySource) builder.modifyEntity(ModifiableEclipseProjectPropertiesEntity::class.java, eclipseProperties) { action(this) } } val storageRootPath = JpsPathUtil.urlToPath(storageRootUrl.url) val libraryNames = HashSet<String>() val expandMacroMap = reader.getExpandMacroMap(imlFileUrl.url) val sourceRoots = mutableListOf<VirtualFileUrl>() val dependencies = ArrayList<ModuleDependencyItem>() dependencies.add(ModuleDependencyItem.ModuleSourceDependency) classpathTag.getChildren(EclipseXml.CLASSPATHENTRY_TAG).forEachIndexed { index, entryTag -> val kind = entryTag.getAttributeValue(EclipseXml.KIND_ATTR) if (kind == null) { reportError("'${EclipseXml.KIND_ATTR}' attribute is missing in '${EclipseXml.CLASSPATHENTRY_TAG}' tag") return@forEachIndexed } val path = entryTag.getAttributeValue(EclipseXml.PATH_ATTR) if (path == null) { reportError("'${EclipseXml.PATH_ATTR}' attribute is missing in '${EclipseXml.CLASSPATHENTRY_TAG}' tag") return@forEachIndexed } val exported = EclipseXml.TRUE_VALUE == entryTag.getAttributeValue(EclipseXml.EXPORTED_ATTR) when (kind) { EclipseXml.SRC_KIND -> { if (path.startsWith("/")) { dependencies.add(ModuleDependencyItem.Exportable.ModuleDependency(ModuleId(path.removePrefix("/")), exported, ModuleDependencyItem.DependencyScope.COMPILE, false)) } else { val linkedPath = expandLinkedResourcesPath(storageRootPath, expandMacroMap, path) val srcUrl: VirtualFileUrl val sourceRoot = if (linkedPath == null) { srcUrl = getUrlByRelativePath(path) builder.addSourceRootEntity(contentRootEntity, srcUrl, JAVA_SOURCE_ROOT_TYPE_ID, contentRootEntity.entitySource) } else { srcUrl = convertToRootUrl(linkedPath, virtualUrlManager) editEclipseProperties { it.setVariable(EclipseModuleManagerImpl.SRC_LINK_PREFIX, path, srcUrl.url) } val newContentRoot = moduleEntity.contentRoots.firstOrNull { it.url == srcUrl } ?: builder.addContentRootEntity(srcUrl, emptyList(), emptyList(), moduleEntity) builder.addSourceRootEntity(newContentRoot, srcUrl, JAVA_SOURCE_ROOT_TYPE_ID, newContentRoot.entitySource) } builder.addJavaSourceRootEntity(sourceRoot, false, "") sourceRoots.add(sourceRoot.url) dependencies.removeIf { it is ModuleDependencyItem.ModuleSourceDependency } dependencies.add(ModuleDependencyItem.ModuleSourceDependency) editEclipseProperties { it.expectedModuleSourcePlace = dependencies.size - 1 it.srcPlace[srcUrl.url] = index } } } EclipseXml.OUTPUT_KIND -> { val linked = expandLinkedResourcesPath(storageRootPath, expandMacroMap, path) val outputUrl: VirtualFileUrl if (linked != null) { outputUrl = virtualUrlManager.fromUrl(pathToUrl(linked)) editEclipseProperties { it.setVariable(EclipseModuleManagerImpl.LINK_PREFIX, path, outputUrl.url) } } else { outputUrl = getUrlByRelativePath(path) } builder.addJavaModuleSettingsEntity(false, true, outputUrl, null, null, moduleEntity, contentRootEntity.entitySource) } EclipseXml.LIB_KIND -> { val linked = expandLinkedResourcesPath(storageRootPath, expandMacroMap, path) val url: VirtualFileUrl if (linked != null) { url = convertToRootUrl(linked, virtualUrlManager) editEclipseProperties { it.setVariable(EclipseModuleManagerImpl.LINK_PREFIX, path, url.url) } } else { url = convertRelativePathToUrl(path, contentRootEntity, relativePathResolver, virtualUrlManager) } editEclipseProperties { it.eclipseUrls.add(url) } val sourcePath = entryTag.getAttributeValue(EclipseXml.SOURCEPATH_ATTR) val srcUrl: VirtualFileUrl? if (sourcePath != null) { val linkedSrc = expandLinkedResourcesPath(storageRootPath, expandMacroMap, sourcePath) if (linkedSrc != null) { srcUrl = convertToRootUrl(linkedSrc, virtualUrlManager) editEclipseProperties { it.setVariable(EclipseModuleManagerImpl.SRC_LINK_PREFIX, path, srcUrl.url) } } else { srcUrl = convertRelativePathToUrl(sourcePath, contentRootEntity, relativePathResolver, virtualUrlManager) } } else { srcUrl = null } val nativeRoot = AbstractEclipseClasspathReader.getNativeLibraryRoot(entryTag)?.let { convertRelativePathToUrl(it, contentRootEntity, relativePathResolver, virtualUrlManager) } val name = generateUniqueLibraryName(path, libraryNames) val roots = createLibraryRoots(url, srcUrl, nativeRoot, entryTag, moduleEntity, relativePathResolver, virtualUrlManager) val libraryEntity = builder.addLibraryEntity(name, LibraryTableId.ModuleLibraryTableId(moduleEntity.persistentId()), roots, emptyList(), contentRootEntity.entitySource) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryEntity.persistentId(), exported, ModuleDependencyItem.DependencyScope.COMPILE)) } EclipseXml.VAR_KIND -> { val slash = path.indexOf('/') if (slash == 0) { reportError("'${EclipseXml.PATH_ATTR}' attribute format is incorrect for '${EclipseXml.VAR_KIND}': $path") return@forEachIndexed } val libName = generateUniqueLibraryName(path, libraryNames) val url = convertVariablePathToUrl(expandMacroMap, path, 0, virtualUrlManager) editEclipseProperties { it.setVariable("", path, url.url) } val srcPath = entryTag.getAttributeValue(EclipseXml.SOURCEPATH_ATTR) val srcUrl: VirtualFileUrl? if (srcPath != null) { srcUrl = convertVariablePathToUrl(expandMacroMap, srcPath, AbstractEclipseClasspathReader.srcVarStart(srcPath), virtualUrlManager) editEclipseProperties { it.setVariable(EclipseModuleManagerImpl.SRC_PREFIX, srcPath, srcUrl.url) } } else { srcUrl = null } val nativeRoot = AbstractEclipseClasspathReader.getNativeLibraryRoot(entryTag)?.let { convertRelativePathToUrl(it, contentRootEntity, relativePathResolver, virtualUrlManager) } val roots = createLibraryRoots(url, srcUrl, nativeRoot, entryTag, moduleEntity, relativePathResolver, virtualUrlManager) val libraryEntity = builder.addLibraryEntity(libName, LibraryTableId.ModuleLibraryTableId(moduleEntity.persistentId()), roots, emptyList(), contentRootEntity.entitySource) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryEntity.persistentId(), exported, ModuleDependencyItem.DependencyScope.COMPILE)) } EclipseXml.CON_KIND -> { if (path == EclipseXml.ECLIPSE_PLATFORM) { val libraryId = LibraryId(IdeaXml.ECLIPSE_LIBRARY, LibraryTableId.GlobalLibraryTableId(LibraryTablesRegistrar.APPLICATION_LEVEL)) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryId, exported, ModuleDependencyItem.DependencyScope.COMPILE)) } else if (path.startsWith(EclipseXml.JRE_CONTAINER)) { val jdkName = AbstractEclipseClasspathReader.getLastPathComponent(path) dependencies.removeIf { it is ModuleDependencyItem.SdkDependency || it == ModuleDependencyItem.InheritedSdkDependency } dependencies.add(if (jdkName != null) ModuleDependencyItem.SdkDependency(jdkName, IdeaXml.JAVA_SDK_TYPE) else ModuleDependencyItem.InheritedSdkDependency) } else if (path.startsWith(EclipseXml.USER_LIBRARY)) { val libraryName = AbstractEclipseClasspathReader.getPresentableName(path) val globalLevel = findGlobalLibraryLevel(libraryName) val tableId = if (globalLevel != null) LibraryTableId.GlobalLibraryTableId(globalLevel) else LibraryTableId.ProjectLibraryTableId val libraryId = LibraryId(libraryName, tableId) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryId, exported, ModuleDependencyItem.DependencyScope.COMPILE)) } else if (path.startsWith(EclipseXml.JUNIT_CONTAINER)) { val junitName = IdeaXml.JUNIT + AbstractEclipseClasspathReader.getPresentableName(path) val url = EclipseClasspathReader.getJunitClsUrl(junitName.contains("4")) val roots = listOf(LibraryRoot(virtualUrlManager.fromUrl(url), LibraryRootTypeId.COMPILED)) val libraryEntity = builder.addLibraryEntity(junitName, LibraryTableId.ModuleLibraryTableId(moduleEntity.persistentId()), roots, emptyList(), contentRootEntity.entitySource) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryEntity.persistentId(), exported, ModuleDependencyItem.DependencyScope.COMPILE)) } else { val definedCons = EclipseNatureImporter.getAllDefinedCons() if (path in definedCons) { editEclipseProperties { it.knownCons.add(path) it.srcPlace[path] = index } } else { editEclipseProperties { it.unknownCons.add(path) } val libraryId = LibraryId(path, LibraryTableId.GlobalLibraryTableId(LibraryTablesRegistrar.APPLICATION_LEVEL)) dependencies.add(ModuleDependencyItem.Exportable.LibraryDependency(libraryId, exported, ModuleDependencyItem.DependencyScope.COMPILE)) } } } else -> { reportError("Unknown '${EclipseXml.KIND_ATTR}' in '${EclipseXml.CLASSPATHENTRY_TAG}': $kind") } } } if (dependencies.none { it is ModuleDependencyItem.SdkDependency || it == ModuleDependencyItem.InheritedSdkDependency }) { editEclipseProperties { it.forceConfigureJdk = true it.expectedModuleSourcePlace++ } dependencies.add(0, ModuleDependencyItem.InheritedSdkDependency) } storeSourceRootsOrder(sourceRoots, contentRootEntity, builder) return builder.modifyEntity(ModifiableModuleEntity::class.java, moduleEntity) { this.dependencies = dependencies } } private fun findGlobalLibraryLevel(libraryName: String): String? { val registrar = LibraryTablesRegistrar.getInstance() if (registrar.libraryTable.getLibraryByName(libraryName) != null) return LibraryTablesRegistrar.APPLICATION_LEVEL return registrar.customLibraryTables.find { it.getLibraryByName(libraryName) != null }?.tableLevel } private fun generateUniqueLibraryName(path: String, libraryNames: MutableSet<String>): String { val pathComponent = AbstractEclipseClasspathReader.getLastPathComponent(path) if (pathComponent != null && libraryNames.add(pathComponent)) return pathComponent val name = UniqueNameGenerator.generateUniqueName(path, libraryNames) libraryNames.add(name) return name } private fun createLibraryRoots(url: VirtualFileUrl, srcUrl: VirtualFileUrl?, nativeRoot: VirtualFileUrl?, entryTag: Element, moduleEntity: ModuleEntity, relativePathResolver: ModuleRelativePathResolver, virtualUrlManager: VirtualFileUrlManager): ArrayList<LibraryRoot> { val roots = ArrayList<LibraryRoot>() roots.add(LibraryRoot(url, LibraryRootTypeId.COMPILED)) if (srcUrl != null) { roots.add(LibraryRoot(srcUrl, LibraryRootTypeId.SOURCES)) } if (nativeRoot != null) { roots.add(LibraryRoot(nativeRoot, NATIVE_TYPE)) } entryTag.getChild("attributes")?.getChildren("attribute") ?.filter { it.getAttributeValue("name") == EclipseXml.JAVADOC_LOCATION } ?.mapTo(roots) { LibraryRoot(convertToJavadocUrl(it.getAttributeValue("value")!!, moduleEntity, relativePathResolver, virtualUrlManager), JAVADOC_TYPE) } return roots } override fun saveRoots(module: ModuleEntity, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, writer: JpsFileContentWriter, customDir: String?, imlFileUrl: VirtualFileUrl, storage: WorkspaceEntityStorage, virtualFileManager: VirtualFileUrlManager) { fun saveXmlFile(path: Path, root: Element) { //todo get rid of WriteAction here WriteAction.runAndWait<RuntimeException> { getOrCreateVirtualFile(path, this).getOutputStream(this).use { //todo use proper line separator EclipseJDOMUtil.output(root, OutputStreamWriter(it, StandardCharsets.UTF_8), //todo inline; schedule System.lineSeparator()) } } } @Suppress("UNCHECKED_CAST") val contentRoots = entities[ContentRootEntity::class.java] as List<ContentRootEntity>? ?: emptyList() val entitySource = contentRoots.asSequence().map { it.entitySource }.filterIsInstance<EclipseProjectFile>().firstOrNull() ?: return val dotProjectFile = entitySource.classpathFile.toPath().parent.resolve(EclipseXml.PROJECT_FILE) if (!dotProjectFile.exists()) { val content = DotProjectFileHelper.generateProjectFileContent(ModuleTypeManager.getInstance().findByID(module.type), module.name) saveXmlFile(dotProjectFile, content) } val classpathFile = VirtualFileManager.getInstance().findFileByUrl(entitySource.classpathFile.url) val oldClasspath = classpathFile?.inputStream?.use { JDOMUtil.load(it) } val pathShortener = ModulePathShortener(storage) if (oldClasspath != null || !entities[SourceRootEntity::class.java].isNullOrEmpty() || module.dependencies.size > 2) { val newClasspath = saveClasspathTags(module, entities, entitySource, oldClasspath, pathShortener) if (oldClasspath == null || !JDOMUtil.areElementsEqual(newClasspath, oldClasspath)) { saveXmlFile(entitySource.classpathFile.toPath(), newClasspath) } } val emlFileUrl = getEmlFileUrl(imlFileUrl) val emlRoot = EmlFileSaver(module, entities, pathShortener, writer.getReplacePathMacroMap(imlFileUrl.url), writer.getReplacePathMacroMap(emlFileUrl)).saveEml() if (emlRoot != null) { saveXmlFile(Paths.get(JpsPathUtil.urlToPath(emlFileUrl)), emlRoot) } else { val emlFile = VirtualFileManager.getInstance().findFileByUrl(emlFileUrl) if (emlFile != null) { runAsWriteActionIfNeeded { try { emlFile.delete(this) } catch (e: IOException) { } } } } } private fun saveClasspathTags(module: ModuleEntity, entities: Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>, entitySource: EclipseProjectFile, oldClasspath: Element?, pathShortener: ModulePathShortener): Element { val classpathTag = Element(EclipseXml.CLASSPATH_TAG) val oldEntries = oldClasspath?.getChildren(EclipseXml.CLASSPATHENTRY_TAG)?.associateBy { it.getAttributeValue(EclipseXml.KIND_ATTR)!! + EclipseClasspathWriter.getJREKey(it.getAttributeValue(EclipseXml.PATH_ATTR)) } ?: emptyMap() fun addClasspathEntry(kind: String, path: String?, index: Int = -1): Element { return addOrderEntry(kind, path, classpathTag, index, oldEntries) } val eclipseProperties = module.eclipseProperties @Suppress("UNCHECKED_CAST") val sourceRoots = entities[SourceRootEntity::class.java] as List<SourceRootEntity>? ?: emptyList() @Suppress("UNCHECKED_CAST") val moduleLibraries = (entities[LibraryEntity::class.java] as List<LibraryEntity>? ?: emptyList()).associateBy { it.name } for ((itemIndex, item) in module.dependencies.withIndex()) { when (item) { ModuleDependencyItem.ModuleSourceDependency -> { val shouldPlaceSeparately = eclipseProperties?.expectedModuleSourcePlace == itemIndex val comparator = module.mainContentRoot?.getSourceRootsComparator() ?: compareBy<SourceRootEntity> { it.url.url } for (sourceRoot in sourceRoots.sortedWith(comparator)) { var relativePath = convertToEclipsePath(sourceRoot.url, module, entitySource, pathShortener) if (sourceRoot.contentRoot.url != module.mainContentRoot?.url) { val linkedPath = eclipseProperties?.getVariable(EclipseModuleManagerImpl.SRC_LINK_PREFIX, sourceRoot.url.url) if (linkedPath != null) { relativePath = linkedPath } } val index = eclipseProperties?.srcPlace?.get(sourceRoot.url.url) ?: -1 addClasspathEntry(EclipseXml.SRC_KIND, relativePath, if (shouldPlaceSeparately) index else -1) } } is ModuleDependencyItem.Exportable.ModuleDependency -> { val path = "/${item.module.name}" val oldElement = EclipseClasspathWriter.getOldElement(EclipseXml.SRC_KIND, path, oldEntries) val classpathEntry = addClasspathEntry(EclipseXml.SRC_KIND, path) if (oldElement == null) { EclipseClasspathWriter.setAttributeIfAbsent(classpathEntry, EclipseXml.COMBINEACCESSRULES_ATTR, EclipseXml.FALSE_VALUE) } EclipseClasspathWriter.setExported(classpathEntry, item.exported) } is ModuleDependencyItem.Exportable.LibraryDependency -> { val libraryName = item.library.name if (item.library.tableId is LibraryTableId.ModuleLibraryTableId) { val libraryRoots = moduleLibraries[libraryName]?.roots ?: emptyList() val libraryClassesRoots = libraryRoots.filter { it.type.name == OrderRootType.CLASSES.name() } val firstRoot = libraryClassesRoots.firstOrNull()?.url if (firstRoot != null) { val firstUrl = firstRoot.url if (libraryName.contains(IdeaXml.JUNIT) && firstUrl == EclipseClasspathReader.getJunitClsUrl(libraryName.contains("4"))) { val classpathEntry = addClasspathEntry(EclipseXml.CON_KIND, EclipseXml.JUNIT_CONTAINER + "/" + libraryName.substring(IdeaXml.JUNIT.length)) EclipseClasspathWriter.setExported(classpathEntry, item.exported) } else { var newVarLibrary = false var link = false var eclipseVariablePath: String? = eclipseProperties?.getVariable("", firstUrl) if (eclipseVariablePath == null) { eclipseVariablePath = eclipseProperties?.getVariable(EclipseModuleManagerImpl.LINK_PREFIX, firstUrl) link = eclipseVariablePath != null } if (eclipseVariablePath == null && eclipseProperties?.eclipseUrls?.contains(firstRoot) != true) { //new library was added newVarLibrary = true eclipseVariablePath = convertToEclipsePathWithVariable(libraryClassesRoots) } var classpathEntry = if (eclipseVariablePath != null) { addClasspathEntry(if (link) EclipseXml.LIB_KIND else EclipseXml.VAR_KIND, eclipseVariablePath) } else { LOG.assertTrue(!StringUtil.isEmptyOrSpaces(firstUrl), "Library: $libraryName") addClasspathEntry(EclipseXml.LIB_KIND, convertToEclipsePath(firstRoot, module, entitySource, pathShortener)) } val srcRelativePath: String? var eclipseSrcVariablePath: String? = null var addSrcRoots = true val librarySourceRoots = libraryRoots.filter { it.type.name == OrderRootType.SOURCES.name() } val firstSrcRoot = librarySourceRoots.firstOrNull()?.url if (firstSrcRoot == null) { srcRelativePath = null } else { val firstSrcUrl = firstSrcRoot.url srcRelativePath = convertToEclipsePath(firstSrcRoot, module, entitySource, pathShortener) if (eclipseVariablePath != null) { eclipseSrcVariablePath = eclipseProperties?.getVariable(EclipseModuleManagerImpl.SRC_PREFIX, firstSrcUrl) if (eclipseSrcVariablePath == null) { eclipseSrcVariablePath = eclipseProperties?.getVariable(EclipseModuleManagerImpl.SRC_LINK_PREFIX, firstSrcUrl) } if (eclipseSrcVariablePath == null) { eclipseSrcVariablePath = convertToEclipsePathWithVariable(librarySourceRoots) if (eclipseSrcVariablePath != null) { eclipseSrcVariablePath = "/$eclipseSrcVariablePath" } else { if (newVarLibrary) { //new library which cannot be replaced with vars classpathEntry.detach() classpathEntry = addClasspathEntry(EclipseXml.LIB_KIND, convertToEclipsePath(firstRoot, module, entitySource, pathShortener)) } else { LOG.info("Added root $srcRelativePath (in existing var library) can't be replaced with any variable; src roots placed in .eml only") addSrcRoots = false } } } } } EclipseClasspathWriter.setOrRemoveAttribute(classpathEntry, EclipseXml.SOURCEPATH_ATTR, if (addSrcRoots) eclipseSrcVariablePath ?: srcRelativePath else null) EJavadocUtil.setupAttributes(classpathEntry, { convertToEclipseJavadocPath(it, module, entitySource.internalSource.projectLocation, pathShortener) }, EclipseXml.JAVADOC_LOCATION, libraryRoots.filter { it.type.name == "JAVADOC" }.map { it.url }.toList().toTypedArray()) val nativeRoots = libraryRoots.asSequence().filter { it.type.name == "NATIVE" }.map { it.url }.toList().toTypedArray() if (nativeRoots.isNotEmpty()) { EJavadocUtil.setupAttributes(classpathEntry, Function { convertToEclipsePath(it, module, entitySource, pathShortener)!! }, EclipseXml.DLL_LINK, nativeRoots) } EclipseClasspathWriter.setExported(classpathEntry, item.exported) } } } else { val path = when { eclipseProperties?.unknownCons?.contains(libraryName) == true -> libraryName libraryName == IdeaXml.ECLIPSE_LIBRARY -> EclipseXml.ECLIPSE_PLATFORM else -> EclipseXml.USER_LIBRARY + '/' + libraryName } val classpathEntry = addClasspathEntry(EclipseXml.CON_KIND, path) EclipseClasspathWriter.setExported(classpathEntry, item.exported) } } ModuleDependencyItem.InheritedSdkDependency -> { if (eclipseProperties?.forceConfigureJdk != true) { addClasspathEntry(EclipseXml.CON_KIND, EclipseXml.JRE_CONTAINER) } } is ModuleDependencyItem.SdkDependency -> { val jdkLink = "${EclipseXml.JRE_CONTAINER}${if (item.sdkType == "JavaSDK") EclipseXml.JAVA_SDK_TYPE else ""}/${item.sdkName}" addClasspathEntry(EclipseXml.CON_KIND, jdkLink) } } } val compilerOutput = module.javaSettings?.compilerOutput val outputPath = if (compilerOutput != null) { val linkedPath = eclipseProperties?.getVariable(EclipseModuleManagerImpl.LINK_PREFIX, compilerOutput.url) linkedPath ?: convertToEclipsePath(compilerOutput, module, entitySource, pathShortener) } else { "bin" } eclipseProperties?.knownCons?.forEach { addClasspathEntry(EclipseXml.CON_KIND, it, eclipseProperties.srcPlace[it] ?: -1) } EclipseClasspathWriter.setAttributeIfAbsent(addClasspathEntry(EclipseXml.OUTPUT_KIND, outputPath), EclipseXml.PATH_ATTR, EclipseXml.BIN_DIR) return classpathTag } }
apache-2.0
ba2e8d60e80dd3ab2ce9074dab7b6746
53.405186
161
0.6505
5.519237
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/scripting/gradle/GradleScriptListenerTest.kt
1
11557
// 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.scripting.gradle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.util.ui.UIUtil import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager import org.jetbrains.kotlin.idea.gradleJava.scripting.legacy.GradleStandaloneScriptActionsManager import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.kotlin.idea.script.AbstractScriptConfigurationLoadingTest import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.test.JUnit3RunnerWithInners import org.jetbrains.plugins.gradle.settings.DistributionType import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.util.GradleConstants import org.junit.runner.RunWith import java.io.File @RunWith(JUnit3RunnerWithInners::class) open class GradleScriptListenerTest : AbstractScriptConfigurationLoadingTest() { companion object { internal const val outsidePlaceholder = "// OUTSIDE_SECTIONS" internal const val insidePlaceholder = "// INSIDE_SECTIONS" } private lateinit var testFiles: TestFiles data class TestFiles( val buildKts: KtFile, val settings: KtFile, val prop: PsiFile, val gradleWrapperProperties: VirtualFile ) override fun setUpTestProject() { val rootDir = IDEA_TEST_DATA_DIR.resolve("script/definition/loading/gradle/") val settings: KtFile = copyFromTestdataToProject(File(rootDir, GradleConstants.KOTLIN_DSL_SETTINGS_FILE_NAME)) val prop: PsiFile = copyFromTestdataToProject(File(rootDir, "gradle.properties")) val gradleCoreJar = createFileInProject("gradle/lib/gradle-core-1.0.0.jar") val gradleWrapperProperties = createFileInProject("gradle/wrapper/gradle-wrapper.properties") val buildGradleKts = rootDir.walkTopDown().find { it.name == GradleConstants.KOTLIN_DSL_SCRIPT_NAME } ?: error("Couldn't find main script") configureScriptFile(rootDir, buildGradleKts) val build = (myFile as? KtFile) ?: error("") val newProjectSettings = GradleProjectSettings() newProjectSettings.gradleHome = gradleCoreJar.parentFile.parent newProjectSettings.distributionType = DistributionType.LOCAL newProjectSettings.externalProjectPath = settings.virtualFile.parent.path ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).linkProject(newProjectSettings) testFiles = TestFiles( build, settings, prop, LocalFileSystem.getInstance().findFileByIoFile(gradleWrapperProperties)!! ) } fun testSectionChange() { assertAndLoadInitialConfiguration(testFiles.buildKts) changeBuildKtsInsideSections() assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testSpacesInSectionsChange() { assertAndLoadInitialConfiguration(testFiles.buildKts) changeBuildKtsInsideSections("// INSIDE PLUGINS\n") assertConfigurationUpToDate(testFiles.buildKts) } fun testCommentsInSectionsChange() { assertAndLoadInitialConfiguration(testFiles.buildKts) changeBuildKtsInsideSections("// My test comment\n") assertConfigurationUpToDate(testFiles.buildKts) } fun testOutsideSectionChange() { assertAndLoadInitialConfiguration(testFiles.buildKts) changeBuildKtsOutsideSections() assertConfigurationUpToDate(testFiles.buildKts) } fun testSectionsInSettingsChange() { assertAndLoadInitialConfiguration(testFiles.settings) changeSettingsKtsInsideSections() assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) } fun testOutsideSectionsInSettingsChange() { assertAndLoadInitialConfiguration(testFiles.settings) changeSettingsKtsOutsideSections() assertConfigurationUpToDate(testFiles.settings) } fun testChangeOutsideSectionsInvalidatesOtherFiles() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) changeBuildKtsOutsideSections() assertConfigurationUpToDate(testFiles.buildKts) assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) } fun testChangeInsideSectionsInvalidatesOtherFiles() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) changeBuildKtsInsideSections() assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) } fun testChangeInsideNonKtsFileInvalidatesOtherFiles() { assertAndLoadInitialConfiguration(testFiles.buildKts) changePropertiesFile() assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testTwoFilesChanged() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) changePropertiesFile() changeSettingsKtsOutsideSections() assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) } fun testFileAttributes() { assertAndLoadInitialConfiguration(testFiles.buildKts) ScriptConfigurationManager.clearCaches(project) assertConfigurationUpToDate(testFiles.buildKts) } fun testFileAttributesUpToDate() { assertAndLoadInitialConfiguration(testFiles.buildKts) ScriptConfigurationManager.clearCaches(project) changeBuildKtsInsideSections() assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testFileAttributesUpToDateAfterChangeOutsideSections() { assertAndLoadInitialConfiguration(testFiles.buildKts) ScriptConfigurationManager.clearCaches(project) changeBuildKtsOutsideSections() assertConfigurationUpToDate(testFiles.buildKts) } fun testFileAttributesUpdateAfterChangeOutsideSectionsOfOtherFile() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) ScriptConfigurationManager.clearCaches(project) changeSettingsKtsOutsideSections() assertConfigurationUpToDate(testFiles.settings) assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testConfigurationUpdateAfterProjectClosing() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) changeSettingsKtsOutsideSections() assertConfigurationUpToDate(testFiles.settings) assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testConfigurationUpdateAfterProjectClosing2() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) changeSettingsKtsOutsideSections() val ts = System.currentTimeMillis() markFileChanged(testFiles.buildKts.virtualFile, ts) markFileChanged(testFiles.settings.virtualFile, ts) assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } fun testConfigurationUpdateAfterProjectClosing3() { assertAndLoadInitialConfiguration(testFiles.buildKts) assertAndLoadInitialConfiguration(testFiles.settings) val ts = System.currentTimeMillis() markFileChanged(testFiles.buildKts.virtualFile, ts) markFileChanged(testFiles.settings.virtualFile, ts) changePropertiesFile() assertConfigurationUpdateWasDoneAfterClick(testFiles.settings) assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) } private fun markFileChanged(virtualFile: VirtualFile, ts: Long) { GradleBuildRootsManager.getInstance(project)!!.fileChanged(virtualFile.path, ts) } fun testLoadedConfigurationWhenExternalFileChanged() { assertAndLoadInitialConfiguration(testFiles.buildKts) changePropertiesFile() assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) assertConfigurationUpToDate(testFiles.buildKts) } fun testChangeGradleWrapperPropertiesFile() { assertAndLoadInitialConfiguration(testFiles.buildKts) markFileChanged(testFiles.gradleWrapperProperties, System.currentTimeMillis()) assertConfigurationUpdateWasDoneAfterClick(testFiles.buildKts) assertConfigurationUpToDate(testFiles.buildKts) } override fun assertAndLoadInitialConfiguration(file: KtFile) { assertNull(scriptConfigurationManager.getConfiguration(file)) assertReloadingSuggestedAndDoReload(file) assertAndDoAllBackgroundTasks() assertSingleLoading() assertAppliedConfiguration(file.text, file) checkHighlighting(file) } private fun assertReloadingSuggestedAndDoReload(file: KtFile = myFile as KtFile) { ApplicationManager.getApplication().invokeLater {} UIUtil.dispatchAllInvocationEvents() assertTrue( "reloading configuration should be suggested", GradleStandaloneScriptActionsManager.getInstance(project).performSuggestedLoading(file.virtualFile) ) } private fun assertConfigurationUpToDate(file: KtFile) { scriptConfigurationManager.default.ensureUpToDatedConfigurationSuggested(file) assertNoBackgroundTasks() assertNoLoading() } private fun assertConfigurationUpdateWasDoneAfterClick(file: KtFile) { scriptConfigurationManager.default.ensureUpToDatedConfigurationSuggested(file) assertReloadingSuggestedAndDoReload(file) assertAndDoAllBackgroundTasks() assertSingleLoading() } private fun changeBuildKtsInsideSections(text: String = "application") { changeBuildKts(insidePlaceholder, text) } private fun changeBuildKtsOutsideSections() { changeBuildKts(outsidePlaceholder, "compile(\"\")") } private fun changeSettingsKtsInsideSections() { changeSettingsKts(insidePlaceholder, "mavenCentral()") } private fun changeSettingsKtsOutsideSections() { changeSettingsKts(outsidePlaceholder, "include: 'aaa'") } private fun changeBuildKts(placeHolder: String, text: String) { changeContents(testFiles.buildKts.text.replace(placeHolder, text), testFiles.buildKts) testFiles = testFiles.copy(buildKts = myFile as KtFile) } private fun changeSettingsKts(placeHolder: String, text: String) { changeContents(testFiles.settings.text.replace(placeHolder, text), testFiles.settings) testFiles = testFiles.copy(settings = myFile as KtFile) } private fun changePropertiesFile() { changeContents(testFiles.prop.text.replace(outsidePlaceholder.replace("//", "#"), "myProp = true"), testFiles.prop) testFiles = testFiles.copy(prop = myFile) } }
apache-2.0
8920bacf6d01330d71618ec3a043f3c1
35.457413
158
0.756252
5.104682
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveTopLevelDeclarations/misc/moveFunctionWithImportsRetained/after/first/Test.kt
13
193
package first import fourth.X import second.A import third.B import third.D fun test() { val a = A() val b = B() val d_ = D() val c = B.C() val x = X() val y = X.Y() }
apache-2.0
92b4cd02aece142c8a3efe3cb237f0e4
11.933333
17
0.523316
2.680556
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataStubBuilder.kt
1
3068
// 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.decompiler.common import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.compiled.ClsStubBuilder import com.intellij.psi.impl.compiled.ClassFileStubBuilder import com.intellij.psi.stubs.PsiFileStub import com.intellij.util.indexing.FileContent import org.jetbrains.kotlin.idea.decompiler.stubBuilder.* import org.jetbrains.kotlin.metadata.deserialization.TypeTable import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol import org.jetbrains.kotlin.serialization.deserialization.ProtoBasedClassDataFinder import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer import org.jetbrains.kotlin.serialization.deserialization.getClassId open class KotlinMetadataStubBuilder( private val version: Int, private val fileType: FileType, private val serializerProtocol: () -> SerializerExtensionProtocol, private val readFile: (VirtualFile, ByteArray) -> FileWithMetadata? ) : ClsStubBuilder() { override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + version override fun buildFileStub(content: FileContent): PsiFileStub<*>? { val virtualFile = content.file assert(FileTypeRegistry.getInstance().isFileOfType(virtualFile, fileType)) { "Unexpected file type ${virtualFile.fileType}" } val file = readFile(virtualFile, content.content) ?: return null when (file) { is FileWithMetadata.Incompatible -> { return createIncompatibleAbiVersionFileStub() } is FileWithMetadata.Compatible -> { val packageProto = file.proto.`package` val packageFqName = file.packageFqName val nameResolver = file.nameResolver val components = ClsStubBuilderComponents( ProtoBasedClassDataFinder(file.proto, nameResolver, file.version), AnnotationLoaderForStubBuilderImpl(serializerProtocol()), virtualFile ) val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable)) val fileStub = createFileStub(packageFqName, isScript = false) createPackageDeclarationsStubs( fileStub, context, ProtoContainer.Package(packageFqName, context.nameResolver, context.typeTable, source = null), packageProto ) for (classProto in file.classesToDecompile) { createClassStub( fileStub, classProto, nameResolver, nameResolver.getClassId(classProto.fqName), source = null, context = context ) } return fileStub } } } }
apache-2.0
9aae1da665c24bb47c6c22de69e34b3d
48.483871
158
0.693611
5.401408
false
false
false
false
Cognifide/gradle-aem-plugin
src/functionalTest/kotlin/com/cognifide/gradle/aem/pkg/PackagePluginTest.kt
1
17597
package com.cognifide.gradle.aem.pkg import com.cognifide.gradle.aem.test.AemBuildTest import org.gradle.testkit.runner.TaskOutcome import org.junit.jupiter.api.Test import java.io.File @Suppress("LongMethod", "MaxLineLength") class PackagePluginTest : AemBuildTest() { @Test fun `should build package using minimal configuration`() { val projectDir = prepareProject("package-minimal") { settingsGradle("") buildGradle(""" plugins { id("com.cognifide.aem.package") } group = "com.company.example" version = "1.0.0" """) file("src/main/content/jcr_root/apps/example/.content.xml", """ <?xml version="1.0" encoding="UTF-8"?> <jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" jcr:primaryType="sling:Folder"/> """) file("src/main/content/META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/example"/> </workspaceFilter> """) } runBuild(projectDir, "packageCompose", "-Poffline") { assertTask(":packageCompose") val pkg = file("build/packageCompose/package-minimal-1.0.0.zip") assertPackage(pkg) assertZipEntry(pkg, "jcr_root/apps/example/.content.xml") assertZipEntryEquals(pkg, "META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/example"/> </workspaceFilter> """) assertZipEntryEquals(pkg, "META-INF/vault/properties.xml", """ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="group">com.company.example</entry> <entry key="name">package-minimal</entry> <entry key="version">1.0.0</entry> <entry key="createdBy">${System.getProperty("user.name")}</entry> <entry key="acHandling">merge_preserve</entry> <entry key="requiresRoot">false</entry> </properties> """) assertZipEntryMatchingOrdered(pkg, "META-INF/MANIFEST.MF", """ Manifest-Version: 1.0 Build-Jdk: * Built-By: ${System.getProperty("user.name")} Content-Package-Id: com.company.example:package-minimal:1.0.0 Content-Package-Roots: /apps/example Content-Package-Type: application Created-By: Gradle (AEM Plugin) Implementation-Vendor-Id: com.company.example Implementation-Version: 1.0.0 """) } runBuild(projectDir, "packageValidate", "-Poffline") { assertTask(":packageCompose", TaskOutcome.UP_TO_DATE) assertTask(":packageValidate") } } @Test fun `should build assembly package with content and bundles merged`() { val projectDir = prepareProject("package-assembly") { settingsGradle(""" rootProject.name = "example" include("ui.apps") include("ui.content") include("assembly") """) gradleProperties(""" version=1.0.0 """) file("assembly/build.gradle.kts", """ plugins { id("com.cognifide.aem.package") id("maven-publish") } group = "com.company.example.aem" tasks { packageCompose { mergePackageProject(":ui.apps") mergePackageProject(":ui.content") } } publishing { repositories { maven(rootProject.file("build/repository")) } publications { create<MavenPublication>("maven") { artifact(common.publicationArtifact("packageCompose")) } } } """) uiApps() uiContent() } runBuild(projectDir, ":assembly:packageCompose", "-Poffline") { assertTask(":assembly:packageCompose") val pkg = file("assembly/build/packageCompose/example-assembly-1.0.0.zip") assertPackage(pkg) // Check if bundle was build in sub-project assertBundle("ui.apps/build/libs/example-ui.apps-1.0.0.jar") assertZipEntryEquals("ui.apps/build/libs/example-ui.apps-1.0.0.jar", "OSGI-INF/com.company.example.aem.HelloService.xml", """ <?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.3.0" name="com.company.example.aem.HelloService" immediate="true" activate="activate" deactivate="deactivate"> <service> <provide interface="com.company.example.aem.HelloService"/> </service> <implementation class="com.company.example.aem.HelloService"/> </scr:component> """) // Check assembled package assertZipEntryEquals(pkg, "META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/example/ui.apps"/> <filter root="/content/example"/> </workspaceFilter> """) assertZipEntryEquals(pkg, "META-INF/vault/properties.xml", """ <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <entry key="group">com.company.example.aem</entry> <entry key="name">example-assembly</entry> <entry key="version">1.0.0</entry> <entry key="createdBy">${System.getProperty("user.name")}</entry> <entry key="acHandling">merge_preserve</entry> <entry key="requiresRoot">false</entry> <entry key="installhook.actool.class">biz.netcentric.cq.tools.actool.installhook.AcToolInstallHook</entry> <entry key="ui.apps.merged">test</entry> <entry key="installhook.aecu.class">de.valtech.aecu.core.installhook.AecuInstallHook</entry> </properties> """) assertZipEntry(pkg, "jcr_root/content/example/.content.xml") assertZipEntry(pkg, "jcr_root/apps/example/ui.apps/install/example-ui.apps-1.0.0.jar") assertZipEntryMatching(pkg, "META-INF/vault/nodetypes.cnd", """ <'apps'='http://apps.com/apps/1.0'> <'content'='http://content.com/content/1.0'> * [apps:Folder] > nt:folder - * (undefined) multiple - * (undefined) + * (nt:base) = apps:Folder version * [content:Folder] > nt:folder - * (undefined) multiple - * (undefined) + * (nt:base) = content:Folder version """) } runBuild(projectDir, ":assembly:packageValidate", "-Poffline") { assertTask(":assembly:packageCompose", TaskOutcome.UP_TO_DATE) assertTask(":assembly:packageValidate") } runBuild(projectDir, ":assembly:publish", "-Poffline") { val mavenDir = projectDir.resolve("build/repository/com/company/example/aem/assembly/1.0.0") assertFileExists(mavenDir.resolve("assembly-1.0.0.zip")) assertFileExists(mavenDir.resolve("assembly-1.0.0.pom")) } } @Test fun `should build package with nested bundle and subpackages from Maven repository`() { val projectDir = prepareProject("package-nesting-repository") { settingsGradle("") buildGradle(""" plugins { id("com.cognifide.aem.package") } group = "com.company.example" version = "1.0.0" tasks { packageCompose { installBundle("org.jsoup:jsoup:1.10.2") installBundle("com.github.mickleroy:aem-sass-compiler:1.0.1") // installBundle("com.neva.felix:search-webconsole-plugin:1.3.0") { runMode.set("author") } nestPackage("com.adobe.cq:core.wcm.components.all:2.8.0") nestPackage("com.adobe.cq:core.wcm.components.examples:2.8.0") nestPackage("https://github.com/icfnext/aem-groovy-console/releases/download/14.0.0/aem-groovy-console-14.0.0.zip") } } """) defaultPlanJson() } runBuild(projectDir, "packageCompose", "-Poffline") { assertTask(":packageCompose") val pkg = file("build/packageCompose/package-nesting-repository-1.0.0.zip") assertPackage(pkg) assertZipEntry(pkg, "jcr_root/apps/package-nesting-repository/install/jsoup-1.10.2.jar") assertZipEntry(pkg, "jcr_root/apps/package-nesting-repository/install/aem-sass-compiler-1.0.1.jar") // assertZipEntry(pkg, "jcr_root/apps/package-nesting-repository/install.author/search-webconsole-plugin-1.3.0.jar") assertZipEntry(pkg, "jcr_root/etc/packages/adobe/cq60/core.wcm.components.all-2.8.0.zip") assertZipEntry(pkg, "jcr_root/etc/packages/adobe/cq60/core.wcm.components.examples-2.8.0.zip") assertZipEntry(pkg, "jcr_root/etc/packages/ICF Next/aem-groovy-console-14.0.0.zip") assertZipEntryEquals(pkg, "META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/package-nesting-repository/install/jsoup-1.10.2.jar"/> <filter root="/apps/package-nesting-repository/install/aem-sass-compiler-1.0.1.jar"/> <filter root="/etc/packages/adobe/cq60/core.wcm.components.all-2.8.0.zip"/> <filter root="/etc/packages/adobe/cq60/core.wcm.components.examples-2.8.0.zip"/> <filter root="/etc/packages/ICF Next/aem-groovy-console-14.0.0.zip"/> </workspaceFilter> """) } runBuild(projectDir, "packageValidate", "-Poffline") { assertTask(":packageCompose", TaskOutcome.UP_TO_DATE) assertTask(":packageValidate") } } @Test fun `should build package with nested bundle and sub-package built by sub-projects`() { val projectDir = prepareProject("package-nesting-built") { settingsGradle(""" rootProject.name = "example" include("ui.apps") include("ui.content") """) gradleProperties(""" version=1.0.0 """) buildGradle(""" plugins { id("com.cognifide.aem.package") } group = "com.company.example" repositories { maven("https://repo.adobe.com/nexus/content/groups/public") } tasks { packageCompose { nestPackageProject(":ui.content") installBundleProject(":ui.apps") } } """) defaultPlanJson() uiApps() uiContent() } runBuild(projectDir, "packageCompose", "-Poffline") { assertTask(":packageCompose") assertTask(":ui.apps:jar") assertTask(":ui.apps:test") assertTask(":ui.content:packageCompose") assertTask(":ui.content:packageValidate") val pkg = file("build/packageCompose/example-1.0.0.zip") assertPackage(pkg) assertZipEntry(pkg, "jcr_root/apps/example/ui.apps/install/example-ui.apps-1.0.0.jar") assertZipEntry(pkg, "jcr_root/etc/packages/com.company.example/example-ui.content-1.0.0.zip") assertZipEntryEquals(pkg, "META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/example/ui.apps/install/example-ui.apps-1.0.0.jar"/> <filter root="/etc/packages/com.company.example/example-ui.content-1.0.0.zip"/> </workspaceFilter> """) } } private fun File.uiApps() { file("ui.apps/build.gradle.kts", """ plugins { id("com.cognifide.aem.bundle") id("com.cognifide.aem.package") } group = "com.company.example.aem" repositories { maven("https://repo.adobe.com/nexus/content/groups/public") } dependencies { compileOnly("org.slf4j:slf4j-api:1.5.10") compileOnly("org.osgi:osgi.cmpn:6.0.0") testImplementation("org.junit.jupiter:junit-jupiter:5.5.2") // testImplementation("io.wcm:io.wcm.testing.aem-mock.junit5:2.5.2") } tasks { packageCompose { vaultDefinition { property("installhook.actool.class", "biz.netcentric.cq.tools.actool.installhook.AcToolInstallHook") } merged { assembly -> assembly.vaultDefinition.property("ui.apps.merged", "test") } } } """) file("ui.apps/src/main/content/META-INF/vault/nodetypes.cnd", """ <'apps'='http://apps.com/apps/1.0'> [apps:Folder] > nt:folder - * (undefined) multiple - * (undefined) + * (nt:base) = apps:Folder version """) file("ui.apps/src/main/content/META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/apps/example/ui.apps"/> </workspaceFilter> """) helloServiceJava("ui.apps") } private fun File.uiContent() { file("ui.content/build.gradle.kts", """ plugins { id("com.cognifide.aem.package") } group = "com.company.example" tasks { packageCompose { vaultDefinition { property("installhook.aecu.class", "de.valtech.aecu.core.installhook.AecuInstallHook") } } } """) file("ui.content/src/main/content/jcr_root/content/example/.content.xml", """ <?xml version="1.0" encoding="UTF-8"?> <jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" jcr:primaryType="sling:Folder"/> """) file("ui.content/src/main/content/META-INF/vault/filter.xml", """ <?xml version="1.0" encoding="UTF-8"?> <workspaceFilter version="1.0"> <filter root="/content/example"/> </workspaceFilter> """) file("ui.content/src/main/content/META-INF/vault/nodetypes.cnd", """ <'content'='http://content.com/content/1.0'> [content:Folder] > nt:folder - * (undefined) multiple - * (undefined) + * (nt:base) = content:Folder version """) } private fun File.defaultPlanJson() { file("src/aem/package/OAKPAL_OPEAR/default-plan.json", """ { "checklists": [ "net.adamcin.oakpal.core/basic" ], "installHookPolicy": "SKIP", "checks": [ { "name": "basic/subpackages", "config": { "denyAll": false } } ] } """) } }
apache-2.0
db93ed7c159b877d3d09c7e7474f249b
37.845475
185
0.494573
4.441444
false
false
false
false
aosp-mirror/platform_frameworks_support
room/compiler/src/main/kotlin/androidx/room/solver/types/BoxedBooleanToBoxedIntConverter.kt
1
2048
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.solver.types import androidx.room.ext.L import androidx.room.solver.CodeGenScope import javax.annotation.processing.ProcessingEnvironment /** * int to boolean adapter. */ object BoxedBooleanToBoxedIntConverter { fun create(processingEnvironment: ProcessingEnvironment): List<TypeConverter> { val tBoolean = processingEnvironment.elementUtils.getTypeElement("java.lang.Boolean") .asType() val tInt = processingEnvironment.elementUtils.getTypeElement("java.lang.Integer") .asType() return listOf( object : TypeConverter(tBoolean, tInt) { override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) { scope.builder().addStatement("$L = $L == null ? null : ($L ? 1 : 0)", outputVarName, inputVarName, inputVarName) } }, object : TypeConverter(tInt, tBoolean) { override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) { scope.builder().addStatement("$L = $L == null ? null : $L != 0", outputVarName, inputVarName, inputVarName) } } ) } }
apache-2.0
278c8ac1b1d306307b2129345091e1a7
40.795918
93
0.605469
4.982968
false
false
false
false
atlarge-research/opendc-simulator
opendc-model-odc/core/src/main/kotlin/com/atlarge/opendc/model/odc/platform/scheduler/stages/StageMeasurement.kt
1
4265
/* * MIT License * * Copyright (c) 2018 atlarge-research * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.atlarge.opendc.model.odc.platform.scheduler.stages import com.atlarge.opendc.simulator.Instant import java.lang.management.ManagementFactory /** * The measurements related to a single stage in the scheduler. * * @property stage The identifier of the stage. * @property time The point in time at which the measurement occurred. * @property cpu The duration in cpu time (ns) of the stage. * @property wall The duration in wall time (ns) of the stage. * @property size The total size of the input of the stage. * @property iterations The amount of iterations in the stage. */ data class StageMeasurement(val stage: Int, val time: Instant, val cpu: Long, val wall: Long, val size: Int, val iterations: Int) /** * A class that accumulates and manages the measurements of the stages. * * @property time The point in simulation time at which the measurements occur. * @property size The input size of the scheduler. */ class StageMeasurementAccumulator(val time: Instant, val size: Int) { /** * A collection of measurements that have been collected during the runtime of the continuation. */ val measurements: MutableList<StageMeasurement> = mutableListOf() /** * The MXBean to measure cpu time. */ val bean = ManagementFactory.getThreadMXBean() /** * Measure the initial cpu time */ private var cpuStart = -1L /** * Measure the initial wall time. */ private var wallStart = -1L /** * Start the accumulation of measurements. */ fun start() { measurements.clear() cpuStart = bean.currentThreadUserTime wallStart = System.nanoTime() } /** * End the accumulation of measurements. */ fun end() { val cpu = bean.currentThreadUserTime - cpuStart - measurements.map { it.cpu }.sum() val wall = System.nanoTime() - wallStart - measurements.map { it.wall }.sum() val measurement = StageMeasurement(measurements.size + 1, time, cpu, wall, size, 1) measurements.add(measurement) } /** * Measure the duration of a stage. * * @param stage The identifier of the stage. * @param input The size of the input. * @param block The block to measure. */ inline fun <R> runStage(stage: Int, input: Int, block: () -> R): R { val cpuStart = bean.currentThreadUserTime val wallStart = System.nanoTime() val res = block() val cpu = bean.currentThreadUserTime - cpuStart val wall = System.nanoTime() - wallStart val previous = if (stage - 1 < measurements.size) measurements[stage - 1] else null if (previous != null) { measurements[stage - 1] = StageMeasurement(stage, time, cpu + previous.cpu, wall + previous.wall, input + previous.size, previous.iterations + 1) } else { measurements.add(StageMeasurement(stage, time, cpu, wall, input, 1)) } return res } }
mit
ac9a56e34f5a76b7c0923f20257381f1
35.144068
157
0.661899
4.433472
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/util/QuranFileUtils.kt
2
22357
package com.quran.labs.androidquran.util import android.content.Context import android.graphics.Bitmap import android.graphics.Bitmap.CompressFormat.PNG import android.graphics.Bitmap.Config.ALPHA_8 import android.graphics.BitmapFactory import android.graphics.BitmapFactory.Options import android.os.Environment import androidx.annotation.WorkerThread import com.quran.data.core.QuranFileManager import com.quran.data.source.PageProvider import com.quran.labs.androidquran.BuildConfig import com.quran.labs.androidquran.common.Response import com.quran.labs.androidquran.data.QuranDataProvider import com.quran.labs.androidquran.extension.closeQuietly import okhttp3.OkHttpClient import okhttp3.Request.Builder import okhttp3.ResponseBody import okio.Buffer import okio.ForwardingSource import okio.Source import okio.buffer import okio.sink import okio.source import timber.log.Timber import java.io.File import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.InterruptedIOException import java.text.NumberFormat import java.util.ArrayList import java.util.Collections import java.util.Locale import javax.inject.Inject class QuranFileUtils @Inject constructor( context: Context, pageProvider: PageProvider, private val quranScreenInfo: QuranScreenInfo, private val urlUtil: UrlUtil ): QuranFileManager { // server urls private val imageBaseUrl: String = pageProvider.getImagesBaseUrl() private val imageZipBaseUrl: String = pageProvider.getImagesZipBaseUrl() private val patchBaseUrl: String = pageProvider.getPatchBaseUrl() private val databaseBaseUrl: String = pageProvider.getDatabasesBaseUrl() private val ayahInfoBaseUrl: String = pageProvider.getAyahInfoBaseUrl() // local paths private val databaseDirectory: String = pageProvider.getDatabaseDirectoryName() private val audioDirectory: String = pageProvider.getAudioDirectoryName() private val ayahInfoDirectory: String = pageProvider.getAyahInfoDirectoryName() private val imagesDirectory: String = pageProvider.getImagesDirectoryName() val ayahInfoDbHasGlyphData = pageProvider.ayahInfoDbHasGlyphData() private val appContext: Context = context.applicationContext val gaplessDatabaseRootUrl: String = pageProvider.getAudioDatabasesBaseUrl() // check if the images with the given width param have a version // that we specify (ex if version is 3, check for a .v3 file). @WorkerThread override fun isVersion(widthParam: String, version: Int): Boolean { // version 1 or below are true as long as you have images return version <= 1 || hasVersionFile(appContext, widthParam, version) } private fun hasVersionFile(context: Context, widthParam: String, version: Int): Boolean { val quranDirectory = getQuranImagesDirectory(context, widthParam) Timber.d( "isVersion: checking if version %d exists for width %s at %s", version, widthParam, quranDirectory ) return if (quranDirectory == null) { false } else try { val vFile = File( quranDirectory + File.separator + ".v" + version ) vFile.exists() } catch (e: Exception) { Timber.e(e, "isVersion: exception while checking version file") false } // check the version code } fun getPotentialFallbackDirectory(context: Context, totalPages: Int): String? { val state = Environment.getExternalStorageState() if (state == Environment.MEDIA_MOUNTED) { if (haveAllImages(context, "_1920", totalPages, false)) { return "1920" } } return null } override fun quranImagesDirectory(): String? = getQuranImagesDirectory(appContext) override fun ayahInfoFileDirectory(): String? { val base = quranAyahDatabaseDirectory return if (base != null) { val filename = ayaPositionFileName base + File.separator + filename } else { null } } @WorkerThread override fun removeFilesForWidth(width: Int, directoryLambda: ((String) -> String)) { val widthParam = "_$width" val quranDirectoryWithoutLambda = getQuranImagesDirectory(appContext, widthParam) ?: return val quranDirectory = directoryLambda(quranDirectoryWithoutLambda) val file = File(quranDirectory) if (file.exists()) { deleteFileOrDirectory(file) val ayahDatabaseDirectoryWithoutLambda = getQuranAyahDatabaseDirectory(appContext) ?: return val ayahDatabaseDirectory = directoryLambda(ayahDatabaseDirectoryWithoutLambda) val ayahinfoFile = File(ayahDatabaseDirectory, "ayahinfo_$width.db") if (ayahinfoFile.exists()) { ayahinfoFile.delete() } } } @WorkerThread override fun writeVersionFile(widthParam: String, version: Int) { val quranDirectory = getQuranImagesDirectory(appContext, widthParam) ?: return File(quranDirectory, ".v$version").createNewFile() } @WorkerThread override fun writeNoMediaFileRelative(widthParam: String) { val quranDirectory = getQuranImagesDirectory(appContext, widthParam) ?: return writeNoMediaFile(quranDirectory) } fun haveAllImages(context: Context, widthParam: String, totalPages: Int, makeDirectory: Boolean, oneFilePerPage: Boolean = true ): Boolean { val quranDirectory = getQuranImagesDirectory(context, widthParam) Timber.d("haveAllImages: for width %s, directory is: %s", widthParam, quranDirectory) if (quranDirectory == null) { return false } val state = Environment.getExternalStorageState() if (state == Environment.MEDIA_MOUNTED) { val dir = File(quranDirectory + File.separator) if (dir.isDirectory) { Timber.d("haveAllImages: media state is mounted and directory exists") val fileList = dir.list() if (fileList == null) { Timber.d("haveAllImages: null fileList, checking page by page...") for (i in 1..totalPages) { val name = if (oneFilePerPage) getPageFileName(i) else i.toString() if (!File(dir, name).exists()) { Timber.d("haveAllImages: couldn't find page %d", i) return false } } } else if (fileList.size < totalPages) { // ideally, we should loop for each page and ensure // all pages are there, but this will do for now. Timber.d("haveAllImages: found %d files instead of 604.", fileList.size) return false } return true } else { Timber.d( "haveAllImages: couldn't find the directory, so %s", if (makeDirectory) "making it instead." else "doing nothing." ) if (makeDirectory) { makeQuranDirectory(context, widthParam) } } } return false } private val isSDCardMounted: Boolean get() { val state = Environment.getExternalStorageState() return state == Environment.MEDIA_MOUNTED } fun getImageFromSD( context: Context, widthParam: String?, filename: String ): Response { val location: String = widthParam?.let { getQuranImagesDirectory(context, it) } ?: getQuranImagesDirectory(context) ?: return Response(Response.ERROR_SD_CARD_NOT_FOUND) val options = Options() options.inPreferredConfig = ALPHA_8 val bitmap = BitmapFactory.decodeFile(location + File.separator + filename, options) return bitmap?.let { Response(it) } ?: Response(Response.ERROR_FILE_NOT_FOUND) } private fun writeNoMediaFile(parentDir: String): Boolean { val f = File("$parentDir/.nomedia") return if (f.exists()) { true } else try { f.createNewFile() } catch (e: IOException) { false } } fun makeQuranDirectory(context: Context, widthParam: String): Boolean { val path = getQuranImagesDirectory(context, widthParam) ?: return false val directory = File(path) return if (directory.exists() && directory.isDirectory) { writeNoMediaFile(path) } else { directory.mkdirs() && writeNoMediaFile(path) } } private fun makeDirectory(path: String?): Boolean { if (path == null) { return false } val directory = File(path) return directory.exists() && directory.isDirectory || directory.mkdirs() } private fun makeQuranDatabaseDirectory(context: Context): Boolean { return makeDirectory(getQuranDatabaseDirectory(context)) } private fun makeQuranAyahDatabaseDirectory(context: Context): Boolean { return makeQuranDatabaseDirectory(context) && makeDirectory(getQuranAyahDatabaseDirectory(context)) } @WorkerThread override fun copyFromAssetsRelative(assetsPath: String, filename: String, destination: String) { val actualDestination = getQuranBaseDirectory(appContext) + destination val dir = File(actualDestination) if (!dir.exists()) { dir.mkdirs() } copyFromAssets(assetsPath, filename, actualDestination) } @WorkerThread override fun removeOldArabicDatabase(): Boolean { val databaseQuranArabicDatabase = File( getQuranDatabaseDirectory(appContext), QuranDataProvider.QURAN_ARABIC_DATABASE ) return if (databaseQuranArabicDatabase.exists()) { databaseQuranArabicDatabase.delete() } else true } @WorkerThread private fun copyFromAssets(assetsPath: String, filename: String, destination: String) { val assets = appContext.assets assets.open(assetsPath) .source() .use { source -> File(destination, filename).sink() .buffer() .use { destination -> destination.writeAll(source) } } if (filename.endsWith(".zip")) { val zipFile = destination + File.separator + filename ZipUtils.unzipFile(zipFile, destination, filename, null) // delete the zip file, since there's no need to have it twice File(zipFile).delete() } } fun getImageFromWeb( okHttpClient: OkHttpClient, context: Context, widthParam: String, filename: String ): Response { return getImageFromWeb(okHttpClient, context, widthParam, filename, false) } private fun getImageFromWeb( okHttpClient: OkHttpClient, context: Context, widthParam: String, filename: String, isRetry: Boolean ): Response { val base = if (isRetry) urlUtil.fallbackUrl(imageBaseUrl) else imageBaseUrl val urlString = (base + "width" + widthParam + File.separator + filename) Timber.d("want to download: %s", urlString) val request = Builder() .url(urlString) .build() val call = okHttpClient.newCall(request) var responseBody: ResponseBody? = null try { val response = call.execute() if (response.isSuccessful) { responseBody = response.body if (responseBody != null) { // handling for BitmapFactory.decodeStream not throwing an error // when the download is interrupted or an exception occurs. This // is taken from both Glide (see ExceptionHandlingInputStream) and // Picasso (see BitmapFactory). val exceptionCatchingSource = ExceptionCatchingSource(responseBody.source()) val bufferedSource = exceptionCatchingSource.buffer() val bitmap = decodeBitmapStream(bufferedSource.inputStream()) // throw if an error occurred while decoding the stream exceptionCatchingSource.throwIfCaught() if (bitmap != null) { var path = getQuranImagesDirectory(context, widthParam) var warning = Response.WARN_SD_CARD_NOT_FOUND if (path != null && makeQuranDirectory(context, widthParam)) { path += File.separator + filename warning = if (tryToSaveBitmap( bitmap, path ) ) 0 else Response.WARN_COULD_NOT_SAVE_FILE } return Response(bitmap, warning) } } } } catch (iioe: InterruptedIOException) { // do nothing, this is expected if the job is canceled } catch (ioe: IOException) { Timber.e(ioe, "exception downloading file") } finally { responseBody.closeQuietly() } return if (isRetry) Response( Response.ERROR_DOWNLOADING_ERROR ) else getImageFromWeb(okHttpClient, context, filename, widthParam, true) } private fun decodeBitmapStream(`is`: InputStream): Bitmap? { val options = Options() options.inPreferredConfig = ALPHA_8 return BitmapFactory.decodeStream(`is`, null, options) } private fun tryToSaveBitmap(bitmap: Bitmap, savePath: String): Boolean { var output: FileOutputStream? = null try { output = FileOutputStream(savePath) return bitmap.compress(PNG, 100, output) } catch (ioe: IOException) { // do nothing } finally { try { if (output != null) { output.flush() output.close() } } catch (e: Exception) { // ignore... } } return false } val quranBaseDirectory: String? get() = getQuranBaseDirectory(appContext) fun getQuranBaseDirectory(context: Context): String? { var basePath = QuranSettings.getInstance(context).appCustomLocation if (!isSDCardMounted) { // if our best guess suggests that we won't have access to the data due to the sdcard not // being mounted, then set the base path to null for now. if (basePath == null || basePath == Environment.getExternalStorageDirectory().absolutePath || basePath.contains(BuildConfig.APPLICATION_ID) && context.getExternalFilesDir(null) == null) { basePath = null } } if (basePath != null) { if (!basePath.endsWith(File.separator)) { basePath += File.separator } return basePath + QURAN_BASE } return null } /** * Returns the app used space in megabytes */ fun getAppUsedSpace(context: Context): Int { val baseDirectory = getQuranBaseDirectory(context) ?: return -1 val base = File(baseDirectory) val files = ArrayList<File>() files.add(base) var size: Long = 0 while (files.isNotEmpty()) { val f = files.removeAt(0) if (f.isDirectory) { val subFiles = f.listFiles() if (subFiles != null) { Collections.addAll(files, *subFiles) } } else { size += f.length() } } return (size / (1024 * 1024).toLong()).toInt() } fun getQuranDatabaseDirectory(context: Context): String? { val base = getQuranBaseDirectory(context) return if (base == null) null else base + databaseDirectory } val quranAyahDatabaseDirectory: String? get() = getQuranAyahDatabaseDirectory(appContext) fun getQuranAyahDatabaseDirectory(context: Context): String? { val base = getQuranBaseDirectory(context) return if (base == null) null else base + ayahInfoDirectory } override fun audioFileDirectory(): String? = getQuranAudioDirectory(appContext) fun getQuranAudioDirectory(context: Context): String? { var path = getQuranBaseDirectory(context) ?: return null path += audioDirectory val dir = File(path) if (!dir.exists() && !dir.mkdirs()) { return null } writeNoMediaFile(path) return path + File.separator } fun getQuranImagesBaseDirectory(context: Context): String? { val s = getQuranBaseDirectory(context) return if (s == null) null else s + imagesDirectory } private fun getQuranImagesDirectory(context: Context): String? { return getQuranImagesDirectory(context, quranScreenInfo.widthParam) } fun getQuranImagesDirectory( context: Context, widthParam: String ): String? { val base = getQuranBaseDirectory(context) return if (base == null) null else base + (if (imagesDirectory.isEmpty()) "" else imagesDirectory + File.separator) + "width" + widthParam } private fun recitationsDirectory(): String { val recitationDirectory = getQuranBaseDirectory(appContext).toString() + "recitation/" makeDirectory(recitationDirectory) return recitationDirectory } override fun recitationSessionsDirectory(): String { val sessionsDirectory = recitationsDirectory() + "sessions/" makeDirectory(sessionsDirectory) return sessionsDirectory } override fun recitationRecordingsDirectory(): String { val recordingsDirectory = recitationsDirectory() + "recordings/" makeDirectory(recordingsDirectory) return recordingsDirectory } val zipFileUrl: String get() = getZipFileUrl(quranScreenInfo.widthParam) fun getZipFileUrl(widthParam: String): String { var url = imageZipBaseUrl url += "images$widthParam.zip" return url } fun getPatchFileUrl( widthParam: String, toVersion: Int ): String { return patchBaseUrl + toVersion + "/patch" + widthParam + "_v" + toVersion + ".zip" } private val ayaPositionFileName: String get() = getAyaPositionFileName(quranScreenInfo.widthParam) fun getAyaPositionFileName(widthParam: String): String { return "ayahinfo$widthParam.db" } val ayaPositionFileUrl: String get() = getAyaPositionFileUrl(quranScreenInfo.widthParam) fun getAyaPositionFileUrl(widthParam: String): String { return ayahInfoBaseUrl + "ayahinfo" + widthParam + ".zip" } fun haveAyaPositionFile(context: Context): Boolean { val base = getQuranAyahDatabaseDirectory(context) if (base == null && !makeQuranAyahDatabaseDirectory(context)) { return false } val filename = ayaPositionFileName val ayaPositionDb = base + File.separator + filename val f = File(ayaPositionDb) return f.exists() } fun hasTranslation(context: Context, fileName: String): Boolean { var path = getQuranDatabaseDirectory(context) if (path != null) { path += File.separator + fileName return File(path) .exists() } return false } @WorkerThread override fun hasArabicSearchDatabase(): Boolean { val context = appContext if (hasTranslation(context, QuranDataProvider.QURAN_ARABIC_DATABASE)) { return true } else if (databaseDirectory != ayahInfoDirectory) { // non-hafs flavors copy their ayahinfo and arabic search database in a subdirectory, // so we copy back the arabic database into the translations directory where it can // be shared across all flavors of quran android val ayahInfoFile = File( getQuranAyahDatabaseDirectory(context), QuranDataProvider.QURAN_ARABIC_DATABASE ) val baseDir = getQuranDatabaseDirectory(context) if (ayahInfoFile.exists() && baseDir != null) { val base = File(baseDir) val translationsFile = File(base, QuranDataProvider.QURAN_ARABIC_DATABASE) if (base.exists() || base.mkdir()) { try { copyFile(ayahInfoFile, translationsFile) return true } catch (ioe: IOException) { if (!translationsFile.delete()) { Timber.e("Error deleting translations file") } } } } } return false } val arabicSearchDatabaseUrl: String get() = databaseBaseUrl + QuranDataProvider.QURAN_ARABIC_DATABASE + ".zip" fun moveAppFiles(context: Context, newLocation: String): Boolean { if (QuranSettings.getInstance(context).appCustomLocation == newLocation) { return true } val baseDir = getQuranBaseDirectory(context) ?: return false val currentDirectory = File(baseDir) val newDirectory = File(newLocation, QURAN_BASE) if (!currentDirectory.exists()) { // No files to copy, so change the app directory directly return true } else if (newDirectory.exists() || newDirectory.mkdirs()) { try { copyFileOrDirectory(currentDirectory, newDirectory) try { Timber.d("Removing $currentDirectory due to move to $newDirectory") deleteFileOrDirectory(currentDirectory) } catch (e: IOException) { // swallow silently Timber.e(e, "warning while deleting app files") } return true } catch (e: IOException) { Timber.e(e, "error moving app files") } } return false } private fun deleteFileOrDirectory(file: File) { if (file.isDirectory) { val subFiles = file.listFiles() // subFiles is null on some devices, despite this being a directory val length = subFiles?.size ?: 0 for (i in 0 until length) { val sf = subFiles!![i] if (sf.isFile) { if (!sf.delete()) { Timber.e("Error deleting %s", sf.path) } } else { deleteFileOrDirectory(sf) } } } if (!file.delete()) { Timber.e("Error deleting %s", file.path) } } private fun copyFileOrDirectory(source: File, destination: File) { if (source.isDirectory) { if (!destination.exists() && !destination.mkdirs()) { return } val files = source.listFiles() ?: throw IOException("null listFiles() output...") for (f in files) { copyFileOrDirectory(f, File(destination, f.name)) } } else { copyFile(source, destination) } } private fun copyFile(source: File, destination: File) { destination.sink().buffer().use { sink -> source.source().use { source -> sink.writeAll(source) } } } // taken from Picasso's BitmapUtils class // also Glide's ExceptionHandlingInputSource internal class ExceptionCatchingSource(delegate: Source) : ForwardingSource(delegate) { var ioException: IOException? = null @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { return try { super.read(sink, byteCount) } catch (ioe: IOException) { ioException = ioe throw ioException!! } } @Throws(IOException::class) fun throwIfCaught() { if (ioException != null) { throw ioException as IOException } } } companion object { private const val QURAN_BASE = "quran_android/" @JvmStatic fun getPageFileName(p: Int): String { val nf = NumberFormat.getInstance(Locale.US) nf.minimumIntegerDigits = 3 return "page" + nf.format(p.toLong()) + ".png" } } }
gpl-3.0
a325fca7c232497d0e684d0c6519753f
32.170623
104
0.673346
4.427129
false
false
false
false
square/sqldelight
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/compiler/model/NamedExecute.kt
1
766
package com.squareup.sqldelight.core.compiler.model import com.intellij.psi.PsiElement import com.squareup.sqldelight.core.lang.psi.StmtIdentifierMixin import com.squareup.sqldelight.core.lang.util.sqFile open class NamedExecute( identifier: StmtIdentifierMixin, statement: PsiElement ) : BindableQuery(identifier, statement) { val name = identifier.name!! override val id: Int // the sqlFile package name -> com.example. // sqlFile.name -> test.sq // name -> query name get() = idForIndex(null) internal fun idForIndex(index: Int?): Int { val postFix = if (index == null) "" else "_$index" return getUniqueQueryIdentifier( statement.sqFile().let { "${it.packageName}:${it.name}:$name$postFix" } ) } }
apache-2.0
d8d5272db76e7035c1d31be89a185696
27.37037
64
0.695822
3.868687
false
false
false
false
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/sighting/SightingIcon.kt
2
268
package nl.rsdt.japp.jotial.maps.sighting /** * @author Dingenis Sieger Sinke * @version 1.0 * @since 13-7-2016 * Description... */ object SightingIcon { val HUNT = 4 val SPOT = 3 val DEFAULT = 0 val INVALID = 2 val LAST_LOCATION = 1 }
apache-2.0
e8f5c12a9f8360b7224b196fd36ea88b
11.761905
41
0.61194
3.228916
false
false
false
false
OpenConference/OpenConference-android
app/src/main/java/com/openconference/model/backend/schedule/TimebaseScheduleDataStateDeterminer.kt
1
1670
package com.openconference.model.backend.schedule import android.content.SharedPreferences import org.threeten.bp.Instant import rx.Observable /** * This [TimebaseScheduleDataStateDeterminer] basically says that every two hours a sync will run in background * @author Hannes Dorfmann */ class TimebaseScheduleDataStateDeterminer(private val sharedPrefs: SharedPreferences, private val runAfter: Long = 2 * 3600 * 1000) : ScheduleDataStateDeterminer { companion object { val KEY_LAST_SYNC = "lastSync" val KEY_RUN_AT_LEAST_ONCE = "atLeastOnce" } override fun getScheduleSyncDataState(): Observable<ScheduleDataStateDeterminer.ScheduleDataState> = Observable.fromCallable { val atLeastOnce = sharedPrefs.getBoolean(KEY_RUN_AT_LEAST_ONCE, false) if (!atLeastOnce) { ScheduleDataStateDeterminer.ScheduleDataState.NO_DATA } else { val lastSyncMS = sharedPrefs.getLong(KEY_LAST_SYNC, 0) val lastSync = Instant.ofEpochMilli(lastSyncMS) val currentTime = currentTime() val expiresAt = lastSync.plusMillis(runAfter) if (expiresAt.isAfter(currentTime)) { ScheduleDataStateDeterminer.ScheduleDataState.UP_TO_DATE } else { ScheduleDataStateDeterminer.ScheduleDataState.RUN_BACKGROUND_SYNC } } } override fun markScheduleSyncedSuccessful(): Observable<Boolean> = Observable.fromCallable { sharedPrefs.edit() .putBoolean(KEY_RUN_AT_LEAST_ONCE, true) .putLong(KEY_LAST_SYNC, currentTime().toEpochMilli()) .commit() } fun currentTime() = Instant.now() }
apache-2.0
dda855f4675b2d6ffba2a3fad225d655
34.553191
163
0.697006
4.691011
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/entity/info/EpisodeInfo.kt
2
1065
package me.proxer.library.entity.info import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.enums.Category import me.proxer.library.enums.MediaLanguage /** * Entity containing information about the available episodes or chapters of an [Entry]. * * @property firstEpisode The first available episode. * @property lastEpisode The last available episode. * @property category The category of the associated media entry. * @property availableLanguages The available languages. * @property userProgress The progress, the user has made on this media entry so far. * @property episodes The actual list of episodes. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class EpisodeInfo( @Json(name = "start") val firstEpisode: Int, @Json(name = "end") val lastEpisode: Int, @Json(name = "kat") val category: Category, @Json(name = "lang") val availableLanguages: Set<MediaLanguage>, @Json(name = "state") val userProgress: Int?, @Json(name = "episodes") val episodes: List<Episode> )
gpl-3.0
29a55c8e3f152fa2ecb73f3b1e83a7cb
37.035714
88
0.744601
3.988764
false
false
false
false
NephyProject/Penicillin
src/main/kotlin/jp/nephy/penicillin/endpoints/blocks/ListUsers.kt
1
3622
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.blocks import jp.nephy.penicillin.core.request.action.CursorJsonObjectApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.get import jp.nephy.penicillin.endpoints.Blocks import jp.nephy.penicillin.endpoints.Option import jp.nephy.penicillin.models.cursor.CursorUsers /** * Returns a collection of [user objects](https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/user-object) that the authenticating user is blocking. * * **Important** This method is cursored, meaning your app must make multiple requests in order to receive all blocks correctly. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more details on how cursoring works. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/mute-block-report-users/api-reference/get-blocks-list) * * @param includeEntities Optional. The entities node will not be included when set to false. * @param skipStatus Optional. When set to either true, t or 1 statuses will not be included in the returned user objects. * @param cursor Semi-Optional. Causes the list of blocked users to be broken into pages of no more than 5000 IDs at a time. The number of IDs returned is not guaranteed to be 5000 as suspended users are filtered out after connections are queried. If no cursor is provided, a value of -1 will be assumed, which is the first "page." The response from the API will include a previous_cursor and next_cursor to allow paging back and forth. See [Using cursors to navigate collections](https://developer.twitter.com/en/docs/basics/cursoring) for more information. * @param options Optional. Custom parameters of this request. * @receiver [Blocks] endpoint instance. * @return [CursorJsonObjectApiAction] for [CursorUsers] model. */ fun Blocks.listUsers( includeEntities: Boolean? = null, skipStatus: Boolean? = null, cursor: Long? = null, vararg options: Option ) = client.session.get("/1.1/blocks/list.json") { parameters( "include_entities" to includeEntities, "skip_status" to skipStatus, "cursor" to cursor, *options ) }.cursorJsonObject<CursorUsers>() /** * Shorthand extension property to [Blocks.listUsers]. * @see Blocks.listUsers */ val Blocks.listUsers get() = listUsers()
mit
9a37173984f8b010c2c7a8b338329d9b
51.492754
558
0.760077
4.256169
false
false
false
false
bk138/multivnc
android/app/src/main/java/com/coboltforge/dontmind/multivnc/MetaList.kt
1
453
package com.coboltforge.dontmind.multivnc import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.serialization.Serializable @Serializable @Entity(tableName = "META_LIST") data class MetaList( @JvmField @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") var id: Long = 0, @JvmField @ColumnInfo(name = "NAME") var name: String? = null )
gpl-3.0
b3e2ac20ae4045ddd42f122481c5ab67
22.894737
41
0.684327
3.973684
false
false
false
false
tingtingths/jukebot
app/src/main/java/com/jukebot/jukebot/Jukebot.kt
1
2626
package com.jukebot.jukebot import android.app.Application import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.preference.PreferenceManager import com.jukebot.jukebot.logging.Logger import com.jukebot.jukebot.manager.MessageManager import com.jukebot.jukebot.storage.PersistentStorage import com.jukebot.jukebot.storage.VolatileStorage import com.jukebot.jukebot.telegram.Bot import com.pengrad.telegrambot.request.SendMessage /** * Created by Ting. */ class Jukebot : Application() { companion object { lateinit var ctx: Context private set lateinit var listener: SharedPreferences.OnSharedPreferenceChangeListener } override fun onCreate() { super.onCreate() Jukebot.ctx = applicationContext val chatId = PersistentStorage.get(Constant.KEY_VERIFIED_CHAT_ID) if (chatId is String && !chatId.isNullOrEmpty()) { try { val id: Long = chatId.toLong() VolatileStorage.put(Constant.KEY_VERIFIED_CHAT_ID, id) } catch (e: Exception) { PersistentStorage.remove(Constant.KEY_VERIFIED_CHAT_ID) } } val botToken = PersistentStorage.get(Constant.KEY_BOT_TOKEN) if (botToken is String && !botToken.isNullOrEmpty()) { Logger.log(this.javaClass.simpleName, "token=${PersistentStorage.get(Constant.KEY_BOT_TOKEN)}") startService(Intent(this, Bot::class.java).putExtra("token", PersistentStorage.get(Constant.KEY_BOT_TOKEN) as String)) } val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ctx) listener = SharedPreferences.OnSharedPreferenceChangeListener { pref, key -> Logger.log(this.javaClass.simpleName, "pref change, key=$key") if (key == Constant.KEY_BOT_TOKEN && !pref.getString(key, null).isNullOrEmpty()) { stopService(Intent(this, Bot::class.java)) startService(Intent(this, Bot::class.java).putExtra("token", PersistentStorage.get(Constant.KEY_BOT_TOKEN) as String)) } if (key == Constant.KEY_AUTH_CHAT_PASSWD && !pref.getString(key, null).isNullOrEmpty()) { MessageManager.enqueue(Pair(SendMessage(VolatileStorage.get(Constant.KEY_VERIFIED_CHAT_ID), "Unbind..."), null)) VolatileStorage.remove(Constant.KEY_VERIFIED_CHAT_ID) PersistentStorage.remove(Constant.KEY_VERIFIED_CHAT_ID) } } sharedPrefs.registerOnSharedPreferenceChangeListener(listener) } }
mit
1559f6ca401b5d3692b5649b11c91f93
40.03125
134
0.67936
4.527586
false
false
false
false
lena0204/Plattenspieler
app/src/main/java/com/lk/plattenspieler/utils/LyricsAccess.kt
1
3987
package com.lk.plattenspieler.utils import android.util.Log import org.jaudiotagger.audio.AudioFileIO import org.jaudiotagger.audio.mp3.MP3File import org.jaudiotagger.tag.FieldKey import org.jaudiotagger.tag.id3.ID3v24FieldKey import org.jaudiotagger.tag.id3.ID3v24Tag import org.jaudiotagger.tag.mp4.Mp4FieldKey import org.jaudiotagger.tag.mp4.Mp4Tag import java.io.* /** * Erstellt von Lena am 13.05.18. * Lesender und schreibender Zugriff auf die Liedtexte eines Liedes über eine externe Bibliothek */ object LyricsAccess { private val TAG = this.javaClass.simpleName private var currentLyrics = "" fun readLyrics(filepath: String): String { Log.d(TAG, filepath) currentLyrics = "" if(filepath.contains("mp3")){ readMP3Lyrics(filepath) } else if(filepath.contains("m4a")) { readM4ALyrics(filepath) } return currentLyrics } // TESTING_ refactoring and test m4a files fun readLyrics(inputStream: InputStream, fileType: String): String { try { val file = File.createTempFile("musicFile", ".$fileType") val fileOutputStream = FileOutputStream(file) fileOutputStream.write(inputStream.readBytes()) fileOutputStream.close() inputStream.close() currentLyrics = "" if (fileType == "mp3") { readMP3Lyrics(file) } else if (fileType == "m4a") { readM4ALyrics(file) } // Lyrics editor might add carriage return (\r) instead of new line currentLyrics = currentLyrics.replace("\r", "\n") } catch(e: Exception) { Log.e(TAG, "Error in reading lyrics") e.printStackTrace() } return currentLyrics } private fun readMP3Lyrics(filepath: String) { readMP3Lyrics(File(filepath)) } private fun readMP3Lyrics(file: File) { val mp3File = AudioFileIO.read(file) as MP3File if(mp3File.hasID3v2Tag()) { val lyrics = mp3File.iD3v2TagAsv24.getFirst(ID3v24FieldKey.LYRICS) if (!lyrics.isNullOrEmpty()) { currentLyrics = lyrics } } } private fun readM4ALyrics(filepath: String) { readM4ALyrics(File(filepath)) } private fun readM4ALyrics(file: File) { val m4aTag = AudioFileIO.read(file).tag as Mp4Tag val lyrics = m4aTag.getFirst(Mp4FieldKey.LYRICS) if(!lyrics.isNullOrEmpty()){ currentLyrics = lyrics } } // PROBLEM_ schreiben auf die SD-Karte ist nicht unbedingt ohne weiteres möglich ... // Nutzer informieren, wenn schreiben der Lyrics fehlgeschlagen ist, geeignete Rückgabe !! /*fun writeLyrics(lyrics: String, datapath: String){ if(datapath != ""){ Log.i(TAG, datapath) if(datapath.contains("mp3")){ writeLyricsForMP3File(datapath, lyrics) } else if(datapath.contains("m4a")) { writeLyricsForM4AFile(datapath, lyrics) } } } private fun writeLyricsForMP3File(path: String, lyrics: String){ try { val mp3File = AudioFileIO.read(File(path)) val mp3Tag = mp3File.tag if (!mp3Tag.isEmpty && mp3Tag is ID3v24Tag) { mp3Tag.setField(FieldKey.LYRICS, lyrics) mp3File.tag = mp3Tag } else { Log.w(TAG, "Kein ID3v2 Tag vorhanden, keine Lyrics geschrieben.") } AudioFileIO.write(mp3File) } catch(ex: Exception){ Log.e(TAG, ex.message ?: "No error message") } } private fun writeLyricsForM4AFile(path: String, lyrics: String){ // m4a Datei // muss getestet werden -> auch Problem mit SD-Karte val m4aTag = AudioFileIO.read(File(path)).tag as Mp4Tag m4aTag.setField(Mp4FieldKey.LYRICS, lyrics) }*/ }
gpl-3.0
a00fdfc60f2bdfaebd01f620f76aefbe
32.762712
96
0.609187
3.635036
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/settings/manager/DefaultPreferenceManager.kt
1
5250
package com.arcao.geocaching4locus.settings.manager import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit import androidx.preference.PreferenceManager import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.constants.PrefConstants import com.arcao.geocaching4locus.base.util.getParsedFloat import com.arcao.geocaching4locus.base.util.getParsedInt import kotlin.math.max import kotlin.math.min class DefaultPreferenceManager( context: Context ) { private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) val showLiveMapDisabledNotification get() = preferences.getBoolean(PrefConstants.SHOW_LIVE_MAP_DISABLED_NOTIFICATION, false) val hideGeocachesOnLiveMapDisabled get() = preferences.getBoolean(PrefConstants.LIVE_MAP_HIDE_CACHES_ON_DISABLED, false) val disableDnfNmNaGeocaches get() = preferences.getBoolean(PrefConstants.DOWNLOADING_DISABLE_DNF_NM_NA_CACHES, false) val disableDnfNmNaGeocachesThreshold get() = preferences.getInt(PrefConstants.DOWNLOADING_DISABLE_DNF_NM_NA_CACHES_LOGS_COUNT, 1) var liveMapLastRequests get() = preferences.getInt(PrefConstants.LIVE_MAP_LAST_REQUESTS, 0) set(value) = preferences.edit { putInt(PrefConstants.LIVE_MAP_LAST_REQUESTS, value) } val downloadingGeocacheLogsCount get() = preferences.getInt(PrefConstants.DOWNLOADING_COUNT_OF_LOGS, 5) val downloadLogsUpdateCache get() = preferences.getBoolean(PrefConstants.DOWNLOAD_LOGS_UPDATE_CACHE, true) val downloadFullGeocacheOnShow get() = PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_ONCE == preferences.getString( PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW, PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_ONCE ) val downloadGeocacheOnShow get() = PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_NEVER != preferences.getString( PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW, PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_ONCE ) val downloadDistanceMeters: Int get() { val imperialUnits = useImperialUnits val defaultValue = if (imperialUnits) { AppConstants.DISTANCE_MILES_DEFAULT } else { AppConstants.DISTANCE_KM_DEFAULT } var distance = preferences.getParsedFloat(PrefConstants.FILTER_DISTANCE, defaultValue) if (imperialUnits) { // to metric units [km] distance *= AppConstants.MILES_PER_KILOMETER } // to meters [m] distance *= 1000 // fix for min and max distance error in Geocaching Live API return max(min(distance.toInt(), AppConstants.DISTANCE_MAX_METERS), AppConstants.DISTANCE_MIN_METERS) } var lastLatitude: Double get() = preferences.getFloat(PrefConstants.LAST_LATITUDE, Float.NaN).toDouble() set(value) = preferences.edit { putFloat(PrefConstants.LAST_LATITUDE, value.toFloat()) } var lastLongitude: Double get() = preferences.getFloat(PrefConstants.LAST_LONGITUDE, Float.NaN).toDouble() set(value) = preferences.edit { putFloat(PrefConstants.LAST_LONGITUDE, value.toFloat()) } var downloadingGeocachesCount: Int get() { var value = preferences.getInt( PrefConstants.DOWNLOADING_COUNT_OF_CACHES, AppConstants.DOWNLOADING_COUNT_OF_CACHES_DEFAULT ) val step = downloadingGeocachesCountStep if (value > MAX_GEOCACHES_COUNT) { value = MAX_GEOCACHES_COUNT preferences.edit().putInt(PrefConstants.DOWNLOADING_COUNT_OF_CACHES, value).apply() } if (value % step != 0) { value = (value / step + 1) * step preferences.edit().putInt(PrefConstants.DOWNLOADING_COUNT_OF_CACHES, value).apply() } return value } set(value) { val step = downloadingGeocachesCountStep val correctValue = when { value > MAX_GEOCACHES_COUNT -> MAX_GEOCACHES_COUNT value % step != 0 -> (value / step + 1) * step else -> value } preferences.edit().putInt(PrefConstants.DOWNLOADING_COUNT_OF_CACHES, correctValue).apply() } val downloadingGeocachesCountStep: Int get() = preferences.getParsedInt( PrefConstants.DOWNLOADING_COUNT_OF_CACHES_STEP, AppConstants.DOWNLOADING_COUNT_OF_CACHES_STEP_DEFAULT ) private val useImperialUnits: Boolean get() = preferences.getBoolean(PrefConstants.IMPERIAL_UNITS, false) companion object { val MAX_GEOCACHES_COUNT: Int get() = if (Runtime.getRuntime().maxMemory() <= AppConstants.LOW_MEMORY_THRESHOLD) { AppConstants.DOWNLOADING_COUNT_OF_CACHES_MAX_LOW_MEMORY } else { AppConstants.DOWNLOADING_COUNT_OF_CACHES_MAX } } }
gpl-3.0
d38271f2e61744a30fc2d913bbe8702a
38.473684
113
0.664952
4.464286
false
false
false
false
santirivera92/wtnv-android
app/src/main/java/com/razielsarafan/wtnv/api/WTNVApi.kt
1
5164
package com.razielsarafan.wtnv.api import android.app.Application import android.content.Context import com.google.gson.ExclusionStrategy import com.google.gson.FieldAttributes import com.google.gson.Gson import com.google.gson.GsonBuilder import com.razielsarafan.wtnv.api.utils.StringConverter import com.razielsarafan.wtnv.model.Episode import com.razielsarafan.wtnv.model.Transcript import io.realm.Realm import io.realm.RealmConfiguration import retrofit.Callback import retrofit.RestAdapter import retrofit.RetrofitError import retrofit.client.Response import retrofit.converter.GsonConverter import java.util.* class WTNVApi private constructor(context: Context) { private val wtnvInterface: EpisodesInterface private val transcriptsInterface: TranscriptsInterface private val app: Application private val realm: Realm init { val gson = GsonBuilder().setExclusionStrategies(object : ExclusionStrategy { override fun shouldSkipField(f: FieldAttributes): Boolean { return f.getDeclaredClass().equals(Episode::class.java) } override fun shouldSkipClass(clazz: Class<*>?): Boolean { return false } }) .create(); val gsonConverter = GsonConverter(gson) wtnvInterface = RestAdapter.Builder().setEndpoint("https://raw.githubusercontent.com/santirivera92/wtnv-json/master").setConverter(gsonConverter).build().create(EpisodesInterface::class.java) transcriptsInterface = RestAdapter.Builder().setEndpoint("https://raw.githubusercontent.com/santirivera92/wtnv-json/master").setConverter(StringConverter()).build().create(TranscriptsInterface::class.java) app = context.applicationContext as Application val config = RealmConfiguration.Builder(app) .name("wtnv.realm") .deleteRealmIfMigrationNeeded() .build(); realm = Realm.getInstance(config) } fun getTranscriptForInterface(transcriptId: String, callback: Callback<Transcript>) { val transcript = getTranscriptFromPreferences(transcriptId) if (transcript != null) { callback.success(transcript, null) } else { transcriptsInterface.getTranscriptForId(transcriptId, object : Callback<String> { override fun success(s: String, response: Response) { val transcriptObj = Transcript(transcriptId, s) writeTranscriptToPreferences(transcriptObj) callback.success(transcriptObj, response) } override fun failure(error: RetrofitError) { callback.failure(error) } }) } } fun downloadTranscriptsForList(list: List<Episode>) { list.forEach { transcriptsInterface.getTranscriptForId(it.transcript, object : Callback<String> { override fun success(s: String, response: Response) { val transcript = Transcript(it.transcript, s) writeTranscriptToPreferences(transcript) } override fun failure(error: RetrofitError) { } }) } } fun getEpisodeList(callback: Callback<List<Episode>>) { val episodeList = listFromPreferences() if (episodeList.size != 0) { callback.success(episodeList, null) } else { wtnvInterface.getAllEpisodes(object : Callback<List<Episode>> { override fun success(episodes: List<Episode>, response: Response) { writeListToPreferences(episodes) callback.success(episodes, response) } override fun failure(error: RetrofitError) { callback.failure(error) } }) } } fun forceLoadEpisodeList(callback: Callback<List<Episode>>) { writeListToPreferences(ArrayList<Episode>()) getEpisodeList(callback) } private fun listFromPreferences(): List<Episode> { try { return realm.where(Episode::class.java).findAll() } catch (e: Exception) { return ArrayList() } } private fun writeListToPreferences(list: List<Episode>) { realm.beginTransaction() list.forEach { realm.copyToRealmOrUpdate(it) } realm.commitTransaction() } private fun getTranscriptFromPreferences(id: String): Transcript? { var transcript = realm.where(Transcript::class.java).equalTo("id", id).findFirst() return transcript } private fun writeTranscriptToPreferences(transcript: Transcript) { realm.beginTransaction() realm.copyToRealmOrUpdate(transcript) realm.commitTransaction() } companion object { private var instance: WTNVApi? = null fun getInstance(context: Context): WTNVApi { if (instance == null) { instance = WTNVApi(context) } return instance!! } } }
gpl-2.0
3a914dd6070c73f3c14002d0a6ca0157
34.369863
213
0.635167
4.885525
false
false
false
false
jitsi/jibri
src/main/kotlin/org/jitsi/jibri/util/ProcessStatePublisher.kt
1
5967
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jibri.util import org.jitsi.jibri.util.extensions.scheduleAtFixedRate import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger import java.time.Duration import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong /** * [ProcessStatePublisher] is responsible for publishing a [ProcessState] every time: * 1) The process writes a line of output (to stdout/stderr) * 2) If the process hasn't written any output in [NO_OUTPUT_TIMEOUT], then we'll check its alive state * and publish a [ProcessState] with its current alive state and its most recent line of output */ class ProcessStatePublisher( parentLogger: Logger, private val name: String, private val process: ProcessWrapper ) : StatusPublisher<ProcessState>() { private val logger = createChildLogger(parentLogger) private val tail: PublishingTail private var recurringProcessAliveTask: ScheduledFuture<*>? = null private var lastStatusUpdateTimestamp = AtomicLong(0) private val processRunningState: AliveState get() { return if (process.isAlive) { ProcessRunning() } else { ProcessExited(process.exitValue) } } companion object { private val NO_OUTPUT_TIMEOUT = Duration.ofSeconds(2) } init { tail = LoggingUtils.createPublishingTail(process.getOutput(), this::onProcessOutput) startProcessAliveChecks() } private fun onProcessOutput(output: String) { lastStatusUpdateTimestamp.set(System.currentTimeMillis()) // In this event-driven process output handler (which is invoked for every line of the process' output // we read) we always denote the process' state as running. The reason for this is that there is an out-of-sync // problem between the log line we read and the process' current state: the log lines will always be delayed // in comparison to the process' current state (running or exited). Rather than be misleading and publish // a status with a state of exited but a log line that was written at some point when the process was still // running, we always state that the process is running here. When the process actually is dead, it won't // write anymore and the timer-based check (from startProcessAliveChecks below) will get the process' last line // and publish its true running/exited state. Note that this does not prevent other code from parsing an // output line that clearly denotes the process has exited and reacting appropriately. publishStatus(ProcessState(ProcessRunning(), output)) } /** * We publish status updates based on every line the process writes to stdout. But it's possible it could be * killed and no longer write anything, so we need to separately monitor if the process is alive or not. * * We'll publish an update on whether or not it's alive if we haven't based on the stdout checks for over 2 * seconds. */ private fun startProcessAliveChecks() { recurringProcessAliveTask = TaskPools.recurringTasksPool.scheduleAtFixedRate(2, TimeUnit.SECONDS, 5) { val timeSinceLastStatusUpdate = Duration.ofMillis(System.currentTimeMillis() - lastStatusUpdateTimestamp.get()) if (timeSinceLastStatusUpdate > Duration.ofSeconds(2)) { logger.debug { "Process $name hasn't written in 2 seconds, publishing periodic update" } ProcessState(processRunningState, tail.mostRecentLine).also { TaskPools.ioPool.submit { // We fire all state transitions in the ioPool, otherwise we may try and cancel the // processAliveChecks from within the thread it was executing in. Another solution would've been // to pass 'false' to recurringProcessAliveTask.cancel, but it felt cleaner to separate the threads publishStatus(it) } } } } } fun stop() { recurringProcessAliveTask?.cancel(true) // TODO: not calling 'tail.stop()' results in us processing ffmpeg's--for example--successful // exit, which causes a 'finished' state update to propagate up and results in a duplicate 'stopService' // call in JibriManager, since we have to call stopService after we receive finish (to handle the case // of the service detecting an empty call, for example) and we can't distinguish a 'finished' state // from an actual jibri service finishing on its own and the one that results from any call to // 'stop' when ffmpeg exits. Calling 'tail.stop()' here fixes that behavior, but, i don't // think that's what we want to do: instead we should be processing every log message a process // writes to ensure that it exits correctly. In addition to that, we should technically be modeling // the 'stop' flow differently to be something more like: tell everything to stop and then *ensure* // it all stopped cleanly and correctly and, if anything didn't, log an error (and perhaps update // the health state) } }
apache-2.0
7c39f8b985261668f06d25a0b87b40a2
51.80531
123
0.69214
4.691038
false
false
false
false
MaibornWolff/codecharta
analysis/filter/MergeFilter/src/test/kotlin/de/maibornwolff/codecharta/filter/mergefilter/ParserDialogTest.kt
1
2325
package de.maibornwolff.codecharta.filter.mergefilter import com.github.kinquirer.KInquirer import com.github.kinquirer.components.promptConfirm import com.github.kinquirer.components.promptInput import io.mockk.every import io.mockk.mockkStatic import io.mockk.unmockkAll import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import picocli.CommandLine import java.io.File @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ParserDialogTest { @AfterAll fun afterTest() { unmockkAll() } @Test fun `should output correct arguments`() { val inputFolderName = "folder" val outputFileName = "sampleOutputFile" val compress = false val addMissing = false val recursive = false val leaf = false val ignoreCase = false mockkStatic("com.github.kinquirer.components.InputKt") every { KInquirer.promptInput(any(), any(), any()) } returns inputFolderName andThen outputFileName mockkStatic("com.github.kinquirer.components.ConfirmKt") every { KInquirer.promptConfirm(any(), any()) } returns compress andThen addMissing andThen recursive andThen leaf andThen ignoreCase val parserArguments = ParserDialog.collectParserArgs() val commandLine = CommandLine(MergeFilter()) val parseResult = commandLine.parseArgs(*parserArguments.toTypedArray()) assertThat(parseResult.matchedPositional(0).getValue<Array<File>>().map { it.name }).isEqualTo( listOf( inputFolderName ) ) assertThat(parseResult.matchedOption("output-file").getValue<String>()).isEqualTo(outputFileName) assertThat(parseResult.matchedOption("not-compressed").getValue<Boolean>()).isEqualTo(compress) assertThat(parseResult.matchedOption("add-missing").getValue<Boolean>()).isEqualTo(addMissing) assertThat(parseResult.matchedOption("recursive").getValue<Boolean>()).isEqualTo(recursive) assertThat(parseResult.matchedOption("leaf").getValue<Boolean>()).isEqualTo(leaf) assertThat(parseResult.matchedOption("ignore-case").getValue<Boolean>()).isEqualTo(ignoreCase) } }
bsd-3-clause
f5cec63bf507eef45f98e9e77155240e
38.40678
105
0.713548
4.925847
false
true
false
false
danrien/projectBlue
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/media/files/list/FileListActivity.kt
1
6928
package com.lasthopesoftware.bluewater.client.browsing.items.media.files.list import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ProgressBar import android.widget.ViewAnimator import androidx.appcompat.app.AppCompatActivity import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.lasthopesoftware.bluewater.R import com.lasthopesoftware.bluewater.client.browsing.items.IItem import com.lasthopesoftware.bluewater.client.browsing.items.Item import com.lasthopesoftware.bluewater.client.browsing.items.list.IItemListViewContainer import com.lasthopesoftware.bluewater.client.browsing.items.list.menus.changes.handlers.ItemListMenuChangeHandler import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.FileProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListProvider import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemMenuBuilder import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemNowPlayingRegistrar import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener import com.lasthopesoftware.bluewater.client.browsing.items.menu.handlers.ViewChangedHandler import com.lasthopesoftware.bluewater.client.connection.HandleViewIoException import com.lasthopesoftware.bluewater.client.connection.selected.InstantiateSelectedConnectionActivity.Companion.restoreSelectedConnection import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionProvider import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFileProvider.Companion.fromActiveLibrary import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFloatingActionButton import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.NowPlayingFloatingActionButton.Companion.addNowPlayingFloatingActionButton import com.lasthopesoftware.bluewater.shared.MagicPropertyBuilder import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils import com.lasthopesoftware.bluewater.shared.exceptions.UnexpectedExceptionToasterResponse import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise class FileListActivity : AppCompatActivity(), IItemListViewContainer, Runnable { private val lazyFileProvider = lazy { val stringListProvider = FileStringListProvider(SelectedConnectionProvider(this)) FileProvider(stringListProvider) } private val pbLoading = LazyViewFinder<ProgressBar>(this, R.id.recyclerLoadingProgress) private val fileListView = LazyViewFinder<RecyclerView>(this, R.id.loadedRecyclerView) private lateinit var nowPlayingFloatingActionButton: NowPlayingFloatingActionButton private var itemId = 0 private var viewAnimator: ViewAnimator? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_list_view) setSupportActionBar(findViewById(R.id.listViewToolbar)) supportActionBar?.setDisplayHomeAsUpEnabled(true) fileListView.findView().visibility = View.INVISIBLE pbLoading.findView().visibility = View.VISIBLE if (savedInstanceState != null) itemId = savedInstanceState.getInt(key) if (itemId == 0) itemId = this.intent.getIntExtra(key, 1) title = intent.getStringExtra(value) nowPlayingFloatingActionButton = addNowPlayingFloatingActionButton(findViewById(R.id.asynchronousRecyclerViewContainer)) run() } override fun run() { val parameters = FileListParameters.getInstance().getFileListParameters(Item(itemId)) lazyFileProvider.value.promiseFiles(FileListParameters.Options.None, *parameters) .eventually { serviceFiles -> fromActiveLibrary(this) .eventually(LoopedInPromise.response({ l -> l?.let { nowPlayingFileProvider -> val fileListItemMenuBuilder = FileListItemMenuBuilder( serviceFiles, nowPlayingFileProvider, FileListItemNowPlayingRegistrar(LocalBroadcastManager.getInstance(this)) ) ItemListMenuChangeHandler(this).apply { fileListItemMenuBuilder.setOnViewChangedListener( ViewChangedHandler() .setOnViewChangedListener(this) .setOnAnyMenuShown(this) .setOnAllMenusHidden(this) ) } val fileListView = fileListView.findView() fileListView.adapter = FileListAdapter(serviceFiles, fileListItemMenuBuilder) val layoutManager = LinearLayoutManager(this) fileListView.layoutManager = layoutManager fileListView.addItemDecoration(DividerItemDecoration(this, layoutManager.orientation)) fileListView.visibility = View.VISIBLE pbLoading.findView().visibility = View.INVISIBLE } }, this)) } .excuse(HandleViewIoException(this, this)) .eventuallyExcuse(LoopedInPromise.response(UnexpectedExceptionToasterResponse(this), this)) .then { finish() } } public override fun onStart() { super.onStart() restoreSelectedConnection(this) } public override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putInt(key, itemId) } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) itemId = savedInstanceState.getInt(key) } override fun onCreateOptionsMenu(menu: Menu) = ViewUtils.buildStandardMenu(this, menu) override fun onOptionsItemSelected(item: MenuItem) = ViewUtils.handleNavMenuClicks(this, item) || super.onOptionsItemSelected(item) override fun onBackPressed() { if (LongClickViewAnimatorListener.tryFlipToPreviousView(viewAnimator)) return super.onBackPressed() } override fun updateViewAnimator(viewAnimator: ViewAnimator) { this.viewAnimator = viewAnimator } override fun getNowPlayingFloatingActionButton() = nowPlayingFloatingActionButton companion object { private val magicPropertyBuilder = MagicPropertyBuilder(FileListActivity::class.java) private val key = magicPropertyBuilder.buildProperty("key") private val value = magicPropertyBuilder.buildProperty("value") @JvmStatic fun startFileListActivity(context: Context, item: IItem) { val fileListIntent = Intent(context, FileListActivity::class.java) fileListIntent.putExtra(key, item.key) fileListIntent.putExtra(value, item.value) context.startActivity(fileListIntent) } } }
lgpl-3.0
d3a32bba32506c2e60747edd7a9a1284
43.127389
144
0.82347
4.681081
false
false
false
false
mastizada/focus-android
app/src/main/java/org/mozilla/focus/utils/FileUtils.kt
3
1729
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * 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.utils import android.content.Context import java.io.File // WebView directory and contents. private const val WEBVIEW_DIRECTORY = "app_webview" private const val LOCAL_STORAGE_DIR = "Local Storage" // Cache directory contents. private const val WEBVIEW_CACHE_DIR = "org.chromium.android_webview" class FileUtils { companion object { @JvmStatic fun truncateCacheDirectory(context: Context) = deleteContent(context.cacheDir, doNotEraseWhitelist = setOf( // If the folder or its contents are deleted, WebView will stop using the disk cache entirely. WEBVIEW_CACHE_DIR )) @JvmStatic fun deleteWebViewDirectory(context: Context): Boolean { val webviewDirectory = File(context.applicationInfo.dataDir, WEBVIEW_DIRECTORY) return deleteContent(webviewDirectory, doNotEraseWhitelist = setOf( // If the folder or its contents is deleted, WebStorage.deleteAllData does not clear Local Storage // in memory. LOCAL_STORAGE_DIR )) } private fun deleteContent(directory: File, doNotEraseWhitelist: Set<String> = emptySet()): Boolean { val filesToDelete = directory.listFiles()?.filter { !doNotEraseWhitelist.contains(it.name) } ?: return false return filesToDelete.all { it.deleteRecursively() } } } }
mpl-2.0
6944d0f170b16f56062cd2a4f8c63323
41.170732
120
0.669173
4.479275
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/activity/Reading.kt
1
32846
package com.newsblur.activity import android.content.Intent import android.content.res.Configuration import android.database.Cursor import android.os.Bundle import android.util.Log import android.view.KeyEvent import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.fragment.app.FragmentManager import androidx.fragment.app.commit import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.viewpager.widget.ViewPager import androidx.viewpager.widget.ViewPager.OnPageChangeListener import com.google.android.material.progressindicator.CircularProgressIndicator import com.newsblur.R import com.newsblur.database.ReadingAdapter import com.newsblur.databinding.ActivityReadingBinding import com.newsblur.di.IconLoader import com.newsblur.domain.Story import com.newsblur.fragment.ReadingItemFragment import com.newsblur.fragment.ReadingPagerFragment import com.newsblur.service.NBSyncReceiver.Companion.UPDATE_REBUILD import com.newsblur.service.NBSyncReceiver.Companion.UPDATE_STATUS import com.newsblur.service.NBSyncReceiver.Companion.UPDATE_STORY import com.newsblur.service.NBSyncService import com.newsblur.util.* import com.newsblur.util.PrefConstants.ThemeValue import com.newsblur.view.ReadingScrollView.ScrollChangeListener import com.newsblur.viewModel.StoriesViewModel import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import java.lang.Runnable import javax.inject.Inject import kotlin.math.abs @AndroidEntryPoint abstract class Reading : NbActivity(), OnPageChangeListener, ScrollChangeListener { @Inject lateinit var feedUtils: FeedUtils @Inject @IconLoader lateinit var iconLoader: ImageLoader @JvmField var fs: FeedSet? = null private var stories: Cursor? = null // Activities navigate to a particular story by hash. // We can find it once we have the cursor. private var storyHash: String? = null private var pager: ViewPager? = null private var readingAdapter: ReadingAdapter? = null private var stopLoading = false private var unreadSearchActive = false // mark story as read behavior private var markStoryReadJob: Job? = null private lateinit var markStoryReadBehavior: MarkStoryReadBehavior // unread count for the circular progress overlay. set to nonzero to activate the progress indicator overlay private var startingUnreadCount = 0 private var overlayRangeTopPx = 0f private var overlayRangeBotPx = 0f private var lastVScrollPos = 0 // enabling multi window mode from recent apps on the device // creates a different activity lifecycle compared to a device rotation // resulting in onPause being called when the app is actually on the screen. // calling onPause sets stopLoading as true and content wouldn't be loaded. // track the multi window mode config change and skip stopLoading in first onPause call. // refactor stopLoading mechanism as a cancellation signal tied to the view lifecycle. private var isMultiWindowModeHack = false private val pageHistory = mutableListOf<Story>() private lateinit var volumeKeyNavigation: VolumeKeyNavigation private lateinit var intelState: StateFilter private lateinit var binding: ActivityReadingBinding private lateinit var storiesViewModel: StoriesViewModel override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) } override fun onCreate(savedInstanceBundle: Bundle?) { super.onCreate(savedInstanceBundle) storiesViewModel = ViewModelProvider(this).get(StoriesViewModel::class.java) binding = ActivityReadingBinding.inflate(layoutInflater) setContentView(binding.root) try { fs = intent.getSerializableExtra(EXTRA_FEEDSET) as FeedSet? } catch (re: RuntimeException) { // in the wild, the notification system likes to pass us an Intent that has missing or very stale // Serializable extras. com.newsblur.util.Log.e(this, "failed to unfreeze required extras", re) finish() return } if (fs == null) { com.newsblur.util.Log.w(this.javaClass.name, "reading view had no FeedSet") finish() return } if (savedInstanceBundle != null && savedInstanceBundle.containsKey(BUNDLE_STARTING_UNREAD)) { startingUnreadCount = savedInstanceBundle.getInt(BUNDLE_STARTING_UNREAD) } // Only use the storyHash the first time the activity is loaded. Ignore when // recreated due to rotation etc. storyHash = if (savedInstanceBundle == null) { intent.getStringExtra(EXTRA_STORY_HASH) } else { savedInstanceBundle.getString(EXTRA_STORY_HASH) } intelState = PrefsUtils.getStateFilter(this) volumeKeyNavigation = PrefsUtils.getVolumeKeyNavigation(this) markStoryReadBehavior = PrefsUtils.getMarkStoryReadBehavior(this) setupViews() setupListeners() setupObservers() getActiveStoriesCursor(true) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (storyHash != null) { outState.putString(EXTRA_STORY_HASH, storyHash) } else if (pager != null) { val currentItem = pager!!.currentItem val story = readingAdapter!!.getStory(currentItem) if (story != null) { outState.putString(EXTRA_STORY_HASH, story.storyHash) } } if (startingUnreadCount != 0) { outState.putInt(BUNDLE_STARTING_UNREAD, startingUnreadCount) } } override fun onResume() { super.onResume() if (NBSyncService.isHousekeepingRunning()) finish() // this view shows stories, it is not safe to perform cleanup stopLoading = false // this is not strictly necessary, since our first refresh with the fs will swap in // the correct session, but that can be delayed by sync backup, so we try here to // reduce UI lag, or in case somehow we got redisplayed in a zero-story state feedUtils.prepareReadingSession(fs, false) } override fun onPause() { super.onPause() if (isMultiWindowModeHack) { isMultiWindowModeHack = false } else { stopLoading = true } } override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration) { super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig) isMultiWindowModeHack = isInMultiWindowMode } private fun setupViews() { // this value is expensive to compute but doesn't change during a single runtime overlayRangeTopPx = UIUtils.dp2px(this, OVERLAY_RANGE_TOP_DP).toFloat() overlayRangeBotPx = UIUtils.dp2px(this, OVERLAY_RANGE_BOT_DP).toFloat() ViewUtils.setViewElevation(binding.readingOverlayLeft, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlayRight, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlayText, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlaySend, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlayProgress, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlayProgressLeft, OVERLAY_ELEVATION_DP) ViewUtils.setViewElevation(binding.readingOverlayProgressRight, OVERLAY_ELEVATION_DP) // this likes to default to 'on' for some platforms enableProgressCircle(binding.readingOverlayProgressLeft, false) enableProgressCircle(binding.readingOverlayProgressRight, false) supportFragmentManager.findFragmentByTag(ReadingPagerFragment::class.java.name) ?: supportFragmentManager.commit { add(R.id.activity_reading_container, ReadingPagerFragment.newInstance(), ReadingPagerFragment::class.java.name) } } private fun setupListeners() { binding.readingOverlayText.setOnClickListener { overlayTextClick() } binding.readingOverlaySend.setOnClickListener { overlaySendClick() } binding.readingOverlayLeft.setOnClickListener { overlayLeftClick() } binding.readingOverlayRight.setOnClickListener { overlayRightClick() } binding.readingOverlayProgress.setOnClickListener { overlayProgressCountClick() } } private fun setupObservers() { storiesViewModel.activeStoriesLiveData.observe(this) { setCursorData(it) } } private fun getActiveStoriesCursor(finishOnInvalidFs: Boolean = false) { fs?.let { storiesViewModel.getActiveStories(it) } ?: run { if (finishOnInvalidFs) { Log.e(this.javaClass.name, "can't create activity, no feedset ready") // this is probably happening in a finalisation cycle or during a crash, pop the activity stack finish() } } } private fun setCursorData(cursor: Cursor) { if (!dbHelper.isFeedSetReady(fs)) { com.newsblur.util.Log.i(this.javaClass.name, "stale load") // the system can and will re-use activities, so during the initial mismatch of // data, don't show the old stories pager!!.visibility = View.INVISIBLE binding.readingEmptyViewText.visibility = View.VISIBLE stories = null triggerRefresh(AppConstants.READING_STORY_PRELOAD) return } // swapCursor() will asynch process the new cursor and fully update the pager, // update child fragments, and then call pagerUpdated() readingAdapter?.swapCursor(cursor, pager) stories = cursor com.newsblur.util.Log.d(this.javaClass.name, "loaded cursor with count: " + cursor.count) if (cursor.count < 1) { triggerRefresh(AppConstants.READING_STORY_PRELOAD) } } /** * notify the activity that the dataset for the pager has fully been updated */ fun pagerUpdated() { // see if we are just starting and need to jump to a target story skipPagerToStoryHash() if (unreadSearchActive) { // if we left this flag high, we were looking for an unread, but didn't find one; // now that we have more stories, look again. nextUnread() } updateOverlayNav() updateOverlayText() } private fun skipPagerToStoryHash() { // if we already started and found our target story, this will be unset if (storyHash == null) { pager!!.visibility = View.VISIBLE binding.readingEmptyViewText.visibility = View.INVISIBLE return } val position: Int = if (storyHash == FIND_FIRST_UNREAD) { readingAdapter!!.findFirstUnread() } else { readingAdapter!!.findHash(storyHash) } if (stopLoading) return if (position >= 0) { pager!!.setCurrentItem(position, false) onPageSelected(position) // now that the pager is getting the right story, make it visible pager!!.visibility = View.VISIBLE binding.readingEmptyViewText.visibility = View.INVISIBLE storyHash = null return } // if the story wasn't found, try to get more stories into the cursor checkStoryCount(readingAdapter!!.count + 1) } /* * The key component of this activity is the pager, which in order to correctly use * child fragments for stories, needs to be within an enclosing fragment. Because * the view heirarchy of that fragment will have a different lifecycle than the * activity, we need a way to get access to the pager when it is created and only * then can we set it up. */ fun offerPager(pager: ViewPager, childFragmentManager: FragmentManager) { this.pager = pager // since it might start on the wrong story, create the pager as invisible pager.visibility = View.INVISIBLE pager.pageMargin = UIUtils.dp2px(this, 1) when (PrefsUtils.getSelectedTheme(this)) { ThemeValue.LIGHT -> pager.setPageMarginDrawable(R.drawable.divider_light) ThemeValue.DARK, ThemeValue.BLACK -> pager.setPageMarginDrawable(R.drawable.divider_dark) ThemeValue.AUTO -> { when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { Configuration.UI_MODE_NIGHT_YES -> pager.setPageMarginDrawable(R.drawable.divider_dark) Configuration.UI_MODE_NIGHT_NO -> pager.setPageMarginDrawable(R.drawable.divider_light) Configuration.UI_MODE_NIGHT_UNDEFINED -> pager.setPageMarginDrawable(R.drawable.divider_light) } } else -> { } } var showFeedMetadata = true if (fs!!.isSingleNormal) showFeedMetadata = false var sourceUserId: String? = null if (fs!!.singleSocialFeed != null) sourceUserId = fs!!.singleSocialFeed.key readingAdapter = ReadingAdapter(childFragmentManager, sourceUserId, showFeedMetadata, this, dbHelper) pager.adapter = readingAdapter // if the first story in the list was "viewed" before the page change listener was set, // the calback was probably missed if (storyHash == null) { onPageSelected(pager.currentItem) } updateOverlayNav() enableOverlays() } /** * Query the DB for the current unreadcount for this view. */ private val unreadCount: Int // saved stories and global shared stories don't have unreads get() { // saved stories and global shared stories don't have unreads if (fs!!.isAllSaved || fs!!.isGlobalShared) return 0 val result = dbHelper.getUnreadCount(fs, intelState) return if (result < 0) 0 else result } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == android.R.id.home) { finish() true } else { super.onOptionsItemSelected(item) } } override fun handleUpdate(updateType: Int) { if (updateType and UPDATE_REBUILD != 0) { finish() } if (updateType and UPDATE_STATUS != 0) { enableMainProgress(NBSyncService.isFeedSetSyncing(fs, this)) var syncStatus = NBSyncService.getSyncStatusMessage(this, true) if (syncStatus != null) { if (AppConstants.VERBOSE_LOG) { syncStatus += UIUtils.getMemoryUsageDebug(this) } binding.readingSyncStatus.text = syncStatus binding.readingSyncStatus.visibility = View.VISIBLE } else { binding.readingSyncStatus.visibility = View.GONE } } if (updateType and UPDATE_STORY != 0) { getActiveStoriesCursor() updateOverlayNav() } readingFragment?.handleUpdate(updateType) } // interface OnPageChangeListener override fun onPageScrollStateChanged(arg0: Int) {} override fun onPageScrolled(arg0: Int, arg1: Float, arg2: Int) {} override fun onPageSelected(position: Int) { lifecycleScope.executeAsyncTask( doInBackground = { readingAdapter?.let { readingAdapter -> val story = readingAdapter.getStory(position) if (story != null) { synchronized(pageHistory) { // if the history is just starting out or the last entry in it isn't this page, add this page if (pageHistory.size < 1 || story != pageHistory[pageHistory.size - 1]) { pageHistory.add(story) } } triggerMarkStoryReadBehavior(story) } checkStoryCount(position) updateOverlayText() enableOverlays() } } ) } // interface ScrollChangeListener override fun scrollChanged(hPos: Int, vPos: Int, currentWidth: Int, currentHeight: Int) { // only update overlay alpha every few pixels. modern screens are so dense that it // is way overkill to do it on every pixel if (abs(lastVScrollPos - vPos) < 2) return lastVScrollPos = vPos val scrollMax = currentHeight - binding.root.measuredHeight val posFromBot = scrollMax - vPos var newAlpha = 0.0f if (vPos < overlayRangeTopPx && posFromBot < overlayRangeBotPx) { // if we have a super-tiny scroll window such that we never leave either top or bottom, // just leave us at full alpha. newAlpha = 1.0f } else if (vPos < overlayRangeTopPx) { val delta = overlayRangeTopPx - vPos.toFloat() newAlpha = delta / overlayRangeTopPx } else if (posFromBot < overlayRangeBotPx) { val delta = overlayRangeBotPx - posFromBot.toFloat() newAlpha = delta / overlayRangeBotPx } setOverlayAlpha(newAlpha) } private fun setOverlayAlpha(a: Float) { // check to see if the device even has room for all the overlays, moving some to overflow if not val widthPX = binding.root.measuredWidth var overflowExtras = false if (widthPX != 0) { val widthDP = UIUtils.px2dp(this, widthPX) if (widthDP < OVERLAY_MIN_WIDTH_DP) { overflowExtras = true } } val _overflowExtras = overflowExtras runOnUiThread { UIUtils.setViewAlpha(binding.readingOverlayLeft, a, true) UIUtils.setViewAlpha(binding.readingOverlayRight, a, true) UIUtils.setViewAlpha(binding.readingOverlayProgress, a, true) UIUtils.setViewAlpha(binding.readingOverlayText, a, true) UIUtils.setViewAlpha(binding.readingOverlaySend, a, !_overflowExtras) } } /** * Make visible and update the overlay UI. */ fun enableOverlays() { setOverlayAlpha(1.0f) } fun disableOverlays() { setOverlayAlpha(0.0f) } /** * Update the next/back overlay UI after the read-state of a story changes or we navigate in any way. */ private fun updateOverlayNav() { val currentUnreadCount = unreadCount if (currentUnreadCount > startingUnreadCount) { startingUnreadCount = currentUnreadCount } binding.readingOverlayLeft.isEnabled = getLastReadPosition(false) != -1 binding.readingOverlayRight.setText(if (currentUnreadCount > 0) R.string.overlay_next else R.string.overlay_done) if (currentUnreadCount > 0) { binding.readingOverlayRight.setBackgroundResource(UIUtils.getThemedResource(this, R.attr.selectorOverlayBackgroundRight, android.R.attr.background)) } else { binding.readingOverlayRight.setBackgroundResource(UIUtils.getThemedResource(this, R.attr.selectorOverlayBackgroundRightDone, android.R.attr.background)) } if (startingUnreadCount == 0) { // sessions with no unreads just show a full progress bar binding.readingOverlayProgress.max = 1 binding.readingOverlayProgress.progress = 1 } else { val unreadProgress = startingUnreadCount - currentUnreadCount binding.readingOverlayProgress.max = startingUnreadCount binding.readingOverlayProgress.progress = unreadProgress } binding.readingOverlayProgress.invalidate() invalidateOptionsMenu() } private fun updateOverlayText() { runOnUiThread(Runnable { val item = readingFragment ?: return@Runnable if (item.selectedViewMode == DefaultFeedView.STORY) { binding.readingOverlayText.setBackgroundResource(UIUtils.getThemedResource(this@Reading, R.attr.selectorOverlayBackgroundText, android.R.attr.background)) binding.readingOverlayText.setText(R.string.overlay_text) } else { binding.readingOverlayText.setBackgroundResource(UIUtils.getThemedResource(this@Reading, R.attr.selectorOverlayBackgroundStory, android.R.attr.background)) binding.readingOverlayText.setText(R.string.overlay_story) } }) } // override fun onWindowFocusChanged(hasFocus: Boolean) { // // this callback is a good API-level-independent way to tell when the root view size/layout changes // super.onWindowFocusChanged(hasFocus) // contentView = findViewById(android.R.id.content) // } /** * While navigating the story list and at the specified position, see if it is possible * and desirable to start loading more stories in the background. Note that if a load * is triggered, this method will be called again by the callback to ensure another * load is not needed and all latches are tripped. */ private fun checkStoryCount(position: Int) { if (stories == null) { triggerRefresh(position + AppConstants.READING_STORY_PRELOAD) } else { if (AppConstants.VERBOSE_LOG) { Log.d(this.javaClass.name, String.format("story %d of %d selected, stopLoad: %b", position, stories!!.count, stopLoading)) } // if the pager is at or near the number of stories loaded, check for more unless we know we are at the end of the list if (position + AppConstants.READING_STORY_PRELOAD >= stories!!.count) { triggerRefresh(position + AppConstants.READING_STORY_PRELOAD) } } } private fun enableMainProgress(enabled: Boolean) { enableProgressCircle(binding.readingOverlayProgressRight, enabled) } fun enableLeftProgressCircle(enabled: Boolean) { enableProgressCircle(binding.readingOverlayProgressLeft, enabled) } private fun enableProgressCircle(view: CircularProgressIndicator, enabled: Boolean) { runOnUiThread { if (enabled) { view.progress = 0 view.visibility = View.VISIBLE } else { view.progress = 100 view.visibility = View.GONE } } } private fun triggerRefresh(desiredStoryCount: Int) { if (!stopLoading) { var currentCount: Int? = null if (stories != null) currentCount = stories!!.count val gotSome = NBSyncService.requestMoreForFeed(fs, desiredStoryCount, currentCount) if (gotSome) triggerSync() } } /** * Click handler for the righthand overlay nav button. */ private fun overlayRightClick() { if (unreadCount <= 0) { // if there are no unread stories, go back to the feed list val i = Intent(this, Main::class.java) i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(i) finish() } else { // if there are unreads, go to the next one lifecycleScope.executeAsyncTask( doInBackground = { nextUnread() } ) } } /** * Search our set of stories for the next unread one. */ private fun nextUnread() { unreadSearchActive = true // if we somehow got tapped before construction or are running during destruction, stop and // let either finish. search will happen when the cursor is pushed. if (pager == null || readingAdapter == null) return var unreadFound = false // start searching just after the current story val currentIndex = pager!!.currentItem var candidate = currentIndex + 1 unreadSearch@ while (!unreadFound) { // if we've reached the end of the list, start searching backward from the current story if (candidate >= readingAdapter!!.count) { candidate = currentIndex - 1 } // if we have looked all the way back to the first story, there aren't any left if (candidate < 0) { break@unreadSearch } val story = readingAdapter!!.getStory(candidate) if (stopLoading) { // this activity was ended before we finished. just stop. unreadSearchActive = false return } // iterate through the stories in our cursor until we find an unread one if (story != null) { unreadFound = if (story.read) { if (candidate > currentIndex) { // if we are still searching past the current story, search forward candidate++ } else { // if we hit the end and re-started before the current story, search backward candidate-- } continue@unreadSearch } else { true } } // if we didn't continue or break, the cursor probably changed out from under us, so stop. break@unreadSearch } if (unreadFound) { // jump to the story we found val page = candidate runOnUiThread { pager!!.setCurrentItem(page, true) } // disable the search flag, as we are done unreadSearchActive = false } else { // We didn't find a story, so we should trigger a check to see if the API can load any more. // First, though, double check that there are even any left, as there may have been a delay // between marking an earlier one and double-checking counts. if (unreadCount <= 0) { unreadSearchActive = false } else { // trigger a check to see if there are any more to search before proceeding. By leaving the // unreadSearchActive flag high, this method will be called again when a new cursor is loaded checkStoryCount(readingAdapter!!.count + 1) } } } /** * Click handler for the lefthand overlay nav button. */ private fun overlayLeftClick() { val targetPosition = getLastReadPosition(true) if (targetPosition != -1) { pager!!.setCurrentItem(targetPosition, true) } else { Log.e(this.javaClass.name, "reading history contained item not found in cursor.") } } /** * Get the pager position of the last story read during this activity or -1 if there is nothing * in the history. * * @param trimHistory optionally trim the history of the currently displayed page iff the * back button has been pressed. */ private fun getLastReadPosition(trimHistory: Boolean): Int { synchronized(pageHistory) { // the last item is always the currently shown page, do not count it if (pageHistory.size < 2) { return -1 } val targetStory = pageHistory[pageHistory.size - 2] val targetPosition = readingAdapter!!.getPosition(targetStory) if (trimHistory && targetPosition != -1) { pageHistory.removeAt(pageHistory.size - 1) } return targetPosition } } /** * Click handler for the progress indicator on the righthand overlay nav button. */ private fun overlayProgressCountClick() { val unreadText = getString(if (unreadCount == 1) R.string.overlay_count_toast_1 else R.string.overlay_count_toast_N) Toast.makeText(this, String.format(unreadText, unreadCount), Toast.LENGTH_SHORT).show() } private fun overlaySendClick() { if (readingAdapter == null || pager == null) return val story = readingAdapter!!.getStory(pager!!.currentItem) feedUtils.sendStoryUrl(story, this) } private fun overlayTextClick() { val item = readingFragment ?: return lifecycleScope.executeAsyncTask( doInBackground = { item.switchSelectedViewMode() } ) } private val readingFragment: ReadingItemFragment? get() = if (readingAdapter == null || pager == null) null else readingAdapter!!.getExistingItem(pager!!.currentItem) fun viewModeChanged() { var frag = readingAdapter!!.getExistingItem(pager!!.currentItem) frag?.viewModeChanged() // fragments to the left or the right may have already preloaded content and need to also switch frag = readingAdapter!!.getExistingItem(pager!!.currentItem - 1) frag?.viewModeChanged() frag = readingAdapter!!.getExistingItem(pager!!.currentItem + 1) frag?.viewModeChanged() updateOverlayText() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return if (isVolumeKeyNavigationEvent(keyCode)) { processVolumeKeyNavigationEvent(keyCode) true } else { super.onKeyDown(keyCode, event) } } private fun isVolumeKeyNavigationEvent(keyCode: Int): Boolean = volumeKeyNavigation != VolumeKeyNavigation.OFF && (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) private fun processVolumeKeyNavigationEvent(keyCode: Int) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN && volumeKeyNavigation == VolumeKeyNavigation.DOWN_NEXT || keyCode == KeyEvent.KEYCODE_VOLUME_UP && volumeKeyNavigation == VolumeKeyNavigation.UP_NEXT) { if (pager == null) return val nextPosition = pager!!.currentItem + 1 if (nextPosition < readingAdapter!!.count) { try { pager!!.currentItem = nextPosition } catch (e: Exception) { // Just in case cursor changes. } } } else { if (pager == null) return val nextPosition = pager!!.currentItem - 1 if (nextPosition >= 0) { try { pager!!.currentItem = nextPosition } catch (e: Exception) { // Just in case cursor changes. } } } } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { // Required to prevent the default sound playing when the volume key is pressed return if (isVolumeKeyNavigationEvent(keyCode)) { true } else { super.onKeyUp(keyCode, event) } } private fun triggerMarkStoryReadBehavior(story: Story) { markStoryReadJob?.cancel() if (story.read) return val delayMillis = markStoryReadBehavior.getDelayMillis() if (delayMillis >= 0) { markStoryReadJob = createMarkStoryReadJob(story, delayMillis).also { it.start() } } } private fun createMarkStoryReadJob(story: Story, delayMillis: Long): Job = lifecycleScope.launch(Dispatchers.Default) { if (isActive) delay(delayMillis) if (isActive) feedUtils.markStoryAsRead(story, this@Reading) } companion object { const val EXTRA_FEEDSET = "feed_set" const val EXTRA_STORY_HASH = "story_hash" const val EXTRA_STORY = "story" private const val BUNDLE_STARTING_UNREAD = "starting_unread" /** special value for starting story hash that jumps to the first unread. */ const val FIND_FIRST_UNREAD = "FIND_FIRST_UNREAD" private const val OVERLAY_ELEVATION_DP = 1.5f private const val OVERLAY_RANGE_TOP_DP = 40 private const val OVERLAY_RANGE_BOT_DP = 60 /** The minimum screen width (in DP) needed to show all the overlay controls. */ private const val OVERLAY_MIN_WIDTH_DP = 355 } }
mit
5d28b1b8d9243b377174db240b5d0b48
39.303067
171
0.634232
4.900925
false
false
false
false
JetBrains/resharper-unity
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/explorer/ReferenceNodes.kt
1
3319
package com.jetbrains.rider.plugins.unity.explorer import com.intellij.ide.projectView.PresentationData import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vfs.VirtualFile import com.intellij.workspaceModel.ide.impl.toVirtualFile import com.jetbrains.rd.util.getOrCreate import com.jetbrains.rider.model.RdCustomLocation import com.jetbrains.rider.projectView.workspace.* import icons.UnityIcons class ReferenceRootNode(project: Project) : AbstractTreeNode<Any>(project, key) { companion object { val key = Any() } override fun update(presentation: PresentationData) { presentation.presentableText = "References" presentation.setIcon(UnityIcons.Explorer.ReferencesRoot) } override fun getChildren(): MutableCollection<AbstractTreeNode<*>> { val referenceNames = hashMapOf<String, ReferenceItemNode>() val visitor = object : ProjectModelEntityVisitor() { override fun visitReference(entity: ProjectModelEntity): Result { if (entity.isAssemblyReference()) { val virtualFile = entity.url?.toVirtualFile() if (virtualFile != null) { val itemLocation = entity.descriptor.location val itemKey = if (itemLocation is RdCustomLocation) itemLocation.customLocation else itemLocation.toString() val item = referenceNames.getOrCreate(itemKey) { ReferenceItemNode(myProject, entity.descriptor.name, virtualFile, arrayListOf()) } item.entityReferences.add(entity.toReference()) } } return Result.Stop } } visitor.visit(myProject) val children = arrayListOf<AbstractTreeNode<*>>() for ((_, item) in referenceNames) { children.add(item) } return children } } class ReferenceItemNode( project: Project, private val referenceName: String, virtualFile: VirtualFile, override val entityReferences: ArrayList<ProjectModelEntityReference> ) : UnityExplorerFileSystemNode(project, virtualFile, emptyList(), AncestorNodeType.References) { override fun isAlwaysLeaf() = true override fun update(presentation: PresentationData) { presentation.presentableText = referenceName presentation.setIcon(UnityIcons.Explorer.Reference) } override fun navigate(requestFocus: Boolean) { // the same VirtualFile may be added as a file inside Assets folder, so simple click on the reference would jump to that file } override val entities: List<ProjectModelEntity> get() = entityReferences.mapNotNull { it.getEntity(myProject) } override val entity: ProjectModelEntity? get() = entityReference?.getEntity(myProject) override val entityReference: ProjectModelEntityReference? get() = entityReferences.firstOrNull() // Don't show references with weird file statuses. They are files, and some will be in ignored folders // (e.g. Library/PackageCache) override fun getFileStatus(): FileStatus = FileStatus.NOT_CHANGED }
apache-2.0
ee20ea698d5b1bce0932fbb2e2ec8368
39.975309
133
0.68605
5.161742
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/search/ManualAddSearchEnginePreference.kt
1
4649
/* 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.search import android.content.Context import android.os.Bundle import android.os.Parcelable import android.text.TextUtils import android.util.AttributeSet import android.widget.EditText import android.widget.ProgressBar import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.core.widget.doOnTextChanged import androidx.preference.Preference import androidx.preference.PreferenceViewHolder import com.google.android.material.textfield.TextInputLayout import mozilla.components.browser.state.search.SearchEngine import mozilla.components.support.utils.ext.getParcelableCompat import org.mozilla.focus.R import org.mozilla.focus.utils.UrlUtils import org.mozilla.focus.utils.ViewUtils class ManualAddSearchEnginePreference(context: Context, attrs: AttributeSet) : Preference(context, attrs) { private var engineNameEditText: EditText? = null private var searchQueryEditText: EditText? = null private var engineNameErrorLayout: TextInputLayout? = null private var searchQueryErrorLayout: TextInputLayout? = null private var progressView: ProgressBar? = null private var savedSearchEngineName: String? = null private var savedSearchQuery: String? = null override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) engineNameErrorLayout = holder.findViewById(R.id.edit_engine_name_layout) as TextInputLayout searchQueryErrorLayout = holder.findViewById(R.id.edit_search_string_layout) as TextInputLayout engineNameEditText = holder.findViewById(R.id.edit_engine_name) as EditText engineNameEditText?.doOnTextChanged { _, _, _, _ -> engineNameErrorLayout?.error = null } searchQueryEditText = holder.findViewById(R.id.edit_search_string) as EditText searchQueryEditText?.doOnTextChanged { _, _, _, _ -> searchQueryErrorLayout?.error = null } progressView = holder.findViewById(R.id.progress) as ProgressBar updateState() ViewUtils.showKeyboard(engineNameEditText) } override fun onRestoreInstanceState(state: Parcelable?) { val bundle = state as Bundle super.onRestoreInstanceState(bundle.getParcelableCompat(SUPER_STATE_KEY, Parcelable::class.java)) savedSearchEngineName = bundle.getString(SEARCH_ENGINE_NAME_KEY) savedSearchQuery = bundle.getString(SEARCH_QUERY_KEY) } override fun onSaveInstanceState(): Parcelable { val state = super.onSaveInstanceState() return bundleOf( SUPER_STATE_KEY to state, SEARCH_ENGINE_NAME_KEY to engineNameEditText?.text.toString(), SEARCH_QUERY_KEY to searchQueryEditText?.text.toString(), ) } fun validateEngineNameAndShowError(engineName: String, existingEngines: List<SearchEngine>): Boolean { val errorMessage = when { TextUtils.isEmpty(engineName) -> context.getString(R.string.search_add_error_empty_name) existingEngines.any { it.name.equals(engineName, ignoreCase = true) } -> context.getString(R.string.search_add_error_duplicate_name) else -> null } engineNameErrorLayout?.error = errorMessage return errorMessage == null } fun validateSearchQueryAndShowError(searchQuery: String): Boolean { val errorMessage = when { TextUtils.isEmpty(searchQuery) -> context.getString(R.string.search_add_error_empty_search) !UrlUtils.isValidSearchQueryUrl(searchQuery) -> context.getString(R.string.search_add_error_format) else -> null } searchQueryErrorLayout?.error = errorMessage return errorMessage == null } fun setSearchQueryErrorText(err: String) { searchQueryErrorLayout?.error = err } fun setProgressViewShown(isShown: Boolean) { progressView?.isVisible = isShown } private fun updateState() { if (engineNameEditText != null) engineNameEditText?.setText(savedSearchEngineName) if (searchQueryEditText != null) searchQueryEditText?.setText(savedSearchQuery) } companion object { private val SUPER_STATE_KEY = "super-state" private val SEARCH_ENGINE_NAME_KEY = "search-engine-name" private val SEARCH_QUERY_KEY = "search-query" } }
mpl-2.0
d511b26b7c07ad117f13cb3708fd6e2e
35.896825
111
0.71069
4.827622
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/ApplyingUpdates.kt
1
5713
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.samples.litho.kotlin.collection import android.graphics.Color import android.graphics.drawable.ColorDrawable import com.facebook.litho.ClickEvent import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Style import com.facebook.litho.drawableColor import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.useCallback import com.facebook.litho.useState import com.facebook.litho.view.background import com.facebook.litho.view.onClick import com.facebook.litho.widget.collection.LazyList class ListWithIds(private val friends: List<Person>) : KComponent() { override fun ComponentScope.render(): Component { val topFriend = friends[0] val shouldShowGreeting = useState { false } return LazyList { // start_static_id_example child(Header()) // generated id is "Header:0" // end_static_id_example // start_child_id_example if (shouldShowGreeting.value) { child(id = "greeting", component = Text("Greetings!")) } child(id = "title", component = Text("Title")) // end_child_id_example // start_children_id_example children(items = friends, id = { it.id }) { Text(it.name) } // end_children_id_example } } } class Header : KComponent() { override fun ComponentScope.render(): Component = Text("Header") } // start_name_list_unnecessary_update class Name(val firstName: String, val secondName: String) class NameComponent(val name: Name) : KComponent() { override fun ComponentScope.render(): Component = Text("${name.firstName} ${name.secondName}") } class NameList_UnnecessaryUpdate : KComponent() { override fun ComponentScope.render(): Component = LazyList { child(NameComponent(Name("Mark", "Zuckerberg"))) } } // end_name_list_unnecessary_update data class NameWithEquals(val firstName: String, val secondName: String) class NameComponentWithEquals(val name: NameWithEquals) : KComponent() { override fun ComponentScope.render(): Component = Text("${name.firstName} ${name.secondName}") } // start_name_list_fixed class NameList_Fixed : KComponent() { override fun ComponentScope.render(): Component = LazyList { // Option 1. Convert to a prop with an `equals()` implementation child(NameComponentWithEquals(NameWithEquals("Mark", "Zuckerberg"))) // Option 2. Manually specify dependencies (in this case empty) child(deps = arrayOf()) { NameComponent(Name("Mark", "Zuckerberg")) } } } // end_name_list_fixed // start_drawable_unnecessary_update class Drawable_UnnecessaryUpdate : KComponent() { override fun ComponentScope.render(): Component = LazyList { child(Text("text", style = Style.background(ColorDrawable(Color.RED)))) } } // end_drawable_unnecessary_update // start_drawable_fixed class Drawable_Fixed : KComponent() { override fun ComponentScope.render(): Component = LazyList { // Option 1. Use a `ComparableDrawable` wrapper child(Text("text", style = Style.background(drawableColor(Color.RED)))) // Option 2. Manually specify dependencies (in this case empty). child(deps = arrayOf()) { Text("text", style = Style.background(ColorDrawable(Color.RED))) } } } // end_drawable_fixed // start_lambda_unnecessary_update class Lambda_UnnecessaryUpdate(val name: String) : KComponent() { override fun ComponentScope.render(): Component = LazyList { child(Text("text", style = Style.onClick { println("Hello $name") })) } } // end_lambda_unnecessary_update // start_lambda_fixed class Lambda_Fixed(val name: String) : KComponent() { override fun ComponentScope.render(): Component { val callBack = useCallback { _: ClickEvent -> println("Hello $name") } return LazyList { child(Text("text", style = Style.onClick(action = callBack))) } } } // end_lambda_fixed // start_shopping_list_example class ShoppingList : KComponent() { override fun ComponentScope.render(): Component { val shoppingList = listOf("Apples", "Cheese", "Bread") // Create a state containing the items that should be shown with a checkmark: ☑ // Initially empty val checkedItems = useState { setOf<String>() } // Create a callback to toggle the checkmark for an item // States should always use immutable data, so a new Set is created val toggleChecked = useCallback { item: String -> checkedItems.update { it.toMutableSet().apply { if (contains(item)) remove(item) else add(item) }.toSet() } } return LazyList { children(items = shoppingList, id = { it }) { val isChecked = checkedItems.value.contains(it) ShoppingListItem(it, isChecked, toggleChecked) } } } } class ShoppingListItem( private val item: String, private val isChecked: Boolean, private val toggleSelected: (String) -> Unit, ) : KComponent() { override fun ComponentScope.render(): Component = Text("${if (isChecked) "☑" else "☐"} $item", style = Style.onClick { toggleSelected(item) }) } // end_shopping_list_example
apache-2.0
3a70b263e3cc40bc9499eca127897c16
33.379518
98
0.70983
4.021846
false
false
false
false
facebook/litho
litho-core-kotlin/src/main/kotlin/com/facebook/litho/core/CoreStyles.kt
1
9988
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho.core import com.facebook.litho.Component import com.facebook.litho.ComponentContext import com.facebook.litho.Dimen import com.facebook.litho.Style import com.facebook.litho.StyleItem import com.facebook.litho.StyleItemField import com.facebook.litho.exhaustive import com.facebook.litho.getCommonPropsHolder import com.facebook.yoga.YogaEdge /** Enums for [CoreDimenStyleItem]. */ @PublishedApi internal enum class CoreDimenField : StyleItemField { WIDTH, HEIGHT, MIN_WIDTH, MAX_WIDTH, MIN_HEIGHT, MAX_HEIGHT, PADDING_START, PADDING_TOP, PADDING_END, PADDING_BOTTOM, PADDING_LEFT, PADDING_RIGHT, PADDING_HORIZONTAL, PADDING_VERTICAL, PADDING_ALL, MARGIN_START, MARGIN_TOP, MARGIN_END, MARGIN_BOTTOM, MARGIN_LEFT, MARGIN_RIGHT, MARGIN_HORIZONTAL, MARGIN_VERTICAL, MARGIN_ALL, } /** Enums for [CoreFloatStyleItem]. */ @PublishedApi internal enum class CoreFloatField : StyleItemField { WIDTH_PERCENT, HEIGHT_PERCENT, MIN_WIDTH_PERCENT, MAX_WIDTH_PERCENT, MIN_HEIGHT_PERCENT, MAX_HEIGHT_PERCENT, } /** Common style item for all core dimen styles. See note on [CoreDimenField] about this pattern. */ @PublishedApi internal data class CoreDimenStyleItem( override val field: CoreDimenField, override val value: Dimen ) : StyleItem<Dimen> { override fun applyToComponent(context: ComponentContext, component: Component) { val commonProps = component.getCommonPropsHolder() val pixelValue = value.toPixels(context.resourceResolver) when (field) { // TODO(t89044330): When yoga is decoupled from Litho, implement these more generically. CoreDimenField.WIDTH -> commonProps.widthPx(pixelValue) CoreDimenField.HEIGHT -> commonProps.heightPx(pixelValue) CoreDimenField.MIN_WIDTH -> commonProps.minWidthPx(pixelValue) CoreDimenField.MAX_WIDTH -> commonProps.maxWidthPx(pixelValue) CoreDimenField.MIN_HEIGHT -> commonProps.minHeightPx(pixelValue) CoreDimenField.MAX_HEIGHT -> commonProps.maxHeightPx(pixelValue) CoreDimenField.PADDING_START -> commonProps.paddingPx(YogaEdge.START, pixelValue) CoreDimenField.PADDING_TOP -> commonProps.paddingPx(YogaEdge.TOP, pixelValue) CoreDimenField.PADDING_END -> commonProps.paddingPx(YogaEdge.END, pixelValue) CoreDimenField.PADDING_BOTTOM -> commonProps.paddingPx(YogaEdge.BOTTOM, pixelValue) CoreDimenField.PADDING_LEFT -> commonProps.paddingPx(YogaEdge.LEFT, pixelValue) CoreDimenField.PADDING_RIGHT -> commonProps.paddingPx(YogaEdge.RIGHT, pixelValue) CoreDimenField.PADDING_HORIZONTAL -> commonProps.paddingPx(YogaEdge.HORIZONTAL, pixelValue) CoreDimenField.PADDING_VERTICAL -> commonProps.paddingPx(YogaEdge.VERTICAL, pixelValue) CoreDimenField.PADDING_ALL -> commonProps.paddingPx(YogaEdge.ALL, pixelValue) CoreDimenField.MARGIN_START -> commonProps.marginPx(YogaEdge.START, pixelValue) CoreDimenField.MARGIN_TOP -> commonProps.marginPx(YogaEdge.TOP, pixelValue) CoreDimenField.MARGIN_END -> commonProps.marginPx(YogaEdge.END, pixelValue) CoreDimenField.MARGIN_BOTTOM -> commonProps.marginPx(YogaEdge.BOTTOM, pixelValue) CoreDimenField.MARGIN_LEFT -> commonProps.marginPx(YogaEdge.LEFT, pixelValue) CoreDimenField.MARGIN_RIGHT -> commonProps.marginPx(YogaEdge.RIGHT, pixelValue) CoreDimenField.MARGIN_HORIZONTAL -> commonProps.marginPx(YogaEdge.HORIZONTAL, pixelValue) CoreDimenField.MARGIN_VERTICAL -> commonProps.marginPx(YogaEdge.VERTICAL, pixelValue) CoreDimenField.MARGIN_ALL -> commonProps.marginPx(YogaEdge.ALL, pixelValue) }.exhaustive } } /** Common style item for all core float styles. See note on [CoreDimenField] about this pattern. */ @PublishedApi internal class CoreFloatStyleItem(override val field: CoreFloatField, override val value: Float) : StyleItem<Float> { override fun applyToComponent(context: ComponentContext, component: Component) { val commonProps = component.getCommonPropsHolder() when (field) { // TODO(t89044330): When yoga is decoupled from Litho, implement these more generically. CoreFloatField.WIDTH_PERCENT -> commonProps.widthPercent(value) CoreFloatField.HEIGHT_PERCENT -> commonProps.heightPercent(value) CoreFloatField.MIN_WIDTH_PERCENT -> commonProps.minWidthPercent(value) CoreFloatField.MAX_WIDTH_PERCENT -> commonProps.maxWidthPercent(value) CoreFloatField.MIN_HEIGHT_PERCENT -> commonProps.minHeightPercent(value) CoreFloatField.MAX_HEIGHT_PERCENT -> commonProps.maxHeightPercent(value) }.exhaustive } } /** Sets a specific preferred width for this component when its parent lays it out. */ inline fun Style.width(width: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.WIDTH, width) /** Sets a specific preferred height for this component when its parent lays it out. */ inline fun Style.height(height: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.HEIGHT, height) /** Sets a specific preferred percent width for this component when its parent lays it out. */ inline fun Style.widthPercent(widthPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.WIDTH_PERCENT, widthPercent) /** Sets a specific preferred percent height for this component when its parent lays it out. */ inline fun Style.heightPercent(heightPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.HEIGHT_PERCENT, heightPercent) /** Sets a preferred minimum width for this component when its parent lays it out. */ inline fun Style.minWidth(minWidth: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.MIN_WIDTH, minWidth) /** Sets a preferred maximum width for this component when its parent lays it out. */ inline fun Style.maxWidth(maxWidth: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.MAX_WIDTH, maxWidth) /** Sets a preferred minimum height for this component when its parent lays it out. */ inline fun Style.minHeight(minHeight: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.MIN_HEIGHT, minHeight) /** Sets a preferred maximum height for this component when its parent lays it out. */ inline fun Style.maxHeight(maxHeight: Dimen): Style = this + CoreDimenStyleItem(CoreDimenField.MAX_HEIGHT, maxHeight) /** Sets a specific minimum percent width for this component when its parent lays it out. */ inline fun Style.minWidthPercent(minWidthPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.MIN_WIDTH_PERCENT, minWidthPercent) /** Sets a specific maximum percent width for this component when its parent lays it out. */ inline fun Style.maxWidthPercent(maxWidthPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.MAX_WIDTH_PERCENT, maxWidthPercent) /** Sets a specific minimum percent height for this component when its parent lays it out. */ inline fun Style.minHeightPercent(minHeightPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.MIN_HEIGHT_PERCENT, minHeightPercent) /** Sets a specific maximum percent height for this component when its parent lays it out. */ inline fun Style.maxHeightPercent(maxHeightPercent: Float): Style = this + CoreFloatStyleItem(CoreFloatField.MAX_HEIGHT_PERCENT, maxHeightPercent) /** Defines padding on the component on a per-edge basis. */ inline fun Style.padding( all: Dimen? = null, horizontal: Dimen? = null, vertical: Dimen? = null, start: Dimen? = null, top: Dimen? = null, end: Dimen? = null, bottom: Dimen? = null, left: Dimen? = null, right: Dimen? = null, ): Style = this + all?.let { CoreDimenStyleItem(CoreDimenField.PADDING_ALL, it) } + horizontal?.let { CoreDimenStyleItem(CoreDimenField.PADDING_HORIZONTAL, it) } + vertical?.let { CoreDimenStyleItem(CoreDimenField.PADDING_VERTICAL, it) } + start?.let { CoreDimenStyleItem(CoreDimenField.PADDING_START, it) } + top?.let { CoreDimenStyleItem(CoreDimenField.PADDING_TOP, it) } + end?.let { CoreDimenStyleItem(CoreDimenField.PADDING_END, it) } + bottom?.let { CoreDimenStyleItem(CoreDimenField.PADDING_BOTTOM, it) } + left?.let { CoreDimenStyleItem(CoreDimenField.PADDING_LEFT, it) } + right?.let { CoreDimenStyleItem(CoreDimenField.PADDING_RIGHT, it) } /** Defines margin around the component on a per-edge basis. */ inline fun Style.margin( all: Dimen? = null, horizontal: Dimen? = null, vertical: Dimen? = null, start: Dimen? = null, top: Dimen? = null, end: Dimen? = null, bottom: Dimen? = null, left: Dimen? = null, right: Dimen? = null, ): Style = this + all?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_ALL, it) } + horizontal?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_HORIZONTAL, it) } + vertical?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_VERTICAL, it) } + start?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_START, it) } + top?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_TOP, it) } + end?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_END, it) } + bottom?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_BOTTOM, it) } + left?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_LEFT, it) } + right?.let { CoreDimenStyleItem(CoreDimenField.MARGIN_RIGHT, it) }
apache-2.0
21dd16e155c3b3eeba61514b4742a603
45.02765
100
0.744894
4.191355
false
false
false
false
square/leakcanary
shark/src/main/java/shark/internal/DominatorTree.kt
2
8380
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "CANNOT_OVERRIDE_INVISIBLE_MEMBER") package shark.internal import shark.ValueHolder import shark.internal.ObjectDominators.DominatorNode import shark.internal.hppc.LongLongScatterMap import shark.internal.hppc.LongLongScatterMap.ForEachCallback import shark.internal.hppc.LongScatterSet internal class DominatorTree(expectedElements: Int = 4) { /** * Map of objects to their dominator. * * If an object is dominated by more than one GC root then its dominator is set to * [ValueHolder.NULL_REFERENCE]. */ private val dominated = LongLongScatterMap(expectedElements) /** * Records that [objectId] is a root. */ fun updateDominatedAsRoot(objectId: Long): Boolean { return updateDominated(objectId, ValueHolder.NULL_REFERENCE) } /** * Records that [objectId] can be reached through [parentObjectId], updating the dominator for * [objectId] to be either [parentObjectId] if [objectId] has no known dominator and otherwise to * the Lowest Common Dominator between [parentObjectId] and the previously determined dominator * for [objectId]. * * [parentObjectId] should already have been added via [updateDominatedAsRoot]. Failing to do * that will throw [IllegalStateException] on future calls. * * This implementation is optimized with the assumption that the graph is visited as a breadth * first search, so when objectId already has a known dominator then its dominator path is * shorter than the dominator path of [parentObjectId]. * * @return true if [objectId] already had a known dominator, false otherwise. */ fun updateDominated( objectId: Long, parentObjectId: Long ): Boolean { val dominatedSlot = dominated.getSlot(objectId) val hasDominator = dominatedSlot != -1 if (!hasDominator || parentObjectId == ValueHolder.NULL_REFERENCE) { dominated[objectId] = parentObjectId } else { val currentDominator = dominated.getSlotValue(dominatedSlot) if (currentDominator != ValueHolder.NULL_REFERENCE) { // We're looking for the Lowest Common Dominator between currentDominator and // parentObjectId. We know that currentDominator likely has a shorter dominator path than // parentObjectId since we're exploring the graph with a breadth first search. So we build // a temporary hash set for the dominator path of currentDominator (since it's smaller) // and then go through the dominator path of parentObjectId checking if any id exists // in that hash set. // Once we find either a common dominator or none, we update the map accordingly val currentDominators = LongScatterSet() var dominator = currentDominator while (dominator != ValueHolder.NULL_REFERENCE) { currentDominators.add(dominator) val nextDominatorSlot = dominated.getSlot(dominator) if (nextDominatorSlot == -1) { throw IllegalStateException( "Did not find dominator for $dominator when going through the dominator chain for $currentDominator: $currentDominators" ) } else { dominator = dominated.getSlotValue(nextDominatorSlot) } } dominator = parentObjectId while (dominator != ValueHolder.NULL_REFERENCE) { if (dominator in currentDominators) { break } val nextDominatorSlot = dominated.getSlot(dominator) if (nextDominatorSlot == -1) { throw IllegalStateException( "Did not find dominator for $dominator when going through the dominator chain for $parentObjectId" ) } else { dominator = dominated.getSlotValue(nextDominatorSlot) } } dominated[objectId] = dominator } } return hasDominator } private class MutableDominatorNode { var shallowSize = 0 var retainedSize = 0 var retainedCount = 0 val dominated = mutableListOf<Long>() } fun buildFullDominatorTree(computeSize: (Long) -> Int): Map<Long, DominatorNode> { val dominators = mutableMapOf<Long, MutableDominatorNode>() dominated.forEach(ForEachCallback {key, value -> // create entry for dominated dominators.getOrPut(key) { MutableDominatorNode() } // If dominator is null ref then we still have an entry for that, to collect all dominator // roots. dominators.getOrPut(value) { MutableDominatorNode() }.dominated += key }) val allReachableObjectIds = dominators.keys.toSet() - ValueHolder.NULL_REFERENCE val retainedSizes = computeRetainedSizes(allReachableObjectIds) { objectId -> val shallowSize = computeSize(objectId) dominators.getValue(objectId).shallowSize = shallowSize shallowSize } dominators.forEach { (objectId, node) -> if (objectId != ValueHolder.NULL_REFERENCE) { val (retainedSize, retainedCount) = retainedSizes.getValue(objectId) node.retainedSize = retainedSize node.retainedCount = retainedCount } } val rootDominator = dominators.getValue(ValueHolder.NULL_REFERENCE) rootDominator.retainedSize = rootDominator.dominated.map { dominators[it]!!.retainedSize }.sum() rootDominator.retainedCount = rootDominator.dominated.map { dominators[it]!!.retainedCount }.sum() // Sort children with largest retained first dominators.values.forEach { node -> node.dominated.sortBy { -dominators.getValue(it).retainedSize } } return dominators.mapValues { (_, node) -> DominatorNode( node.shallowSize, node.retainedSize, node.retainedCount, node.dominated ) } } /** * Computes the size retained by [retainedObjectIds] using the dominator tree built using * [updateDominatedAsRoot]. The shallow size of each object is provided by [computeSize]. * @return a map of object id to retained size. */ fun computeRetainedSizes( retainedObjectIds: Set<Long>, computeSize: (Long) -> Int ): Map<Long, Pair<Int, Int>> { val nodeRetainedSizes = mutableMapOf<Long, Pair<Int, Int>>() retainedObjectIds.forEach { objectId -> nodeRetainedSizes[objectId] = 0 to 0 } dominated.forEach(object : ForEachCallback { override fun onEntry( key: Long, value: Long ) { // lazy computing of instance size var instanceSize = -1 // If the entry is a node, add its size to nodeRetainedSizes nodeRetainedSizes[key]?.let { (currentRetainedSize, currentRetainedCount) -> instanceSize = computeSize(key) nodeRetainedSizes[key] = currentRetainedSize + instanceSize to currentRetainedCount + 1 } if (value != ValueHolder.NULL_REFERENCE) { var dominator = value val dominatedByNextNode = mutableListOf(key) while (dominator != ValueHolder.NULL_REFERENCE) { // If dominator is a node if (nodeRetainedSizes.containsKey(dominator)) { // Update dominator for all objects in the dominator path so far to directly point // to it. We're compressing the dominator path to make this iteration faster and // faster as we go through each entry. dominatedByNextNode.forEach { objectId -> dominated[objectId] = dominator } if (instanceSize == -1) { instanceSize = computeSize(key) } // Update retained size for that node val (currentRetainedSize, currentRetainedCount) = nodeRetainedSizes.getValue( dominator ) nodeRetainedSizes[dominator] = (currentRetainedSize + instanceSize) to currentRetainedCount + 1 dominatedByNextNode.clear() } else { dominatedByNextNode += dominator } dominator = dominated[dominator] } // Update all dominator for all objects found in the dominator path after the last node dominatedByNextNode.forEach { objectId -> dominated[objectId] = ValueHolder.NULL_REFERENCE } } } }) dominated.release() return nodeRetainedSizes } }
apache-2.0
979c1022b9e190265a12868b4e11e763
37.976744
134
0.665632
4.385139
false
false
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/settings/fragment/SearchSettingFragment.kt
1
7769
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.settings.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import androidx.annotation.LayoutRes import androidx.annotation.StringRes import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import jp.toastkid.lib.color.IconColorFinder import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.view.CompoundDrawableColorApplier import jp.toastkid.search.SearchCategory import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.FragmentSettingSearchBinding import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.search.category.SearchCategoryAdapter import jp.toastkid.yobidashi.settings.fragment.search.category.Adapter /** * @author toastkidjp */ class SearchSettingFragment : Fragment() { /** * View Data Binding object. */ private lateinit var binding: FragmentSettingSearchBinding /** * Preferences wrapper. */ private lateinit var preferenceApplier: PreferenceApplier override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false) val activityContext = context ?: return super.onCreateView(inflater, container, savedInstanceState) preferenceApplier = PreferenceApplier(activityContext) binding.fragment = this binding.searchCategories.adapter = SearchCategoryAdapter(activityContext) val index = SearchCategory.findIndex( PreferenceApplier(activityContext).getDefaultSearchEngine() ?: SearchCategory.getDefaultCategoryName() ) binding.searchCategories.setSelection(index) binding.searchCategories.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { preferenceApplier.setDefaultSearchEngine( SearchCategory.values()[binding.searchCategories.selectedItemPosition].name) } override fun onNothingSelected(parent: AdapterView<*>?) = Unit } val adapter = Adapter(preferenceApplier) binding.settingSearchCategories.adapter = adapter binding.checkSearchCategory.setOnClickListener { adapter.invokeCheckAll() } adapter.notifyDataSetChanged() return binding.root } override fun onResume() { super.onResume() binding.enableSearchQueryExtractCheck.isChecked = preferenceApplier.enableSearchQueryExtract binding.enableSearchQueryExtractCheck.jumpDrawablesToCurrentState() binding.enableSearchWithClipCheck.isChecked = preferenceApplier.enableSearchWithClip binding.enableSearchWithClipCheck.jumpDrawablesToCurrentState() binding.useSuggestionCheck.isChecked = preferenceApplier.isEnableSuggestion binding.useSuggestionCheck.jumpDrawablesToCurrentState() binding.useHistoryCheck.isChecked = preferenceApplier.isEnableSearchHistory binding.useHistoryCheck.jumpDrawablesToCurrentState() binding.useFavoriteCheck.isChecked = preferenceApplier.isEnableFavoriteSearch binding.useFavoriteCheck.jumpDrawablesToCurrentState() binding.useViewHistoryCheck.isChecked = preferenceApplier.isEnableViewHistory binding.useViewHistoryCheck.jumpDrawablesToCurrentState() binding.useUrlModuleCheck.isChecked = preferenceApplier.isEnableUrlModule() binding.useUrlModuleCheck.jumpDrawablesToCurrentState() binding.useTrendCheck.isChecked = preferenceApplier.isEnableTrendModule() binding.useTrendCheck.jumpDrawablesToCurrentState() val color = IconColorFinder.from(binding.root).invoke() CompoundDrawableColorApplier().invoke( color, binding.textUseViewHistory, binding.textDefaultSearchEngine, binding.textEnableSearchQueryExtract, binding.textEnableSearchWithClip, binding.textUseFavorite, binding.textUseHistory, binding.textUseSuggestion, binding.textUseTrend, binding.textUseUrlModule, binding.textSearchCategory ) } /** * Open search categories spinner. */ fun openSearchCategory() { binding.searchCategories.performClick() } /** * Switch search query extraction. */ fun switchSearchQueryExtract() { val newState = !preferenceApplier.enableSearchQueryExtract preferenceApplier.enableSearchQueryExtract = newState binding.enableSearchQueryExtractCheck.isChecked = newState } /** * Switch notification widget displaying. * * @param v only use [com.google.android.material.snackbar.Snackbar]'s parent. */ fun switchSearchWithClip(v: View) { val newState = !preferenceApplier.enableSearchWithClip preferenceApplier.enableSearchWithClip = newState binding.enableSearchWithClipCheck.isChecked = newState @StringRes val messageId: Int = if (newState) { R.string.message_enable_swc } else { R.string.message_disable_swc } Toaster.snackShort(v, messageId, preferenceApplier.colorPair()) } /** * Switch state of using query suggestion. */ fun switchUseSuggestion() { val newState = !preferenceApplier.isEnableSuggestion preferenceApplier.switchEnableSuggestion() binding.useSuggestionCheck.isChecked = newState } /** * Switch state of using search history words suggestion. */ fun switchUseSearchHistory() { val newState = !preferenceApplier.isEnableSearchHistory preferenceApplier.switchEnableSearchHistory() binding.useHistoryCheck.isChecked = newState } /** * Switch state of using favorite search word suggestion. */ fun switchUseFavoriteSearch() { val newState = !preferenceApplier.isEnableFavoriteSearch preferenceApplier.switchEnableFavoriteSearch() binding.useFavoriteCheck.isChecked = newState } /** * Switch state of using view history suggestion. */ fun switchUseViewHistory() { val newState = !preferenceApplier.isEnableViewHistory preferenceApplier.switchEnableViewHistory() binding.useViewHistoryCheck.isChecked = newState } /** * Switch state of using view history suggestion. */ fun switchUseUrlModule() { val newState = !preferenceApplier.isEnableUrlModule() preferenceApplier.switchEnableUrlModule() binding.useUrlModuleCheck.isChecked = newState } /** * Switch state of using trend suggestion. */ fun switchUseTrendModule() { val newState = !preferenceApplier.isEnableTrendModule() preferenceApplier.switchEnableTrendModule() binding.useTrendCheck.isChecked = newState } companion object : TitleIdSupplier { @LayoutRes private const val LAYOUT_ID = R.layout.fragment_setting_search @StringRes override fun titleId() = R.string.subhead_search } }
epl-1.0
2b229eda06758f8686fd23800a984528
36
104
0.710902
5.387656
false
false
false
false
consp1racy/android-commons
commons/src/main/java/net/xpece/android/widget/HeaderFooterRecyclerViewAdapter.kt
1
20971
package net.xpece.android.widget import android.support.v7.widget.RecyclerView import android.view.ViewGroup /** * Created by Eugen on 22.10.2016. */ abstract class HeaderFooterRecyclerViewAdapter<T : RecyclerView.ViewHolder> : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { internal const val VIEW_TYPE_MAX_COUNT = 0x0000ffff internal const val HEADER_VIEW_TYPE_OFFSET = VIEW_TYPE_MAX_COUNT internal const val CONTENT_VIEW_TYPE_OFFSET = HEADER_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT internal const val PRE_FOOTER_VIEW_TYPE_OFFSET = CONTENT_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT internal const val FOOTER_VIEW_TYPE_OFFSET = PRE_FOOTER_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT } fun isItemHeader(adapterPosition: Int): Boolean { val headerItemCount = this.headerItemCount return headerItemCount > 0 && adapterPosition < headerItemCount } fun isItemContent(adapterPosition: Int): Boolean { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount return contentItemCount > 0 && adapterPosition < headerItemCount + contentItemCount && adapterPosition >= headerItemCount } internal fun isItemPreFooter(adapterPosition: Int): Boolean { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount val preFooterItemCount = this.preFooterItemCount return preFooterItemCount > 0 && adapterPosition < headerItemCount + contentItemCount + preFooterItemCount && adapterPosition >= headerItemCount + contentItemCount } fun isItemFooter(adapterPosition: Int): Boolean { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount val preFooterItemCount = this.preFooterItemCount val footerItemCount = this.footerItemCount return footerItemCount > 0 && adapterPosition < headerItemCount + contentItemCount + preFooterItemCount + footerItemCount && adapterPosition >= headerItemCount + contentItemCount + preFooterItemCount } /** * Gets the header item view type. By default, this method returns 0. * @param position the position. * * * @return the header item view type (within the range [0 - VIEW_TYPE_MAX_COUNT-1]). */ protected open fun getHeaderItemViewType(position: Int) = 0 /** * Gets the footer item view type. By default, this method returns 0. * @param position the position. * * * @return the footer item view type (within the range [0 - VIEW_TYPE_MAX_COUNT-1]). */ protected open fun getFooterItemViewType(position: Int) = 0 /** * Gets the content item view type. By default, this method returns 0. * @param position the position. * * * @return the content item view type (within the range [0 - VIEW_TYPE_MAX_COUNT-1]). */ protected open fun getContentItemViewType(position: Int) = 0 internal open fun getPreFooterItemViewType(position: Int) = 0 override fun getItemViewType(position: Int): Int { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount val preFooterItemCount = this.preFooterItemCount val footerItemCount = this.footerItemCount // Delegate to proper methods based on the position, but validate first. if (headerItemCount > 0 && position < headerItemCount) { return validateViewType(getHeaderItemViewType(position)) + HEADER_VIEW_TYPE_OFFSET } else if (contentItemCount > 0 && position - headerItemCount < contentItemCount) { return validateViewType(getContentItemViewType(position - headerItemCount)) + CONTENT_VIEW_TYPE_OFFSET } else if (preFooterItemCount > 0 && position - headerItemCount - contentItemCount < preFooterItemCount) { return validateViewType(getPreFooterItemViewType(position - headerItemCount - contentItemCount)) + PRE_FOOTER_VIEW_TYPE_OFFSET } else if (footerItemCount > 0 && position - headerItemCount - contentItemCount - preFooterItemCount < footerItemCount) { return validateViewType(getFooterItemViewType(position - headerItemCount - contentItemCount - preFooterItemCount)) + FOOTER_VIEW_TYPE_OFFSET } else { throw IllegalArgumentException("No view type for position $position.") } } /** * Validates that the view type is within the valid range. * @param viewType the view type. * * @return the given view type. */ private fun validateViewType(viewType: Int): Int { if (viewType < 0 || viewType >= VIEW_TYPE_MAX_COUNT) { throw IllegalStateException("viewType must be between 0 and " + VIEW_TYPE_MAX_COUNT) } return viewType } /** * Gets the header item count. This method can be called several times, so it should not calculate the count every time. */ open val headerItemCount: Int get () = 0 /** * Gets the content item count. This method can be called several times, so it should not calculate the count every time. */ abstract val contentItemCount: Int /** * Gets the footer item count. This method can be called several times, so it should not calculate the count every time. */ open val footerItemCount: Int get() = 0 open internal val preFooterItemCount: Int get() = 0 override final fun getItemCount() = headerItemCount + contentItemCount + preFooterItemCount + footerItemCount @Suppress("UNCHECKED_CAST") override final fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount val preFooterItemCount = this.preFooterItemCount val footerItemCount = this.footerItemCount if (headerItemCount > 0 && position < headerItemCount) { onBindHeaderItemViewHolder(holder, position) } else if (contentItemCount > 0 && position - headerItemCount < contentItemCount) { onBindContentItemViewHolder(holder as T, position - headerItemCount) } else if (preFooterItemCount > 0 && position - headerItemCount - contentItemCount < preFooterItemCount) { onBindPreFooterItemViewHolder(holder, position - headerItemCount - contentItemCount) } else if (footerItemCount > 0 && position - headerItemCount - contentItemCount - preFooterItemCount < footerItemCount) { onBindFooterItemViewHolder(holder, position - headerItemCount - contentItemCount - preFooterItemCount) } else { throw IllegalStateException("Invalid position $position, item count is $itemCount.") } } @Suppress("UNCHECKED_CAST") override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int, payloads: List<@JvmSuppressWildcards Any>) { val headerItemCount = this.headerItemCount val contentItemCount = this.contentItemCount val preFooterItemCount = this.preFooterItemCount val footerItemCount = this.footerItemCount if (headerItemCount > 0 && position < headerItemCount) { onBindHeaderItemViewHolder(holder, position, payloads) } else if (contentItemCount > 0 && position - headerItemCount < contentItemCount) { onBindContentItemViewHolder(holder as T, position - headerItemCount, payloads) } else if (preFooterItemCount > 0 && position - headerItemCount - contentItemCount < preFooterItemCount) { onBindPreFooterItemViewHolder(holder, position - headerItemCount - contentItemCount, payloads) } else if (footerItemCount > 0 && position - headerItemCount - contentItemCount - preFooterItemCount < footerItemCount) { onBindFooterItemViewHolder(holder, position - headerItemCount - contentItemCount - preFooterItemCount, payloads) } else { throw IllegalStateException("Invalid position $position, item count is $itemCount.") } } override final fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { if (viewType >= HEADER_VIEW_TYPE_OFFSET && viewType < HEADER_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT) { return onCreateHeaderItemViewHolder(parent, viewType - HEADER_VIEW_TYPE_OFFSET) } else if (viewType >= CONTENT_VIEW_TYPE_OFFSET && viewType < CONTENT_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT) { return onCreateContentItemViewHolder(parent, viewType - CONTENT_VIEW_TYPE_OFFSET) } else if (viewType >= PRE_FOOTER_VIEW_TYPE_OFFSET && viewType < PRE_FOOTER_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT) { return onCreatePreFooterItemViewHolder(parent, viewType - PRE_FOOTER_VIEW_TYPE_OFFSET) } else if (viewType >= FOOTER_VIEW_TYPE_OFFSET && viewType < FOOTER_VIEW_TYPE_OFFSET + VIEW_TYPE_MAX_COUNT) { return onCreateFooterItemViewHolder(parent, viewType - FOOTER_VIEW_TYPE_OFFSET) } else { throw IllegalStateException("Unknown view type $viewType") } } /** * This method works exactly the same as [.onCreateViewHolder], but for header items. * @param parent the parent view. * * * @param headerViewType the view type for the header. * * * @return the view holder. */ protected open fun onCreateHeaderItemViewHolder(parent: ViewGroup, headerViewType: Int): RecyclerView.ViewHolder { throw UnsupportedOperationException() } /** * This method works exactly the same as [.onCreateViewHolder], but for footer items. * @param parent the parent view. * * * @param footerViewType the view type for the footer. * * * @return the view holder. */ protected open fun onCreateFooterItemViewHolder(parent: ViewGroup, footerViewType: Int): RecyclerView.ViewHolder { throw UnsupportedOperationException() } internal open fun onCreatePreFooterItemViewHolder(parent: ViewGroup, footerViewType: Int): RecyclerView.ViewHolder { throw UnsupportedOperationException() } /** * This method works exactly the same as [.onCreateViewHolder], but for content items. * @param parent the parent view. * * * @param contentViewType the view type for the content. * * * @return the view holder. */ protected abstract fun onCreateContentItemViewHolder(parent: ViewGroup, contentViewType: Int): T /** * This method works exactly the same as [.onBindViewHolder], but for header items. * @param headerViewHolder the view holder for the header item. * * * @param position the position. */ protected open fun onBindHeaderItemViewHolder(headerViewHolder: RecyclerView.ViewHolder, position: Int) { } /** * This method works exactly the same as [.onBindViewHolder], but for footer items. * @param footerViewHolder the view holder for the footer item. * * * @param position the position. */ protected open fun onBindFooterItemViewHolder(footerViewHolder: RecyclerView.ViewHolder, position: Int) { } internal open fun onBindPreFooterItemViewHolder(footerViewHolder: RecyclerView.ViewHolder, position: Int) { } /** * This method works exactly the same as [.onBindViewHolder], but for content items. * @param contentViewHolder the view holder for the content item. * * * @param position the position. */ protected abstract fun onBindContentItemViewHolder(contentViewHolder: T, position: Int) /** * This method works exactly the same as [.onBindViewHolder], but for header items. * @param headerViewHolder the view holder for the header item. * @param position the position. * @param payloads A non-null list of merged payloads. Can be empty list if requires full update. */ protected open fun onBindHeaderItemViewHolder(headerViewHolder: RecyclerView.ViewHolder, position: Int, payloads: List<@JvmSuppressWildcards Any>) { onBindHeaderItemViewHolder(headerViewHolder, position) } /** * This method works exactly the same as [.onBindViewHolder], but for footer items. * @param footerViewHolder the view holder for the footer item. * @param position the position. * @param payloads A non-null list of merged payloads. Can be empty list if requires full update. */ protected open fun onBindFooterItemViewHolder(footerViewHolder: RecyclerView.ViewHolder, position: Int, payloads: List<@JvmSuppressWildcards Any>) { onBindFooterItemViewHolder(footerViewHolder, position) } internal open fun onBindPreFooterItemViewHolder(footerViewHolder: RecyclerView.ViewHolder, position: Int, payloads: List<@JvmSuppressWildcards Any>) { onBindPreFooterItemViewHolder(footerViewHolder, position) } /** * This method works exactly the same as [.onBindViewHolder], but for content items. * @param contentViewHolder the view holder for the content item. * @param position the position. * @param payloads A non-null list of merged payloads. Can be empty list if requires full update. */ protected open fun onBindContentItemViewHolder(contentViewHolder: T, position: Int, payloads: List<@JvmSuppressWildcards Any>) { onBindContentItemViewHolder(contentViewHolder, position) } /** * Notifies that a header item is inserted. * @param position the position of the header item. */ fun notifyHeaderItemInserted(position: Int) { notifyHeaderItemRangeInserted(position, 1) } /** * Notifies that multiple header items are inserted. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyHeaderItemRangeInserted(positionStart: Int, itemCount: Int) { notifyItemRangeInserted(positionStart, itemCount) } /** * Notifies that a header item is changed. * @param position the position. */ fun notifyHeaderItemChanged(position: Int) { notifyHeaderItemRangeChanged(position, 1) } /** * Notifies that multiple header items are changed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyHeaderItemRangeChanged(positionStart: Int, itemCount: Int) { notifyItemRangeChanged(positionStart, itemCount) } /** * Notifies that an existing header item is moved to another position. * @param fromPosition the original position. * * * @param toPosition the new position. */ open fun notifyHeaderItemMoved(fromPosition: Int, toPosition: Int) { notifyItemMoved(fromPosition, toPosition) } /** * Notifies that a header item is removed. * @param position the position. */ fun notifyHeaderItemRemoved(position: Int) { notifyHeaderItemRangeRemoved(position, 1) } /** * Notifies that multiple header items are removed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyHeaderItemRangeRemoved(positionStart: Int, itemCount: Int) { notifyItemRangeRemoved(positionStart, itemCount) } /** * Notifies that a content item is inserted. * @param position the position of the content item. */ fun notifyContentItemInserted(position: Int) { notifyContentItemRangeInserted(position, 1) } /** * Notifies that multiple content items are inserted. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyContentItemRangeInserted(positionStart: Int, itemCount: Int) { notifyItemRangeInserted(positionStart + headerItemCount, itemCount) } /** * Notifies that a content item is changed. * @param position the position. */ fun notifyContentItemChanged(position: Int) { notifyContentItemRangeChanged(position, 1) } /** * Notifies that multiple content items are changed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyContentItemRangeChanged(positionStart: Int, itemCount: Int) { notifyItemRangeChanged(positionStart + headerItemCount, itemCount) } /** * Notifies that an existing content item is moved to another position. * @param fromPosition the original position. * * * @param toPosition the new position. */ open fun notifyContentItemMoved(fromPosition: Int, toPosition: Int) { notifyItemMoved(fromPosition + headerItemCount, toPosition + headerItemCount) } /** * Notifies that a content item is removed. * @param position the position. */ fun notifyContentItemRemoved(position: Int) { notifyContentItemRangeRemoved(position, 1) } /** * Notifies that multiple content items are removed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyContentItemRangeRemoved(positionStart: Int, itemCount: Int) { notifyItemRangeRemoved(positionStart + headerItemCount, itemCount) } /** * Notifies that a footer item is inserted. * @param position the position of the content item. */ fun notifyFooterItemInserted(position: Int) { notifyFooterItemRangeInserted(position, 1) } /** * Notifies that multiple footer items are inserted. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyFooterItemRangeInserted(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount + preFooterItemCount notifyItemRangeInserted(positionStart + offset, itemCount) } /** * Notifies that a footer item is changed. * @param position the position. */ fun notifyFooterItemChanged(position: Int) { notifyFooterItemRangeChanged(position, 1) } /** * Notifies that multiple footer items are changed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyFooterItemRangeChanged(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount + preFooterItemCount notifyItemRangeChanged(positionStart + offset, itemCount) } /** * Notifies that an existing footer item is moved to another position. * @param fromPosition the original position. * * * @param toPosition the new position. */ open fun notifyFooterItemMoved(fromPosition: Int, toPosition: Int) { val offset = headerItemCount + contentItemCount + preFooterItemCount notifyItemMoved(offset + fromPosition, toPosition + offset) } /** * Notifies that a footer item is removed. * @param position the position. */ fun notifyFooterItemRemoved(position: Int) { notifyFooterItemRangeRemoved(position, 1) } /** * Notifies that multiple footer items are removed. * @param positionStart the position. * * * @param itemCount the item count. */ open fun notifyFooterItemRangeRemoved(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount + preFooterItemCount notifyItemRangeRemoved(positionStart + offset, itemCount) } internal fun notifyPreFooterItemInserted(position: Int) { notifyFooterItemRangeInserted(position, 1) } open internal fun notifyPreFooterItemRangeInserted(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount notifyItemRangeInserted(positionStart + offset, itemCount) } internal fun notifyPreFooterItemChanged(position: Int) { notifyPreFooterItemRangeChanged(position, 1) } open internal fun notifyPreFooterItemRangeChanged(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount notifyItemRangeChanged(positionStart + offset, itemCount) } open internal fun notifyPreFooterItemMoved(fromPosition: Int, toPosition: Int) { val offset = headerItemCount + contentItemCount notifyItemMoved(offset + fromPosition, toPosition + offset) } internal fun notifyPreFooterItemRemoved(position: Int) { notifyPreFooterItemRangeRemoved(position, 1) } open internal fun notifyPreFooterItemRangeRemoved(positionStart: Int, itemCount: Int) { val offset = headerItemCount + contentItemCount notifyItemRangeRemoved(positionStart + offset, itemCount) } }
apache-2.0
0876fbb05d3984c7288bf1074b912c96
36.990942
154
0.688284
4.947157
false
false
false
false
amith01994/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/NetService.kt
9
4442
package org.jetbrains.builtInWebServer import com.intellij.execution.ExecutionException import com.intellij.execution.filters.TextConsoleBuilder import com.intellij.execution.process.OSProcessHandler import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.ui.ConsoleViewContentType import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.util.Consumer import com.intellij.util.net.NetUtils import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.AsyncValueLoader import org.jetbrains.concurrency.Promise import org.jetbrains.util.concurrency import org.jetbrains.util.concurrency.toPromise import javax.swing.Icon val LOG: Logger = Logger.getInstance(javaClass<NetService>()) public abstract class NetService @jvmOverloads protected constructor(protected val project: Project, private val consoleManager: ConsoleManager = ConsoleManager()) : Disposable { protected val processHandler: AsyncValueLoader<OSProcessHandler> = object : AsyncValueLoader<OSProcessHandler>() { override fun isCancelOnReject() = true private fun doGetProcessHandler(port: Int): OSProcessHandler? { try { return createProcessHandler(project, port) } catch (e: ExecutionException) { LOG.error(e) return null } } override fun load(promise: AsyncPromise<OSProcessHandler>): Promise<OSProcessHandler> { val port = NetUtils.findAvailableSocketPort() val processHandler = doGetProcessHandler(port) if (processHandler == null) { promise.setError("rejected") return promise } promise.rejected(Consumer { processHandler.destroyProcess() Promise.logError(LOG, it) }) val processListener = MyProcessAdapter() processHandler.addProcessListener(processListener) processHandler.startNotify() if (promise.getState() == Promise.State.REJECTED) { return promise } ApplicationManager.getApplication().executeOnPooledThread(object : Runnable { override fun run() { if (promise.getState() != Promise.State.REJECTED) { try { connectToProcess(promise.toPromise(), port, processHandler, processListener) } catch (e: Throwable) { if (!promise.setError(e)) { LOG.error(e) } } } } }) return promise } override fun disposeResult(processHandler: OSProcessHandler) { try { closeProcessConnections() } finally { processHandler.destroyProcess() } } } throws(ExecutionException::class) protected abstract fun createProcessHandler(project: Project, port: Int): OSProcessHandler? protected open fun connectToProcess(promise: concurrency.AsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) { promise.setResult(processHandler) } protected abstract fun closeProcessConnections() override fun dispose() { processHandler.reset() } protected open fun configureConsole(consoleBuilder: TextConsoleBuilder) { } protected abstract fun getConsoleToolWindowId(): String protected abstract fun getConsoleToolWindowIcon(): Icon public open fun getConsoleToolWindowActions(): ActionGroup = DefaultActionGroup() private inner class MyProcessAdapter : ProcessAdapter(), Consumer<String> { override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { print(event.getText(), ConsoleViewContentType.getConsoleViewType(outputType)) } private fun print(text: String, contentType: ConsoleViewContentType) { consoleManager.getConsole(this@NetService).print(text, contentType) } override fun processTerminated(event: ProcessEvent) { processHandler.reset() print("${getConsoleToolWindowId()} terminated\n", ConsoleViewContentType.SYSTEM_OUTPUT) } override fun consume(message: String) { print(message, ConsoleViewContentType.ERROR_OUTPUT) } } }
apache-2.0
dfbf1ee008ad4d85885122c369c1bb99
33.44186
178
0.731652
5.159117
false
false
false
false
Tapadoo/Alerter
alerter/src/main/java/com/tapadoo/alerter/SwipeDismissTouchListener.kt
1
9367
package com.tapadoo.alerter /* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications Copyright (C) 2017 David Kwon */ import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.os.Build import androidx.annotation.RequiresApi import android.view.MotionEvent import android.view.VelocityTracker import android.view.View import android.view.ViewConfiguration /** * A [View.OnTouchListener] that makes any [View] dismissable when the * user swipes (drags her finger) horizontally across the view. * * @param mView The view to make dismissable. * @param mCallbacks The callback to trigger when the user has indicated that she would like to * dismiss this view. */ internal class SwipeDismissTouchListener( private val mView: View, private val mCallbacks: DismissCallbacks) : View.OnTouchListener { // Cached ViewConfiguration and system-wide constant values private val mSlop: Int private val mMinFlingVelocity: Int private val mAnimationTime: Long private var mViewWidth = 1 // 1 and not 0 to prevent dividing by zero // Transient properties private var mDownX: Float = 0.toFloat() private var mDownY: Float = 0.toFloat() private var mSwiping: Boolean = false private var mSwipingSlop: Int = 0 private var mVelocityTracker: VelocityTracker? = null private var mTranslationX: Float = 0.toFloat() init { val vc = ViewConfiguration.get(mView.context) mSlop = vc.scaledTouchSlop mMinFlingVelocity = vc.scaledMinimumFlingVelocity * 16 mAnimationTime = mView.context.resources.getInteger( android.R.integer.config_shortAnimTime).toLong() } @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1) override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { // offset because the view is translated during swipe motionEvent.offsetLocation(mTranslationX, 0f) if (mViewWidth < 2) { mViewWidth = mView.width } when (motionEvent.actionMasked) { MotionEvent.ACTION_DOWN -> { mDownX = motionEvent.rawX mDownY = motionEvent.rawY if (mCallbacks.canDismiss()) { mVelocityTracker = VelocityTracker.obtain() mVelocityTracker!!.addMovement(motionEvent) } mCallbacks.onTouch(view, true) return false } MotionEvent.ACTION_UP -> { mVelocityTracker?.run { val deltaX = motionEvent.rawX - mDownX this.addMovement(motionEvent) this.computeCurrentVelocity(1000) val velocityX = this.xVelocity val absVelocityX = Math.abs(velocityX) val absVelocityY = Math.abs(this.yVelocity) var dismiss = false var dismissRight = false if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) { dismiss = true dismissRight = deltaX > 0 } else if (mMinFlingVelocity <= absVelocityX && absVelocityY < absVelocityX && mSwiping) { // dismiss only if flinging in the same direction as dragging dismiss = velocityX < 0 == deltaX < 0 dismissRight = this.xVelocity > 0 } if (dismiss) { // dismiss mView.animate() .translationX((if (dismissRight) mViewWidth else -mViewWidth).toFloat()) .alpha(0f) .setDuration(mAnimationTime) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { performDismiss() } }) } else if (mSwiping) { // cancel mView.animate() .translationX(0f) .alpha(1f) .setDuration(mAnimationTime) .setListener(null) mCallbacks.onTouch(view, false) } this.recycle() mVelocityTracker = null mTranslationX = 0f mDownX = 0f mDownY = 0f mSwiping = false } } MotionEvent.ACTION_CANCEL -> { mVelocityTracker?.run { mView.animate() .translationX(0f) .alpha(1f) .setDuration(mAnimationTime) .setListener(null) this.recycle() mVelocityTracker = null mTranslationX = 0f mDownX = 0f mDownY = 0f mSwiping = false } } MotionEvent.ACTION_MOVE -> { mVelocityTracker?.run { this.addMovement(motionEvent) val deltaX = motionEvent.rawX - mDownX val deltaY = motionEvent.rawY - mDownY if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) { mSwiping = true mSwipingSlop = if (deltaX > 0) mSlop else -mSlop mView.parent.requestDisallowInterceptTouchEvent(true) // Cancel listview's touch val cancelEvent = MotionEvent.obtain(motionEvent) cancelEvent.action = MotionEvent.ACTION_CANCEL or (motionEvent.actionIndex shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) mView.onTouchEvent(cancelEvent) cancelEvent.recycle() } if (mSwiping) { mTranslationX = deltaX mView.translationX = deltaX - mSwipingSlop // TODO: use an ease-out interpolator or such mView.alpha = Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)) return true } } } else -> { view.performClick() return false } } return false } @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) private fun performDismiss() { // Animate the dismissed view to zero-height and then fire the dismiss callback. // This triggers layout on each animation frame; in the future we may want to do something // smarter and more performant. val lp = mView.layoutParams val originalHeight = mView.height val animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { mCallbacks.onDismiss(mView) // Reset view presentation mView.alpha = 1f mView.translationX = 0f lp.height = originalHeight mView.layoutParams = lp } }) animator.addUpdateListener { valueAnimator -> lp.height = valueAnimator.animatedValue as Int mView.layoutParams = lp } animator.start() } /** * The callback interface used by [SwipeDismissTouchListener] to inform its client * about a successful dismissal of the view for which it was created. */ internal interface DismissCallbacks { /** * Called to determine whether the view can be dismissed. * * @return boolean The view can dismiss. */ fun canDismiss(): Boolean /** * Called when the user has indicated they she would like to dismiss the view. * * @param view The originating [View] */ fun onDismiss(view: View) /** * Called when the user touches the view or release the view. * * @param view The originating [View] * @param touch The view is being touched. */ fun onTouch(view: View, touch: Boolean) } }
mit
9de788ec4ce888fd88d85b7e58a6b6c2
38.361345
142
0.539447
5.683859
false
false
false
false
google/ksp
benchmark/exhaustive-processor/processor/src/main/kotlin/ExhaustiveProcessor.kt
1
7792
/* * Copyright 2022 Google LLC * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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. */ import com.google.devtools.ksp.isLocal import com.google.devtools.ksp.processing.CodeGenerator import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.processing.SymbolProcessor import com.google.devtools.ksp.processing.SymbolProcessorEnvironment import com.google.devtools.ksp.processing.SymbolProcessorProvider import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.visitor.KSTopDownVisitor import java.io.File class ExhaustiveProcessor( val codeGenerator: CodeGenerator, val options: Map<String, String> ) : SymbolProcessor { val file: File? = null override fun finish() { } override fun process(resolver: Resolver): List<KSAnnotated> { file?.writeText("") val visitor = ExhaustiveVisitor() resolver.getAllFiles().forEach { it.accept(visitor, Unit) } file?.appendText(visitor.collectedNodes.joinToString("\n")) return emptyList() } inner class ExhaustiveVisitor : KSTopDownVisitor<Unit, Unit>() { val collectedNodes = mutableListOf<String>() override fun defaultHandler(node: KSNode, data: Unit) { file?.appendText("--- visiting ${node.location} ---\n") } override fun visitAnnotated(annotated: KSAnnotated, data: Unit) { super.visitAnnotated(annotated, data) } override fun visitAnnotation(annotation: KSAnnotation, data: Unit) { file?.appendText("ANNO: ${annotation.shortName}") annotation.shortName annotation.useSiteTarget super.visitAnnotation(annotation, data) } override fun visitCallableReference(reference: KSCallableReference, data: Unit) { super.visitCallableReference(reference, data) } override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) { classDeclaration.classKind classDeclaration.primaryConstructor?.accept(this, Unit) classDeclaration.isCompanionObject classDeclaration.getAllFunctions().map { it.accept(this, Unit) } classDeclaration.getAllProperties().map { it.accept(this, Unit) } classDeclaration.asStarProjectedType() if (classDeclaration.origin != Origin.KOTLIN_LIB && classDeclaration.origin != Origin.JAVA_LIB) { classDeclaration.superTypes.map { it.accept(this, Unit) } } return super.visitClassDeclaration(classDeclaration, data) } override fun visitClassifierReference(reference: KSClassifierReference, data: Unit) { reference.referencedName() super.visitClassifierReference(reference, data) } override fun visitDeclaration(declaration: KSDeclaration, data: Unit) { declaration.containingFile declaration.packageName declaration.qualifiedName declaration.simpleName declaration.parentDeclaration super.visitDeclaration(declaration, data) } override fun visitDeclarationContainer(declarationContainer: KSDeclarationContainer, data: Unit) { super.visitDeclarationContainer(declarationContainer, data) } override fun visitDynamicReference(reference: KSDynamicReference, data: Unit) { super.visitDynamicReference(reference, data) } override fun visitFile(file: KSFile, data: Unit) { file.fileName file.packageName file.filePath super.visitFile(file, data) } override fun visitFunctionDeclaration(function: KSFunctionDeclaration, data: Unit) { function.functionKind function.isAbstract function.findOverridee() super.visitFunctionDeclaration(function, data) } override fun visitModifierListOwner(modifierListOwner: KSModifierListOwner, data: Unit) { modifierListOwner.modifiers super.visitModifierListOwner(modifierListOwner, data) } override fun visitNode(node: KSNode, data: Unit) { collectedNodes.add(node.origin.toString()) collectedNodes.add(node.location.toString()) super.visitNode(node, data) } override fun visitParenthesizedReference(reference: KSParenthesizedReference, data: Unit) { super.visitParenthesizedReference(reference, data) } override fun visitPropertyAccessor(accessor: KSPropertyAccessor, data: Unit) { accessor.receiver super.visitPropertyAccessor(accessor, data) } override fun visitPropertyDeclaration(property: KSPropertyDeclaration, data: Unit) { if (!property.isLocal()) { property.isMutable property.findOverridee() property.isDelegated() } super.visitPropertyDeclaration(property, data) } override fun visitPropertyGetter(getter: KSPropertyGetter, data: Unit) { super.visitPropertyGetter(getter, data) } override fun visitPropertySetter(setter: KSPropertySetter, data: Unit) { super.visitPropertySetter(setter, data) } override fun visitReferenceElement(element: KSReferenceElement, data: Unit) { super.visitReferenceElement(element, data) } override fun visitTypeAlias(typeAlias: KSTypeAlias, data: Unit) { typeAlias.name super.visitTypeAlias(typeAlias, data) } override fun visitTypeArgument(typeArgument: KSTypeArgument, data: Unit) { typeArgument.variance super.visitTypeArgument(typeArgument, data) } override fun visitTypeParameter(typeParameter: KSTypeParameter, data: Unit) { typeParameter.name typeParameter.variance typeParameter.isReified super.visitTypeParameter(typeParameter, data) } override fun visitTypeReference(typeReference: KSTypeReference, data: Unit) { typeReference.resolve() super.visitTypeReference(typeReference, data) } override fun visitValueArgument(valueArgument: KSValueArgument, data: Unit) { valueArgument.name valueArgument.isSpread valueArgument.value super.visitValueArgument(valueArgument, data) } override fun visitValueParameter(valueParameter: KSValueParameter, data: Unit) { valueParameter.name valueParameter.isCrossInline valueParameter.isNoInline valueParameter.isVal valueParameter.isVar valueParameter.isVararg valueParameter.hasDefault super.visitValueParameter(valueParameter, data) } } } class ExhaustiveProcessorProvider : SymbolProcessorProvider { override fun create( env: SymbolProcessorEnvironment ): SymbolProcessor { return ExhaustiveProcessor(env.codeGenerator, env.options) } }
apache-2.0
ad09b22c5043d8e4616774f00c975809
37.384236
109
0.668891
5.37009
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIFont.kt
1
1428
package com.yy.codex.uikit import android.graphics.Typeface import android.graphics.Typeface.DEFAULT import android.graphics.Typeface.DEFAULT_BOLD import android.text.TextPaint /** * Created by cuiminghui on 2017/1/9. */ class UIFont(val fontFamily: String?, val fontSize: Float) { constructor(fontSize: Float): this(null, fontSize) val typeface: Typeface? get() { val fontFamily = fontFamily ?: return Typeface.create(fontFamily, Typeface.NORMAL) if (fontFamily.equals("System", ignoreCase = true)) { return DEFAULT } else if (fontFamily.equals("SystemBold", ignoreCase = true)) { return DEFAULT_BOLD } else { return Typeface.create(fontFamily, Typeface.NORMAL) } } private val textPaint = TextPaint() var lineHeight: Double = 0.0 get() { typeface?.let { textPaint.typeface = it textPaint.textSize = (fontSize * UIScreen.mainScreen.scale()).toFloat() return (Math.abs(textPaint.fontMetrics.ascent).toDouble() + Math.abs(textPaint.fontMetrics.descent).toDouble()) / UIScreen.mainScreen.scale() } return 0.0 } companion object { fun systemBold(fontSize: Float): UIFont { return UIFont("SystemBold", fontSize) } } }
gpl-3.0
cd675ba5f241be54c88eb346deff7965
27
157
0.595938
4.697368
false
false
false
false
michael-johansen/workshop-jb
src/v_collections/B_FilterMap.kt
4
867
package v_collections fun example1(list: List<Int>) { // If a lambda has exactly one parameter, that parameter can be accessed as 'it' val positiveNumbers = list.filter { it > 0 } val squares = list.map { it * it } } fun Shop.getCitiesCustomersAreFrom(): Set<City> { // Return the set of cities the customers are from todoCollectionTask() } fun Shop.getCustomersFrom(city: City): List<Customer> { // Return a list of the customers who live in the given city todoCollectionTask() } //Note fun whyMapOperationOnSetReturnsListNotSet() { class Client(val name: String, val city: String) val clients = setOf(Client("Noah", "Ottawa"), Client("Xavier", "Ottawa")) val cities = clients.map { it.city } // If map returned a set of cities (instead of a list): clients.size() != cities.size() // could be surprising! }
mit
ff2bbd70843d68d8057c8dec78fbe9de
25.272727
84
0.679354
3.769565
false
false
false
false
SimpleTimeTracking/StandaloneClient
src/main/kotlin/org/stt/persistence/stt/STTItemPersister.kt
1
3200
package org.stt.persistence.stt import org.stt.model.TimeTrackingItem import org.stt.persistence.ItemPersister import java.io.* import java.util.* import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton /** * Writes [TimeTrackingItem]s to a new line. Multiline comments get joined * into one line: line endings \r and \n get replaced by the string \r and \n * respectively. */ @Singleton class STTItemPersister @Inject constructor(@STTFile val readerProvider: Provider<Reader>, @STTFile val writerProvider: Provider<Writer>) : ItemPersister { private val converter = STTItemConverter() override fun persist(itemToInsert: TimeTrackingItem) { val stringWriter = StringWriter() val providedReader: Reader = readerProvider.get() try { STTItemReader(providedReader).use { `in` -> STTItemWriter(stringWriter).use { out -> InsertHelper(`in`, out, itemToInsert).performInsert() } rewriteFileWith(stringWriter.toString()) } } catch (e: IOException) { throw UncheckedIOException(e) } } override fun replace(item: TimeTrackingItem, with: TimeTrackingItem) { delete(item) persist(with) } override fun delete(item: TimeTrackingItem) { val stringWriter = StringWriter() val printWriter = PrintWriter(stringWriter) val lineOfItemToDelete = converter.timeTrackingItemToLine(item) BufferedReader(readerProvider.get()).useLines { it.filter { it != lineOfItemToDelete }.forEach { printWriter.println(it) } } rewriteFileWith(stringWriter.toString()) } override fun updateActivitities(itemsToUpdate: Collection<TimeTrackingItem>, newActivity: String): Collection<ItemPersister.UpdatedItem> { try { STTItemReader(readerProvider.get()).use { `in` -> StringWriter().use { sw -> STTItemWriter(sw).use { out -> val matchingItems = HashSet(itemsToUpdate) val updatedItems = ArrayList<ItemPersister.UpdatedItem>() while (true) { `in`.read()?.let { val toWrite = if (matchingItems.contains(it)) { val updateItem = it.withActivity(newActivity) updatedItems.add(ItemPersister.UpdatedItem(it, updateItem)) updateItem } else it out.write(toWrite) } ?: break } rewriteFileWith(sw.toString()) return updatedItems } } } } catch (e: IOException) { throw UncheckedIOException(e) } } private fun rewriteFileWith(content: String) { writerProvider.get().use { it.write(content) } } }
gpl-3.0
5337f7b4776ff4bb801ce2c1410d3e48
34.955056
142
0.553438
5.306799
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/util/image/BitmapTransformation.kt
1
1731
package com.booboot.vndbandroid.util.image import android.content.Context import android.graphics.* import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicBlur object BitmapTransformation { fun darkBlur(context: Context, bitmap: Bitmap): Bitmap { return darken(blur(context, bitmap)) } fun blur(context: Context, bitmap: Bitmap): Bitmap { val rs = RenderScript.create(context) // Create another bitmap that will hold the results of the filter. val blurredBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true) // Allocate memory for Renderscript to work with val input = Allocation.createFromBitmap(rs, blurredBitmap, Allocation.MipmapControl.MIPMAP_FULL, Allocation.USAGE_SHARED) val output = Allocation.createTyped(rs, input.type) // Load up an instance of the specific script that we want to use. val script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)) script.setInput(input) // Set the blur radius script.setRadius(25f) // Start the ScriptIntrinisicBlur script.forEach(output) // Copy the output to the blurred bitmap output.copyTo(blurredBitmap) return blurredBitmap } fun darken(bitmap: Bitmap): Bitmap { val canvas = Canvas(bitmap) val p = Paint(Color.RED) //ColorFilter filter = new LightingColorFilter(0xFFFFFFFF , 0x00222222); // lighten val filter = LightingColorFilter(-0x808081, 0x00000000) // darken p.colorFilter = filter canvas.drawBitmap(bitmap, Matrix(), p) return bitmap } }
gpl-3.0
7fd5093c7c42e6ec95f753160a77849b
32.960784
129
0.693241
4.382278
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_hrs/src/main/java/no/nordicsemi/android/hrs/view/HRSScreen.kt
1
4250
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.hrs.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import no.nordicsemi.android.hrs.R import no.nordicsemi.android.hrs.viewmodel.HRSViewModel import no.nordicsemi.android.service.* import no.nordicsemi.android.ui.view.BackIconAppBar import no.nordicsemi.android.ui.view.LoggerIconAppBar import no.nordicsemi.android.utils.exhaustive import no.nordicsemi.ui.scanner.ui.DeviceConnectingView import no.nordicsemi.ui.scanner.ui.DeviceDisconnectedView import no.nordicsemi.ui.scanner.ui.NoDeviceView import no.nordicsemi.ui.scanner.ui.Reason @Composable fun HRSScreen() { val viewModel: HRSViewModel = hiltViewModel() val state = viewModel.state.collectAsState().value Column { val navigateUp = { viewModel.onEvent(NavigateUpEvent) } AppBar(state, navigateUp, viewModel) Column(modifier = Modifier.verticalScroll(rememberScrollState())) { when (state) { NoDeviceState -> NoDeviceView() is WorkingState -> when (state.result) { is IdleResult, is ConnectingResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) } is ConnectedResult -> DeviceConnectingView { viewModel.onEvent(DisconnectEvent) } is DisconnectedResult -> DeviceDisconnectedView(Reason.USER, navigateUp) is LinkLossResult -> DeviceDisconnectedView(Reason.LINK_LOSS, navigateUp) is MissingServiceResult -> DeviceDisconnectedView(Reason.MISSING_SERVICE, navigateUp) is UnknownErrorResult -> DeviceDisconnectedView(Reason.UNKNOWN, navigateUp) is SuccessResult -> HRSContentView(state.result.data, state.zoomIn) { viewModel.onEvent(it) } } }.exhaustive } } } @Composable private fun AppBar(state: HRSViewState, navigateUp: () -> Unit, viewModel: HRSViewModel) { val toolbarName = (state as? WorkingState)?.let { (it.result as? DeviceHolder)?.deviceName() } if (toolbarName == null) { BackIconAppBar(stringResource(id = R.string.hrs_title), navigateUp) } else { LoggerIconAppBar(toolbarName, navigateUp, { viewModel.onEvent(DisconnectEvent) }) { viewModel.onEvent(OpenLoggerEvent) } } }
bsd-3-clause
bd996accf69636b25578f12a3f78de38
44.212766
113
0.734588
4.624592
false
false
false
false
jtransc/jtransc
jtransc-core/src/com/jtransc/plugin/reflection/AstBuilderExt.kt
1
2833
package com.jtransc.plugin.reflection import com.jtransc.ast.* fun AstProgram.createClass(name: FqName, parent: FqName? = "java.lang.Object".fqname, interfaces: List<FqName> = listOf(), gen: AstClass.() -> Unit = { }): AstClass { val program = this val clazz = AstClass("source", program, name, AstModifiers.withFlags(AstModifiers.ACC_PUBLIC), parent, interfaces) clazz.gen() program.add(clazz) return clazz } fun AstClass.hasMethod(name: String, desc: AstType.METHOD): Boolean { return this.getMethod(name, desc.desc) != null } fun AstClass.createMethod(name: String, desc: AstType.METHOD, isStatic: Boolean = false, asyncOpt: Boolean? = null, body: AstBuilder2.(args: List<AstArgument>) -> Unit = { RETURN() }): AstMethod { val clazz = this val types: AstTypes = this.program.types val method = AstMethod( containingClass = clazz, name = name, methodType = desc, annotations = listOf(), parameterAnnotations = listOf(), modifiers = AstModifiers(AstModifiers.ACC_PUBLIC or if (isStatic) AstModifiers.ACC_STATIC else 0), generateBody = { AstBody(types, AstBuilder2(types, AstBuilderBodyCtx()).apply { body(desc.args) }.genstm(), desc, AstMethodRef(clazz.name, name, desc)) }, defaultTag = null, signature = desc.mangle(), genericSignature = null ) method.asyncOpt = asyncOpt clazz.add(method) return method } fun AstClass.createConstructor(desc: AstType.METHOD, asyncOpt: Boolean? = null, body: AstBuilder2.(args: List<AstArgument>) -> Unit = { RETURN() }): AstMethod { return createMethod("<init>", desc, isStatic = false, body = body, asyncOpt = asyncOpt) } fun AstClass.createField(name: String, type: AstType, isStatic: Boolean = false, constantValue: Any? = null): AstField { val clazz = this val types: AstTypes = this.program.types val field = AstField( containingClass = clazz, name = name, type = type, modifiers = AstModifiers(AstModifiers.ACC_PUBLIC or if (isStatic) AstModifiers.ACC_STATIC else 0), desc = type.mangle(), annotations = listOf(), genericSignature = null, constantValue = constantValue, types = types ) clazz.add(field) return field } fun AstProgram.createDataClass(name: FqName, fieldsInfo: List<Pair<String, AstType>>, parent: FqName = "java.lang.Object".fqname, interfaces: List<FqName> = listOf(), gen: AstClass.() -> Unit = { }): AstClass { val clazz = createClass(name, parent, interfaces) { val fields = fieldsInfo.map { createField(it.first, it.second) } val args = fieldsInfo.withIndex().map { AstArgument(it.index, it.value.second) } createConstructor(AstType.METHOD(args, AstType.VOID), asyncOpt = false) { for ((arg, field) in args.zip(fields)) { STM(AstStm.SET_FIELD_INSTANCE(field.ref, THIS, arg.expr)) } } } clazz.gen() return clazz } /* class AstBuilder(val program: AstProgram) { fun createClass } */
apache-2.0
2142fffabbc52d8419823726d99a54c2
35.333333
210
0.716202
3.429782
false
false
false
false
orbit/orbit
src/orbit-client/src/test/kotlin/orbit/client/BasicActorTests.kt
1
6679
/* Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved. This file is part of the Orbit Project <https://www.orbit.cloud>. See license in LICENSE. */ package orbit.client import io.kotlintest.shouldBe import kotlinx.coroutines.Deferred import kotlinx.coroutines.awaitAll import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import orbit.client.actor.ActorWithNoImpl import orbit.client.actor.ArgumentOnDeactivate import orbit.client.actor.BasicOnDeactivate import orbit.client.actor.ComplexDtoActor import orbit.client.actor.GreeterActor import orbit.client.actor.IdActor import orbit.client.actor.IncrementActor import orbit.client.actor.NullActor import orbit.client.actor.SuspendingMethodActor import orbit.client.actor.TestException import orbit.client.actor.ThrowingActor import orbit.client.actor.TimeoutActor import orbit.client.actor.TrackingGlobals import orbit.client.actor.createProxy import orbit.client.util.TimeoutException import orbit.util.misc.RNGUtils import org.junit.Test import org.junit.jupiter.api.assertThrows import java.io.InvalidObjectException import kotlin.test.assertEquals import kotlin.test.assertTrue class BasicActorTests : BaseIntegrationTest() { @Test fun `test basic actor request response`() { runBlocking { val actor = client.actorFactory.createProxy<GreeterActor>() val result = actor.greetAsync("Joe").await() assertEquals(result, "Hello Joe") } } @Test fun `test basic actor request response concurrent`() { runBlocking { val list = mutableListOf<Deferred<String>>() repeat(100) { val actor = client.actorFactory.createProxy<GreeterActor>() list += actor.greetAsync("Joe") } list.awaitAll().forEach { assertEquals(it, "Hello Joe") } } } @Test fun `test complex dto request response`() { runBlocking { val actor = client.actorFactory.createProxy<ComplexDtoActor>() actor.complexCall(ComplexDtoActor.ComplexDto("Hello")).await() } } @Test(expected = TestException::class) fun `ensure throw fails`() { runBlocking { val actor = client.actorFactory.createProxy<ThrowingActor>() actor.doThrow().await() } } @Test(expected = IllegalStateException::class) fun `ensure invalid actor type throws`() { runBlocking { val actor = client.actorFactory.createProxy<ActorWithNoImpl>() actor.greetAsync("Daniel Jackson").await() } } @Test(expected = TimeoutException::class) fun `ensure message timeout throws`() { runBlocking { val actor = client.actorFactory.createProxy<TimeoutActor>() actor.timeout().await() } } @Test fun `ensure actor reused`() { runBlocking { val actor = client.actorFactory.createProxy<IncrementActor>() val result1 = actor.increment().await() val result2 = actor.increment().await() assertTrue(result2 > result1) } } @Test fun `ensure actor deactivates`() { runBlocking { val actor = client.actorFactory.createProxy<IncrementActor>() val call1 = actor.increment().await() advanceTime(client.config.addressableTTL.multipliedBy(2)) delay(client.config.tickRate.toMillis() * 2) // Wait twice the tick so the deactivation should have happened val call2 = actor.increment().await() assertTrue(call2 <= call1) } } @Test fun `ensure method onDeactivate`() { runBlocking { val before = TrackingGlobals.deactivateTestCounts.get() val argActor = client.actorFactory.createProxy<BasicOnDeactivate>() argActor.greetAsync("Test").await() val noArgActor = client.actorFactory.createProxy<ArgumentOnDeactivate>() noArgActor.greetAsync("Test").await() advanceTime(client.config.addressableTTL.multipliedBy(2)) delay(client.config.tickRate.toMillis() * 2) // Wait twice the tick so the deactivation should have happened val after = TrackingGlobals.deactivateTestCounts.get() assertTrue(before < after) } } @Test fun `test actor with id and context`() { runBlocking { val actorKey = RNGUtils.randomString(128) val actor = client.actorFactory.createProxy<IdActor>(actorKey) val result = actor.getId().await() assertEquals(result, actorKey) } } @Test fun `test actor with simple null argument`() { runBlocking { val actor = client.actorFactory.createProxy<NullActor>() val result = actor.simpleNull("Hi ", null).await() assertEquals("Hi null", result) } } @Test fun `test actor with complex null argument`() { runBlocking { val actor = client.actorFactory.createProxy<NullActor>() val result = actor.complexNull("Bob ", null).await() assertEquals("Bob null", result) } } @Test(expected = TestException::class) fun `test platform exception`() { runBlocking { val customClient = startClient( namespace = "platformExceptionTest", platformExceptions = true ) val actor = customClient.actorFactory.createProxy<ThrowingActor>() actor.doThrow().await() } } @Test fun `Calling an actor with a suspended method returns correct result`() { runBlocking { val actor = client.actorFactory.createProxy<SuspendingMethodActor>("test") actor.ping("test message") shouldBe "test message" } } @Test fun `Deactivating actor with suspend onDeactivate calls deactivate`() { runBlocking { val actor = client.actorFactory.createProxy<SuspendingMethodActor>("test") actor.ping("test message") shouldBe "test message" disconnectClient() TrackingGlobals.deactivateTestCounts.get() shouldBe 1 } } @Test fun `Actor with suspending method with error throws exception`() { runBlocking { val actor = client.actorFactory.createProxy<SuspendingMethodActor>("test") assertThrows<InvalidObjectException> { runBlocking { actor.fail() } } } } }
bsd-3-clause
6160508e249ec710be13181382aecc15
30.956938
120
0.631232
4.710155
false
true
false
false
hanmomhanda/DesignPatterns
zTest/KotlinTest.kt
1
4138
package zTest import java.time.LocalDate import java.time.Month /** * Created by hanmomhanda on 2016-07-02. */ fun main(args: Array<String>) { // ifExpression() 을 여기에서 호출하면 컴파일에러 // 조건식 fun ifExpression() { println("===== if expression =====") val a = 1 val b = 2 println( if (a > b) a else b ) // 대신 3항연산자가 없다.. // println( a > b ? a : b) // 컴파일에러 } ifExpression() // null-safety fun nullSafety() { println("===== null-safety =====") // 아래는 컴파일 에러 // val a: Int = null // Int는 null을 할당받을 수 없다. // 타입에 `?`를 붙여주면 null을 할당받을 수 있는 Nullable 타입이 된다. val a: LocalDate? = null // LocalDate 타입의 변수는 LocalDate 의 모든 메서드를 호출할 수 있지만, val today: LocalDate = LocalDate.now() println("today.dayOfMonth : " + today.dayOfMonth) // LocalDate? 타입의 변수는 그렇지 않다. // println("a,dayOfMonth : " + a.dayOfMonth) // 컴파일 에러 발생 // Nullable 타입의 변수 a에 ? 후치연산자를 붙여주면, a? 는 다시 Non-null 타입이 되어 LocalDate의 모든 메서드를 호출할 수 있게 된다. // Nullable 타입의 변수 a가 null 이라면 a?.anyMethod()는 실행되지 않고 그냥 null을 반환한다. println("a?.dayOfMonth : " + a?.dayOfMonth) // 컴파일 에러 발생하지 않는다. a가 null 이므로 a?.dayOfMonth는 실행되지 않고 그냥 null 반환 // 따라서 Nullable 타입의 변수에 ? 후치연산자를 붙여 사용하는 것이 일반적으로 가장 자연스럽다 // Nullable 타입의 변수에 !! 후치연산자를 쓰면 NPE가 발생하게 할 수 있다. print("a!!.dayOfMonth()로 호출되면 NPE 발생 : ") // println(a!!.dayOfMonth) // 컴파일 에러는 발생하지 않으며, 실행 시 이 지점에서 NPE 발생 println("") // Non-null 타입의 변수는 !! 후치연산자를 붙여주지 않아도 NPE가 발생할 수 있으므로, Non-null 타입의 변수에는 !! 사용 불필요 // Elvis 연산자(?:)는 연산자의 왼쪽 식이 null 이 아니면 왼쪽 식의 값을 반환하고 오른쪽 식은 평가하지 않으며, // 왼쪽 식의 값이 null 이면 우측 식을 평가하고 결과값을 반환한다. val b: String? = "abc" val l1 = b?.length ?: -1 println("""length of "abc" : $l1""") val nullB: String? = null val l2 = nullB?.length ?: -1 println("""length of nullableString : $l2""") // null 은 Any 타입이 아니다. println("null is Any : " + (null is Any).toString()) // null 은 Any? 타입이다. println("null is Any? : " + (null is Any?).toString()) // Any? 타입에 // 따라서 null.toString()은 NPE를 발생하지 않는다. println("toString() of Any is invoked : " + null.toString()) // null.toString() 은 문자열 "null" 을 반환한다. println("""null.toString() equals "null" : ${"null".equals(null.toString())}""") } nullSafety() // Smart cast fun typeCheckAndCastUsing_is_operator(obj: Any) { println("===== Smart Cast =====") if (obj is Int) { // is 연산자가 true를 반환하면 자동으로 캐스팅 됨 println(obj * 7) // println(obj + " is Int") // 숫자 + 문자열은 컴파일에러 } else if (obj is String && obj.length > 0) { // && 에 진입한다는 것은 is 연산자가 true라는 의미므로 자동으로 캐스팅됨 println(obj + " is String") } else { println("obj is still of Type `Any` : " + obj is Any) } } typeCheckAndCastUsing_is_operator(3) typeCheckAndCastUsing_is_operator("abc") // switch, case 대신 when, -> fun whenArrow() { } // Extension Function }
bsd-3-clause
aeb724d647bcd382f717931ed00aa527
28.192661
118
0.540855
2.497645
false
false
false
false
Aidanvii7/Toolbox
delegates-observable-rxjava/src/main/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxMapDecorator.kt
1
1994
package com.aidanvii.toolbox.delegates.observable.rxjava import androidx.annotation.RestrictTo import io.reactivex.Observable import kotlin.reflect.KProperty /** * Returns an [RxObservableProperty] that will transform the type [TT1] to [TT2] via the given [transform] function. * @param transform a transformational function to apply to each item emitted by the receiver [RxObservableProperty]. * @param ST the base type of the source observable ([RxObservableProperty.SourceTransformer]). * @param TT1 the type on which the receiver [RxObservableProperty] operates. * @param TT2 the transformed type on which the resulting [RxObservableProperty] operates (as dictacted be the [transform] function). */ infix fun <ST, TT1, TT2> RxObservableProperty<ST, TT1>.map( transform: (TT1) -> TT2 ) = RxMapDecorator(this, transform) class RxMapDecorator<ST, TT1, TT2>( private val decorated: RxObservableProperty<ST, TT1>, private val transform: (TT1) -> TT2 ) : RxObservableProperty<ST, TT2> { override val observable: Observable<RxObservableProperty.ValueContainer<TT2>> get() = decorated.observable.map { RxObservableProperty.ValueContainer( property = it.property, oldValue = it.oldValue?.let { transform(it) }, newValue = transform(it.newValue) ) } @RestrictTo(RestrictTo.Scope.LIBRARY) override fun subscribe(observable: Observable<*>) { decorated.subscribe(observable) } override fun getValue(thisRef: Any?, property: KProperty<*>): ST = decorated.getValue(thisRef, property) override fun setValue(thisRef: Any?, property: KProperty<*>, value: ST) { decorated.setValue(thisRef, property, value) } operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): RxMapDecorator<ST, TT1, TT2> { onProvideDelegate(thisRef, property) subscribe(observable) return this } }
apache-2.0
7de130a8d8bc938ce8c4b05f2c55cb1e
39.714286
133
0.694082
4.450893
false
false
false
false
kohesive/kovert
vertx-example/src/main/kotlin/uy/kohesive/kovert/vertx/sample/services/PeopleService.kt
1
1258
package uy.kohesive.kovert.vertx.sample.services import org.kodein.di.Kodein import org.kodein.di.generic.bind import org.kodein.di.generic.singleton interface PeopleService { fun findPersonById(id: Int): Person? fun findPersonsByName(name: String): List<Person> fun findPeopleByCompany(company: String): List<Person> fun upsertPerson(newPerson: Person): Unit } data class Person(val id: Int, val name: String, val age: Int, val company: Company? = null) object KodeinPeopleService { val module = Kodein.Module { bind<PeopleService>() with singleton { MockPeopleService() } } } class MockPeopleService : PeopleService { override fun findPersonById(id: Int): Person? = mockData_peopleById.get(id) override fun findPersonsByName(name: String): List<Person> = mockData_peopleById.values.filter { it.name.equals(name, ignoreCase = true) } override fun findPeopleByCompany(company: String): List<Person> = mockData_peopleById.values.filter { it.company?.name?.equals(company, ignoreCase = true) ?: false } override fun upsertPerson(newPerson: Person): Unit { // ignoring the company part, this is a silly demo afterall mockData_peopleById.put(newPerson.id, newPerson) } }
mit
9490f38346d3277d3aa8cee9777b87a3
36
107
0.725755
3.755224
false
false
false
false
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/accounts/savings/Status.kt
1
1270
package org.mifos.mobile.models.accounts.savings import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class Status( @SerializedName("id") var id: Int? = null, @SerializedName("code") var code: String, @SerializedName("value") var value: String, @SerializedName("submittedAndPendingApproval") var submittedAndPendingApproval: Boolean? = null, @SerializedName("approved") var approved: Boolean? = null, @SerializedName("rejected") var rejected: Boolean? = null, @SerializedName("withdrawnByApplicant") var withdrawnByApplicant: Boolean? = null, @SerializedName("active") var active: Boolean? = null, @SerializedName("closed") var closed: Boolean? = null, @SerializedName("prematureClosed") var prematureClosed: Boolean? = null, @SerializedName("transferInProgress") internal var transferInProgress: Boolean? = null, @SerializedName("transferOnHold") internal var transferOnHold: Boolean? = null, @SerializedName("matured") var matured: Boolean? = null ) : Parcelable
mpl-2.0
aeb9accc27e37ee7a0b963b5c9c8ef65
24.938776
57
0.650394
4.686347
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpapi/jetpack/JetpackWPAPIRestClient.kt
1
3589
package org.wordpress.android.fluxc.network.rest.wpapi.jetpack import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.Payload import org.wordpress.android.fluxc.generated.endpoint.JPAPI import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.jetpack.JetpackUser import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpapi.BaseWPAPIRestClient import org.wordpress.android.fluxc.network.rest.wpapi.Nonce import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIEncodedBodyRequestBuilder import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Error import org.wordpress.android.fluxc.network.rest.wpapi.WPAPIResponse.Success import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton class JetpackWPAPIRestClient @Inject constructor( private val wpApiEncodedBodyRequestBuilder: WPAPIEncodedBodyRequestBuilder, private val wpApiGsonRequestBuilder: WPAPIGsonRequestBuilder, dispatcher: Dispatcher, @Named("custom-ssl") requestQueue: RequestQueue, userAgent: UserAgent ) : BaseWPAPIRestClient(dispatcher, requestQueue, userAgent) { suspend fun fetchJetpackConnectionUrl( site: SiteModel, nonce: Nonce? ): JetpackWPAPIPayload<String> { val baseUrl = site.wpApiRestUrl ?: "${site.url}/wp-json" val url = "${baseUrl.trimEnd('/')}/${JPAPI.connection.url.pathV4.trimStart('/')}" val response = wpApiEncodedBodyRequestBuilder.syncGetRequest( restClient = this, url = url, nonce = nonce?.value ) return when (response) { is Success<String> -> JetpackWPAPIPayload(response.data) is Error -> JetpackWPAPIPayload(response.error) } } suspend fun fetchJetpackUser( site: SiteModel, nonce: Nonce? ): JetpackWPAPIPayload<JetpackUser> { val url = site.buildUrl(JPAPI.connection.data.pathV4) val response = wpApiGsonRequestBuilder.syncGetRequest( restClient = this, url = url, nonce = nonce?.value, clazz = JetpackConnectionDataResponse::class.java ) return when (response) { is Success<JetpackConnectionDataResponse> -> JetpackWPAPIPayload( response.data?.let { JetpackUser( isConnected = it.currentUser.isConnected ?: false, isMaster = it.currentUser.isMaster ?: false, username = it.currentUser.username.orEmpty(), wpcomEmail = it.currentUser.wpcomUser?.email.orEmpty(), wpcomId = it.currentUser.wpcomUser?.id ?: 0L, wpcomUsername = it.currentUser.wpcomUser?.login.orEmpty() ) } ) is Error -> JetpackWPAPIPayload(response.error) } } private fun SiteModel.buildUrl(path: String): String { val baseUrl = wpApiRestUrl ?: "${url}/wp-json" return "${baseUrl.trimEnd('/')}/${path.trimStart('/')}" } data class JetpackWPAPIPayload<T>( val result: T? ) : Payload<BaseNetworkError?>() { constructor(error: BaseNetworkError) : this(null) { this.error = error } } }
gpl-2.0
f1dc78f5384b4b2baed2c38c3d5c907c
38.877778
89
0.669824
4.560356
false
false
false
false
xusx1024/AndroidSystemServiceSample
accoumanagersample/src/main/java/com/shunwang/accoumanagersample/LoginActivity.kt
1
6256
/* * Copyright (C) 2017 The sxxxxxxxxxu's 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.shunwang.accoumanagersample import android.Manifest import android.accounts.Account import android.accounts.AccountAuthenticatorActivity import android.accounts.AccountManager import android.accounts.AccountManagerCallback import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.support.v4.app.ActivityCompat import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ListView import android.widget.PopupWindow import android.widget.Toast import com.shunwang.accoumanagersample.AuthedUserActivity.Companion.ACCOUNT_TYPE import com.shunwang.accoumanagersample.AuthedUserActivity.Companion.AUTH_TOKEN_TYPE import com.shunwang.accoumanagersample.AuthedUserActivity.Companion.KEY_ACCOUNT import com.shunwang.accoumanagersample.RegisterActivity.Companion.REQUEST_ACTIVITY_CODE import kotlinx.android.synthetic.main.activity_auth.expandAll import kotlinx.android.synthetic.main.activity_auth.login import kotlinx.android.synthetic.main.activity_auth.name import kotlinx.android.synthetic.main.activity_auth.password import kotlinx.android.synthetic.main.activity_auth.register /** * Fun: * Created by sxx.xu on 9/28/2017. */ class LoginActivity : AccountAuthenticatorActivity() { private var mPop: AccountPopWindow? = null private var mManager: AccountManager? = null override fun onCreate(icicle: Bundle?) { super.onCreate(icicle) setContentView(R.layout.activity_auth) init() } private fun init() { mManager = AccountManager.get(this) register.setOnClickListener { var intent = Intent(this@LoginActivity, RegisterActivity::class.java) startActivityForResult(intent, REQUEST_ACTIVITY_CODE) } login.setOnClickListener { var userName = name.text.toString() var psw = password.text.toString() if (userName.isBlank()) { Toast.makeText(this@LoginActivity, "账号不能为空", Toast.LENGTH_LONG).show() return@setOnClickListener } if (psw.isBlank()) { Toast.makeText(this@LoginActivity, "密码不能为空", Toast.LENGTH_LONG).show() return@setOnClickListener } var account = Account(userName, ACCOUNT_TYPE) var callback = AccountManagerCallback<Bundle> { future -> try { //该变量没有用到,但是可以在用户名密码错误的情况下,提前触发下面的java.lang.IllegalArgumentException: getAuthToken not supported future.result.getString(AccountManager.KEY_AUTHTOKEN) var intent = Intent(this@LoginActivity, AuthedUserActivity::class.java) var account1 = Account(future.result.getString(AccountManager.KEY_ACCOUNT_NAME) , future.result.getString(AccountManager.KEY_ACCOUNT_TYPE)) intent.putExtra(KEY_ACCOUNT, account1) startActivity(intent) } catch (e: Exception) { Toast.makeText(this@LoginActivity, "error:" + e.localizedMessage, Toast.LENGTH_LONG).show() e.printStackTrace() } } mManager!!.getAuthToken(account, AUTH_TOKEN_TYPE, null, this@LoginActivity, callback, null) } var datas: MutableList<Account> = ArrayList<Account>() mPop = AccountPopWindow(this, datas) expandAll.setOnClickListener { var code = ActivityCompat.checkSelfPermission(this@LoginActivity, Manifest.permission.GET_ACCOUNTS) if (code != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this@LoginActivity, arrayOf(Manifest.permission.GET_ACCOUNTS), ACCOUNT_PERMISSION_CODE) } else { showPop() } } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) { if (requestCode == ACCOUNT_PERMISSION_CODE) { if (grantResults!!.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showPop() } } } private fun showPop() { var accounts = mManager!!.getAccountsByType(ACCOUNT_TYPE) mPop!!.updateData(accounts.toMutableList()) mPop!!.showAsDropDown(expandAll) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) } inner class AccountPopWindow(context: Context, accounts: MutableList<Account>) : PopupWindow( context) { private var mAdapter: AccountAdapter? = null init { width = ViewGroup.LayoutParams.MATCH_PARENT height = ViewGroup.LayoutParams.WRAP_CONTENT var inflater: LayoutInflater = context.getSystemService( Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater var listView = inflater.inflate(R.layout.pop_account, null) as ListView mAdapter = AccountAdapter(this@LoginActivity, R.layout.item_account, accounts) listView.adapter = mAdapter listView.setOnItemClickListener { parent, _, position, _ -> var account: Account = parent.adapter.getItem(position) as Account name.setText(account.name) password.setText(mManager!!.getPassword(account)) dismiss() } contentView = listView isTouchable = true isOutsideTouchable = true setBackgroundDrawable(ColorDrawable(Color.WHITE)) } fun updateData(accounts: MutableList<Account>) { mAdapter!!.getData().clear() mAdapter!!.getData().addAll(accounts) } } companion object { var ACCOUNT_PERMISSION_CODE = 0 } }
apache-2.0
986d6fe0ccf0a4e5c15ecbee024a8c5d
35.288235
106
0.72487
4.371368
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/ui/adapter/itemdecorator/MovieHorizontalItemDecorator.kt
1
779
package taiwan.no1.app.ui.adapter.itemdecorator import android.graphics.Rect import android.support.v7.widget.RecyclerView import android.view.View /** * * @author Jieyi * @since 12/30/16 */ class MovieHorizontalItemDecorator(val space: Int): RecyclerView.ItemDecoration() { override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { val position: Int = parent.getChildAdapterPosition(view) val childrenCount: Int = parent.childCount if (0 == position) outRect.set(space, space, space / 2, space) else if (childrenCount - 1 != position) outRect.set(space / 2, space, space, space) else outRect.set(space / 2, space, space / 2, space) } }
apache-2.0
51a697b737afbc91199beb565727a665
30.2
109
0.67009
3.97449
false
false
false
false
pokk/mvp-magazine
app/src/main/kotlin/taiwan/no1/app/mvp/models/cast/CastListResModel.kt
1
1209
package taiwan.no1.app.mvp.models.cast import android.os.Parcel import android.os.Parcelable /** * * @author Jieyi * @since 2/2/17 */ data class CastListResModel(val page: Int = 0, val total_results: Int = 0, val total_pages: Int = 0, val results: List<CastBriefModel>? = null): Parcelable { //region Parcelable companion object { @JvmField val CREATOR: Parcelable.Creator<CastListResModel> = object: Parcelable.Creator<CastListResModel> { override fun createFromParcel(source: Parcel): CastListResModel = CastListResModel(source) override fun newArray(size: Int): Array<CastListResModel?> = arrayOfNulls(size) } } constructor(source: Parcel): this(source.readInt(), source.readInt(), source.readInt(), source.createTypedArrayList(CastBriefModel.CREATOR)) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(page) dest?.writeInt(total_results) dest?.writeInt(total_pages) dest?.writeTypedList(results) } //endregion }
apache-2.0
3cd814a159002b8c19828053d7d1518b
30.842105
116
0.622002
4.348921
false
false
false
false
hellenxu/AndroidAdvanced
CrashCases/app/src/main/java/six/ca/crashcases/fragment/manager/ProfileManager.kt
1
1751
package six.ca.crashcases.fragment.manager import com.squareup.moshi.Moshi import six.ca.crashcases.fragment.data.profile.Account import six.ca.crashcases.fragment.data.AccountType import six.ca.crashcases.fragment.data.profile.Achievement import six.ca.crashcases.fragment.data.profile.Profile import six.ca.crashcases.fragment.data.AppCache import six.ca.crashcases.fragment.data.profile.ProfileRepository /** * @author hellenxu * @date 2020-08-20 * Copyright 2020 Six. All rights reserved. */ class ProfileManager { lateinit var account: Account lateinit var accountType: AccountType private val _achievements: MutableList<Achievement> = mutableListOf() val achievement: List<Achievement> get() = _achievements fun updateCurrentProfile(profile: Profile) { account = profile.account _achievements.clear() _achievements.addAll(profile.achievements) } fun setSelectedAccountType(type: AccountType) { accountType = type } suspend fun recoverFromCache() { if (!accountIsSet()) { val cache = AppCache.getCache(ProfileRepository.CACHE_KEY_PROFILE) val profileAdapter = Moshi.Builder().build().adapter(Profile::class.java) if (cache != null) { profileAdapter.fromJson(cache)?.let { updateCurrentProfile(it) } } } } private fun accountIsSet(): Boolean { return this::account.isInitialized } } // crash cases: // 1) press home -> app in background -> terminate application(simulate low memory) -> bring the app back foreground -> crash // 2) press home -> app in background -> wait for hours -> bring the app back foreground -> crash
apache-2.0
4512a84f5eed72cef2ae8f418b440638
31.444444
125
0.684752
4.559896
false
false
false
false
debop/debop4k
debop4k-units/src/main/kotlin/debop4k/units/Masses.kt
1
4842
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ @file:JvmName("Masses") package debop4k.units import debop4k.core.loggerOf import java.io.Serializable private val log = loggerOf("Masses") const val MILLIGRAM_IN_GRAM: Double = 1.0 / 1000.0 const val GRAM_IN_GRAM: Double = 1.0 const val KILOGRAM_IN_GRAM: Double = 1000.0 const val TON_IN_GRAM: Double = 1000.0 * 1000.0 fun Int.milligram(): Mass = Mass.of(this.toDouble(), MassUnit.MILLIGRAM) fun Int.gram(): Mass = Mass.of(this.toDouble(), MassUnit.GRAM) fun Int.kilogram(): Mass = Mass.of(this.toDouble(), MassUnit.KILOGRAM) fun Int.ton(): Mass = Mass.of(this.toDouble(), MassUnit.TON) operator fun Int.times(m: Mass): Mass = m.times(this.toDouble()) fun Double.milligram(): Mass = Mass.of(this, MassUnit.MILLIGRAM) fun Double.gram(): Mass = Mass.of(this, MassUnit.GRAM) fun Double.kilogram(): Mass = Mass.of(this, MassUnit.KILOGRAM) fun Double.ton(): Mass = Mass.of(this, MassUnit.TON) operator fun Double.times(m: Mass): Mass = m.times(this) /** * 질량/무게 (Mass/Weight) 단위를 표현합니다. */ enum class MassUnit(val unitName: String, val factor: Double) { MILLIGRAM("mg", MILLIGRAM_IN_GRAM), GRAM("g", GRAM_IN_GRAM), KILOGRAM("kg", KILOGRAM_IN_GRAM), TON("ton", TON_IN_GRAM); companion object { @JvmStatic fun parse(unitStr: String): MassUnit { var lower = unitStr.toLowerCase() if (lower.endsWith("s")) { lower = lower.dropLast(1) } return MassUnit.values().find { it.unitName == lower } ?: throw NumberFormatException("Unknown Mess unit. unit=$unitStr") } } } /** * 질량/무게 (Mass/Weight) 를 표현합니다. */ data class Mass(val gram: Double = 0.0) : Comparable<Mass>, Serializable { fun inMilligram(): Double = gram / MILLIGRAM_IN_GRAM fun inGram(): Double = gram fun inKilogram(): Double = gram / KILOGRAM_IN_GRAM fun inTon(): Double = gram / TON_IN_GRAM fun inUnit(unit: MassUnit = MassUnit.GRAM): Double = when (unit) { MassUnit.MILLIGRAM -> inMilligram() MassUnit.GRAM -> inGram() MassUnit.KILOGRAM -> inKilogram() MassUnit.TON -> inTon() else -> throw UnsupportedOperationException("Unknown Mass unit. unit=$unit") } operator fun plus(other: Mass): Mass = Mass(gram + other.gram) operator fun minus(other: Mass): Mass = Mass(gram - other.gram) operator fun times(scalar: Double): Mass = Mass(gram * scalar) operator fun times(other: Mass): Mass = Mass(gram * other.gram) operator fun div(scalar: Double): Mass = Mass(gram / scalar) operator fun div(other: Mass): Mass = Mass(gram / other.gram) operator fun unaryMinus(): Mass = Mass(-gram) fun toHuman(): String { var unit = MassUnit.GRAM var display = Math.abs(gram) if (display > TON_IN_GRAM) { display /= TON_IN_GRAM unit = MassUnit.TON return "%.1f %s".format(display * Math.signum(gram), unit.unitName) } if (display < GRAM_IN_GRAM) { unit = MassUnit.MILLIGRAM display /= MILLIGRAM_IN_GRAM } else if (display > KILOGRAM_IN_GRAM) { unit = MassUnit.KILOGRAM display /= KILOGRAM_IN_GRAM } return "%.1f %s".format(display * Math.signum(gram), unit.unitName) } override fun compareTo(other: Mass): Int = this.gram.compareTo(other.gram) override fun toString(): String = "%.1f %s".format(gram, MassUnit.GRAM.unitName) companion object { @JvmField val ZERO: Mass = Mass(0.0) @JvmField val MAX_VALUE = Mass(Double.MAX_VALUE) @JvmField val MIN_VALUE = Mass(Double.MIN_VALUE) @JvmField val POSITIVE_INF: Mass = Mass(Double.POSITIVE_INFINITY) @JvmField val NEGATIVE_INF: Mass = Mass(Double.NEGATIVE_INFINITY) @JvmField val NaN: Mass = Mass(Double.NaN) @JvmOverloads @JvmStatic fun of(value: Double = 0.0, unit: MassUnit = MassUnit.GRAM): Mass = Mass(value * unit.factor) @JvmStatic fun parse(str: String?): Mass { if (str.isNullOrBlank()) return Mass.ZERO try { val (value, unit) = str!!.trim().split(" ", limit = 2) return of(value.toDouble(), MassUnit.parse(unit)) } catch(e: Exception) { throw NumberFormatException("Invalid Mass string. str=$str") } } } }
apache-2.0
95abf38cf57c6f7a8b487fcc66dfbd10
31.201342
94
0.66361
3.388418
false
false
false
false
GuiyeC/Aerlink-for-Android
wear/src/main/java/com/codegy/aerlink/MainService.kt
1
11165
package com.codegy.aerlink import android.app.PendingIntent import android.app.Service import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothManager import android.content.Intent import android.graphics.BitmapFactory import android.os.Binder import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.codegy.aerlink.connection.BondManager import com.codegy.aerlink.connection.CharacteristicIdentifier import com.codegy.aerlink.connection.Command import com.codegy.aerlink.connection.ConnectionManager import com.codegy.aerlink.connection.ConnectionState import com.codegy.aerlink.connection.DiscoveryManager import com.codegy.aerlink.extensions.NotificationChannelImportance import com.codegy.aerlink.extensions.createChannelIfNeeded import com.codegy.aerlink.service.ServiceManager import com.codegy.aerlink.service.aerlink.cameraremote.ACRSContract import com.codegy.aerlink.service.aerlink.reminders.ARSContract import com.codegy.aerlink.service.battery.BASContract import com.codegy.aerlink.service.media.AMSContract import com.codegy.aerlink.service.notifications.ANCSContract import com.codegy.aerlink.ui.MainActivity import com.codegy.aerlink.utils.CommandHandler import kotlin.reflect.KClass class MainService : Service(), DiscoveryManager.Callback, BondManager.Callback, ConnectionManager.Callback, CommandHandler { interface Observer { fun onConnectionStateChanged(state: ConnectionState) } var state: ConnectionState = ConnectionState.Disconnected set(value) { if (field == ConnectionState.Stopped || field == value) return field = value updateNotification() observers.forEach { it.onConnectionStateChanged(field) } } private var observers: MutableList<Observer> = mutableListOf() private val bluetoothManager: BluetoothManager by lazy { getSystemService(BluetoothManager::class.java) } private val notificationManager: NotificationManagerCompat by lazy { NotificationManagerCompat.from(this) } private var discoveryManager: DiscoveryManager? = null private var bondManager: BondManager? = null private var connectionManager: ConnectionManager? = null private val serviceManagers: MutableMap<KClass<out ServiceManager>, ServiceManager> = mutableMapOf() override fun onCreate() { super.onCreate() Log.i(LOG_TAG, "-=-=-=-=-=-=-=-=-= Service created =-=-=-=-=-=-=-=-=-") val channelDescription = getString(R.string.service_notification_channel) val importance = NotificationChannelImportance.Min notificationManager.createChannelIfNeeded(NOTIFICATION_CHANNEL_ID, channelDescription, importance) updateNotification() startDiscovery() } override fun onDestroy() { super.onDestroy() state = ConnectionState.Stopped notificationManager.cancelAll() serviceManagers.values.forEach { it.close() } serviceManagers.clear() discoveryManager?.close() bondManager?.close() connectionManager?.close() Log.i(LOG_TAG, "xXxXxXxXxXxXxXxXxX Service destroyed XxXxXxXxXxXxXxXxXx") } override fun onBind(intent: Intent): IBinder = ServiceBinder() fun getServiceManager(managerClass: KClass<out ServiceManager>): ServiceManager? { return serviceManagers[managerClass] } fun addObserver(observer: Observer) { if (!observers.contains(observer)) { observers.add(observer) } observer.onConnectionStateChanged(state) } fun removeObserver(observer: Observer) { observers.remove(observer) } private fun startDiscovery() { Log.d(LOG_TAG, "startDiscovery") val discoveryManager = DiscoveryManager(this, bluetoothManager) discoveryManager.startDiscovery() this.discoveryManager = discoveryManager } override fun onDeviceDiscovery(discoveryManager: DiscoveryManager, device: BluetoothDevice) { Log.d(LOG_TAG, "onDeviceDiscovery :: Device: $device") discoveryManager.stopDiscovery() this.discoveryManager = null connectToDevice(device) } private fun bondToDevice(device: BluetoothDevice) { Log.d(LOG_TAG, "bondToDevice :: Device: $device") state = ConnectionState.Bonding val bondManager = BondManager(device, this, this) bondManager.createBond() this.bondManager = bondManager } override fun onBondSuccessful(bondManager: BondManager, device: BluetoothDevice) { Log.d(LOG_TAG, "onBondSuccessful :: Device: $device") bondManager.close() this.bondManager = null connectToDevice(device) } override fun onBondFailed(bondManager: BondManager, device: BluetoothDevice) { Log.w(LOG_TAG, "onBondFailed :: Device: $device") state = ConnectionState.Disconnected bondManager.close() this.bondManager = null startDiscovery() } private fun connectToDevice(device: BluetoothDevice) { Log.d(LOG_TAG, "connectToDevice :: Device: $device") if (device.bondState != BluetoothDevice.BOND_BONDED) { bondToDevice(device) } else { state = ConnectionState.Connecting val connectionManager = ConnectionManager(device, this, this, bluetoothManager) connectionManager.connect() this.connectionManager = connectionManager } } override fun onReadyToSubscribe(connectionManager: ConnectionManager): List<CharacteristicIdentifier> { Log.d(LOG_TAG, "onReady To Subscribe") val characteristicsToSubscribe = mutableListOf<CharacteristicIdentifier>() serviceContracts.forEach { if (connectionManager.checkServiceAvailability(it.serviceUuid)) { val serviceManager = it.createManager(this, this) Log.v(LOG_TAG, "Manager created: ${serviceManager::class}") serviceManagers[serviceManager::class] = serviceManager characteristicsToSubscribe.addAll(it.characteristicsToSubscribe) } else { Log.v(LOG_TAG, "Service not available: ${it.serviceUuid}") } } return characteristicsToSubscribe } override fun onConnectionReady(connectionManager: ConnectionManager) { Log.d(LOG_TAG, "Connection Ready") state = ConnectionState.Ready val initializingCommands = mutableListOf<Command>() for (serviceManager in serviceManagers.values) { val commands = serviceManager.initialize() if (commands != null) { initializingCommands.addAll(commands) } } for (command in initializingCommands) { connectionManager.handleCommand(command) } } override fun onDisconnected(connectionManager: ConnectionManager) { Log.w(LOG_TAG, "Disconnected") state = ConnectionState.Disconnected connectionManager.close() this.connectionManager = null notificationManager.cancelAll() startDiscovery() } override fun onConnectionError(connectionManager: ConnectionManager) { Log.e(LOG_TAG, "Connection Error") state = ConnectionState.Disconnected serviceManagers.values.forEach { it.close() } serviceManagers.clear() connectionManager.close() this.connectionManager = null notificationManager.cancelAll() startDiscovery() } override fun onBondingRequired(connectionManager: ConnectionManager, device: BluetoothDevice) { Log.d(LOG_TAG, "onBondingRequired :: Device: $device") connectionManager.close() this.connectionManager = null notificationManager.cancelAll() bondToDevice(device) } override fun onCharacteristicChanged(connectionManager: ConnectionManager, characteristic: BluetoothGattCharacteristic) { Log.d(LOG_TAG, "onCharacteristicChanged :: Characteristic: $characteristic") val serviceManager = serviceManagers.values.firstOrNull { it.canHandleCharacteristic(characteristic) } ?: return serviceManager.handleCharacteristic(characteristic) } override fun handleCommand(command: Command) { Log.d(LOG_TAG, "handleCommand :: Command: $command") connectionManager?.handleCommand(command) } private fun updateNotification() { if (state == ConnectionState.Ready && android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.O) { notificationManager.cancel(NOTIFICATION_ID) return } val title = when (state) { ConnectionState.Stopped, ConnectionState.Disconnected -> R.string.connection_state_disconnected ConnectionState.Bonding -> R.string.connection_state_bonding ConnectionState.Connecting -> R.string.connection_state_connecting ConnectionState.Ready -> R.string.connection_state_ready } val text = if (state == ConnectionState.Ready) R.string.connection_state_ready_help else R.string.connection_state_disconnected_help val aerlinkIntent = Intent(this, MainActivity::class.java) aerlinkIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) val pendingIntent = PendingIntent.getActivity(this, 0, aerlinkIntent, 0) val notificationBuilder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setSmallIcon(R.drawable.nic_aerlink) .setOngoing(true) .setColor(getColor(R.color.aerlink_blue)) .setContentTitle(getString(title)) .setContentText(getString(text)) .setContentIntent(pendingIntent) .setOnlyAlertOnce(true) .setPriority(NotificationCompat.PRIORITY_MIN) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { startForeground(NOTIFICATION_ID, notificationBuilder.build()) } else { val background = BitmapFactory.decodeResource(resources, R.drawable.bg_aerlink) val wearableExtender = NotificationCompat.WearableExtender().setBackground(background) notificationBuilder.extend(wearableExtender) notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()) } } companion object { private const val NOTIFICATION_ID: Int = 1000 private const val NOTIFICATION_CHANNEL_ID: String = "com.codegy.aerlink.service" private val serviceContracts = listOf( BASContract, AMSContract, ACRSContract, ARSContract, ANCSContract ) private val LOG_TAG = MainService::class.java.simpleName } inner class ServiceBinder : Binder() { val service: MainService get() = this@MainService } }
mit
8a3b998c0a99af4b385e20f819c8c1e8
37.633218
125
0.690103
4.905536
false
false
false
false
FHannes/intellij-community
platform/projectModel-api/src/org/jetbrains/concurrency/promise.kt
12
8363
/* * 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. */ @file:JvmName("Promises") package org.jetbrains.concurrency import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.util.ActionCallback import com.intellij.util.Consumer import com.intellij.util.Function import com.intellij.util.SmartList import com.intellij.util.ThreeState import com.intellij.util.concurrency.AppExecutorUtil import java.util.* val Promise<*>.isRejected: Boolean get() = state == Promise.State.REJECTED val Promise<*>.isPending: Boolean get() = state == Promise.State.PENDING val Promise<*>.isFulfilled: Boolean get() = state == Promise.State.FULFILLED internal val OBSOLETE_ERROR by lazy { createError("Obsolete") } private val REJECTED: Promise<*> by lazy { RejectedPromise<Any?>(createError("rejected")) } private val DONE: Promise<*> by lazy(LazyThreadSafetyMode.NONE) { Promise.DONE } private val CANCELLED_PROMISE: Promise<*> by lazy { RejectedPromise<Any?>(OBSOLETE_ERROR) } @Suppress("UNCHECKED_CAST") fun <T> resolvedPromise(): Promise<T> = DONE as Promise<T> fun nullPromise(): Promise<*> = DONE fun <T> resolvedPromise(result: T): Promise<T> = if (result == null) resolvedPromise() else DonePromise(result) @Suppress("UNCHECKED_CAST") fun <T> rejectedPromise(): Promise<T> = REJECTED as Promise<T> fun <T> rejectedPromise(error: String): Promise<T> = RejectedPromise(createError(error, true)) fun <T> rejectedPromise(error: Throwable?): Promise<T> = if (error == null) rejectedPromise() else RejectedPromise(error) @Suppress("UNCHECKED_CAST") fun <T> cancelledPromise(): Promise<T> = CANCELLED_PROMISE as Promise<T> // only internal usage interface ObsolescentFunction<Param, Result> : Function<Param, Result>, Obsolescent abstract class ValueNodeAsyncFunction<PARAM, RESULT>(private val node: Obsolescent) : Function<PARAM, Promise<RESULT>>, Obsolescent { override fun isObsolete() = node.isObsolete } abstract class ObsolescentConsumer<T>(private val obsolescent: Obsolescent) : Obsolescent, Consumer<T> { override fun isObsolete() = obsolescent.isObsolete } inline fun <T, SUB_RESULT> Promise<T>.then(obsolescent: Obsolescent, crossinline handler: (T) -> SUB_RESULT) = then(object : ObsolescentFunction<T, SUB_RESULT> { override fun `fun`(param: T) = handler(param) override fun isObsolete() = obsolescent.isObsolete }) inline fun <T> Promise<T>.done(node: Obsolescent, crossinline handler: (T) -> Unit) = done(object : ObsolescentConsumer<T>(node) { override fun consume(param: T) = handler(param) }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.processed(node: Obsolescent, crossinline handler: () -> Unit) = (this as Promise<Any?>).processed(object : ObsolescentConsumer<Any?>(node) { override fun consume(param: Any?) = handler() }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.doneRun(crossinline handler: () -> Unit) = done({ handler() }) @Suppress("UNCHECKED_CAST") inline fun <T> Promise<*>.thenRun(crossinline handler: () -> T): Promise<T> = (this as Promise<Any?>).then({ handler() }) @Suppress("UNCHECKED_CAST") inline fun Promise<*>.processedRun(crossinline handler: () -> Unit): Promise<*> = (this as Promise<Any?>).processed({ handler() }) inline fun <T, SUB_RESULT> Promise<T>.thenAsync(node: Obsolescent, crossinline handler: (T) -> Promise<SUB_RESULT>) = thenAsync(object : ValueNodeAsyncFunction<T, SUB_RESULT>(node) { override fun `fun`(param: T) = handler(param) }) @Suppress("UNCHECKED_CAST") inline fun <T> Promise<T>.thenAsyncAccept(node: Obsolescent, crossinline handler: (T) -> Promise<*>) = thenAsync(object : ValueNodeAsyncFunction<T, Any?>(node) { override fun `fun`(param: T) = handler(param) as Promise<Any?> }) inline fun <T> Promise<T>.thenAsyncAccept(crossinline handler: (T) -> Promise<*>) = thenAsync(Function<T, Promise<Any?>> { param -> @Suppress("UNCHECKED_CAST") (return@Function handler(param) as Promise<Any?>) }) inline fun Promise<*>.rejected(node: Obsolescent, crossinline handler: (Throwable) -> Unit) = rejected(object : ObsolescentConsumer<Throwable>(node) { override fun consume(param: Throwable) = handler(param) }) @JvmOverloads fun <T> collectResults(promises: List<Promise<T>>, ignoreErrors: Boolean = false): Promise<List<T>> { if (promises.isEmpty()) { return resolvedPromise(emptyList()) } val results: MutableList<T> = if (promises.size == 1) SmartList<T>() else ArrayList<T>(promises.size) for (promise in promises) { promise.done { results.add(it) } } return all(promises, results, ignoreErrors) } @JvmOverloads fun createError(error: String, log: Boolean = false): RuntimeException = MessageError(error, log) inline fun <T> AsyncPromise<T>.compute(runnable: () -> T) { val result = catchError(runnable) if (!isRejected) { setResult(result) } } inline fun <T> runAsync(crossinline runnable: () -> T): Promise<T> { val promise = AsyncPromise<T>() AppExecutorUtil.getAppExecutorService().execute { val result = try { runnable() } catch (e: Throwable) { promise.setError(e) return@execute } promise.setResult(result) } return promise } @SuppressWarnings("ExceptionClassNameDoesntEndWithException") internal class MessageError(error: String, log: Boolean) : RuntimeException(error) { internal val log = ThreeState.fromBoolean(log) fun fillInStackTrace() = this } /** * Log error if not a message error */ fun Logger.errorIfNotMessage(e: Throwable): Boolean { if (e is MessageError) { val log = e.log if (log == ThreeState.YES || (log == ThreeState.UNSURE && (ApplicationManager.getApplication()?.isUnitTestMode ?: false))) { error(e) return true } } else if (e !is ProcessCanceledException) { error(e) return true } return false } fun ActionCallback.toPromise(): Promise<Void> { val promise = AsyncPromise<Void>() doWhenDone { promise.setResult(null) }.doWhenRejected { error -> promise.setError(createError(error ?: "Internal error")) } return promise } fun all(promises: Collection<Promise<*>>): Promise<*> = if (promises.size == 1) promises.first() else all(promises, null) @JvmOverloads fun <T> all(promises: Collection<Promise<*>>, totalResult: T?, ignoreErrors: Boolean = false): Promise<T> { if (promises.isEmpty()) { @Suppress("UNCHECKED_CAST") return DONE as Promise<T> } val totalPromise = AsyncPromise<T>() val done = CountDownConsumer(promises.size, totalPromise, totalResult) val rejected = if (ignoreErrors) Consumer<Throwable> { done.consume(null) } else Consumer<Throwable> { totalPromise.setError(it) } for (promise in promises) { promise.done(done) promise.rejected(rejected) } return totalPromise } private class CountDownConsumer<T>(@Volatile private var countDown: Int, private val promise: AsyncPromise<T>, private val totalResult: T?) : Consumer<Any?> { override fun consume(t: Any?) { if (--countDown == 0) { promise.setResult(totalResult) } } } fun <T> any(promises: Collection<Promise<T>>, totalError: String): Promise<T> { if (promises.isEmpty()) { @Suppress("UNCHECKED_CAST") return DONE as Promise<T> } else if (promises.size == 1) { return promises.first() } val totalPromise = AsyncPromise<T>() val done = Consumer<T> { result -> totalPromise.setResult(result) } val rejected = object : Consumer<Throwable> { @Volatile private var toConsume = promises.size override fun consume(throwable: Throwable) { if (--toConsume <= 0) { totalPromise.setError(totalError) } } } for (promise in promises) { promise.done(done) promise.rejected(rejected) } return totalPromise }
apache-2.0
1c41c0439056fae3e7b3ce823256adec
33.419753
182
0.715174
3.944811
false
false
false
false
bravelocation/yeltzland-android
app/src/main/java/com/bravelocation/yeltzlandnew/widget/WidgetSimpleTextView.kt
1
2317
package com.bravelocation.yeltzlandnew.widget import androidx.compose.runtime.Composable import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.glance.GlanceModifier import androidx.glance.Image import androidx.glance.ImageProvider import androidx.glance.action.clickable import androidx.glance.appwidget.action.actionRunCallback import androidx.glance.background import androidx.glance.layout.* import androidx.glance.text.Text import androidx.glance.text.TextStyle import androidx.glance.unit.ColorProvider import com.bravelocation.yeltzlandnew.R import com.bravelocation.yeltzlandnew.ui.AppColors @Composable fun WidgetSimpleTextView(title: String, body: String) { Row( modifier = GlanceModifier .fillMaxSize() .background(AppColors.widgetBackgroundColor()) .padding(6.dp), ) { Image( provider = ImageProvider( resId = R.drawable.ic_reset ), contentDescription = null, modifier = GlanceModifier .clickable( onClick = actionRunCallback<WidgetRefreshAction>() ) .size(40.dp) .padding(horizontal = 8.dp) ) Spacer(modifier = GlanceModifier.width(8.dp)) Column() { Row(modifier = GlanceModifier .fillMaxWidth() .padding(0.dp), horizontalAlignment = Alignment.Start, verticalAlignment = Alignment.CenterVertically ) { Image( provider = ImageProvider(R.drawable.ic_htfc_logo), modifier = GlanceModifier.size(12.dp).padding(0.dp), contentScale = ContentScale.FillBounds, contentDescription = "Yeltz logo" ) Text(text = title, modifier = GlanceModifier.padding(start = 4.dp, end = 4.dp), style = TextStyle(color = ColorProvider(AppColors.widgetTextColor()), fontSize = 10.sp)) } Text(text = body, style = TextStyle(color = ColorProvider(AppColors.widgetTextColor()), fontSize = 16.sp)) } } }
mit
e3a15d6f08ec3e81bd7778045cb37399
33.597015
89
0.59344
5.036957
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/db/Migrations.kt
1
48636
package org.tasks.db import android.database.sqlite.SQLiteException import androidx.room.DeleteColumn import androidx.room.migration.AutoMigrationSpec import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.todoroo.astrid.api.FilterListItem.NO_ORDER import com.todoroo.astrid.data.Task import com.todoroo.astrid.data.Task.Companion.NOTIFY_AFTER_DEADLINE import com.todoroo.astrid.data.Task.Companion.NOTIFY_AT_DEADLINE import com.todoroo.astrid.data.Task.Companion.NOTIFY_AT_START import org.tasks.caldav.FileStorage import org.tasks.data.Alarm.Companion.TYPE_RANDOM import org.tasks.data.Alarm.Companion.TYPE_REL_END import org.tasks.data.Alarm.Companion.TYPE_REL_START import org.tasks.data.Alarm.Companion.TYPE_SNOOZE import org.tasks.data.CaldavAccount.Companion.SERVER_UNKNOWN import org.tasks.data.OpenTaskDao.Companion.getLong import org.tasks.extensions.getLongOrNull import org.tasks.extensions.getString import org.tasks.repeats.RecurrenceUtils.newRecur import org.tasks.time.DateTime import timber.log.Timber import java.io.File import java.util.concurrent.TimeUnit.HOURS object Migrations { @DeleteColumn.Entries( DeleteColumn(tableName = "caldav_accounts", columnName = "cda_encryption_key"), DeleteColumn(tableName = "caldav_accounts", columnName = "cda_repeat"), ) class AutoMigrate83to84: AutoMigrationSpec private val MIGRATION_35_36: Migration = object : Migration(35, 36) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tagdata` ADD COLUMN `color` INTEGER DEFAULT -1") } } private val MIGRATION_36_37: Migration = object : Migration(36, 37) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `store` ADD COLUMN `deleted` INTEGER DEFAULT 0") } } private val MIGRATION_37_38: Migration = object : Migration(37, 38) { override fun migrate(database: SupportSQLiteDatabase) { try { database.execSQL("ALTER TABLE `store` ADD COLUMN `value4` TEXT DEFAULT -1") } catch (e: SQLiteException) { Timber.w(e) } } } private val MIGRATION_38_39: Migration = object : Migration(38, 39) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `notification` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL)") database.execSQL( "CREATE UNIQUE INDEX `index_notification_task` ON `notification` (`task`)") } } private val MIGRATION_46_47: Migration = object : Migration(46, 47) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `alarms` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `time` INTEGER NOT NULL)") database.execSQL( "INSERT INTO `alarms` (`task`, `time`) SELECT `task`, `value` FROM `metadata` WHERE `key` = 'alarm' AND `deleted` = 0") database.execSQL("DELETE FROM `metadata` WHERE `key` = 'alarm'") } } private val MIGRATION_47_48: Migration = object : Migration(47, 48) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `locations` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL, `radius` INTEGER NOT NULL)") database.execSQL("INSERT INTO `locations` (`task`, `name`, `latitude`, `longitude`, `radius`) " + "SELECT `task`, `value`, `value2`, `value3`, `value4` FROM `metadata` WHERE `key` = 'geofence' AND `deleted` = 0") database.execSQL("DELETE FROM `metadata` WHERE `key` = 'geofence'") } } private val MIGRATION_48_49: Migration = object : Migration(48, 49) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `tags` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `tag_uid` TEXT, `task_uid` TEXT)") database.execSQL("INSERT INTO `tags` (`task`, `name`, `tag_uid`, `task_uid`) " + "SELECT `task`, `value`, `value2`, `value3` FROM `metadata` WHERE `key` = 'tags-tag' AND `deleted` = 0") database.execSQL("DELETE FROM `metadata` WHERE `key` = 'tags-tag'") } } private val MIGRATION_49_50: Migration = object : Migration(49, 50) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `google_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `remote_id` TEXT, `list_id` TEXT, `parent` INTEGER NOT NULL, `indent` INTEGER NOT NULL, `order` INTEGER NOT NULL, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL)") database.execSQL("INSERT INTO `google_tasks` (`task`, `remote_id`, `list_id`, `parent`, `indent`, `order`, `remote_order`, `last_sync`, `deleted`) " + "SELECT `task`, `value`, `value2`, IFNULL(`value3`, 0), IFNULL(`value4`, 0), IFNULL(`value5`, 0), IFNULL(`value6`, 0), IFNULL(`value7`, 0), IFNULL(`deleted`, 0) FROM `metadata` WHERE `key` = 'gtasks'") database.execSQL("DROP TABLE IF EXISTS `metadata`") } } private val MIGRATION_50_51: Migration = object : Migration(50, 51) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `filters` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `sql` TEXT, `values` TEXT, `criterion` TEXT)") database.execSQL("INSERT INTO `filters` (`title`, `sql`, `values`, `criterion`) " + "SELECT `item`, `value`, `value2`, `value3` FROM `store` WHERE `type` = 'filter' AND `deleted` = 0") database.execSQL("DELETE FROM `store` WHERE `type` = 'filter'") } } private val MIGRATION_51_52: Migration = object : Migration(51, 52) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `google_task_lists` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `remote_id` TEXT, `title` TEXT, `remote_order` INTEGER NOT NULL, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `color` INTEGER)") database.execSQL("INSERT INTO `google_task_lists` (`remote_id`, `title`, `remote_order`, `last_sync`, `color`, `deleted`) " + "SELECT `item`, `value`, `value2`, `value3`, `value4`, `deleted` FROM `store` WHERE `type` = 'gtasks-list'") database.execSQL("DROP TABLE IF EXISTS `store`") } } private val MIGRATION_52_53: Migration = object : Migration(52, 53) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tagdata` RENAME TO `tagdata-temp`") database.execSQL( "CREATE TABLE `tagdata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `name` TEXT, `color` INTEGER, `tagOrdering` TEXT)") database.execSQL("INSERT INTO `tagdata` (`remoteId`, `name`, `color`, `tagOrdering`) " + "SELECT `remoteId`, `name`, `color`, `tagOrdering` FROM `tagdata-temp`") database.execSQL("DROP TABLE `tagdata-temp`") database.execSQL("ALTER TABLE `userActivity` RENAME TO `userActivity-temp`") database.execSQL( "CREATE TABLE `userActivity` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `message` TEXT, `picture` TEXT, `target_id` TEXT, `created_at` INTEGER)") database.execSQL("INSERT INTO `userActivity` (`remoteId`, `message`, `picture`, `target_id`, `created_at`) " + "SELECT `remoteId`, `message`, `picture`, `target_id`, `created_at` FROM `userActivity-temp`") database.execSQL("DROP TABLE `userActivity-temp`") database.execSQL("ALTER TABLE `task_attachments` RENAME TO `task_attachments-temp`") database.execSQL( "CREATE TABLE `task_attachments` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `task_id` TEXT, `name` TEXT, `path` TEXT, `content_type` TEXT)") database.execSQL("INSERT INTO `task_attachments` (`remoteId`, `task_id`, `name`, `path`, `content_type`) " + "SELECT `remoteId`, `task_id`, `name`, `path`, `content_type` FROM `task_attachments-temp`") database.execSQL("DROP TABLE `task_attachments-temp`") } } private val MIGRATION_53_54: Migration = object : Migration(53, 54) { override fun migrate(database: SupportSQLiteDatabase) { // need to drop columns that were removed in the past database.execSQL("ALTER TABLE `task_list_metadata` RENAME TO `task_list_metadata-temp`") database.execSQL( "CREATE TABLE `task_list_metadata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `remoteId` TEXT, `tag_uuid` TEXT, `filter` TEXT, `task_ids` TEXT)") database.execSQL("INSERT INTO `task_list_metadata` (`remoteId`, `tag_uuid`, `filter`, `task_ids`) " + "SELECT `remoteId`, `tag_uuid`, `filter`, `task_ids` FROM `task_list_metadata-temp`") database.execSQL("DROP TABLE `task_list_metadata-temp`") database.execSQL("ALTER TABLE `tasks` RENAME TO `tasks-temp`") database.execSQL( "CREATE TABLE `tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `title` TEXT, `importance` INTEGER, `dueDate` INTEGER, `hideUntil` INTEGER, `created` INTEGER, `modified` INTEGER, `completed` INTEGER, `deleted` INTEGER, `notes` TEXT, `estimatedSeconds` INTEGER, `elapsedSeconds` INTEGER, `timerStart` INTEGER, `notificationFlags` INTEGER, `notifications` INTEGER, `lastNotified` INTEGER, `snoozeTime` INTEGER, `recurrence` TEXT, `repeatUntil` INTEGER, `calendarUri` TEXT, `remoteId` TEXT)") database.execSQL("DROP INDEX `t_rid`") database.execSQL("CREATE UNIQUE INDEX `t_rid` ON `tasks` (`remoteId`)") database.execSQL("INSERT INTO `tasks` (`_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId`) " + "SELECT `_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId` FROM `tasks-temp`") database.execSQL("DROP TABLE `tasks-temp`") } } private val MIGRATION_54_58: Migration = object : Migration(54, 58) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_account` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uuid` TEXT, `name` TEXT, `url` TEXT, `username` TEXT, `password` TEXT)") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_calendar` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `uuid` TEXT, `name` TEXT, `color` INTEGER NOT NULL, `ctag` TEXT, `url` TEXT)") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `calendar` TEXT, `object` TEXT, `remote_id` TEXT, `etag` TEXT, `last_sync` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `vtodo` TEXT)") } } private val MIGRATION_58_59: Migration = object : Migration(58, 59) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `google_task_accounts` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` TEXT, `error` TEXT)") database.execSQL("ALTER TABLE `google_task_lists` ADD COLUMN `account` TEXT") database.execSQL("ALTER TABLE `caldav_account` ADD COLUMN `error` TEXT") } } private val MIGRATION_59_60: Migration = object : Migration(59, 60) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `locations` ADD COLUMN `address` TEXT") database.execSQL("ALTER TABLE `locations` ADD COLUMN `phone` TEXT") database.execSQL("ALTER TABLE `locations` ADD COLUMN `url` TEXT") database.execSQL( "ALTER TABLE `locations` ADD COLUMN `arrival` INTEGER DEFAULT 1 NOT NULL") database.execSQL( "ALTER TABLE `locations` ADD COLUMN `departure` INTEGER DEFAULT 0 NOT NULL") database.execSQL("ALTER TABLE `notification` ADD COLUMN `location` INTEGER") } } private val MIGRATION_60_61: Migration = object : Migration(60, 61) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `places` (`place_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `uid` TEXT, `name` TEXT, `address` TEXT, `phone` TEXT, `url` TEXT, `latitude` REAL NOT NULL, `longitude` REAL NOT NULL)") database.execSQL( "CREATE TABLE IF NOT EXISTS `geofences` (`geofence_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `place` TEXT, `radius` INTEGER NOT NULL, `arrival` INTEGER NOT NULL, `departure` INTEGER NOT NULL)") database.execSQL( "INSERT INTO `places` (`place_id`, `uid`, `name`, `address`, `phone`, `url`, `latitude`, `longitude`) SELECT `_id`, hex(randomblob(16)), `name`, `address`, `phone`, `url`, `latitude`, `longitude` FROM `locations`") database.execSQL( "INSERT INTO `geofences` (`geofence_id`, `task`, `place`, `radius`, `arrival`, `departure`) SELECT `_id`, `task`, `uid`, `radius`, `arrival`, `departure` FROM `locations` INNER JOIN `places` ON `_id` = `place_id`") database.execSQL("DROP TABLE `locations`") } } private val MIGRATION_61_62: Migration = object : Migration(61, 62) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `google_task_accounts` ADD COLUMN `etag` TEXT") } } private val MIGRATION_62_63: Migration = object : Migration(62, 63) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `google_tasks` RENAME TO `gt-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `google_tasks` (`gt_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `gt_task` INTEGER NOT NULL, `gt_remote_id` TEXT, `gt_list_id` TEXT, `gt_parent` INTEGER NOT NULL, `gt_remote_parent` TEXT, `gt_moved` INTEGER NOT NULL, `gt_order` INTEGER NOT NULL, `gt_remote_order` INTEGER NOT NULL, `gt_last_sync` INTEGER NOT NULL, `gt_deleted` INTEGER NOT NULL)") database.execSQL("INSERT INTO `google_tasks` (`gt_id`, `gt_task`, `gt_remote_id`, `gt_list_id`, `gt_parent`, `gt_remote_parent`, `gt_moved`, `gt_order`, `gt_remote_order`, `gt_last_sync`, `gt_deleted`) " + "SELECT `_id`, `task`, `remote_id`, `list_id`, `parent`, '', 0, `order`, `remote_order`, `last_sync`, `deleted` FROM `gt-temp`") database.execSQL("DROP TABLE `gt-temp`") database.execSQL("UPDATE `google_task_lists` SET `last_sync` = 0") } } private val MIGRATION_63_64: Migration = object : Migration(63, 64) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `caldav_tasks` RENAME TO `caldav-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`cd_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cd_task` INTEGER NOT NULL, `cd_calendar` TEXT, `cd_object` TEXT, `cd_remote_id` TEXT, `cd_etag` TEXT, `cd_last_sync` INTEGER NOT NULL, `cd_deleted` INTEGER NOT NULL, `cd_vtodo` TEXT)") database.execSQL("INSERT INTO `caldav_tasks` (`cd_id`, `cd_task`, `cd_calendar`, `cd_object`, `cd_remote_id`, `cd_etag`, `cd_last_sync`, `cd_deleted`, `cd_vtodo`)" + "SELECT `_id`, `task`, `calendar`, `object`, `remote_id`, `etag`, `last_sync`, `deleted`, `vtodo` FROM `caldav-temp`") database.execSQL("DROP TABLE `caldav-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_accounts` (`cda_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cda_uuid` TEXT, `cda_name` TEXT, `cda_url` TEXT, `cda_username` TEXT, `cda_password` TEXT, `cda_error` TEXT)") database.execSQL("INSERT INTO `caldav_accounts` (`cda_id`, `cda_uuid`, `cda_name`, `cda_url`, `cda_username`, `cda_password`, `cda_error`) " + "SELECT `_id`, `uuid`, `name`, `url`, `username`, `password`, `error` FROM `caldav_account`") database.execSQL("DROP TABLE `caldav_account`") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_lists` (`cdl_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cdl_account` TEXT, `cdl_uuid` TEXT, `cdl_name` TEXT, `cdl_color` INTEGER NOT NULL, `cdl_ctag` TEXT, `cdl_url` TEXT, `cdl_icon` INTEGER)") database.execSQL("INSERT INTO `caldav_lists` (`cdl_id`, `cdl_account`, `cdl_uuid`, `cdl_name`, `cdl_color`, `cdl_ctag`, `cdl_url`) " + "SELECT `_id`, `account`, `uuid`, `name`, `color`, `ctag`, `url` FROM caldav_calendar") database.execSQL("DROP TABLE `caldav_calendar`") database.execSQL("ALTER TABLE `google_task_accounts` RENAME TO `gta-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `google_task_accounts` (`gta_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `gta_account` TEXT, `gta_error` TEXT, `gta_etag` TEXT)") database.execSQL("INSERT INTO `google_task_accounts` (`gta_id`, `gta_account`, `gta_error`, `gta_etag`) " + "SELECT `_id`, `account`, `error`, `etag` FROM `gta-temp`") database.execSQL("DROP TABLE `gta-temp`") database.execSQL("ALTER TABLE `google_task_lists` RENAME TO `gtl-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `google_task_lists` (`gtl_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `gtl_account` TEXT, `gtl_remote_id` TEXT, `gtl_title` TEXT, `gtl_remote_order` INTEGER NOT NULL, `gtl_last_sync` INTEGER NOT NULL, `gtl_color` INTEGER, `gtl_icon` INTEGER)") database.execSQL("INSERT INTO `google_task_lists` (`gtl_id`, `gtl_account`, `gtl_remote_id`, `gtl_title`, `gtl_remote_order`, `gtl_last_sync`, `gtl_color`) " + "SELECT `_id`, `account`, `remote_id`, `title`, `remote_order`, `last_sync`, `color` FROM `gtl-temp`") database.execSQL("DROP TABLE `gtl-temp`") database.execSQL("ALTER TABLE `filters` ADD COLUMN `f_color` INTEGER") database.execSQL("ALTER TABLE `filters` ADD COLUMN `f_icon` INTEGER") database.execSQL("ALTER TABLE `tagdata` ADD COLUMN `td_icon` INTEGER") } } private val MIGRATION_64_65: Migration = object : Migration(64, 65) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `caldav_tasks` ADD COLUMN `cd_parent` INTEGER NOT NULL DEFAULT 0") database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `cd_remote_parent` TEXT") } } private val MIGRATION_65_66: Migration = object : Migration(65, 66) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE UNIQUE INDEX `place_uid` ON `places` (`uid`)") database.execSQL("CREATE INDEX `geo_task` ON `geofences` (`task`)") database.execSQL("CREATE INDEX `tag_task` ON `tags` (`task`)") database.execSQL("CREATE INDEX `gt_list_parent` ON `google_tasks` (`gt_list_id`, `gt_parent`)") database.execSQL("CREATE INDEX `gt_task` ON `google_tasks` (`gt_task`)") database.execSQL("CREATE INDEX `cd_calendar_parent` ON `caldav_tasks` (`cd_calendar`, `cd_parent`)") database.execSQL("CREATE INDEX `cd_task` ON `caldav_tasks` (`cd_task`)") } } private val MIGRATION_66_67: Migration = object : Migration(66, 67) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `caldav_accounts` ADD COLUMN `cda_repeat` INTEGER NOT NULL DEFAULT 0") } } private val MIGRATION_67_68: Migration = object : Migration(67, 68) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE INDEX `active_and_visible` ON `tasks` (`completed`, `deleted`, `hideUntil`)") } } private val MIGRATION_68_69: Migration = object : Migration(68, 69) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `tasks` ADD COLUMN `collapsed` INTEGER NOT NULL DEFAULT 0") } } private val MIGRATION_69_70: Migration = object : Migration(69, 70) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tasks` ADD COLUMN `parent` INTEGER NOT NULL DEFAULT 0") database.execSQL("ALTER TABLE `tasks` ADD COLUMN `parent_uuid` TEXT") database.execSQL( "UPDATE `tasks` SET `parent` = IFNULL((" + " SELECT p.cd_task FROM caldav_tasks" + " INNER JOIN caldav_tasks AS p ON p.cd_remote_id = caldav_tasks.cd_remote_parent" + " WHERE caldav_tasks.cd_task = tasks._id" + " AND caldav_tasks.cd_deleted = 0" + " AND p.cd_calendar = caldav_tasks.cd_calendar" + " AND p.cd_deleted = 0), 0)") database.execSQL("ALTER TABLE `caldav_tasks` RENAME TO `caldav_tasks-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`cd_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cd_task` INTEGER NOT NULL, `cd_calendar` TEXT, `cd_object` TEXT, `cd_remote_id` TEXT, `cd_etag` TEXT, `cd_last_sync` INTEGER NOT NULL, `cd_deleted` INTEGER NOT NULL, `cd_vtodo` TEXT, `cd_remote_parent` TEXT)") database.execSQL("INSERT INTO `caldav_tasks` (`cd_id`, `cd_task`, `cd_calendar`, `cd_object`, `cd_remote_id`, `cd_etag`, `cd_last_sync`, `cd_deleted`, `cd_vtodo`, `cd_remote_parent`) " + "SELECT `cd_id`, `cd_task`, `cd_calendar`, `cd_object`, `cd_remote_id`, `cd_etag`, `cd_last_sync`, `cd_deleted`, `cd_vtodo`, `cd_remote_parent` FROM `caldav_tasks-temp`") database.execSQL("DROP TABLE `caldav_tasks-temp`") database.execSQL("CREATE INDEX `cd_task` ON `caldav_tasks` (`cd_task`)") } } private val MIGRATION_70_71: Migration = object : Migration(70, 71) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `caldav_accounts` ADD COLUMN `cda_encryption_key` TEXT") database.execSQL( "ALTER TABLE `caldav_accounts` ADD COLUMN `cda_account_type` INTEGER NOT NULL DEFAULT 0") } } private val MIGRATION_71_72: Migration = object : Migration(71, 72) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `caldav_accounts` ADD COLUMN `cda_collapsed` INTEGER NOT NULL DEFAULT 0") database.execSQL( "ALTER TABLE `google_task_accounts` ADD COLUMN `gta_collapsed` INTEGER NOT NULL DEFAULT 0") } } private val MIGRATION_72_73: Migration = object : Migration(72, 73) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `places` ADD COLUMN `place_color` INTEGER NOT NULL DEFAULT 0") database.execSQL("ALTER TABLE `places` ADD COLUMN `place_icon` INTEGER NOT NULL DEFAULT -1") } } private val MIGRATION_73_74: Migration = object : Migration(73, 74) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tasks` RENAME TO `tasks-temp`") database.execSQL("DROP INDEX `t_rid`") database.execSQL("DROP INDEX `active_and_visible`") database.execSQL("CREATE TABLE IF NOT EXISTS `tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `importance` INTEGER NOT NULL, `dueDate` INTEGER NOT NULL, `hideUntil` INTEGER NOT NULL, `created` INTEGER NOT NULL, `modified` INTEGER NOT NULL, `completed` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `notes` TEXT, `estimatedSeconds` INTEGER NOT NULL, `elapsedSeconds` INTEGER NOT NULL, `timerStart` INTEGER NOT NULL, `notificationFlags` INTEGER NOT NULL, `notifications` INTEGER NOT NULL, `lastNotified` INTEGER NOT NULL, `snoozeTime` INTEGER NOT NULL, `recurrence` TEXT, `repeatUntil` INTEGER NOT NULL, `calendarUri` TEXT, `remoteId` TEXT, `collapsed` INTEGER NOT NULL, `parent` INTEGER NOT NULL, `parent_uuid` TEXT)") database.execSQL("INSERT INTO `tasks` (`_id`, `title`, `importance`, `dueDate`, `hideUntil`, `created`, `modified`, `completed`, `deleted`, `notes`, `estimatedSeconds`, `elapsedSeconds`, `timerStart`, `notificationFlags`, `notifications`, `lastNotified`, `snoozeTime`, `recurrence`, `repeatUntil`, `calendarUri`, `remoteId`, `collapsed`, `parent`, `parent_uuid`) " + "SELECT `_id`, `title`, IFNULL(`importance`, 3), IFNULL(`dueDate`, 0), IFNULL(`hideUntil`, 0), IFNULL(`created`, 0), IFNULL(`modified`, 0), IFNULL(`completed`, 0), IFNULL(`deleted`, 0), `notes`, IFNULL(`estimatedSeconds`, 0), IFNULL(`elapsedSeconds`, 0), IFNULL(`timerStart`, 0), IFNULL(`notificationFlags`, 0), IFNULL(`notifications`, 0), IFNULL(`lastNotified`, 0), IFNULL(`snoozeTime`, 0), `recurrence`, IFNULL(`repeatUntil`, 0), `calendarUri`, `remoteId`, `collapsed`, IFNULL(`parent`, 0), `parent_uuid` FROM `tasks-temp`") database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `t_rid` ON `tasks` (`remoteId`)") database.execSQL("CREATE INDEX IF NOT EXISTS `active_and_visible` ON `tasks` (`completed`, `deleted`, `hideUntil`)") database.execSQL("DROP TABLE `tasks-temp`") } } private val MIGRATION_74_75: Migration = object : Migration(74, 75) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `caldav_tasks` ADD COLUMN `cd_order` INTEGER") } } private val MIGRATION_75_76: Migration = object : Migration(75, 76) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tagdata` ADD COLUMN `td_order` INTEGER NOT NULL DEFAULT $NO_ORDER") database.execSQL("ALTER TABLE `caldav_lists` ADD COLUMN `cdl_order` INTEGER NOT NULL DEFAULT $NO_ORDER") database.execSQL("ALTER TABLE `filters` ADD COLUMN `f_order` INTEGER NOT NULL DEFAULT $NO_ORDER") database.execSQL("ALTER TABLE `places` ADD COLUMN `place_order` INTEGER NOT NULL DEFAULT $NO_ORDER") } } private val MIGRATION_76_77: Migration = object : Migration(76, 77) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `caldav_lists` ADD COLUMN `cdl_access` INTEGER NOT NULL DEFAULT 0") } } private val MIGRATION_77_78: Migration = object : Migration(77, 78) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "CREATE TABLE IF NOT EXISTS `principals` (`principal_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `principal_list` INTEGER NOT NULL, `principal` TEXT, `display_name` TEXT, `invite` INTEGER NOT NULL, `access` INTEGER NOT NULL, FOREIGN KEY(`principal_list`) REFERENCES `caldav_lists`(`cdl_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL( "CREATE UNIQUE INDEX IF NOT EXISTS `index_principals_principal_list_principal` ON `principals` (`principal_list`, `principal`)" ) } } private val MIGRATION_78_79: Migration = object : Migration(78, 79) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL( "ALTER TABLE `caldav_accounts` ADD COLUMN `cda_server_type` INTEGER NOT NULL DEFAULT $SERVER_UNKNOWN" ) } } private val MIGRATION_79_80 = object : Migration(79, 80) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("DROP TABLE `principals`") database.execSQL( "CREATE TABLE IF NOT EXISTS `principals` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `account` INTEGER NOT NULL, `href` TEXT NOT NULL, `email` TEXT, `display_name` TEXT, FOREIGN KEY(`account`) REFERENCES `caldav_accounts`(`cda_id`) ON UPDATE NO ACTION ON DELETE CASCADE )" ) database.execSQL( "CREATE UNIQUE INDEX IF NOT EXISTS `index_principals_account_href` ON `principals` (`account`, `href`)" ) database.execSQL( "CREATE TABLE IF NOT EXISTS `principal_access` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `principal` INTEGER NOT NULL, `list` INTEGER NOT NULL, `invite` INTEGER NOT NULL, `access` INTEGER NOT NULL, FOREIGN KEY(`principal`) REFERENCES `principals`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`list`) REFERENCES `caldav_lists`(`cdl_id`) ON UPDATE NO ACTION ON DELETE CASCADE )" ) database.execSQL( "CREATE UNIQUE INDEX IF NOT EXISTS `index_principal_access_list_principal` ON `principal_access` (`list`, `principal`)" ) database.execSQL( "CREATE INDEX IF NOT EXISTS `index_principal_access_principal` ON `principal_access` (`principal`)" ) } } private val MIGRATION_80_81 = object : Migration(80, 81) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `alarms` ADD COLUMN `type` INTEGER NOT NULL DEFAULT 0") database.execSQL("ALTER TABLE `alarms` ADD COLUMN `repeat` INTEGER NOT NULL DEFAULT 0") database.execSQL("ALTER TABLE `alarms` ADD COLUMN `interval` INTEGER NOT NULL DEFAULT 0") database.execSQL( "INSERT INTO `alarms` (`task`, `time`, `type`) SELECT `_id`, 0, $TYPE_REL_START FROM `tasks` WHERE `hideUntil` > 0 AND `notificationFlags` & $NOTIFY_AT_START = $NOTIFY_AT_START" ) database.execSQL( "INSERT INTO `alarms` (`task`, `time`, `type`) SELECT `_id`, 0, $TYPE_REL_END FROM `tasks` WHERE `dueDate` > 0 AND `notificationFlags` & $NOTIFY_AT_DEADLINE = $NOTIFY_AT_DEADLINE" ) database.execSQL( "INSERT INTO `alarms` (`task`, `time`, `type`, `repeat`, `interval`) SELECT `_id`, ${HOURS.toMillis(24)}, $TYPE_REL_END, 6, ${HOURS.toMillis(24)} FROM `tasks` WHERE `dueDate` > 0 AND `notificationFlags` & $NOTIFY_AFTER_DEADLINE = $NOTIFY_AFTER_DEADLINE" ) database.execSQL( "INSERT INTO `alarms` (`task`, `time`, `type`) SELECT `_id`, `notifications`, $TYPE_RANDOM FROM `tasks` WHERE `notifications` > 0" ) database.execSQL( "INSERT INTO `alarms` (`task`, `time`, `type`) SELECT `_id`, `snoozeTime`, $TYPE_SNOOZE FROM `tasks` WHERE `snoozeTime` > 0" ) } } @Suppress("FunctionName") private fun migration_81_82(fileStorage: FileStorage) = object : Migration(81, 82) { override fun migrate(database: SupportSQLiteDatabase) { database .query("SELECT `cdl_account`, `cd_calendar`, `cd_object`, `cd_vtodo` FROM `caldav_tasks` INNER JOIN `caldav_lists` ON `cdl_uuid` = `cd_calendar`") .use { while (it.moveToNext()) { val file = fileStorage.getFile( it.getString("cdl_account"), it.getString("cd_calendar"), ) ?.apply { mkdirs() } ?: continue val `object` = it.getString("cd_object") ?: continue fileStorage.write(File(file, `object`), it.getString("cd_vtodo")) } } database.execSQL("ALTER TABLE `caldav_tasks` RENAME TO `caldav_tasks-temp`") database.execSQL( "CREATE TABLE IF NOT EXISTS `caldav_tasks` (`cd_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cd_task` INTEGER NOT NULL, `cd_calendar` TEXT, `cd_object` TEXT, `cd_remote_id` TEXT, `cd_etag` TEXT, `cd_last_sync` INTEGER NOT NULL, `cd_deleted` INTEGER NOT NULL, `cd_remote_parent` TEXT, `cd_order` INTEGER)" ) database.execSQL("DROP INDEX `cd_task`") database.execSQL("CREATE INDEX IF NOT EXISTS `cd_task` ON `caldav_tasks` (`cd_task`)") database.execSQL( "INSERT INTO `caldav_tasks` (`cd_id`, `cd_task`, `cd_calendar`, `cd_object`, `cd_remote_id`, `cd_etag`, `cd_last_sync`, `cd_deleted`, `cd_remote_parent`, `cd_order`) SELECT `cd_id`, `cd_task`, `cd_calendar`, `cd_object`, `cd_remote_id`, `cd_etag`, `cd_last_sync`, `cd_deleted`, `cd_remote_parent`, `cd_order` FROM `caldav_tasks-temp`" ) database.execSQL("DROP TABLE `caldav_tasks-temp`") } } private val MIGRATION_82_83 = object : Migration(82, 83) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `places` ADD COLUMN `radius` INTEGER NOT NULL DEFAULT 250") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_alarms` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `time` INTEGER NOT NULL, `type` INTEGER NOT NULL DEFAULT 0, `repeat` INTEGER NOT NULL DEFAULT 0, `interval` INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(`task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_alarms` (`task`,`repeat`,`interval`,`_id`,`time`,`type`) SELECT `task`,`repeat`,`interval`,`alarms`.`_id`,`time`,`type` FROM `alarms` INNER JOIN `tasks` ON `tasks`.`_id` = `task`") database.execSQL("DROP TABLE `alarms`") database.execSQL("ALTER TABLE `_new_alarms` RENAME TO `alarms`") database.execSQL("CREATE INDEX IF NOT EXISTS `index_alarms_task` ON `alarms` (`task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_google_tasks` (`gt_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `gt_task` INTEGER NOT NULL, `gt_remote_id` TEXT, `gt_list_id` TEXT, `gt_parent` INTEGER NOT NULL, `gt_remote_parent` TEXT, `gt_moved` INTEGER NOT NULL, `gt_order` INTEGER NOT NULL, `gt_remote_order` INTEGER NOT NULL, `gt_last_sync` INTEGER NOT NULL, `gt_deleted` INTEGER NOT NULL, FOREIGN KEY(`gt_task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_google_tasks` (`gt_parent`,`gt_task`,`gt_remote_parent`,`gt_order`,`gt_last_sync`,`gt_id`,`gt_remote_id`,`gt_list_id`,`gt_moved`,`gt_remote_order`,`gt_deleted`) SELECT `gt_parent`,`gt_task`,`gt_remote_parent`,`gt_order`,`gt_last_sync`,`gt_id`,`gt_remote_id`,`gt_list_id`,`gt_moved`,`gt_remote_order`,`gt_deleted` FROM `google_tasks` INNER JOIN `tasks` ON `tasks`.`_id` = `gt_task`") database.execSQL("DROP TABLE `google_tasks`") database.execSQL("ALTER TABLE `_new_google_tasks` RENAME TO `google_tasks`") database.execSQL("CREATE INDEX IF NOT EXISTS `gt_list_parent` ON `google_tasks` (`gt_list_id`, `gt_parent`)") database.execSQL("CREATE INDEX IF NOT EXISTS `index_google_tasks_gt_task` ON `google_tasks` (`gt_task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_tags` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `name` TEXT, `tag_uid` TEXT, `task_uid` TEXT, FOREIGN KEY(`task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_tags` (`task`,`task_uid`,`name`,`tag_uid`,`_id`) SELECT `task`,`task_uid`,`name`,`tag_uid`,`tags`.`_id` FROM `tags` INNER JOIN `tasks` ON `tasks`.`_id` = `task`") database.execSQL("DROP TABLE `tags`") database.execSQL("ALTER TABLE `_new_tags` RENAME TO `tags`") database.execSQL("CREATE INDEX IF NOT EXISTS `index_tags_task` ON `tags` (`task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_notification` (`uid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `timestamp` INTEGER NOT NULL, `type` INTEGER NOT NULL, `location` INTEGER, FOREIGN KEY(`task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_notification` (`uid`,`task`,`location`,`type`,`timestamp`) SELECT `uid`,`task`,`location`,`type`,`timestamp` FROM `notification` INNER JOIN `tasks` ON `tasks`.`_id` = `task`") database.execSQL("DROP TABLE `notification`") database.execSQL("ALTER TABLE `_new_notification` RENAME TO `notification`") database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_notification_task` ON `notification` (`task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_caldav_tasks` (`cd_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `cd_task` INTEGER NOT NULL, `cd_calendar` TEXT, `cd_object` TEXT, `cd_remote_id` TEXT, `cd_etag` TEXT, `cd_last_sync` INTEGER NOT NULL, `cd_deleted` INTEGER NOT NULL, `cd_remote_parent` TEXT, `cd_order` INTEGER, FOREIGN KEY(`cd_task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_caldav_tasks` (`cd_object`,`cd_deleted`,`cd_order`,`cd_remote_parent`,`cd_etag`,`cd_id`,`cd_calendar`,`cd_remote_id`,`cd_last_sync`,`cd_task`) SELECT `cd_object`,`cd_deleted`,`cd_order`,`cd_remote_parent`,`cd_etag`,`cd_id`,`cd_calendar`,`cd_remote_id`,`cd_last_sync`,`cd_task` FROM `caldav_tasks` INNER JOIN `tasks` ON `tasks`.`_id` = `cd_task`") database.execSQL("DROP TABLE `caldav_tasks`") database.execSQL("ALTER TABLE `_new_caldav_tasks` RENAME TO `caldav_tasks`") database.execSQL("CREATE INDEX IF NOT EXISTS `index_caldav_tasks_cd_task` ON `caldav_tasks` (`cd_task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_geofences` (`geofence_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `task` INTEGER NOT NULL, `place` TEXT, `arrival` INTEGER NOT NULL, `departure` INTEGER NOT NULL, FOREIGN KEY(`task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE )") database.execSQL("INSERT INTO `_new_geofences` (`task`,`geofence_id`,`arrival`,`place`,`departure`) SELECT `task`,`geofence_id`,`arrival`,`place`,`departure` FROM `geofences` INNER JOIN `tasks` ON `tasks`.`_id` = `task`") database.execSQL("DROP TABLE `geofences`") database.execSQL("ALTER TABLE `_new_geofences` RENAME TO `geofences`") database.execSQL("CREATE INDEX IF NOT EXISTS `index_geofences_task` ON `geofences` (`task`)") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_task_list_metadata` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `tag_uuid` TEXT, `filter` TEXT, `task_ids` TEXT)") database.execSQL("INSERT INTO `_new_task_list_metadata` (`filter`,`tag_uuid`,`_id`,`task_ids`) SELECT `filter`,`tag_uuid`,`_id`,`task_ids` FROM `task_list_metadata`") database.execSQL("DROP TABLE `task_list_metadata`") database.execSQL("ALTER TABLE `_new_task_list_metadata` RENAME TO `task_list_metadata`") database.execSQL("CREATE TABLE IF NOT EXISTS `_new_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `importance` INTEGER NOT NULL, `dueDate` INTEGER NOT NULL, `hideUntil` INTEGER NOT NULL, `created` INTEGER NOT NULL, `modified` INTEGER NOT NULL, `completed` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `notes` TEXT, `estimatedSeconds` INTEGER NOT NULL, `elapsedSeconds` INTEGER NOT NULL, `timerStart` INTEGER NOT NULL, `notificationFlags` INTEGER NOT NULL, `lastNotified` INTEGER NOT NULL, `recurrence` TEXT, `repeatUntil` INTEGER NOT NULL, `calendarUri` TEXT, `remoteId` TEXT, `collapsed` INTEGER NOT NULL, `parent` INTEGER NOT NULL)") database.execSQL("INSERT INTO `_new_tasks` (`parent`,`notes`,`timerStart`,`estimatedSeconds`,`importance`,`created`,`collapsed`,`dueDate`,`completed`,`repeatUntil`,`title`,`hideUntil`,`remoteId`,`recurrence`,`deleted`,`notificationFlags`,`calendarUri`,`modified`,`_id`,`lastNotified`,`elapsedSeconds`) SELECT `parent`,`notes`,`timerStart`,`estimatedSeconds`,`importance`,`created`,`collapsed`,`dueDate`,`completed`,`repeatUntil`,`title`,`hideUntil`,`remoteId`,`recurrence`,`deleted`,`notificationFlags`,`calendarUri`,`modified`,`_id`,`lastNotified`,`elapsedSeconds` FROM `tasks`") database.execSQL("DROP TABLE `tasks`") database.execSQL("ALTER TABLE `_new_tasks` RENAME TO `tasks`") database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `t_rid` ON `tasks` (`remoteId`)") database.execSQL("CREATE INDEX IF NOT EXISTS `active_and_visible` ON `tasks` (`completed`, `deleted`, `hideUntil`)") } } private val MIGRATION_84_85 = object : Migration(84, 85) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("ALTER TABLE `tasks` ADD COLUMN `repeat_from` INTEGER NOT NULL DEFAULT ${Task.RepeatFrom.DUE_DATE}") database .query("SELECT `_id`, `repeatUntil`, `recurrence` FROM `tasks` WHERE `recurrence` IS NOT NULL AND `recurrence` != ''") .use { cursor -> while (cursor.moveToNext()) { val id = cursor.getLong("_id") val recurrence = cursor.getString("recurrence")?.takeIf { it.isNotBlank() } ?: continue val recur = newRecur(recurrence.withoutFrom()!!) cursor.getLongOrNull("repeatUntil") ?.takeIf { it > 0 } ?.let { recur.until = DateTime(it).toDate() } val repeatFrom = recurrence.repeatFrom() database.execSQL("UPDATE `tasks` SET `repeat_from` = $repeatFrom, `recurrence` = '$recur' WHERE `_id` = $id") } } database.execSQL("CREATE TABLE IF NOT EXISTS `_new_tasks` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `title` TEXT, `importance` INTEGER NOT NULL, `dueDate` INTEGER NOT NULL, `hideUntil` INTEGER NOT NULL, `created` INTEGER NOT NULL, `modified` INTEGER NOT NULL, `completed` INTEGER NOT NULL, `deleted` INTEGER NOT NULL, `notes` TEXT, `estimatedSeconds` INTEGER NOT NULL, `elapsedSeconds` INTEGER NOT NULL, `timerStart` INTEGER NOT NULL, `notificationFlags` INTEGER NOT NULL, `lastNotified` INTEGER NOT NULL, `recurrence` TEXT, `repeat_from` INTEGER NOT NULL DEFAULT 0, `calendarUri` TEXT, `remoteId` TEXT, `collapsed` INTEGER NOT NULL, `parent` INTEGER NOT NULL)") database.execSQL("INSERT INTO `_new_tasks` (`parent`,`notes`,`timerStart`,`estimatedSeconds`,`importance`,`created`,`collapsed`,`dueDate`,`completed`,`title`,`hideUntil`,`remoteId`,`recurrence`,`deleted`,`notificationFlags`,`calendarUri`,`modified`,`_id`,`lastNotified`,`elapsedSeconds`,`repeat_from`) SELECT `parent`,`notes`,`timerStart`,`estimatedSeconds`,`importance`,`created`,`collapsed`,`dueDate`,`completed`,`title`,`hideUntil`,`remoteId`,`recurrence`,`deleted`,`notificationFlags`,`calendarUri`,`modified`,`_id`,`lastNotified`,`elapsedSeconds`,`repeat_from` FROM `tasks`") database.execSQL("DROP TABLE `tasks`") database.execSQL("ALTER TABLE `_new_tasks` RENAME TO `tasks`") database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `t_rid` ON `tasks` (`remoteId`)") database.execSQL("CREATE INDEX IF NOT EXISTS `active_and_visible` ON `tasks` (`completed`, `deleted`, `hideUntil`)") } } private val MIGRATION_85_86 = object : Migration(85, 86) { override fun migrate(database: SupportSQLiteDatabase) { database.execSQL("CREATE TABLE IF NOT EXISTS `attachment_file` (`file_id` INTEGER PRIMARY KEY AUTOINCREMENT, `file_uuid` TEXT NOT NULL, `filename` TEXT NOT NULL, `uri` TEXT NOT NULL)") database.execSQL("INSERT INTO `attachment_file` (`file_id`, `uri`,`filename`,`file_id`,`file_uuid`) SELECT `_id`, `path`,`name`,`_id`,`remoteId` FROM `task_attachments`") database.execSQL("CREATE TABLE IF NOT EXISTS `attachment` (`attachment_id` INTEGER PRIMARY KEY AUTOINCREMENT, `task` INTEGER NOT NULL, `file` INTEGER NOT NULL, `file_uuid` TEXT NOT NULL, FOREIGN KEY(`task`) REFERENCES `tasks`(`_id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`file`) REFERENCES `attachment_file`(`file_id`) ON UPDATE NO ACTION ON DELETE CASCADE)") database.execSQL("CREATE INDEX IF NOT EXISTS `index_attachment_task` ON `attachment` (`task`)") database.execSQL("CREATE INDEX IF NOT EXISTS `index_attachment_file` ON `attachment` (`file`)") database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS `index_attachment_task_file` ON `attachment` (`task`, `file`)") database.execSQL( "INSERT INTO `attachment` (`task`, `file`, `file_uuid`) SELECT `tasks`.`_id`, `task_attachments`.`_id`, `task_attachments`.`remoteId` FROM `task_attachments` JOIN `tasks` ON `tasks`.`remoteId` = `task_attachments`.`task_id`" ) database.execSQL("DROP TABLE `task_attachments`") } } fun migrations(fileStorage: FileStorage) = arrayOf( MIGRATION_35_36, MIGRATION_36_37, MIGRATION_37_38, MIGRATION_38_39, noop(39, 46), MIGRATION_46_47, MIGRATION_47_48, MIGRATION_48_49, MIGRATION_49_50, MIGRATION_50_51, MIGRATION_51_52, MIGRATION_52_53, MIGRATION_53_54, MIGRATION_54_58, MIGRATION_58_59, MIGRATION_59_60, MIGRATION_60_61, MIGRATION_61_62, MIGRATION_62_63, MIGRATION_63_64, MIGRATION_64_65, MIGRATION_65_66, MIGRATION_66_67, MIGRATION_67_68, MIGRATION_68_69, MIGRATION_69_70, MIGRATION_70_71, MIGRATION_71_72, MIGRATION_72_73, MIGRATION_73_74, MIGRATION_74_75, MIGRATION_75_76, MIGRATION_76_77, MIGRATION_77_78, MIGRATION_78_79, MIGRATION_79_80, MIGRATION_80_81, migration_81_82(fileStorage), MIGRATION_82_83, MIGRATION_84_85, MIGRATION_85_86, ) private fun noop(from: Int, to: Int): Migration = object : Migration(from, to) { override fun migrate(database: SupportSQLiteDatabase) {} } fun String?.repeatFrom() = if (this?.contains("FROM=COMPLETION") == true) { Task.RepeatFrom.COMPLETION_DATE } else { Task.RepeatFrom.DUE_DATE } fun String?.withoutFrom(): String? = this?.replace(";?FROM=[^;]*".toRegex(), "") }
gpl-3.0
7527f041f5d3b0f3beb91625d18ef599
75.233542
753
0.629986
3.954468
false
false
false
false
rcgroot/open-gpstracker-ng
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/gpxexport/GpxShareProvider.kt
1
4063
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ - ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.gpxexport import android.content.ContentProvider import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.net.Uri import android.os.ParcelFileDescriptor import nl.sogeti.android.gpstracker.ng.base.BuildConfig import nl.sogeti.android.gpstracker.ng.features.gpxexport.tasks.GpxCreator import nl.sogeti.android.gpstracker.service.util.trackUri import timber.log.Timber import java.io.FileOutputStream class GpxShareProvider : ContentProvider() { companion object { const val MIME_TYPE_GPX = "application/gpx+xml" const val MIME_TYPE_GENERAL = "application/octet-stream" val AUTHORITY = BuildConfig.APPLICATION_ID + ".gpxshareprovider" val uriMatcher = UriMatcher(UriMatcher.NO_MATCH) private val TRACK_ID = 1 init { uriMatcher.addURI(AUTHORITY, "tracks/#", TRACK_ID) } } override fun onCreate(): Boolean { return true } override fun getType(uri: Uri?): String? { var type: String? = null val match = uriMatcher.match(uri) if (match == TRACK_ID) { type = MIME_TYPE_GPX } return type } override fun openFile(uri: Uri?, mode: String?): ParcelFileDescriptor? { var file: ParcelFileDescriptor? = null val match = uriMatcher.match(uri) if (match == TRACK_ID) { file = openPipeHelper(uri, MIME_TYPE_GPX, null, null) { output, shareUri, _, _, _ -> val outputStream = FileOutputStream(output.fileDescriptor) val trackUri = trackUri(shareUri.lastPathSegment.toLong()) val gpxCreator = GpxCreator(context, trackUri) gpxCreator.createGpx(outputStream) } } return file } override fun insert(uri: Uri?, values: ContentValues?): Uri? { Timber.e("Insert not supported") return null } override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? { Timber.e("Query not supported") return null } override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int { Timber.e("Update not supported") return 0 } override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int { Timber.e("Delete not supported") return 0 } }
gpl-3.0
203ad50b9b56c180e3d30ee7de23cee2
36.62037
151
0.621954
4.638128
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/channels/ChannelViewModel.kt
1
6060
package org.tvheadend.tvhclient.ui.features.channels import android.app.Application import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import org.tvheadend.data.entity.Channel import org.tvheadend.tvhclient.R import timber.log.Timber class ChannelViewModel(application: Application) : BaseChannelViewModel(application), SharedPreferences.OnSharedPreferenceChangeListener { var selectedListPosition = 0 var selectedTimeOffset = 0 val channels: LiveData<List<Channel>> var showGenreColor = MutableLiveData<Boolean>() var showNextProgramTitle = MutableLiveData<Boolean>() var showProgressBar = MutableLiveData<Boolean>() var showProgramSubtitle = MutableLiveData<Boolean>() val showChannelName = MutableLiveData<Boolean>() val showChannelNumber = MutableLiveData<Boolean>() private val channelSortOrder = MutableLiveData<Int>() private val defaultShowChannelName = application.applicationContext.resources.getBoolean(R.bool.pref_default_channel_name_enabled) private val defaultShowChannelNumber = application.applicationContext.resources.getBoolean(R.bool.pref_default_channel_number_enabled) private val defaultShowProgramSubtitle = application.applicationContext.resources.getBoolean(R.bool.pref_default_program_subtitle_enabled) private val defaultShowProgressBar = application.applicationContext.resources.getBoolean(R.bool.pref_default_program_progressbar_enabled) private val defaultShowNextProgramTitle = application.applicationContext.resources.getBoolean(R.bool.pref_default_next_program_title_enabled) private val defaultShowGenreColor = application.applicationContext.resources.getBoolean(R.bool.pref_default_genre_colors_for_channels_enabled) private val defaultShowAllChannelTags = application.applicationContext.resources.getBoolean(R.bool.pref_default_empty_channel_tags_enabled) init { val trigger = ChannelLiveData(selectedTime, channelSortOrder, selectedChannelTagIds) channels = Transformations.switchMap(trigger) { value -> val time = value.first val sortOrder = value.second val tagIds = value.third if (time == null) { Timber.d("Not loading channels because the selected time is not set") return@switchMap null } if (sortOrder == null) { Timber.d("Not loading channels because no channel sort order is set") return@switchMap null } if (tagIds == null) { Timber.d("Not loading channels because no selected channel tag id is set") return@switchMap null } Timber.d("Loading channels because either the selected time, channel sort order or channel tag ids have changed") return@switchMap appRepository.channelData.getAllChannelsByTime(time, sortOrder, tagIds) } onSharedPreferenceChanged(sharedPreferences, "channel_sort_order") onSharedPreferenceChanged(sharedPreferences, "channel_name_enabled") onSharedPreferenceChanged(sharedPreferences, "channel_number_enabled") onSharedPreferenceChanged(sharedPreferences, "program_progressbar_enabled") onSharedPreferenceChanged(sharedPreferences, "program_subtitle_enabled") onSharedPreferenceChanged(sharedPreferences, "next_program_title_enabled") onSharedPreferenceChanged(sharedPreferences, "genre_colors_for_channels_enabled") onSharedPreferenceChanged(sharedPreferences, "empty_channel_tags_enabled") sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onCleared() { sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onCleared() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { Timber.d("Shared preference $key has changed") if (sharedPreferences == null) return when (key) { "channel_sort_order" -> channelSortOrder.value = Integer.valueOf(sharedPreferences.getString("channel_sort_order", defaultChannelSortOrder) ?: defaultChannelSortOrder) "channel_name_enabled" -> showChannelName.value = sharedPreferences.getBoolean(key, defaultShowChannelName) "channel_number_enabled" -> showChannelNumber.value = sharedPreferences.getBoolean(key, defaultShowChannelNumber) "program_subtitle_enabled" -> showProgramSubtitle.value = sharedPreferences.getBoolean(key, defaultShowProgramSubtitle) "program_progressbar_enabled" -> showProgressBar.value = sharedPreferences.getBoolean(key, defaultShowProgressBar) "next_program_title_enabled" -> showNextProgramTitle.value = sharedPreferences.getBoolean(key, defaultShowNextProgramTitle) "genre_colors_for_channels_enabled" -> showGenreColor.value = sharedPreferences.getBoolean(key, defaultShowGenreColor) "empty_channel_tags_enabled" -> showAllChannelTags.value = sharedPreferences.getBoolean(key, defaultShowAllChannelTags) } } internal class ChannelLiveData(selectedTime: LiveData<Long>, selectedChannelSortOrder: LiveData<Int>, selectedChannelTagIds: LiveData<List<Int>?>) : MediatorLiveData<Triple<Long?, Int?, List<Int>?>>() { init { addSource(selectedTime) { time -> value = Triple(time, selectedChannelSortOrder.value, selectedChannelTagIds.value) } addSource(selectedChannelSortOrder) { order -> value = Triple(selectedTime.value, order, selectedChannelTagIds.value) } addSource(selectedChannelTagIds) { integers -> value = Triple(selectedTime.value, selectedChannelSortOrder.value, integers) } } } }
gpl-3.0
19766256a461e661adc9fc562dbab38e
57.269231
179
0.726073
5.311131
false
false
false
false
iiordanov/remote-desktop-clients
bVNC/src/main/java/com/iiordanov/util/SamsungDexUtils.kt
1
875
package com.iiordanov.util import android.app.Activity import android.content.ComponentName import android.util.Log object SamsungDexUtils { val TAG = this::class.java.name fun dexMetaKeyCapture(activity: Activity) { runCatching { val semWindowManager = Class.forName("com.samsung.android.view.SemWindowManager") val getInstanceMethod = semWindowManager.getMethod("getInstance") val manager = getInstanceMethod.invoke(null) val requestMetaKeyEvent = semWindowManager.getDeclaredMethod( "requestMetaKeyEvent", ComponentName::class.java, Boolean::class.java) requestMetaKeyEvent.invoke(manager, activity.componentName, true) }.onFailure { Log.d(TAG, "Could not call com.samsung.android.view.SemWindowManager.requestMetaKeyEvent " + it.message) } } }
gpl-3.0
dcb40fcda138dfdb46852cf929f42885
37.086957
116
0.701714
4.581152
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/support/IngestionModelAccessService.kt
1
4054
package net.nemerosa.ontrack.extension.github.ingestion.support import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.github.ingestion.processing.events.WorkflowRun import net.nemerosa.ontrack.extension.github.ingestion.processing.model.IPullRequest import net.nemerosa.ontrack.extension.github.ingestion.processing.model.Repository import net.nemerosa.ontrack.extension.github.model.GitHubEngineConfiguration import net.nemerosa.ontrack.model.structure.* /** * Service used to access the model resources (project, branch) when dealing with * the ingestion. */ interface IngestionModelAccessService { /** * Gets the GitHub configuration for a given repository. */ fun findGitHubEngineConfiguration( repository: Repository, configurationName: String?, ): GitHubEngineConfiguration /** * Gets or creates a project for the given repository. * * @param repository Repository * @param configuration GitHub configuration name */ fun getOrCreateProject( repository: Repository, configuration: String?, ): Project /** * Gets or creates a branch for the given [project]. * * @param project Parent project * @param headBranch Git branch * @param pullRequest Pull request (if any) */ fun getOrCreateBranch( project: Project, headBranch: String, pullRequest: IPullRequest?, ): Branch /** * Gets a branch from a payload if it exists. * * @param repository Repository * @param headBranch Git branch * @param pullRequest Pull request (if any) */ fun getBranchIfExists( repository: Repository, headBranch: String, pullRequest: IPullRequest?, ): Branch? /** * Finds a project from a repository. */ fun findProjectFromRepository(repository: Repository): Project? /** * Finds a branch from a Git reference */ fun findBranchByRef(project: Project, ref: String, pullRequest: IPullRequest?,): Branch? /** * Sets a workflow run ID on a build. * * @param build Build to set * @param workflowRun Run to register */ fun setBuildRunId( build: Build, workflowRun: WorkflowRun, ) /** * Finds a build using its workflow run ID. */ fun findBuildByRunId( repository: Repository, runId: Long, ): Build? /** * Finds a build using its name. */ fun findBuildByBuildName( repository: Repository, buildName: String, ): Build? /** * Finds a build using its release property (label). */ fun findBuildByBuildLabel( repository: Repository, buildLabel: String, ): Build? /** * Gets or creates a validation stamp * * @param branch Parent branch * @param vsName Name of the validation stamp * @param vsDescription Description of the validation stamp * @param dataType FQCN or shortcut of the data type for this validation stamp * @param dataTypeConfig JSON configuration for the data type * @param image Image reference */ fun setupValidationStamp( branch: Branch, vsName: String, vsDescription: String?, dataType: String? = null, dataTypeConfig: JsonNode? = null, image: String? = null, ): ValidationStamp /** * Gets or creates a promotion level * * @param branch Parent branch * @param plName Name of the promotion level * @param plDescription Description of the promotion level * @param image Image reference */ fun setupPromotionLevel( branch: Branch, plName: String, plDescription: String?, image: String? = null, ): PromotionLevel } /** * Prefix for the tags */ const val REFS_TAGS_PREFIX = "refs/tags/" /** * Prefix for the branches */ const val REFS_HEADS_PREFIX = "refs/heads/"
mit
eb10b5475ec54ec7f01cb12be550528b
25.847682
84
0.640602
4.703016
false
true
false
false
openHPI/android-app
app/src/main/java/de/xikolo/download/filedownload/FileDownloadItem.kt
1
10115
package de.xikolo.download.filedownload import android.util.Log import androidx.fragment.app.FragmentActivity import de.xikolo.App import de.xikolo.download.DownloadItem import de.xikolo.download.DownloadStatus import de.xikolo.extensions.observeOnce import de.xikolo.managers.PermissionManager import de.xikolo.models.DownloadAsset import de.xikolo.models.Storage import de.xikolo.states.PermissionStateLiveData import de.xikolo.utils.LanalyticsUtil import de.xikolo.utils.extensions.buildWriteErrorMessage import de.xikolo.utils.extensions.createIfNotExists import de.xikolo.utils.extensions.internalStorage import de.xikolo.utils.extensions.open import de.xikolo.utils.extensions.preferredStorage import de.xikolo.utils.extensions.sdcardStorage import de.xikolo.utils.extensions.showToast import java.io.File open class FileDownloadItem( val url: String?, open val fileName: String, var storage: Storage = App.instance.preferredStorage ) : DownloadItem<File, FileDownloadIdentifier>() { companion object { val TAG: String? = DownloadAsset::class.simpleName } protected open fun getFileFolder(): String { return storage.file.absolutePath } val filePath: String get() = getFileFolder() + File.separator + fileName protected open val size: Long = 0L protected open val mimeType = "application/pdf" protected open val showNotification = true protected open val secondaryDownloadItems = setOf<FileDownloadItem>() protected open val deleteSecondaryDownloadItemPredicate: (FileDownloadItem) -> Boolean = { _ -> true } private var downloader: FileDownloadHandler = FileDownloadHandler private val request get() = FileDownloadRequest( url!!, File("$filePath.tmp"), title, showNotification ) private var downloadIdentifier: FileDownloadIdentifier? = null private fun getDownloadIdentifier(): FileDownloadIdentifier { return downloadIdentifier ?: FileDownloadIdentifier(request.buildRequest().id) } override val isDownloadable: Boolean get() = url != null override val title: String get() = fileName override val downloadSize: Long get() { var total = size secondaryDownloadItems.forEach { total += it.downloadSize } return total } override val download: File? get() { val originalStorage: Storage = storage storage = App.instance.internalStorage val internalFile = File(filePath) if (internalFile.exists() && internalFile.isFile) { storage = originalStorage return internalFile } val sdcardStorage: Storage? = App.instance.sdcardStorage if (sdcardStorage != null) { storage = sdcardStorage val sdcardFile = File(filePath) if (sdcardFile.exists() && sdcardFile.isFile) { storage = originalStorage return sdcardFile } } storage = originalStorage return null } override val openAction: ((FragmentActivity) -> Unit)? get() = { activity -> download?.open(activity, mimeType, false) } override var stateListener: StateListener? = null override fun start(activity: FragmentActivity, callback: ((FileDownloadIdentifier?) -> Unit)?) { performAction(activity) { isDownloadRunning { isDownloadRunning -> when { isDownloadRunning || downloadExists -> callback?.invoke(null) isDownloadable -> { File( filePath.substring( 0, filePath.lastIndexOf(File.separator) ) ).createIfNotExists() downloader.download( request, { status -> when (status?.state) { DownloadStatus.State.CANCELLED -> cancel(activity) DownloadStatus.State.SUCCESSFUL -> { File("$filePath.tmp").renameTo(File(filePath)) stateListener?.onCompleted() } DownloadStatus.State.FAILED -> stateListener?.onCompleted() } }, { identifier -> if (identifier != null) { downloadIdentifier = identifier if (this is DownloadAsset.Course.Item) { LanalyticsUtil.trackDownloadedFile(this) } secondaryDownloadItems.forEach { it.start(activity) } stateListener?.onStarted() callback?.invoke(identifier) } else { callback?.invoke(null) } } ) } else -> callback?.invoke(null) } } } } override fun cancel(activity: FragmentActivity, callback: ((Boolean) -> Unit)?) { performAction(activity) { downloader.cancel(getDownloadIdentifier()) { success -> delete(activity) secondaryDownloadItems.forEach { it.cancel(activity) } callback?.invoke(success) } } } override fun delete(activity: FragmentActivity, callback: ((Boolean) -> Unit)?) { performAction(activity) { downloader.cancel(getDownloadIdentifier()) { if (!downloadExists) { File(filePath).parentFile?.let { Storage(it).clean() } stateListener?.onDeleted() callback?.invoke(false) } else { if (download?.delete() == true) { secondaryDownloadItems.forEach { if (deleteSecondaryDownloadItemPredicate(it)) { it.delete(activity) } } } stateListener?.onDeleted() callback?.invoke(true) } } } } override fun getProgress(callback: (Pair<Long?, Long?>) -> Unit) { status { callback(it?.downloadedBytes to it?.totalBytes) } } override fun isDownloadRunning(callback: (Boolean) -> Unit) { if (!isDownloadable) { callback(false) return } status { callback( if (it != null) { it.state == DownloadStatus.State.RUNNING || it.state == DownloadStatus.State.PENDING } else false ) } } private fun status(callback: (DownloadStatus?) -> Unit) { var totalBytes = 0L var writtenBytes = 0L var state = DownloadStatus.State.SUCCESSFUL downloader.status(getDownloadIdentifier()) { mainDownload -> if (mainDownload != null && mainDownload.totalBytes > 0L) { totalBytes += mainDownload.totalBytes writtenBytes += mainDownload.downloadedBytes state = state.and(mainDownload.state) } else { totalBytes += size } secondaryDownloadItems.forEach { it.status { status -> if (status != null) { totalBytes += status.totalBytes writtenBytes += status.downloadedBytes state = state.and(status.state) callback( DownloadStatus( totalBytes, writtenBytes, state ) ) } } } callback( DownloadStatus( totalBytes, writtenBytes, state ) ) } } private fun performAction(activity: FragmentActivity, action: () -> Unit): Boolean { return if (storage.isWritable) { if ( PermissionManager(activity).requestPermission( PermissionManager.WRITE_EXTERNAL_STORAGE ) == 1 ) { action() true } else { App.instance.state.permission.of( PermissionManager.REQUEST_CODE_WRITE_EXTERNAL_STORAGE ) .observeOnce(activity) { state -> return@observeOnce if ( state == PermissionStateLiveData.PermissionStateCode.GRANTED ) { performAction(activity, action) true } else false } false } } else { val msg = App.instance.buildWriteErrorMessage() Log.w(TAG, msg) activity.showToast(msg) false } } }
bsd-3-clause
28a3b0c6c48d990a1d3b286d5a9f2c8f
33.057239
100
0.485022
6.160171
false
false
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/ActivityThemeProvider.kt
1
1424
package org.equeim.tremotesf.ui import androidx.appcompat.app.AppCompatDelegate import kotlinx.coroutines.MainScope import kotlinx.coroutines.async import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking import timber.log.Timber object ActivityThemeProvider { val colorTheme: StateFlow<Settings.ColorTheme> /** * Get initial values of theme and night mode, blocking main thread * until they are retrieved from SharedPreferences */ init { Timber.i("init() called") val (initialColorTheme, initialDarkThemeMode) = runBlocking { val colors = async { Settings.colorTheme.get().also { Timber.i("Received initial value of color theme: $it") } } val darkThemeMode = async { Settings.darkThemeMode.get().also { Timber.i("Received initial value of dark theme mode: $it") } } colors.await() to darkThemeMode.await() } val scope = MainScope() colorTheme = Settings.colorTheme.flow() .stateIn(scope, SharingStarted.Eagerly, initialColorTheme) AppCompatDelegate.setDefaultNightMode(initialDarkThemeMode.nightMode) Settings.darkThemeMode.flow().dropWhile { it == initialDarkThemeMode }.onEach { Timber.i("Dark theme mode changed to $it") AppCompatDelegate.setDefaultNightMode(it.nightMode) }.launchIn(scope) Timber.i("init() returned") } }
gpl-3.0
a84c6082f36b8b21f6bc4d730fa7c8ce
35.512821
138
0.692416
4.730897
false
false
false
false
ksmirenko/kpc
src/test/kotlin/io/github/ksmirenko/kpc/TokenInterpreterTest.kt
1
1103
package io.github.ksmirenko.kpc import org.junit.Test import kotlin.test.assertEquals class TokenInterpreterTest { val parser = BrainfuckParser() val interpreter = TokenInterpreter() @Test fun testSimpleOutput() = testInterpreter( "+++++-+++++.", "", "${9.toByte().toChar()}" ) @Test fun testByteOverflow() = testInterpreter( "------.", "", "${250.toByte().toChar()}" ) @Test fun testInputNextPrev() = testInterpreter( ",>,>,>,>,>,.<.<.<.<.<.", "kotlin", "niltok" ) @Test fun testHelloWorld() = testInterpreter( "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---" + ".+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.", "", "Hello World!\n" ) fun testInterpreter(program : String, input : String, output : String) { val sw = StringPrintStream() interpreter.run(parser.parse(program), StringInputStream(input), sw) assertEquals(output, sw.toString()) } }
mit
f37301acb04cdd27fa349e32b10cf713
26.6
76
0.466002
3.967626
false
true
false
false
Ztiany/Repository
Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/utils/githubDateFormatter.kt
2
1203
package com.bennyhuo.github.utils import java.text.SimpleDateFormat import java.util.* /** * Created by benny on 9/25/17. */ /** * ISO 8601 * https://stackoverflow.com/questions/19112357/java-simpledateformatyyyy-mm-ddthhmmssz-gives-timezone-as-ist */ val githubDateFormatter by lazy { SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.CHINA) .apply { timeZone = TimeZone.getTimeZone("GMT") } } val outputDateFormatter by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA) } fun Date.format(pattern: String) = SimpleDateFormat(pattern, Locale.CHINA).format(this) fun githubTimeToDate(time: String) = githubDateFormatter.parse(time) fun Date.view(): String{ val now = System.currentTimeMillis() val seconds = (now - this.time) / 1000 val minutes = seconds / 60 return if(minutes >= 60){ val hours = minutes / 60 if(hours in 24..47){ "Yesterday" } else if(hours >= 48 ){ outputDateFormatter.format(this) } else { "$hours hours ago" } } else if(minutes < 1){ "$seconds seconds ago" } else { "$minutes minutes ago" } }
apache-2.0
aaa2195e1514cd1c30ae7623453984f1
24.617021
109
0.623441
3.712963
false
false
false
false
lare96/luna
plugins/world/player/skill/fletching/stringBow/StringBowAction.kt
1
1410
package world.player.skill.fletching.stringBow import api.predef.* import io.luna.game.action.Action import io.luna.game.action.InventoryAction import io.luna.game.model.item.Item import io.luna.game.model.mob.Animation import io.luna.game.model.mob.Player /** * An [InventoryAction] implementation that strings bows. */ class StringBowAction(plr: Player, val bow: Bow, count: Int) : InventoryAction(plr, true, 2, count) { companion object { /** * The stringing animation. */ val ANIMATION = Animation(713) } override fun add() = listOf(bow.strungItem) override fun remove() = listOf(bow.unstrungItem, Item(Bow.BOW_STRING)) override fun executeIf(start: Boolean) = when { mob.fletching.level < bow.level -> { mob.sendMessage("You need a Fletching level of ${bow.level} to string this bow.") false } !mob.inventory.containsAll(Bow.BOW_STRING, bow.unstrung) -> false else -> true } override fun execute() { mob.sendMessage("You add a string to the bow.") mob.animation(ANIMATION) mob.fletching.addExperience(bow.exp) } override fun ignoreIf(other: Action<*>) = when (other) { is StringBowAction -> bow == other.bow else -> false } }
mit
ab612ff50bd7c2888a88d7afd0b4fd67
27.795918
97
0.600709
3.905817
false
false
false
false
Ribesg/anko
dsl/static/src/common/Dimensions.kt
1
3262
/* * 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.Fragment import android.content.Context import android.view.View val LDPI: Int = android.util.DisplayMetrics.DENSITY_LOW val MDPI: Int = android.util.DisplayMetrics.DENSITY_MEDIUM val HDPI: Int = android.util.DisplayMetrics.DENSITY_HIGH //May not be available on older Android versions val TVDPI: Int = 213 val XHDPI: Int = 320 val XXHDPI: Int = 480 val XXXHDPI: Int = 640 val MAXDPI: Int = 0xfffe //returns dip(dp) dimension value in pixels fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt() fun Context.dip(value: Float): Int = (value * resources.displayMetrics.density).toInt() //return sp dimension value in pixels fun Context.sp(value: Int): Int = (value * resources.displayMetrics.scaledDensity).toInt() fun Context.sp(value: Float): Int = (value * resources.displayMetrics.scaledDensity).toInt() //converts px value into dip or sp fun Context.px2dip(px: Int): Float = (px.toFloat() / resources.displayMetrics.density).toFloat() fun Context.px2sp(px: Int): Float = (px.toFloat() / resources.displayMetrics.scaledDensity).toFloat() fun Context.dimen(resource: Int): Int = resources.getDimensionPixelSize(resource) //the same for nested DSL components inline fun AnkoContext<*>.dip(value: Int): Int = ctx.dip(value) inline fun AnkoContext<*>.dip(value: Float): Int = ctx.dip(value) inline fun AnkoContext<*>.sp(value: Int): Int = ctx.sp(value) inline fun AnkoContext<*>.sp(value: Float): Int = ctx.sp(value) inline fun AnkoContext<*>.px2dip(px: Int): Float = ctx.px2dip(px) inline fun AnkoContext<*>.px2sp(px: Int): Float = ctx.px2sp(px) inline fun AnkoContext<*>.dimen(resource: Int): Int = ctx.dimen(resource) //the same for the views inline fun View.dip(value: Int): Int = context.dip(value) inline fun View.dip(value: Float): Int = context.dip(value) inline fun View.sp(value: Int): Int = context.sp(value) inline fun View.sp(value: Float): Int = context.sp(value) inline fun View.px2dip(px: Int): Float = context.px2dip(px) inline fun View.px2sp(px: Int): Float = context.px2sp(px) inline fun View.dimen(resource: Int): Int = context.dimen(resource) //the same for Fragments inline fun Fragment.dip(value: Int): Int = activity.dip(value) inline fun Fragment.dip(value: Float): Int = activity.dip(value) inline fun Fragment.sp(value: Int): Int = activity.sp(value) inline fun Fragment.sp(value: Float): Int = activity.sp(value) inline fun Fragment.px2dip(px: Int): Float = activity.px2dip(px) inline fun Fragment.px2sp(px: Int): Float = activity.px2sp(px) inline fun Fragment.dimen(resource: Int): Int = activity.dimen(resource)
apache-2.0
a619c9c220b5e417d9364a7ed0c1b823
41.934211
101
0.746168
3.48877
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/activity/BaseActivity.kt
1
11919
package org.wikipedia.activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.net.ConnectivityManager import android.os.Build import android.os.Bundle import android.view.* import android.widget.TextView import androidx.annotation.ColorInt import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.pm.ShortcutManagerCompat import com.skydoves.balloon.Balloon import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.functions.Consumer import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.LoginFunnel import org.wikipedia.analytics.eventplatform.BreadCrumbLogEvent import org.wikipedia.analytics.eventplatform.NotificationInteractionEvent import org.wikipedia.appshortcuts.AppShortcuts import org.wikipedia.auth.AccountUtil import org.wikipedia.events.* import org.wikipedia.login.LoginActivity import org.wikipedia.main.MainActivity import org.wikipedia.page.LinkMovementMethodExt import org.wikipedia.readinglist.ReadingListSyncBehaviorDialogs import org.wikipedia.readinglist.ReadingListsReceiveSurveyHelper import org.wikipedia.readinglist.ReadingListsShareSurveyHelper import org.wikipedia.readinglist.sync.ReadingListSyncAdapter import org.wikipedia.readinglist.sync.ReadingListSyncEvent import org.wikipedia.recurring.RecurringTasksExecutor import org.wikipedia.savedpages.SavedPageSyncService import org.wikipedia.settings.Prefs import org.wikipedia.settings.SiteInfoClient import org.wikipedia.util.* import org.wikipedia.views.ImageZoomHelper import org.wikipedia.views.ViewUtil import kotlin.math.abs abstract class BaseActivity : AppCompatActivity() { private lateinit var exclusiveBusMethods: ExclusiveBusConsumer private val networkStateReceiver = NetworkStateReceiver() private var previousNetworkState = WikipediaApp.instance.isOnline private val disposables = CompositeDisposable() private var currentTooltip: Balloon? = null private var imageZoomHelper: ImageZoomHelper? = null private var startTouchX = 0f private var startTouchY = 0f private var startTouchMillis = 0L private var touchSlopPx = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) exclusiveBusMethods = ExclusiveBusConsumer() disposables.add(WikipediaApp.instance.bus.subscribe(NonExclusiveBusConsumer())) setTheme() removeSplashBackground() if (AppShortcuts.ACTION_APP_SHORTCUT == intent.action) { intent.putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, Constants.InvokeSource.APP_SHORTCUTS) val shortcutId = intent.getStringExtra(AppShortcuts.APP_SHORTCUT_ID) if (!shortcutId.isNullOrEmpty()) { ShortcutManagerCompat.reportShortcutUsed(applicationContext, shortcutId) } } supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { NotificationInteractionEvent.processIntent(intent) } // Conditionally execute all recurring tasks RecurringTasksExecutor(WikipediaApp.instance).run() if (Prefs.isReadingListsFirstTimeSync && AccountUtil.isLoggedIn) { Prefs.isReadingListsFirstTimeSync = false Prefs.isReadingListSyncEnabled = true ReadingListSyncAdapter.manualSyncWithForce() } val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(networkStateReceiver, filter) DeviceUtil.setLightSystemUiVisibility(this) setStatusBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)) setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)) maybeShowLoggedOutInBackgroundDialog() if (ReadingListsShareSurveyHelper.shouldShowSurvey(this)) { ReadingListsShareSurveyHelper.maybeShowSurvey(this) } else { ReadingListsReceiveSurveyHelper.maybeShowSurvey(this) } touchSlopPx = ViewConfiguration.get(this).scaledTouchSlop Prefs.localClassName = localClassName } override fun onResumeFragments() { super.onResumeFragments() BreadCrumbLogEvent.logScreenShown(this) } override fun onDestroy() { unregisterReceiver(networkStateReceiver) disposables.dispose() if (EXCLUSIVE_BUS_METHODS === exclusiveBusMethods) { unregisterExclusiveBusMethods() } super.onDestroy() } override fun onStop() { WikipediaApp.instance.sessionFunnel.persistSession() super.onStop() } override fun onResume() { super.onResume() WikipediaApp.instance.sessionFunnel.touchSession() // allow this activity's exclusive bus methods to override any existing ones. unregisterExclusiveBusMethods() EXCLUSIVE_BUS_METHODS = exclusiveBusMethods EXCLUSIVE_DISPOSABLE = WikipediaApp.instance.bus.subscribe(EXCLUSIVE_BUS_METHODS!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> false } } override fun onBackPressed() { super.onBackPressed() BreadCrumbLogEvent.logBackPress(this) } override fun dispatchTouchEvent(event: MotionEvent): Boolean { if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) { dismissCurrentTooltip() } when (event.action) { MotionEvent.ACTION_DOWN -> { startTouchMillis = System.currentTimeMillis() startTouchX = event.x startTouchY = event.y } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { val touchMillis = System.currentTimeMillis() - startTouchMillis val dx = abs(startTouchX - event.x) val dy = abs(startTouchY - event.y) if (dx <= touchSlopPx && dy <= touchSlopPx) { ViewUtil.findClickableViewAtPoint(window.decorView, startTouchX.toInt(), startTouchY.toInt())?.let { if (it is TextView && it.movementMethod is LinkMovementMethodExt) { // If they clicked a link in a TextView, it will be handled by the // MovementMethod instead of here. } else { if (touchMillis > ViewConfiguration.getLongPressTimeout()) { BreadCrumbLogEvent.logLongClick(this@BaseActivity, it) } else { BreadCrumbLogEvent.logClick(this@BaseActivity, it) } } } } } } imageZoomHelper?.let { return it.onDispatchTouchEvent(event) || super.dispatchTouchEvent(event) } return super.dispatchTouchEvent(event) } protected fun setStatusBarColor(@ColorInt color: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { window.statusBarColor = color } } protected fun setNavigationBarColor(@ColorInt color: Int) { DeviceUtil.setNavigationBarColor(window, color) } protected open fun setTheme() { setTheme(WikipediaApp.instance.currentTheme.resourceId) } protected open fun onGoOffline() {} protected open fun onGoOnline() {} private inner class NetworkStateReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val isDeviceOnline = WikipediaApp.instance.isOnline if (isDeviceOnline) { if (!previousNetworkState) { onGoOnline() } SavedPageSyncService.enqueue() } else { onGoOffline() } previousNetworkState = isDeviceOnline } } private fun removeSplashBackground() { window.setBackgroundDrawable(null) } private fun unregisterExclusiveBusMethods() { EXCLUSIVE_DISPOSABLE?.dispose() EXCLUSIVE_DISPOSABLE = null EXCLUSIVE_BUS_METHODS = null } private fun maybeShowLoggedOutInBackgroundDialog() { if (Prefs.loggedOutInBackground) { Prefs.loggedOutInBackground = false AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.logged_out_in_background_title) .setMessage(R.string.logged_out_in_background_dialog) .setPositiveButton(R.string.logged_out_in_background_login) { _, _ -> startActivity(LoginActivity.newIntent(this@BaseActivity, LoginFunnel.SOURCE_LOGOUT_BACKGROUND)) } .setNegativeButton(R.string.logged_out_in_background_cancel, null) .show() } } private fun dismissCurrentTooltip() { currentTooltip?.dismiss() currentTooltip = null } fun setCurrentTooltip(tooltip: Balloon) { dismissCurrentTooltip() currentTooltip = tooltip } fun setImageZoomHelper() { imageZoomHelper = ImageZoomHelper(this) } open fun onUnreadNotification() { } /** * Bus consumer that should be registered by all created activities. */ private inner class NonExclusiveBusConsumer : Consumer<Any> { override fun accept(event: Any) { if (event is ThemeFontChangeEvent) { ActivityCompat.recreate(this@BaseActivity) } } } /** * Bus methods that should be caught only by the topmost activity. */ private inner class ExclusiveBusConsumer : Consumer<Any> { override fun accept(event: Any) { if (event is NetworkConnectEvent) { SavedPageSyncService.enqueue() } else if (event is SplitLargeListsEvent) { AlertDialog.Builder(this@BaseActivity) .setMessage(getString(R.string.split_reading_list_message, SiteInfoClient.maxPagesPerReadingList)) .setPositiveButton(R.string.reading_list_split_dialog_ok_button_text, null) .show() } else if (event is ReadingListsNoLongerSyncedEvent) { ReadingListSyncBehaviorDialogs.detectedRemoteTornDownDialog(this@BaseActivity) } else if (event is ReadingListsEnableDialogEvent && this@BaseActivity is MainActivity) { ReadingListSyncBehaviorDialogs.promptEnableSyncDialog(this@BaseActivity) } else if (event is LoggedOutInBackgroundEvent) { maybeShowLoggedOutInBackgroundDialog() } else if (event is ReadingListSyncEvent) { if (event.showMessage && !Prefs.isSuggestedEditsHighestPriorityEnabled) { FeedbackUtil.makeSnackbar(this@BaseActivity, getString(R.string.reading_list_toast_last_sync)).show() } } else if (event is UnreadNotificationsEvent) { runOnUiThread { if (!isDestroyed) { onUnreadNotification() } } } } } companion object { private var EXCLUSIVE_BUS_METHODS: ExclusiveBusConsumer? = null private var EXCLUSIVE_DISPOSABLE: Disposable? = null } }
apache-2.0
915efb039f6135b2c54f9205cf5e34f5
37.698052
187
0.660878
5.299689
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsTypeItemView.kt
1
2358
package org.wikipedia.suggestededits import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.LinearLayout import androidx.appcompat.content.res.AppCompatResources import androidx.core.widget.ImageViewCompat import org.wikipedia.R import org.wikipedia.databinding.ItemSuggestedEditsTypeBinding import org.wikipedia.usercontrib.Contribution.Companion.EDIT_TYPE_GENERIC import org.wikipedia.util.DimenUtil import org.wikipedia.util.ResourceUtil class SuggestedEditsTypeItemView constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) { private val binding = ItemSuggestedEditsTypeBinding.inflate(LayoutInflater.from(context), this) private var editType: Int = EDIT_TYPE_GENERIC private var callback: Callback? = null interface Callback { fun onTypeItemClick(editType: Int) } init { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) setPadding(0, DimenUtil.roundedDpToPx(4f), 0, DimenUtil.roundedDpToPx(4f)) setOnClickListener { callback?.onTypeItemClick(editType) } } fun setEnabledStateUI() { binding.editTypeTitle.setTextColor(ResourceUtil.getThemedColor(context, R.attr.themed_icon_color)) ImageViewCompat.setImageTintList(binding.editTypeImage, AppCompatResources.getColorStateList(context, ResourceUtil.getThemedAttributeId(context, R.attr.themed_icon_color))) binding.editTypeContainer.setBackgroundResource(R.drawable.rounded_12dp_accent90_fill) } fun setDisabledStateUI() { binding.editTypeTitle.setTextColor(ResourceUtil.getThemedColor(context, R.attr.secondary_text_color)) ImageViewCompat.setImageTintList(binding.editTypeImage, AppCompatResources.getColorStateList(context, ResourceUtil.getThemedAttributeId(context, R.attr.chart_shade4))) binding.editTypeContainer.setBackgroundResource(R.drawable.rounded_12dp_corner_base90_fill) } fun setAttributes(title: String, imageResource: Int, editType: Int, callback: Callback) { binding.editTypeTitle.text = title binding.editTypeImage.setImageResource(imageResource) this.editType = editType this.callback = callback } }
apache-2.0
2993dda9b844e5039e6ffebc09a6a2f7
45.235294
180
0.779898
4.650888
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/acra/AcraJob.kt
1
3071
package org.softeg.slartus.forpdaplus.acra import android.util.Log import com.evernote.android.job.Job import com.evernote.android.job.JobManager import com.evernote.android.job.JobRequest import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit /* * Created by slinkin on 07.02.2018. */ class AcraJob : Job() { companion object { const val TAG = "acra_job_tag" fun scheduleJob(): Int { sendLogs() val jobRequests = JobManager.instance().getAllJobRequestsForTag(TAG) if (jobRequests.isNotEmpty()) { return jobRequests.iterator().next().jobId } return JobRequest.Builder(TAG) .setExecutionWindow(1000, TimeUnit.DAYS.toMillis(1)) .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED) .build() .schedule() } private fun sendLogs(){ val countDownLatch = CountDownLatch(1) object : Thread() { override fun run() { // do async operation here try { synchronized(AcraReportContainer.instance().lock) { while (AcraReportContainer.instance().reports.size > 0) { val report = AcraReportContainer.instance().reports[0] ru.slartus.http.Http.instance.performPost(report.url, report.params) AcraReportContainer.instance().reports.removeAt(0) } } } catch (e: Throwable) { Log.e(TAG, e.message, e) } finally { countDownLatch.countDown() } } }.start() try { countDownLatch.await() } catch (ignored: InterruptedException) { } } } override fun onRunJob(params: Params): Result { val countDownLatch = CountDownLatch(1) object : Thread() { override fun run() { // do async operation here try { synchronized(AcraReportContainer.instance().lock) { while (AcraReportContainer.instance().reports.size > 0) { val report = AcraReportContainer.instance().reports[0] ru.slartus.http.Http.instance.performPost(report.url, report.params) AcraReportContainer.instance().reports.removeAt(0) } } } catch (e: Throwable) { Log.e(TAG, e.message, e) } finally { countDownLatch.countDown() } } }.start() try { countDownLatch.await() } catch (ignored: InterruptedException) { } return Result.SUCCESS } }
apache-2.0
cc33236a15d9c671c3af9df79907a0f1
32.021505
100
0.494953
5.313149
false
false
false
false
ioc1778/incubator
incubator-events/src/main/java/com/riaektiv/akka/spices/LongEventExitActor.kt
2
1011
package com.riaektiv.akka.spices import com.riaektiv.events.LongEvent import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger /** * Coding With Passion Since 1991 * Created: 12/25/2016, 12:24 PM Eastern Time * @author Sergey Chuykov */ class LongEventExitActor : AbstractUntypedActor() { var eventsToConsume = AtomicInteger(0) var latch = CountDownLatch(1) override fun onReceive(msg: Any?) { when (msg) { is LongEvent -> { log(msg) if (eventsToConsume.decrementAndGet().toLong() == 0L) { latch.countDown() } } is OneToThreePipelineTicket -> { val ticket = msg eventsToConsume.set(ticket.eventsToConsume) latch = ticket.latch ticket.driver.tell(ActorState.Ready(), self()) } else -> { unhandled(msg) } } } }
bsd-3-clause
21b9d6cf0bd2be256ea9e267e3d6a926
22
71
0.557864
4.554054
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_indirect_parameters.kt
1
4384
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_indirect_parameters = "ARBIndirectParameters".nativeClassGL("ARB_indirect_parameters", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. OpenGL 4.3 (with the introduction of the ${ARB_multi_draw_indirect.link} extension) enhanced the ability of OpenGL to allow a large sets of parameters for indirect draws (introduced with OpenGL 4.0) into a buffer object and dispatch the entire list with one API call. This allows, for example, a shader (such as a compute shader via shader storage buffers, or a geometry shader via transform feedback) to produce lists of draw commands that can then be consumed by OpenGL without a server-client round trip. However, when a variable and potentially unknown number of draws are produced by such a shader, it becomes difficult to know how many draws are in the output array(s). Applications must resort to techniques such as transform feedback primitive queries, or mapping buffers containing the content of atomic counters, which can cause stalls or bubbles in the OpenGL pipeline. This extension introduces the concept of the "parameter buffer", which is a target allowing buffers to store parameters for certain drawing commands. Also in this extension, new variants of GL43#MultiDrawArraysIndirect() and GL43#MultiDrawElementsIndirect() are introduced that source some of their parameters from this buffer. Further commands could potentially be introduced that source other parameters from a buffer. Requires ${GL42.core}. """ IntConstant( """ Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv, MapBufferRange, FlushMappedBufferRange, GetBufferParameteriv, and CopyBufferSubData. """, "PARAMETER_BUFFER_ARB"..0x80EE ) IntConstant( "Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.", "PARAMETER_BUFFER_BINDING_ARB"..0x80EF ) var src = GL43["MultiDrawArraysIndirect"] void( "MultiDrawArraysIndirectCountARB", """ Behaves similarly to GL43#MultiDrawArraysIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER_ARB binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, an implementation stop processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], Check("maxdrawcount * (stride == 0 ? (4 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..DRAW_INDIRECT_BUFFER..const..void_p.IN("indirect", "an array of structures containing the draw parameters"), GLintptr.IN("drawcount", "the offset into the parameter buffer object"), GLsizei.IN("maxdrawcount", "the maximum number of draws"), src["stride"] ) src = GL43["MultiDrawElementsIndirect"] void( "MultiDrawElementsIndirectCountARB", """ Behaves similarly to GL43#MultiDrawElementsIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER_ARB binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, an implementation stop processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], src["type"], Check("maxdrawcount * (stride == 0 ? (5 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..DRAW_INDIRECT_BUFFER..const..void_p.IN("indirect", "a structure containing an array of draw parameters"), GLintptr.IN("drawcount", "the offset into the parameter buffer object"), GLsizei.IN("maxdrawcount", "the maximum number of draws"), src["stride"] ) }
bsd-3-clause
f4203ae4b75e4f62b64e41f15522fffb
52.47561
154
0.759352
4.131951
false
false
false
false
WonderBeat/vasilich
src/main/kotlin/com/vasilich/system/FileSystem.kt
1
1121
package com.vasilich.system import java.nio.file.FileStore import java.nio.file.FileSystems import java.util.ArrayList /** * * @author Ilya_Mestnikov */ enum class Size (val k: Long) { Kb : Size(1024) Mb : Size(Size.Kb.k * 1000) Gb : Size(Size.Mb.k * 1000) fun get(value: Long): Long { return value / k } } public class Disk(val fs : FileStore) { val name : String get() = fs.name()!! val total : Long get() = fs.getTotalSpace() val available : Long get() = fs.getTotalSpace() - fs.getUnallocatedSpace() val used : Long get() = fs.getUsableSpace() /*fun name: String { if (SystemUtils.IS_OS_WINDOWS) { return name!!.split("\\s").filter { it.matches("^\\([A-Z]:\\)$") }.first as String } }*/ } public class FileSystem { val disks: ArrayList<Disk>; { val fs = FileSystems.getDefault()!! val stores = fs.getFileStores()!! disks = ArrayList() for (store in stores) { val disk = Disk(store) disks.add(disk) } } }
gpl-2.0
7e2d1b93010570ea8cbf0b7075b73bc7
19.035714
57
0.548617
3.592949
false
false
false
false
trife/Field-Book
app/src/main/java/com/fieldbook/tracker/location/gnss/ConnectedThread.kt
1
1993
package com.fieldbook.tracker.location.gnss import android.bluetooth.BluetoothSocket import android.os.Handler import android.util.Log import java.io.IOException import java.io.InputStream /** * Thread implementation that reads strings with \r\n ending. * Takes a bluetooth socket, created in ConnectThread and a handler used to broadcast messages. */ class ConnectedThread constructor(private val socket: BluetoothSocket, val handler: Handler): Thread() { private lateinit var mmInStream: InputStream private lateinit var mmBuffer: ByteArray private companion object { const val TAG = "ConnectedThread" } //initialize input stream to read bytes from init { try { mmInStream = socket.inputStream } catch (e: IOException) { e.printStackTrace() } } override fun run() { mmBuffer = ByteArray(256) var bytes = 0 while (socket.isConnected) try { mmBuffer[bytes] = mmInStream.read().toByte() //check if the buffer has a line end, send the message if (bytes > 1 && String(mmBuffer, 0, bytes-1).endsWith("\r\n")) { val msg = String(mmBuffer, 0, bytes-1) val readMsg = handler.obtainMessage( GNSSResponseReceiver.MESSAGE_OUTPUT_CODE, bytes, -1, msg) readMsg.sendToTarget() bytes = 0 } else bytes++ } catch (e: IOException) { e.printStackTrace() //if the thread is a daemon and still reading messages, cancel the thread if ("socket closed" in e.message ?: String()) { cancel() } } } // Closes the client socket and causes the thread to finish. fun cancel() = try { mmInStream.close() socket.close() } catch (e: IOException) { Log.e(TAG, "Could not close the client socket", e) } }
gpl-2.0
1b2c15033bd1ad562ae02b44b97865e5
24.564103
104
0.592574
4.602771
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCompAttrConstructorPsiImpl.kt
1
1981
/* * Copyright (C) 2016, 2020-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmElementNode import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyAtomicType import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathExpr import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryCompAttrConstructor class XQueryCompAttrConstructorPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XQueryCompAttrConstructor { // region XpmExpression override val expressionElement: PsiElement? = null // endregion // region XdmAttributeNode override val nodeName: XsQNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull() override val parentNode: XdmNode? get() = when (val parent = parent) { is XdmElementNode -> parent is XPathExpr -> parent.parent as? XdmElementNode else -> null } override val stringValue: String? get() = null override val typedValue: XsAnyAtomicType? get() = null // endregion }
apache-2.0
3a9ee5df21340f69dbe453717d0feab3
35.685185
111
0.744573
4.188161
false
false
false
false
treelzebub/SweepingCircleProgressView
lib/src/main/java/net/treelzebub/sweepingcircleprogressview/SweepingCircleProgressView.kt
1
10913
package net.treelzebub.sweepingcircleprogressview import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.ValueAnimator 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.DecelerateInterpolator import android.view.animation.LinearInterpolator /** * Created by Tre Murillo on 12/21/16 */ class SweepingCircleProgressView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : EquilateralView(context, attrs, defStyle) { private val INDETERMINANT_MIN_SWEEP = 15f private val ANIM_DUR = 4000L private val ANIM_SWEEP_DUR = 5000L private val ANIM_SYNC_DUR = 500L private val ANIM_STEPS = 3 private val INIT_ANGLE = 0f interface Listener { fun onModeChanged(isIndeterminate: Boolean) {} fun onAnimationReset() {} fun onProgressUpdate(progress: Float) {} fun onProgressEnd(progress: Float) {} } private val paint: Paint private var size = 0 private val bounds: RectF private val thickness: Float private val color: Int private var currentProgress: Float private val maxProgress: Float private val autostartAnimation: Boolean private var indeterminateSweep = 0f private var indeterminateRotateOffset = 0f private var startAngle = 0f private var actualProgress = 0f private var startAngleRotate: ValueAnimator? = null private var progressAnimator: ValueAnimator? = null private var indeterminateAnimator: AnimatorSet? = null private val listeners = mutableListOf<Listener>() var isIndeterminate: Boolean = false set(value) { val reset = field == value field = value if (reset) { resetAnimation() } else { listeners.forEach { it.onModeChanged(isIndeterminate) } } } var progress: Float @Synchronized get() = currentProgress @Synchronized set(value) { this.currentProgress = value if (!isIndeterminate) { if (progressAnimator?.isRunning.orFalse()) progressAnimator!!.cancel() progressAnimator = ValueAnimator.ofFloat(actualProgress, currentProgress) progressAnimator!!.duration = ANIM_SYNC_DUR progressAnimator!!.interpolator = LinearInterpolator() progressAnimator!!.addUpdateListener { actualProgress = it.animatedValue as Float invalidate() } progressAnimator!!.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { listeners.forEach { it.onProgressEnd(currentProgress) } } }) progressAnimator!!.start() } invalidate() listeners.forEach { it.onProgressUpdate(currentProgress) } } init { val styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.SweepingCircleProgressView, defStyle, 0) color = styledAttrs.getColor(R.styleable.SweepingCircleProgressView_progressColor, Color.BLACK) currentProgress = styledAttrs.getFloat(R.styleable.SweepingCircleProgressView_progress, 0f) maxProgress = styledAttrs.getFloat(R.styleable.SweepingCircleProgressView_maxProgress, 100f) thickness = styledAttrs.getDimension(R.styleable.SweepingCircleProgressView_stroke, 8f) isIndeterminate = styledAttrs.getBoolean(R.styleable.SweepingCircleProgressView_isIndeterminate, false) autostartAnimation = styledAttrs.getBoolean(R.styleable.SweepingCircleProgressView_autostart, isIndeterminate) styledAttrs.recycle() paint = Paint(Paint.ANTI_ALIAS_FLAG) updatePaint() bounds = RectF() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val xPad = paddingLeft + paddingRight val yPad = paddingTop + paddingBottom val width = measuredWidth - xPad val height = measuredHeight - yPad size = if (width < height) width else height setMeasuredDimension(size + xPad, size + yPad) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) size = if (w < h) w else h updateBounds() } private fun updateBounds() { val _paddingLeft = paddingLeft val _paddingTop = paddingTop bounds.set(_paddingLeft + thickness, _paddingTop + thickness, size - _paddingLeft - thickness, size - _paddingTop - thickness) } private fun updatePaint() { paint.color = color paint.style = Paint.Style.STROKE paint.strokeWidth = thickness paint.strokeCap = Paint.Cap.ROUND } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val sweepAngle = actualProgress / maxProgress * 360 if (isIndeterminate) { canvas.drawArc(bounds, startAngle + indeterminateRotateOffset, indeterminateSweep, false, paint) } else { canvas.drawArc(bounds, startAngle, sweepAngle, false, paint) } } fun listen(listener: Listener) = listeners.add(listener) fun unlisten(listener: Listener) = listeners.remove(listener) fun startAnimation() = resetAnimation() fun resetAnimation() { if (startAngleRotate?.isRunning.orFalse()) startAngleRotate!!.cancel() if (progressAnimator?.isRunning.orFalse()) progressAnimator!!.cancel() if (indeterminateAnimator?.isRunning.orFalse()) indeterminateAnimator!!.cancel() if (isIndeterminate) { indeterminateSweep = INDETERMINANT_MIN_SWEEP indeterminateAnimator = AnimatorSet() var prevSet: AnimatorSet? = null var nextSet: AnimatorSet for (k in 0..ANIM_STEPS - 1) { nextSet = createIndeterminateAnimator(k.toFloat()) val builder = indeterminateAnimator!!.play(nextSet) if (prevSet != null) builder.after(prevSet) prevSet = nextSet } // Infinitely loop indeterminateAnimator!!.addListener(object : AnimatorListenerAdapter() { private var cancelled = false override fun onAnimationCancel(animation: Animator) { cancelled = true } override fun onAnimationEnd(animation: Animator) { if (!cancelled) resetAnimation() } }) indeterminateAnimator!!.start() listeners.forEach { it.onAnimationReset() } } else { startAngle = INIT_ANGLE startAngleRotate = ValueAnimator.ofFloat(startAngle, startAngle + 360) startAngleRotate!!.duration = ANIM_SWEEP_DUR startAngleRotate!!.interpolator = DecelerateInterpolator(2f) startAngleRotate!!.addUpdateListener { startAngle = it.animatedValue as Float invalidate() } startAngleRotate!!.start() actualProgress = 0f progressAnimator = ValueAnimator.ofFloat(actualProgress, currentProgress) progressAnimator!!.duration = ANIM_SYNC_DUR progressAnimator!!.interpolator = LinearInterpolator() progressAnimator!!.addUpdateListener { actualProgress = it.animatedValue as Float invalidate() } progressAnimator!!.start() } } fun stopAnimation() { startAngleRotate?.cancel() startAngleRotate = null progressAnimator?.cancel() progressAnimator = null indeterminateAnimator?.cancel() indeterminateAnimator = null } private fun createIndeterminateAnimator(step: Float): AnimatorSet { val maxSweep = 360f * (ANIM_STEPS - 1) / ANIM_STEPS + INDETERMINANT_MIN_SWEEP val start = -90f + step * (maxSweep - INDETERMINANT_MIN_SWEEP) // Sweep the front of the arc... pew! pew! pew! val frontEndExtend = ValueAnimator.ofFloat(INDETERMINANT_MIN_SWEEP, maxSweep) frontEndExtend.duration = ANIM_DUR / ANIM_STEPS / 2 frontEndExtend.interpolator = DecelerateInterpolator(1f) frontEndExtend.addUpdateListener { indeterminateSweep = it.animatedValue as Float invalidate() } val rotateAnimator1 = ValueAnimator.ofFloat(step * 720f / ANIM_STEPS, (step + .5f) * 720f / ANIM_STEPS) rotateAnimator1.duration = ANIM_DUR / ANIM_STEPS / 2 rotateAnimator1.interpolator = LinearInterpolator() rotateAnimator1.addUpdateListener { indeterminateRotateOffset = it.animatedValue as Float } // Retract the back end of the arc val backEndRetract = ValueAnimator.ofFloat(start, start + maxSweep - INDETERMINANT_MIN_SWEEP) backEndRetract.duration = ANIM_DUR / ANIM_STEPS / 2 backEndRetract.interpolator = DecelerateInterpolator(1f) backEndRetract.addUpdateListener { startAngle = it.animatedValue as Float indeterminateSweep = maxSweep - startAngle + start invalidate() } val rotateAnimator2 = ValueAnimator.ofFloat((step + .5f) * 720f / ANIM_STEPS, (step + 1) * 720f / ANIM_STEPS) rotateAnimator2.duration = ANIM_DUR / ANIM_STEPS / 2 rotateAnimator2.interpolator = LinearInterpolator() rotateAnimator2.addUpdateListener { indeterminateRotateOffset = it.animatedValue as Float } val set = AnimatorSet() set.play(frontEndExtend).with(rotateAnimator1) set.play(backEndRetract).with(rotateAnimator2).after(rotateAnimator1) return set } override fun onAttachedToWindow() { super.onAttachedToWindow() if (autostartAnimation) startAnimation() } override fun onDetachedFromWindow() { super.onDetachedFromWindow() stopAnimation() } override fun setVisibility(visibility: Int) { val currentVisibility = getVisibility() super.setVisibility(visibility) if (visibility != currentVisibility) { if (visibility == View.VISIBLE) { resetAnimation() } else if (visibility == View.GONE || visibility == View.INVISIBLE) { stopAnimation() } } } }
mit
a1115c94ef6f505b64ff454f6d6a2668
37.839858
134
0.640429
5.08054
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/VariableManager.kt
1
5790
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.llvm import llvm.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.name.Name internal class VariableManager(val functionGenerationContext: FunctionGenerationContext) { internal interface Record { fun load() : LLVMValueRef fun store(value: LLVMValueRef) fun address() : LLVMValueRef } inner class SlotRecord(val address: LLVMValueRef, val refSlot: Boolean, val isVar: Boolean) : Record { override fun load() : LLVMValueRef = functionGenerationContext.loadSlot(address, isVar) override fun store(value: LLVMValueRef) = functionGenerationContext.storeAnyLocal(value, address) override fun address() : LLVMValueRef = this.address override fun toString() = (if (refSlot) "refslot" else "slot") + " for ${address}" } class ValueRecord(val value: LLVMValueRef, val name: Name) : Record { override fun load() : LLVMValueRef = value override fun store(value: LLVMValueRef) = throw Error("writing to immutable: ${name}") override fun address() : LLVMValueRef = throw Error("no address for: ${name}") override fun toString() = "value of ${value} from ${name}" } val variables: ArrayList<Record> = arrayListOf() val contextVariablesToIndex: HashMap<ValueDescriptor, Int> = hashMapOf() // Clears inner state of variable manager. fun clear() { variables.clear() contextVariablesToIndex.clear() } fun createVariable(descriptor: VariableDescriptor, value: LLVMValueRef? = null, variableLocation: VariableDebugLocation?) : Int { // Note that we always create slot for object references for memory management. if (!descriptor.isVar && value != null) return createImmutable(descriptor, value) else // Unfortunately, we have to create mutable slots here, // as even vals can be assigned on multiple paths. However, we use varness // knowledge, as anonymous slots are created only for true vars (for vals // their single assigner already have slot). return createMutable(descriptor, descriptor.isVar, value, variableLocation) } fun createMutable(descriptor: VariableDescriptor, isVar: Boolean, value: LLVMValueRef? = null, variableLocation: VariableDebugLocation?) : Int { assert(!contextVariablesToIndex.contains(descriptor)) val index = variables.size val type = functionGenerationContext.getLLVMType(descriptor.type) val slot = functionGenerationContext.alloca(type, descriptor.name.asString(), variableLocation) if (value != null) functionGenerationContext.storeAnyLocal(value, slot) variables.add(SlotRecord(slot, functionGenerationContext.isObjectType(type), isVar)) contextVariablesToIndex[descriptor] = index return index } // Creates anonymous mutable variable. // Think of slot reuse. fun createAnonymousSlot(value: LLVMValueRef? = null) : LLVMValueRef { val index = createAnonymousMutable(functionGenerationContext.kObjHeaderPtr, value) return addressOf(index) } private fun createAnonymousMutable(type: LLVMTypeRef, value: LLVMValueRef? = null) : Int { val index = variables.size val slot = functionGenerationContext.alloca(type, variableLocation = null) if (value != null) functionGenerationContext.storeAnyLocal(value, slot) variables.add(SlotRecord(slot, functionGenerationContext.isObjectType(type), true)) return index } fun createImmutable(descriptor: ValueDescriptor, value: LLVMValueRef) : Int { if (contextVariablesToIndex.containsKey(descriptor)) throw Error("$descriptor is already defined") val index = variables.size variables.add(ValueRecord(value, descriptor.name)) contextVariablesToIndex[descriptor] = index return index } fun indexOf(descriptor: ValueDescriptor) : Int { return contextVariablesToIndex.getOrElse(descriptor) { -1 } } fun addressOf(index: Int): LLVMValueRef { return variables[index].address() } fun load(index: Int): LLVMValueRef { return variables[index].load() } fun store(value: LLVMValueRef, index: Int) { variables[index].store(value) } fun debugInfoLocalVariableLocation(functionScope: DIScopeOpaqueRef, diType: DITypeOpaqueRef, name:Name, file: DIFileRef, line: Int, location: DILocationRef?):VariableDebugLocation { val variableDeclaration = DICreateAutoVariable( builder = functionGenerationContext.context.debugInfo.builder, scope = functionScope, name = name.asString(), file = file, line = line, type = diType) return VariableDebugLocation(localVariable = variableDeclaration!!, location = location, file = file, line = line) } } internal data class VariableDebugLocation(val localVariable: DILocalVariableRef, val location:DILocationRef?, val file:DIFileRef, val line:Int)
apache-2.0
a91e5455fa351c1c2d9db2d68593bc79
42.541353
185
0.691537
4.730392
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/in_app_web_view/ui/activity/InAppWebViewActivity.kt
2
1662
package org.stepik.android.view.in_app_web_view.ui.activity import android.content.Context import android.content.Intent import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.R import org.stepic.droid.base.SingleFragmentActivity import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment class InAppWebViewActivity : SingleFragmentActivity() { companion object { private val REVIEW_SESSIONS_PATTERN = "/review/sessions".toRegex() private const val EXTRA_TITLE = "title" private const val EXTRA_URL = "url" fun createIntent(context: Context, title: String, url: String): Intent = Intent(context, InAppWebViewActivity::class.java) .putExtra(EXTRA_TITLE, title) .putExtra(EXTRA_URL, url) } override fun createFragment(): Fragment { val intentDataString = intent.dataString.orEmpty() val (title, url) = when { REVIEW_SESSIONS_PATTERN.containsMatchIn(intentDataString) -> getString(R.string.step_quiz_review_given_title) to intentDataString else -> intent.getStringExtra(EXTRA_TITLE).orEmpty() to intent.getStringExtra(EXTRA_URL).orEmpty() } return InAppWebViewDialogFragment.newInstance( title = title, url = url, isProvideAuth = true ) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } }
apache-2.0
65689af64d1265790666ab9c3f95a08d
32.938776
106
0.66065
4.52861
false
false
false
false
JesseScott/Make-A-Wish
MakeAWish/app/src/main/java/tt/co/jesses/makeawish/MainActivity.kt
1
1848
package tt.co.jesses.makeawish import android.content.Intent import android.os.Bundle import android.support.design.widget.FloatingActionButton import android.support.v7.app.AppCompatActivity import android.support.v7.widget.RecyclerView import android.util.Log import android.view.Menu import android.view.MenuItem import com.google.firebase.analytics.FirebaseAnalytics import tt.co.jesses.makeawish.helpers.AlarmHelper class MainActivity : AppCompatActivity() { private var recyclerView: RecyclerView? = null private var floatingActionButton: FloatingActionButton? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) recyclerView = findViewById(R.id.main_rv) as RecyclerView floatingActionButton = findViewById(R.id.main_fab) as FloatingActionButton floatingActionButton!!.setOnClickListener { Log.d(TAG, "FAB") } FirebaseAnalytics.getInstance(this.applicationContext).setCurrentScreen(this@MainActivity, "MainActivity", MainActivity::class.java.simpleName) val alarmHelper = AlarmHelper(applicationContext) alarmHelper.setAlarms() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_settings -> { Log.d(TAG, "Settings selected") val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) return true } else -> return super.onOptionsItemSelected(item) } } companion object { private val TAG = MainActivity::class.java.simpleName } }
gpl-2.0
9e1492ff7a6c09939bddd859403e1f63
32
151
0.708333
4.8125
false
false
false
false
enihsyou/Sorting-algorithm
Java_part/Assigment9/src/Q1.kt
1
1889
import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.RepeatedTest import java.util.* import java.util.Collections.swap import kotlin.test.assertEquals /** * 1)分治算法求n个数的数组中找出第二个最大元素 */ fun main(args: Array<String>) { Scanner(System.`in`).use { s -> println("输入数组数字,以非数字结束") val list = ArrayList<Long>() while (s.hasNextLong()) list.add(s.nextLong()) println(list.findKthLargest(2)) } } fun <T : Comparable<T>> MutableList<T>.findKthLargest(k: Int): T { val n = this.size if (k > n || k < 0) throw IllegalArgumentException("没有这种操作") return quickSelect(this, 0, n - 1, k - 1) } fun <T : Comparable<T>> quickSelect(list: MutableList<T>, _left: Int, _right: Int, k: Int): T { var left = _left var right = _right while (left <= right) { if (left == right) return list[left] var pivotIndex = (left + right) / 2 pivotIndex = partition(list, left, right, pivotIndex) when { k == pivotIndex -> return list[k] k < pivotIndex -> right = pivotIndex - 1 k > pivotIndex -> left = pivotIndex + 1 } } throw RuntimeException(String.format("%d %d", left, right)) } fun <T : Comparable<T>> partition(list: MutableList<T>, left: Int, right: Int, pivotIndex: Int): Int { val pivot = list[pivotIndex] swap(list, pivotIndex, right) var index = left for (i in left until right) { if (list[i] > pivot) { // 下降序排列 swap(list, index, i) index++ } } swap(list, right, index) return index } class Q1KtTest { @DisplayName("╯°□°)╯") @RepeatedTest(5) fun findKthLargest() { val random = Random() val list = LongArray(1000000, { random.nextLong() }) assertEquals( list.sortedArrayDescending()[1], list.toMutableList().findKthLargest(2)) } }
mit
25eb0828e2d69abca4c2661b90965048
24.927536
102
0.631638
3.149648
false
true
false
false
apollostack/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo3/internal/interceptor/ApolloCacheInterceptor.kt
1
7327
package com.apollographql.apollo3.internal.interceptor import com.apollographql.apollo3.ApolloCall import com.apollographql.apollo3.api.Operation import com.apollographql.apollo3.api.ApolloResponse import com.apollographql.apollo3.api.ResponseAdapterCache import com.apollographql.apollo3.api.internal.ApolloLogger import com.apollographql.apollo3.cache.ApolloCacheHeaders import com.apollographql.apollo3.cache.normalized.ApolloStore import com.apollographql.apollo3.cache.normalized.internal.ReadMode import com.apollographql.apollo3.cache.normalized.internal.RealApolloStore import com.apollographql.apollo3.exception.ApolloException import com.apollographql.apollo3.exception.ApolloGenericException import com.apollographql.apollo3.interceptor.ApolloInterceptor import com.apollographql.apollo3.interceptor.ApolloInterceptor.CallBack import com.apollographql.apollo3.interceptor.ApolloInterceptor.FetchSourceType import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorRequest import com.apollographql.apollo3.interceptor.ApolloInterceptor.InterceptorResponse import com.apollographql.apollo3.interceptor.ApolloInterceptorChain import com.apollographql.apollo3.withCacheInfo import com.benasher44.uuid.uuid4 import java.lang.Runnable import java.util.concurrent.Executor import java.util.concurrent.atomic.AtomicReference import kotlinx.coroutines.runBlocking /** * ApolloCacheInterceptor is a concrete [ApolloInterceptor] responsible for serving requests from the normalized * cache if [InterceptorRequest.fetchFromCache] is true. Saves all network responses to cache. */ class ApolloCacheInterceptor<D : Operation.Data>( val apolloStore: ApolloStore, private val dispatcher: Executor, val logger: ApolloLogger, private val responseCallback: AtomicReference<ApolloCall.Callback<D>?>, private val writeToCacheAsynchronously: Boolean, private val responseAdapterCache: ResponseAdapterCache ) : ApolloInterceptor { @Volatile var disposed = false override fun interceptAsync(request: InterceptorRequest, chain: ApolloInterceptorChain, dispatcher: Executor, callBack: CallBack) { dispatcher.execute(Runnable { if (disposed) return@Runnable if (request.fetchFromCache) { callBack.onFetch(FetchSourceType.CACHE) val cachedResponse: InterceptorResponse try { cachedResponse = resolveFromCache(request) callBack.onResponse(cachedResponse) callBack.onCompleted() } catch (e: ApolloException) { callBack.onFailure(e) } } else { writeOptimisticUpdatesAndPublish(request) chain.proceedAsync(request, dispatcher, object : CallBack { override fun onResponse(response: InterceptorResponse) { if (disposed) return cacheResponseAndPublish(request, response, writeToCacheAsynchronously) callBack.onResponse(response) callBack.onCompleted() } override fun onFailure(e: ApolloException) { rollbackOptimisticUpdates(request, true) callBack.onFailure(e) } override fun onCompleted() { // call onCompleted in onResponse } override fun onFetch(sourceType: FetchSourceType) { callBack.onFetch(sourceType) } }) } }) } override fun dispose() { disposed = true } @Throws(ApolloException::class) fun resolveFromCache(request: InterceptorRequest): InterceptorResponse { val data = runBlocking { apolloStore.readOperation( operation = request.operation, cacheHeaders = request.cacheHeaders, responseAdapterCache = responseAdapterCache, mode = ReadMode.BATCH ) } if (data != null) { logger.d("Cache HIT for operation %s", request.operation.name()) return InterceptorResponse( null, ApolloResponse( requestUuid = uuid4(), operation = request.operation, data = data, ).withCacheInfo(true) ) } logger.d("Cache MISS for operation %s", request.operation.name()) throw ApolloGenericException(String.format("Cache miss for operation %s", request.operation.name())) } private fun cacheResponse( networkResponse: InterceptorResponse, request: InterceptorRequest ): Set<String> { if (networkResponse.parsedResponse.isPresent && networkResponse.parsedResponse.get()!!.hasErrors() && !request.cacheHeaders.hasHeader(ApolloCacheHeaders.STORE_PARTIAL_RESPONSES)) { return emptySet() } val data = networkResponse.parsedResponse.get()!!.data return if (data != null && apolloStore is RealApolloStore) { val (records, changedKeys) = runBlocking { apolloStore.writeOperationWithRecords( request.operation as Operation<Operation.Data>, data, request.cacheHeaders, false, // don't publish here, it's done later responseAdapterCache ) } responseCallback.get()?.onCached(records.toList()) changedKeys } else { emptySet() } } fun cacheResponseAndPublish(request: InterceptorRequest, networkResponse: InterceptorResponse, async: Boolean) { if (async) { dispatcher.execute { cacheResponseAndPublishSynchronously(request, networkResponse) } } else { cacheResponseAndPublishSynchronously(request, networkResponse) } } private fun cacheResponseAndPublishSynchronously(request: InterceptorRequest, networkResponse: InterceptorResponse) { try { val networkResponseCacheKeys = cacheResponse(networkResponse, request) val rolledBackCacheKeys = rollbackOptimisticUpdates(request, false) publishCacheKeys(rolledBackCacheKeys + networkResponseCacheKeys) } catch (rethrow: Exception) { rollbackOptimisticUpdates(request, true) throw rethrow } } private fun writeOptimisticUpdatesAndPublish(request: InterceptorRequest) { dispatcher.execute { try { if (request.optimisticUpdates.isPresent) { val optimisticUpdates = request.optimisticUpdates.get() runBlocking { apolloStore.writeOptimisticUpdates( request.operation as Operation<Operation.Data>, optimisticUpdates, request.uniqueId, responseAdapterCache, true, ) } } } catch (e: Exception) { logger.e(e, "failed to write operation optimistic updates, for: %s", request.operation) } } } fun rollbackOptimisticUpdates(request: InterceptorRequest, publish: Boolean): Set<String> { return try { runBlocking { apolloStore.rollbackOptimisticUpdates(request.uniqueId, publish) } } catch (e: Exception) { logger.e(e, "failed to rollback operation optimistic updates, for: %s", request.operation) emptySet() } } fun publishCacheKeys(cacheKeys: Set<String>?) { dispatcher.execute { try { runBlocking { apolloStore.publish(cacheKeys!!) } } catch (e: Exception) { logger.e(e, "Failed to publish cache changes") } } } }
mit
b66e5637c78597f789d84fbd33762095
35.093596
119
0.69742
4.914152
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpUTCAndTimeZone.kt
1
1707
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption import org.joda.time.DateTime import org.joda.time.DateTimeZone class DanaRSPacketOptionSetPumpUTCAndTimeZone( injector: HasAndroidInjector, private var time: Long = 0, private var zoneOffset: Int = 0 ) : DanaRSPacket(injector) { var error = 0 init { opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_UTC_AND_TIME_ZONE aapsLogger.debug(LTag.PUMPCOMM, "Setting UTC pump time ${dateUtil.dateAndTimeAndSecondsString(time)} ZoneOffset: $zoneOffset") } override fun getRequestParams(): ByteArray { val date = DateTime(time).withZone(DateTimeZone.UTC) val request = ByteArray(7) request[0] = (date.year - 2000 and 0xff).toByte() request[1] = (date.monthOfYear and 0xff).toByte() request[2] = (date.dayOfMonth and 0xff).toByte() request[3] = (date.hourOfDay and 0xff).toByte() request[4] = (date.minuteOfHour and 0xff).toByte() request[5] = (date.secondOfMinute and 0xff).toByte() request[6] = zoneOffset.toByte() return request } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override val friendlyName: String = "OPTION__SET_PUMP_UTC_AND_TIMEZONE" }
agpl-3.0
7c96cf4ad438bd89d710b4833d129e77
34.583333
134
0.667838
4.183824
false
false
false
false
hotpodata/common
src/main/java/com/hotpodata/common/utils/HashUtils.kt
1
792
package com.hotpodata.common.utils import timber.log.Timber import java.security.MessageDigest /** * Created by jdrotos on 1/15/16. */ object HashUtils { fun md5(s: String): String { try { var digest = MessageDigest.getInstance("MD5") digest.update(s.toByteArray()) var messageDigest = digest.digest() var hexString = StringBuffer() for (i in messageDigest.indices) { var h = Integer.toHexString(0xFF and messageDigest[i].toInt()) while (h.length < 2) h = "0" + h hexString.append(h) } return hexString.toString() } catch(ex: Exception) { Timber.e(ex, "Fail in md5"); } return "" } }
apache-2.0
1154b7d626215c07125cbfeed36bab73
26.344828
78
0.534091
4.327869
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/NotificationResponse.kt
1
837
package io.github.feelfreelinux.wykopmobilny.models.pojo import com.squareup.moshi.Json data class NotificationResponse( @Json(name = "author") val author : String?, @Json(name = "author_avatar") val authorAvatar : String, @Json(name = "author_avatar_med") val authorAvatarMed : String, @Json(name = "author_avatar_lo") val authorAvatarLo : String, @Json(name = "author_group") val authorGroup : Int, @Json(name = "author_sex") val authorSex : String, @Json(name = "date") val date : String, @Json(name = "type") val type : String, @Json(name = "body") val body : String, @Json(name = "url") val url : String, @Json(name = "new") val new : Boolean )
mit
b1cf7e792ff6572a8afdea8c66b4638e
21.052632
56
0.549582
3.893023
false
false
false
false
bajdcc/jMiniLang
src/main/kotlin/com/bajdcc/LALR1/grammar/tree/ExpCycleCtrl.kt
1
1299
package com.bajdcc.LALR1.grammar.tree import com.bajdcc.LALR1.grammar.codegen.ICodegen import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder import com.bajdcc.LALR1.grammar.tree.closure.IClosureScope import com.bajdcc.util.lexer.token.KeywordType import com.bajdcc.util.lexer.token.Token /** * 【语义分析】循环控制表达式 * * @author bajdcc */ class ExpCycleCtrl : IExp { /** * 变量名 */ var name: Token? = null override fun isConstant(): Boolean { return false } override fun isEnumerable(): Boolean { return false } override fun simplify(recorder: ISemanticRecorder): IExp { return this } override fun analysis(recorder: ISemanticRecorder) { } override fun genCode(codegen: ICodegen) { val keyword = name!!.obj as KeywordType? if (keyword === KeywordType.BREAK) { codegen.blockService.genBreak() } else { codegen.blockService.genContinue() } } override fun toString(): String { return print(StringBuilder()) } override fun print(prefix: StringBuilder): String { return name!!.toRealString() } override fun addClosure(scope: IClosureScope) { } override fun setYield() { } }
mit
f0eb7316246d2db62edb8a7717faeb75
19.786885
62
0.643252
4.127036
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/transformers/BERTLayer.kt
1
6649
/* Copyright 2020-present Simone Cangialosi. All Rights Reserved. * * 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 com.kotlinnlp.simplednn.deeplearning.transformers import com.kotlinnlp.simplednn.core.arrays.AugmentedArray import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor import com.kotlinnlp.simplednn.core.neuralprocessor.batchfeedforward.BatchFeedforwardProcessor import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsAccumulator import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList import com.kotlinnlp.simplednn.deeplearning.attention.multihead.MultiHeadAttentionNetwork import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray /** * A single BERT layer. * * @property params the layer parameters * @property propagateToInput whether to propagate the errors to the input during the [backward] * @property id a unique ID */ internal class BERTLayer( val params: BERTParameters, override val propagateToInput: Boolean = false, override val id: Int = 0 ) : NeuralProcessor< List<DenseNDArray>, // InputType List<DenseNDArray>, // OutputType List<DenseNDArray>, // ErrorsType List<DenseNDArray> // InputErrorsType > { /** * The errors accumulator. */ private val errorsAccumulator = ParamsErrorsAccumulator() /** * The input sequence. */ private lateinit var inputSequence: List<AugmentedArray<DenseNDArray>> /** * The multi-head scaled-dot attention network. */ private val multiHeadAttention = MultiHeadAttentionNetwork(model = this.params.attention, propagateToInput = this.propagateToInput) /** * The multi-head norm batch processor. */ private val multiHeadNorm: BatchFeedforwardProcessor<DenseNDArray> = BatchFeedforwardProcessor(model = this.params.multiHeadNorm, propagateToInput = true) /** * The batch of output feed-forward processors. */ private val outputFF: BatchFeedforwardProcessor<DenseNDArray> = BatchFeedforwardProcessor(model = this.params.outputFF, propagateToInput = true) /** * The output norm batch processor. */ private val outputNorm: BatchFeedforwardProcessor<DenseNDArray> = BatchFeedforwardProcessor(model = this.params.outputNorm, propagateToInput = true) /** * @param input the input sequence * * @return the encoded sequence */ override fun forward(input: List<DenseNDArray>): List<DenseNDArray> { this.inputSequence = input.map { AugmentedArray(it) } return this.forwardOutput(this.forwardAttention(input)) } /** * Propagate the output errors using the gradient descent algorithm. * * @param outputErrors the output errors */ override fun backward(outputErrors: List<DenseNDArray>) { this.errorsAccumulator.clear() val inputErrors: List<DenseNDArray> = this.backwardAttention(this.backwardOutput(outputErrors)) if (this.propagateToInput) this.inputSequence.zip(inputErrors).forEach { (input, errors) -> input.assignErrors(errors) } } /** * Return the params errors of the last backward. * * @param copy a Boolean indicating whether the returned errors must be a copy or a reference (default true) * * @return the parameters errors */ override fun getParamsErrors(copy: Boolean): ParamsErrorsList = this.errorsAccumulator.getParamsErrors(copy = copy) /** * Return the input errors of the last backward. * Before calling this method make sure that [propagateToInput] is enabled. * * @param copy whether to return by value or by reference (default true) * * @return the input errors */ override fun getInputErrors(copy: Boolean): List<DenseNDArray> = this.inputSequence.map { if (copy) it.errors.copy() else it.errors } /** * The attention component forward. * * @param input the input sequence * * @return the output arrays of the attention */ private fun forwardAttention(input: List<DenseNDArray>): List<DenseNDArray> { val attentionArrays: List<DenseNDArray> = this.multiHeadAttention.forward(input) return this.multiHeadNorm.forward(input.zip(attentionArrays).map { it.first.sum(it.second) }) } /** * The output component forward. * * @param attentionArrays the attention arrays * * @return the output arrays */ private fun forwardOutput(attentionArrays: List<DenseNDArray>): List<DenseNDArray> { val ffOutputs: List<DenseNDArray> = this.outputFF.forward(attentionArrays) return this.outputNorm.forward(attentionArrays.zip(ffOutputs).map { it.first.sum(it.second) }) } /** * The output component backward. * * @param outputErrors the output errors * * @return the errors of the attention arrays */ private fun backwardOutput(outputErrors: List<DenseNDArray>): List<DenseNDArray> { val normErrors: List<DenseNDArray> = this.backwardNorm(errors = outputErrors, processor = this.outputNorm) this.outputFF.backward(normErrors) this.errorsAccumulator.accumulate(this.outputFF.getParamsErrors(copy = false), copy = false) return this.outputFF.getInputErrors(copy = false).zip(normErrors).map { (inputErrors, errors) -> inputErrors.sum(errors) } } /** * The attention component backward. * * @param attentionErrors the errors of the attention arrays * * @return the layer input errors */ private fun backwardAttention(attentionErrors: List<DenseNDArray>): List<DenseNDArray> { val normErrors: List<DenseNDArray> = this.backwardNorm(errors = attentionErrors, processor = this.multiHeadNorm) this.multiHeadAttention.backward(normErrors) this.errorsAccumulator.accumulate(this.multiHeadAttention.getParamsErrors(copy = false), copy = false) return if (this.propagateToInput) this.multiHeadAttention.getInputErrors().zip(normErrors).map { it.first.assignSum(it.second) } else listOf() } /** * Execute the backward of the given norm processor. * * @param errors the output errors * @param processor the norm processor on which to call the backward * * @return the inputs errors */ private fun backwardNorm(errors: List<DenseNDArray>, processor: BatchFeedforwardProcessor<DenseNDArray>): List<DenseNDArray> = processor.let { it.backward(errors) this.errorsAccumulator.accumulate(it.getParamsErrors(copy = false)) it.getInputErrors(copy = false) } }
mpl-2.0
9ddf6f4c3920d7ffa426ec8691cfcafa
32.245
116
0.722214
4.39458
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/stats/refresh/utils/StatsDateSelector.kt
1
4549
package org.wordpress.android.ui.stats.refresh.utils import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import org.wordpress.android.fluxc.network.utils.StatsGranularity import org.wordpress.android.fluxc.network.utils.StatsGranularity.DAYS import org.wordpress.android.fluxc.network.utils.StatsGranularity.MONTHS import org.wordpress.android.fluxc.network.utils.StatsGranularity.WEEKS import org.wordpress.android.fluxc.network.utils.StatsGranularity.YEARS import org.wordpress.android.ui.stats.refresh.StatsViewModel.DateSelectorUiModel import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection import org.wordpress.android.ui.stats.refresh.lists.StatsListViewModel.StatsSection.INSIGHTS import org.wordpress.android.ui.stats.refresh.lists.sections.granular.SelectedDateProvider import org.wordpress.android.ui.stats.refresh.lists.sections.granular.SelectedDateProvider.SelectedDate import org.wordpress.android.util.perform import javax.inject.Inject class StatsDateSelector constructor( private val selectedDateProvider: SelectedDateProvider, private val statsDateFormatter: StatsDateFormatter, private val siteProvider: StatsSiteProvider, private val statsSection: StatsSection ) { private val _dateSelectorUiModel = MutableLiveData<DateSelectorUiModel>() val dateSelectorData: LiveData<DateSelectorUiModel> = _dateSelectorUiModel val selectedDate = selectedDateProvider.granularSelectedDateChanged(this.statsSection) .perform { updateDateSelector() } fun start(startDate: SelectedDate) { selectedDateProvider.updateSelectedDate(startDate, statsSection) } fun updateDateSelector() { val shouldShowDateSelection = this.statsSection != INSIGHTS val updatedDate = getDateLabelForSection() val currentState = dateSelectorData.value if (!shouldShowDateSelection && currentState?.isVisible != false) { emitValue(currentState, DateSelectorUiModel(false)) } else { val timeZone = statsDateFormatter.printTimeZone(siteProvider.siteModel) val updatedState = DateSelectorUiModel( shouldShowDateSelection, updatedDate, enableSelectPrevious = selectedDateProvider.hasPreviousDate(statsSection), enableSelectNext = selectedDateProvider.hasNextDate(statsSection), timeZone = timeZone ) emitValue(currentState, updatedState) } } private fun emitValue( currentState: DateSelectorUiModel?, updatedState: DateSelectorUiModel ) { if (currentState != updatedState) { _dateSelectorUiModel.value = updatedState } } private fun getDateLabelForSection(): String? { return statsDateFormatter.printGranularDate( selectedDateProvider.getSelectedDate(statsSection) ?: selectedDateProvider.getCurrentDate(), toStatsGranularity() ) } private fun toStatsGranularity(): StatsGranularity { return when (statsSection) { StatsSection.DETAIL, StatsSection.TOTAL_LIKES_DETAIL, StatsSection.TOTAL_COMMENTS_DETAIL, StatsSection.TOTAL_FOLLOWERS_DETAIL, StatsSection.INSIGHTS, StatsSection.INSIGHT_DETAIL, StatsSection.DAYS -> DAYS StatsSection.WEEKS -> WEEKS StatsSection.MONTHS -> MONTHS StatsSection.ANNUAL_STATS, StatsSection.YEARS -> YEARS } } fun onNextDateSelected() { selectedDateProvider.selectNextDate(statsSection) } fun onPreviousDateSelected() { selectedDateProvider.selectPreviousDate(statsSection) } fun clear() { selectedDateProvider.clear(statsSection) } fun getSelectedDate(): SelectedDate { return selectedDateProvider.getSelectedDateState(statsSection) } class Factory @Inject constructor( private val selectedDateProvider: SelectedDateProvider, private val siteProvider: StatsSiteProvider, private val statsDateFormatter: StatsDateFormatter ) { fun build(statsSection: StatsSection): StatsDateSelector { return StatsDateSelector( selectedDateProvider, statsDateFormatter, siteProvider, statsSection ) } } }
gpl-2.0
7bad3c1736390dc6f2daf113ed008c5a
36.908333
108
0.698615
5.252887
false
false
false
false
ingokegel/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/style/Properties.kt
13
1636
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.customFrameDecorations.style import java.awt.Color import java.awt.Insets import javax.swing.Icon import javax.swing.JComponent import javax.swing.border.Border class Properties { private val map = HashMap<StyleProperty, Any?>() var background: Color? set(value) = setValue(StyleProperty.BACKGROUND, value) get() = getValue(StyleProperty.BACKGROUND) as Color var isOpaque: Boolean? set(value) = setValue(StyleProperty.OPAQUE, value) get() = getValue(StyleProperty.OPAQUE) as Boolean var foreground: Color? set(value) = setValue(StyleProperty.FOREGROUND, value) get() = getValue(StyleProperty.FOREGROUND) as Color var border: Border? set(value) = setValue(StyleProperty.BORDER, value) get() = getValue(StyleProperty.BORDER) as Border var icon: Icon? set(value) = setValue(StyleProperty.ICON, value) get() = getValue(StyleProperty.ICON) as Icon var margin: Insets? set(value) = setValue(StyleProperty.MARGIN, value) get() = getValue(StyleProperty.MARGIN) as Insets fun setValue(prop: StyleProperty, value: Any?) { map[prop] = value } fun getValue(prop: StyleProperty): Any? = map[prop] fun clone(): Properties { val new = Properties() new.map +=map return new } fun updateBy(source: Properties): Properties { map += source.map return this } fun <T : JComponent> applyTo(component: T) { for ((k, v) in map) { k.apply(component, v) } } }
apache-2.0
5bc1e54d25d206af4240cbcae90a57cc
29.886792
140
0.705379
3.778291
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/HintsTypeRenderer.kt
2
15833
// 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.parameterInfo import org.jetbrains.kotlin.builtins.* import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotated import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.idea.ClassifierNamePolicyEx import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetail import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail import org.jetbrains.kotlin.idea.codeInsight.hints.TypeInlayInfoDetail import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.SpecialNames import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.renderer.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject import org.jetbrains.kotlin.resolve.descriptorUtil.parentsWithSelf import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.error.* import org.jetbrains.kotlin.types.error.ErrorUtils import org.jetbrains.kotlin.types.typeUtil.isUnresolvedType import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * copy-pasted and inspired by [DescriptorRendererImpl] * * To render any kotlin type into a sequence of short and human-readable kotlin types like * - Int * - Int? * - List<String?>? * * For each type short name and fqName is provided (see [TypeInlayInfoDetail]). */ class HintsTypeRenderer private constructor(override val options: HintsDescriptorRendererOptions) : KotlinIdeDescriptorRenderer(options) { init { check(options.isLocked) { "options have not been locked yet to prevent mutability" } check(options.textFormat == RenderingFormat.PLAIN) { "only PLAIN text format is supported" } check(!options.verbose) { "verbose mode is not supported" } check(!options.renderTypeExpansions) { "Type expansion rendering is unsupported" } } private val renderer = COMPACT_WITH_SHORT_TYPES.withOptions {} @Suppress("SuspiciousCollectionReassignment") private val functionTypeAnnotationsRenderer: HintsTypeRenderer by lazy { HintsTypeRenderer.withOptions { excludedTypeAnnotationClasses += listOf(StandardNames.FqNames.extensionFunctionType) } } private fun renderName(name: Name): String = escape(name.render()) /* TYPES RENDERING */ fun renderTypeIntoInlayInfo(type: KotlinType): List<InlayInfoDetail> { val list = mutableListOf<InlayInfoDetail>() return options.typeNormalizer.invoke(type).renderNormalizedTypeTo(list) } private fun MutableList<InlayInfoDetail>.append(text: String): MutableList<InlayInfoDetail> = apply { add(TextInlayInfoDetail(text)) } private fun MutableList<InlayInfoDetail>.append(text: String, descriptor: ClassifierDescriptor?): MutableList<InlayInfoDetail> { descriptor?.let { add(TypeInlayInfoDetail(text, it.fqNameSafe.asString())) } ?: run { append(text) } return this } private fun KotlinType.renderNormalizedTypeTo(list: MutableList<InlayInfoDetail>): MutableList<InlayInfoDetail> { this.unwrap().safeAs<AbbreviatedType>()?.let { abbreviated -> // TODO nullability is lost for abbreviated type? abbreviated.abbreviation.renderNormalizedTypeAsIsTo(list) if (options.renderUnabbreviatedType) { abbreviated.renderAbbreviatedTypeExpansionTo(list) } return list } this.renderNormalizedTypeAsIsTo(list) return list } private fun AbbreviatedType.renderAbbreviatedTypeExpansionTo(list: MutableList<InlayInfoDetail>) { list.append(" /* = ") this.expandedType.renderNormalizedTypeAsIsTo(list) list.append(" */") } private fun KotlinType.renderNormalizedTypeAsIsTo(list: MutableList<InlayInfoDetail>) { if (this is WrappedType && !this.isComputed()) { list.append("<Not computed yet>") return } when (val unwrappedType = this.unwrap()) { // KTIJ-19098: platform type (e.g. `String!`) is rendered like a plain text `String!` w/o fqName link is FlexibleType -> list.append(unwrappedType.render(renderer, options)) is SimpleType -> unwrappedType.renderSimpleTypeTo(list) } } private fun SimpleType.renderSimpleTypeTo(list: MutableList<InlayInfoDetail>) { if (this == TypeUtils.CANNOT_INFER_FUNCTION_PARAM_TYPE || TypeUtils.isDontCarePlaceholder(this)) { list.append("???") return } if (ErrorUtils.isUninferredTypeVariable(this)) { if (options.uninferredTypeParameterAsName) { list.append(renderError((this.constructor as ErrorTypeConstructor).getParam(0))) } else { list.append("???") } return } if (this.isError) { this.renderDefaultTypeTo(list) return } if (shouldRenderAsPrettyFunctionType(this)) { this.renderFunctionTypeTo(list) } else { this.renderDefaultTypeTo(list) } } private fun List<TypeProjection>.renderTypeArgumentsTo(list: MutableList<InlayInfoDetail>) { if (this.isNotEmpty()) { list.append(lt()) this.appendTypeProjectionsTo(list) list.append(gt()) } } private fun KotlinType.renderDefaultTypeTo(list: MutableList<InlayInfoDetail>) { renderAnnotationsTo(list) if (this.isError) { if (isUnresolvedType(this) && options.presentableUnresolvedTypes) { list.append(ErrorUtils.unresolvedTypeAsItIs(this)) } else { if (this is ErrorType && !options.informativeErrorType) { list.append(this.debugMessage) } else { list.append(this.constructor.toString()) // Debug name of an error type is more informative } this.arguments.renderTypeArgumentsTo(list) } } else { this.renderTypeConstructorAndArgumentsTo(list) } if (this.isMarkedNullable) { list.append("?") } if (classifierNamePolicy !is ClassifierNamePolicyEx) { if (this.isDefinitelyNotNullType) { list.append(" & Any") } } } private fun KotlinType.renderTypeConstructorAndArgumentsTo( list: MutableList<InlayInfoDetail>, typeConstructor: TypeConstructor = this.constructor ) { val possiblyInnerType = this.buildPossiblyInnerType() if (possiblyInnerType == null) { typeConstructor.renderTypeConstructorOfTypeTo(list, this) this.arguments.renderTypeArgumentsTo(list) return } possiblyInnerType.renderPossiblyInnerTypeTo(list) } private fun PossiblyInnerType.renderPossiblyInnerTypeTo(list: MutableList<InlayInfoDetail>) { this.outerType?.let { it.renderPossiblyInnerTypeTo(list) list.append(".") list.append(renderName(this.classifierDescriptor.name)) } ?: this.classifierDescriptor.typeConstructor.renderTypeConstructorTo(list) this.arguments.renderTypeArgumentsTo(list) } fun TypeConstructor.renderTypeConstructorOfTypeTo(list: MutableList<InlayInfoDetail>, type: KotlinType){ val text = when (val cd = this.declarationDescriptor) { is TypeParameterDescriptor, is ClassDescriptor, is TypeAliasDescriptor -> renderClassifierNameWithType(cd, type) null -> this.toString() else -> error("Unexpected classifier: " + cd::class.java) } list.append(text, this.declarationDescriptor) } fun TypeConstructor.renderTypeConstructorTo(list: MutableList<InlayInfoDetail>){ val text = when (val cd = this.declarationDescriptor) { is TypeParameterDescriptor, is ClassDescriptor, is TypeAliasDescriptor -> renderClassifierName(cd) null -> this.toString() else -> error("Unexpected classifier: " + cd::class.java) } list.append(text, this.declarationDescriptor) } override fun renderClassifierName(klass: ClassifierDescriptor): String = if (ErrorUtils.isError(klass)) { klass.typeConstructor.toString() } else options.hintsClassifierNamePolicy.renderClassifier(klass, this) private fun KotlinType.renderFunctionTypeTo(list: MutableList<InlayInfoDetail>) { val type = this val lengthBefore = list.size // we need special renderer to skip @ExtensionFunctionType with(functionTypeAnnotationsRenderer) { type.renderAnnotationsTo(list) } val hasAnnotations = list.size != lengthBefore val isSuspend = this.isSuspendFunctionType val isNullable = this.isMarkedNullable val receiverType = this.getReceiverTypeFromFunctionType() val needParenthesis = isNullable || (hasAnnotations && receiverType != null) if (needParenthesis) { if (isSuspend) { list.add(lengthBefore, TextInlayInfoDetail("(")) } else { if (hasAnnotations) { if (list[list.lastIndex - 1].text != ")") { // last annotation rendered without parenthesis - need to add them otherwise parsing will be incorrect list.add(list.lastIndex, TextInlayInfoDetail("()")) } } list.append("(") } } if (receiverType != null) { val surroundReceiver = shouldRenderAsPrettyFunctionType(receiverType) && !receiverType.isMarkedNullable || receiverType.hasModifiersOrAnnotations() if (surroundReceiver) { list.append("(") } receiverType.renderNormalizedTypeTo(list) if (surroundReceiver) { list.append(")") } list.append(".") } list.append("(") val parameterTypes = this.getValueParameterTypesFromFunctionType() for ((index, typeProjection) in parameterTypes.withIndex()) { if (index > 0) list.append(", ") if (options.parameterNamesInFunctionalTypes) { typeProjection.type.extractParameterNameFromFunctionTypeArgument()?.let { name -> list.append(renderName(name)) list.append(": ") } } typeProjection.renderTypeProjectionTo(list) } list.append(") ").append(arrow()).append(" ") this.getReturnTypeFromFunctionType().renderNormalizedTypeTo(list) if (needParenthesis) list.append(")") if (isNullable) list.append("?") } fun TypeProjection.renderTypeProjectionTo(list: MutableList<InlayInfoDetail>) = listOf(this).appendTypeProjectionsTo(list) private fun List<TypeProjection>.appendTypeProjectionsTo(list: MutableList<InlayInfoDetail>) { val iterator = this.iterator() while (iterator.hasNext()) { val next = iterator.next() if (next.isStarProjection) { list.append("*") } else { val renderedType = renderTypeIntoInlayInfo(next.type) if (next.projectionKind != Variance.INVARIANT) { list.append("${next.projectionKind} ") } list.addAll(renderedType) } if (iterator.hasNext()) { list.append(", ") } } } private fun Annotated.renderAnnotationsTo(list: MutableList<InlayInfoDetail>, target: AnnotationUseSiteTarget? = null) { if (DescriptorRendererModifier.ANNOTATIONS !in options.modifiers) return val excluded = if (this is KotlinType) options.excludedTypeAnnotationClasses else options.excludedAnnotationClasses val annotationFilter = options.annotationFilter for (annotation in this.annotations) { if (annotation.fqName !in excluded && !annotation.isParameterName() && (annotationFilter == null || annotationFilter(annotation)) ) { list.append(renderAnnotation(annotation, target)) if (options.eachAnnotationOnNewLine) { list.append("\n") } else { list.append(" ") } } } } override fun renderAnnotation(annotation: AnnotationDescriptor, target: AnnotationUseSiteTarget?): String { return buildString { append('@') if (target != null) { append(target.renderName + ":") } val annotationType = annotation.type append(renderTypeIntoInlayInfo(annotationType)) } } companion object { @JvmStatic private fun withOptions(changeOptions: HintsDescriptorRendererOptions.() -> Unit): HintsTypeRenderer { val options = HintsDescriptorRendererOptions() options.changeOptions() options.lock() return HintsTypeRenderer(options) } internal fun getInlayHintsTypeRenderer(bindingContext: BindingContext, context: KtElement) = withOptions { modifiers = emptySet() parameterNameRenderingPolicy = ParameterNameRenderingPolicy.ONLY_NON_SYNTHESIZED enhancedTypes = true textFormat = RenderingFormat.PLAIN renderUnabbreviatedType = false hintsClassifierNamePolicy = ImportAwareClassifierNamePolicy(bindingContext, context) } } internal class ImportAwareClassifierNamePolicy( val bindingContext: BindingContext, val context: KtElement ): HintsClassifierNamePolicy { override fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String { if (classifier.containingDeclaration is ClassDescriptor) { val resolutionFacade = context.getResolutionFacade() val scope = context.getResolutionScope(bindingContext, resolutionFacade) if (scope.findClassifier(classifier.name, NoLookupLocation.FROM_IDE) == classifier) { return classifier.name.asString() } } return shortNameWithCompanionNameSkip(classifier, renderer) } private fun shortNameWithCompanionNameSkip(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String { if (classifier is TypeParameterDescriptor) return renderer.renderName(classifier.name) val qualifiedNameParts = classifier.parentsWithSelf .takeWhile { it is ClassifierDescriptor } .filter { !(it.isCompanionObject() && it.name == SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT) } .mapTo(ArrayList()) { it.name } .reversed() return renderFqName(qualifiedNameParts) } } }
apache-2.0
21c60d5958adbf8af5bd874586c53aae
39.392857
138
0.648203
5.191148
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/Field.kt
1
4449
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.schema import com.microsoft.thrifty.schema.parser.ConstValueElement import com.microsoft.thrifty.schema.parser.FieldElement /** * Represents a named value in a struct, union, or exception; a field also * represents parameters accepted by or exceptions thrown by service methods. */ class Field private constructor( private val element: FieldElement, private val mixin: UserElementMixin, private var type_: ThriftType? = null ) : UserElement by mixin { /** * True if this field should be redacted when printed as a string. */ val isRedacted: Boolean get() = mixin.hasThriftOrJavadocAnnotation("redacted") /** * True if this field should be obfuscated when printed as a string. * * The difference is that redaction eliminates _all_ information, while * obfuscation preserves _some_. Typically, scalar values will be rendered * as a hash code, and collections will be rendered as a typename plus a * size, e.g. `list<string>(size=12)`. */ val isObfuscated: Boolean get() = mixin.hasThriftOrJavadocAnnotation("obfuscated") override val isDeprecated: Boolean get() = mixin.isDeprecated /** * The type of value contained within this field. */ val type: ThriftType get() = type_!! /** * The integer ID of this field in its containing structure. */ val id: Int get() = element.fieldId /** * True if this field is explicitly marked `optional`, otherwise false. */ val optional: Boolean get() = element.requiredness === Requiredness.OPTIONAL /** * True if this field is explicitly marked `required`, otherwise false. */ val required: Boolean get() = element.requiredness === Requiredness.REQUIRED /** * The field's default value, if any. */ val defaultValue: ConstValueElement? get() = element.constValue /** * If this field's type is a typedef, this value will be the name of the * typedef itself - that is, the "new" name, not the aliased type's name. */ val typedefName: String? get() { return type_?.let { if (it.isTypedef) it.name else null } } internal constructor(element: FieldElement, namespaces: Map<NamespaceScope, String>) : this(element, UserElementMixin(element, namespaces)) /** * Creates a [Builder] initialized with this field's values. */ fun toBuilder(): Builder = Builder(this) internal fun link(linker: Linker) { this.type_ = linker.resolveType(element.type) } internal fun validate(linker: Linker) { val value = element.constValue if (value != null) { try { Constant.validate(linker, value, type_!!) } catch (e: IllegalStateException) { linker.addError(value.location, e.message ?: "Error validating default field value") } } } /** * An object that can build new [Field] instances. */ class Builder internal constructor(field: Field) : AbstractUserElementBuilder<Field, Builder>(field.mixin) { private val fieldElement: FieldElement = field.element private var fieldType: ThriftType? = null init { this.fieldType = field.type_ } /** * Use the given [type] for the [Field] under construction. */ fun type(type: ThriftType): Builder = apply { this.fieldType = type } override fun build(): Field { return Field(fieldElement, mixin, fieldType) } } }
apache-2.0
ea724e6ecf79251b0deed6dce26f0950
30.111888
116
0.637671
4.539796
false
false
false
false
nkming2/libutils-android
src/main/kotlin/com/nkming/utils/widget/ArrayRecyclerAdapter.kt
1
4849
package com.nkming.utils.widget import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.nkming.utils.Log import java.util.* /** * Derived class of RecyclerView.Adapter that looks similar to the original * ArrayAdapter. Filter is not supported */ class ArrayRecyclerAdapter<_ItemT, _ViewHolderT>( context: Context, resource: Int, textViewResourceId: Int, objects: MutableList<_ItemT>, factory: (root: View, text: TextView) -> _ViewHolderT) : RecyclerView.Adapter<_ViewHolderT>() where _ViewHolderT: RecyclerView.ViewHolder, _ViewHolderT: ArrayRecyclerAdapter.ViewHolderAdapter { companion object { fun <_ViewHolderT> createFromResource(context: Context, textArrayResId: Int, textViewResId: Int, factory: (root: View, text: TextView) -> _ViewHolderT) : ArrayRecyclerAdapter<CharSequence, _ViewHolderT> where _ViewHolderT: RecyclerView.ViewHolder, _ViewHolderT: ArrayRecyclerAdapter.ViewHolderAdapter { val strings: Array<CharSequence> = context.resources.getTextArray( textArrayResId) return ArrayRecyclerAdapter(context, textViewResId, strings, factory) } private /* XXX const */ val LOG_TAG = ArrayRecyclerAdapter::class.java.canonicalName } interface ViewHolderAdapter { fun setText(text: CharSequence) } constructor(context: Context, resource: Int, factory: (root: View, text: TextView) -> _ViewHolderT) : this(context, resource, 0, ArrayList<_ItemT>(), factory) constructor(context: Context, resource: Int, textViewResourceId: Int, factory: (root: View, text: TextView) -> _ViewHolderT) : this(context, resource, textViewResourceId, ArrayList<_ItemT>(), factory) constructor(context: Context, resource: Int, objects: Array<_ItemT>, factory: (root: View, text: TextView) -> _ViewHolderT) : this(context, resource, 0, objects.toMutableList(), factory) constructor(context: Context, resource: Int, textViewResourceId: Int, objects: Array<_ItemT>, factory: (root: View, text: TextView) -> _ViewHolderT) : this(context, resource, textViewResourceId, objects.toMutableList(), factory) constructor(context: Context, resource: Int, objects: MutableList<_ItemT>, factory: (root: View, text: TextView) -> _ViewHolderT) : this(context, resource, 0, objects, factory) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : _ViewHolderT { try { val root = _inflater.inflate(_resource, parent, false) val text = (if (_textId == 0) root else root.findViewById(_textId)) as TextView return _factory(root, text) } catch (e: ClassCastException) { Log.e(LOG_TAG, "You must supply a resource ID for a TextView") throw IllegalStateException( "ArrayRecyclerAdapter requires the resource ID to be a TextView", e) } } override fun onBindViewHolder(holder: _ViewHolderT, position: Int) { val item = _objects[position] if (item is CharSequence) { holder.setText(item) } else { holder.setText(item.toString()) } } override fun getItemCount(): Int = _objects.size fun add(obj: _ItemT) { synchronized(_objects) { _objects.add(obj) } if (notifyOnChange) { notifyItemInserted(_objects.size - 1) } } fun addAll(vararg obj: _ItemT) { var beg: Int = 0 synchronized(_objects) { beg = _objects.size _objects.addAll(obj) } if (notifyOnChange) { notifyItemRangeInserted(beg, obj.size) } } fun insert(obj: _ItemT, position: Int) { synchronized(_objects) { _objects.add(position, obj) } if (notifyOnChange) { notifyItemInserted(position) } } fun remove(obj: _ItemT) { var position: Int = 0 synchronized(_objects) { position = _objects.indexOf(obj) if (position == -1) { return } _objects.removeAt(position) } if (notifyOnChange) { notifyItemRemoved(position) } } fun clear() { var size: Int = 0 synchronized(_objects) { size = _objects.size _objects.clear() } if (notifyOnChange) { notifyItemRangeRemoved(0, size) } } fun sort(comp: Comparator<in _ItemT>) { synchronized(_objects) { Collections.sort(_objects, comp) } if (notifyOnChange) { notifyDataSetChanged() } } /** * Similar to ArrayAdapter#setNotifyOnChange() with one exception: calling * notifyDataSetChanged() would NOT reset the flag to true */ var notifyOnChange: Boolean = true val context: Context get() = _context val count: Int get() = _objects.size private val _context = context private val _inflater = LayoutInflater.from(_context) private val _resource = resource private val _objects = objects private val _textId = textViewResourceId private val _factory = factory }
mit
3e18280b778b85b6c5f6d330b220b512
22.8867
86
0.702413
3.448791
false
false
false
false
team401/SnakeSkin
SnakeSkin-Core/src/main/kotlin/org/snakeskin/init/InitManager.kt
1
5513
package org.snakeskin.init import org.snakeskin.annotation.PostStartup import org.snakeskin.annotation.PreStartup import org.snakeskin.annotation.Setup import org.snakeskin.compiler.RuntimeLoader import org.snakeskin.compiler.VersionManager import org.snakeskin.exception.InitException import org.snakeskin.exception.StartupException import org.snakeskin.logging.LoggerManager import org.snakeskin.runtime.SnakeskinPlatform import org.snakeskin.runtime.SnakeskinRuntime import java.lang.ClassCastException /** * @author Cameron Earle * @version 9/30/2019 */ object InitManager { /** * List of module initializers. We may find them, we may not. They will be loaded in order */ private val initializerClasses = arrayOf( "org.snakeskin.init.CoreInit", "org.snakeskin.init.FrcInit", "org.snakeskin.init.CtreInit", "org.snakeskin.init.RevInit" ) private val initializers = ArrayList<Initializer>(initializerClasses.size) private fun loadInitializers() { initializerClasses.forEach { try { val clazz = Class.forName(it) val ctor = clazz.getConstructor() //Get the default constructor val instance = ctor.newInstance() as Initializer initializers.add(instance) } catch (cnf: ClassNotFoundException) { //Ignore this, just means the module isn't present on the classpath } catch (nmf: NoSuchMethodException) { //This means that the initializer doesn't have a default constructor. This is not supposed to happen throw InitException("Could not find default constructor for initializer '$it'. This is not supposed to happen!", nmf) } catch (cce: ClassCastException) { //This means that the initializer doesn't implement the Initializer interface. This is also not supposed to happen throw InitException("Initializer '$it' does not implement the Initializer interface. This is not supposed to happen!", cce) } catch (e: Exception) { //At this point we have no idea what happened throw InitException("Unknown error while loading initializer '$it'. This is definitely not supposed to happen!", e) } } } /** * This method runs before SETUP is loaded */ @JvmStatic fun preStartup() { //First, do internal initialization initializers.forEach { try { it.preStartup() } catch (e: Exception) { throw InitException("Exception while running INTERNAL pre-startup task '${it.javaClass.name}', this is not supposed to happen!", e) } } //Next, do any user code initialization val preStartupTasks = RuntimeLoader.getAnnotated(PreStartup::class.java) preStartupTasks.forEach { try { it.run() } catch (e: Exception) { throw InitException("Exception while running pre-startup task '${it.javaClass.name}'", e) } } } /** * This method runs after SETUP is loaded */ @JvmStatic fun postStartup() { //First, do internal initialization initializers.forEach { try { it.postStartup() } catch (e: Exception) { throw InitException("Exception while running INTERNAL post-startup task '${it.javaClass.name}', this is not supposed to happen!", e) } } //Next, do any user code initialization val postStartupTasks = RuntimeLoader.getAnnotated(PostStartup::class.java) postStartupTasks.forEach { try { it.run() } catch (e: Exception) { throw InitException("Exception while running post-startup task '${it.javaClass.name}'", e) } } } /** * This method does the initialization */ @JvmStatic fun init(platform: SnakeskinPlatform) { //First, we'll initialize and start the logger LoggerManager.init() LoggerManager.logMainThread() //Print a message to show version println("SnakeSkin: Version '${VersionManager.getVersion()}'") //Next, we'll load all of the annotated tasks and internal initialization classes println("SnakeSkin: Loading classes") loadInitializers() RuntimeLoader.load() println("SnakeSkin: Classes loaded") //Next, we'll run the "pre-startup" init tasks preStartup() //Next, we'll initialize the runtime SnakeskinRuntime.start(platform) //Next, we'll load the setup methods val setupMethods = RuntimeLoader.getAnnotated(Setup::class.java) //If there are not setup methods, crash the code here (this event will be logged as a crash) if (setupMethods.isEmpty()) { throw StartupException("No 'setup' methods found! Make sure they are annotated with the '@Setup' annotation!") } //Run each setup method setupMethods.forEach { try { it.run() } catch (e: Exception) { throw InitException("Exception while running setup method '${it.javaClass.name}'", e) } } //Now that the setup has been completed, we can run the "postStartup" init tasks postStartup() } }
gpl-3.0
acb303e5b132f1a5f3ced3f93a87808e
37.027586
148
0.620171
4.939964
false
false
false
false
android/nowinandroid
app/src/main/java/com/google/samples/apps/nowinandroid/ui/NiaAppState.kt
1
6869
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.ui import androidx.compose.material3.windowsizeclass.WindowHeightSizeClass import androidx.compose.material3.windowsizeclass.WindowSizeClass import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.navigation.NavController import androidx.navigation.NavDestination import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import androidx.navigation.navOptions import androidx.tracing.trace import com.google.samples.apps.nowinandroid.core.data.util.NetworkMonitor import com.google.samples.apps.nowinandroid.core.ui.TrackDisposableJank import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.bookmarksRoute import com.google.samples.apps.nowinandroid.feature.bookmarks.navigation.navigateToBookmarks import com.google.samples.apps.nowinandroid.feature.foryou.navigation.forYouNavigationRoute import com.google.samples.apps.nowinandroid.feature.foryou.navigation.navigateToForYou import com.google.samples.apps.nowinandroid.feature.interests.navigation.interestsRoute import com.google.samples.apps.nowinandroid.feature.interests.navigation.navigateToInterestsGraph import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.BOOKMARKS import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.FOR_YOU import com.google.samples.apps.nowinandroid.navigation.TopLevelDestination.INTERESTS import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn @Composable fun rememberNiaAppState( windowSizeClass: WindowSizeClass, networkMonitor: NetworkMonitor, coroutineScope: CoroutineScope = rememberCoroutineScope(), navController: NavHostController = rememberNavController() ): NiaAppState { NavigationTrackingSideEffect(navController) return remember(navController, coroutineScope, windowSizeClass, networkMonitor) { NiaAppState(navController, coroutineScope, windowSizeClass, networkMonitor) } } @Stable class NiaAppState( val navController: NavHostController, val coroutineScope: CoroutineScope, val windowSizeClass: WindowSizeClass, networkMonitor: NetworkMonitor, ) { val currentDestination: NavDestination? @Composable get() = navController .currentBackStackEntryAsState().value?.destination val currentTopLevelDestination: TopLevelDestination? @Composable get() = when (currentDestination?.route) { forYouNavigationRoute -> FOR_YOU bookmarksRoute -> BOOKMARKS interestsRoute -> INTERESTS else -> null } var shouldShowSettingsDialog by mutableStateOf(false) private set val shouldShowBottomBar: Boolean get() = windowSizeClass.widthSizeClass == WindowWidthSizeClass.Compact || windowSizeClass.heightSizeClass == WindowHeightSizeClass.Compact val shouldShowNavRail: Boolean get() = !shouldShowBottomBar val isOffline = networkMonitor.isOnline .map(Boolean::not) .stateIn( scope = coroutineScope, started = SharingStarted.WhileSubscribed(5_000), initialValue = false ) /** * Map of top level destinations to be used in the TopBar, BottomBar and NavRail. The key is the * route. */ val topLevelDestinations: List<TopLevelDestination> = TopLevelDestination.values().asList() /** * UI logic for navigating to a top level destination in the app. Top level destinations have * only one copy of the destination of the back stack, and save and restore state whenever you * navigate to and from it. * * @param topLevelDestination: The destination the app needs to navigate to. */ fun navigateToTopLevelDestination(topLevelDestination: TopLevelDestination) { trace("Navigation: ${topLevelDestination.name}") { val topLevelNavOptions = navOptions { // Pop up to the start destination of the graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.findStartDestination().id) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true // Restore state when reselecting a previously selected item restoreState = true } when (topLevelDestination) { FOR_YOU -> navController.navigateToForYou(topLevelNavOptions) BOOKMARKS -> navController.navigateToBookmarks(topLevelNavOptions) INTERESTS -> navController.navigateToInterestsGraph(topLevelNavOptions) } } } fun onBackClick() { navController.popBackStack() } fun setShowSettingsDialog(shouldShow: Boolean) { shouldShowSettingsDialog = shouldShow } } /** * Stores information about navigation events to be used with JankStats */ @Composable private fun NavigationTrackingSideEffect(navController: NavHostController) { TrackDisposableJank(navController) { metricsHolder -> val listener = NavController.OnDestinationChangedListener { _, destination, _ -> metricsHolder.state?.putState("Navigation", destination.route.toString()) } navController.addOnDestinationChangedListener(listener) onDispose { navController.removeOnDestinationChangedListener(listener) } } }
apache-2.0
9d4a2ca0a44ab61a71044acbc87a4168
40.379518
100
0.744941
5.263602
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-11/code-to-copy/data/BaseballDao.kt
1
3998
package dev.mfazio.abl.data import androidx.lifecycle.LiveData import androidx.room.* import dev.mfazio.abl.players.Player import dev.mfazio.abl.players.PlayerStats import dev.mfazio.abl.players.PlayerWithStats import dev.mfazio.abl.players.Position import dev.mfazio.abl.scoreboard.ScheduledGame import dev.mfazio.abl.standings.TeamStanding @Dao abstract class BaseballDao { @Insert abstract suspend fun insertStandings(standings: List<TeamStanding>) @Update abstract suspend fun updateStandings(standings: List<TeamStanding>) @Query("SELECT * FROM standings") abstract fun getStandings(): LiveData<List<TeamStanding>> @Query("SELECT * FROM standings") abstract suspend fun getCurrentStandings(): List<TeamStanding> @Query("SELECT * FROM games WHERE gameId LIKE :dateString") abstract fun getGamesForDate( dateString: String ): LiveData<List<ScheduledGame>> @Query("SELECT * FROM games WHERE gameId = :gameId") abstract fun getGameByGameId(gameId: String): ScheduledGame? @Insert abstract suspend fun insertGame(game: ScheduledGame) @Update abstract suspend fun updateGame(game: ScheduledGame) @Transaction open suspend fun insertOrUpdateGames(games: List<ScheduledGame>) { games.forEach { game -> getGameByGameId(game.gameId)?.let { dbGame -> updateGame(game.apply { id = dbGame.id }) } ?: insertGame(game) } } @Query("SELECT * FROM players WHERE playerId = :playerId") abstract fun getPlayerById(playerId: String): Player? @Insert abstract suspend fun insertPlayer(player: Player) @Update abstract suspend fun updatePlayer(player: Player) @Transaction open suspend fun insertOrUpdatePlayers(players: List<Player>) { players.forEach { player -> insertOrUpdatePlayer(player) } } @Transaction open suspend fun insertOrUpdatePlayer(player: Player) { getPlayerById(player.playerId)?.let { dbPlayer -> updatePlayer(player.apply { id = dbPlayer.id }) } ?: insertPlayerAndStats(player) } @Transaction open suspend fun insertPlayerAndStats(player: Player) { insertPlayer(player) if (getPlayerStatsById(player.playerId) == null) { insertPlayerStats(PlayerStats(player.playerId)) } } @Query("DELETE FROM players") abstract suspend fun deleteAllPlayers() @Query("SELECT * FROM stats WHERE playerId = :playerId") abstract suspend fun getPlayerStatsById(playerId: String): PlayerStats? @Insert abstract suspend fun insertPlayerStats(stats: PlayerStats) @Update abstract suspend fun updatePlayerStats(stats: PlayerStats) @Transaction @Query("SELECT * FROM players WHERE playerId = :playerId") abstract fun getPlayerWithStats(playerId: String): LiveData<PlayerWithStats?> @Transaction @Query("SELECT * FROM players WHERE position NOT IN (:pitcherPositions)") abstract fun getBattersWithStats( pitcherPositions: List<Position> = listOf( Position.StartingPitcher, Position.ReliefPitcher ) ): LiveData<List<PlayerWithStats>?> @Transaction @Query("SELECT * FROM players WHERE position IN (:pitcherPositions)") abstract fun getPitchersWithStats( pitcherPositions: List<Position> = listOf( Position.StartingPitcher, Position.ReliefPitcher ) ): LiveData<List<PlayerWithStats>?> @Transaction open suspend fun insertOrUpdateStats(playerStats: List<PlayerStats>) { playerStats.forEach { stats -> insertOrUpdatePlayerStats(stats) } } @Transaction open suspend fun insertOrUpdatePlayerStats(playerStats: PlayerStats) { getPlayerStatsById(playerStats.playerId)?.let { dbPlayerStats -> updatePlayerStats(playerStats.apply { id = dbPlayerStats.id }) } ?: insertPlayerStats(playerStats) } }
apache-2.0
1f6512df05b90dcf043ed20386a5b9ca
30.992
81
0.695098
4.627315
false
false
false
false
AberrantFox/hotbot
src/main/kotlin/me/aberrantfox/hotbot/commandframework/commands/administration/StrikeCommands.kt
1
14502
package me.aberrantfox.hotbot.commandframework.commands.administration import me.aberrantfox.hotbot.commandframework.parsing.ArgumentType import me.aberrantfox.hotbot.dsls.command.CommandSet import me.aberrantfox.hotbot.database.* import me.aberrantfox.hotbot.dsls.command.CommandEvent import me.aberrantfox.hotbot.dsls.command.arg import me.aberrantfox.hotbot.dsls.command.commands import me.aberrantfox.hotbot.dsls.embed.embed import me.aberrantfox.hotbot.extensions.jda.fullName import me.aberrantfox.hotbot.extensions.jda.getMemberJoinString import me.aberrantfox.hotbot.extensions.jda.sendPrivateMessage import me.aberrantfox.hotbot.extensions.stdlib.* import me.aberrantfox.hotbot.services.Configuration import me.aberrantfox.hotbot.services.InfractionAction import me.aberrantfox.hotbot.services.UserID import me.aberrantfox.hotbot.utility.muteMember import net.dv8tion.jda.core.entities.Guild import net.dv8tion.jda.core.entities.MessageEmbed import net.dv8tion.jda.core.entities.User import org.joda.time.format.DateTimeFormat import java.awt.Color data class StrikeRequest(val user: User, val reason: String, val amount: Int, val moderator: User) object StrikeRequests { val map = HashMap<UserID, StrikeRequest>() } @CommandSet fun strikeCommands() = commands { command("warn") { expect(ArgumentType.User, ArgumentType.Sentence) execute { val newArgs = listOf(it.args[0], 0, it.args[1]) val e = it.copy(args=newArgs) infract(e) } } command("strike") { expect(arg(ArgumentType.User), arg(ArgumentType.Integer, optional = true, default = 1), arg(ArgumentType.Sentence)) execute { infract(it) } } command("strikerequest") { expect(ArgumentType.User, ArgumentType.Integer, ArgumentType.Sentence) execute { val target = it.args.component1() as User val amount = it.args.component2() as Int val reason = it.args.component3() as String if(amount > it.config.security.strikeCeil) { it.respond("Error, strike quantity above strike ceiling. ") return@execute } val request = StrikeRequest(target, reason, amount, it.author) StrikeRequests.map.put(target.id, request) it.respond("This has been logged and will be accepted or declined, thank you.") alert("${it.author.fullName()} has a new strike request. Use ++viewRequest ${target.asMention} to see it.") } } command("viewRequest") { expect(ArgumentType.User) execute { val user = it.args.component1() as User if( !(strikeAgainst(user, it)) ) return@execute val request = StrikeRequests.map[user.id]!! it.respond(embed { title("${request.moderator.fullName()}'s request") field { name = "Target" value = "${request.user.asMention}(${request.user.fullName()})" inline = false } field { name = "Reasoning" value = request.reason inline = false } field { name = "Amount" value = "${request.amount}" inline = false } }) } } command("acceptrequest") { expect(ArgumentType.User) execute { val user = it.args.component1() as User if( !(strikeAgainst(user, it)) ) return@execute val request = StrikeRequests.map[user.id]!! val newArgs = listOf(request.user, request.amount, request.reason) infract(it.copy(args = newArgs)) StrikeRequests.map.remove(user.id) it.respond("Strike request on ${user.asMention} was accepted.") } } command("declinerequest") { expect(ArgumentType.User) execute { val user = it.args.component1() as User if( !(strikeAgainst(user, it)) ) return@execute StrikeRequests.map.remove(user.id) it.respond("Strike request on ${user.asMention} was declined.") } } command("deleteRequest") { expect(ArgumentType.User) execute { val user = it.args.component1() as User if( !(strikeAgainst(user, it)) ) return@execute val byInvoker = StrikeRequests.map[user.id]!!.moderator.id == it.author.id if(byInvoker) { StrikeRequests.map.remove(user.id) it.respond("Request removed.") } else { it.respond("You did not make that request and as such cannot delete it.") } } } command("listrequests") { execute { if(StrikeRequests.map.isEmpty()) { it.respond("No requests currently in place.") return@execute } val response = StrikeRequests.map.values .map { "${it.user.asMention }, requested by ${it.moderator.fullName()}" } .reduce {a, b -> "$a \n$b" } it.respond(response) } } command("history") { expect(ArgumentType.User) execute { val target = it.args[0] as User incrementOrSetHistoryCount(target.id) it.respond(buildHistoryEmbed(target, true, getHistory(target.id), getHistoryCount(target.id),getNotesByUser(target.id), it)) } } command("removestrike") { expect(ArgumentType.Integer) execute { val strikeID = it.args[0] as Int val amountRemoved = removeInfraction(strikeID) it.respond("Deleted $amountRemoved strike records.") } } command("cleanse") { expect(ArgumentType.User) execute { val user = it.args[0] as User val amount = removeAllInfractions(user.id) it.respond("Infractions for ${user.asMention} have been wiped. Total removed: $amount") } } command("selfhistory") { execute { val target = it.author target.sendPrivateMessage(buildHistoryEmbed(target, false, getHistory(target.id), getHistoryCount(target.id), null, it)) } } } private fun strikeAgainst(user: User, event: CommandEvent) = if( !(StrikeRequests.map.containsKey(user.id)) ) { event.respond("That user does not currently have a strike request.") false } else { true } private fun infract(event: CommandEvent) { val args = event.args val target = args[0] as User val strikeQuantity = args[1] as Int val reason = args[2] as String if (strikeQuantity < 0 || strikeQuantity > 3) { event.respond("Strike weight should be between 0 and 3") return } if (!(event.guild.isMember(target))) { event.respond("Cannot find the member by the id: ${target.id}") return } insertInfraction(target.id, event.author.id, strikeQuantity, reason) event.author.sendPrivateMessage("User ${target.asMention} has been infracted with weight: $strikeQuantity, with reason:\n$reason") var totalStrikes = getMaxStrikes(target.id) if (totalStrikes > event.config.security.strikeCeil) totalStrikes = event.config.security.strikeCeil administerPunishment(event.config, target, strikeQuantity, reason, event.guild, event.author, totalStrikes) } private fun administerPunishment(config: Configuration, user: User, strikeQuantity: Int, reason: String, guild: Guild, moderator: User, totalStrikes: Int) { user.openPrivateChannel().queue { chan -> val punishmentAction = config.security.infractionActionMap[totalStrikes]?.toString() ?: "None" val infractionEmbed = buildInfractionEmbed(user.asMention, reason, strikeQuantity, totalStrikes, config.security.strikeCeil, punishmentAction) chan.sendMessage(infractionEmbed).queue { when (config.security.infractionActionMap[totalStrikes]) { InfractionAction.Warn -> { chan.sendMessage("This is your warning - Do not break the rules again.").queue() } InfractionAction.Kick -> { chan.sendMessage("You may return via this: https://discord.gg/BQN6BYE - please be mindful of the rules next time.") .queue { guild.controller.kick(user.id, reason).queue() } } InfractionAction.Mute -> { muteMember(guild, user, 1000 * 60 * 60 * 24, "Infraction punishment.", config, moderator) } InfractionAction.Ban -> { chan.sendMessage("Well... that happened. There may be an appeal system in the future. But for now, you're" + " permanently banned. Sorry about that :) ").queue { guild.controller.ban(user.id, 0, reason).queue() } } } } } } private fun buildHistoryEmbed(target: User, includeModerator: Boolean, records: List<StrikeRecord>, historyCount: Int, notes: List<NoteRecord>?, it: CommandEvent) = embed { title("${target.fullName()}'s Record") setColor(Color.MAGENTA) setThumbnail(target.effectiveAvatarUrl) field { name = "" value = "__**Summary**__" inline = false } field { name = "Information" value = "${target.fullName()} has **${records.size}** infractions(s).\nOf these infractions, " + "**${records.filter { it.isExpired }.size}** are expired and **${records.filter { !it.isExpired }.size}** are still in effect." + "\nCurrent strike value of **${getMaxStrikes(target.id)}/${it.config.security.strikeCeil}**" + "\nJoin date: **${it.guild.getMemberJoinString(target)}**" + "\nCreation date: **${target.creationTime.toString().formatJdaDate()}**" inline = false if(includeModerator){ value +="\nHistory has been invoked **$historyCount** times." } } field { name = "" value = "__**Infractions**__" inline = false } records.forEach { record -> field { name = "ID :: __${record.id}__ :: Weight :: __${record.strikes}__" value = "This infraction is **${expired(record.isExpired)}**." inline = false if(includeModerator) { value += "\nIssued by **${record.moderator.retrieveIdToName(it.jda)}** on **${record.dateTime.toString(DateTimeFormat.forPattern("dd/MM/yyyy"))}**" } } produceFields("Infraction Reasoning Given", record.reason).forEach { addField(it) } } if (records.isEmpty()) { field { name = "No Infractions" value = "Clean as a whistle, sir." inline = false } } if (!includeModerator || notes == null) { return@embed } field { name = "" value = "__**Notes**__" inline = false } if(notes.isEmpty()) { field { name = "No Notes" value = "User has no notes written" inline = false } } notes.forEach { note -> field { name = "ID :: __${note.id}__ :: Staff :: __${note.moderator.retrieveIdToName(it.jda)}__" value = "Noted by **${note.moderator.retrieveIdToName(it.jda)}** on **${note.dateTime.toString(DateTimeFormat.forPattern("dd/MM/yyyy"))}**" inline = false } produceFields("NoteMessage", note.note).forEach { addField(it) } } } fun produceFields(title: String, message: String) = message.chunked(1024).mapIndexed { index, chunk -> MessageEmbed.Field("$title -- $index", chunk, false) } private fun buildInfractionEmbed(userMention: String, reason: String, strikeQuantity: Int, totalStrikes: Int, strikeCeil: Int, punishmentAction: String) = embed { title("Infraction") description("$userMention, you have been infracted.\nInfractions are formal warnings from staff members on TPH.\n" + "If you think your infraction is undoubtedly unjustified, please **do not** post about it in a public channel but take it up with an administrator.") ifield { name = "Strike Quantity" value = "$strikeQuantity" } ifield { name = "Strike Count" value = "$totalStrikes / $strikeCeil" } ifield { name = "Punishment" value = punishmentAction } field { name = "__Reason__" value = reason.limit(1024) inline = false } setColor(Color.RED) } private fun expired(boolean: Boolean) = if (boolean) "expired" else "not expired"
mit
708a6833d6dfdcf2451f7b3bfab92504
35.437186
173
0.531168
4.790882
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidKotlindoc/src/main/kotlin/com/eden/orchid/kotlindoc/page/KotlindocClassPage.kt
1
1189
@file:Suppress(SuppressedWarnings.DEPRECATION) package com.eden.orchid.kotlindoc.page import com.copperleaf.dokka.json.models.KotlinClassDoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.kotlindoc.KotlindocGenerator import com.eden.orchid.kotlindoc.model.KotlindocModel import com.eden.orchid.kotlindoc.resources.KotlinClassdocResource import com.eden.orchid.utilities.SuppressedWarnings @Archetype(value = ConfigArchetype::class, key = "${KotlindocGenerator.GENERATOR_KEY}.classPages") @Description(value = "Documentation for a Kotlin or Java class.", name = "Kotlin class") class KotlindocClassPage( context: OrchidContext, val classDoc: KotlinClassDoc ) : BaseKotlindocPage(KotlinClassdocResource(context, classDoc), "kotlindocClass", classDoc.name) { lateinit var model: KotlindocModel var packagePage: KotlindocPackagePage? = null override val itemIds: List<String> get() = listOf( classDoc.qualifiedName, classDoc.name ) }
mit
026fffd91c7084361b8c4e98449adc2f
40
99
0.788057
4.339416
false
true
false
false
GunoH/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/fus/StatisticsRecorderBundledMetadataProvider.kt
2
3241
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.fus import com.intellij.internal.statistic.config.EventLogExternalSettings import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import io.opentelemetry.api.trace.StatusCode import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildOptions import org.jetbrains.intellij.build.TraceManager.spanBuilder import org.jetbrains.intellij.build.downloadAsBytes import org.jetbrains.intellij.build.impl.ModuleOutputPatcher import org.jetbrains.intellij.build.impl.createSkippableJob import java.util.concurrent.CancellationException /** * Download a default version of feature usage statistics metadata to be bundled with IDE. */ internal fun CoroutineScope.createStatisticsRecorderBundledMetadataProviderTask(moduleOutputPatcher: ModuleOutputPatcher, context: BuildContext): Job? { val featureUsageStatisticsProperties = context.proprietaryBuildTools.featureUsageStatisticsProperties ?: return null return createSkippableJob( spanBuilder("bundle a default version of feature usage statistics"), taskId = BuildOptions.FUS_METADATA_BUNDLE_STEP, context = context ) { try { val recorderId = featureUsageStatisticsProperties.recorderId moduleOutputPatcher.patchModuleOutput( moduleName = "intellij.platform.ide.impl", path = "resources/event-log-metadata/$recorderId/events-scheme.json", content = download(appendProductCode(metadataServiceUri(featureUsageStatisticsProperties, context), context)) ) } catch (e: CancellationException) { throw e } catch (e: Throwable) { // do not halt build, just record exception val span = Span.current() span.recordException(RuntimeException("Failed to bundle default version of feature usage statistics metadata", e)) span.setStatus(StatusCode.ERROR) } } } private fun appendProductCode(uri: String, context: BuildContext): String { val name = context.applicationInfo.productCode + ".json" return if (uri.endsWith('/')) "$uri$name" else "$uri/$name" } private suspend fun download(url: String): ByteArray { Span.current().addEvent("download", Attributes.of(AttributeKey.stringKey("url"), url)) return downloadAsBytes(url) } private suspend fun metadataServiceUri(featureUsageStatisticsProperties: FeatureUsageStatisticsProperties, context: BuildContext): String { val providerUri = appendProductCode(featureUsageStatisticsProperties.metadataProviderUri, context) Span.current().addEvent("parsing", Attributes.of(AttributeKey.stringKey("url"), providerUri)) val appInfo = context.applicationInfo val settings = EventLogExternalSettings.parseSendSettings(download(providerUri).inputStream().reader(), "${appInfo.majorVersion}.${appInfo.minorVersion}") return settings.getEndpoint("metadata")!! }
apache-2.0
2224b8275b1eeeda0fa12dbb41de6dd8
46.661765
139
0.755014
4.955657
false
false
false
false