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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DanielGrech/anko | dsl/testData/functional/21s/PropertyTest.kt | 3 | 69869 | public var android.support.v4.view.PagerTitleStrip.textSpacing: Int
get() = getTextSpacing()
set(v) = setTextSpacing(v)
public var android.support.v4.view.ViewPager.adapter: android.support.v4.view.PagerAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public var android.support.v4.view.ViewPager.currentItem: Int
get() = getCurrentItem()
set(v) = setCurrentItem(v)
public var android.support.v4.view.ViewPager.offscreenPageLimit: Int
get() = getOffscreenPageLimit()
set(v) = setOffscreenPageLimit(v)
public var android.support.v4.view.ViewPager.pageMargin: Int
get() = getPageMargin()
set(v) = setPageMargin(v)
public val android.support.v4.view.ViewPager.fakeDragging: Boolean
get() = isFakeDragging()
public val android.support.v4.widget.DrawerLayout.statusBarBackgroundDrawable: android.graphics.drawable.Drawable?
get() = getStatusBarBackgroundDrawable()
public val android.support.v4.widget.NestedScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public val android.support.v4.widget.NestedScrollView.nestedScrollAxes: Int
get() = getNestedScrollAxes()
public var android.support.v4.widget.NestedScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.support.v4.widget.NestedScrollView.nestedScrollingEnabled: Boolean
get() = isNestedScrollingEnabled()
set(v) = setNestedScrollingEnabled(v)
public var android.support.v4.widget.NestedScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.support.v4.widget.SlidingPaneLayout.coveredFadeColor: Int
get() = getCoveredFadeColor()
set(v) = setCoveredFadeColor(v)
public var android.support.v4.widget.SlidingPaneLayout.parallaxDistance: Int
get() = getParallaxDistance()
set(v) = setParallaxDistance(v)
public var android.support.v4.widget.SlidingPaneLayout.sliderFadeColor: Int
get() = getSliderFadeColor()
set(v) = setSliderFadeColor(v)
public val android.support.v4.widget.SlidingPaneLayout.open: Boolean
get() = isOpen()
public val android.support.v4.widget.SlidingPaneLayout.slideable: Boolean
get() = isSlideable()
public val android.support.v4.widget.SwipeRefreshLayout.progressCircleDiameter: Int
get() = getProgressCircleDiameter()
public var android.support.v4.widget.SwipeRefreshLayout.refreshing: Boolean
get() = isRefreshing()
set(v) = setRefreshing(v)
public val android.support.v7.widget.ActionMenuView.menu: android.view.Menu?
get() = getMenu()
public var android.support.v7.widget.ActionMenuView.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public val android.support.v7.widget.ActionMenuView.windowAnimations: Int
get() = getWindowAnimations()
public val android.support.v7.widget.ActionMenuView.overflowMenuShowPending: Boolean
get() = isOverflowMenuShowPending()
public val android.support.v7.widget.ActionMenuView.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public var android.support.v7.widget.ActionMenuView.overflowReserved: Boolean
get() = isOverflowReserved()
set(v) = setOverflowReserved(v)
public val android.support.v7.widget.LinearLayoutCompat.baseline: Int
get() = getBaseline()
public var android.support.v7.widget.LinearLayoutCompat.baselineAlignedChildIndex: Int
get() = getBaselineAlignedChildIndex()
set(v) = setBaselineAlignedChildIndex(v)
public var android.support.v7.widget.LinearLayoutCompat.dividerDrawable: android.graphics.drawable.Drawable?
get() = getDividerDrawable()
set(v) = setDividerDrawable(v)
public var android.support.v7.widget.LinearLayoutCompat.dividerPadding: Int
get() = getDividerPadding()
set(v) = setDividerPadding(v)
public val android.support.v7.widget.LinearLayoutCompat.dividerWidth: Int
get() = getDividerWidth()
public var android.support.v7.widget.LinearLayoutCompat.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.support.v7.widget.LinearLayoutCompat.showDividers: Int
get() = getShowDividers()
set(v) = setShowDividers(v)
public var android.support.v7.widget.LinearLayoutCompat.weightSum: Float
get() = getWeightSum()
set(v) = setWeightSum(v)
public var android.support.v7.widget.LinearLayoutCompat.baselineAligned: Boolean
get() = isBaselineAligned()
set(v) = setBaselineAligned(v)
public var android.support.v7.widget.LinearLayoutCompat.measureWithLargestChildEnabled: Boolean
get() = isMeasureWithLargestChildEnabled()
set(v) = setMeasureWithLargestChildEnabled(v)
public var android.support.v7.widget.SearchView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.support.v7.widget.SearchView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public var android.support.v7.widget.SearchView.maxWidth: Int
get() = getMaxWidth()
set(v) = setMaxWidth(v)
public val android.support.v7.widget.SearchView.query: CharSequence?
get() = getQuery()
public var android.support.v7.widget.SearchView.queryHint: CharSequence?
get() = getQueryHint()
set(v) = setQueryHint(v)
public var android.support.v7.widget.SearchView.suggestionsAdapter: android.support.v4.widget.CursorAdapter?
get() = getSuggestionsAdapter()
set(v) = setSuggestionsAdapter(v)
public val android.support.v7.widget.SearchView.iconfiedByDefault: Boolean
get() = isIconfiedByDefault()
public var android.support.v7.widget.SearchView.iconified: Boolean
get() = isIconified()
set(v) = setIconified(v)
public var android.support.v7.widget.SearchView.queryRefinementEnabled: Boolean
get() = isQueryRefinementEnabled()
set(v) = setQueryRefinementEnabled(v)
public var android.support.v7.widget.SearchView.submitButtonEnabled: Boolean
get() = isSubmitButtonEnabled()
set(v) = setSubmitButtonEnabled(v)
public val android.support.v7.widget.SwitchCompat.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.support.v7.widget.SwitchCompat.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.support.v7.widget.SwitchCompat.showText: Boolean
get() = getShowText()
set(v) = setShowText(v)
public var android.support.v7.widget.SwitchCompat.splitTrack: Boolean
get() = getSplitTrack()
set(v) = setSplitTrack(v)
public var android.support.v7.widget.SwitchCompat.switchMinWidth: Int
get() = getSwitchMinWidth()
set(v) = setSwitchMinWidth(v)
public var android.support.v7.widget.SwitchCompat.switchPadding: Int
get() = getSwitchPadding()
set(v) = setSwitchPadding(v)
public var android.support.v7.widget.SwitchCompat.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.support.v7.widget.SwitchCompat.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.support.v7.widget.SwitchCompat.thumbDrawable: android.graphics.drawable.Drawable?
get() = getThumbDrawable()
set(v) = setThumbDrawable(v)
public var android.support.v7.widget.SwitchCompat.thumbTextPadding: Int
get() = getThumbTextPadding()
set(v) = setThumbTextPadding(v)
public var android.support.v7.widget.SwitchCompat.trackDrawable: android.graphics.drawable.Drawable?
get() = getTrackDrawable()
set(v) = setTrackDrawable(v)
public val android.support.v7.widget.Toolbar.contentInsetEnd: Int
get() = getContentInsetEnd()
public val android.support.v7.widget.Toolbar.contentInsetLeft: Int
get() = getContentInsetLeft()
public val android.support.v7.widget.Toolbar.contentInsetRight: Int
get() = getContentInsetRight()
public val android.support.v7.widget.Toolbar.contentInsetStart: Int
get() = getContentInsetStart()
public var android.support.v7.widget.Toolbar.logo: android.graphics.drawable.Drawable?
get() = getLogo()
set(v) = setLogo(v)
public var android.support.v7.widget.Toolbar.logoResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.logoResource' property does not have a getter")
set(v) = setLogo(v)
public var android.support.v7.widget.Toolbar.logoDescription: CharSequence?
get() = getLogoDescription()
set(v) = setLogoDescription(v)
public var android.support.v7.widget.Toolbar.logoDescriptionResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.logoDescriptionResource' property does not have a getter")
set(v) = setLogoDescription(v)
public val android.support.v7.widget.Toolbar.menu: android.view.Menu?
get() = getMenu()
public var android.support.v7.widget.Toolbar.navigationContentDescription: CharSequence?
get() = getNavigationContentDescription()
set(v) = setNavigationContentDescription(v)
public var android.support.v7.widget.Toolbar.navigationContentDescriptionResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.navigationContentDescriptionResource' property does not have a getter")
set(v) = setNavigationContentDescription(v)
public var android.support.v7.widget.Toolbar.navigationIcon: android.graphics.drawable.Drawable?
get() = getNavigationIcon()
set(v) = setNavigationIcon(v)
public var android.support.v7.widget.Toolbar.navigationIconResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.navigationIconResource' property does not have a getter")
set(v) = setNavigationIcon(v)
public var android.support.v7.widget.Toolbar.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public var android.support.v7.widget.Toolbar.subtitle: CharSequence?
get() = getSubtitle()
set(v) = setSubtitle(v)
public var android.support.v7.widget.Toolbar.subtitleResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.subtitleResource' property does not have a getter")
set(v) = setSubtitle(v)
public var android.support.v7.widget.Toolbar.title: CharSequence?
get() = getTitle()
set(v) = setTitle(v)
public var android.support.v7.widget.Toolbar.titleResource: Int
get() = throw AnkoException("'android.support.v7.widget.Toolbar.titleResource' property does not have a getter")
set(v) = setTitle(v)
public val android.support.v7.widget.Toolbar.wrapper: android.support.v7.internal.widget.DecorToolbar?
get() = getWrapper()
public val android.support.v7.widget.Toolbar.overflowMenuShowPending: Boolean
get() = isOverflowMenuShowPending()
public val android.support.v7.widget.Toolbar.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public val android.support.v7.widget.Toolbar.titleTruncated: Boolean
get() = isTitleTruncated()
public val android.view.SurfaceView.holder: android.view.SurfaceHolder?
get() = getHolder()
public val android.view.TextureView.bitmap: android.graphics.Bitmap?
get() = getBitmap()
public val android.view.TextureView.layerType: Int
get() = getLayerType()
public var android.view.TextureView.surfaceTexture: android.graphics.SurfaceTexture?
get() = getSurfaceTexture()
set(v) = setSurfaceTexture(v)
public val android.view.TextureView.available: Boolean
get() = isAvailable()
public var android.view.TextureView.opaque: Boolean
get() = isOpaque()
set(v) = setOpaque(v)
public var android.view.View.alpha: Float
get() = getAlpha()
set(v) = setAlpha(v)
public var android.view.View.animation: android.view.animation.Animation?
get() = getAnimation()
set(v) = setAnimation(v)
public var android.view.View.backgroundTintList: android.content.res.ColorStateList?
get() = getBackgroundTintList()
set(v) = setBackgroundTintList(v)
public var android.view.View.backgroundTintMode: android.graphics.PorterDuff.Mode?
get() = getBackgroundTintMode()
set(v) = setBackgroundTintMode(v)
public val android.view.View.baseline: Int
get() = getBaseline()
public var android.view.View.bottom: Int
get() = getBottom()
set(v) = setBottom(v)
public var android.view.View.cameraDistance: Float
get() = getCameraDistance()
set(v) = setCameraDistance(v)
public var android.view.View.clipBounds: android.graphics.Rect?
get() = getClipBounds()
set(v) = setClipBounds(v)
public var android.view.View.clipToOutline: Boolean
get() = getClipToOutline()
set(v) = setClipToOutline(v)
public var android.view.View.contentDescription: CharSequence?
get() = getContentDescription()
set(v) = setContentDescription(v)
public val android.view.View.drawableState: IntArray
get() = getDrawableState()
public val android.view.View.drawingCache: android.graphics.Bitmap?
get() = getDrawingCache()
public var android.view.View.drawingCacheBackgroundColor: Int
get() = getDrawingCacheBackgroundColor()
set(v) = setDrawingCacheBackgroundColor(v)
public var android.view.View.drawingCacheQuality: Int
get() = getDrawingCacheQuality()
set(v) = setDrawingCacheQuality(v)
public val android.view.View.drawingTime: Long
get() = getDrawingTime()
public var android.view.View.elevation: Float
get() = getElevation()
set(v) = setElevation(v)
public var android.view.View.filterTouchesWhenObscured: Boolean
get() = getFilterTouchesWhenObscured()
set(v) = setFilterTouchesWhenObscured(v)
public var android.view.View.fitsSystemWindows: Boolean
get() = getFitsSystemWindows()
set(v) = setFitsSystemWindows(v)
public val android.view.View.height: Int
get() = getHeight()
public val android.view.View.horizontalFadingEdgeLength: Int
get() = getHorizontalFadingEdgeLength()
public var android.view.View.id: Int
get() = getId()
set(v) = setId(v)
public var android.view.View.importantForAccessibility: Int
get() = getImportantForAccessibility()
set(v) = setImportantForAccessibility(v)
public var android.view.View.keepScreenOn: Boolean
get() = getKeepScreenOn()
set(v) = setKeepScreenOn(v)
public var android.view.View.labelFor: Int
get() = getLabelFor()
set(v) = setLabelFor(v)
public val android.view.View.layerType: Int
get() = getLayerType()
public var android.view.View.layoutDirection: Int
get() = getLayoutDirection()
set(v) = setLayoutDirection(v)
public var android.view.View.layoutParams: android.view.ViewGroup.LayoutParams?
get() = getLayoutParams()
set(v) = setLayoutParams(v)
public var android.view.View.left: Int
get() = getLeft()
set(v) = setLeft(v)
public val android.view.View.matrix: android.graphics.Matrix?
get() = getMatrix()
public val android.view.View.measuredHeight: Int
get() = getMeasuredHeight()
public val android.view.View.measuredHeightAndState: Int
get() = getMeasuredHeightAndState()
public val android.view.View.measuredState: Int
get() = getMeasuredState()
public val android.view.View.measuredWidth: Int
get() = getMeasuredWidth()
public val android.view.View.measuredWidthAndState: Int
get() = getMeasuredWidthAndState()
public var android.view.View.minimumHeight: Int
get() = getMinimumHeight()
set(v) = setMinimumHeight(v)
public var android.view.View.minimumWidth: Int
get() = getMinimumWidth()
set(v) = setMinimumWidth(v)
public var android.view.View.outlineProvider: android.view.ViewOutlineProvider?
get() = getOutlineProvider()
set(v) = setOutlineProvider(v)
public var android.view.View.overScrollMode: Int
get() = getOverScrollMode()
set(v) = setOverScrollMode(v)
public val android.view.View.overlay: android.view.ViewOverlay?
get() = getOverlay()
public val android.view.View.paddingEnd: Int
get() = getPaddingEnd()
public val android.view.View.paddingStart: Int
get() = getPaddingStart()
public val android.view.View.parent: android.view.ViewParent?
get() = getParent()
public val android.view.View.parentForAccessibility: android.view.ViewParent?
get() = getParentForAccessibility()
public var android.view.View.pivotX: Float
get() = getPivotX()
set(v) = setPivotX(v)
public var android.view.View.pivotY: Float
get() = getPivotY()
set(v) = setPivotY(v)
public val android.view.View.resources: android.content.res.Resources?
get() = getResources()
public var android.view.View.right: Int
get() = getRight()
set(v) = setRight(v)
public val android.view.View.rootView: android.view.View?
get() = getRootView()
public var android.view.View.rotation: Float
get() = getRotation()
set(v) = setRotation(v)
public var android.view.View.rotationX: Float
get() = getRotationX()
set(v) = setRotationX(v)
public var android.view.View.rotationY: Float
get() = getRotationY()
set(v) = setRotationY(v)
public var android.view.View.scaleX: Float
get() = getScaleX()
set(v) = setScaleX(v)
public var android.view.View.scaleY: Float
get() = getScaleY()
set(v) = setScaleY(v)
public var android.view.View.scrollBarDefaultDelayBeforeFade: Int
get() = getScrollBarDefaultDelayBeforeFade()
set(v) = setScrollBarDefaultDelayBeforeFade(v)
public var android.view.View.scrollBarFadeDuration: Int
get() = getScrollBarFadeDuration()
set(v) = setScrollBarFadeDuration(v)
public var android.view.View.scrollBarSize: Int
get() = getScrollBarSize()
set(v) = setScrollBarSize(v)
public var android.view.View.scrollBarStyle: Int
get() = getScrollBarStyle()
set(v) = setScrollBarStyle(v)
public var android.view.View.scrollX: Int
get() = getScrollX()
set(v) = setScrollX(v)
public var android.view.View.scrollY: Int
get() = getScrollY()
set(v) = setScrollY(v)
public val android.view.View.solidColor: Int
get() = getSolidColor()
public var android.view.View.stateListAnimator: android.animation.StateListAnimator?
get() = getStateListAnimator()
set(v) = setStateListAnimator(v)
public var android.view.View.systemUiVisibility: Int
get() = getSystemUiVisibility()
set(v) = setSystemUiVisibility(v)
public var android.view.View.tag: Any?
get() = getTag()
set(v) = setTag(v)
public var android.view.View.textAlignment: Int
get() = getTextAlignment()
set(v) = setTextAlignment(v)
public var android.view.View.textDirection: Int
get() = getTextDirection()
set(v) = setTextDirection(v)
public var android.view.View.top: Int
get() = getTop()
set(v) = setTop(v)
public var android.view.View.touchDelegate: android.view.TouchDelegate?
get() = getTouchDelegate()
set(v) = setTouchDelegate(v)
public var android.view.View.transitionName: String?
get() = getTransitionName()
set(v) = setTransitionName(v)
public var android.view.View.translationX: Float
get() = getTranslationX()
set(v) = setTranslationX(v)
public var android.view.View.translationY: Float
get() = getTranslationY()
set(v) = setTranslationY(v)
public var android.view.View.translationZ: Float
get() = getTranslationZ()
set(v) = setTranslationZ(v)
public val android.view.View.verticalFadingEdgeLength: Int
get() = getVerticalFadingEdgeLength()
public var android.view.View.verticalScrollbarPosition: Int
get() = getVerticalScrollbarPosition()
set(v) = setVerticalScrollbarPosition(v)
public val android.view.View.verticalScrollbarWidth: Int
get() = getVerticalScrollbarWidth()
public val android.view.View.viewTreeObserver: android.view.ViewTreeObserver?
get() = getViewTreeObserver()
public var android.view.View.visibility: Int
get() = getVisibility()
set(v) = setVisibility(v)
public val android.view.View.width: Int
get() = getWidth()
public val android.view.View.windowId: android.view.WindowId?
get() = getWindowId()
public val android.view.View.windowSystemUiVisibility: Int
get() = getWindowSystemUiVisibility()
public val android.view.View.windowToken: android.os.IBinder?
get() = getWindowToken()
public val android.view.View.windowVisibility: Int
get() = getWindowVisibility()
public var android.view.View.x: Float
get() = getX()
set(v) = setX(v)
public var android.view.View.y: Float
get() = getY()
set(v) = setY(v)
public var android.view.View.z: Float
get() = getZ()
set(v) = setZ(v)
public val android.view.View.accessibilityFocused: Boolean
get() = isAccessibilityFocused()
public var android.view.View.activated: Boolean
get() = isActivated()
set(v) = setActivated(v)
public val android.view.View.attachedToWindow: Boolean
get() = isAttachedToWindow()
public var android.view.View.clickable: Boolean
get() = isClickable()
set(v) = setClickable(v)
public val android.view.View.dirty: Boolean
get() = isDirty()
public var android.view.View.drawingCacheEnabled: Boolean
get() = isDrawingCacheEnabled()
set(v) = setDrawingCacheEnabled(v)
public var android.view.View.duplicateParentStateEnabled: Boolean
get() = isDuplicateParentStateEnabled()
set(v) = setDuplicateParentStateEnabled(v)
public var android.view.View.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.view.View.focusable: Boolean
get() = isFocusable()
set(v) = setFocusable(v)
public var android.view.View.focusableInTouchMode: Boolean
get() = isFocusableInTouchMode()
set(v) = setFocusableInTouchMode(v)
public val android.view.View.focused: Boolean
get() = isFocused()
public var android.view.View.hapticFeedbackEnabled: Boolean
get() = isHapticFeedbackEnabled()
set(v) = setHapticFeedbackEnabled(v)
public val android.view.View.hardwareAccelerated: Boolean
get() = isHardwareAccelerated()
public var android.view.View.horizontalFadingEdgeEnabled: Boolean
get() = isHorizontalFadingEdgeEnabled()
set(v) = setHorizontalFadingEdgeEnabled(v)
public var android.view.View.horizontalScrollBarEnabled: Boolean
get() = isHorizontalScrollBarEnabled()
set(v) = setHorizontalScrollBarEnabled(v)
public var android.view.View.hovered: Boolean
get() = isHovered()
set(v) = setHovered(v)
public val android.view.View.inEditMode: Boolean
get() = isInEditMode()
public val android.view.View.inLayout: Boolean
get() = isInLayout()
public val android.view.View.inTouchMode: Boolean
get() = isInTouchMode()
public val android.view.View.laidOut: Boolean
get() = isLaidOut()
public val android.view.View.layoutDirectionResolved: Boolean
get() = isLayoutDirectionResolved()
public val android.view.View.layoutRequested: Boolean
get() = isLayoutRequested()
public var android.view.View.longClickable: Boolean
get() = isLongClickable()
set(v) = setLongClickable(v)
public var android.view.View.nestedScrollingEnabled: Boolean
get() = isNestedScrollingEnabled()
set(v) = setNestedScrollingEnabled(v)
public val android.view.View.opaque: Boolean
get() = isOpaque()
public val android.view.View.paddingRelative: Boolean
get() = isPaddingRelative()
public var android.view.View.pressed: Boolean
get() = isPressed()
set(v) = setPressed(v)
public var android.view.View.saveEnabled: Boolean
get() = isSaveEnabled()
set(v) = setSaveEnabled(v)
public var android.view.View.saveFromParentEnabled: Boolean
get() = isSaveFromParentEnabled()
set(v) = setSaveFromParentEnabled(v)
public var android.view.View.scrollContainer: Boolean
get() = isScrollContainer()
set(v) = setScrollContainer(v)
public var android.view.View.scrollbarFadingEnabled: Boolean
get() = isScrollbarFadingEnabled()
set(v) = setScrollbarFadingEnabled(v)
public var android.view.View.selected: Boolean
get() = isSelected()
set(v) = setSelected(v)
public val android.view.View.shown: Boolean
get() = isShown()
public var android.view.View.soundEffectsEnabled: Boolean
get() = isSoundEffectsEnabled()
set(v) = setSoundEffectsEnabled(v)
public val android.view.View.textAlignmentResolved: Boolean
get() = isTextAlignmentResolved()
public val android.view.View.textDirectionResolved: Boolean
get() = isTextDirectionResolved()
public var android.view.View.verticalFadingEdgeEnabled: Boolean
get() = isVerticalFadingEdgeEnabled()
set(v) = setVerticalFadingEdgeEnabled(v)
public var android.view.View.verticalScrollBarEnabled: Boolean
get() = isVerticalScrollBarEnabled()
set(v) = setVerticalScrollBarEnabled(v)
public var android.view.ViewGroup.clipChildren: Boolean
get() = getClipChildren()
set(v) = setClipChildren(v)
public var android.view.ViewGroup.clipToPadding: Boolean
get() = getClipToPadding()
set(v) = setClipToPadding(v)
public var android.view.ViewGroup.descendantFocusability: Int
get() = getDescendantFocusability()
set(v) = setDescendantFocusability(v)
public var android.view.ViewGroup.layoutAnimation: android.view.animation.LayoutAnimationController?
get() = getLayoutAnimation()
set(v) = setLayoutAnimation(v)
public var android.view.ViewGroup.layoutMode: Int
get() = getLayoutMode()
set(v) = setLayoutMode(v)
public var android.view.ViewGroup.layoutTransition: android.animation.LayoutTransition?
get() = getLayoutTransition()
set(v) = setLayoutTransition(v)
public var android.view.ViewGroup.persistentDrawingCache: Int
get() = getPersistentDrawingCache()
set(v) = setPersistentDrawingCache(v)
public var android.view.ViewGroup.touchscreenBlocksFocus: Boolean
get() = getTouchscreenBlocksFocus()
set(v) = setTouchscreenBlocksFocus(v)
public var android.view.ViewGroup.alwaysDrawnWithCacheEnabled: Boolean
get() = isAlwaysDrawnWithCacheEnabled()
set(v) = setAlwaysDrawnWithCacheEnabled(v)
public var android.view.ViewGroup.animationCacheEnabled: Boolean
get() = isAnimationCacheEnabled()
set(v) = setAnimationCacheEnabled(v)
public var android.view.ViewGroup.motionEventSplittingEnabled: Boolean
get() = isMotionEventSplittingEnabled()
set(v) = setMotionEventSplittingEnabled(v)
public var android.view.ViewGroup.transitionGroup: Boolean
get() = isTransitionGroup()
set(v) = setTransitionGroup(v)
public var android.view.ViewStub.inflatedId: Int
get() = getInflatedId()
set(v) = setInflatedId(v)
public var android.view.ViewStub.layoutInflater: android.view.LayoutInflater?
get() = getLayoutInflater()
set(v) = setLayoutInflater(v)
public var android.view.ViewStub.layoutResource: Int
get() = getLayoutResource()
set(v) = setLayoutResource(v)
public val android.webkit.WebView.contentHeight: Int
get() = getContentHeight()
public val android.webkit.WebView.favicon: android.graphics.Bitmap?
get() = getFavicon()
public val android.webkit.WebView.hitTestResult: android.webkit.WebView.HitTestResult?
get() = getHitTestResult()
public val android.webkit.WebView.originalUrl: String?
get() = getOriginalUrl()
public val android.webkit.WebView.progress: Int
get() = getProgress()
public val android.webkit.WebView.scale: Float
get() = getScale()
public val android.webkit.WebView.settings: android.webkit.WebSettings?
get() = getSettings()
public val android.webkit.WebView.title: String?
get() = getTitle()
public val android.webkit.WebView.url: String?
get() = getUrl()
public val android.webkit.WebView.privateBrowsingEnabled: Boolean
get() = isPrivateBrowsingEnabled()
public var android.widget.AbsListView.cacheColorHint: Int
get() = getCacheColorHint()
set(v) = setCacheColorHint(v)
public val android.widget.AbsListView.checkedItemIds: LongArray
get() = getCheckedItemIds()
public var android.widget.AbsListView.choiceMode: Int
get() = getChoiceMode()
set(v) = setChoiceMode(v)
public val android.widget.AbsListView.selectedView: android.view.View?
get() = getSelectedView()
public var android.widget.AbsListView.selector: android.graphics.drawable.Drawable?
get() = getSelector()
set(v) = setSelector(v)
public var android.widget.AbsListView.selectorResource: Int
get() = throw AnkoException("'android.widget.AbsListView.selectorResource' property does not have a getter")
set(v) = setSelector(v)
public var android.widget.AbsListView.transcriptMode: Int
get() = getTranscriptMode()
set(v) = setTranscriptMode(v)
public var android.widget.AbsListView.fastScrollAlwaysVisible: Boolean
get() = isFastScrollAlwaysVisible()
set(v) = setFastScrollAlwaysVisible(v)
public var android.widget.AbsListView.fastScrollEnabled: Boolean
get() = isFastScrollEnabled()
set(v) = setFastScrollEnabled(v)
public var android.widget.AbsListView.scrollingCacheEnabled: Boolean
get() = isScrollingCacheEnabled()
set(v) = setScrollingCacheEnabled(v)
public var android.widget.AbsListView.smoothScrollbarEnabled: Boolean
get() = isSmoothScrollbarEnabled()
set(v) = setSmoothScrollbarEnabled(v)
public var android.widget.AbsListView.stackFromBottom: Boolean
get() = isStackFromBottom()
set(v) = setStackFromBottom(v)
public var android.widget.AbsListView.textFilterEnabled: Boolean
get() = isTextFilterEnabled()
set(v) = setTextFilterEnabled(v)
public var android.widget.AbsSeekBar.keyProgressIncrement: Int
get() = getKeyProgressIncrement()
set(v) = setKeyProgressIncrement(v)
public var android.widget.AbsSeekBar.splitTrack: Boolean
get() = getSplitTrack()
set(v) = setSplitTrack(v)
public var android.widget.AbsSeekBar.thumb: android.graphics.drawable.Drawable?
get() = getThumb()
set(v) = setThumb(v)
public var android.widget.AbsSeekBar.thumbOffset: Int
get() = getThumbOffset()
set(v) = setThumbOffset(v)
public var android.widget.AbsSeekBar.thumbTintList: android.content.res.ColorStateList?
get() = getThumbTintList()
set(v) = setThumbTintList(v)
public var android.widget.AbsSeekBar.thumbTintMode: android.graphics.PorterDuff.Mode?
get() = getThumbTintMode()
set(v) = setThumbTintMode(v)
public val android.widget.ActionMenuView.menu: android.view.Menu?
get() = getMenu()
public var android.widget.ActionMenuView.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public val android.widget.ActionMenuView.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public var android.widget.AdapterView<out android.widget.Adapter?>.emptyView: android.view.View?
get() = getEmptyView()
set(v) = setEmptyView(v)
public val android.widget.AdapterView<out android.widget.Adapter?>.firstVisiblePosition: Int
get() = getFirstVisiblePosition()
public val android.widget.AdapterView<out android.widget.Adapter?>.lastVisiblePosition: Int
get() = getLastVisiblePosition()
public var android.widget.AdapterViewFlipper.flipInterval: Int
get() = getFlipInterval()
set(v) = setFlipInterval(v)
public var android.widget.AdapterViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.AdapterViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.AutoCompleteTextView.adapter: android.widget.ListAdapter?
get() = getAdapter()
public var android.widget.AutoCompleteTextView.completionHint: CharSequence?
get() = getCompletionHint()
set(v) = setCompletionHint(v)
public var android.widget.AutoCompleteTextView.dropDownAnchor: Int
get() = getDropDownAnchor()
set(v) = setDropDownAnchor(v)
public val android.widget.AutoCompleteTextView.dropDownBackground: android.graphics.drawable.Drawable?
get() = getDropDownBackground()
public var android.widget.AutoCompleteTextView.dropDownHeight: Int
get() = getDropDownHeight()
set(v) = setDropDownHeight(v)
public var android.widget.AutoCompleteTextView.dropDownHorizontalOffset: Int
get() = getDropDownHorizontalOffset()
set(v) = setDropDownHorizontalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownVerticalOffset: Int
get() = getDropDownVerticalOffset()
set(v) = setDropDownVerticalOffset(v)
public var android.widget.AutoCompleteTextView.dropDownWidth: Int
get() = getDropDownWidth()
set(v) = setDropDownWidth(v)
public var android.widget.AutoCompleteTextView.listSelection: Int
get() = getListSelection()
set(v) = setListSelection(v)
public var android.widget.AutoCompleteTextView.threshold: Int
get() = getThreshold()
set(v) = setThreshold(v)
public var android.widget.AutoCompleteTextView.validator: android.widget.AutoCompleteTextView.Validator?
get() = getValidator()
set(v) = setValidator(v)
public val android.widget.AutoCompleteTextView.performingCompletion: Boolean
get() = isPerformingCompletion()
public val android.widget.AutoCompleteTextView.popupShowing: Boolean
get() = isPopupShowing()
public var android.widget.CalendarView.date: Long
get() = getDate()
set(v) = setDate(v)
public var android.widget.CalendarView.dateTextAppearance: Int
get() = getDateTextAppearance()
set(v) = setDateTextAppearance(v)
public var android.widget.CalendarView.firstDayOfWeek: Int
get() = getFirstDayOfWeek()
set(v) = setFirstDayOfWeek(v)
public var android.widget.CalendarView.focusedMonthDateColor: Int
get() = getFocusedMonthDateColor()
set(v) = setFocusedMonthDateColor(v)
public var android.widget.CalendarView.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.CalendarView.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public var android.widget.CalendarView.selectedDateVerticalBar: android.graphics.drawable.Drawable?
get() = getSelectedDateVerticalBar()
set(v) = setSelectedDateVerticalBar(v)
public var android.widget.CalendarView.selectedDateVerticalBarResource: Int
get() = throw AnkoException("'android.widget.CalendarView.selectedDateVerticalBarResource' property does not have a getter")
set(v) = setSelectedDateVerticalBar(v)
public var android.widget.CalendarView.selectedWeekBackgroundColor: Int
get() = getSelectedWeekBackgroundColor()
set(v) = setSelectedWeekBackgroundColor(v)
public var android.widget.CalendarView.showWeekNumber: Boolean
get() = getShowWeekNumber()
set(v) = setShowWeekNumber(v)
public var android.widget.CalendarView.shownWeekCount: Int
get() = getShownWeekCount()
set(v) = setShownWeekCount(v)
public var android.widget.CalendarView.unfocusedMonthDateColor: Int
get() = getUnfocusedMonthDateColor()
set(v) = setUnfocusedMonthDateColor(v)
public var android.widget.CalendarView.weekDayTextAppearance: Int
get() = getWeekDayTextAppearance()
set(v) = setWeekDayTextAppearance(v)
public var android.widget.CalendarView.weekNumberColor: Int
get() = getWeekNumberColor()
set(v) = setWeekNumberColor(v)
public var android.widget.CalendarView.weekSeparatorLineColor: Int
get() = getWeekSeparatorLineColor()
set(v) = setWeekSeparatorLineColor(v)
public var android.widget.CalendarView.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.CheckedTextView.checkMarkDrawable: android.graphics.drawable.Drawable?
get() = getCheckMarkDrawable()
set(v) = setCheckMarkDrawable(v)
public var android.widget.CheckedTextView.checkMarkDrawableResource: Int
get() = throw AnkoException("'android.widget.CheckedTextView.checkMarkDrawableResource' property does not have a getter")
set(v) = setCheckMarkDrawable(v)
public var android.widget.CheckedTextView.checkMarkTintList: android.content.res.ColorStateList?
get() = getCheckMarkTintList()
set(v) = setCheckMarkTintList(v)
public var android.widget.CheckedTextView.checkMarkTintMode: android.graphics.PorterDuff.Mode?
get() = getCheckMarkTintMode()
set(v) = setCheckMarkTintMode(v)
public var android.widget.CheckedTextView.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public var android.widget.Chronometer.base: Long
get() = getBase()
set(v) = setBase(v)
public var android.widget.Chronometer.format: String?
get() = getFormat()
set(v) = setFormat(v)
public var android.widget.CompoundButton.buttonTintList: android.content.res.ColorStateList?
get() = getButtonTintList()
set(v) = setButtonTintList(v)
public var android.widget.CompoundButton.buttonTintMode: android.graphics.PorterDuff.Mode?
get() = getButtonTintMode()
set(v) = setButtonTintMode(v)
public val android.widget.CompoundButton.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.widget.CompoundButton.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.widget.CompoundButton.checked: Boolean
get() = isChecked()
set(v) = setChecked(v)
public val android.widget.DatePicker.calendarView: android.widget.CalendarView?
get() = getCalendarView()
public var android.widget.DatePicker.calendarViewShown: Boolean
get() = getCalendarViewShown()
set(v) = setCalendarViewShown(v)
public val android.widget.DatePicker.dayOfMonth: Int
get() = getDayOfMonth()
public var android.widget.DatePicker.firstDayOfWeek: Int
get() = getFirstDayOfWeek()
set(v) = setFirstDayOfWeek(v)
public var android.widget.DatePicker.maxDate: Long
get() = getMaxDate()
set(v) = setMaxDate(v)
public var android.widget.DatePicker.minDate: Long
get() = getMinDate()
set(v) = setMinDate(v)
public val android.widget.DatePicker.month: Int
get() = getMonth()
public var android.widget.DatePicker.spinnersShown: Boolean
get() = getSpinnersShown()
set(v) = setSpinnersShown(v)
public val android.widget.DatePicker.year: Int
get() = getYear()
public var android.widget.DatePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public val android.widget.DialerFilter.digits: CharSequence?
get() = getDigits()
public val android.widget.DialerFilter.filterText: CharSequence?
get() = getFilterText()
public val android.widget.DialerFilter.letters: CharSequence?
get() = getLetters()
public var android.widget.DialerFilter.mode: Int
get() = getMode()
set(v) = setMode(v)
public val android.widget.DialerFilter.qwertyKeyboard: Boolean
get() = isQwertyKeyboard()
public var android.widget.ExpandableListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ExpandableListView.expandableListAdapter: android.widget.ExpandableListAdapter?
get() = getExpandableListAdapter()
public val android.widget.ExpandableListView.selectedId: Long
get() = getSelectedId()
public val android.widget.ExpandableListView.selectedPosition: Long
get() = getSelectedPosition()
public val android.widget.FrameLayout.considerGoneChildrenWhenMeasuring: Boolean
get() = getConsiderGoneChildrenWhenMeasuring()
public var android.widget.FrameLayout.foreground: android.graphics.drawable.Drawable?
get() = getForeground()
set(v) = setForeground(v)
public var android.widget.FrameLayout.foregroundGravity: Int
get() = getForegroundGravity()
set(v) = setForegroundGravity(v)
public var android.widget.FrameLayout.foregroundTintList: android.content.res.ColorStateList?
get() = getForegroundTintList()
set(v) = setForegroundTintList(v)
public var android.widget.FrameLayout.foregroundTintMode: android.graphics.PorterDuff.Mode?
get() = getForegroundTintMode()
set(v) = setForegroundTintMode(v)
public var android.widget.FrameLayout.measureAllChildren: Boolean
get() = getMeasureAllChildren()
set(v) = setMeasureAllChildren(v)
public var android.widget.GridLayout.alignmentMode: Int
get() = getAlignmentMode()
set(v) = setAlignmentMode(v)
public var android.widget.GridLayout.columnCount: Int
get() = getColumnCount()
set(v) = setColumnCount(v)
public var android.widget.GridLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.GridLayout.rowCount: Int
get() = getRowCount()
set(v) = setRowCount(v)
public var android.widget.GridLayout.useDefaultMargins: Boolean
get() = getUseDefaultMargins()
set(v) = setUseDefaultMargins(v)
public var android.widget.GridLayout.columnOrderPreserved: Boolean
get() = isColumnOrderPreserved()
set(v) = setColumnOrderPreserved(v)
public var android.widget.GridLayout.rowOrderPreserved: Boolean
get() = isRowOrderPreserved()
set(v) = setRowOrderPreserved(v)
public var android.widget.GridView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public var android.widget.GridView.columnWidth: Int
get() = getColumnWidth()
set(v) = setColumnWidth(v)
public var android.widget.GridView.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public var android.widget.GridView.horizontalSpacing: Int
get() = getHorizontalSpacing()
set(v) = setHorizontalSpacing(v)
public var android.widget.GridView.numColumns: Int
get() = getNumColumns()
set(v) = setNumColumns(v)
public val android.widget.GridView.requestedColumnWidth: Int
get() = getRequestedColumnWidth()
public val android.widget.GridView.requestedHorizontalSpacing: Int
get() = getRequestedHorizontalSpacing()
public var android.widget.GridView.stretchMode: Int
get() = getStretchMode()
set(v) = setStretchMode(v)
public var android.widget.GridView.verticalSpacing: Int
get() = getVerticalSpacing()
set(v) = setVerticalSpacing(v)
public val android.widget.HorizontalScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.HorizontalScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.HorizontalScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.widget.ImageView.adjustViewBounds: Boolean
get() = getAdjustViewBounds()
set(v) = setAdjustViewBounds(v)
public var android.widget.ImageView.baseline: Int
get() = getBaseline()
set(v) = setBaseline(v)
public var android.widget.ImageView.baselineAlignBottom: Boolean
get() = getBaselineAlignBottom()
set(v) = setBaselineAlignBottom(v)
public var android.widget.ImageView.colorFilter: android.graphics.ColorFilter?
get() = getColorFilter()
set(v) = setColorFilter(v)
public var android.widget.ImageView.cropToPadding: Boolean
get() = getCropToPadding()
set(v) = setCropToPadding(v)
public var android.widget.ImageView.imageAlpha: Int
get() = getImageAlpha()
set(v) = setImageAlpha(v)
public var android.widget.ImageView.imageMatrix: android.graphics.Matrix?
get() = getImageMatrix()
set(v) = setImageMatrix(v)
public var android.widget.ImageView.imageTintList: android.content.res.ColorStateList?
get() = getImageTintList()
set(v) = setImageTintList(v)
public var android.widget.ImageView.imageTintMode: android.graphics.PorterDuff.Mode?
get() = getImageTintMode()
set(v) = setImageTintMode(v)
public var android.widget.ImageView.maxHeight: Int
get() = getMaxHeight()
set(v) = setMaxHeight(v)
public var android.widget.ImageView.maxWidth: Int
get() = getMaxWidth()
set(v) = setMaxWidth(v)
public var android.widget.ImageView.scaleType: android.widget.ImageView.ScaleType?
get() = getScaleType()
set(v) = setScaleType(v)
public val android.widget.ImageView.opaque: Boolean
get() = isOpaque()
public val android.widget.LinearLayout.baseline: Int
get() = getBaseline()
public var android.widget.LinearLayout.baselineAlignedChildIndex: Int
get() = getBaselineAlignedChildIndex()
set(v) = setBaselineAlignedChildIndex(v)
public var android.widget.LinearLayout.dividerDrawable: android.graphics.drawable.Drawable?
get() = getDividerDrawable()
set(v) = setDividerDrawable(v)
public var android.widget.LinearLayout.dividerPadding: Int
get() = getDividerPadding()
set(v) = setDividerPadding(v)
public var android.widget.LinearLayout.orientation: Int
get() = getOrientation()
set(v) = setOrientation(v)
public var android.widget.LinearLayout.showDividers: Int
get() = getShowDividers()
set(v) = setShowDividers(v)
public var android.widget.LinearLayout.weightSum: Float
get() = getWeightSum()
set(v) = setWeightSum(v)
public var android.widget.LinearLayout.baselineAligned: Boolean
get() = isBaselineAligned()
set(v) = setBaselineAligned(v)
public var android.widget.LinearLayout.measureWithLargestChildEnabled: Boolean
get() = isMeasureWithLargestChildEnabled()
set(v) = setMeasureWithLargestChildEnabled(v)
public var android.widget.ListView.adapter: android.widget.ListAdapter?
get() = getAdapter()
set(v) = setAdapter(v)
public val android.widget.ListView.checkItemIds: LongArray
get() = getCheckItemIds()
public var android.widget.ListView.divider: android.graphics.drawable.Drawable?
get() = getDivider()
set(v) = setDivider(v)
public var android.widget.ListView.dividerHeight: Int
get() = getDividerHeight()
set(v) = setDividerHeight(v)
public val android.widget.ListView.footerViewsCount: Int
get() = getFooterViewsCount()
public val android.widget.ListView.headerViewsCount: Int
get() = getHeaderViewsCount()
public var android.widget.ListView.itemsCanFocus: Boolean
get() = getItemsCanFocus()
set(v) = setItemsCanFocus(v)
public val android.widget.ListView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ListView.overscrollFooter: android.graphics.drawable.Drawable?
get() = getOverscrollFooter()
set(v) = setOverscrollFooter(v)
public var android.widget.ListView.overscrollHeader: android.graphics.drawable.Drawable?
get() = getOverscrollHeader()
set(v) = setOverscrollHeader(v)
public val android.widget.ListView.opaque: Boolean
get() = isOpaque()
public val android.widget.NumberPicker.accessibilityNodeProvider: android.view.accessibility.AccessibilityNodeProvider?
get() = getAccessibilityNodeProvider()
public var android.widget.NumberPicker.displayedValues: Array<String>?
get() = getDisplayedValues()
set(v) = setDisplayedValues(v)
public var android.widget.NumberPicker.maxValue: Int
get() = getMaxValue()
set(v) = setMaxValue(v)
public var android.widget.NumberPicker.minValue: Int
get() = getMinValue()
set(v) = setMinValue(v)
public val android.widget.NumberPicker.solidColor: Int
get() = getSolidColor()
public var android.widget.NumberPicker.value: Int
get() = getValue()
set(v) = setValue(v)
public var android.widget.NumberPicker.wrapSelectorWheel: Boolean
get() = getWrapSelectorWheel()
set(v) = setWrapSelectorWheel(v)
public var android.widget.ProgressBar.indeterminateDrawable: android.graphics.drawable.Drawable?
get() = getIndeterminateDrawable()
set(v) = setIndeterminateDrawable(v)
public var android.widget.ProgressBar.indeterminateTintList: android.content.res.ColorStateList?
get() = getIndeterminateTintList()
set(v) = setIndeterminateTintList(v)
public var android.widget.ProgressBar.indeterminateTintMode: android.graphics.PorterDuff.Mode?
get() = getIndeterminateTintMode()
set(v) = setIndeterminateTintMode(v)
public var android.widget.ProgressBar.interpolator: android.view.animation.Interpolator?
get() = getInterpolator()
set(v) = setInterpolator(v)
public var android.widget.ProgressBar.max: Int
get() = getMax()
set(v) = setMax(v)
public var android.widget.ProgressBar.progress: Int
get() = getProgress()
set(v) = setProgress(v)
public var android.widget.ProgressBar.progressBackgroundTintList: android.content.res.ColorStateList?
get() = getProgressBackgroundTintList()
set(v) = setProgressBackgroundTintList(v)
public var android.widget.ProgressBar.progressBackgroundTintMode: android.graphics.PorterDuff.Mode?
get() = getProgressBackgroundTintMode()
set(v) = setProgressBackgroundTintMode(v)
public var android.widget.ProgressBar.progressDrawable: android.graphics.drawable.Drawable?
get() = getProgressDrawable()
set(v) = setProgressDrawable(v)
public var android.widget.ProgressBar.progressTintList: android.content.res.ColorStateList?
get() = getProgressTintList()
set(v) = setProgressTintList(v)
public var android.widget.ProgressBar.progressTintMode: android.graphics.PorterDuff.Mode?
get() = getProgressTintMode()
set(v) = setProgressTintMode(v)
public var android.widget.ProgressBar.secondaryProgress: Int
get() = getSecondaryProgress()
set(v) = setSecondaryProgress(v)
public var android.widget.ProgressBar.secondaryProgressTintList: android.content.res.ColorStateList?
get() = getSecondaryProgressTintList()
set(v) = setSecondaryProgressTintList(v)
public var android.widget.ProgressBar.secondaryProgressTintMode: android.graphics.PorterDuff.Mode?
get() = getSecondaryProgressTintMode()
set(v) = setSecondaryProgressTintMode(v)
public var android.widget.ProgressBar.indeterminate: Boolean
get() = isIndeterminate()
set(v) = setIndeterminate(v)
public var android.widget.RatingBar.numStars: Int
get() = getNumStars()
set(v) = setNumStars(v)
public var android.widget.RatingBar.rating: Float
get() = getRating()
set(v) = setRating(v)
public var android.widget.RatingBar.stepSize: Float
get() = getStepSize()
set(v) = setStepSize(v)
public val android.widget.RatingBar.indicator: Boolean
get() = isIndicator()
public val android.widget.RelativeLayout.baseline: Int
get() = getBaseline()
public var android.widget.RelativeLayout.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public val android.widget.ScrollView.maxScrollAmount: Int
get() = getMaxScrollAmount()
public var android.widget.ScrollView.fillViewport: Boolean
get() = isFillViewport()
set(v) = setFillViewport(v)
public var android.widget.ScrollView.smoothScrollingEnabled: Boolean
get() = isSmoothScrollingEnabled()
set(v) = setSmoothScrollingEnabled(v)
public var android.widget.SearchView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.widget.SearchView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public var android.widget.SearchView.maxWidth: Int
get() = getMaxWidth()
set(v) = setMaxWidth(v)
public val android.widget.SearchView.query: CharSequence?
get() = getQuery()
public var android.widget.SearchView.queryHint: CharSequence?
get() = getQueryHint()
set(v) = setQueryHint(v)
public var android.widget.SearchView.suggestionsAdapter: android.widget.CursorAdapter?
get() = getSuggestionsAdapter()
set(v) = setSuggestionsAdapter(v)
public val android.widget.SearchView.iconfiedByDefault: Boolean
get() = isIconfiedByDefault()
public var android.widget.SearchView.iconified: Boolean
get() = isIconified()
set(v) = setIconified(v)
public var android.widget.SearchView.queryRefinementEnabled: Boolean
get() = isQueryRefinementEnabled()
set(v) = setQueryRefinementEnabled(v)
public var android.widget.SearchView.submitButtonEnabled: Boolean
get() = isSubmitButtonEnabled()
set(v) = setSubmitButtonEnabled(v)
public val android.widget.SlidingDrawer.content: android.view.View?
get() = getContent()
public val android.widget.SlidingDrawer.handle: android.view.View?
get() = getHandle()
public val android.widget.SlidingDrawer.moving: Boolean
get() = isMoving()
public val android.widget.SlidingDrawer.opened: Boolean
get() = isOpened()
public val android.widget.Spinner.baseline: Int
get() = getBaseline()
public var android.widget.Spinner.dropDownHorizontalOffset: Int
get() = getDropDownHorizontalOffset()
set(v) = setDropDownHorizontalOffset(v)
public var android.widget.Spinner.dropDownVerticalOffset: Int
get() = getDropDownVerticalOffset()
set(v) = setDropDownVerticalOffset(v)
public var android.widget.Spinner.dropDownWidth: Int
get() = getDropDownWidth()
set(v) = setDropDownWidth(v)
public var android.widget.Spinner.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public val android.widget.Spinner.popupBackground: android.graphics.drawable.Drawable?
get() = getPopupBackground()
public var android.widget.Spinner.prompt: CharSequence?
get() = getPrompt()
set(v) = setPrompt(v)
public val android.widget.Switch.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.widget.Switch.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public var android.widget.Switch.showText: Boolean
get() = getShowText()
set(v) = setShowText(v)
public var android.widget.Switch.splitTrack: Boolean
get() = getSplitTrack()
set(v) = setSplitTrack(v)
public var android.widget.Switch.switchMinWidth: Int
get() = getSwitchMinWidth()
set(v) = setSwitchMinWidth(v)
public var android.widget.Switch.switchPadding: Int
get() = getSwitchPadding()
set(v) = setSwitchPadding(v)
public var android.widget.Switch.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.Switch.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.widget.Switch.thumbDrawable: android.graphics.drawable.Drawable?
get() = getThumbDrawable()
set(v) = setThumbDrawable(v)
public var android.widget.Switch.thumbTextPadding: Int
get() = getThumbTextPadding()
set(v) = setThumbTextPadding(v)
public var android.widget.Switch.trackDrawable: android.graphics.drawable.Drawable?
get() = getTrackDrawable()
set(v) = setTrackDrawable(v)
public var android.widget.TabHost.currentTab: Int
get() = getCurrentTab()
set(v) = setCurrentTab(v)
public val android.widget.TabHost.currentTabTag: String?
get() = getCurrentTabTag()
public val android.widget.TabHost.currentTabView: android.view.View?
get() = getCurrentTabView()
public val android.widget.TabHost.currentView: android.view.View?
get() = getCurrentView()
public val android.widget.TabHost.tabContentView: android.widget.FrameLayout?
get() = getTabContentView()
public val android.widget.TabHost.tabWidget: android.widget.TabWidget?
get() = getTabWidget()
public val android.widget.TabWidget.tabCount: Int
get() = getTabCount()
public var android.widget.TabWidget.stripEnabled: Boolean
get() = isStripEnabled()
set(v) = setStripEnabled(v)
public var android.widget.TableLayout.shrinkAllColumns: Boolean
get() = isShrinkAllColumns()
set(v) = setShrinkAllColumns(v)
public var android.widget.TableLayout.stretchAllColumns: Boolean
get() = isStretchAllColumns()
set(v) = setStretchAllColumns(v)
public val android.widget.TableRow.virtualChildCount: Int
get() = getVirtualChildCount()
public var android.widget.TextClock.format12Hour: CharSequence?
get() = getFormat12Hour()
set(v) = setFormat12Hour(v)
public var android.widget.TextClock.format24Hour: CharSequence?
get() = getFormat24Hour()
set(v) = setFormat24Hour(v)
public var android.widget.TextClock.timeZone: String?
get() = getTimeZone()
set(v) = setTimeZone(v)
public var android.widget.TextView.autoLinkMask: Int
get() = getAutoLinkMask()
set(v) = setAutoLinkMask(v)
public val android.widget.TextView.baseline: Int
get() = getBaseline()
public var android.widget.TextView.compoundDrawablePadding: Int
get() = getCompoundDrawablePadding()
set(v) = setCompoundDrawablePadding(v)
public val android.widget.TextView.compoundDrawables: Array<android.graphics.drawable.Drawable>?
get() = getCompoundDrawables()
public val android.widget.TextView.compoundDrawablesRelative: Array<android.graphics.drawable.Drawable>?
get() = getCompoundDrawablesRelative()
public val android.widget.TextView.compoundPaddingBottom: Int
get() = getCompoundPaddingBottom()
public val android.widget.TextView.compoundPaddingEnd: Int
get() = getCompoundPaddingEnd()
public val android.widget.TextView.compoundPaddingLeft: Int
get() = getCompoundPaddingLeft()
public val android.widget.TextView.compoundPaddingRight: Int
get() = getCompoundPaddingRight()
public val android.widget.TextView.compoundPaddingStart: Int
get() = getCompoundPaddingStart()
public val android.widget.TextView.compoundPaddingTop: Int
get() = getCompoundPaddingTop()
public val android.widget.TextView.currentHintTextColor: Int
get() = getCurrentHintTextColor()
public val android.widget.TextView.currentTextColor: Int
get() = getCurrentTextColor()
public var android.widget.TextView.customSelectionActionModeCallback: android.view.ActionMode.Callback?
get() = getCustomSelectionActionModeCallback()
set(v) = setCustomSelectionActionModeCallback(v)
public val android.widget.TextView.editableText: android.text.Editable?
get() = getEditableText()
public var android.widget.TextView.ellipsize: android.text.TextUtils.TruncateAt?
get() = getEllipsize()
set(v) = setEllipsize(v)
public var android.widget.TextView.error: CharSequence?
get() = getError()
set(v) = setError(v)
public val android.widget.TextView.extendedPaddingBottom: Int
get() = getExtendedPaddingBottom()
public val android.widget.TextView.extendedPaddingTop: Int
get() = getExtendedPaddingTop()
public var android.widget.TextView.filters: Array<android.text.InputFilter>?
get() = getFilters()
set(v) = setFilters(v)
public var android.widget.TextView.fontFeatureSettings: String?
get() = getFontFeatureSettings()
set(v) = setFontFeatureSettings(v)
public var android.widget.TextView.freezesText: Boolean
get() = getFreezesText()
set(v) = setFreezesText(v)
public var android.widget.TextView.gravity: Int
get() = getGravity()
set(v) = setGravity(v)
public var android.widget.TextView.highlightColor: Int
get() = getHighlightColor()
set(v) = setHighlightColor(v)
public var android.widget.TextView.hint: CharSequence?
get() = getHint()
set(v) = setHint(v)
public var android.widget.TextView.hintResource: Int
get() = throw AnkoException("'android.widget.TextView.hintResource' property does not have a getter")
set(v) = setHint(v)
public val android.widget.TextView.hintTextColors: android.content.res.ColorStateList?
get() = getHintTextColors()
public val android.widget.TextView.imeActionId: Int
get() = getImeActionId()
public val android.widget.TextView.imeActionLabel: CharSequence?
get() = getImeActionLabel()
public var android.widget.TextView.imeOptions: Int
get() = getImeOptions()
set(v) = setImeOptions(v)
public var android.widget.TextView.includeFontPadding: Boolean
get() = getIncludeFontPadding()
set(v) = setIncludeFontPadding(v)
public var android.widget.TextView.inputType: Int
get() = getInputType()
set(v) = setInputType(v)
public val android.widget.TextView.layout: android.text.Layout?
get() = getLayout()
public var android.widget.TextView.letterSpacing: Float
get() = getLetterSpacing()
set(v) = setLetterSpacing(v)
public val android.widget.TextView.lineCount: Int
get() = getLineCount()
public val android.widget.TextView.lineHeight: Int
get() = getLineHeight()
public val android.widget.TextView.lineSpacingExtra: Float
get() = getLineSpacingExtra()
public val android.widget.TextView.lineSpacingMultiplier: Float
get() = getLineSpacingMultiplier()
public val android.widget.TextView.linkTextColors: android.content.res.ColorStateList?
get() = getLinkTextColors()
public var android.widget.TextView.linksClickable: Boolean
get() = getLinksClickable()
set(v) = setLinksClickable(v)
public var android.widget.TextView.marqueeRepeatLimit: Int
get() = getMarqueeRepeatLimit()
set(v) = setMarqueeRepeatLimit(v)
public var android.widget.TextView.maxEms: Int
get() = getMaxEms()
set(v) = setMaxEms(v)
public var android.widget.TextView.maxHeight: Int
get() = getMaxHeight()
set(v) = setMaxHeight(v)
public var android.widget.TextView.maxLines: Int
get() = getMaxLines()
set(v) = setMaxLines(v)
public var android.widget.TextView.maxWidth: Int
get() = getMaxWidth()
set(v) = setMaxWidth(v)
public var android.widget.TextView.minEms: Int
get() = getMinEms()
set(v) = setMinEms(v)
public var android.widget.TextView.minHeight: Int
get() = getMinHeight()
set(v) = setMinHeight(v)
public var android.widget.TextView.minLines: Int
get() = getMinLines()
set(v) = setMinLines(v)
public var android.widget.TextView.minWidth: Int
get() = getMinWidth()
set(v) = setMinWidth(v)
public var android.widget.TextView.movementMethod: android.text.method.MovementMethod?
get() = getMovementMethod()
set(v) = setMovementMethod(v)
public val android.widget.TextView.paint: android.text.TextPaint
get() = getPaint()
public var android.widget.TextView.paintFlags: Int
get() = getPaintFlags()
set(v) = setPaintFlags(v)
public var android.widget.TextView.privateImeOptions: String?
get() = getPrivateImeOptions()
set(v) = setPrivateImeOptions(v)
public val android.widget.TextView.selectionEnd: Int
get() = getSelectionEnd()
public val android.widget.TextView.selectionStart: Int
get() = getSelectionStart()
public val android.widget.TextView.shadowColor: Int
get() = getShadowColor()
public val android.widget.TextView.shadowDx: Float
get() = getShadowDx()
public val android.widget.TextView.shadowDy: Float
get() = getShadowDy()
public val android.widget.TextView.shadowRadius: Float
get() = getShadowRadius()
public var android.widget.TextView.showSoftInputOnFocus: Boolean
get() = getShowSoftInputOnFocus()
set(v) = setShowSoftInputOnFocus(v)
public var android.widget.TextView.text: CharSequence
get() = getText()
set(v) = setText(v)
public var android.widget.TextView.textResource: Int
get() = throw AnkoException("'android.widget.TextView.textResource' property does not have a getter")
set(v) = setText(v)
public val android.widget.TextView.textColors: android.content.res.ColorStateList?
get() = getTextColors()
public var android.widget.TextView.textLocale: java.util.Locale?
get() = getTextLocale()
set(v) = setTextLocale(v)
public var android.widget.TextView.textScaleX: Float
get() = getTextScaleX()
set(v) = setTextScaleX(v)
public var android.widget.TextView.textSize: Float
get() = getTextSize()
set(v) = setTextSize(v)
public var android.widget.TextView.transformationMethod: android.text.method.TransformationMethod?
get() = getTransformationMethod()
set(v) = setTransformationMethod(v)
public var android.widget.TextView.typeface: android.graphics.Typeface?
get() = getTypeface()
set(v) = setTypeface(v)
public val android.widget.TextView.urls: Array<android.text.style.URLSpan>?
get() = getUrls()
public var android.widget.TextView.cursorVisible: Boolean
get() = isCursorVisible()
set(v) = setCursorVisible(v)
public val android.widget.TextView.inputMethodTarget: Boolean
get() = isInputMethodTarget()
public val android.widget.TextView.suggestionsEnabled: Boolean
get() = isSuggestionsEnabled()
public val android.widget.TimePicker.baseline: Int
get() = getBaseline()
public var android.widget.TimePicker.currentHour: Int?
get() = getCurrentHour()
set(v) = setCurrentHour(v)
public var android.widget.TimePicker.currentMinute: Int?
get() = getCurrentMinute()
set(v) = setCurrentMinute(v)
public var android.widget.TimePicker.enabled: Boolean
get() = isEnabled()
set(v) = setEnabled(v)
public var android.widget.ToggleButton.textOff: CharSequence?
get() = getTextOff()
set(v) = setTextOff(v)
public var android.widget.ToggleButton.textOn: CharSequence?
get() = getTextOn()
set(v) = setTextOn(v)
public var android.widget.Toolbar.logo: android.graphics.drawable.Drawable?
get() = getLogo()
set(v) = setLogo(v)
public var android.widget.Toolbar.logoResource: Int
get() = throw AnkoException("'android.widget.Toolbar.logoResource' property does not have a getter")
set(v) = setLogo(v)
public var android.widget.Toolbar.logoDescription: CharSequence?
get() = getLogoDescription()
set(v) = setLogoDescription(v)
public var android.widget.Toolbar.logoDescriptionResource: Int
get() = throw AnkoException("'android.widget.Toolbar.logoDescriptionResource' property does not have a getter")
set(v) = setLogoDescription(v)
public val android.widget.Toolbar.menu: android.view.Menu?
get() = getMenu()
public var android.widget.Toolbar.navigationContentDescription: CharSequence?
get() = getNavigationContentDescription()
set(v) = setNavigationContentDescription(v)
public var android.widget.Toolbar.navigationContentDescriptionResource: Int
get() = throw AnkoException("'android.widget.Toolbar.navigationContentDescriptionResource' property does not have a getter")
set(v) = setNavigationContentDescription(v)
public var android.widget.Toolbar.navigationIcon: android.graphics.drawable.Drawable?
get() = getNavigationIcon()
set(v) = setNavigationIcon(v)
public var android.widget.Toolbar.navigationIconResource: Int
get() = throw AnkoException("'android.widget.Toolbar.navigationIconResource' property does not have a getter")
set(v) = setNavigationIcon(v)
public var android.widget.Toolbar.popupTheme: Int
get() = getPopupTheme()
set(v) = setPopupTheme(v)
public var android.widget.Toolbar.subtitle: CharSequence?
get() = getSubtitle()
set(v) = setSubtitle(v)
public var android.widget.Toolbar.subtitleResource: Int
get() = throw AnkoException("'android.widget.Toolbar.subtitleResource' property does not have a getter")
set(v) = setSubtitle(v)
public var android.widget.Toolbar.title: CharSequence?
get() = getTitle()
set(v) = setTitle(v)
public var android.widget.Toolbar.titleResource: Int
get() = throw AnkoException("'android.widget.Toolbar.titleResource' property does not have a getter")
set(v) = setTitle(v)
public val android.widget.Toolbar.overflowMenuShowing: Boolean
get() = isOverflowMenuShowing()
public val android.widget.TwoLineListItem.text1: android.widget.TextView?
get() = getText1()
public val android.widget.TwoLineListItem.text2: android.widget.TextView?
get() = getText2()
public val android.widget.VideoView.audioSessionId: Int
get() = getAudioSessionId()
public val android.widget.VideoView.bufferPercentage: Int
get() = getBufferPercentage()
public val android.widget.VideoView.currentPosition: Int
get() = getCurrentPosition()
public val android.widget.VideoView.duration: Int
get() = getDuration()
public val android.widget.VideoView.playing: Boolean
get() = isPlaying()
public var android.widget.ViewAnimator.animateFirstView: Boolean
get() = getAnimateFirstView()
set(v) = setAnimateFirstView(v)
public val android.widget.ViewAnimator.baseline: Int
get() = getBaseline()
public val android.widget.ViewAnimator.currentView: android.view.View?
get() = getCurrentView()
public var android.widget.ViewAnimator.displayedChild: Int
get() = getDisplayedChild()
set(v) = setDisplayedChild(v)
public var android.widget.ViewAnimator.inAnimation: android.view.animation.Animation?
get() = getInAnimation()
set(v) = setInAnimation(v)
public var android.widget.ViewAnimator.outAnimation: android.view.animation.Animation?
get() = getOutAnimation()
set(v) = setOutAnimation(v)
public var android.widget.ViewFlipper.autoStart: Boolean
get() = isAutoStart()
set(v) = setAutoStart(v)
public val android.widget.ViewFlipper.flipping: Boolean
get() = isFlipping()
public val android.widget.ViewSwitcher.nextView: android.view.View?
get() = getNextView()
public var android.widget.ImageView.imageURI: android.net.Uri?
get() = throw AnkoException("'android.widget.ImageView.imageURI' property does not have a getter")
set(v) = setImageURI(v)
public var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
get() = throw AnkoException("'android.widget.ImageView.imageBitmap' property does not have a getter")
set(v) = setImageBitmap(v)
public var android.widget.TextView.enabled: Boolean
get() = throw AnkoException("'android.widget.TextView.enabled' property does not have a getter")
set(v) = setEnabled(v)
public var android.widget.TextView.textColor: Int
get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
set(v) = setTextColor(v)
public var android.widget.TextView.hintTextColor: Int
get() = throw AnkoException("'android.widget.TextView.hintTextColor' property does not have a getter")
set(v) = setHintTextColor(v)
public var android.widget.TextView.linkTextColor: Int
get() = throw AnkoException("'android.widget.TextView.linkTextColor' property does not have a getter")
set(v) = setLinkTextColor(v)
public var android.widget.TextView.lines: Int
get() = throw AnkoException("'android.widget.TextView.lines' property does not have a getter")
set(v) = setLines(v)
public var android.widget.TextView.singleLine: Boolean
get() = throw AnkoException("'android.widget.TextView.singleLine' property does not have a getter")
set(v) = setSingleLine(v)
public var android.widget.LinearLayout.gravity: Int
get() = throw AnkoException("'android.widget.LinearLayout.gravity' property does not have a getter")
set(v) = setGravity(v)
public var android.widget.Gallery.gravity: Int
get() = throw AnkoException("'android.widget.Gallery.gravity' property does not have a getter")
set(v) = setGravity(v) | apache-2.0 | 32b20d3879bb18bdd3090393cdf454a9 | 32.255593 | 139 | 0.747055 | 3.849744 | false | false | false | false |
alexander-schmidt/ihh | ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/tasks/CircularQueue.kt | 1 | 964 | package com.asurasdevelopment.ihh.server.tasks
class CircularQueue<T>(private var queueObjects: MutableList<T> = mutableListOf(),
private var currentPosition: Int = 0) {
fun current(): T {
return queueObjects[currentPosition]
}
fun currentPosition(): Int {
return currentPosition
}
@Synchronized
fun next(): T {
return queueObjects[incPos()]
}
private fun incPos() : Int {
currentPosition = (++currentPosition) % queueObjects.size
return currentPosition
}
fun add(index: Int = queueObjects.size - 1, obj: T) {
queueObjects.add(index, obj)
}
fun remove() {
queueObjects.removeAt(currentPosition)
}
fun remove(obj: T) {
queueObjects.remove(obj)
}
fun get(index: Int): T {
return queueObjects[index]
}
fun set(queueObjects: MutableList<T>) {
this.queueObjects = queueObjects
}
} | apache-2.0 | 3f138d00d4a1a36e206b5c831842d504 | 21.44186 | 82 | 0.605809 | 4.381818 | false | false | false | false |
siosio/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/progress/impl/Progress2IndicatorTest.kt | 2 | 2476 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.progress.impl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.Progress
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.runUnderIndicator
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.util.concurrency.AppExecutorUtil
import com.intellij.util.concurrency.Semaphore
import kotlinx.coroutines.CancellationException
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
class Progress2IndicatorTest : LightPlatformTestCase() {
fun `test progress cancellation cancels indicator`() {
val lock = Semaphore(1)
val cancelled = AtomicBoolean(false)
val progress = Progress {
cancelled.get()
}
val future = AppExecutorUtil.getAppExecutorService().submit {
runUnderIndicator(progress) {
ProgressManager.checkCanceled()
lock.up()
while (true) { // never-ending blocking action
ProgressManager.checkCanceled()
Thread.sleep(1)
}
}
}
assertTrue(lock.waitFor(2000))
cancelled.set(true)
try {
future.get(2000, TimeUnit.MILLISECONDS)
fail("CE expected")
}
catch (e: ExecutionException) {
assertInstanceOf(e.cause, CancellationException::class.java)
}
}
fun `test PCE from runUnderIndicator is rethrown`() {
val progress = Progress {
false
}
val future = AppExecutorUtil.getAppExecutorService().submit {
runUnderIndicator(progress) {
throw ProcessCanceledException()
}
}
try {
future.get(2000, TimeUnit.MILLISECONDS)
fail("PCE expected")
}
catch (e: ExecutionException) {
assertInstanceOf(e.cause, ProcessCanceledException::class.java)
}
}
fun `test CE from runUnderIndicator is rethrown`() {
val progress = Progress {
false
}
val future = AppExecutorUtil.getAppExecutorService().submit {
runUnderIndicator(progress) {
throw CancellationException()
}
}
try {
future.get(2000, TimeUnit.MILLISECONDS)
fail("CE expected")
}
catch (e: ExecutionException) {
assertInstanceOf(e.cause, CancellationException::class.java)
}
}
}
| apache-2.0 | 1323ee6d289dac7a51c5a95c11a3d253 | 29.95 | 140 | 0.706381 | 4.789168 | false | true | false | false |
siosio/intellij-community | plugins/github/src/org/jetbrains/plugins/github/ui/component/GHAccountSelectorComponentFactory.kt | 1 | 7436 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.ui.component
import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask
import com.intellij.collaboration.ui.codereview.avatar.CachingAvatarIconsProvider
import com.intellij.ide.ui.laf.darcula.DarculaUIUtil
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.ui.popup.list.ComboBoxPopup
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.cloneDialog.AccountMenuItem
import com.intellij.util.ui.cloneDialog.AccountMenuItemRenderer
import com.intellij.util.ui.cloneDialog.VcsCloneDialogUiSpec
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.authentication.accounts.GithubAccount
import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.getName
import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader
import java.awt.*
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.concurrent.CompletableFuture
import javax.swing.*
import javax.swing.border.Border
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
class GHAccountSelectorComponentFactory {
fun create(model: ComboBoxWithActionsModel<GithubAccount>): JComponent {
val label = JLabel().apply {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
isFocusable = true
border = FocusBorder()
}
Controller(model, label)
return label
}
class FocusBorder : Border {
override fun paintBorder(c: Component?, g: Graphics?, x: Int, y: Int, width: Int, height: Int) {
if (c?.hasFocus() == true && g is Graphics2D) {
DarculaUIUtil.paintFocusBorder(g, width, height, 0f, true)
}
}
override fun getBorderInsets(c: Component): Insets {
val g2d = c.graphics as? Graphics2D ?: return JBUI.emptyInsets()
val bw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(3).toFloat() else DarculaUIUtil.BW.float
val f = if (UIUtil.isRetina(g2d)) 0.5f else 1.0f
val lw = if (UIUtil.isUnderDefaultMacTheme()) JBUIScale.scale(f) else DarculaUIUtil.LW.float
val insets = (bw + lw).toInt()
return Insets(insets, insets, insets, insets)
}
override fun isBorderOpaque() = false
}
class Controller(private val accountsModel: ComboBoxWithActionsModel<GithubAccount>, private val label: JLabel)
: ComboBoxPopup.Context<ComboBoxWithActionsModel.Item<GithubAccount>> {
private val avatarsProvider = AccountAvatarIconsProvider()
private var popup: ComboBoxPopup<*>? = null
init {
accountsModel.addListDataListener(object : ListDataListener {
override fun contentsChanged(e: ListDataEvent) = updateLabel()
override fun intervalAdded(e: ListDataEvent?) = updateLabel()
override fun intervalRemoved(e: ListDataEvent?) = updateLabel()
})
label.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent?) = showPopup()
})
label.registerPopupOnKeyboardShortcut(KeyEvent.VK_ENTER)
label.registerPopupOnKeyboardShortcut(KeyEvent.VK_SPACE)
updateLabel()
}
private fun updateLabel() {
val selectedAccount = accountsModel.selectedItem?.wrappee
with(label) {
isVisible = accountsModel.items.isNotEmpty()
icon = avatarsProvider.getIcon(selectedAccount, GHUIUtil.AVATAR_SIZE)
toolTipText = selectedAccount?.name ?: GithubBundle.message("account.choose.link")
}
}
private fun showPopup() {
popup = object : ComboBoxPopup<ComboBoxWithActionsModel.Item<GithubAccount>>(this, accountsModel.selectedItem, {
accountsModel.setSelectedItem(it)
}) {
//otherwise component borders are overridden
override fun getListElementRenderer() = renderer
}.apply {
//TODO: remove speedsearch
addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
popup = null
}
})
showUnderneathOf(label)
}
}
private fun JComponent.registerPopupOnKeyboardShortcut(keyCode: Int) {
registerKeyboardAction({ showPopup() }, KeyStroke.getKeyStroke(keyCode, 0), JComponent.WHEN_FOCUSED)
}
override fun getProject(): Project? = null
override fun getModel(): ListModel<ComboBoxWithActionsModel.Item<GithubAccount>> = accountsModel
override fun getRenderer(): ListCellRenderer<ComboBoxWithActionsModel.Item<GithubAccount>> = PopupItemRenderer(avatarsProvider)
}
private class PopupItemRenderer(private val avatarsProvider: AccountAvatarIconsProvider)
: ListCellRenderer<ComboBoxWithActionsModel.Item<GithubAccount>> {
private val delegateRenderer = AccountMenuItemRenderer()
override fun getListCellRendererComponent(list: JList<out ComboBoxWithActionsModel.Item<GithubAccount>>?,
value: ComboBoxWithActionsModel.Item<GithubAccount>,
index: Int,
selected: Boolean,
focused: Boolean): Component {
val item = when (value) {
is ComboBoxWithActionsModel.Item.Wrapper<GithubAccount> ->
value.wrappee.let { account ->
val icon = avatarsProvider.getIcon(account, VcsCloneDialogUiSpec.Components.popupMenuAvatarSize)
val serverAddress = account.server.toString()
AccountMenuItem.Account(account.name, serverAddress, icon)
}
is ComboBoxWithActionsModel.Item.Action<GithubAccount> ->
value.action.let {
AccountMenuItem.Action(it.getName(), {}, showSeparatorAbove = value.needSeparatorAbove)
}
}
return delegateRenderer.getListCellRendererComponent(null, item, index, selected, focused)
}
}
private class AccountAvatarIconsProvider : CachingAvatarIconsProvider<GithubAccount>(
GithubIcons.DefaultAvatar) {
private val requestExecutorManager = GithubApiRequestExecutorManager.getInstance()
private val accountInformationProvider = GithubAccountInformationProvider.getInstance()
private val avatarLoader = CachingGHUserAvatarLoader.getInstance()
override fun loadImage(key: GithubAccount): Image? {
val executor = requestExecutorManager.getExecutor(key)
return ProgressManager.getInstance().submitIOTask(EmptyProgressIndicator()) {
accountInformationProvider.getInformation(executor, it, key)
}.thenCompose {
val url = it.avatarUrl ?: return@thenCompose CompletableFuture.completedFuture(null)
avatarLoader.requestAvatar(executor, url)
}.get()
}
}
} | apache-2.0 | d5a222c0eef234f0cd932a340d2652cd | 42.491228 | 140 | 0.730097 | 5.007407 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/projectView/KtDeclarationTreeNode.kt | 2 | 4025 | // 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.projectView
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.nodes.AbstractPsiBasedNode
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.psi.*
internal class KtDeclarationTreeNode(
project: Project?,
ktDeclaration: KtDeclaration?,
viewSettings: ViewSettings?
) : AbstractPsiBasedNode<KtDeclaration?>(project, ktDeclaration!!, viewSettings) {
override fun extractPsiFromValue(): PsiElement? = value
override fun getChildrenImpl(): Collection<AbstractTreeNode<*>> = emptyList()
override fun updateImpl(data: PresentationData) {
val declaration = value ?: return
data.presentableText = tryGetRepresentableText(declaration)
}
override fun isDeprecated(): Boolean = value?.let { KtPsiUtil.isDeprecated(it) } ?: false
companion object {
private val CLASS_INITIALIZER = "<" + KotlinBundle.message("project.view.class.initializer") + ">"
private val ERROR_NAME = "<" + KotlinBundle.message("project.view.class.error.name") + ">"
private fun String?.orErrorName() = if (!isNullOrBlank()) this else ERROR_NAME
@NlsSafe
fun tryGetRepresentableText(declaration: KtDeclaration): String? {
val settings = declaration.containingKtFile.kotlinCustomSettings
fun StringBuilder.appendColon() {
if (settings.SPACE_BEFORE_TYPE_COLON) append(" ")
append(":")
if (settings.SPACE_AFTER_TYPE_COLON) append(" ")
}
fun KtProperty.presentableText() = buildString {
append(name.orErrorName())
typeReference?.text?.let { reference ->
appendColon()
append(reference)
}
}
fun KtFunction.presentableText() = buildString {
receiverTypeReference?.text?.let { receiverReference ->
append(receiverReference)
append('.')
}
append(name.orErrorName())
append("(")
val valueParameters = valueParameters
valueParameters.forEachIndexed { index, parameter ->
parameter.name?.let { parameterName ->
append(parameterName)
appendColon()
}
parameter.typeReference?.text?.let { typeReference ->
append(typeReference)
}
if (index != valueParameters.size - 1) {
append(", ")
}
}
append(")")
typeReference?.text?.let { returnTypeReference ->
appendColon()
append(returnTypeReference)
}
}
fun KtObjectDeclaration.presentableText(): String? = buildString {
if (isCompanion()) {
append("companion object")
} else {
append(name.orErrorName())
}
}
return when (declaration) {
is KtProperty -> declaration.presentableText()
is KtFunction -> declaration.presentableText()
is KtObjectDeclaration -> declaration.presentableText()
is KtAnonymousInitializer -> CLASS_INITIALIZER
else -> declaration.name.orErrorName()
}
}
}
}
| apache-2.0 | 7afc43c7ea63bd9b27ec3f309b69e131 | 38.851485 | 158 | 0.588323 | 5.75 | false | false | false | false |
JetBrains/intellij-community | plugins/devkit/intellij.devkit.i18n/src/DevKitPropertiesQuotesValidationInspection.kt | 1 | 3696 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.devkit.i18n
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.lang.properties.PropertiesInspectionBase
import com.intellij.lang.properties.parsing.PropertiesTokenTypes
import com.intellij.lang.properties.psi.Property
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.annotations.NonNls
import org.jetbrains.idea.devkit.inspections.DevKitInspectionUtil
import java.text.ChoiceFormat
class DevKitPropertiesQuotesValidationInspection : PropertiesInspectionBase() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
if (!DevKitInspectionUtil.isAllowed(holder.file)) {
return PsiElementVisitor.EMPTY_VISITOR
}
return object : PsiElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element !is Property) return
val value = element.value ?: return
val quotedParam = checkQuotedParam(value) ?: return
val paramString = "{$quotedParam}"
val idx = value.indexOf(paramString) + element.getNode().findChildByType(PropertiesTokenTypes.VALUE_CHARACTERS)!!.startOffsetInParent
holder.registerProblem(element, TextRange(idx, idx + paramString.length),
DevKitI18nBundle.message("inspection.message.wrong.quotes.around.parameter.reference", paramString))
}
}
}
fun checkQuotedParam(pattern: String): Int? {
var raw = true
var inQuote = false
var i = 0
var paramSB : StringBuilder? = null
var level = 0
while (i < pattern.length) {
val ch = pattern[i]
if (raw) {
if (ch == '\'') {
if (i + 1 < pattern.length && pattern[i + 1] == '\'') {
i++
}
else {
if (!inQuote) {
paramSB = StringBuilder()
}
else {
val quotedStr = paramSB.toString()
if (quotedStr.startsWith('{') && quotedStr.endsWith('}')) {
try {
return Integer.parseInt(quotedStr.trimStart { it == '{'}.trimEnd { it == '}'})
}
catch (ignored: NumberFormatException) { }
}
paramSB = null
}
inQuote = !inQuote
}
}
else if (ch == '{' && !inQuote) {
raw = false
}
else if (inQuote) {
paramSB!!.append(ch)
}
}
else {
paramSB?.append(ch)
if (inQuote) {
if (ch == '\'') {
inQuote = false
}
}
else when (ch) {
'{' -> level++
',' -> {
@NonNls val prefix = "choice,"
if (pattern.substring(i + 1).trim().startsWith(prefix)) {
i += prefix.length + 1
paramSB = StringBuilder()
}
}
'}' -> {
if (level -- == 0) {
try {
val choiceFormat = ChoiceFormat(paramSB.toString().trimEnd { it == '}' })
for (format in choiceFormat.formats) {
return checkQuotedParam(format as String) ?: continue
}
}
catch (ignore: IllegalArgumentException) {
//illegal choice format, do nothing for now
}
paramSB = null
raw = true
}
}
'\'' -> inQuote = true
}
}
++i
}
return null
}
} | apache-2.0 | d9f2086893c770a99286b007538a2d1f | 32.609091 | 141 | 0.554654 | 4.696315 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/test/java/androidx/compose/ui/text/input/SetComposingRegionCommandTest.kt | 3 | 4112 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.input
import androidx.compose.ui.text.TextRange
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class SetComposingRegionCommandTest {
@Test
fun test_set() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(1, 4).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(1)
assertThat(eb.compositionEnd).isEqualTo(4)
}
@Test
fun test_preserve_ongoing_composition() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
eb.setComposition(1, 3)
SetComposingRegionCommand(2, 4).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(2)
assertThat(eb.compositionEnd).isEqualTo(4)
}
@Test
fun test_preserve_selection() {
val eb = EditingBuffer("ABCDE", TextRange(1, 4))
SetComposingRegionCommand(2, 4).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.selectionStart).isEqualTo(1)
assertThat(eb.selectionEnd).isEqualTo(4)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(2)
assertThat(eb.compositionEnd).isEqualTo(4)
}
@Test
fun test_set_reversed() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(4, 1).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(1)
assertThat(eb.compositionEnd).isEqualTo(4)
}
@Test
fun test_set_too_small() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(-1000, -1000).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_set_too_large() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(1000, 1000).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isFalse()
}
@Test
fun test_set_too_small_and_too_large() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(-1000, 1000).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(0)
assertThat(eb.compositionEnd).isEqualTo(5)
}
@Test
fun test_set_too_small_and_too_large_reversed() {
val eb = EditingBuffer("ABCDE", TextRange.Zero)
SetComposingRegionCommand(1000, -1000).applyTo(eb)
assertThat(eb.toString()).isEqualTo("ABCDE")
assertThat(eb.cursor).isEqualTo(0)
assertThat(eb.hasComposition()).isTrue()
assertThat(eb.compositionStart).isEqualTo(0)
assertThat(eb.compositionEnd).isEqualTo(5)
}
} | apache-2.0 | 645238868401afbbffdaad18c2b59a8e | 30.638462 | 75 | 0.672422 | 4.26999 | false | true | false | false |
DSteve595/Put.io | app/src/main/java/com/stevenschoen/putionew/tv/TvFolderFragment.kt | 1 | 4059 | package com.stevenschoen.putionew.tv
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.transition.Slide
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.leanback.app.VerticalGridSupportFragment
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.OnItemViewClickedListener
import androidx.leanback.widget.VerticalGridPresenter
import com.stevenschoen.putionew.PutioUtils
import com.stevenschoen.putionew.R
import com.stevenschoen.putionew.UIUtils
import com.stevenschoen.putionew.files.FolderLoader
import com.stevenschoen.putionew.model.ResponseOrError
import com.stevenschoen.putionew.model.files.PutioFile
import io.reactivex.android.schedulers.AndroidSchedulers
class TvFolderFragment : VerticalGridSupportFragment() {
companion object {
private const val EXTRA_FOLDER = "folder"
private const val NUM_COLUMNS = 3
fun newInstance(context: Context, folder: PutioFile): TvFolderFragment {
return Fragment.instantiate(context, TvFolderFragment::class.java.name, Bundle().apply {
putParcelable(EXTRA_FOLDER, folder)
}) as TvFolderFragment
}
}
var onFolderSelected: ((folder: PutioFile) -> Unit)? = null
var requestFocusWhenPossible: Boolean = false
set(value) {
if (value && isVisible) {
view!!.apply {
post {
requestFocus()
}
}
} else {
field = value
}
}
private var arrayAdapter: ArrayObjectAdapter? = null
private val folder by lazy { arguments!!.getParcelable<PutioFile>(EXTRA_FOLDER)!! }
lateinit private var loader: FolderLoader
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (UIUtils.hasLollipop()) {
enterTransition = Slide(Gravity.END)
exitTransition = Slide(Gravity.END)
}
loader = FolderLoader.get(loaderManager, context!!, folder)
loader.refreshFolder(onlyIfStaleOrEmpty = true, cache = false)
loader.folder()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
when (it) {
is FolderLoader.FolderResponse -> populateGrid(it.files)
is ResponseOrError.NetworkError -> Toast.makeText(context, R.string.network_error, Toast.LENGTH_SHORT).show()
}
}, { error ->
PutioUtils.getRxJavaThrowable(error).printStackTrace()
Toast.makeText(context, R.string.network_error, Toast.LENGTH_SHORT).show()
})
title = folder.name
gridPresenter = GridPresenter()
arrayAdapter = ArrayObjectAdapter(TvPutioFileCardPresenter())
adapter = arrayAdapter
onItemViewClickedListener = OnItemViewClickedListener { _, item, _, _ ->
if (item is PutioFile) {
if (item.isFolder) {
onFolderSelected?.invoke(item)
} else {
playVideo(item)
}
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return super.onCreateView(inflater, container, savedInstanceState)!!.apply {
setBackgroundColor(ContextCompat.getColor(context, R.color.putio_tv_background))
if (requestFocusWhenPossible) {
post {
requestFocus()
}
requestFocusWhenPossible = false
}
}
}
private fun playVideo(file: PutioFile) {
startActivity(Intent(context, TvPlayerActivity::class.java).apply {
putExtra(TvPlayerActivity.EXTRA_VIDEO, file)
putExtra(TvPlayerActivity.EXTRA_USE_MP4, file.isMp4Available)
})
}
private fun populateGrid(files: List<PutioFile>) {
arrayAdapter!!.clear()
arrayAdapter!!.addAll(0, files.filter { it.isFolder || it.isMedia })
}
inner class GridPresenter : VerticalGridPresenter() {
init {
numberOfColumns = NUM_COLUMNS
}
}
}
| mit | 789c0ea929cfaa29a93f60bef896c7ad | 30.710938 | 121 | 0.70781 | 4.520045 | false | false | false | false |
androidx/androidx | testutils/testutils-runtime/src/main/java/androidx/testutils/LocaleTestUtils.kt | 3 | 8031 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.testutils
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.LocaleList
import androidx.core.os.ConfigurationCompat
import androidx.core.os.LocaleListCompat
import java.util.Locale
/**
* Utility class to save and restore the locale of the system.
*
* Inspired by [com.android.dialer.util.LocaleTestUtils](https://android.googlesource.com/platform/packages/apps/Dialer/+/94b10b530c0fc297e2974e57e094c500d3ee6003/tests/src/com/android/dialer/util/LocaleTestUtils.java)
*
* This can be used for tests that assume to be run in a certain locale, e.g., because they check
* against strings in a particular language or require an assumption on how the system will behave
* in a specific locale.
*
* In your test, you can change the locale with the following code:
* <pre>
* public class CanadaFrenchTest extends AndroidTestCase {
* private LocaleTestUtils mLocaleTestUtils;
*
* @Override
* public void setUp() throws Exception {
* super.setUp();
* mLocaleTestUtils = new LocaleTestUtils(getContext());
* mLocaleTestUtils.setLocale(Locale.CANADA_FRENCH);
* }
*
* @Override
* public void tearDown() throws Exception {
* mLocaleTestUtils.resetLocale();
* mLocaleTestUtils = null;
* super.tearDown();
* }
*
* ...
* }
* </pre>
* Note that one should not call [setLocale] more than once without calling [resetLocale] first.
*
* This class is not thread-safe. Usually its methods should be invoked only from the test thread.
*
* @property mContext the context on which to alter the locale
* @constructor Create a new instance that can be used to set and reset the locale for the given
* context.
*/
class LocaleTestUtils(private val mContext: Context) {
companion object {
const val DEFAULT_TEST_LANGUAGE = "en_US"
const val RTL_LANGUAGE = "ar_SA"
const val LTR_LANGUAGE = "fr_FR"
}
private var saved: Boolean = false
private var savedContextLocale: LocaleListCompat? = null
private var savedSystemLocale: LocaleListCompat? = null
private var locale: Locale? = null
private var canSave: Boolean = true
/**
* Set the locale to the given value and saves the previous value.
*
* @param lang the language to which the locale should be set, in the same format as
* Locale.toString()
* @throws IllegalStateException if the locale was already set
*/
fun setLocale(lang: String) {
synchronized(this) {
val locale = findLocale(lang)
if (saved) {
throw IllegalStateException("call restoreLocale() before calling setLocale() again")
}
if (!canSave) {
throw IllegalStateException(
"can't set locale after isLocaleChangedAndLock() is " +
"called"
)
}
this.locale = locale
val locales = LocaleListCompat.create(locale)
savedContextLocale = updateResources(mContext.resources, locales)
savedSystemLocale = updateResources(Resources.getSystem(), locales)
saved = true
canSave = false
}
}
/**
* Restores the original locale, if it was changed, and unlocks the ability to change the locale
* for this object, if it was locked by [isLocaleChangedAndLock]. If the locale wasn't changed,
* it leaves the locales untouched, but will still unlock this object if it was locked.
*/
fun resetLocale() {
synchronized(this) {
canSave = true
if (!saved) {
return
}
updateResources(mContext.resources, savedContextLocale!!)
updateResources(Resources.getSystem(), savedSystemLocale!!)
saved = false
}
}
/**
* Gets the Locale to which the locale has been changed, or null if the locale hasn't been
* changed.
*/
fun getLocale(): Locale? {
synchronized(this) {
return locale
}
}
/**
* Returns if the locale has been changed.
*/
fun isLocaleChanged(): Boolean {
synchronized(this) {
return saved
}
}
/**
* Returns if the locale has been changed, and disables all future locale changes until
* [resetLocale] has been called. Calling [setLocale] after calling this method will throw an
* exception.
*
* Use this check-and-lock if the behavior of a component depends on whether or not the locale
* has been changed, and it only checks it when initializing the component. E.g., when starting
* a test Activity.
*/
fun isLocaleChangedAndLock(): Boolean {
synchronized(this) {
canSave = false
return saved
}
}
/**
* Finds the best matching Locale on the system for the given language
*/
private fun findLocale(lang: String): Locale {
// Build list of prefixes ("ar_SA_xx_foo_bar" -> ["ar", "ar_SA", "ar_SA_xx", etc..])
val prefixes = lang.split("_").fold(mutableListOf<String>()) { prefixes, elem ->
prefixes.also { it.add(if (it.isEmpty()) elem else "${it.last()}_$elem") }
}
// Build lists of matches per prefix
val matches = List<MutableList<Locale>>(prefixes.size) { mutableListOf() }
for (locale in Locale.getAvailableLocales()) {
val language = locale.toString()
prefixes.forEachIndexed { i, prefix ->
if (language.startsWith(prefix)) {
if (language == prefix) {
// Exact matches are preferred, so put them in front
matches[i].add(0, locale)
} else if (matches[i].isEmpty()) {
// We only need one inexact match per prefix
matches[i].add(locale)
}
}
}
}
// Find best match: the locale that has the longest common prefix with the given language
return matches.lastOrNull { it.isNotEmpty() }?.first() ?: Locale.getDefault()
}
/**
* Sets the locale(s) for the given resources and returns the previous locales.
*
* @param resources the resources on which to set the locales
* @param locales the value(s) to which to set the locales
* @return the previous value of the locales for the resources
*/
private fun updateResources(resources: Resources, locales: LocaleListCompat): LocaleListCompat {
val savedLocales = ConfigurationCompat.getLocales(resources.configuration)
val newConfig = Configuration(resources.configuration)
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ->
newConfig.setLocales(locales.unwrap() as LocaleList)
Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 ->
newConfig.setLocale(locales.get(0))
else ->
@Suppress("DEPRECATION")
newConfig.locale = locales.get(0)
}
@Suppress("DEPRECATION")
resources.updateConfiguration(newConfig, resources.displayMetrics)
return savedLocales
}
} | apache-2.0 | eeea93e89a5f8bf0f13cd5319a29b8c4 | 36.70892 | 218 | 0.631553 | 4.618171 | false | true | false | false |
GunoH/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/ReviewListItemPresentation.kt | 7 | 1632 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.ui.codereview.list
import com.intellij.openapi.util.NlsSafe
import org.jetbrains.annotations.Nls
import java.util.*
import javax.swing.Icon
interface ReviewListItemPresentation {
val title: @NlsSafe String
val id: @NlsSafe String
val createdDate: Date
val author: UserPresentation?
val tagGroup: NamedCollection<TagPresentation>?
val mergeableStatus: Status?
val buildStatus: Status?
val state: @NlsSafe String?
val userGroup1: NamedCollection<UserPresentation>?
val userGroup2: NamedCollection<UserPresentation>?
val commentsCounter: CommentsCounter?
data class Simple(override val title: String,
override val id: String,
override val createdDate: Date,
override val author: UserPresentation? = null,
override val tagGroup: NamedCollection<TagPresentation>? = null,
override val mergeableStatus: Status? = null,
override val buildStatus: Status? = null,
override val state: String? = null,
override val userGroup1: NamedCollection<UserPresentation>? = null,
override val userGroup2: NamedCollection<UserPresentation>? = null,
override val commentsCounter: CommentsCounter? = null) : ReviewListItemPresentation
data class Status(val icon: Icon, val tooltip: @Nls String)
data class CommentsCounter(val count: Int, val tooltip: @Nls String)
}
| apache-2.0 | 1d3651b0b6d5e772d9d39315188cfceb | 41.947368 | 120 | 0.69424 | 4.716763 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/KotlinSourcePositionProvider.kt | 3 | 7736 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.SourcePositionProvider
import com.intellij.debugger.impl.DebuggerContextImpl
import com.intellij.debugger.impl.DebuggerContextUtil
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.ui.tree.FieldDescriptor
import com.intellij.debugger.ui.tree.LocalVariableDescriptor
import com.intellij.debugger.ui.tree.NodeDescriptor
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.ClassNotPreparedException
import com.sun.jdi.ClassType
import com.sun.jdi.ReferenceType
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.load.java.possibleGetMethodNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContextUtils
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.getPsi
class KotlinSourcePositionProvider : SourcePositionProvider() {
override fun computeSourcePosition(
descriptor: NodeDescriptor,
project: Project,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
if (context.frameProxy == null || DumbService.isDumb(project)) return null
return when(descriptor) {
is FieldDescriptor -> computeSourcePosition(descriptor, context, nearest)
is GetterDescriptor -> computeSourcePosition(descriptor, context, nearest)
is LocalVariableDescriptor -> computeSourcePosition(descriptor, context, nearest)
else -> null
}
}
private fun computeSourcePosition(
descriptor: LocalVariableDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val place = PositionUtil.getContextElement(context) ?: return null
if (place.containingFile !is KtFile) return null
val contextElement = getContextElement(place) ?: return null
val codeFragment = KtPsiFactory(context.project).createExpressionCodeFragment(descriptor.name, contextElement)
val expression = codeFragment.getContentElement()
if (expression is KtSimpleNameExpression) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
val declarationDescriptor = BindingContextUtils.extractVariableDescriptorFromReference(bindingContext, expression)
val sourceElement = declarationDescriptor?.source
if (sourceElement is KotlinSourceElement) {
val element = sourceElement.getPsi() ?: return null
if (nearest) {
return DebuggerContextUtil.findNearest(context, element, element.containingFile)
}
return SourcePosition.createFromOffset(element.containingFile, element.textOffset)
}
}
return null
}
private fun computeSourcePositionForDeclaration(
name: String,
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean
) = computeSourcePositionForDeclaration(declaringType, context, nearest) {
it.name == name
}
private fun computeSourcePositionForPropertyDeclaration(
name: String,
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean
) = computeSourcePositionForDeclaration(declaringType, context, nearest) {
it.name == name || it.name in name.getPropertyDeclarationNameVariations()
}
private fun String.getPropertyDeclarationNameVariations(): List<String> {
val name = Name.guessByFirstCharacter(this)
return possibleGetMethodNames(name).map(Name::asString)
}
private fun computeSourcePositionForDeclaration(
declaringType: ReferenceType,
context: DebuggerContextImpl,
nearest: Boolean,
declarationSelector: (KtDeclaration) -> Boolean
): SourcePosition? {
val myClass = findClassByType(context.project, declaringType, context)?.navigationElement as? KtClassOrObject ?: return null
val declaration = myClass.declarations.firstOrNull(declarationSelector) ?: return null
if (nearest) {
return DebuggerContextUtil.findNearest(context, declaration, myClass.containingFile)
}
return SourcePosition.createFromOffset(declaration.containingFile, declaration.textOffset)
}
private fun computeSourcePosition(
descriptor: FieldDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val fieldName = descriptor.field.name()
if (fieldName == AsmUtil.CAPTURED_THIS_FIELD
|| fieldName == AsmUtil.CAPTURED_RECEIVER_FIELD
|| fieldName.startsWith(AsmUtil.LABELED_THIS_FIELD)
) {
return null
}
return computeSourcePositionForDeclaration(fieldName, descriptor.field.declaringType(), context, nearest)
}
private fun computeSourcePosition(
descriptor: GetterDescriptor,
context: DebuggerContextImpl,
nearest: Boolean
): SourcePosition? {
val name = descriptor.name
val type = descriptor.getter.declaringType()
computeSourcePositionForPropertyDeclaration(name, type, context, nearest)?.let { return it }
if (type is ClassType) {
val interfaces = type.safeAllInterfaces().distinct()
for (intf in interfaces) {
computeSourcePositionForPropertyDeclaration(name, intf, context, nearest)?.let { return it }
}
}
return null
}
private fun findClassByType(project: Project, type: ReferenceType, context: DebuggerContextImpl): PsiElement? {
val session = context.debuggerSession
val scope = session?.searchScope ?: GlobalSearchScope.allScope(project)
val className = JvmClassName.byInternalName(type.name()).fqNameForClassNameWithoutDollars.asString()
val myClass = JavaPsiFacade.getInstance(project).findClass(className, scope)
if (myClass != null) return myClass
val position = getLastSourcePosition(type, context)
if (position != null) {
val element = position.elementAt
if (element != null) {
return element.getStrictParentOfType<KtClassOrObject>()
}
}
return null
}
private fun getLastSourcePosition(type: ReferenceType, context: DebuggerContextImpl): SourcePosition? {
val debugProcess = context.debugProcess
if (debugProcess != null) {
try {
val locations = type.safeAllLineLocations()
if (locations.isNotEmpty()) {
val lastLocation = locations[locations.size - 1]
return debugProcess.positionManager.getSourcePosition(lastLocation)
}
} catch (ignored: AbsentInformationException) {
} catch (ignored: ClassNotPreparedException) {
}
}
return null
}
}
| apache-2.0 | 0946e0481c80e7e1d4c7009d0a8c3a9a | 40.816216 | 158 | 0.703981 | 5.398465 | false | false | false | false |
smmribeiro/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/IconsClassGenerator.kt | 1 | 24798 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package org.jetbrains.intellij.build.images
import com.intellij.openapi.util.text.StringUtil
import com.intellij.ui.svg.SvgTranscoder
import com.intellij.ui.svg.createSvgDocument
import com.intellij.util.LineSeparator
import com.intellij.util.containers.CollectionFactory
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.diff.Diff
import com.intellij.util.io.directoryStreamIfExists
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.lang.Murmur3_32Hash
import com.intellij.util.readXmlAsModel
import org.jetbrains.jps.model.JpsSimpleElement
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.util.JpsPathUtil
import java.awt.image.BufferedImage
import java.io.File
import java.nio.file.*
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import javax.imageio.ImageIO
import javax.xml.stream.XMLStreamException
internal data class ModifiedClass(val module: JpsModule, val file: Path, val result: CharSequence)
// legacy ordering
private val NAME_COMPARATOR: Comparator<String> = compareBy { it.lowercase(Locale.ENGLISH) + '.' }
internal data class IconClassInfo(val customLoad: Boolean,
val packageName: String,
val className: String,
val outFile: Path,
val images: Collection<ImageInfo>)
internal open class IconsClassGenerator(private val projectHome: Path,
val modules: List<JpsModule>,
private val writeChangesToDisk: Boolean = true) {
companion object {
private val deprecatedIconFieldNameMap = CollectionFactory.createCharSequenceMap<String>(true)
init {
deprecatedIconFieldNameMap.put("RwAccess", "Rw_access")
deprecatedIconFieldNameMap.put("MenuOpen", "Menu_open")
deprecatedIconFieldNameMap.put("MenuCut", "Menu_cut")
deprecatedIconFieldNameMap.put("MenuPaste", "Menu_paste")
@Suppress("SpellCheckingInspection")
deprecatedIconFieldNameMap.put("MenuSaveall", "Menu_saveall")
deprecatedIconFieldNameMap.put("PhpIcon", "Php_icon")
deprecatedIconFieldNameMap.put("Emulator02", "Emulator2")
}
}
private val processedClasses = AtomicInteger()
private val processedIcons = AtomicInteger()
private val processedPhantom = AtomicInteger()
private val modifiedClasses = ContainerUtil.createConcurrentList<ModifiedClass>()
private val obsoleteClasses = ContainerUtil.createConcurrentList<Path>()
private val util: JpsModule by lazy {
modules.find { it.name == "intellij.platform.util" } ?: error("Can't load module 'util'")
}
internal open fun getIconClassInfo(module: JpsModule, moduleConfig: IntellijIconClassGeneratorModuleConfig?): List<IconClassInfo> {
val packageName: String
val className: CharSequence
val outFile: Path
when (module.name) {
"intellij.platform.icons" -> {
packageName = "com.intellij.icons"
className = "AllIcons"
val dir = util.getSourceRoots(JavaSourceRootType.SOURCE).first().file.absolutePath + "/com/intellij/icons"
outFile = Path.of(dir, "$className.java")
}
"intellij.android.artwork" -> {
packageName = "icons"
val sourceRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).single().file.absolutePath
val resourceRoot = module.getSourceRoots(JavaResourceRootType.RESOURCE).single()
// avoid merge conflicts - do not transform StudioIcons to nested class of AndroidIcons
var imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig)
val imagesA = imageCollector.collectSubDir(resourceRoot, "icons", includePhantom = true)
imageCollector.printUsedIconRobots()
imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig)
val imagesS = imageCollector.collectSubDir(resourceRoot, "studio/icons", includePhantom = true)
imageCollector.printUsedIconRobots()
return listOf(
IconClassInfo(true, packageName, "AndroidIcons", Path.of(sourceRoot, "icons", "AndroidIcons.java"), imagesA),
IconClassInfo(true, packageName, "StudioIcons", Path.of(sourceRoot, "icons", "StudioIcons.java"), imagesS),
)
}
else -> {
packageName = moduleConfig?.packageName ?: getPluginPackageIfPossible(module) ?: "icons"
val firstRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).firstOrNull() ?: return emptyList()
val firstRootDir = Path.of(JpsPathUtil.urlToPath(firstRoot.url)).resolve("icons")
var oldClassName: String?
// this is added to remove unneeded empty directories created by previous version of this script
if (Files.isDirectory(firstRootDir)) {
try {
Files.delete(firstRootDir)
println("deleting empty directory $firstRootDir")
}
catch (ignore: DirectoryNotEmptyException) {
}
oldClassName = findIconClass(firstRootDir)
}
else {
oldClassName = null
}
val generatedRoot = module.getSourceRoots(JavaSourceRootType.SOURCE).find { it.properties.isForGeneratedSources }
val targetRoot = (generatedRoot ?: firstRoot).file.toPath().resolve(packageName.replace('.', File.separatorChar))
if (generatedRoot != null && oldClassName != null && firstRoot != generatedRoot) {
val oldFile = firstRootDir.resolve("$oldClassName.java")
println("deleting $oldFile from source root which isn't marked as 'generated'")
Files.delete(oldFile)
}
if (moduleConfig?.className == null) {
if (oldClassName == null) {
try {
oldClassName = findIconClass(targetRoot)
}
catch (ignored: NoSuchFileException) {
}
}
className = oldClassName ?: directoryName(module).let {
if (it.endsWith("Icons")) it else "${it}Icons"
}
}
else {
className = moduleConfig.className
}
outFile = targetRoot.resolve("$className.java")
}
}
val imageCollector = ImageCollector(projectHome, moduleConfig = moduleConfig)
val images = imageCollector.collect(module, includePhantom = true)
imageCollector.printUsedIconRobots()
return listOf(IconClassInfo(true, packageName, className.toString(), outFile, images))
}
fun processModule(module: JpsModule, moduleConfig: IntellijIconClassGeneratorModuleConfig?) {
val classCode = StringBuilder()
for (iconsClassInfo in getIconClassInfo(module, moduleConfig)) {
val outFile = iconsClassInfo.outFile
val oldText = try {
Files.readString(outFile)
}
catch (ignored: NoSuchFileException) {
null
}
classCode.setLength(0)
val newText = writeClass(getCopyrightComment(oldText), iconsClassInfo, classCode)
if (newText.isNullOrEmpty()) {
if (Files.exists(outFile)) {
obsoleteClasses.add(outFile)
}
continue
}
processedClasses.incrementAndGet()
val newLines = newText.lines()
val oldLines = oldText?.lines() ?: emptyList()
if (oldLines == newLines) {
continue
}
if (writeChangesToDisk) {
val separator = getSeparators(oldText)
Files.createDirectories(outFile.parent)
Files.writeString(outFile, newLines.joinToString(separator = separator.separatorString))
println("Updated class: ${outFile.fileName}")
}
else {
val diff = Diff.linesDiff(oldLines.toTypedArray(), newLines.toTypedArray()) ?: ""
modifiedClasses.add(ModifiedClass(module, outFile, diff))
}
}
}
fun printStats() {
println(
"\nGenerated classes: ${processedClasses.get()}. " +
"Processed icons: ${processedIcons.get()}. " +
"Phantom icons: ${processedPhantom.get()}"
)
if (obsoleteClasses.isNotEmpty()) {
println("\nObsolete classes:")
println(obsoleteClasses.joinToString("\n"))
println("\nObsolete class it is class for icons that cannot be found anymore. Possible reasons:")
println(
"1. Icons not located under resources root." +
"\n Solution - move icons to resources root or fix existing root type (must be \"resources\")"
)
println("2. Icons were removed but not class.\n Solution - remove class.")
println(
"3. Icons located under resources root named \"compatibilityResources\". \"compatibilityResources\" for icons that not used externally as icon class fields, " +
"but maybe referenced directly by path.\n Solution - remove class or move icons to another resources root"
)
}
}
fun getModifiedClasses(): List<ModifiedClass> = modifiedClasses
private fun findIconClass(dir: Path): String? {
dir.directoryStreamIfExists { stream ->
for (it in stream) {
val name = it.fileName.toString()
if (name.endsWith("Icons.java")) {
return name.substring(0, name.length - ".java".length)
}
}
}
return null
}
private fun getCopyrightComment(text: String?): String {
if (text == null) {
return ""
}
val i = text.indexOf("package ")
if (i == -1) {
return ""
}
val comment = text.substring(0, i)
return if (comment.trim().endsWith("*/") || comment.trim().startsWith("//")) comment else ""
}
private fun getSeparators(text: String?): LineSeparator {
return StringUtil.detectSeparators(text ?: return LineSeparator.LF) ?: LineSeparator.LF
}
private fun writeClass(copyrightComment: String, info: IconClassInfo, result: StringBuilder): CharSequence? {
val images = info.images
if (images.isEmpty()) {
return null
}
result.append(copyrightComment)
append(result, "package ${info.packageName};\n", 0)
append(result, "import com.intellij.ui.IconManager;", 0)
append(result, "import org.jetbrains.annotations.NotNull;", 0)
result.append('\n')
append(result, "import javax.swing.*;", 0)
result.append('\n')
if (images.any(ImageInfo::scheduledForRemoval)) {
append(result, "import org.jetbrains.annotations.ApiStatus.ScheduledForRemoval;", 0)
result.append('\n')
}
// IconsGeneratedSourcesFilter depends on following comment, if you are going to change the text
// please do correspond changes in IconsGeneratedSourcesFilter as well
result.append("/**\n")
result.append(" * NOTE THIS FILE IS AUTO-GENERATED\n")
result.append(" * DO NOT EDIT IT BY HAND, run \"Generate icon classes\" configuration instead\n")
result.append(" */\n")
result.append("public")
// backward compatibility
if (info.className != "AllIcons") {
result.append(" final")
}
result.append(" class ").append(info.className).append(" {\n")
if (info.customLoad) {
append(result, "private static @NotNull Icon load(@NotNull String path, int cacheKey, int flags) {", 1)
append(result, "return $iconLoaderCode.loadRasterizedIcon(path, ${info.className}.class.getClassLoader(), cacheKey, flags);", 2)
append(result, "}", 1)
val customExternalLoad = images.any { it.deprecation?.replacementContextClazz != null }
if (customExternalLoad) {
result.append('\n')
append(result, "private static @NotNull Icon load(@NotNull String path, @NotNull Class<?> clazz) {", 1)
append(result, "return $iconLoaderCode.getIcon(path, clazz);", 2)
append(result, "}", 1)
}
}
val inners = StringBuilder()
processIcons(images, inners, info.customLoad, 0)
if (inners.isEmpty()) {
return null
}
result.append(inners)
append(result, "}", 0)
return result
}
private fun processIcons(images: Collection<ImageInfo>, result: StringBuilder, customLoad: Boolean, depth: Int) {
val level = depth + 1
val nodeMap = HashMap<String, MutableList<ImageInfo>>(images.size / 2)
val leafMap = HashMap<String, ImageInfo>(images.size)
for (imageInfo in images) {
val imageId = getImageId(imageInfo, depth)
val index = imageId.indexOf('/')
if (index >= 0) {
nodeMap.computeIfAbsent(imageId.substring(0, index)) { mutableListOf() }.add(imageInfo)
}
else {
leafMap.put(imageId, imageInfo)
}
}
fun getWeight(key: String): Int {
val image = leafMap.get(key) ?: return 0
return if (image.deprecated) 1 else 0
}
val sortedKeys = ArrayList<String>(nodeMap.size + leafMap.size)
sortedKeys.addAll(nodeMap.keys)
sortedKeys.addAll(leafMap.keys)
sortedKeys.sortWith(NAME_COMPARATOR)
sortedKeys.sortWith(Comparator { o1, o2 -> getWeight(o1) - getWeight(o2) })
var innerClassWasBefore = false
for (key in sortedKeys) {
val group = nodeMap.get(key)
if (group != null) {
val oldLength = result.length
val className = className(key)
if (isInlineClass(className)) {
processIcons(group, result, customLoad, depth + 1)
}
else {
// if first in block, do not add yet another extra newline
if (result.length < 2 || result.get(result.length - 1) != '\n' || result.get(result.length - 2) != '{') {
result.append('\n')
}
append(result, "public static final class $className {", level)
val lengthBeforeBody = result.length
processIcons(group, result, customLoad, depth + 1)
if (lengthBeforeBody == result.length) {
result.setLength(oldLength)
}
else {
append(result, "}", level)
innerClassWasBefore = true
}
}
}
val image = leafMap.get(key)
if (image != null) {
if (innerClassWasBefore) {
innerClassWasBefore = false
result.append('\n')
}
appendImage(image, result, level, customLoad)
}
}
}
protected open fun isInlineClass(name: CharSequence) = false
private fun appendImage(image: ImageInfo, result: StringBuilder, level: Int, customLoad: Boolean) {
val file = image.basicFile ?: return
if (!image.phantom && !isIcon(file)) {
return
}
processedIcons.incrementAndGet()
if (image.phantom) {
processedPhantom.incrementAndGet()
}
if (image.used || image.deprecated) {
val deprecationComment = image.deprecation?.comment
if (deprecationComment != null) {
// if first in block, do not add yet another extra newline
if (result.get(result.length - 1) != '\n' || result.get(result.length - 2) != '\n') {
result.append('\n')
}
append(result, "/** @deprecated $deprecationComment */", level)
}
append(result, "@SuppressWarnings(\"unused\")", level)
}
if (image.deprecated) {
append(result, "@Deprecated", level)
}
if (image.scheduledForRemoval) {
append(result, "@ScheduledForRemoval(inVersion = \"${image.scheduledForRemovalRelease}\")", level)
}
val sourceRoot = image.sourceRoot
var rootPrefix = "/"
if (sourceRoot.rootType == JavaSourceRootType.SOURCE) {
@Suppress("UNCHECKED_CAST")
val packagePrefix = (sourceRoot.properties as JpsSimpleElement<JavaSourceRootProperties>).data.packagePrefix
if (packagePrefix.isNotEmpty()) {
rootPrefix += packagePrefix.replace('.', '/') + "/"
}
}
// backward compatibility - use streaming camel case for StudioIcons
val iconName = generateIconFieldName(file)
val deprecation = image.deprecation
if (deprecation?.replacementContextClazz != null) {
val method = if (customLoad) "load" else "$iconLoaderCode.getIcon"
append(result, "public static final @NotNull Icon $iconName = " +
"$method(\"${deprecation.replacement}\", ${deprecation.replacementContextClazz}.class);", level)
return
}
else if (deprecation?.replacementReference != null) {
append(result, "public static final @NotNull Icon $iconName = ${deprecation.replacementReference};", level)
return
}
val rootDir = Path.of(JpsPathUtil.urlToPath(sourceRoot.url))
val imageFile: Path
if (deprecation?.replacement == null) {
imageFile = file
}
else {
imageFile = rootDir.resolve(deprecation.replacement.removePrefix("/").removePrefix(File.separator))
assert(isIcon(imageFile)) {
"Invalid deprecation replacement '${deprecation.replacement}': $imageFile is not an icon"
}
}
var javaDoc: String
var key: Int
try {
val loadedImage: BufferedImage
if (file.toString().endsWith(".svg")) {
// don't mask any exception for svg file
val data = loadAndNormalizeSvgFile(imageFile).toByteArray()
loadedImage = SvgTranscoder.createImage(1f, createSvgDocument(null, data), null)
key = getImageKey(data, file.fileName.toString())
}
else {
loadedImage = Files.newInputStream(file).buffered().use { ImageIO.read(it) }
key = 0
}
javaDoc = "/** ${loadedImage.width}x${loadedImage.height} */ "
}
catch (e: NoSuchFileException) {
if (!image.phantom) {
throw e
}
javaDoc = ""
key = 0
}
val method = if (customLoad) "load" else "$iconLoaderCode.getIcon"
val relativePath = rootPrefix + rootDir.relativize(imageFile).systemIndependentPath
assert(relativePath.startsWith("/"))
append(result, "${javaDoc}public static final @NotNull Icon $iconName = " +
"$method(\"${relativePath.removePrefix("/")}\", $key, ${image.getFlags()});", level)
val oldName = deprecatedIconFieldNameMap.get(iconName)
if (oldName != null) {
append(result, "${javaDoc}public static final @Deprecated @NotNull Icon $oldName = $iconName;", level)
}
}
protected fun append(result: StringBuilder, text: String, level: Int) {
if (text.isNotBlank()) {
for (i in 0 until level) {
result.append(' ').append(' ')
}
}
result.append(text).append('\n')
}
}
private fun generateIconFieldName(file: Path): CharSequence {
val imageFileName = file.fileName.toString()
val path = file.toString()
when {
path.contains("android/artwork/resources/studio") -> {
return toStreamingSnakeCaseJavaIdentifier(imageFileName, imageFileName.lastIndexOf('.'))
}
path.contains("android/artwork/resources/icons") -> {
return toCamelCaseJavaIdentifier(imageFileName, imageFileName.lastIndexOf('.'))
}
else -> {
val id = if ((imageFileName.length - 4) == 2) {
imageFileName.uppercase(Locale.ENGLISH)
}
else {
imageFileName.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.ENGLISH) else it.toString()
}
}
return toJavaIdentifier(id = id, endIndex = imageFileName.lastIndexOf('.'))
}
}
}
private fun getImageId(image: ImageInfo, depth: Int): String {
val path = image.id.removePrefix("/").split("/")
if (path.size < depth) {
throw IllegalArgumentException("Can't get image id - ${image.id}, $depth")
}
return path.drop(depth).joinToString("/")
}
private fun directoryName(module: JpsModule): CharSequence {
return directoryNameFromConfig(module) ?: className(module.name)
}
private fun directoryNameFromConfig(module: JpsModule): String? {
val rootUrl = getFirstContentRootUrl(module) ?: return null
val rootDir = Paths.get(JpsPathUtil.urlToPath(rootUrl))
val file = rootDir.resolve(ROBOTS_FILE_NAME)
val prefix = "name:"
try {
Files.lines(file).use { lines ->
for (line in lines) {
if (line.startsWith(prefix)) {
val name = line.substring(prefix.length).trim()
if (name.isNotEmpty()) {
return name
}
}
}
}
}
catch (ignore: NoSuchFileException) {
}
return null
}
private fun getFirstContentRootUrl(module: JpsModule) = module.contentRootsList.urls.firstOrNull()
private fun className(name: String): CharSequence {
val result = StringBuilder(name.length)
name.removePrefix("intellij.vcs.").removePrefix("intellij.").split('-', '_', '.').forEach {
result.append(capitalize(it))
}
return toJavaIdentifier(result, result.length)
}
private fun toJavaIdentifier(id: CharSequence, endIndex: Int): CharSequence {
var sb: StringBuilder? = null
var index = 0
while (index < endIndex) {
val c = id[index]
if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) {
sb?.append(c)
}
else {
if (sb == null) {
sb = StringBuilder(endIndex)
sb.append(id, 0, index)
}
if (c == '-') {
index++
if (index == endIndex) {
break
}
sb.append(id[index].uppercaseChar())
}
else {
sb.append('_')
}
}
index++
}
return sb ?: id.subSequence(0, endIndex)
}
private fun toStreamingSnakeCaseJavaIdentifier(id: String, endIndex: Int): CharSequence {
val sb = StringBuilder(endIndex)
var index = 0
while (index < endIndex) {
val c = id[index]
if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) {
sb.append(c.uppercaseChar())
}
else {
sb.append('_')
}
index++
}
return sb
}
private fun toCamelCaseJavaIdentifier(id: String, endIndex: Int): CharSequence {
val sb = StringBuilder(endIndex)
var index = 0
var upperCase = true
while (index < endIndex) {
val c = id[index]
if (c == '_' || c == '-') {
upperCase = true
}
else if (if (index == 0) Character.isJavaIdentifierStart(c) else Character.isJavaIdentifierPart(c)) {
if (upperCase) {
sb.append(c.uppercaseChar())
upperCase = false
}
else {
sb.append(c)
}
}
else {
sb.append('_')
}
index++
}
return sb
}
private fun capitalize(name: String): String {
return if (name.length == 2) name.uppercase(Locale.ENGLISH) else name.replaceFirstChar {
if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString()
}
}
private const val iconLoaderCode = "IconManager.getInstance()"
// grid-layout.svg duplicates grid-view.svg, but grid-layout_dark.svg differs from grid-view_dark.svg
// so, add filename to image id to support such scenario
internal fun getImageKey(fileData: ByteArray, fileName: String): Int {
val h = Murmur3_32Hash.Murmur3_32Hasher(0)
h.putBytes(fileData, 0, fileData.size)
h.putString(fileName)
return h.hash()
}
// remove line separators to unify line separators (\n vs \r\n), trim lines
// normalization is required because cache key is based on content
internal fun loadAndNormalizeSvgFile(svgFile: Path): String {
val builder = StringBuilder()
Files.lines(svgFile).use { lines ->
for (line in lines) {
for (start in line.indices) {
if (line[start].isWhitespace()) {
continue
}
var end = line.length
for (j in (line.length - 1) downTo (start + 1)) {
if (!line[j].isWhitespace()) {
end = j + 1
break
}
}
builder.append(line, start, end)
// if tag is not closed, space must be added to ensure that code on next line is separated from previous line of code
if (builder[end - 1] != '>') {
builder.append(' ')
}
break
}
}
}
return builder.toString()
}
private fun getPluginPackageIfPossible(module: JpsModule): String? {
for (resourceRoot in module.getSourceRoots(JavaResourceRootType.RESOURCE)) {
val root = Path.of(JpsPathUtil.urlToPath(resourceRoot.url))
var pluginXml = root.resolve("META-INF/plugin.xml")
if (!Files.exists(pluginXml)) {
// ok, any xml file
pluginXml = Files.newDirectoryStream(root).use { files -> files.find { it.toString().endsWith(".xml") } } ?: break
}
try {
return readXmlAsModel(Files.newInputStream(pluginXml)).getAttributeValue("package") ?: "icons"
}
catch (ignore: NoSuchFileException) {
}
catch (ignore: XMLStreamException) {
// ignore invalid XML
}
}
return null
} | apache-2.0 | 9e239ecde58ddaa68003200b7e87b839 | 34.630747 | 168 | 0.651343 | 4.394471 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ExpandBooleanExpressionIntention.kt | 1 | 2127 | // 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.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isBoolean
class ExpandBooleanExpressionIntention : SelfTargetingRangeIntention<KtExpression>(
KtExpression::class.java,
KotlinBundle.lazyMessage("expand.boolean.expression.to.if.else")
) {
override fun applicabilityRange(element: KtExpression): TextRange? {
if (!element.isTargetExpression() || element.parent.isTargetExpression()) return null
if (element.deparenthesize() is KtConstantExpression) return null
val parent = element.parent
if (parent is KtValueArgument || parent is KtParameter || parent is KtStringTemplateEntry) return null
val context = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
if (context[BindingContext.EXPRESSION_TYPE_INFO, element]?.type?.isBoolean() != true) return null
return element.textRange
}
private fun PsiElement.isTargetExpression() = this is KtSimpleNameExpression || this is KtCallExpression ||
this is KtQualifiedExpression || this is KtOperationExpression || this is KtParenthesizedExpression
override fun applyTo(element: KtExpression, editor: Editor?) {
val ifExpression = KtPsiFactory(element).createExpressionByPattern("if ($0) {\ntrue\n} else {\nfalse\n}", element)
val replaced = element.replace(ifExpression)
if (replaced != null) {
editor?.caretModel?.moveToOffset(replaced.startOffset)
}
}
}
| apache-2.0 | ed8c1644fdbe5c9f44962ac01fbda2c7 | 50.878049 | 158 | 0.765397 | 4.900922 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertPropertyGetterToInitializerIntention.kt | 5 | 2027 | // 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.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.endOffset
class ConvertPropertyGetterToInitializerIntention : SelfTargetingIntention<KtPropertyAccessor>(
KtPropertyAccessor::class.java, KotlinBundle.lazyMessage("convert.property.getter.to.initializer")
) {
override fun isApplicableTo(element: KtPropertyAccessor, caretOffset: Int): Boolean {
if (!element.isGetter || element.singleExpression() == null) return false
val property = element.parent as? KtProperty ?: return false
if (property.hasInitializer()
|| property.receiverTypeReference != null
|| property.containingClass()?.isInterface() == true
|| (property.descriptor as? PropertyDescriptor)?.isExpect == true
) return false
return true
}
override fun applyTo(element: KtPropertyAccessor, editor: Editor?) {
val property = element.parent as? KtProperty ?: return
val commentSaver = CommentSaver(property)
property.initializer = element.singleExpression()
property.deleteChildRange(property.initializer?.nextSibling, element)
editor?.caretModel?.moveToOffset(property.endOffset)
commentSaver.restore(property)
}
}
private fun KtPropertyAccessor.singleExpression(): KtExpression? = when (val bodyExpression = bodyExpression) {
is KtBlockExpression -> (bodyExpression.statements.singleOrNull() as? KtReturnExpression)?.returnedExpression
else -> bodyExpression
}
| apache-2.0 | 882fce162d7972d78bea66e9ced7d795 | 45.068182 | 158 | 0.75481 | 5.118687 | false | false | false | false |
mr-max/anko | dsl/testData/functional/sdk23/ComplexListenerClassTest.kt | 12 | 10246 | class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null
private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
_onViewAttachedToWindow?.invoke(v)
}
public fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) {
_onViewAttachedToWindow = listener
}
override fun onViewDetachedFromWindow(v: android.view.View) {
_onViewDetachedFromWindow?.invoke(v)
}
public fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) {
_onViewDetachedFromWindow = listener
}
}
class __TextWatcher : android.text.TextWatcher {
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
private var _onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
_beforeTextChanged?.invoke(s, start, count, after)
}
public fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
_onTextChanged?.invoke(s, start, before, count)
}
public fun onTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
override fun afterTextChanged(s: android.text.Editable?) {
_afterTextChanged?.invoke(s)
}
public fun afterTextChanged(listener: (android.text.Editable?) -> Unit) {
_afterTextChanged = listener
}
}
class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureStarted?.invoke(overlay, event)
}
public fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureStarted = listener
}
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGesture?.invoke(overlay, event)
}
public fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGesture = listener
}
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureEnded?.invoke(overlay, event)
}
public fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureEnded = listener
}
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
_onGestureCancelled?.invoke(overlay, event)
}
public fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureCancelled = listener
}
}
class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null
private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
_onGesturingStarted?.invoke(overlay)
}
public fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingStarted = listener
}
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
_onGesturingEnded?.invoke(overlay)
}
public fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingEnded = listener
}
}
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
_onChildViewAdded?.invoke(parent, child)
}
public fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
_onChildViewRemoved?.invoke(parent, child)
}
public fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null
private var _onScroll: ((android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
_onScrollStateChanged?.invoke(view, scrollState)
}
public fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) {
_onScrollStateChanged = listener
}
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
_onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
public fun onScroll(listener: (android.widget.AbsListView?, Int, Int, Int) -> Unit) {
_onScroll = listener
}
}
class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
_onItemSelected?.invoke(p0, p1, p2, p3)
}
public fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
_onItemSelected = listener
}
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
_onNothingSelected?.invoke(p0)
}
public fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) {
_onNothingSelected = listener
}
}
class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
public fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
public fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
public fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
public fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: ((android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
private var _onStopTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
_onProgressChanged?.invoke(seekBar, progress, fromUser)
}
public fun onProgressChanged(listener: (android.widget.SeekBar?, Int, Boolean) -> Unit) {
_onProgressChanged = listener
}
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStartTrackingTouch?.invoke(seekBar)
}
public fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStartTrackingTouch = listener
}
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
_onStopTrackingTouch?.invoke(seekBar)
}
public fun onStopTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStopTrackingTouch = listener
}
}
class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (() -> Unit)? = null
private var _onScrollEnded: (() -> Unit)? = null
override fun onScrollStarted() {
_onScrollStarted?.invoke()
}
public fun onScrollStarted(listener: () -> Unit) {
_onScrollStarted = listener
}
override fun onScrollEnded() {
_onScrollEnded?.invoke()
}
public fun onScrollEnded(listener: () -> Unit) {
_onScrollEnded = listener
}
} | apache-2.0 | 0d2cfe4aafd5fb34524006bd931ffa59 | 37.092937 | 129 | 0.700566 | 4.812588 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/utils/ToastUtils.kt | 1 | 1329 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.utils
import android.widget.Toast
import com.zwq65.unity.App
/**
* ================================================
* 防止多次调用弹出toast,统一以[ToastUtils]显示Toast
*
* Created by NIRVANA on 2017/09/29
* Contact with <[email protected]>
* ================================================
*/
object ToastUtils {
private var toast: Toast? = null
fun makeText(message: String, duration: Int) {
if (toast == null) {
toast = Toast.makeText(App.instance, message, duration)
} else {
toast!!.setText(message)
toast!!.duration = duration
}
toast!!.show()
}
}
| apache-2.0 | a14202fd3a781d8f43187b69ecb76bb2 | 29.302326 | 78 | 0.609363 | 4.097484 | false | false | false | false |
stakkato95/KotlinDroidPlayer | KMusic/app/src/main/java/com/github/stakkato95/kmusic/screen/main/widget/SimpleOnGestureListener.kt | 1 | 1416 | package com.github.stakkato95.kmusic.screen.main.widget
import android.view.GestureDetector
import android.view.MotionEvent
/**
* Created by artsiomkaliaha on 28.06.17.
*/
class SimpleOnGestureListener(
var onShowPressEvent: (MotionEvent) -> Unit = {},
var onSingleTapUpEvent: (MotionEvent?) -> Boolean = { false },
var onDownEvent: (MotionEvent?) -> Boolean = { false },
var onFlingEvent: (MotionEvent?, MotionEvent?, Float, Float) -> Boolean = { _, _, _, _ -> false },
var onScrollEvent: (MotionEvent?, MotionEvent?, Float, Float) -> Boolean = { _, _, _, _ -> false },
var onLongPressEvent: (MotionEvent?) -> Unit = {}) : GestureDetector.OnGestureListener {
override fun onShowPress(p0: MotionEvent?) {
onShowPressEvent.invoke(p0!!)
}
override fun onSingleTapUp(p0: MotionEvent?): Boolean {
return onSingleTapUpEvent.invoke(p0)
}
override fun onDown(p0: MotionEvent?): Boolean {
return onDownEvent.invoke(p0)
}
override fun onFling(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
return onFlingEvent.invoke(p0, p1, p2, p3)
}
override fun onScroll(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
return onScrollEvent.invoke(p0, p1, p2, p3)
}
override fun onLongPress(p0: MotionEvent?) {
onLongPressEvent.invoke(p0)
}
} | gpl-3.0 | c324a1898a862d0aa844c044752a0862 | 33.560976 | 107 | 0.649011 | 3.94429 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/ui/src/main/java/jp/hazuki/yuzubrowser/ui/widget/swipebutton/SmallButtonDrawable.kt | 1 | 1762 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.ui.widget.swipebutton
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.drawable.Drawable
import kotlin.math.min
class SmallButtonDrawable(private val icon: Drawable, private val maxSize: Int) : Drawable() {
override fun draw(canvas: Canvas) {
if (isVisible) {
icon.draw(canvas)
}
}
override fun setAlpha(alpha: Int) {
icon.alpha = alpha
}
@Deprecated("")
@Suppress("DEPRECATION")
override fun getOpacity() = icon.opacity
override fun setColorFilter(colorFilter: ColorFilter?) {
icon.colorFilter = colorFilter
}
override fun setBounds(left: Int, top: Int, right: Int, bottom: Int) {
super.setBounds(left, top, right, bottom)
val width = ((right - left) / 3f + 0.5f).toInt()
val height = ((bottom - top) / 3f + 0.5f).toInt()
val size = min(min(width, height), maxSize)
icon.setBounds(right - size, bottom - size, right, bottom)
}
override fun getIntrinsicWidth() = icon.intrinsicWidth
override fun getIntrinsicHeight() = icon.intrinsicHeight
}
| apache-2.0 | 17ee1cb98769c8f8c7975668dfb04b3e | 29.37931 | 94 | 0.684449 | 4.15566 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/skin/formatter/SkinCodeStyleSettings.kt | 1 | 1627 | @file:Suppress("PropertyName")
package com.gmail.blueboxware.libgdxplugin.filetypes.skin.formatter
import com.gmail.blueboxware.libgdxplugin.filetypes.skin.LibGDXSkinLanguage
import com.intellij.json.JsonBundle
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.CustomCodeStyleSettings
/*
*
* Adapted from
* https://github.com/JetBrains/intellij-community/blob/171.2152/json/src/com/intellij/json/formatter/JsonCodeStyleSettings.java
*
*/
class SkinCodeStyleSettings(container: CodeStyleSettings) :
CustomCodeStyleSettings(LibGDXSkinLanguage.INSTANCE.id, container) {
companion object {
val DO_NOT_ALIGN_PROPERTY = PropertyAlignment.DO_NOT_ALIGN.id
val ALIGN_PROPERTY_ON_VALUE = PropertyAlignment.ALIGN_ON_VALUE.id
val ALIGN_PROPERTY_ON_COLON = PropertyAlignment.ALIGN_ON_COLON.id
}
@JvmField
var SPACE_BEFORE_COLON = false
@JvmField
var SPACE_AFTER_COLON = true
@JvmField
var OBJECT_WRAPPING = CommonCodeStyleSettings.WRAP_ALWAYS
@JvmField
var ARRAY_WRAPPING = CommonCodeStyleSettings.WRAP_AS_NEEDED
@JvmField
var PROPERTY_ALIGNMENT = DO_NOT_ALIGN_PROPERTY
@JvmField
var DO_NOT_WRAP_COLORS = true
enum class PropertyAlignment(val description: String, val id: Int) {
DO_NOT_ALIGN(JsonBundle.message("formatter.align.properties.none"), 0),
ALIGN_ON_VALUE(JsonBundle.message("formatter.align.properties.on.value"), 1),
ALIGN_ON_COLON(JsonBundle.message("formatter.align.properties.on.colon"), 2);
}
}
| apache-2.0 | fb96f26c486b9a6201b9e2b1b3aa55ca | 30.288462 | 128 | 0.75169 | 4.047264 | false | false | false | false |
TonnyTao/Acornote | Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/colortag/ColorTagListFragment.kt | 1 | 1177 | package tonnysunm.com.acornote.ui.colortag
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import tonnysunm.com.acornote.databinding.FragmentColortagsBinding
private val TAG = "ColorTagListFragment"
open class ColorTagListFragment() : Fragment() {
val viewModel by viewModels<ColorTagViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val fragment = this
val binding = FragmentColortagsBinding.inflate(inflater, container, false).apply {
lifecycleOwner = fragment
viewModel = fragment.viewModel
recyclerview.adapter = ColorTagListAdapter(listOf())
}
viewModel.data.observe(this.viewLifecycleOwner, Observer {
val adapter = binding.recyclerview.adapter as ColorTagListAdapter
adapter.array = it
adapter.notifyDataSetChanged()
})
return binding.root
}
}
| apache-2.0 | 05088839016453d4c1ff1ac40123deb1 | 28.425 | 90 | 0.71198 | 5.117391 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/Interpreter.kt | 2 | 22418 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl.execution
import com.google.common.annotations.VisibleForTesting
import org.gradle.api.GradleScriptException
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.initialization.Settings
import org.gradle.api.initialization.dsl.ScriptHandler
import org.gradle.api.internal.GeneratedSubclass
import org.gradle.api.internal.file.temp.TemporaryFileProvider
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.invocation.Gradle
import org.gradle.groovy.scripts.ScriptSource
import org.gradle.initialization.ClassLoaderScopeOrigin
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.exceptions.LocationAwareException
import org.gradle.internal.hash.HashCode
import org.gradle.internal.service.ServiceRegistry
import org.gradle.kotlin.dsl.accessors.ProjectAccessorsClassPathGenerator
import org.gradle.kotlin.dsl.support.KotlinScriptHost
import org.gradle.kotlin.dsl.support.ScriptCompilationException
import org.gradle.kotlin.dsl.support.loggerFor
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.kotlin.dsl.support.serviceRegistryOf
import org.gradle.plugin.management.internal.PluginRequests
import java.io.File
import java.lang.reflect.InvocationTargetException
import kotlin.script.experimental.api.KotlinType
/**
* An optimised interpreter for the Kotlin DSL based on the idea of
* [partial evaluation](https://en.wikipedia.org/wiki/Partial_evaluation).
*
* Instead of interpreting a given Kotlin DSL script directly, the interpreter emits a
* specialized program that captures the optimal execution procedure for the particular
* combination of script structure (does it contain a `buildscript` block? a `plugins` block?
* a script body? etc), target object and context (top-level or not).
*
* The specialized program is then cached via a cheap cache key based on the original,
* unprocessed contents of the script, the target object type and parent `ClassLoader`.
*
* Because each program is specialized to a given script structure, a lot of work is
* avoided. For example, a top-level script containing a `plugins` block but no body
* can be compiled down to a specialized program that instantiates the precompiled
* `plugins` block class directly - without reflection - and does nothing else. The
* same strategy can be used for a **script plugin** (a non top-level script) with a
* body but no `buildscript` block since the classpath is completely determined at
* the time the specialized program is emitted.
*
* @see Program
* @see PartialEvaluator
* @see ResidualProgram
* @see ResidualProgramCompiler
*/
class Interpreter(val host: Host) {
interface Host {
fun cachedClassFor(
programId: ProgramId
): CompiledScript?
fun cache(
specializedProgram: CompiledScript,
programId: ProgramId
)
fun cachedDirFor(
scriptHost: KotlinScriptHost<*>,
templateId: String,
sourceHash: HashCode,
compilationClassPath: ClassPath,
accessorsClassPath: ClassPath,
initializer: (File) -> Unit
): File
fun startCompilerOperation(
description: String
): AutoCloseable
fun compilationClassPathOf(
classLoaderScope: ClassLoaderScope
): ClassPath
/**
* Provides an additional [ClassPath] to be used in the compilation of a top-level [Project] script
* `plugins` block.
*
* The [ClassPath] is assumed not to influence the cache key of the script by itself as it should
* already be implied by [ProgramId.parentClassLoader].
*/
fun pluginAccessorsFor(
scriptHost: KotlinScriptHost<*>
): ClassPath
fun loadClassInChildScopeOf(
classLoaderScope: ClassLoaderScope,
childScopeId: String,
origin: ClassLoaderScopeOrigin,
location: File,
className: String,
accessorsClassPath: ClassPath
): CompiledScript
fun applyPluginsTo(
scriptHost: KotlinScriptHost<*>,
pluginRequests: PluginRequests
)
fun applyBasePluginsTo(project: ProjectInternal)
fun setupEmbeddedKotlinFor(scriptHost: KotlinScriptHost<*>)
fun closeTargetScopeOf(scriptHost: KotlinScriptHost<*>)
fun hashOf(classPath: ClassPath): HashCode
fun runCompileBuildOperation(scriptPath: String, stage: String, action: () -> String): String
fun onScriptClassLoaded(scriptSource: ScriptSource, specializedProgram: Class<*>)
val implicitImports: List<String>
fun serviceRegistryFor(programTarget: ProgramTarget, target: Any): ServiceRegistry = when (programTarget) {
ProgramTarget.Project -> serviceRegistryOf(target as Project)
ProgramTarget.Settings -> serviceRegistryOf(target as Settings)
ProgramTarget.Gradle -> serviceRegistryOf(target as Gradle)
}
}
fun eval(
target: Any,
scriptSource: ScriptSource,
sourceHash: HashCode,
scriptHandler: ScriptHandler,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope,
topLevelScript: Boolean,
options: EvalOptions = defaultEvalOptions
) {
val programKind =
if (topLevelScript) ProgramKind.TopLevel
else ProgramKind.ScriptPlugin
val programTarget =
programTargetFor(target)
val templateId =
templateIdFor(programTarget, programKind, "stage1")
val parentClassLoader =
baseScope.exportClassLoader
val programId =
ProgramId(templateId, sourceHash, parentClassLoader)
val cachedProgram =
host.cachedClassFor(programId)
val scriptHost =
scriptHostFor(programTarget, target, scriptSource, scriptHandler, targetScope, baseScope)
val programHost =
programHostFor(options)
if (cachedProgram != null) {
programHost.eval(cachedProgram, scriptHost)
return
}
val specializedProgram =
emitSpecializedProgramFor(
scriptHost,
scriptSource,
sourceHash,
templateId,
targetScope,
baseScope,
programKind,
programTarget
)
host.cache(
specializedProgram,
programId
)
programHost.eval(specializedProgram, scriptHost)
}
private
fun programTargetFor(target: Any): ProgramTarget =
when (target) {
is Settings -> ProgramTarget.Settings
is Project -> ProgramTarget.Project
is Gradle -> ProgramTarget.Gradle
else -> throw IllegalArgumentException("Unsupported target: $target")
}
private
fun scriptHostFor(
programTarget: ProgramTarget,
target: Any,
scriptSource: ScriptSource,
scriptHandler: ScriptHandler,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope
) =
KotlinScriptHost(
target,
scriptSource,
scriptHandler,
targetScope,
baseScope,
host.serviceRegistryFor(programTarget, target)
)
private
fun programHostFor(options: EvalOptions) =
if (EvalOption.SkipBody in options) FirstStageOnlyProgramHost() else defaultProgramHost
private
fun emitSpecializedProgramFor(
scriptHost: KotlinScriptHost<Any>,
scriptSource: ScriptSource,
sourceHash: HashCode,
templateId: String,
targetScope: ClassLoaderScope,
baseScope: ClassLoaderScope,
programKind: ProgramKind,
programTarget: ProgramTarget
): CompiledScript {
// TODO: consider computing plugin accessors only when there's a plugins block
val pluginAccessorsClassPath = when {
requiresAccessors(programTarget, programKind) -> host.pluginAccessorsFor(scriptHost)
else -> ClassPath.EMPTY
}
val scriptPath = scriptHost.fileName
val classesDir = compile(
scriptHost,
templateId,
scriptPath,
scriptSource,
sourceHash,
programKind,
programTarget,
host.compilationClassPathOf(targetScope.parent),
pluginAccessorsClassPath,
scriptHost.temporaryFileProvider
)
return loadClassInChildScopeOf(
baseScope,
scriptPath,
classesDir,
templateId,
pluginAccessorsClassPath,
scriptSource
)
}
private
fun compile(
scriptHost: KotlinScriptHost<*>,
templateId: String,
scriptPath: String,
scriptSource: ScriptSource,
sourceHash: HashCode,
programKind: ProgramKind,
programTarget: ProgramTarget,
compilationClassPath: ClassPath,
pluginAccessorsClassPath: ClassPath,
temporaryFileProvider: TemporaryFileProvider
): File = host.cachedDirFor(
scriptHost,
templateId,
sourceHash,
compilationClassPath,
ClassPath.EMPTY
) { cachedDir ->
startCompilerOperationFor(scriptSource, templateId).use {
val sourceText =
scriptSource.resource!!.text
val programSource =
ProgramSource(scriptPath, sourceText)
val program =
ProgramParser.parse(programSource, programKind, programTarget)
val residualProgram = program.map(
PartialEvaluator(programKind, programTarget)::reduce
)
scriptSource.withLocationAwareExceptionHandling {
ResidualProgramCompiler(
outputDir = cachedDir,
classPath = compilationClassPath,
originalSourceHash = sourceHash,
programKind = programKind,
programTarget = programTarget,
implicitImports = host.implicitImports,
logger = interpreterLogger,
temporaryFileProvider = temporaryFileProvider,
compileBuildOperationRunner = host::runCompileBuildOperation,
pluginAccessorsClassPath = pluginAccessorsClassPath,
packageName = residualProgram.packageName,
injectedProperties = scriptHost.injectedProperties
).compile(residualProgram.document)
}
}
}
private
val KotlinScriptHost<*>.injectedProperties: Map<String, KotlinType>
get() = when (target) {
is Project -> {
target.extensions.findByType(VersionCatalogsExtension::class.java)
?.map { it.name to target.extensions.findByName(it.name) }
?.filter { it.second != null }
?.associate { it.first to it.second!!.getKotlinType() }
?: mapOf()
}
else -> mapOf()
}
private
fun Any.getKotlinType(): KotlinType = when (this) {
is GeneratedSubclass -> KotlinType(this.publicType().kotlin)
else -> KotlinType(this.javaClass.kotlin)
}
private
fun loadClassInChildScopeOf(
baseScope: ClassLoaderScope,
scriptPath: String,
classesDir: File,
scriptTemplateId: String,
accessorsClassPath: ClassPath,
scriptSource: ScriptSource
): CompiledScript {
logClassLoadingOf(scriptTemplateId, scriptSource)
return host.loadClassInChildScopeOf(
baseScope,
childScopeId = classLoaderScopeIdFor(scriptPath, scriptTemplateId),
origin = ClassLoaderScopeOrigin.Script(scriptSource.fileName, scriptSource.displayName),
accessorsClassPath = accessorsClassPath,
location = classesDir,
className = "Program"
)
}
private
val defaultProgramHost = ProgramHost()
private
inner class FirstStageOnlyProgramHost : ProgramHost() {
override fun evaluateSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
accessorsClassPath: ClassPath
) = Unit
}
private
open inner class ProgramHost : ExecutableProgram.Host {
override fun setupEmbeddedKotlinFor(scriptHost: KotlinScriptHost<*>) {
host.setupEmbeddedKotlinFor(scriptHost)
}
override fun applyPluginsTo(scriptHost: KotlinScriptHost<*>, pluginRequests: PluginRequests) {
host.applyPluginsTo(scriptHost, pluginRequests)
}
override fun applyBasePluginsTo(project: Project) {
host.applyBasePluginsTo(project as ProjectInternal)
}
override fun handleScriptException(
exception: Throwable,
scriptClass: Class<*>,
scriptHost: KotlinScriptHost<*>
) {
locationAwareExceptionHandlingFor(exception, scriptClass, scriptHost.scriptSource)
}
override fun closeTargetScopeOf(scriptHost: KotlinScriptHost<*>) {
host.closeTargetScopeOf(scriptHost)
}
override fun evaluateSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
accessorsClassPath: ClassPath
) {
val targetScope = scriptHost.targetScope
val parentClassLoader = targetScope.exportClassLoader
val compileClassPath = host.compilationClassPathOf(targetScope.parent)
val programId = ProgramId(
scriptTemplateId,
sourceHash,
parentClassLoader,
host.hashOf(accessorsClassPath),
host.hashOf(compileClassPath)
)
val cachedProgram = host.cachedClassFor(programId)
if (cachedProgram != null) {
eval(cachedProgram, scriptHost)
return
}
val specializedProgram =
program.loadSecondStageFor(
this,
scriptHost,
scriptTemplateId,
sourceHash,
accessorsClassPath
)
host.cache(
specializedProgram,
programId
)
eval(specializedProgram, scriptHost)
}
override fun accessorsClassPathFor(scriptHost: KotlinScriptHost<*>): ClassPath {
val project = scriptHost.target as Project
val projectAccessorsClassPathGenerator = project.serviceOf<ProjectAccessorsClassPathGenerator>()
return projectAccessorsClassPathGenerator.projectAccessorsClassPath(
project,
host.compilationClassPathOf(scriptHost.targetScope)
).bin
}
override fun compileSecondStageOf(
program: ExecutableProgram.StagedProgram,
scriptHost: KotlinScriptHost<*>,
scriptTemplateId: String,
sourceHash: HashCode,
programKind: ProgramKind,
programTarget: ProgramTarget,
accessorsClassPath: ClassPath
): CompiledScript {
val originalScriptPath = scriptHost.fileName
val targetScope = scriptHost.targetScope
val scriptSource = scriptHost.scriptSource
val targetScopeClassPath = host.compilationClassPathOf(targetScope)
val compilationClassPath = targetScopeClassPath + accessorsClassPath
val cacheDir =
host.cachedDirFor(
scriptHost,
scriptTemplateId,
sourceHash,
compilationClassPath,
accessorsClassPath
) { outputDir ->
startCompilerOperationFor(scriptSource, scriptTemplateId).use {
scriptSource.withLocationAwareExceptionHandling {
scriptHost.temporaryFileProvider.withTemporaryScriptFileFor(originalScriptPath, program.secondStageScriptText) { scriptFile ->
ResidualProgramCompiler(
outputDir,
compilationClassPath,
sourceHash,
programKind,
programTarget,
host.implicitImports,
interpreterLogger,
scriptHost.temporaryFileProvider,
host::runCompileBuildOperation
).emitStage2ProgramFor(
scriptFile,
originalScriptPath
)
}
}
}
}
return loadClassInChildScopeOf(
targetScope,
originalScriptPath,
cacheDir,
scriptTemplateId,
accessorsClassPath,
scriptSource
)
}
fun eval(compiledScript: CompiledScript, scriptHost: KotlinScriptHost<*>) {
val program = load(compiledScript, scriptHost)
withContextClassLoader(program.classLoader) {
host.onScriptClassLoaded(scriptHost.scriptSource, program)
instantiate(program).execute(this, scriptHost)
}
}
private
fun load(compiledScript: CompiledScript, scriptHost: KotlinScriptHost<*>) =
try {
compiledScript.program
} catch (e: Exception) {
throw LocationAwareException(
GradleScriptException("Failed to load compiled script from classpath ${compiledScript.classPath}.", e),
scriptHost.scriptSource,
1
)
}
private
fun instantiate(specializedProgram: Class<*>) =
specializedProgram.getDeclaredConstructor().newInstance() as ExecutableProgram
}
private
fun startCompilerOperationFor(scriptSource: ScriptSource, scriptTemplateId: String): AutoCloseable {
logCompilationOf(scriptTemplateId, scriptSource)
return host.startCompilerOperation(scriptSource.shortDisplayName.displayName)
}
}
@VisibleForTesting
fun templateIdFor(programTarget: ProgramTarget, programKind: ProgramKind, stage: String): String =
programTarget.name + "/" + programKind.name + "/" + stage
private
fun classLoaderScopeIdFor(scriptPath: String, stage: String) =
"kotlin-dsl:$scriptPath:$stage"
private
fun locationAwareExceptionHandlingFor(e: Throwable, scriptClass: Class<*>, scriptSource: ScriptSource): Nothing {
val targetException = maybeUnwrapInvocationTargetException(e)
val locationAware = locationAwareExceptionFor(targetException, scriptClass, scriptSource)
throw locationAware ?: targetException
}
private
fun locationAwareExceptionFor(
original: Throwable,
scriptClass: Class<*>,
scriptSource: ScriptSource
): LocationAwareException? {
val scriptClassName = scriptClass.name
val scriptClassNameInnerPrefix = "$scriptClassName$"
fun scriptStackTraceElement(element: StackTraceElement) =
element.className?.run {
equals(scriptClassName) || startsWith(scriptClassNameInnerPrefix)
} == true
tailrec fun inferLocationFrom(exception: Throwable): LocationAwareException? {
if (exception is LocationAwareException) {
return exception
}
exception.stackTrace.find(::scriptStackTraceElement)?.run {
return LocationAwareException(original, scriptSource, lineNumber.takeIf { it >= 0 })
}
val cause = exception.cause ?: return null
return inferLocationFrom(cause)
}
return inferLocationFrom(original)
}
private
inline fun <T> ScriptSource.withLocationAwareExceptionHandling(action: () -> T): T =
try {
action()
} catch (e: ScriptCompilationException) {
throw LocationAwareException(e, this, e.firstErrorLine)
}
private
fun maybeUnwrapInvocationTargetException(e: Throwable) =
if (e is InvocationTargetException) e.targetException
else e
private
inline fun withContextClassLoader(classLoader: ClassLoader, block: () -> Unit) {
val currentThread = Thread.currentThread()
val previous = currentThread.contextClassLoader
try {
currentThread.contextClassLoader = classLoader
block()
} finally {
currentThread.contextClassLoader = previous
}
}
private
fun logCompilationOf(templateId: String, source: ScriptSource) {
interpreterLogger.debug("Compiling $templateId from ${source.displayName}")
}
private
fun logClassLoadingOf(templateId: String, source: ScriptSource) {
interpreterLogger.debug("Loading $templateId from ${source.displayName}")
}
internal
val interpreterLogger = loggerFor<Interpreter>()
| apache-2.0 | 830af60f997967451d10432ac4d75922 | 33.17378 | 154 | 0.63275 | 5.880902 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/testFixtures/kotlin/org/gradle/kotlin/dsl/fixtures/bytecode/AsmExtensions.kt | 4 | 7598 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.kotlin.dsl.fixtures.bytecode
import org.jetbrains.org.objectweb.asm.ClassVisitor
import org.jetbrains.org.objectweb.asm.ClassWriter
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
import org.jetbrains.org.objectweb.asm.Opcodes.T_BYTE
import org.jetbrains.org.objectweb.asm.Type
import kotlin.reflect.KClass
fun publicClass(
name: InternalName,
superName: InternalName? = null,
interfaces: List<InternalName>? = null,
classBody: ClassWriter.() -> Unit = {}
) = beginPublicClass(name, superName, interfaces).run {
classBody()
endClass()
}
internal
fun beginPublicClass(name: InternalName, superName: InternalName? = null, interfaces: List<InternalName>? = null) =
beginClass(Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL, name, superName, interfaces)
internal
fun beginClass(
modifiers: Int,
name: InternalName,
superName: InternalName? = null,
interfaces: List<InternalName>? = null
): ClassWriter = ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES).apply {
visit(
Opcodes.V1_8,
modifiers,
name.value,
null,
(superName ?: InternalNameOf.javaLangObject).value,
interfaces?.map { it.value }?.toTypedArray()
)
}
internal
fun ClassWriter.endClass(): ByteArray {
visitEnd()
return toByteArray()
}
fun ClassWriter.publicDefaultConstructor(superName: InternalName = InternalNameOf.javaLangObject) {
publicMethod("<init>", "()V") {
ALOAD(0)
INVOKESPECIAL(superName, "<init>", "()V")
RETURN()
}
}
internal
fun ClassVisitor.publicStaticMethod(
name: String,
desc: String,
signature: String? = null,
exceptions: Array<String>? = null,
methodBody: MethodVisitor.() -> Unit
) {
method(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, name, desc, signature, exceptions, methodBody)
}
fun ClassVisitor.publicMethod(
name: String,
desc: String,
signature: String? = null,
exceptions: Array<String>? = null,
methodBody: MethodVisitor.() -> Unit
) {
method(Opcodes.ACC_PUBLIC, name, desc, signature, exceptions, methodBody)
}
internal
fun ClassVisitor.method(
access: Int,
name: String,
desc: String,
signature: String? = null,
exceptions: Array<String>? = null,
methodBody: MethodVisitor.() -> Unit
) {
visitMethod(access, name, desc, signature, exceptions).apply {
visitCode()
methodBody()
visitMaxs(0, 0)
visitEnd()
}
}
internal
fun MethodVisitor.loadByteArray(byteArray: ByteArray) {
LDC(byteArray.size)
NEWARRAY(T_BYTE)
for ((i, byte) in byteArray.withIndex()) {
DUP()
LDC(i)
LDC(byte)
BASTORE()
}
}
internal
fun MethodVisitor.NEW(type: InternalName) {
visitTypeInsn(Opcodes.NEW, type)
}
internal
fun MethodVisitor.visitTypeInsn(opcode: Int, type: InternalName) {
visitTypeInsn(opcode, type.value)
}
internal
fun MethodVisitor.NEWARRAY(primitiveType: Int) {
visitIntInsn(Opcodes.NEWARRAY, primitiveType)
}
internal
fun MethodVisitor.LDC(type: InternalName) {
visitLdcInsn(Type.getType("L${type.value};"))
}
internal
fun MethodVisitor.LDC(value: Any) {
visitLdcInsn(value)
}
internal
fun MethodVisitor.INVOKEVIRTUAL(owner: InternalName, name: String, desc: String, itf: Boolean = false) {
visitMethodInsn_(Opcodes.INVOKEVIRTUAL, owner, name, desc, itf)
}
internal
fun MethodVisitor.INVOKESPECIAL(owner: InternalName, name: String, desc: String, itf: Boolean = false) {
visitMethodInsn_(Opcodes.INVOKESPECIAL, owner, name, desc, itf)
}
internal
fun MethodVisitor.INVOKEINTERFACE(owner: InternalName, name: String, desc: String, itf: Boolean = true) {
visitMethodInsn_(Opcodes.INVOKEINTERFACE, owner, name, desc, itf)
}
internal
fun MethodVisitor.INVOKESTATIC(owner: InternalName, name: String, desc: String) {
visitMethodInsn_(Opcodes.INVOKESTATIC, owner, name, desc, false)
}
private
fun MethodVisitor.visitMethodInsn_(opcode: Int, owner: InternalName, name: String, desc: String, itf: Boolean) {
visitMethodInsn(opcode, owner.value, name, desc, itf)
}
internal
fun MethodVisitor.BASTORE() {
visitInsn(Opcodes.BASTORE)
}
internal
fun MethodVisitor.DUP() {
visitInsn(Opcodes.DUP)
}
internal
fun MethodVisitor.ARETURN() {
visitInsn(Opcodes.ARETURN)
}
fun MethodVisitor.RETURN() {
visitInsn(Opcodes.RETURN)
}
internal
fun MethodVisitor.ALOAD(`var`: Int) {
visitVarInsn(Opcodes.ALOAD, `var`)
}
internal
fun MethodVisitor.ASTORE(`var`: Int) {
visitVarInsn(Opcodes.ASTORE, `var`)
}
internal
fun MethodVisitor.GOTO(label: Label) {
visitJumpInsn(Opcodes.GOTO, label)
}
internal
inline fun <reified T> MethodVisitor.TRY_CATCH(
noinline tryBlock: MethodVisitor.() -> Unit,
noinline catchBlock: MethodVisitor.() -> Unit
) =
TRY_CATCH(T::class.internalName, tryBlock, catchBlock)
internal
fun MethodVisitor.TRY_CATCH(
exceptionType: InternalName,
tryBlock: MethodVisitor.() -> Unit,
catchBlock: MethodVisitor.() -> Unit
) {
val tryBlockStart = Label()
val tryBlockEnd = Label()
val catchBlockStart = Label()
val catchBlockEnd = Label()
visitTryCatchBlock(tryBlockStart, tryBlockEnd, catchBlockStart, exceptionType.value)
visitLabel(tryBlockStart)
tryBlock()
GOTO(catchBlockEnd)
visitLabel(tryBlockEnd)
visitLabel(catchBlockStart)
catchBlock()
visitLabel(catchBlockEnd)
}
internal
fun <T : Enum<T>> MethodVisitor.GETSTATIC(field: T) {
val owner = field.declaringClass.internalName
GETSTATIC(owner, field.name, "L$owner;")
}
internal
fun MethodVisitor.GETSTATIC(owner: InternalName, name: String, desc: String) {
visitFieldInsn(Opcodes.GETSTATIC, owner.value, name, desc)
}
internal
fun MethodVisitor.GETFIELD(owner: InternalName, name: String, desc: String) {
visitFieldInsn(Opcodes.GETFIELD, owner.value, name, desc)
}
internal
fun MethodVisitor.PUTFIELD(owner: InternalName, name: String, desc: String) {
visitFieldInsn(Opcodes.PUTFIELD, owner.value, name, desc)
}
internal
fun MethodVisitor.CHECKCAST(type: InternalName) {
visitTypeInsn(Opcodes.CHECKCAST, type)
}
internal
fun MethodVisitor.ACONST_NULL() {
visitInsn(Opcodes.ACONST_NULL)
}
/**
* A JVM internal type name (as in `java/lang/Object` instead of `java.lang.Object`).
*/
@Suppress("experimental_feature_warning")
inline class InternalName(val value: String) {
companion object {
fun from(sourceName: String) = InternalName(sourceName.replace('.', '/'))
}
override fun toString() = value
}
internal
object InternalNameOf {
val javaLangObject = InternalName("java/lang/Object")
}
val KClass<*>.internalName: InternalName
get() = java.internalName
inline val Class<*>.internalName: InternalName
get() = InternalName(Type.getInternalName(this))
| apache-2.0 | e24b3e717fa181de399511b2e344bfc5 | 22.024242 | 115 | 0.711371 | 3.932712 | false | false | false | false |
Alfresco/activiti-android-app | auth-library/src/main/kotlin/com/alfresco/ui/components/SnackbarContentLayout.kt | 1 | 1852 | package com.alfresco.ui.components
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RestrictTo
import com.alfresco.android.aims.R
import com.google.android.material.snackbar.ContentViewCallback
/** @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class SnackbarContentLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs), ContentViewCallback {
lateinit var titleView: TextView
private set
lateinit var messageView: TextView
private set
lateinit var actionView: Button
private set
override fun onFinishInflate() {
super.onFinishInflate()
titleView = findViewById(R.id.snackbar_title)
messageView = findViewById(R.id.snackbar_message)
actionView = findViewById(R.id.snackbar_action)
}
override fun animateContentIn(delay: Int, duration: Int) {
titleView.alpha = 0f
titleView.animate().alpha(1f).setDuration(duration.toLong()).setStartDelay(delay.toLong()).start()
if (actionView.visibility == View.VISIBLE) {
actionView.alpha = 0f
actionView.animate().alpha(1f).setDuration(duration.toLong()).setStartDelay(delay.toLong()).start()
}
}
override fun animateContentOut(delay: Int, duration: Int) {
titleView.alpha = 1f
titleView.animate().alpha(0f).setDuration(duration.toLong()).setStartDelay(delay.toLong()).start()
if (actionView.visibility == View.VISIBLE) {
actionView.alpha = 1f
actionView.animate().alpha(0f).setDuration(duration.toLong()).setStartDelay(delay.toLong()).start()
}
}
}
| lgpl-3.0 | f57e86ae11df2d6f4dae9c5715d5b32f | 35.313725 | 154 | 0.711123 | 4.462651 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/dt.kt | 1 | 21199 | package edu.kit.iti.formal.automation.datatypes
import edu.kit.iti.formal.automation.VariableScope
import edu.kit.iti.formal.automation.datatypes.values.*
import edu.kit.iti.formal.automation.st.Identifiable
import edu.kit.iti.formal.automation.st.ast.*
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*
import java.util.regex.Pattern
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
import kotlin.math.ceil
import kotlin.math.ln
sealed class AnyDt(override var name: String = "ANY") : Identifiable {
constructor() : this("") {
name = javaClass.getSimpleName().toUpperCase()
}
abstract fun repr(obj: Any): String
abstract fun <T> accept(visitor: DataTypeVisitorNN<T>): T
override fun toString() = name
open fun reprDecl(): String = "n/a"
fun isAnonym(): Boolean = name.equals(ANONYM_DATATYPE)
fun isAssignableTo(expected: AnyDt): Boolean = accept(DataTypeAssignability(expected))
companion object {
val ANONYM_DATATYPE = "ANONYM"
}
}
object VOID : AnyDt("VOID") {
override fun repr(obj: Any): String = TODO("not implemented")
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T = visitor.visit(this)
}
/**
* Created by weigl on 10.06.14.
*
* @author weigl
* @version $Id: $Id
*/
open class AnyNum : AnyDt("ANY_NUM") {
/** {@inheritDoc} */
override fun repr(obj: Any): String {
throw IllegalStateException("No repr for AnyNum")
}
/** {@inheritDoc} */
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
companion object {
val ANY_NUM: AnyDt = AnyNum()
}
}
abstract class AnyReal : AnyNum() {
override fun repr(obj: Any): String {
val d = obj as BigDecimal
return name.toUpperCase() + "#" + d
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
object REAL : AnyReal() {
init {
name = "REAL"
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
object LREAL : AnyReal() {
init {
name = "LREAL"
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
}
/**
* Created by weigl on 10.06.14.
*
* @author weigl
* @version $Id: $Id
*/
abstract class AnyBit(var bitLength: Int = 0) : AnyDt() {
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T = visitor.visit(this)
override fun repr(obj: Any): String {
if (obj is Bits)
if (obj.register > 0)
return (name.toUpperCase() + "#2#" + java.lang.Long.toBinaryString(obj.register))
return ""
}
object BOOL : AnyBit(1) {
override fun repr(obj: Any): String {
if (obj is Bits) {
if (obj.register > 0)
return "TRUE"
}
if (obj is Boolean) {
if (obj)
return "TRUE"
}
return "FALSE"
}
override fun toString(): String = name
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
object BYTE : AnyBit(8) {
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
object WORD : AnyBit(16) {
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
object DWORD : AnyBit(32) {
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
object LWORD : AnyBit(64) {
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
companion object {
val DATATYPES = Arrays.asList(AnyBit.BYTE,
AnyBit.LWORD, AnyBit.WORD, AnyBit.DWORD, AnyBit.BOOL)
}
}
/**
*
* Abstract AnyDate class.
*
* @author weigl
* @version $Id: $Id
*/
abstract class AnyDate(name: String = "ANY_DATE") : AnyDt(name) {
object DATE : AnyDate("DATE") {
override fun repr(obj: Any): String {
val dt = obj as DateData
return String.format("DATE#%4d-%2d-%2d",
dt.year, dt.month, dt.day)
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object TIME_OF_DAY : AnyDate("TIME_OF_DAY") {
override fun repr(obj: Any): String {
val dt = obj as TimeofDayData
return String.format("TOD#%2d:%2d:%2d.%3d",
dt.hours, dt.minutes, dt.seconds, dt.millieseconds)
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object DATE_AND_TIME : AnyDate("DATE_AND_TIME") {
override fun repr(obj: Any): String {
val dt = obj as DateAndTimeData
return String.format("DT#%4d-%2d-%2d-%2d:%2d:%2d.%3d",
dt.year, dt.month, dt.day, dt.hours, dt.minutes, dt.seconds, dt.millieSeconds)
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
}
class ArrayType(name: String, val fieldType: AnyDt,
var ranges: MutableList<Range> = ArrayList()) : AnyDt(name) {
constructor(fieldType: AnyDt, ranges: List<Range>)
: this(ANONYM_DATATYPE, fieldType, ranges.toMutableList())
/*
constructor(arrayTypeDeclaration: ArrayTypeDeclaration) {
fieldType = arrayTypeDeclaration.baseType
ranges = arrayTypeDeclaration.ranges
}
*/
override fun repr(obj: Any): String {
val ary = obj as MultiDimArrayValue
return ary.internalData().joinToString(",") { fieldType.repr(it) }
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T = visitor.visit(this)
fun allIndices() =
ranges.map { it.toIntRange() }.expand()
fun dimSize(d: Int): Int = ranges[d].stopValue
override fun reprDecl(): String {
return if (isAnonym())
ranges.joinToString(", ", " ARRAY[", "] of ${fieldType.reprDecl()}") {
"${it.startValue}..${it.stopValue}"
}
else
name
}
}
/**
* Super highly complicated code, do not touch.
*/
fun List<IntRange>.expand(): Array<IntArray> {
val span = this.map { it.last - it.first + 1 }
val amount = span.reduce { a, b -> a * b }
val factorRight = IntArray(size) { 0 }
factorRight[size - 1] = 1
for (i in (size - 2) downTo 0)
factorRight[i] = factorRight[i + 1] * span[i + 1]
val arrays = Array(amount) { IntArray(this.size) { -1 } }
forEachIndexed { arrayPos, idxRange ->
val factor = factorRight[arrayPos]
val r = factor
val outer = amount / span[arrayPos] / r
var apos = 0
repeat(outer) {
idxRange.forEach { idx ->
repeat(r) {
arrays[apos++][arrayPos] = idx
}
}
}
}
return arrays
}
/**
* This data type represents a class.
*
* @author Alexander Weigl, Augusto Modanese
* @version 1
* @since 04.03.17
*/
sealed class ClassDataType(name: String) : AnyDt(name) {
object AnyClassDt : ClassDataType("BOTTOM CLASS")
class ClassDt(val clazz: ClassDeclaration) : ClassDataType(clazz.name)
class InterfaceDt(val clazz: InterfaceDeclaration) : ClassDataType(clazz.name)
override fun repr(obj: Any) =
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
/* override var fields: Scope
get() = Scope(OOUtils.getEffectiveScope(clazz).parallelStream()
.map<VariableDeclaration>(Function<VariableDeclaration, VariableDeclaration> { it.copy() })
.collect<List<VariableDeclaration>, Any>(Collectors.toList()))
set(value: Scope) {
super.fields = value
}
*/
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
abstract class IECString : AnyDt() {
object WSTRING : IECString() {
override fun repr(obj: Any) = "WSTRING#\"$obj\""
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
/** Constant `STRING_16BIT` */
object STRING : IECString() {
override fun repr(obj: Any) = "WSTRING#'$obj'"
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
companion object {
/**
* Interprets escape chars in IEC strings.
Escape Sequences
The dollar sign ($) is used as an escape character to insert any character code into a string.
Sequence Usage Description
$$ Both Dollar sign ($) character
$' Single Apostrophe (') character
$" Double Double quotation mark (") character
$L Both Line feed (U+000A) character
$N Both Line feed (U+000A) character
$R Both Carriage return (U+000D) character
$T Both Horizontal tab (U+0009) character
$nn Single Single byte character, where nn is the two digit hexadecimal value of the character
$nnnn Double Double byte character, where nnnn is the four digit hexadecimal value of the character
*/
fun interpret(str: String): String = when {
str.startsWith("'") -> interpret(str.trim('\''), false)
str.startsWith("\"") -> interpret(str.trim('"'), true)
else -> interpret(str, true)
}
@JvmStatic
fun interpret(str: String, wide: Boolean): String {
val sb = StringBuffer()
val bytes = if (wide) 4 else 2
val pattern = Pattern.compile("[\$]([\"'NLRTnlrt]|[0-9]{$bytes})")
val m = pattern.matcher(str)
while (m.find()) {
val replacement = when (m.group(1).toUpperCase()) {
"$" -> "$"
"'" -> "'"
"\"" -> "\""
"L" -> "\u000A"
"N" -> "\u000A"
"R" -> "\u000D"
"T" -> "\t"
else -> {
val v = m.group(1)
//$nn Single Single byte character, where nn is the two digit hexadecimal value of the character
//$nnnn Double Double byte character, where nnnn is the four digit hexadecimal value of the character
v.toInt().toChar().toString()
}
}
m.appendReplacement(sb, replacement);
}
m.appendTail(sb);
return sb.toString()
}
}
}
/**
* Created by weigl on 25.11.16.
*
* @author weigl
* @version $Id: $Id
*/
data class FunctionBlockDataType(var functionBlock: FunctionBlockDeclaration) : AnyDt() {
override fun repr(obj: Any): String {
return this.functionBlock!!.name
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
fun asRecord(): RecordType {
val rt = RecordType(functionBlock.name, functionBlock.scope.variables)
return rt
}
override var name: String
get() = functionBlock.name
set(value) {}
}
/**
* Created by weigl on 10.06.14.
*
* @author weigl
*/
class EnumerateType(name: String = "ENUM",
var allowedValues: LinkedHashMap<String, Int> = LinkedHashMap()) : AnyDt(name) {
lateinit var defValue: String
val bitlength: Int
get() {
return ceil(ln(allowedValues.size.toDouble())).toInt()
}
constructor(name: String, allowedValues: MutableList<String>,
defValue: String = allowedValues[0]) : this(name) {
allowedValues.forEachIndexed { index, s -> this.allowedValues[s] = index }
this.defValue = defValue
}
constructor(etd: EnumerationTypeDeclaration) : this() {
name = etd.name
etd.allowedValues.zip(etd.values).forEach { (a, b) ->
allowedValues.put(a.text!!.toUpperCase(), b)
}
defValue = etd.allowedValues[0].text.toUpperCase()
}
override fun repr(obj: Any): String {
return "$name#$obj"
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
fun isAllowedValue(value: String) = this.allowedValues.contains(value)
operator fun contains(textValue: String) = textValue.toUpperCase() in allowedValues
override fun toString(): String = "ENUM $name"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is EnumerateType) return false
if (allowedValues != other.allowedValues) return false
if (defValue != other.defValue) return false
return true
}
override fun hashCode(): Int {
var result = allowedValues.hashCode()
result = 31 * result + defValue.hashCode()
return result
}
operator fun get(value: String) = allowedValues[value]
operator fun get(value: Int) = allowedValues.entries.find { (a, b) -> b == value }?.key
fun range(start: String, end: String): List<String> {
val keys = allowedValues.keys.toList()
val s = keys.indexOf(start)
val e = keys.indexOf(end)
if (s < 0) throw IllegalStateException()
if (e < 0) throw IllegalStateException()
return keys.subList(s, e + 1)
}
}
open class AnyInt(var bitLength: kotlin.Int = 0, var isSigned: Boolean = false) : AnyNum() {
init {
name = javaClass.getSimpleName().toUpperCase()
}
open val upperBound: BigInteger
get() =
if (isSigned)
BigInteger.ONE.shiftLeft(bitLength - 1).subtract(BigInteger.ONE)
else
BigInteger.ONE.shiftLeft(bitLength).subtract(BigInteger.ONE)
open val lowerBound: BigInteger
get() {
if (!isSigned)
return BigInteger.ZERO
else
return BigInteger.ONE.shiftLeft(bitLength - 1).negate()
}
constructor(bitLength: kotlin.Int) : this(bitLength, true)
override fun repr(obj: Any): String {
return javaClass.getSimpleName().toUpperCase() + "#" + obj
}
open fun next(): AnyInt? = null
open fun asUnsigned() = if (isSigned) AnyInt(bitLength, false) else this
open fun asSigned() = if (isSigned) this else AnyInt(bitLength, true)
open fun isValid(value: BigInteger): Boolean {
return value in lowerBound..upperBound
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is AnyInt) return false
val anyInt = o as AnyInt?
return if (bitLength != anyInt!!.bitLength) false else isSigned == anyInt.isSigned
}
override fun hashCode(): kotlin.Int {
var result = bitLength
result = 31 * result + if (isSigned) 1 else 0
return result
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
override fun toString(): String = name
companion object {
fun getDataTypeFor(number: Int, unsigned: Boolean): AnyInt {
val values: Array<AnyInt>
if (unsigned)
values = arrayOf(USINT, UINT, ULINT, UDINT)
else
values = arrayOf(SINT, INT, LINT, DINT)
val bits = Math.ceil(Math.log(number.toDouble()) / Math.log(2.0)).toInt()
for (candidate in values) {
if (candidate.bitLength >= bits)
return candidate
}
if (bits < 0)
return if (unsigned) USINT else SINT
/*for (AnyInt bit : values)
if (bit.getBitLength() >= bits)
return bit;*/
return if (unsigned)
AnyInt(bits, false)
else
AnyInt(bits, true)
}
}
}
object ANY_INT : AnyInt(-1, true)
object UDINT : AnyInt(32, false) {
override fun next() = ULINT
override fun asUnsigned() = this
override fun asSigned() = LINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object ULINT : AnyInt(64, false) {
override fun next() = null
override fun asSigned() = LINT
override fun asUnsigned() = this
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object UINT : AnyInt(16, false) {
override fun next() = UDINT
override fun asUnsigned() = this
override fun asSigned() = DINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object USINT : AnyInt(8, false) {
override fun asUnsigned() = this
override fun next() = UINT
override fun asSigned() = SINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object INT : AnyInt(16) {
override fun next() = DINT
override fun asUnsigned() = UINT
override fun asSigned() = this
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object LINT : AnyInt(64) {
override fun next() = null
override fun asSigned() = this
override fun asUnsigned() = ULINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object SINT : AnyInt(8) {
override fun next() = INT
override fun asSigned() = this
override fun asUnsigned() = USINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
object DINT : AnyInt(32) {
override fun next() = LINT
override fun asSigned() = this
override fun asUnsigned() = UDINT
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
/**
* Created by weigl on 10.06.14.
*
* @author weigl
* @version $Id: $Id
*/
data class RangeType(
var bottom: BigInteger = BigInteger.ZERO,
var top: BigInteger = BigInteger.ZERO,
var default: BigInteger = bottom,
var base: AnyInt = INT) : AnyInt(base.bitLength, base.isSigned) {
override val upperBound: BigInteger
get() = top
override val lowerBound: BigInteger
get() = bottom
override fun repr(obj: Any) = base.repr(obj)
override fun next() = null
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
//TODO as object
class TimeType : AnyDt("TIME") {
/** {@inheritDoc} */
override fun repr(obj: Any): String {
val time = obj as TimeData
val stb = StringTimeBuilder()
stb.add(time.days.toDouble(), "d")
stb.add(time.hours.toDouble(), "h")
stb.add(time.minutes.toDouble(), "m")
stb.add(time.seconds.toDouble(), "s")
stb.add(time.milliseconds.toDouble(), "ms")
return stb.sb.toString()
/**
*
* add.
*
* @param value a double.
* @param unit a [java.lang.String] object.
*/
}
/** {@inheritDoc} */
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
companion object {
/** Constant `TIME_TYPE` */
val TIME_TYPE = TimeType()
val LTIME_TYPE = TimeType()
}
}
internal class StringTimeBuilder {
var sb = StringBuilder("TIME#")
fun add(value: Double, unit: String) {
if (value != 0.0) {
sb.append(value).append(unit)
}
}
}
data class ReferenceDt(val refTo: AnyDt) : AnyDt("REF TO $refTo") {
override fun repr(obj: Any): String {
throw IllegalStateException("No repr for ReferenceDt")
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
companion object {
val ANY_REF = ReferenceDt(VOID)
}
}
/**
* Created by weigl on 10.06.14.
*
* @author weigl
* @version $Id: $Id
*/
data class RecordType(override var name: String = ANONYM_DATATYPE, val fields: VariableScope = VariableScope()) : AnyDt(name) {
fun addField(name: String, dataType: AnyDt) = fields.add(VariableDeclaration(name, dataType))
override fun repr(obj: Any): String {
val record = obj as RecordValue
return record.fieldValues.entries
.joinToString(", ", "(", ")") { (k, v) ->
k + ":=" + v.dataType.repr(v.value)
}
}
override fun <T> accept(visitor: DataTypeVisitorNN<T>) = visitor.visit(this)
}
/**
* Created by weigl on 01.08.16.
*
* @author weigl
* @version $Id: $Id
*/
class PointerType(var of: AnyDt) : AnyDt() {
/** {@inheritDoc} */
override fun toString(): String {
return of.toString() + "^"
}
/** {@inheritDoc} */
override fun repr(obj: Any): String {
return "n/a"
}
/** {@inheritDoc} */
override fun <T> accept(visitor: DataTypeVisitorNN<T>): T {
return visitor.visit(this)
}
}
| gpl-3.0 | fef019651f1ddb78d2d8f2b20a37275a | 27.378849 | 127 | 0.584603 | 3.910533 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/dsl-verification/src/main/java/com/example/dsl_verification/constraint/AspectRatio.kt | 2 | 3345 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("DslVerificationKt")
@file:JvmMultifileClass
package com.example.dsl_verification.constraint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
@Preview
@Composable
fun Test5() {
val constraintSet = ConstraintSet {
val box1 = createRefFor("box1")
constrain(box1) {
width = Dimension.fillToConstraints
height = Dimension.ratio("1:1.2")
centerTo(parent)
}
}
Column {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = true), constraintSet = constraintSet
) {
Box(
modifier = Modifier
.background(Color.Red)
.layoutId("box1")
)
}
Button(onClick = { }) {
Text(text = "Run")
}
}
}
@Preview
@Composable
fun Test6() {
val constraintSet = ConstraintSet {
val text1 = createRefFor("text1")
val box1 = createRefFor("box1")
constrain(text1) {
width = Dimension.wrapContent
height = Dimension.ratio("1:2")
centerVerticallyTo(parent)
start.linkTo(parent.start)
end.linkTo(box1.start)
}
constrain(box1) {
width = Dimension.value(50.dp)
height = Dimension.value(50.dp)
centerVerticallyTo(parent)
end.linkTo(parent.end, 8.dp)
}
}
Column {
ConstraintLayout(
modifier = Modifier
.fillMaxWidth()
.weight(1f, fill = true), constraintSet = constraintSet
) {
Text(
modifier = Modifier
.layoutId("text1")
.background(Color.Red),
text = "Hello, World!"
)
Box(
modifier = Modifier
.layoutId("box1")
.background(Color.Blue)
)
}
Button(onClick = { }) {
Text(text = "Run")
}
}
} | apache-2.0 | 29f1c2be981e6f7a36b23dedbdbfa1db | 29.418182 | 75 | 0.609567 | 4.632964 | false | false | false | false |
ProjectSandstone/SandstoneBukkit | src/main/kotlin/com/github/projectsandstone/bukkit/scheduler/BukkitScheduler.kt | 1 | 3557 | /**
* SandstoneBukkit - Bukkit implementation of SandstoneCommon
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Sandstone <https://github.com/ProjectSandstone/>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.projectsandstone.bukkit.scheduler
import com.github.projectsandstone.api.scheduler.SubmittedTask
import com.github.projectsandstone.api.scheduler.Task
import com.github.projectsandstone.bukkit.SandstoneBukkit
import com.github.projectsandstone.bukkit.util.MinecraftTicks
import com.github.projectsandstone.common.scheduler.SandstoneScheduler
import org.bukkit.Bukkit
import org.bukkit.scheduler.BukkitTask
import java.time.Duration
/**
* Created by jonathan on 27/08/16.
*/
object BukkitScheduler : SandstoneScheduler() {
override fun submit(task: Task): SubmittedTask {
val interval = task.interval
val isRepeating = interval != Duration.ZERO
val isAsync = task.isAsync
val bukkitTask: BukkitTask
if (isRepeating) {
if (isAsync) {
bukkitTask = Bukkit.getScheduler().runTaskTimerAsynchronously(
SandstoneBukkit.getSandstonePluginInstance(),
task.runnable,
task.delay.toMinecraftTicks(),
task.interval.toMinecraftTicks())
} else {
bukkitTask = Bukkit.getScheduler().runTaskTimer(
SandstoneBukkit.getSandstonePluginInstance(),
task.runnable,
task.delay.toMinecraftTicks(),
task.interval.toMinecraftTicks())
}
} else {
if (isAsync) {
bukkitTask = Bukkit.getScheduler().runTaskLaterAsynchronously(
SandstoneBukkit.getSandstonePluginInstance(),
task.runnable,
task.delay.toMinecraftTicks())
} else {
bukkitTask = Bukkit.getScheduler().runTaskLater(
SandstoneBukkit.getSandstonePluginInstance(),
task.runnable,
task.delay.toMinecraftTicks())
}
}
return BukkitSubmittedTask(task, bukkitTask)
}
internal fun Duration.toMinecraftTicks(): Long {
return MinecraftTicks.milliToTicks(this.toMillis())
}
} | mit | f2c2adfcbcc4dd22f50ac51411b39c0a | 40.858824 | 85 | 0.644082 | 4.85929 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/command/payment/PaymentListCommand.kt | 1 | 4431 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.payments.bukkit.command.payment
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.core.service.Services
import com.rpkit.payments.bukkit.RPKPaymentsBukkit
import com.rpkit.payments.bukkit.group.RPKPaymentGroupService
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
/**
* Payment list command.
* Lists all payment groups currently involved in.
*/
class PaymentListCommand(private val plugin: RPKPaymentsBukkit) : CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.payments.command.payment.list")) {
sender.sendMessage(plugin.messages["no-permission-payment-list"])
return true
}
if (sender !is Player) {
sender.sendMessage(plugin.messages["not-from-console"])
return true
}
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java]
if (minecraftProfileService == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile-service"])
return true
}
val characterService = Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages["no-character-service"])
return true
}
val paymentGroupService = Services[RPKPaymentGroupService::class.java]
if (paymentGroupService == null) {
sender.sendMessage(plugin.messages["no-payment-group-service"])
return true
}
val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender)
if (minecraftProfile == null) {
sender.sendMessage(plugin.messages["no-minecraft-profile"])
return true
}
val character = characterService.getPreloadedActiveCharacter(minecraftProfile)
sender.sendMessage(plugin.messages["payment-list-title"])
paymentGroupService.paymentGroups.thenAccept { paymentGroups ->
paymentGroups.forEach { paymentGroup ->
paymentGroup.owners.thenAccept { owners ->
if (owners.contains(character)) {
sender.sendMessage(
plugin.messages["payment-list-item", mapOf(
"name" to paymentGroup.name.value,
"rank" to "Owner"
)]
)
}
}
}
paymentGroups.forEach { paymentGroup ->
paymentGroup.members.thenAccept { members ->
if (members.contains(character)) {
sender.sendMessage(
plugin.messages["payment-list-item", mapOf(
"name" to paymentGroup.name.value,
"rank" to "Member"
)]
)
}
}
}
paymentGroups.forEach { paymentGroup ->
paymentGroup.invites.thenAccept { invites ->
if (invites.contains(character)) {
sender.sendMessage(
plugin.messages["payment-list-item", mapOf(
"name" to paymentGroup.name.value,
"rank" to "Invited"
)]
)
}
}
}
}
return true
}
} | apache-2.0 | 63bb4aa924953880fdd918f585bbcc3b | 41.615385 | 118 | 0.589258 | 5.370909 | false | false | false | false |
Anizoptera/Aza-Kotlin-CSS | main/azagroup/kotlin/css/colors/colors.kt | 1 | 292 | @file:Suppress("unused")
package azagroup.kotlin.css.colors
fun hex(hex: String) = Color.fromHex(hex)!!
fun hex(hex: Int) = Color.fromHex(hex)!!
fun rgb(r: Int, g: Int, b: Int) = Color.fromRgb(r, g, b)
fun rgba(r: Int, g: Int, b: Int, a: Number = 1f) = Color.fromRgb(r, g, b, a.toFloat())
| mit | 4a8dd52035e82ace5b1e3e905ee71da8 | 31.444444 | 86 | 0.64726 | 2.517241 | false | false | false | false |
Kotlin/anko | anko/library/static/constraint-layout/src/main/java/ConstraintLayout.kt | 2 | 11529 | /*
* Copyright 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:Suppress("unused")
package org.jetbrains.anko.constraint.layout
import android.support.annotation.IdRes
import android.support.constraint.ConstraintLayout
import android.support.constraint.ConstraintSet
import android.view.View
import org.jetbrains.anko.constraint.layout.ConstraintSetBuilder.Connection.BasicConnection
import org.jetbrains.anko.constraint.layout.ConstraintSetBuilder.Side
import org.jetbrains.anko.internals.AnkoInternals
import org.jetbrains.anko.internals.AnkoInternals.noGetter
val ConstraintLayout.matchConstraint
get() = ConstraintLayout.LayoutParams.MATCH_CONSTRAINT
fun ConstraintLayout.applyConstraintSet(init: ConstraintSetBuilder.() -> Unit): ConstraintSet =
constraintSet(init).also { it.applyTo(this) }
fun ConstraintLayout.constraintSet(init: ConstraintSetBuilder.() -> Unit): ConstraintSet =
ConstraintSetBuilder().also { it.clone(this) }.apply(init)
class ViewConstraintBuilder(
private @IdRes val viewId: Int,
private val constraintSetBuilder: ConstraintSetBuilder) {
infix fun Pair<Side, Side>.of(@IdRes targetViewId: Int): BasicConnection =
constraintSetBuilder.run { (first of viewId) to (second of targetViewId) }
infix fun Pair<Side, Side>.of(targetView: View): BasicConnection = this of targetView.id
fun clear() {
constraintSetBuilder.clear(viewId)
}
fun clear(sideId: Int) {
constraintSetBuilder.clear(viewId, sideId)
}
fun setMargin(sideId: Int, value: Int) {
constraintSetBuilder.setMargin(viewId, sideId, value)
}
fun setGoneMargin(sideId: Int, value: Int) {
constraintSetBuilder.setGoneMargin(viewId, sideId, value)
}
var horizontalBias: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setHorizontalBias(viewId, value)
}
var verticalBias: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setVerticalBias(viewId, value)
}
var dimensionRatio: String
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setDimensionRatio(viewId, value)
}
var visibility: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setVisibility(viewId, value)
}
var alpha: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setAlpha(viewId, value)
}
var applyElevation: Boolean
get() = constraintSetBuilder.getApplyElevation(viewId)
set(value) {
constraintSetBuilder.setApplyElevation(viewId, value)
}
var elevation: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setElevation(viewId, value)
}
var rotationX: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setRotationX(viewId, value)
}
var rotationY: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setRotationY(viewId, value)
}
var scaleX: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setScaleX(viewId, value)
}
var scaleY: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setScaleY(viewId, value)
}
var transformPivotX: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setTransformPivotX(viewId, value)
}
var transformPivotY: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setTransformPivotY(viewId, value)
}
var translationX: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setTranslationX(viewId, value)
}
var translationY: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setTranslationY(viewId, value)
}
var translationZ: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setTranslationZ(viewId, value)
}
var height: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainHeight(viewId, value)
}
var width: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainWidth(viewId, value)
}
var maxHeight: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainMaxHeight(viewId, value)
}
var maxWidth: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainMaxWidth(viewId, value)
}
var minHeight: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainMinHeight(viewId, value)
}
var minWidth: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainMinWidth(viewId, value)
}
var defaultHeight: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainDefaultHeight(viewId, value)
}
var defaultWidth: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.constrainDefaultWidth(viewId, value)
}
var horizontalWeight: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setHorizontalWeight(viewId, value)
}
var verticalWeight: Float
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setVerticalWeight(viewId, value)
}
var horizontalChainStyle: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setHorizontalChainStyle(viewId, value)
}
var verticalChainStyle: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = noGetter()
set(value) {
constraintSetBuilder.setVerticalChainStyle(viewId, value)
}
}
class ConstraintSetBuilder : ConstraintSet() {
operator fun Int.invoke(init: ViewConstraintBuilder.() -> Unit) {
ViewConstraintBuilder(this, this@ConstraintSetBuilder).apply(init)
}
operator fun View.invoke(init: ViewConstraintBuilder.() -> Unit) = id.invoke(init)
infix fun Side.of(@IdRes viewId: Int) = when (this) {
Side.LEFT -> ViewSide.Left(viewId)
Side.RIGHT -> ViewSide.Right(viewId)
Side.TOP -> ViewSide.Top(viewId)
Side.BOTTOM -> ViewSide.Bottom(viewId)
Side.BASELINE -> ViewSide.Baseline(viewId)
Side.START -> ViewSide.Start(viewId)
Side.END -> ViewSide.End(viewId)
}
infix fun Side.of(view: View) = this of view.id
infix fun Pair<ViewSide, Side>.of(@IdRes viewId: Int) = first to (second of viewId)
infix fun Pair<ViewSide, Side>.of(view: View) = first to (second of view.id)
infix fun ViewSide.to(targetSide: ViewSide) = BasicConnection(this, targetSide)
infix fun BasicConnection.margin(margin: Int) = Connection.MarginConnection(from, to, margin)
fun connect(vararg connections: Connection) {
for (connection in connections) {
when (connection) {
is Connection.MarginConnection -> connect(
connection.from.viewId,
connection.from.sideId,
connection.to.viewId,
connection.to.sideId,
connection.margin
)
is BasicConnection -> connect(
connection.from.viewId,
connection.from.sideId,
connection.to.viewId,
connection.to.sideId
)
}
}
}
enum class Side {
LEFT,
RIGHT,
TOP,
BOTTOM,
BASELINE,
START,
END,
}
sealed class ViewSide(@IdRes val viewId: Int) {
class Left(@IdRes viewId: Int) : ViewSide(viewId)
class Right(@IdRes viewId: Int) : ViewSide(viewId)
class Top(@IdRes viewId: Int) : ViewSide(viewId)
class Bottom(@IdRes viewId: Int) : ViewSide(viewId)
class Baseline(@IdRes viewId: Int) : ViewSide(viewId)
class Start(@IdRes viewId: Int) : ViewSide(viewId)
class End(@IdRes viewId: Int) : ViewSide(viewId)
val sideId: Int
get() = when(this) {
is ViewSide.Left -> ConstraintSet.LEFT
is ViewSide.Right -> ConstraintSet.RIGHT
is ViewSide.Top -> ConstraintSet.TOP
is ViewSide.Bottom -> ConstraintSet.BOTTOM
is ViewSide.Baseline -> ConstraintSet.BASELINE
is ViewSide.Start -> ConstraintSet.START
is ViewSide.End -> ConstraintSet.END
}
}
sealed class Connection(val from: ViewSide, val to: ViewSide) {
class BasicConnection(from: ViewSide, to: ViewSide) : Connection(from, to)
class MarginConnection(from: ViewSide, to: ViewSide, val margin: Int) : Connection(from, to)
}
}
| apache-2.0 | bc51b5f094c9b793c33d507526515df5 | 35.716561 | 100 | 0.648192 | 4.555117 | false | false | false | false |
spolnik/JAlgoArena-Problems | src/main/kotlin/com/jalgoarena/data/XodusProblemsRepository.kt | 1 | 3026 | package com.jalgoarena.data
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.jalgoarena.domain.Constants
import com.jalgoarena.domain.Problem
import jetbrains.exodus.entitystore.Entity
import jetbrains.exodus.entitystore.PersistentEntityStore
import jetbrains.exodus.entitystore.PersistentEntityStores
import jetbrains.exodus.entitystore.PersistentStoreTransaction
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Repository
@Repository
open class XodusProblemsRepository(dbName: String) : ProblemsRepository {
constructor() : this(Constants.STORE_PATH)
private val logger = LoggerFactory.getLogger(this.javaClass)
private val store: PersistentEntityStore = PersistentEntityStores.newInstance(dbName)
override fun findAll(): List<Problem> {
return readonly {
it.getAll(Constants.ENTITY_TYPE).map { Problem.from(it) }
}
}
override fun find(id: String): Problem? {
return readonly {
it.find(
Constants.ENTITY_TYPE,
Constants.problemId,
id
).map { Problem.from(it) }.firstOrNull()
}
}
override fun addOrUpdate(problem: Problem): Problem {
return transactional {
val existingEntity = it.find(
Constants.ENTITY_TYPE, Constants.problemId, problem.id
).firstOrNull()
val entity = when (existingEntity) {
null -> it.newEntity(Constants.ENTITY_TYPE)
else -> existingEntity
}
updateEntity(entity, problem)
}
}
private fun updateEntity(entity: Entity, problem: Problem): Problem {
entity.apply {
setProperty(Constants.problemId, problem.id)
setProperty(Constants.problemTitle, problem.title)
setProperty(Constants.problemDescription, problem.description)
setProperty(Constants.problemLevel, problem.level)
setProperty(Constants.problemTimeLimit, problem.timeLimit)
setProperty(Constants.problemFunction, toJson(problem.func!!))
setProperty(Constants.problemTestCases, toJson(problem.testCases!!))
}
return Problem.from(entity)
}
override fun destroy() {
try {
logger.info("Closing persistent store.")
store.close()
logger.info("persistent store closed")
} catch (e: RuntimeException) {
logger.error("error closing persistent store", e)
}
}
private fun toJson(obj: Any): String =
jacksonObjectMapper().writeValueAsString(obj)
private fun <T> transactional(call: (PersistentStoreTransaction) -> T): T {
return store.computeInTransaction { call(it as PersistentStoreTransaction) }
}
private fun <T> readonly(call: (PersistentStoreTransaction) -> T): T {
return store.computeInReadonlyTransaction { call(it as PersistentStoreTransaction) }
}
}
| apache-2.0 | 42457e94e8aa1a764aeda726e1ab67e2 | 33.781609 | 92 | 0.660939 | 4.960656 | false | false | false | false |
shiraji/permissions-dispatcher-plugin | src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/views/GeneratePMCodeDialogDelegate.kt | 1 | 4286 | package com.github.shiraji.permissionsdispatcherplugin.views
import com.intellij.openapi.ui.DialogWrapper
import javax.swing.JCheckBox
import javax.swing.JOptionPane
class GeneratePMCodeDialogDelegate(val dialog: GeneratePMCodeDialog) {
val dangerPermissionsCheckbox = listOf<JCheckBox>(
dialog.readCalendar, dialog.writeCalendar, dialog.camera, dialog.readContacts,
dialog.writeContacts, dialog.getAccounts, dialog.accessFineLocation,
dialog.accessCoarseLocation, dialog.recordAudio, dialog.readPhoneState,
dialog.callPhone, dialog.readCallLog, dialog.writeCallLog, dialog.addVoicemail,
dialog.useSip, dialog.processOutgoingCall, dialog.bodySensors, dialog.sendSms,
dialog.receiveSms, dialog.readSms, dialog.receiveWapPush, dialog.receiveMms,
dialog.readExternalStorage, dialog.writeExternalStorage)
val specialPermissionsCheckbox = listOf<JCheckBox>(dialog.systemAlertWindow, dialog.writeSettings)
val methodNameUI = mapOf(
dialog.needsPermissionTextField to dialog.needsPermissionCheckBox,
dialog.onShowRationaleTextField to dialog.onShowRationaleCheckBox,
dialog.onPermissionDeniedTextField to dialog.onPermissionDeniedCheckBox,
dialog.onNeverAskAgainTextField to dialog.onNeverAskAgainCheckBox)
init {
dialog.apply {
setTitle("PermissionsDispatcher Plugin")
addOkAction().setText("Generate")
setOkOperation({
if (isValidInfo()) {
dialogWrapper.close(DialogWrapper.OK_EXIT_CODE, false)
}
})
addCancelAction()
}
dangerPermissionsCheckbox.forEach {
it.addChangeListener {
val checkBox: JCheckBox = it.source as JCheckBox
if (checkBox.isSelected) {
specialPermissionsCheckbox.forEach {
it.isSelected = false
}
}
}
}
specialPermissionsCheckbox.forEach {
it.addChangeListener {
val checkBox = it.source as JCheckBox
if (checkBox.isSelected) {
dangerPermissionsCheckbox.forEach {
it.isSelected = false
}
specialPermissionsCheckbox.filterNot {
it == checkBox
}.forEach {
it.isSelected = false
}
}
}
}
methodNameUI.entries.forEach {
val jCheckBox = it.value
val jTextField = it.key
jCheckBox.addChangeListener {
val checkBox = it.source as JCheckBox
jTextField.isEditable = checkBox.isSelected
jTextField.isEnabled = checkBox.isSelected
}
}
}
private fun isValidInfo(): Boolean {
if (dangerPermissionsCheckbox.none { it.isSelected } && specialPermissionsCheckbox.none { it.isSelected } ) {
JOptionPane.showMessageDialog(null, "Must select at least one permission.")
return false
}
val methodNames = methodNameUI.entries.filter { it.value.isSelected && it.key.text.isEmpty() }
if (methodNames.isNotEmpty()) {
JOptionPane.showMessageDialog(null, "Must provide method name for ${methodNames.map { it.value.text }.joinToString { it }}")
return false
}
return isValidMaxSdkVersion()
}
private fun isValidMaxSdkVersion(): Boolean {
val maxSdkVersionText = dialog.maxSdkVersionTextField.text ?: return true
try {
if (maxSdkVersionText.isNotBlank()) {
maxSdkVersionText.toInt()
}
} catch(e: NumberFormatException) {
JOptionPane.showMessageDialog(null, "maxSdkVersion should be an integer")
return false
}
return true
}
fun getSelectedPermissions(): List<String> {
return setOf(*dangerPermissionsCheckbox.toTypedArray(), *specialPermissionsCheckbox.toTypedArray()).filter {
it.isSelected
}.map {
it.text
}
}
} | apache-2.0 | 7bb962f028efc0dae9e0f741f782a7a9 | 37.621622 | 136 | 0.608959 | 5.551813 | false | false | false | false |
asathe/jsonlin | src/main/kotlin/org/sathe/json/JsonType.kt | 1 | 10542 | package org.sathe.json
import java.io.StringWriter
import java.io.Writer
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*
interface JsonType {
fun toJson(writer: Writer, format: JsonFormat = PrettyPrint())
fun toJson(format: JsonFormat = PrettyPrint()): String {
val writer = StringWriter()
toJson(writer, format)
return writer.toString()
}
fun accept(visitor: JsonVisitor)
fun find(path: String): JsonType {
val jsonPath = JsonPath(path)
accept(jsonPath)
return jsonPath.result()
}
}
interface JsonVisitor {
fun visit(json: JsonObject)
fun visit(json: JsonArray)
fun visit(json: JsonValue)
fun visit(json: JsonNull)
fun visit(json: JsonSequence)
}
class JsonPath(path: String) : JsonVisitor {
private val tokens = StringTokenizer(path, ".[]", true)
private var result: JsonType? = null
override fun visit(json: JsonObject) {
if (!tokens.hasMoreTokens()) {
result = json
return
}
var token = tokens.nextToken()
if (token == ".") token = tokens.nextToken()
json.child(generateKey(token, json)).accept(this)
}
private tailrec fun generateKey(token: String, json: JsonObject): String {
if (json.hasChild(token)) {
return token
}
if (!tokens.hasMoreTokens()) {
throw JsonException("Unable to find $token in $json")
}
return generateKey(token + tokens.nextToken(), json)
}
override fun visit(json: JsonArray) {
if (!tokens.hasMoreTokens()) {
result = json
return
}
assert(tokens.nextToken() == "[")
val index = Integer.valueOf(tokens.nextToken())
if (json.size() <= index) {
throw JsonException("Index $index not found in $json")
}
assert(tokens.nextToken() == "]")
json[index].accept(this)
}
override fun visit(json: JsonValue) {
if (tokens.hasMoreTokens()) {
throw JsonException("Path \"${tokens.toList().joinToString()}\" goes beyond a leaf - found $json")
}
result = json
}
override fun visit(json: JsonNull) {
if (tokens.hasMoreTokens()) {
throw JsonException("Path \"${tokens.toList().joinToString()}\" goes beyond a leaf - found $json")
}
result = json
}
override fun visit(json: JsonSequence) {
assert(tokens.nextToken() == "[")
val index = Integer.valueOf(tokens.nextToken())
assert(tokens.nextToken() == "]")
json.elementAt(index).accept(this)
}
fun result(): JsonType {
return result!!
}
}
class JsonObject() : JsonType {
private val entries = LinkedHashMap<String, JsonType>()
constructor(data: Map<*, *>) : this() {
data.forEach { entries[it.key.toString()] = convert(it.value) }
}
override fun toJson(writer: Writer, format: JsonFormat) {
val maxIndex = entries.size - 1
writer.write(format.startObject())
entries.entries.forEachIndexed { i, entry ->
writer.write(format.startItem())
encoded(writer, entry.key)
writer.write(format.separator())
entry.value.toJson(writer, format)
if (i < maxIndex) writer.write(",")
}
writer.write(format.endObject())
}
override fun accept(visitor: JsonVisitor) {
visitor.visit(this)
}
fun add(key: String, item: JsonType): JsonObject {
entries[key] = item
return this
}
fun add(key: String, item: String): JsonObject {
entries[key] = value(item)
return this
}
fun add(key: String, item: BigDecimal): JsonObject {
entries[key] = value(item)
return this
}
fun add(key: String, item: Int): JsonObject {
entries[key] = value(item)
return this
}
fun add(key: String, item: BigInteger): JsonObject {
entries[key] = value(item)
return this
}
fun add(key: String, item: Boolean): JsonObject {
entries[key] = value(item)
return this
}
fun child(key: String) = entries[key] ?: throw JsonException("No entry for '$key'")
fun hasChild(key: String) = entries.containsKey(key)
fun string(key: String) = asValue(key).string()
fun decimal(key: String) = asValue(key).decimal()
fun integer(key: String) = asValue(key).integer()
fun boolean(key: String) = asValue(key).boolean()
fun list(key: String): JsonArray {
val value = entries[key] ?: throw JsonException("No entry for '$key'")
return value as? JsonArray
?: throw JsonException("Expecting a list for '$key' but got '$value'")
}
fun entries() = entries.toMap().entries
override fun toString(): String = toJson(Minimal())
override fun equals(other: Any?): Boolean = if (other is JsonObject) entries == other.entries else false
override fun hashCode(): Int = entries.hashCode()
fun copy(): JsonObject {
val copy: HashMap<String, JsonType> = HashMap()
copy.putAll(entries)
return JsonObject(copy)
}
private fun asValue(key: String): JsonValue {
val value = entries[key] ?: throw JsonException("No entry for '$key'")
return value as JsonValue
}
}
class JsonSequence(private val types: Iterator<JsonType>) : JsonType, Sequence<JsonType> {
override fun toJson(writer: Writer, format: JsonFormat) {
writer.write(format.startList())
types.forEach { item ->
writer.write(format.startItem())
item.toJson(writer, format)
if (types.hasNext()) writer.write(",")
}
writer.write(format.endList())
}
override fun iterator(): Iterator<JsonType> {
return types
}
override fun accept(visitor: JsonVisitor) {
visitor.visit(this)
}
}
class JsonArray() : JsonType, Iterable<JsonType> {
private val items = ArrayList<JsonType>()
constructor(entries: List<Any?>) : this() {
entries.forEach { items.add(convert(it)) }
}
override fun iterator(): Iterator<JsonType> {
return items.iterator()
}
override fun toJson(writer: Writer, format: JsonFormat) {
val maxIndex = items.size - 1
writer.write(format.startList())
items.forEachIndexed { i, item ->
writer.write(format.startItem())
item.toJson(writer, format)
if (i < maxIndex) writer.write(",")
}
writer.write(format.endList())
}
override fun accept(visitor: JsonVisitor) {
visitor.visit(this)
}
operator fun get(index: Int): JsonType {
return items[index]
}
fun add(item: JsonType): JsonArray {
items.add(item)
return this
}
fun size(): Int {
return items.size
}
override fun toString(): String = toJson(Minimal())
override fun equals(other: Any?): Boolean = if (other is JsonArray) items == other.items else false
override fun hashCode(): Int = items.hashCode()
}
private val encodings = Array(128) {
when (it) {
'\t'.toInt() -> "\\t"
'\n'.toInt() -> "\\n"
'\r'.toInt() -> "\\r"
'\b'.toInt() -> "\\b"
'\"'.toInt() -> "\\\""
'\\'.toInt() -> "\\\\"
'\u000C'.toInt() -> "\\f"
in 0..0x1f -> "\\u%04x".format(it)
else -> null
}
}
private fun encoded(writer: Writer, value: String) {
writer.write("\"")
value.forEach { writer.write(encodedCharacterFor(it)) }
writer.write("\"")
}
private fun encodedCharacterFor(c: Char): String {
if (c.toInt() >= encodings.size) return c.toString()
val encoded = encodings[c.toInt()]
return encoded ?: c.toString()
}
class JsonValue(private val value: Any) : JsonType {
override fun toJson(writer: Writer, format: JsonFormat) {
when (value) {
is String -> encoded(writer, value)
else -> writer.write("$value")
}
}
override fun accept(visitor: JsonVisitor) {
visitor.visit(this)
}
fun value(): Any = value
fun string(): String = value.toString()
fun decimal(): BigDecimal = when (value) {
is BigDecimal -> value
is BigInteger -> BigDecimal(value)
is String -> BigDecimal(value)
is Int -> BigDecimal(value)
else -> throw incorrectType("a decimal")
}
fun integer(): Int = when (value) {
is BigInteger -> value.intValueExact()
is Int -> value
is String -> value.toInt()
else -> throw incorrectType("an integer")
}
fun boolean(): Boolean = when (value) {
is Boolean -> value
is String -> value.toBoolean()
else -> throw incorrectType("a boolean")
}
private fun incorrectType(type: String): JsonException =
JsonException("Expecting $type but got $value (${value.javaClass.simpleName})")
override fun toString(): String = toJson(Minimal())
override fun equals(other: Any?): Boolean = if (other is JsonValue) value == other.value else false
override fun hashCode(): Int = value.hashCode()
}
class JsonNull : JsonType {
override fun toJson(writer: Writer, format: JsonFormat) = writer.write("null")
override fun accept(visitor: JsonVisitor) {
visitor.visit(this)
}
override fun equals(other: Any?): Boolean = other is JsonNull
override fun hashCode(): Int = 0
}
private fun convert(value: Any?): JsonType {
return when (value) {
null -> JsonNull()
is JsonType -> value
is String -> JsonValue(value)
is Number -> JsonValue(value)
is Boolean -> JsonValue(value)
is Enum<*> -> JsonValue(value.name)
is Map<*, *> -> JsonObject(value)
is List<*> -> JsonArray(value)
else -> throw JsonException("Unable to convert $value")
}
}
fun obj(vararg entries: Pair<String, *>): JsonObject {
val map = LinkedHashMap<String, Any?>()
map.putAll(entries)
return JsonObject(map)
}
fun obj(entries: Map<String, JsonType>): JsonObject = JsonObject(entries)
fun array(vararg entries: Any?): JsonArray = JsonArray(listOf(*entries))
fun array(entries: List<Any>): JsonArray = JsonArray(entries)
fun value(value: String): JsonValue = JsonValue(value)
fun value(value: Number): JsonValue = JsonValue(value)
fun value(value: Boolean): JsonValue = JsonValue(value)
| apache-2.0 | 3a20f2cc0d2461911ff4d5154293fd3f | 27.262735 | 110 | 0.599222 | 4.210064 | false | false | false | false |
tim-group/SassPlugin | src/main/kotlin/com/youdevise/gradle/plugins/CompileSassTask.kt | 1 | 2313 | package com.youdevise.gradle.plugins
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.InputDirectory
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import java.io.File
import javax.script.ScriptEngineManager
open class CompileSassTask : DefaultTask() {
@InputDirectory
val inputDir = project.objects.directoryProperty().convention(project.layout.projectDirectory.dir("src").dir("main").dir(
"sass"))
@OutputDirectory
val outputDir = project.objects.directoryProperty().convention(project.layout.buildDirectory.dir("sass"))
@Internal
val cacheLocation = project.objects.directoryProperty().convention(project.layout.buildDirectory.dir("sass-cache"))
init {
group = "build"
description = "Compiles SASS or SCSS files to CSS"
}
@TaskAction
fun compileSass() {
val inputDirFile = inputDir.asFile.get()
val outputDirFile = outputDir.asFile.get()
val cacheLocationFile = cacheLocation.asFile.get()
val mappings = mutableMapOf<String, String>()
inputDirFile.walk()
.onEnter {
!(it.isHidden)
}
.forEach { inputFile ->
if (inputFile.isFile && (inputFile.name.endsWith(".sass") || inputFile.name.endsWith(".scss"))) {
val outputFile = File(outputDirFile, relativePath(inputDirFile, inputFile) + ".css")
outputFile.parentFile.mkdirs()
mappings[inputFile.path] = outputFile.path
}
}
ScriptEngineManager().getEngineByName("jruby")!!.run {
put("cacheLocation", cacheLocationFile.path)
put("mappings", mappings)
eval(driverScript)
}
}
}
private val driverScript: String by lazy {
CompileSassTask::class.java.getResourceAsStream("driver_script.rb")!!.use { stream ->
stream.reader().readText()
}
}
private fun relativePath(root: File, descendant: File): String {
val rootPath = root.absolutePath
val descendantPath = descendant.absolutePath
require(descendantPath.startsWith(rootPath))
return descendantPath.substring(rootPath.length + 1)
}
| bsd-2-clause | 9d3f9c6a03aca1cede29358d2f39bdf0 | 34.584615 | 125 | 0.650238 | 4.653924 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/QueueBlockedItem.kt | 1 | 2427 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.CauseAction
import org.openapitools.model.FreeStyleProject
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param propertyClass
* @param actions
* @param blocked
* @param buildable
* @param id
* @param inQueueSince
* @param params
* @param stuck
* @param task
* @param url
* @param why
* @param buildableStartMilliseconds
*/
data class QueueBlockedItem(
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("actions") val actions: kotlin.collections.List<CauseAction>? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("blocked") val blocked: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("buildable") val buildable: kotlin.Boolean? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("id") val id: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("inQueueSince") val inQueueSince: kotlin.Int? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("params") val params: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("stuck") val stuck: kotlin.Boolean? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("task") val task: FreeStyleProject? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("url") val url: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("why") val why: kotlin.String? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("buildableStartMilliseconds") val buildableStartMilliseconds: kotlin.Int? = null
) {
}
| mit | dc7fc227b5db72c5357a704126621640 | 31.36 | 104 | 0.709106 | 3.933549 | false | false | false | false |
ruuvi/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/tagdetails/ui/TagViewModel.kt | 1 | 7541 | package com.ruuvi.station.tagdetails.ui
import android.os.Handler
import android.os.Looper
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.ruuvi.station.app.preferences.GlobalSettings
import com.ruuvi.station.bluetooth.IRuuviGattListener
import com.ruuvi.station.bluetooth.LogReading
import com.ruuvi.station.bluetooth.domain.BluetoothGattInteractor
import com.ruuvi.station.database.tables.TagSensorReading
import com.ruuvi.station.tag.domain.RuuviTag
import com.ruuvi.station.tagdetails.domain.TagDetailsInteractor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.*
class TagViewModel(
private val tagDetailsInteractor: TagDetailsInteractor,
private val gattInteractor: BluetoothGattInteractor,
val tagId: String
) : ViewModel() {
private val tagEntry = MutableLiveData<RuuviTag?>(null)
val tagEntryObserve: LiveData<RuuviTag?> = tagEntry
private val tagReadings = MutableLiveData<List<TagSensorReading>?>(null)
val tagReadingsObserve: LiveData<List<TagSensorReading>?> = tagReadings
enum class SyncProgress {
STILL, CONNECTING, CONNECTED, DISCONNECTED, READING_INFO, READING_DATA, SAVING_DATA, NOT_SUPPORTED, NOT_FOUND, ERROR, DONE
}
class SyncStatus {
var syncProgress = SyncProgress.STILL
var deviceInfoModel = ""
var deviceInfoFw = ""
var readDataSize = 0
}
private val syncStatusObj = MutableLiveData<SyncStatus>()
val syncStatusObserve: LiveData<SyncStatus> = syncStatusObj
private val ioScope = CoroutineScope(Dispatchers.IO)
private var showGraph = false
private var selected = false
init {
Timber.d("TagViewModel initialized")
getTagInfo()
}
fun isShowGraph(isShow: Boolean) {
showGraph = isShow
}
fun disconnectGatt() {
tagEntryObserve.value?.let { tag ->
gattInteractor.disconnect(tag.id)
}
}
fun syncGatt() {
syncStatusObj.value = SyncStatus()
syncStatusObj.value?.syncProgress = SyncProgress.CONNECTING
syncStatusObj.postValue(syncStatusObj.value)
tagEntryObserve.value?.let { tag ->
var syncFrom = tag.lastSync
val historyLength = Date(Date().time - 1000 * 60 * 60 * 24 * GlobalSettings.historyLengthDays)
if (syncFrom == null || syncFrom.before(historyLength)) {
syncFrom = historyLength
}
Timber.d("sync logs from: %s", syncFrom)
val found = gattInteractor.readLogs(tag.id, syncFrom, object : IRuuviGattListener {
override fun connected(state: Boolean) {
if (state) {
syncStatusObj.value?.syncProgress = SyncProgress.CONNECTED
syncStatusObj.value?.syncProgress = SyncProgress.READING_INFO
} else {
if (syncStatusObj.value?.syncProgress == SyncProgress.SAVING_DATA) {
syncStatusObj.value?.syncProgress = SyncProgress.DONE
} else {
syncStatusObj.value?.syncProgress = SyncProgress.DISCONNECTED
}
}
syncStatusObj.postValue(syncStatusObj.value)
}
override fun deviceInfo(model: String, fw: String, canReadLogs: Boolean) {
syncStatusObj.value?.deviceInfoModel = model
syncStatusObj.value?.deviceInfoFw = fw
if (canReadLogs) {
syncStatusObj.value?.syncProgress = SyncProgress.READING_DATA
} else {
syncStatusObj.value?.syncProgress = SyncProgress.NOT_SUPPORTED
}
syncStatusObj.postValue(syncStatusObj.value)
}
override fun dataReady(data: List<LogReading>) {
syncStatusObj.value?.readDataSize = data.size
syncStatusObj.value?.syncProgress = SyncProgress.SAVING_DATA
syncStatusObj.postValue(syncStatusObj.value)
saveGattReadings(tag, data)
}
override fun heartbeat(raw: String) {
}
})
if (!found) {
syncStatusObj.value?.syncProgress = SyncProgress.NOT_FOUND
syncStatusObj.postValue(syncStatusObj.value)
}
} ?: kotlin.run {
Handler(Looper.getMainLooper()).post {
syncStatusObj.value?.syncProgress = SyncProgress.ERROR
syncStatusObj.postValue(syncStatusObj.value)
}
}
}
fun removeTagData() {
TagSensorReading.removeForTag(tagId)
tagDetailsInteractor.clearLastSync(tagId)
}
fun saveGattReadings(tag: RuuviTag, data: List<LogReading>) {
val tagReadingList = mutableListOf<TagSensorReading>()
data.forEach { logReading ->
val reading = TagSensorReading()
reading.ruuviTagId = tag.id
reading.temperature = logReading.temperature
reading.humidity = logReading.humidity
reading.pressure = logReading.pressure
reading.createdAt = logReading.date
tagReadingList.add(reading)
}
TagSensorReading.saveList(tagReadingList)
updateLastSync(Date())
}
fun updateLastSync(date: Date?) {
tagDetailsInteractor.updateLastSync(tagId, date)
}
fun tagSelected(selectedTag: RuuviTag?) {
selected = tagId == selectedTag?.id
}
fun getTagInfo() {
ioScope.launch {
Timber.d("getTagInfo $tagId")
getTagEntryData(tagId)
if (showGraph && selected) getGraphData(tagId)
}
}
private fun getGraphData(tagId: String) {
Timber.d("Get graph data for tagId = $tagId")
ioScope.launch {
tagDetailsInteractor
.getTagReadings(tagId)
?.let {
withContext(Dispatchers.Main) {
tagReadings.value = it
}
}
}
}
private fun getTagEntryData(tagId: String) {
Timber.d("getTagEntryData for tagId = $tagId")
ioScope.launch {
tagDetailsInteractor
.getTagById(tagId)
?.let {
withContext(Dispatchers.Main) {
tagEntry.value = it
}
}
}
}
fun getTemperatureString(tag: RuuviTag): String =
tagDetailsInteractor.getTemperatureString(tag)
fun getTemperatureStringWithoutUnit(tag: RuuviTag): String =
tagDetailsInteractor.getTemperatureStringWithoutUnit(tag)
fun getTemperatureUnitString(): String =
tagDetailsInteractor.getTemperatureUnitString()
fun getHumidityString(tag: RuuviTag): String =
tagDetailsInteractor.getHumidityString(tag)
fun getPressureString(tag: RuuviTag): String =
tagDetailsInteractor.getPressureString(tag)
fun getSignalString(tag: RuuviTag): String =
tagDetailsInteractor.getSignalString(tag)
override fun onCleared() {
super.onCleared()
Timber.d("TagViewModel cleared!")
}
} | mit | 1c2caf373833fa0845beda063a7fb536 | 34.575472 | 130 | 0.617292 | 4.846401 | false | false | false | false |
robinverduijn/gradle | subprojects/instant-execution-report/src/main/kotlin/data/Trie.kt | 1 | 1500 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 data
@Suppress("experimental_feature_warning")
inline class Trie<T>(
private
val nestedMaps: Map<T, Any>
) {
companion object {
fun <T> from(paths: Sequence<List<T>>) =
Trie(nestedMapsFrom(paths))
}
val entries: Sequence<Pair<T, Trie<T>>>
get() = nestedMaps.asSequence().map { (label, subTrie) ->
label to Trie<T>(subTrie.uncheckedCast())
}
val size: Int
get() = nestedMaps.size
}
private
fun <T> nestedMapsFrom(paths: Sequence<List<T>>): Map<T, Any> {
val root = hashMapOf<T, HashMap<T, Any>>()
for (path in paths) {
var node = root
for (segment in path) {
node = node.getOrPut(segment) {
hashMapOf()
}.uncheckedCast()
}
}
return root
}
private
inline fun <reified T> Any.uncheckedCast(): T = this as T
| apache-2.0 | c6e04b24a4acc468c5e7c57cd615be2a | 24.423729 | 75 | 0.636 | 3.916449 | false | false | false | false |
yshrsmz/monotweety | app2/src/main/java/net/yslibrary/monotweety/ui/settings/SettingsFragment.kt | 1 | 13069 | package net.yslibrary.monotweety.ui.settings
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.oss.licenses.OssLicensesMenuActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.michaelflisar.changelog.ChangelogBuilder
import com.michaelflisar.changelog.internal.ChangelogDialogFragment
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.GroupieViewHolder
import com.xwray.groupie.Section
import net.yslibrary.monotweety.BuildConfig
import net.yslibrary.monotweety.R
import net.yslibrary.monotweety.analytics.Analytics
import net.yslibrary.monotweety.databinding.FragmentSettingsBinding
import net.yslibrary.monotweety.notification.NotificationService
import net.yslibrary.monotweety.ui.base.ViewBindingFragment
import net.yslibrary.monotweety.ui.base.consumeEffects
import net.yslibrary.monotweety.ui.base.consumeStates
import net.yslibrary.monotweety.ui.base.navigateSafe
import net.yslibrary.monotweety.ui.base.openExternalAppWithShareIntent
import net.yslibrary.monotweety.ui.base.openExternalAppWithUrl
import net.yslibrary.monotweety.ui.base.requireAppCompatActivity
import net.yslibrary.monotweety.ui.di.HasComponent
import net.yslibrary.monotweety.ui.di.ViewModelFactory
import net.yslibrary.monotweety.ui.di.getComponentProvider
import net.yslibrary.monotweety.ui.launcher.LauncherActivity
import net.yslibrary.monotweety.ui.settings.widget.DividerItemDecoration
import net.yslibrary.monotweety.ui.settings.widget.OneLineTextItem
import net.yslibrary.monotweety.ui.settings.widget.SubHeaderItem
import net.yslibrary.monotweety.ui.settings.widget.TwoLineTextItem
import net.yslibrary.monotweety.ui.settings.widget.UserItem
import timber.log.Timber
import javax.inject.Inject
class SettingsFragment : ViewBindingFragment<FragmentSettingsBinding>(
R.layout.fragment_settings,
FragmentSettingsBinding::bind,
), HasComponent<SettingsFragmentComponent> {
override val component: SettingsFragmentComponent by lazy {
requireActivity()
.getComponentProvider<SettingsFragmentComponent.ComponentProvider>()
.settingsFragmentComponent()
.build()
}
@Inject
lateinit var factory: ViewModelFactory<SettingsViewModel>
@Inject
lateinit var analytics: Analytics
private val viewModel: SettingsViewModel by viewModels { factory }
private val userSection by lazy { Section(SubHeaderItem(getString(R.string.account))) }
private val settingsSection by lazy { Section(SubHeaderItem(getString(R.string.settings))) }
private val privacySection by lazy {
Section(SubHeaderItem(getString(R.string.privacy)))
.apply {
add(OneLineTextItem(
item = OneLineTextItem.Item(
title = getString(R.string.privacy_policy),
enabled = true,
),
onClick = { viewModel.dispatch(SettingsIntent.PrivacyPolicySelected) }
))
}
}
private val othersSection by lazy {
Section(SubHeaderItem(getString(R.string.others)))
.apply {
addAll(listOf(
TwoLineTextItem(
item = TwoLineTextItem.Item(
title = getString(R.string.version,
BuildConfig.VERSION_NAME,
BuildConfig.VERSION_CODE),
subTitle = getString(R.string.version_description),
enabled = true
),
onClick = { viewModel.dispatch(SettingsIntent.ChangelogSelected) }
),
OneLineTextItem(
item = OneLineTextItem.Item(
title = getString(R.string.license),
enabled = true
),
onClick = { viewModel.dispatch(SettingsIntent.LicenseSelected) }
)
))
}
}
private val supportSection by lazy {
Section(SubHeaderItem(getString(R.string.support_developer)))
.apply {
addAll(listOf(
TwoLineTextItem(
item = TwoLineTextItem.Item(
title = getString(R.string.follow_developer),
subTitle = getString(R.string.follow_developer_description),
enabled = true,
),
onClick = { viewModel.dispatch(SettingsIntent.FollowDeveloperSelected) }
),
TwoLineTextItem(
item = TwoLineTextItem.Item(
title = getString(R.string.share),
subTitle = getString(R.string.share_description),
enabled = true
),
onClick = { viewModel.dispatch(SettingsIntent.ShareAppSelected) }
),
OneLineTextItem(
item = OneLineTextItem.Item(
title = getString(R.string.rate_on_store),
enabled = true
),
onClick = { viewModel.dispatch(SettingsIntent.RateAppSelected) }
),
OneLineTextItem(
item = OneLineTextItem.Item(
title = getString(R.string.star_github),
enabled = true
),
onClick = { viewModel.dispatch(SettingsIntent.GitHubSelected) }
),
))
}
}
private val adapter by lazy {
GroupAdapter<GroupieViewHolder>().apply {
addAll(listOf(
userSection,
settingsSection,
privacySection,
othersSection,
supportSection,
))
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component.inject(this)
viewLifecycleOwnerLiveData.observe(this) { owner ->
viewModel.consumeEffects(owner.lifecycleScope, this::handleEffect)
viewModel.consumeStates(owner.lifecycleScope, this::render)
}
viewModel.dispatch(SettingsIntent.Initialize)
analytics.screenView(Analytics.Screen.Settings, this::class)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.notificationSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
Timber.d("notificationSwitch: $isChecked")
viewModel.dispatch(SettingsIntent.NotificationStateUpdated(enabled = isChecked))
}
binding.list.let { list ->
(list.itemAnimator as? DefaultItemAnimator)?.supportsChangeAnimations = false
list.layoutManager = LinearLayoutManager(requireContext())
list.addItemDecoration(DividerItemDecoration(requireContext()))
list.adapter = adapter
}
}
private fun handleEffect(effect: SettingsEffect) {
when (effect) {
SettingsEffect.ToLicense -> {
analytics.screenView(Analytics.Screen.License, OssLicensesMenuActivity::class)
startActivity(Intent(context, OssLicensesMenuActivity::class.java))
}
SettingsEffect.ToChangelog -> showChangelog()
is SettingsEffect.OpenBrowser -> {
context?.openExternalAppWithUrl(effect.url)
}
is SettingsEffect.ShareApp -> {
requireContext().openExternalAppWithShareIntent(
getString(R.string.share_message, effect.url)
)
}
SettingsEffect.ToSplash -> {
startActivity(LauncherActivity.callingIntent(requireContext()))
requireActivity().finish()
}
is SettingsEffect.UpdateNotification -> {
val context = requireContext()
val intent = NotificationService.callingIntent(context)
if (effect.enabled) {
ContextCompat.startForegroundService(context, intent)
} else {
context.stopService(intent)
}
}
}
}
private fun render(state: SettingsState) {
Timber.d("newState: $state")
userSection.update(listOf(UserItem(
user = state.user,
onLogoutClick = {
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.confirm)
.setMessage(R.string.logout_confirmation)
.setCancelable(true)
.setPositiveButton(R.string.logout) { _, _ -> viewModel.dispatch(SettingsIntent.LogoutSelected) }
.setNegativeButton(R.string.cancel, null)
.show()
},
onProfileClick = { viewModel.dispatch(SettingsIntent.ProfileSelected) },
)))
settingsSection.update(
listOf(
createFooterItem(state),
createTimelineAppItem(state),
),
)
val notiEnabled = state.settings?.notificationEnabled == true
val notiStateResId = if (notiEnabled) R.string.label_on else R.string.label_off
binding.notificationSwitch.text =
getString(R.string.label_notification_state, getString(notiStateResId))
val notificationStateChanged = binding.notificationSwitch.isChecked != notiEnabled
if (notificationStateChanged) {
binding.notificationSwitch.isChecked = notiEnabled
}
}
private fun createFooterItem(state: SettingsState): TwoLineTextItem {
val description = if (state.settings?.footerEnabled == true) {
getString(R.string.footer_description_on, state.settings.footerText)
} else {
getString(R.string.footer_description_off)
}
return TwoLineTextItem(
item = TwoLineTextItem.Item(
title = getString(R.string.footer),
subTitle = description,
enabled = state.settings != null,
),
onClick = {
findNavController().navigateSafe(SettingsFragmentDirections.toFooterEditor())
}
)
}
private fun createTimelineAppItem(state: SettingsState): TwoLineTextItem {
val description =
if (state.settings?.timelineAppEnabled == true && state.selectedTimelineApp != null) {
getString(R.string.timelineapp_description_on,
state.selectedTimelineApp.name)
} else {
getString(R.string.timelineapp_description_off)
}
return TwoLineTextItem(
item = TwoLineTextItem.Item(
title = getString(R.string.timelineapp),
subTitle = description,
enabled = true
),
onClick = {
val s = viewModel.state
val timelineApps = viewModel.state.timelineApps
val selectedIndex = timelineApps.indexOf(s.selectedTimelineApp)
MaterialAlertDialogBuilder(requireContext())
.setTitle(R.string.timelineapp_dialog_title)
.setSingleChoiceItems(
(listOf(getString(R.string.timelineapp_dialog_disable_value)) + timelineApps.map { it.name })
.toTypedArray(),
if (selectedIndex < 0) 0 else selectedIndex + 1,
null
)
.setPositiveButton(R.string.confirm) { dialog, _ ->
val selected = (dialog as AlertDialog).listView.checkedItemPosition
val app = timelineApps.getOrNull(selected - 1)
viewModel.dispatch(SettingsIntent.TimelineAppSelected(app?.packageName?.packageName
?: ""))
}
.show()
}
)
}
private fun showChangelog() {
analytics.screenView(Analytics.Screen.Changelog, ChangelogDialogFragment::class)
ChangelogBuilder()
.withUseBulletList(true)
.buildAndShowDialog(requireAppCompatActivity(), false)
}
}
| apache-2.0 | 62fb2869313623148f853c25bb8ba5be | 41.431818 | 117 | 0.598516 | 5.521335 | false | false | false | false |
hotshotmentors/Yengg-App-Android | app/src/main/java/in/yeng/user/syllabus/helpers/SyllabusAdapter.kt | 2 | 1609 | package `in`.yeng.user.syllabus.helpers
import `in`.yeng.user.R
import `in`.yeng.user.helpers.AnimUtil
import `in`.yeng.user.helpers.FragmentHelper
import `in`.yeng.user.helpers.viewbinders.BinderTypes
import `in`.yeng.user.home.MainActivity
import `in`.yeng.user.syllabus.SyllabusFragment
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.view.View
import jp.satorufujiwara.binder.recycler.RecyclerBinder
import kotlinx.android.synthetic.main.syllabus_card.view.*
open class SyllabusAdapter(val activity: AppCompatActivity, val data: String, val idStr: String) : RecyclerBinder<BinderTypes>(activity, BinderTypes.TYPE_SYLLABUS_DIR) {
override fun layoutResId(): Int = R.layout.syllabus_card
override fun onCreateViewHolder(v: View): ViewHolder = ViewHolder(v)
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
val holder = viewHolder as ViewHolder
with(holder.view) {
AnimUtil.fadeUp(this, 350, 40f, 0.98f)
content.text = data.replace(idStr.plus("_"), "")
findViewById<View>(R.id.card).setOnClickListener {
AnimUtil.clickAnimation(it)
val fragSyllabus = SyllabusFragment()
fragSyllabus.arguments = Bundle().apply { putString("id", data) }
FragmentHelper.addFragment(fragSyllabus, activity, MainActivity.CONTAINER_LAYOUT, SyllabusFragment.TAG, 250)
}
}
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)
} | gpl-3.0 | 565827edf36af3763d99fdc39930db36 | 40.282051 | 169 | 0.722188 | 3.707373 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/tvseason/get/TVSeasonGet.kt | 1 | 1607 | package uk.co.ourfriendirony.medianotifier.clients.tmdb.tvseason.get
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(
"_id",
"air_date",
"episodes",
"name",
"overview",
"id",
"poster_path",
"season_number",
"external_ids"
)
class TVSeasonGet {
@get:JsonProperty("_id")
@set:JsonProperty("_id")
@JsonProperty("_id")
var idCore: String? = null
@get:JsonProperty("air_date")
@set:JsonProperty("air_date")
@JsonProperty("air_date")
var airDate: String? = null
@get:JsonProperty("episodes")
@set:JsonProperty("episodes")
@JsonProperty("episodes")
var tvSeasonGetEpisodes: List<TVSeasonGetEpisode>? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("overview")
@set:JsonProperty("overview")
@JsonProperty("overview")
var overview: String? = null
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: Int? = null
@get:JsonProperty("poster_path")
@set:JsonProperty("poster_path")
@JsonProperty("poster_path")
var posterPath: String? = null
@get:JsonProperty("season_number")
@set:JsonProperty("season_number")
@JsonProperty("season_number")
var seasonNumber: Int? = null
@get:JsonProperty("external_ids")
@set:JsonProperty("external_ids")
@JsonProperty("external_ids")
var tVSeasonGetExternalIds: TVSeasonGetExternalIds? = null
} | apache-2.0 | 0b5b0cc8d4a3a265151c658a8e691a18 | 24.52381 | 68 | 0.664592 | 3.817102 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/tab/TabList.kt | 1 | 8559 | package jp.toastkid.yobidashi.tab
import android.content.Context
import androidx.annotation.Keep
import jp.toastkid.yobidashi.browser.archive.IdGenerator
import jp.toastkid.yobidashi.tab.model.ArticleListTab
import jp.toastkid.yobidashi.tab.model.ArticleTab
import jp.toastkid.yobidashi.tab.model.CalendarTab
import jp.toastkid.yobidashi.tab.model.EditorTab
import jp.toastkid.yobidashi.tab.model.PdfTab
import jp.toastkid.yobidashi.tab.model.Tab
import jp.toastkid.yobidashi.tab.model.WebTab
import kotlinx.serialization.Required
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okio.buffer
import okio.sink
import okio.source
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.Collections
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* First class collection of [Tab].
*
* @author toastkidjp
*/
@Serializable
class TabList {
@Transient
private val tabs: MutableList<Tab> = mutableListOf()
@Required
@Keep
private var index: Int = 0
internal fun currentTab(): Tab? {
if (tabs.isEmpty() || invalidIndex(index)) {
return null
}
return tabs[index]
}
internal fun setIndex(newIndex: Int) {
index = if (invalidIndex(newIndex)) 0 else newIndex
}
@Keep
fun getIndex(): Int = index
@Keep
fun size(): Int = tabs.size
internal fun get(position: Int): Tab? =
if (position < 0 || tabs.size <= position) {
null
} else {
tabs[position]
}
internal fun set(index: Int, currentTab: Tab) {
val target = if (invalidIndex(index)) { 0 } else { index }
tabs[target] = currentTab
}
private fun invalidIndex(newIndex: Int): Boolean {
return !inRange(newIndex)
}
/**
* Save current state to file.
*/
internal fun save() {
val json = jsonSerializer.encodeToString(this)
tabsFile?.let {
it.sink().use { sink ->
sink.buffer().use { buffered ->
buffered.writeUtf8(json)
buffered.flush()
}
}
}
savingLock.withLock {
itemsDir?.let {
it.deleteRecursively()
it.mkdirs()
}
tabs.forEach { tab ->
val source: ByteArray? = when (tab) {
is WebTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
is EditorTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
is PdfTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
is ArticleTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
is ArticleListTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
is CalendarTab -> jsonSerializer.encodeToString(tab)?.toByteArray(charset)
else -> ByteArray(0)
}
source?.let {
File(itemsDir, "${tab.id()}.json").sink().use { sink ->
sink.buffer().use { bufferedSink ->
bufferedSink.write(source)
}
}
}
}
}
}
internal val isEmpty: Boolean
get() = tabs.isEmpty()
internal fun add(newTab: Tab) {
addTo(newTab, index + 1)
}
internal fun addTo(tab: Tab, index: Int) {
if (inRange(index)) {
tabs.add(index, tab)
} else {
tabs.add(tab)
}
}
internal fun closeTab(index: Int) {
if (index <= this.index && this.index != 0) {
this.index--
}
val tab: Tab = tabs[index]
File(itemsDir, tab.id() + ".json").delete()
tabs.remove(tab)
}
internal fun clear() {
tabs.clear()
index = 0
tabsFile?.delete()
itemsDir?.delete()
save()
}
fun swap(from: Int, to: Int) {
if (inRange(from, to)) {
val currentTab = currentTab() ?: return
Collections.swap(tabs, from, to)
setIndex(tabs.indexOf(currentTab))
}
}
private fun inRange(vararg indexes: Int): Boolean {
val size = tabs.size
return indexes.none { it < 0 || size <= it }
}
companion object {
private const val TABS_DIR = "tabs"
private const val TABS_ITEM_DIR = "$TABS_DIR/items"
private val savingLock = ReentrantLock()
private var tabsFile: File? = null
private val charset = charset("UTF-8")
private val jsonSerializer = Json {
ignoreUnknownKeys = true
}
private var itemsDir: File? = null
internal fun loadOrInit(context: Context): TabList {
initTabsFile(context)
if (tabsFile == null || tabsFile?.exists() == false) {
return TabList()
}
try {
val file = tabsFile
val fromJson: TabList =
if (file == null) TabList()
else file.source().use { source ->
source.buffer().use { bufferedSource ->
jsonSerializer.decodeFromString(bufferedSource.readUtf8())
}
} ?: TabList()
loadTabsFromDir()
?.forEach { it?.let { fromJson.add(it) } }
if (fromJson.size() <= fromJson.index) {
fromJson.index = fromJson.size() - 1
}
return fromJson
} catch (e: IOException) {
Timber.e(e)
}
return TabList()
}
private fun loadTabsFromDir(): List<Tab?>? {
return itemsDir?.list()
?.map {
val json: String = File(itemsDir, it).source().use { source ->
source.buffer().use { bufferedSource ->
bufferedSource.readUtf8()
}
}
when {
json.contains("editorTab") -> jsonSerializer.decodeFromString<EditorTab>(json)
json.contains("pdfTab") -> jsonSerializer.decodeFromString<PdfTab>(json)
json.contains("articleTab") -> jsonSerializer.decodeFromString<ArticleTab>(json)
json.contains("articleListTab") -> jsonSerializer.decodeFromString<ArticleListTab>(json)
json.contains("calendarTab") -> jsonSerializer.decodeFromString<CalendarTab>(json)
else -> jsonSerializer.decodeFromString<WebTab>(json)
}
}
}
private fun initTabsFile(context: Context) {
val storeDir = File(context.filesDir, TABS_DIR)
if (!storeDir.exists()) {
storeDir.mkdirs()
}
tabsFile = File(storeDir, "tabs.json")
itemsDir = File(context.filesDir, TABS_ITEM_DIR)
if (itemsDir != null && !(itemsDir as File).exists()) {
itemsDir?.mkdirs()
}
}
}
internal fun indexOf(tab: Tab): Int = tabs.indexOf(tab)
override fun toString(): String = tabs.toString()
fun updateWithIdAndHistory(idAndHistory: Pair<String, History>) {
val targetId = idAndHistory.first
tabs.firstOrNull { it is WebTab && it.id() == targetId }
?.let {
val currentIndex = tabs.indexOf(it)
(it as? WebTab)?.addHistory(idAndHistory.second)
tabs.set(currentIndex, it)
save()
}
}
fun thumbnailNames(): Collection<String> = makeCopyTabs().map { it.thumbnailPath() }
fun archiveIds(): Collection<String> {
val idGenerator = IdGenerator()
return makeCopyTabs().map { idGenerator.from(it.getUrl()) ?: "" }
}
fun ids(): Collection<String> {
return makeCopyTabs().map { it.id() }
}
private fun makeCopyTabs(): MutableList<Tab> {
return ArrayList(tabs)
}
}
| epl-1.0 | c4ec7a08ae698913916e1d17cfe0d12e | 30.466912 | 116 | 0.539666 | 4.744457 | false | false | false | false |
robfletcher/kork | kork-plugins/src/main/kotlin/com/netflix/spinnaker/kork/plugins/proxy/aspects/MetricInvocationAspect.kt | 2 | 6625 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins.proxy.aspects
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import com.netflix.spectator.api.Clock
import com.netflix.spectator.api.DefaultRegistry
import com.netflix.spectator.api.Id
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.kork.annotations.Metered
import com.netflix.spinnaker.kork.plugins.SpinnakerPluginDescriptor
import com.netflix.spinnaker.kork.plugins.api.internal.SpinnakerExtensionPoint
import com.netflix.spinnaker.kork.telemetry.MethodInstrumentation
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.ObjectProvider
/**
* Adds metric instrumentation to extension method invocations.
*
* Two metrics will be recorded for any extension: timing and invocations, with an additional tag
* for "result", having either the value "success" or "failure".
*
*/
class MetricInvocationAspect(
private val registryProvider: ObjectProvider<Registry>
) : InvocationAspect<MetricInvocationState> {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
private val methodMetricIds: Cache<Method, MetricIds> = Caffeine.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.expireAfterWrite(1, TimeUnit.HOURS)
.build<Method, MetricIds>()
/**
* Extensions are loaded early in the Spring application lifecycle, and there's a chance that the
* Spectator [Registry] does not yet exist when an extension method is invoked. This allows us to
* fallback to a temporary registry. Metrics collected in the fallback registry are discarded.
*
* Open question - If a fallback registry is returned, can we collect those metrics and then dump
* them onto the main registry once that exists?
*/
private fun ObjectProvider<Registry>.getOrFallback(extensionName: String): Registry {
val registry = this.ifAvailable
if (registry == null) {
log.warn("Returning fallback registry for extension={}; metrics collected in fallback are discarded.", extensionName)
return DefaultRegistry(Clock.SYSTEM)
}
return registry
}
override fun supports(invocationState: Class<InvocationState>): Boolean {
return invocationState == MetricInvocationState::class.java
}
override fun before(
target: SpinnakerExtensionPoint,
proxy: Any,
method: Method,
args: Array<out Any>?,
descriptor: SpinnakerPluginDescriptor
): MetricInvocationState {
val extensionName = target.javaClass.simpleName.toString()
val registry = registryProvider.getOrFallback(extensionName)
val metricIds = methodMetricIds.getOrPut(target, method, descriptor, registry)
return MetricInvocationState(
extensionName = extensionName,
startTimeMs = System.currentTimeMillis(),
timingId = metricIds?.timingId
)
}
override fun after(invocationState: MetricInvocationState) {
recordMetrics(Result.SUCCESS, invocationState)
}
override fun error(e: InvocationTargetException, invocationState: MetricInvocationState) {
recordMetrics(Result.FAILURE, invocationState)
}
private fun recordMetrics(result: Result, invocationState: MetricInvocationState) {
if (invocationState.timingId != null) {
val registry = registryProvider.getOrFallback(invocationState.extensionName)
registry.timer(invocationState.timingId.withTag("result", result.toString()))
.record(System.currentTimeMillis() - invocationState.startTimeMs, TimeUnit.MILLISECONDS)
}
}
/**
* Looks for methods annotated with [Metered].
*
* Performs a [Cache] `get` which retrieves the cached data or else creates the data and then
* inserts it into the cache.
*/
private fun Cache<Method, MetricIds>.getOrPut(
target: Any,
method: Method,
descriptor: SpinnakerPluginDescriptor,
registry: Registry
): MetricIds? {
return this.get(target.javaClass.getMethod(method.name, *method.parameterTypes)) { m ->
m.declaredAnnotations
.find { it is Metered }
.let { metered ->
if (metered != null) {
(metered as Metered)
if (metered.ignore) {
null
} else {
val defaultTags = mapOf(
Pair("pluginVersion", descriptor.version),
Pair("pluginExtension", target.javaClass.simpleName.toString())
)
val tags = MethodInstrumentation.coalesceTags(
target,
method, defaultTags, metered.tags
)
val metricIds = MetricIds(
timingId = registry.createId(toMetricId(m, descriptor.pluginId, metered.metricName, TIMING), tags)
)
for (mutableEntry in this.asMap()) {
if (mutableEntry.value.timingId.name() == metricIds.timingId.name()) {
throw MethodInstrumentation.MetricNameCollisionException(
target,
metricIds.timingId.name(), mutableEntry.key, m
)
}
}
metricIds
}
} else {
null
}
}
}
}
private fun toMetricId(method: Method, metricNamespace: String, annotationMetricId: String?, metricName: String): String? {
val methodMetricId = if (method.parameterCount == 0) method.name else String.format("%s%d", method.name, method.parameterCount)
val metricId = if (annotationMetricId.isNullOrEmpty()) methodMetricId else annotationMetricId
return MethodInstrumentation.toMetricId(metricNamespace, metricId, metricName)
}
private data class MetricIds(val timingId: Id)
companion object {
private const val TIMING = "timing"
private const val MAX_CACHE_SIZE = 1000L
enum class Result {
SUCCESS, FAILURE;
override fun toString(): String = name.toLowerCase()
}
}
}
| apache-2.0 | 99d43c3b7b301b34dbe47e03dd692d0b | 35.805556 | 131 | 0.703698 | 4.568966 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryCategoryView.kt | 2 | 8511 | package eu.kanade.tachiyomi.ui.library
import android.content.Context
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.widget.FrameLayout
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.davidea.flexibleadapter.SelectableAdapter
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.library.LibraryUpdateService
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.util.inflate
import eu.kanade.tachiyomi.util.plusAssign
import eu.kanade.tachiyomi.util.toast
import eu.kanade.tachiyomi.widget.AutofitRecyclerView
import kotlinx.android.synthetic.main.library_category.view.*
import rx.subscriptions.CompositeSubscription
import uy.kohesive.injekt.injectLazy
/**
* Fragment containing the library manga for a certain category.
*/
class LibraryCategoryView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
FrameLayout(context, attrs),
FlexibleAdapter.OnItemClickListener,
FlexibleAdapter.OnItemLongClickListener {
/**
* Preferences.
*/
private val preferences: PreferencesHelper by injectLazy()
/**
* The fragment containing this view.
*/
private lateinit var controller: LibraryController
/**
* Category for this view.
*/
lateinit var category: Category
private set
/**
* Recycler view of the list of manga.
*/
private lateinit var recycler: RecyclerView
/**
* Adapter to hold the manga in this category.
*/
private lateinit var adapter: LibraryCategoryAdapter
/**
* Subscriptions while the view is bound.
*/
private var subscriptions = CompositeSubscription()
fun onCreate(controller: LibraryController) {
this.controller = controller
recycler = if (preferences.libraryAsList().getOrDefault()) {
(swipe_refresh.inflate(R.layout.library_list_recycler) as RecyclerView).apply {
layoutManager = LinearLayoutManager(context)
}
} else {
(swipe_refresh.inflate(R.layout.library_grid_recycler) as AutofitRecyclerView).apply {
spanCount = controller.mangaPerRow
}
}
adapter = LibraryCategoryAdapter(this)
recycler.setHasFixedSize(true)
recycler.adapter = adapter
swipe_refresh.addView(recycler)
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recycler: RecyclerView, newState: Int) {
// Disable swipe refresh when view is not at the top
val firstPos = (recycler.layoutManager as LinearLayoutManager)
.findFirstCompletelyVisibleItemPosition()
swipe_refresh.isEnabled = firstPos <= 0
}
})
// Double the distance required to trigger sync
swipe_refresh.setDistanceToTriggerSync((2 * 64 * resources.displayMetrics.density).toInt())
swipe_refresh.setOnRefreshListener {
if (!LibraryUpdateService.isRunning(context)) {
LibraryUpdateService.start(context, category)
context.toast(R.string.updating_category)
}
// It can be a very long operation, so we disable swipe refresh and show a toast.
swipe_refresh.isRefreshing = false
}
}
fun onBind(category: Category) {
this.category = category
adapter.mode = if (controller.selectedMangas.isNotEmpty()) {
SelectableAdapter.Mode.MULTI
} else {
SelectableAdapter.Mode.SINGLE
}
subscriptions += controller.searchRelay
.doOnNext { adapter.searchText = it }
.skip(1)
.subscribe { adapter.performFilter() }
subscriptions += controller.libraryMangaRelay
.subscribe { onNextLibraryManga(it) }
subscriptions += controller.selectionRelay
.subscribe { onSelectionChanged(it) }
}
fun onRecycle() {
adapter.setItems(emptyList())
adapter.clearSelection()
unsubscribe()
}
fun unsubscribe() {
subscriptions.clear()
}
/**
* Subscribe to [LibraryMangaEvent]. When an event is received, it updates the content of the
* adapter.
*
* @param event the event received.
*/
fun onNextLibraryManga(event: LibraryMangaEvent) {
// Get the manga list for this category.
val mangaForCategory = event.getMangaForCategory(category).orEmpty()
// Update the category with its manga.
adapter.setItems(mangaForCategory)
if (adapter.mode == SelectableAdapter.Mode.MULTI) {
controller.selectedMangas.forEach { manga ->
val position = adapter.indexOf(manga)
if (position != -1 && !adapter.isSelected(position)) {
adapter.toggleSelection(position)
(recycler.findViewHolderForItemId(manga.id!!) as? LibraryHolder)?.toggleActivation()
}
}
}
}
/**
* Subscribe to [LibrarySelectionEvent]. When an event is received, it updates the selection
* depending on the type of event received.
*
* @param event the selection event received.
*/
private fun onSelectionChanged(event: LibrarySelectionEvent) {
when (event) {
is LibrarySelectionEvent.Selected -> {
if (adapter.mode != SelectableAdapter.Mode.MULTI) {
adapter.mode = SelectableAdapter.Mode.MULTI
}
findAndToggleSelection(event.manga)
}
is LibrarySelectionEvent.Unselected -> {
findAndToggleSelection(event.manga)
if (controller.selectedMangas.isEmpty()) {
adapter.mode = SelectableAdapter.Mode.SINGLE
}
}
is LibrarySelectionEvent.Cleared -> {
adapter.mode = SelectableAdapter.Mode.SINGLE
adapter.clearSelection()
}
}
}
/**
* Toggles the selection for the given manga and updates the view if needed.
*
* @param manga the manga to toggle.
*/
private fun findAndToggleSelection(manga: Manga) {
val position = adapter.indexOf(manga)
if (position != -1) {
adapter.toggleSelection(position)
(recycler.findViewHolderForItemId(manga.id!!) as? LibraryHolder)?.toggleActivation()
}
}
/**
* Called when a manga is clicked.
*
* @param position the position of the element clicked.
* @return true if the item should be selected, false otherwise.
*/
override fun onItemClick(position: Int): Boolean {
// If the action mode is created and the position is valid, toggle the selection.
val item = adapter.getItem(position) ?: return false
if (adapter.mode == SelectableAdapter.Mode.MULTI) {
toggleSelection(position)
return true
} else {
openManga(item.manga)
return false
}
}
/**
* Called when a manga is long clicked.
*
* @param position the position of the element clicked.
*/
override fun onItemLongClick(position: Int) {
controller.createActionModeIfNeeded()
toggleSelection(position)
}
/**
* Opens a manga.
*
* @param manga the manga to open.
*/
private fun openManga(manga: Manga) {
controller.openManga(manga)
}
/**
* Tells the presenter to toggle the selection for the given position.
*
* @param position the position to toggle.
*/
private fun toggleSelection(position: Int) {
val item = adapter.getItem(position) ?: return
controller.setSelection(item.manga, !adapter.isSelected(position))
controller.invalidateActionMode()
}
}
| apache-2.0 | ea7075ffb8cc6bd77d6aa04402c064cf | 32.45749 | 104 | 0.618964 | 5.221472 | false | false | false | false |
asymmetric-team/secure-messenger-android | create-conversation-core/src/test/java/com/safechat/conversation/create/CreateConversationControllerTest.kt | 1 | 1610 | package com.safechat.conversation.create
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
import rx.Observable
class CreateConversationControllerTest {
val service = mock<CreateConversationService>()
val repository = mock<CreateConversationRepository>()
val suidCalculator = mock<SuidCalculator>()
val view = mock<CreateConversationView>()
val controller = CreateConversationControllerImpl(service, repository, suidCalculator, view)
@Before
fun setUp() {
whenever(suidCalculator.findShortestUniqueSubstring(any(), any())).thenReturn("my_public")
whenever(service.getUsers()).thenReturn(Observable.just(listOf(User("A"), User("B"))))
whenever(repository.getPublicKeyString()).thenReturn("my_public_key")
}
@Test
fun shouldGetAllUsersOnCreate() {
controller.onCreate()
verify(service).getUsers()
}
@Test
fun shouldGetOwnerKeyFromRepositoryOnCreate() {
controller.onCreate()
verify(repository).getPublicKeyString()
}
@Test
fun shouldShowShortestUniqueSubstringOfUserRSA() {
controller.onCreate()
verify(view).showShortestUniqueId(Mockito.anyString())
}
@Test
fun shouldShowErrorWhenRetrieveUsersFails() {
whenever(service.getUsers()).thenReturn(Observable.error(RuntimeException()))
controller.onCreate()
verify(view).showError()
}
}
| apache-2.0 | 6cd9bca8c599e76f4d9386ee87babc48 | 27.245614 | 98 | 0.719876 | 4.613181 | false | true | false | false |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/db/DuplicateItemPairDao.kt | 1 | 2363 | /*
* Copyright 2021, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import com.github.duplicates.DuplicateItemType
/**
* Pair entity DAO.
*/
@Dao
interface DuplicateItemPairDao : BaseDao<DuplicateItemPairEntity> {
/**
* Select all pairs from the table.
*
* @return all pairs.
*/
@Query("SELECT * FROM pair")
fun queryAll(): List<DuplicateItemPairEntity>
/**
* Select all pairs from the table.
*
* @return all pairs.
*/
@Transaction
@Query("SELECT * FROM pair")
fun queryAllWithTasksLive(): LiveData<List<DuplicateItemPairEntity>>
/**
* Select all pairs from the table.
*
* @return all pairs.
*/
@Query("SELECT * FROM pair WHERE type=:type")
fun queryAll(type: DuplicateItemType): List<DuplicateItemPairEntity>
/**
* Delete all pairs.
*/
@Query("DELETE FROM pair")
fun deleteAll(): Int
/**
* Delete all pairs.
*/
@Query("DELETE FROM pair WHERE type=:type")
fun deleteAll(type: DuplicateItemType): Int
/**
* Delete all items.
*/
@Query("DELETE FROM pair WHERE (type=:type) AND ((id1=:id) OR (id2=:id))")
fun deleteAll(type: DuplicateItemType, id: Long)
/**
* Update the item1's checked status.
*/
@Query("UPDATE pair SET checked1=:checked WHERE (type=:type) AND (id1=:id)")
fun updateItemChecked1(type: DuplicateItemType, id: Long, checked: Boolean): Int
/**
* Update the item2's checked status.
*/
@Query("UPDATE pair SET checked2=:checked WHERE (type=:type) AND (id2=:id)")
fun updateItemChecked2(type: DuplicateItemType, id: Long, checked: Boolean): Int
} | apache-2.0 | aa86cfe24e5583c4ee5abb5ef2b38c6f | 26.811765 | 84 | 0.665256 | 4.067126 | false | false | false | false |
googlearchive/android-RecyclerView | kotlinApp/app/src/main/java/com/example/android/common/logger/LogFragment.kt | 3 | 3139 | /*
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.common.logger
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.TextViewCompat
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ScrollView
/**
* Simple fragment which contains a LogView and uses is to output log data it receives
* through the LogNode interface.
*/
class LogFragment : Fragment() {
lateinit var logView: LogView
private set
private lateinit var scrollView: ScrollView
private fun inflateViews(): View {
scrollView = ScrollView(activity)
val scrollParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT)
scrollView.layoutParams = scrollParams
logView = LogView(activity as Context)
val logParams = ViewGroup.LayoutParams(scrollParams)
logParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
with(logView) {
layoutParams = logParams
isClickable = true
isFocusable = true
typeface = Typeface.MONOSPACE
}
// Want to set padding as 16 dips, setPadding takes pixels. Hooray math!
val paddingDips = 16
val scale = resources.displayMetrics.density.toDouble()
val paddingPixels = (paddingDips * scale + .5).toInt()
logView.setPadding(paddingPixels, paddingPixels, paddingPixels, paddingPixels)
logView.compoundDrawablePadding = paddingPixels
logView.gravity = Gravity.BOTTOM
TextViewCompat.setTextAppearance(logView, android.R.style.TextAppearance_Holo_Medium)
scrollView.addView(logView)
return scrollView
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val result = inflateViews()
logView.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
scrollView.fullScroll(ScrollView.FOCUS_DOWN)
}
})
return result
}
} | apache-2.0 | 0185d77fab0befca11225812f27ddb9c | 33.505495 | 98 | 0.700542 | 4.741692 | false | false | false | false |
alashow/music-android | modules/base/src/main/java/tm/alashow/base/util/date/CalendarUtils.kt | 1 | 5046 | /*
* Copyright (C) 2019, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.base.util.date
import java.util.*
fun Calendar.toDate(): Date = time
fun Date.toCalendar(): Calendar = Calendar.getInstance().also {
it.timeInMillis = this.time
}
fun Long.toCalendar() = Calendar.getInstance().also {
it.timeInMillis = this
}
fun Calendar.copy() = clone() as Calendar
/**
* @param month starting from 0, as [Calendar.MONTH].
*/
fun calendar(year: Int, month: Int, date: Int, hourOfDay: Int = 0, minute: Int = 0, seconds: Int = 0): Calendar {
val calendar = Calendar.getInstance()
calendar.set(year, month, date, hourOfDay, minute, seconds)
return calendar
}
fun Calendar.year() = get(Calendar.YEAR)
fun Calendar.month() = get(Calendar.MONTH)
fun Calendar.day() = get(Calendar.DAY_OF_MONTH)
fun Calendar.minute() = get(Calendar.MINUTE)
fun Calendar.second() = get(Calendar.SECOND)
fun Calendar.dayPadded() = "%01d".format(day())
fun Calendar.dayOfYear() = get(Calendar.DAY_OF_YEAR)
fun Calendar.toDateString() = "${year()}, ${month()}, ${day()}"
operator fun Calendar.component1() = year()
operator fun Calendar.component2() = month()
operator fun Calendar.component3() = day()
operator fun Calendar.component4() = minute()
operator fun Calendar.component5() = second()
infix fun Calendar.sameYear(other: Calendar) = year() == other.year()
infix fun Calendar.sameMonth(other: Calendar) = month() == other.month()
infix fun Calendar.sameDate(other: Calendar) = sameYear(other) && sameMonth(other) && (day() == other.day())
infix fun Date.sameYear(other: Calendar) = toCalendar().sameYear(other)
infix fun Date.sameYear(other: Date) = sameYear(other.toCalendar())
infix fun Date.sameMonth(other: Date) = toCalendar().sameMonth(other.toCalendar())
infix fun Date.sameDate(other: Date) = toCalendar().sameDate(other.toCalendar())
infix fun Calendar.diff(end: Calendar): Long {
val startTime = timeInMillis
val endTime = end.timeInMillis
return endTime - startTime
}
infix fun Calendar.diffInDays(end: Calendar): Long {
val diffTime = diff(end)
return diffTime / (1000 * 60 * 60 * 24)
}
fun Calendar.addPure(field: Int, value: Int): Calendar = this.copy().apply {
add(field, value)
}
fun Date.addPure(field: Int, value: Int): Date = toCalendar().addPure(field, value).time
infix fun Calendar.addDays(days: Int): Calendar = addPure(Calendar.DAY_OF_YEAR, days)
infix fun Calendar.addMonths(months: Int): Calendar = addPure(Calendar.MONTH, months)
infix fun Calendar.addYears(years: Int): Calendar = addPure(Calendar.YEAR, years)
infix fun Date.addDays(days: Int): Date = (toCalendar() addDays days).time
infix fun Date.addMonths(months: Int): Date = (toCalendar() addMonths months).time
infix fun Date.addYears(years: Int): Date = (toCalendar() addYears years).time
infix operator fun Calendar.minus(that: Calendar) = (timeInMillis - that.timeInMillis).toCalendar()
infix operator fun Calendar.plus(that: Calendar) = (timeInMillis + that.timeInMillis).toCalendar()
infix operator fun Date.minus(that: Date) = Date(time - that.time)
infix operator fun Date.plus(that: Date) = Date(time + that.time)
infix operator fun Calendar.compareTo(that: Date): Int = (timeInMillis - that.time).toInt()
infix operator fun Calendar.compareTo(that: Calendar): Int = (timeInMillis - that.timeInMillis).toInt()
infix operator fun Date.compareTo(that: Date): Int = (time - that.time).toInt()
infix operator fun Date.compareTo(that: Calendar): Int = (time - that.timeInMillis).toInt()
operator fun Calendar.inc() = this addDays 1
operator fun Calendar.dec() = this addDays -1
operator fun Date.inc() = this addDays 1
operator fun Date.dec() = this addDays -1
fun Calendar.isLeapYear(): Boolean {
var year = get(Calendar.YEAR)
if (year % 100 == 0)
year /= 100
return year % 4 == 0
}
fun Calendar.daysInAYear() = when (isLeapYear()) {
true -> 366
else -> 365
}
infix fun Calendar.yearsDiff(end: Calendar): Float {
val years = (year() - end.year()).toFloat()
val dayOfYearDiff = (dayOfYear() - end.dayOfYear())
return years - dayOfYearDiff.toFloat() / daysInAYear().toFloat()
}
fun Calendar.timeless(): Calendar = this.copy().apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
fun Date.timeless(): Date = toCalendar().timeless().time
fun List<Date>.timeless(): List<Date> = map { it.timeless() }
fun List<Calendar>.limit(min: Calendar? = null, max: Calendar? = null) = map {
when {
min != null && it < min -> min
max != null && it > max -> max
else -> it
}
}
fun List<Date>.limit(min: Date? = null, max: Date? = null) = map {
when {
min != null && it < min -> min
max != null && it > max -> max
else -> it
}
}
fun List<Date>.isValid(min: Date? = null, max: Date? = null) = map {
when {
min != null && it < min -> false
max != null && it > max -> false
else -> true
}
}.all { it }
| apache-2.0 | 8957f26394383a5359680aa1ec15370c | 33.8 | 113 | 0.680143 | 3.487215 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/Split.kt | 1 | 2530 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import kotlinx.serialization.Transient
import net.devrieze.util.collection.replaceBy
import net.devrieze.util.collection.setOfNotNull
import nl.adaptivity.process.ProcessConsts.Engine
import nl.adaptivity.process.util.Identifiable
import nl.adaptivity.process.util.Identified
import nl.adaptivity.process.util.Identifier
import nl.adaptivity.xmlutil.QName
interface Split : ProcessNode, JoinSplit {
val predecessor: Identifiable?
override fun builder(): Builder
interface Builder : JoinSplit.Builder {
override fun <R> visit(visitor: ProcessNode.BuilderVisitor<R>) = visitor.visitSplit(this)
var predecessor: Identifiable?
override val predecessors: Set<Identified>
get() = setOfNotNull(predecessor?.identifier)
override var successors: MutableSet<Identified>
fun setSuccessors(value: Iterable<Identified>) = successors.replaceBy(value)
override fun addSuccessor(identifier: Identifier) {
successors.add(identifier)
}
override fun addPredecessor(identifier: Identifier) {
val p = predecessor
if (p != null) {
if (p.identifier == identifier) return
throw IllegalStateException("Predecessor already set")
}
predecessor = identifier
}
override fun removeSuccessor(identifier: Identifiable) {
successors.remove(identifier)
}
override fun removePredecessor(identifier: Identifiable) {
if (predecessor?.id == identifier.id) predecessor = null
}
}
companion object {
const val ELEMENTLOCALNAME = "split"
val ELEMENTNAME = QName(Engine.NAMESPACE, ELEMENTLOCALNAME, Engine.NSPREFIX)
}
// No methods beyond JoinSplit
}
| lgpl-3.0 | 6b4d2e6c4124c145527a8ec91603b725 | 31.025316 | 112 | 0.703162 | 4.809886 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/service/pagination/PaginationCalculator.kt | 1 | 9921 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.service.pagination
import ninja.leaping.configurate.ConfigurationNode
import ninja.leaping.configurate.commented.CommentedConfigurationNode
import ninja.leaping.configurate.hocon.HoconConfigurationLoader
import ninja.leaping.configurate.loader.ConfigurationLoader
import ninja.leaping.configurate.loader.HeaderMode
import org.lanternpowered.api.text.LiteralText
import org.lanternpowered.api.text.LiteralTextBuilder
import org.lanternpowered.api.text.Text
import org.lanternpowered.api.text.format.TextDecoration
import org.lanternpowered.api.text.format.TextDecorationState
import org.lanternpowered.api.text.textOf
import org.lanternpowered.api.text.toPlain
import org.spongepowered.math.GenericMath
import kotlin.math.ceil
/**
* Pagination calculator for players.
*
* @property linesPerPage The amount of lines per page there should be
*/
internal class PaginationCalculator(val linesPerPage: Int) {
companion object {
private var NON_UNICODE_CHARS: String
private val NON_UNICODE_CHAR_WIDTHS: IntArray
private val UNICODE_CHAR_WIDTHS: ByteArray
private const val LINE_WIDTH = 320
init {
val loader: ConfigurationLoader<CommentedConfigurationNode> = HoconConfigurationLoader.builder()
.setURL(PaginationCalculator::class.java.getResource("/internal/font_sizes.json"))
.setHeaderMode(HeaderMode.PRESET)
.build()
val node: ConfigurationNode = loader.load()
NON_UNICODE_CHARS = node.getNode("non-unicode").string!!
val charWidths = node.getNode("char-widths").childrenList
NON_UNICODE_CHAR_WIDTHS = IntArray(charWidths.size)
for (i in NON_UNICODE_CHAR_WIDTHS.indices)
NON_UNICODE_CHAR_WIDTHS[i] = charWidths[i].int
val glyphWidths = node.getNode("glyph-widths").childrenList
UNICODE_CHAR_WIDTHS = ByteArray(glyphWidths.size)
for (i in UNICODE_CHAR_WIDTHS.indices)
UNICODE_CHAR_WIDTHS[i] = glyphWidths[i].int.toByte()
}
}
/**
* Gets the number of lines the specified text flows into.
*
* @param text The text to calculate the number of lines for
* @return The number of lines that this text flows into
*/
fun getLines(text: Text): Int =
ceil(this.getWidth(text).toDouble() / LINE_WIDTH).toInt()
/**
* Gets the width of a character with the specified code
* point, accounting for if its text is bold our not.
*
* @param codePoint The code point of the character
* @param bold Whether or not the character is bold or not
* @return The width of the character at the code point
*/
private fun getWidth(codePoint: Int, bold: Boolean): Int {
val nonUnicodeIdx = NON_UNICODE_CHARS.indexOf(codePoint.toChar())
var width: Int
if (codePoint == 167) {
// Color code character, this has no width
width = 0
} else if (codePoint == 32) {
// Space
width = 4
} else if (codePoint > 0 && nonUnicodeIdx != -1) {
width = NON_UNICODE_CHAR_WIDTHS[nonUnicodeIdx]
} else if (UNICODE_CHAR_WIDTHS[codePoint].toInt() != 0) {
// from 1.9 & 255 to avoid strange signed int math ruining things.
// https://bugs.mojang.com/browse/MC-7181
val temp = UNICODE_CHAR_WIDTHS[codePoint].toInt() and 0xff
// Split into high and low nibbles.
// bit digits
// 87654321 >>> 4 = 00008765
val startColumn = temp ushr 4
// 87654321 & 00001111 = 00004321
val endColumn = temp and 0xf
width = (endColumn + 1) - startColumn
// Why does this scaling happen?
// I believe it makes unicode fonts skinnier to better match the character widths of the default Minecraft
// font however there is a int math vs float math bug in the Minecraft FontRenderer.
// The float math is adjusted for rendering, they attempt to do the same thing for calculating string widths
// using integer math, this has potential rounding errors, but we should copy it and use ints as well.
width = (width / 2) + 1
} else {
width = 0
}
// If bold, the width gets 1 added
if (bold && width > 0)
width++
return width
}
/**
* Gets the length of a text.
*
* @param text The text to get the length of
* @return The length of the text
*/
private fun getWidth(text: Text): Int =
this.getWidth(text, false)
private fun getWidth(text: Text, bold: Boolean): Int {
@Suppress("NAME_SHADOWING")
var bold = bold
val boldState = text.style().decoration(TextDecoration.BOLD)
if (boldState != TextDecorationState.NOT_SET)
bold = boldState == TextDecorationState.TRUE
val content = if (text is LiteralText) {
text.content()
} else {
text.children(emptyList()).toPlain()
}
var length = this.getWidth(content, bold)
// Get the length of all the children
for (child in text.children())
length += this.getWidth(child, bold)
return length
}
private fun getWidth(text: String, bold: Boolean): Int {
var total = 0
var newLine = false
val it = text.codePoints().iterator()
while (it.hasNext()) {
val codePoint = it.nextInt()
if (codePoint == '\n'.toInt()) {
// If the previous character is a '\n'
if (newLine) {
total += LINE_WIDTH
} else {
total = ceil(total.toDouble() / LINE_WIDTH).toInt() * LINE_WIDTH
newLine = true
}
} else {
val width = this.getWidth(codePoint, bold)
total += width
newLine = false
}
}
return total
}
/**
* Centers a text within the middle of the chat box.
*
* Generally used for titles and footers.
*
* To use no heading, just pass in a 0 width text for
* the first argument.
*
* @param text The text to center
* @param padding A padding character with a width >1
* @return The centered text, or if too big, the original text
*/
fun center(text: Text, padding: Text): Text {
@Suppress("NAME_SHADOWING")
var text = text
@Suppress("NAME_SHADOWING")
var padding = padding
var inputLength = this.getWidth(text)
if (inputLength >= LINE_WIDTH)
return text
val textWithSpaces = this.addSpaces(LiteralText.space(), text)
val addSpaces = this.getWidth(textWithSpaces) <= LINE_WIDTH
var paddingLength = this.getWidth(padding)
val output = LiteralText.builder()
// Using 0 width unicode symbols as padding throws us into an unending loop, replace them with the default padding
if (paddingLength < 1) {
padding = textOf("=")
paddingLength = this.getWidth(padding)
}
// If we only need padding
if (inputLength == 0) {
this.addPadding(padding, output, GenericMath.floor(LINE_WIDTH.toDouble() / paddingLength))
} else {
if (addSpaces) {
text = textWithSpaces
inputLength = this.getWidth(textWithSpaces)
}
val paddingNecessary = LINE_WIDTH - inputLength
val paddingCount = GenericMath.floor(paddingNecessary / paddingLength.toFloat())
// Pick a halfway point
val beforePadding = GenericMath.floor(paddingCount / 2.0)
// Do not use ceil, this prevents floating point errors.
val afterPadding = paddingCount - beforePadding
this.addPadding(padding, output, beforePadding)
output.append(text)
this.addPadding(padding, output, afterPadding)
}
return output.style(text.style()).build()
}
/**
* Adds spaces to both sides of the specified text.
*
*
* Overrides all color and style with the
* text's color and style.
*
* @param spaces The spaces to use
* @param text The text to add to
* @return The text with the added spaces
*/
private fun addSpaces(spaces: Text, text: Text): Text = LiteralText.builder()
.append(spaces)
.append(text)
.append(spaces)
.build()
/**
* Adds the specified padding text to a piece of text being built
* up to a certain amount specified by a count.
*
* @param padding The padding text to use
* @param builder The work in progress text to add to
* @param count The amount of padding to add
*/
private fun addPadding(padding: Text, builder: LiteralTextBuilder, count: Int) {
if (count <= 0)
return
if (padding is LiteralText && padding.children().isEmpty()) {
// Can be added as a single text component
val fullPadding = LiteralText.builder()
.content(padding.content().repeat(count))
.style(padding.style())
.build()
builder.append(fullPadding)
} else {
repeat(count) { builder.append(padding) }
}
}
}
| mit | 4bc5c2da510888219e1844cacb957cc6 | 36.296992 | 122 | 0.605483 | 4.550917 | false | false | false | false |
hubme/WorkHelperApp | app/src/main/java/com/king/app/workhelper/kotlin/Lambda.kt | 1 | 739 | package com.king.app.workhelper.kotlin
/**
*
* @author VanceKing
* @since 19-7-18.
*/
fun main() {
lambda()
}
fun lambda() {
run { println("Hello Kotlin") }
}
fun lambda1() {
{ println("Hello Kotlin") }.invoke()
}
fun lambda2() {
{ println("Hello Kotlin") }()
}
fun lambda3() {
//{参数名: 参数类型 -> Lambda体}()
{ str: String -> println(str) }("VanceKing")
}
fun lambda4() {
{ name: String, age: Int -> println("name = $name, age = $age") }("VanceKing", 18)
}
fun lambd5() {
//Lambda 变量的签名不需要写参数名,只需要写类型
val value1: (String, Int) -> Int
val value2 = { name: String, age: Int ->
println("name = $name, age = $age")
age
}
} | apache-2.0 | 5371805f2fcf55d3ea2a86cce4452690 | 16.15 | 86 | 0.548905 | 2.807377 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RPhoto.kt | 1 | 4215 | @file:JvmName("RichUtils")
@file:JvmMultifileClass
package pyxis.uzuki.live.richutilskt.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.support.annotation.DrawableRes
import android.support.media.ExifInterface
import java.io.IOException
private val options: BitmapFactory.Options by lazy {
val opt = BitmapFactory.Options()
opt.inJustDecodeBounds = true
opt
}
/**
* get Width of Image which given String
*
* @return Width of Image
*/
fun String.getImageWidth(): Int {
BitmapFactory.decodeFile(this, options)
return options.outWidth
}
/**
* get Height of Image which given String
*
* @return Height of Image
*/
fun String.getImageHeight(): Int {
BitmapFactory.decodeFile(this, options)
return options.outHeight
}
/**
* get MimeType of Image which given String
*
* @return MimeType of Image
*/
fun String.getImageMimeType(): String {
BitmapFactory.decodeFile(this, options)
return options.outMimeType ?: ""
}
/**
* get Width of Image which given Drawable Resources
*
* @return Width of Image
*/
fun Context.getImageWidth(@DrawableRes resId: Int): Int {
BitmapFactory.decodeResource(this.resources, resId, options)
return options.outWidth
}
/**
* get Height of Image which given Drawable Resources
*
* @return Height of Image
*/
fun Context.getImageHeight(@DrawableRes resId: Int): Int {
BitmapFactory.decodeResource(this.resources, resId, options)
return options.outHeight
}
/**
* get MimeType of Image which given Drawable Resources
*
* @return MimeType of Image
*/
fun Context.getImageMimeType(@DrawableRes resId: Int): String {
BitmapFactory.decodeResource(this.resources, resId, options)
return options.outMimeType ?: ""
}
/**
* get width of photo from ExifInterface
*
* @param[filePath] real path of photo
* @return width of photo
*/
fun getPhotoWidth(filePath: String?): Int {
var width = 0
var exif: ExifInterface? = null
if (filePath == null)
return width
try {
exif = ExifInterface(filePath)
} catch (e: IOException) {
println("Error: " + e.message)
}
if (exif != null)
width = exif.getAttributeInt(ExifInterface.TAG_IMAGE_WIDTH, -1)
return width
}
/**
* get height of photo from ExifInterface
*
* @param[filePath] real path of photo
* @return height of photo
*/
fun getPhotoHeight(filePath: String?): Int {
var height = 0
var exif: ExifInterface? = null
if (filePath == null)
return height
try {
exif = ExifInterface(filePath)
} catch (e: IOException) {
println("Error: " + e.message)
}
if (exif != null)
height = exif.getAttributeInt(ExifInterface.TAG_IMAGE_LENGTH, -1)
return height
}
/**
* get orientation degree of photo from ExifInterface
*
* @param[filePath] real path of photo
* @return orientation degree of photo
*/
fun getPhotoOrientationDegree(filePath: String?): Int {
var degree = 0
var exif: ExifInterface? = null
if (filePath == null)
return degree
try {
exif = ExifInterface(filePath)
} catch (e: IOException) {
println("Error: " + e.message)
}
if (exif != null) {
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1)
if (orientation != -1) {
degree = when (orientation) {
ExifInterface.ORIENTATION_NORMAL, ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> 0
ExifInterface.ORIENTATION_ROTATE_180, ExifInterface.ORIENTATION_FLIP_VERTICAL -> 180
ExifInterface.ORIENTATION_ROTATE_90, ExifInterface.ORIENTATION_TRANSPOSE -> 90
ExifInterface.ORIENTATION_ROTATE_270, ExifInterface.ORIENTATION_TRANSVERSE -> 270
else -> 0
}
}
}
return degree
}
/**
* rotate bitmap
*
* @param[bitmap] Bitmap which rotate
* @param[degree] rotate amount
*/
fun rotate(bitmap: Bitmap, degree: Int): Bitmap {
val mat = Matrix()
mat.postRotate(degree.toFloat())
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, mat, true)
} | apache-2.0 | faff61548c94530120e176aa80c64336 | 23.091429 | 100 | 0.674496 | 4.206587 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/util/TexLivePackages.kt | 1 | 2914 | package nl.hannahsten.texifyidea.util
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import nl.hannahsten.texifyidea.settings.sdk.LatexSdkUtil
object TexLivePackages {
/**
* List of installed packages.
*/
var packageList: MutableList<String> = mutableListOf()
/**
* Given a package name used in \usepackage or \RequirePackage, find the
* name needed to install from TeX Live. E.g. to be able to use \usepackage{rubikrotation}
* we need to install the rubik package.
*
* In the output
*
* tlmgr: package repository http://ctan.math.utah.edu/ctan/tex-archive/systems/texlive/tlnet (verified)
* rubik:
* texmf-dist/tex/latex/rubik/rubikrotation.sty
*
* we are looking for "rubik". Possibly tex live outputs a "TeX Live 2019 is frozen" message before, so
* we search for the line that starts with tlmgr. Then the name of the package we are
* looking for will be on the next line, if it exists.
*/
fun findTexLiveName(task: Task.Backgroundable, packageName: String, project: Project): String? {
// Find the package name for tlmgr.
task.title = "Searching for $packageName..."
val tlmgrExecutable = LatexSdkUtil.getExecutableName("tlmgr", project)
// Assume that you can not use the bundle name in a \usepackage if it is different from the package name (otherwise this search won't work and we would need to use tlmgr search --global $packageName
val searchResult = "$tlmgrExecutable search --file --global /$packageName.sty".runCommand()
?: return null
// Check if tlmgr needs to be updated first, and do so if needed.
val tlmgrUpdateCommand = "$tlmgrExecutable update --self"
if (searchResult.contains(tlmgrUpdateCommand)) {
task.title = "Updating tlmgr..."
tlmgrUpdateCommand.runCommand()
}
return extractRealPackageNameFromOutput(searchResult)
}
fun extractRealPackageNameFromOutput(output: String): String? {
val tlFrozen = Regex(
"""
TeX Live \d{4} is frozen forever and will no
longer be updated\. This happens in preparation for a new release\.
If you're interested in helping to pretest the new release \(when
pretests are available\), please read https:\/\/tug\.org\/texlive\/pretest\.html\.
Otherwise, just wait, and the new release will be ready in due time\.
""".trimIndent()
)
val lines = tlFrozen.replace(output, "").trim().split('\n')
val tlmgrIndex = lines.indexOfFirst { it.startsWith("tlmgr:") }
return try {
lines[tlmgrIndex + 1].trim().dropLast(1) // Drop the : behind the package name.
}
catch (e: IndexOutOfBoundsException) {
null
}
}
} | mit | 7e97534b08df6c6fbdbdf6019b768b3c | 42.507463 | 206 | 0.650309 | 4.291605 | false | false | false | false |
Finnerale/FileBase | src/main/kotlin/de/leopoldluley/filebase/view/TagView.kt | 1 | 4166 | package de.leopoldluley.filebase.view
import de.leopoldluley.filebase.app.Styles
import de.leopoldluley.filebase.controller.DataCtrl
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.layout.Priority
import tornadofx.*
class TagView : View() {
private val dataCtrl: DataCtrl by inject()
private val tags = SortedFilteredList<String>()
private val search = SimpleStringProperty("")
private val selectedTag = SimpleStringProperty()
private val newName = SimpleStringProperty("")
override val root = vbox {
title = "FileBase - " + messages["manageTagsTitle"]
padding = Insets(10.0)
spacing = 10.0
hbox {
spacing = 10.0
textfield(search) {
hgrow = Priority.ALWAYS
promptText = messages["search"]
}
button(messages["back"]) {
action {
replaceWith(MainView::class, ViewTransition.Slide(300.millis, ViewTransition.Direction.LEFT))
}
}
}
listview<String> {
vgrow = Priority.ALWAYS
items = tags
bindSelected(selectedTag)
}
hbox {
spacing = 10.0
alignment = Pos.CENTER
enableWhen(selectedTag.isNotEmpty)
hbox {
spacing = 3.0
hgrow = Priority.ALWAYS
textfield(newName) {
selectedTag.onChange { newName.value = it }
hgrow = Priority.ALWAYS
}
button(messages["save"]) {
newName.onChange {
this.isDisable = it.isNullOrBlank()
|| it!!.trim().contains(' ')
|| it == selectedTag.value
|| tags.items.contains(it)
}
action {
updateTag()
}
}
}
button(messages["delete"]) {
action {
openInternalBuilderWindow("", closeButton = false, modal = true) {
vbox {
padding = Insets(10.0)
spacing = 10.0
label(messages["deleteDialogTitle"].replace("#name", selectedTag.value)) { addClass(Styles.entryTitle) }
label(messages["deleteDialogTagText"])
hbox {
spacing = 10.0
button(messages["cancel"]) {
action {
close()
}
}
button(messages["deleteDialogButton"].replace("#name", selectedTag.value)) {
action {
deleteTag()
}
}
}
}
}
}
}
}
}
private fun updateTag() {
val old = selectedTag.value
val new = newName.value.trim()
if (dataCtrl.updateTag(old, new)) {
tags.replaceAll {
if (it == old) {
new
} else {
it
}
}
selectedTag.value = new
}
}
private fun deleteTag() {
if (dataCtrl.deleteTag(selectedTag.value)) {
tags.remove(selectedTag.value)
selectedTag.value = ""
close()
}
}
override fun onDock() {
tags.clear()
tags.addAll(dataCtrl.getTags())
tags.filterWhen(search) { search, tag -> tag.contains(search) }
}
}
| mit | c727b1d88bece2ff943ce9e28ca41246 | 31.596774 | 132 | 0.418147 | 5.810321 | false | false | false | false |
NextFaze/dev-fun | devfun/src/main/java/com/nextfaze/devfun/core/Composite.kt | 1 | 1285 | package com.nextfaze.devfun.core
import java.util.ArrayDeque
/**
* Use by providers to facilitate user provided types [T] to the composting provider.
*
* In general additions are checked in reverse order. i.e. newest added are checked first.
*
* Users should remove their type when disposed of or out of scope.
*/
interface Composite<T : Any> : Iterable<T> {
/** Add to this [Composite]. */
operator fun plusAssign(other: T)
/** Remove from this [Composite] */
operator fun minusAssign(other: T)
}
internal abstract class Composited<T : Any> : Composite<T> {
private var components = ArrayDeque<T>()
internal fun clear() {
components = ArrayDeque()
}
override fun iterator(): Iterator<T> = components.descendingIterator()
override operator fun plusAssign(other: T) {
if (components.peekLast() == other) return
components = components.clone().apply {
remove(other)
add(other)
}
onComponentsChanged()
}
override operator fun minusAssign(other: T) {
val mutated = components.clone()
if (mutated.remove(other)) {
components = mutated
onComponentsChanged()
}
}
internal open fun onComponentsChanged() = Unit
}
| apache-2.0 | 446745153e826a626e4bc925bc2e0d9a | 25.770833 | 90 | 0.642023 | 4.385666 | false | false | false | false |
sungmin-park/Klask | src/main/kotlin/com/klask/client.kt | 1 | 1399 | package com.klask.client
import com.klask.Klask
import com.klask.RequestMethod
import com.klask.Response
import javax.servlet.http.Cookie
public class Client(val app: Klask) {
var cookies = array<Cookie>()
public fun get(url: String): Response {
return request(url, RequestMethod.GET)
}
public fun post(url: String, data: List<Pair<String, String>> = listOf()): Response {
return request(url, RequestMethod.POST, data)
}
fun request(url: String, method: RequestMethod, data: List<Pair<String, String>> = listOf()): Response {
val request = ClientHttpServletRequest(
url, cookies, method,
data.map { it.first }
.toSet()
.map { key -> key to data.filter { it.first == key }.map { it.second } }
.toMap()
)
val response = ClientHttpServletResponse()
return app.processRequest(request, response).let {
cookies = response.cookies.copyToArray()
it
}
}
fun context(url: String, method: RequestMethod = RequestMethod.GET, context: () -> Unit) {
val request = ClientHttpServletRequest(url, cookies, method, mapOf())
val response = ClientHttpServletResponse()
app.processRequestContext<Unit>(request, response) { a, b, c ->
context()
}
}
}
| mit | d52f33e646286c6531088906237e123f | 33.121951 | 108 | 0.598284 | 4.455414 | false | false | false | false |
jonalmeida/focus-android | app/src/main/java/org/mozilla/focus/session/SessionManagerExtension.kt | 2 | 1715 | /* 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.session
import mozilla.components.browser.session.Session
import mozilla.components.browser.session.SessionManager
import org.mozilla.focus.ext.savedWebViewState
import org.mozilla.focus.utils.AppConstants
import org.mozilla.focus.web.GeckoWebViewProvider
import org.mozilla.geckoview.GeckoSession
fun SessionManager.removeAndCloseSession(session: Session) {
if (AppConstants.isGeckoBuild) {
val geckoSession =
session.savedWebViewState?.getParcelable<GeckoSession>(GeckoWebViewProvider.GECKO_SESSION)
if (geckoSession != null && geckoSession.isOpen) {
geckoSession.close()
}
}
remove(session)
}
fun SessionManager.removeAndCloseAllSessions() {
if (AppConstants.isGeckoBuild) {
sessions.forEach { session ->
val geckoSession =
session.savedWebViewState?.getParcelable<GeckoSession>(GeckoWebViewProvider.GECKO_SESSION)
if (geckoSession != null && geckoSession.isOpen) {
geckoSession.close()
}
}
}
removeSessions()
}
fun SessionManager.removeAllAndCloseAllSessions() {
if (AppConstants.isGeckoBuild) {
all.forEach { session ->
val geckoSession =
session.savedWebViewState?.getParcelable<GeckoSession>(GeckoWebViewProvider.GECKO_SESSION)
if (geckoSession != null && geckoSession.isOpen) {
geckoSession.close()
}
}
}
removeAll()
}
| mpl-2.0 | 6e7e27472290ab125a92d5327742ff26 | 34 | 106 | 0.68105 | 4.40874 | false | false | false | false |
ohtomi/gradle-init | kotlin/src/main/kotlin/com/example/PluginTask.kt | 1 | 541 | package com.example
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
open class PluginTask() : DefaultTask() {
var filePath: String = ""
var fileContent: String = ""
@TaskAction
fun greet() {
val hello = project.property("hello") as PluginConfiguration
println("Hello world! value=${hello.value}")
val file = project.file(filePath)
file.parentFile.mkdirs()
file.writeText("content: ${fileContent}")
println("file created. path: ${file}")
}
}
| mit | 38df52b555ddf6f5954c3975b5d61310 | 22.521739 | 68 | 0.643253 | 4.259843 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/test/java/net/nemerosa/ontrack/extension/git/GitCommitSearchExtensionIT.kt | 1 | 4602 | package net.nemerosa.ontrack.extension.git
import net.nemerosa.ontrack.model.structure.SearchIndexService
import net.nemerosa.ontrack.model.structure.SearchRequest
import net.nemerosa.ontrack.model.structure.SearchService
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.TestPropertySource
import kotlin.test.assertNotNull
import kotlin.test.assertNull
/**
* Testing the search on Git commits.
*/
class GitCommitSearchExtensionIT : AbstractGitSearchTestSupport() {
@Autowired
protected lateinit var gitCommitSearchExtension: GitCommitSearchExtension
@Test
fun `Looking for a commit on a project when Git repo is not indexed yet`() {
createRepo {
commits(10)
} and { repo, commits ->
project {
gitProject(repo, sync = false)
// Re-indexes the commits
searchIndexService.index(gitCommitSearchExtension)
// Looks for every commit, they must not be found
commits.forEach { (_, commit) ->
val results = searchService.paginatedSearch(SearchRequest(commit)).items
val title = "$name $commit"
val result = results.find { it.title == title }
assertNull(result, "No commit is indexed yet")
}
}
}
}
@Test
fun `Looking for a commit on a project when Git repo has been removed`() {
createRepo {
commits(10)
} and { repo, commits ->
project {
gitProject(repo, sync = false)
// Destroys the repository
repo.close()
// Re-indexes the commits
searchIndexService.index(gitCommitSearchExtension)
// Looks for every commit, they must not be found
commits.forEach { (_, commit) ->
val results = searchService.paginatedSearch(SearchRequest(commit)).items
val title = "$name $commit"
val result = results.find { it.title == title }
assertNull(result, "No commit is indexed yet")
}
}
}
}
@Test
fun `Looking for a commit on a project`() {
createRepo {
commits(10)
} and { repo, commits ->
project {
gitProject(repo)
// Re-indexes the commits
searchIndexService.index(gitCommitSearchExtension)
// Looks for every commit
commits.forEach { (_, commit) ->
val results = searchService.paginatedSearch(SearchRequest(commit)).items
val title = "$name $commit"
val result = results.find { it.title == title }
assertNotNull(result)
}
}
}
}
@Test
fun `Looking for a commit on a project using its short ID`() {
createRepo {
commits(10, shortId = true)
} and { repo, commits ->
project {
gitProject(repo)
// Re-indexes the commits
searchIndexService.index(gitCommitSearchExtension)
// Looks for every commit
commits.forEach { (_, commit) ->
val results = searchService.paginatedSearch(SearchRequest(commit)).items
val title = "$name $commit"
val result = results.find { it.title.startsWith(title) }
assertNotNull(result)
}
}
}
}
@Test
fun `Looking for a commit on a project after its has been deleted`() {
createRepo {
commits(10)
} and { repo, commits ->
val project = project {
gitProject(repo)
}
asAdmin {
// Re-indexes the commits
searchIndexService.index(gitCommitSearchExtension)
// Deletes the project
structureService.deleteProject(project.id)
}
// Looks for every commit
commits.forEach { (_, commit) ->
val results = searchService.paginatedSearch(SearchRequest(commit)).items
val title = "${project.name} $commit"
val result = results.find { it.title == title }
assertNull(result, "Cannot find commit after project is deleted")
}
}
}
} | mit | 21bf42ca9c960da7f62de18753db0f00 | 35.531746 | 92 | 0.543242 | 5.388759 | false | true | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/PluginRegistration.kt | 1 | 4644 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers
import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.VirtualFileManager
import com.thomas.needham.neurophidea.Constants.INITIALISATION_ACTION
import com.thomas.needham.neurophidea.Constants.MENU_ACTION
import com.thomas.needham.neurophidea.Constants.WINDOW_MENU_ACTION
import com.thomas.needham.neurophidea.actions.InitialisationAction
import com.thomas.needham.neurophidea.core.FileSaveListener
import com.thomas.needham.neurophidea.core.NeurophProjectManagerListener
import com.thomas.needham.neurophidea.designer.editor.nnet.NnetDecompiler
import com.thomas.needham.neurophidea.designer.editor.tset.TsetDecompiler
import com.thomas.needham.neurophidea.designer.psi.nnet.NnetFileType
import com.thomas.needham.neurophidea.designer.psi.snnet.SnnetFileType
import com.thomas.needham.neurophidea.designer.psi.tset.TsetFileType
/**
* Created by Thomas Needham on 25/05/2016.
*/
class PluginRegistration : ApplicationComponent {
val actionManager = ActionManager.getInstance()
val init = InitialisationAction()
val fileManager: FileTypeManagerImpl = FileTypeManagerImpl.getInstance() as FileTypeManagerImpl
val virtualFileManager = VirtualFileManager.getInstance()
val fileSaveListener = FileSaveListener()
val projectListener = NeurophProjectManagerListener()
val nnetDecompiler = NnetDecompiler()
val tsetDecompiler = TsetDecompiler()
val nnetFileType = NnetFileType()
val snnetFileType = SnnetFileType()
val tsetFileType = TsetFileType()
companion object Data {
@JvmStatic
var projectClosing = false
}
override fun getComponentName(): String {
return "Neuroph For Intellij"
}
override fun disposeComponent() {
println("Plugin Unloaded: ${this.componentName}")
virtualFileManager.removeVirtualFileListener(fileSaveListener)
actionManager.unregisterAction(MENU_ACTION)
actionManager.unregisterAction(INITIALISATION_ACTION)
BinaryFileTypeDecompilers.INSTANCE.removeExplicitExtension(fileManager.getFileTypeByExtension("nnet"), nnetDecompiler)
BinaryFileTypeDecompilers.INSTANCE.removeExplicitExtension(fileManager.getFileTypeByExtension("tset"), tsetDecompiler)
fileManager.unregisterFileType(nnetFileType)
fileManager.unregisterFileType(snnetFileType)
fileManager.unregisterFileType(tsetFileType)
ProjectManager.getInstance().removeProjectManagerListener(projectListener)
}
override fun initComponent() {
println("Plugin Loaded: ${this.componentName}")
fileManager.registerFileType(nnetFileType, *arrayOf("nnet"))
fileManager.registerFileType(snnetFileType, *arrayOf("snnet"))
fileManager.registerFileType(tsetFileType, *arrayOf("tset"))
BinaryFileTypeDecompilers.INSTANCE.addExplicitExtension(fileManager.getFileTypeByExtension("nnet"), nnetDecompiler)
BinaryFileTypeDecompilers.INSTANCE.addExplicitExtension(fileManager.getFileTypeByExtension("tset"), tsetDecompiler)
virtualFileManager.addVirtualFileListener(fileSaveListener)
actionManager.registerAction(INITIALISATION_ACTION, init)
val defaultActionGroup: DefaultActionGroup? = actionManager.getAction(WINDOW_MENU_ACTION) as DefaultActionGroup?
defaultActionGroup?.addSeparator()
ProjectManager.getInstance().addProjectManagerListener(projectListener)
}
} | mit | 25832f6e0fe980b7a865a5bdbcb8ebae | 47.385417 | 120 | 0.833549 | 4.530732 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/feature/customView/PreviousIconAnimator.kt | 1 | 1573 | package be.florien.anyflow.feature.customView
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import be.florien.anyflow.R
class PreviousIconAnimator(context: Context) : IconAnimator(context) {
private var enabledColor = ContextCompat.getColor(context, R.color.iconInApp)
private var disabledColor = ContextCompat.getColor(context, R.color.disabled)
override fun getStartAnimation(newState: Int): AnimatedVectorDrawableCompat? = null
override fun getEndAnimation(newState: Int): AnimatedVectorDrawableCompat? = when (newState) {
oldState -> null
STATE_PREVIOUS_NO_PREVIOUS -> getAnimatedIcon(R.drawable.ic_start_to_previous)
STATE_PREVIOUS_START -> getAnimatedIcon(R.drawable.ic_previous_to_start)
else -> getAnimatedIcon(R.drawable.ic_start_to_previous)
}
override fun getFixedIcon(newState: Int): Drawable {
iconColor = if (newState == STATE_PREVIOUS_NO_PREVIOUS) {
disabledColor
} else {
enabledColor
}
return when (newState) {
STATE_PREVIOUS_NO_PREVIOUS -> getIcon(R.drawable.ic_previous)
STATE_PREVIOUS_PREVIOUS -> getIcon(R.drawable.ic_previous)
else -> getIcon(R.drawable.ic_start)
}
}
companion object {
const val STATE_PREVIOUS_NO_PREVIOUS = 0
const val STATE_PREVIOUS_PREVIOUS = 1
const val STATE_PREVIOUS_START = 2
}
} | gpl-3.0 | e3b1fc0d345ddded84aee49c5d6a6bf1 | 37.390244 | 98 | 0.706294 | 4.443503 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/model/ThreadInfo.kt | 1 | 2923 | package com.emogoth.android.phone.mimi.model
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
class ThreadInfo : Parcelable {
@Expose
var threadId: Long = 0
@Expose
var boardName: String = ""
@Expose
var boardTitle: String = ""
@Expose
var watched = false
@Expose
var refreshTimestamp: Long = 0
constructor() {}
constructor(threadId: Long, boardName: String, boardTitle: String, watched: Boolean) {
this.threadId = threadId
this.boardName = boardName
this.boardTitle = boardTitle
this.watched = watched
refreshTimestamp = 0
}
constructor(threadId: Long, boardName: String, boardTitle: String, watched: Boolean, lastRefreshTime: Long) {
this.threadId = threadId
this.boardName = boardName
this.boardTitle = boardTitle
this.watched = watched
this.refreshTimestamp = lastRefreshTime
}
constructor(threadId: Long, boardName: String, lastRefreshTime: Long, watched: Boolean) {
this.threadId = threadId
this.boardName = boardName
boardTitle = ""
this.watched = watched
refreshTimestamp = lastRefreshTime
}
fun setTimestamp(timestamp: Long) {
refreshTimestamp = timestamp
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || (this as Any).javaClass != o.javaClass) return false
val that = o as ThreadInfo
if (threadId == 0L) return false
if (boardName != that.boardName) return false
return if (threadId != that.threadId) false else true
}
override fun hashCode(): Int {
var result = threadId
result = 31 * result + boardName.hashCode()
return result.toInt()
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(threadId)
dest.writeString(boardName)
dest.writeString(boardTitle)
dest.writeByte(if (watched) 1.toByte() else 0.toByte())
dest.writeLong(refreshTimestamp)
}
constructor(input: Parcel) : this(
threadId = input.readLong(),
boardName = input.readString() ?: "",
boardTitle = input.readString() ?: "",
watched = input.readByte().toInt() != 0,
lastRefreshTime = input.readLong())
companion object {
const val BUNDLE_KEY = "thread_bundle"
@JvmField
val CREATOR: Parcelable.Creator<ThreadInfo> = object : Parcelable.Creator<ThreadInfo> {
override fun createFromParcel(source: Parcel): ThreadInfo? {
return ThreadInfo(source)
}
override fun newArray(size: Int): Array<ThreadInfo?> {
return arrayOfNulls(size)
}
}
}
} | apache-2.0 | 757e97465273d9284b6740a17aa292dc | 27.950495 | 113 | 0.615464 | 4.752846 | false | false | false | false |
255BITS/hypr | app/src/androidTest/java/hypr/a255bits/com/hypr/Main/GeneratorTest.kt | 1 | 2683 | package hypr.hypergan.com.hypr.Main
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.test.suitebuilder.annotation.LargeTest
import hypr.hypergan.com.hypr.GeneratorLoader.EasyGeneratorLoader
import hypr.hypergan.com.hypr.Util.ImageSaver
import hypr.hypergan.com.hypr.Util.JsonReader
import hypr.hypergan.com.hypr.Util.toBitmap
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.BufferedInputStream
import java.io.InputStream
@LargeTest
@RunWith(AndroidJUnit4::class)
open class GeneratorTest {
@get:Rule open val mActivityTestRule = ActivityTestRule(MainActivity::class.java)
private val IMAGES_TO_TRANSFER_FOLDERNAME = "beforeImages"
val gen = JsonReader().getGeneratorsFromJson(mActivityTestRule.activity)
val generator = EasyGeneratorLoader(mActivityTestRule.activity)
@Test
fun generatorTest() {
mActivityTestRule.activity.requestPermissions(arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
val listOfImages = mActivityTestRule.activity.applicationContext.resources.assets.list(IMAGES_TO_TRANSFER_FOLDERNAME)
writeTransformedBitmapsToAndroidGallery(listOfImages)
}
private fun writeTransformedBitmapsToAndroidGallery(listOfImages: Array<out String>?) {
listOfImages?.forEach { filename ->
val imageFile = openFile("$IMAGES_TO_TRANSFER_FOLDERNAME/$filename")
val image = getBitmapFromFile(imageFile)
val encodedBitmap = encodeImage(image)
writeImageToFileOnAndroidDeviceGallery(encodedBitmap, mActivityTestRule.activity.applicationContext)
}
}
private fun openFile(filenamePath: String): InputStream? {
return mActivityTestRule.activity.applicationContext.resources.assets.open(filenamePath)
}
private fun getBitmapFromFile(imageFile: InputStream?): Bitmap? {
val imageReaderFromFile = BufferedInputStream(imageFile)
return BitmapFactory.decodeStream(imageReaderFromFile)
}
private fun encodeImage(image: Bitmap?): Bitmap {
generator.load(mActivityTestRule.activity.assets)
val scaled = Bitmap.createScaledBitmap(image, 128, 128, false)
val imageFace = generator.sampleImageWithoutImage(index)
return imageFace.toBitmap(generator.width, generator.height)
}
private fun writeImageToFileOnAndroidDeviceGallery(encodedBitmap: Bitmap, context: Context) {
ImageSaver().saveImageToInternalStorage(encodedBitmap, context, "after")
}
}
| mit | f60a69955ed0115c8066f559709ba3b7 | 39.044776 | 125 | 0.773015 | 4.649913 | false | true | false | false |
Andr3Carvalh0/mGBA | app/src/main/java/io/mgba/settings/categories/SettingsCategoriesActivity.kt | 1 | 1991 | package io.mgba.settings.categories
import androidx.recyclerview.widget.LinearLayoutManager
import io.mgba.R
import io.mgba.base.BaseActivity
import io.mgba.base.BaseAdapter
import io.mgba.data.settings.Settings
import io.mgba.settings.categories.recyclerView.SettingsAdapter
import kotlinx.android.synthetic.main.activity_settings.*
class SettingsCategoriesActivity : BaseActivity<SettingsCategoriesViewModel>(){
private val settings: List<Settings> = listOf(Settings(getString(R.string.settings_audio), R.drawable.ic_audiotrack),
Settings(getString(R.string.settings_video), R.drawable.ic_screen),
Settings(getString(R.string.settings_emulation), R.drawable.ic_gamepad),
Settings(getString(R.string.settings_bios), R.drawable.ic_memory),
Settings(getString(R.string.settings_paths), R.drawable.ic_folder),
Settings(getString(R.string.settings_customization), R.drawable.ic_themes))
override fun getLayout(): Int = R.layout.activity_settings
override fun getViewModel(): Class<SettingsCategoriesViewModel> = SettingsCategoriesViewModel::class.java
override fun onCreate() {
setupToolbar()
setupRecyclerView()
}
private fun setupRecyclerView() {
list.setHasFixedSize(true)
list.layoutManager = LinearLayoutManager(this)
list.adapter = SettingsAdapter(this) { s -> vm.onClick(s) }
(list.adapter as BaseAdapter<Settings>).data = ArrayList(settings)
}
private fun setupToolbar() {
supportActionBar?.let {
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| mpl-2.0 | fd0ff713f43f7106075f612a0e28a03b | 43.244444 | 125 | 0.649925 | 5.158031 | false | false | false | false |
apixandru/intellij-community | platform/script-debugger/backend/src/debugger/values/ValueManager.kt | 6 | 1386 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.values
import org.jetbrains.concurrency.Obsolescent
import java.util.concurrent.atomic.AtomicInteger
/**
* The main idea of this class - don't create value for remote value handle if already exists. So,
* implementation of this class keep map of value to remote value handle.
* Also, this class maintains cache timestamp.
* Currently WIP implementation doesn't keep such map due to protocol issue. But V8 does.
*/
abstract class ValueManager() : Obsolescent {
private val cacheStamp = AtomicInteger()
@Volatile private var obsolete = false
open fun clearCaches() {
cacheStamp.incrementAndGet()
}
fun getCacheStamp() = cacheStamp.get()
override final fun isObsolete() = obsolete
fun markObsolete() {
obsolete = true
}
} | apache-2.0 | 1ce75275a3f95f58f248246a1ddd3d92 | 31.255814 | 98 | 0.744589 | 4.291022 | false | false | false | false |
Ribesg/anko | preview/intentions/src/org/jetbrains/anko/idea/intentions/FindViewByIdIntention.kt | 5 | 2104 | package org.jetbrains.anko.idea.intentions
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
class FindViewByIdIntention : AnkoIntention<KtExpression>(
KtExpression::class.java,
"Simplify findViewById() with Anko"
) {
override fun isApplicable(element: KtExpression, caretOffset: Int): Boolean {
fun PsiElement?.requireFindViewByIdCall() = requireCall(FIND_VIEW_BY_ID, 1) {
val resolvedCall = getResolvedCall(analyze())
isValueParameterTypeOf(0, resolvedCall, "kotlin.Int")
&& isReceiverParameterTypeOf(resolvedCall, FqNames.ACTIVITY_FQNAME, FqNames.VIEW_FQNAME)
}
return element.require<KtBinaryExpressionWithTypeRHS>() {
operation.require<KtSimpleNameExpression>("as")
&& (left.requireFindViewByIdCall() || left.require<KtDotQualifiedExpression> {
selector.requireFindViewByIdCall()
})
}
}
override fun replaceWith(element: KtExpression, psiFactory: KtPsiFactory): NewElement? {
fun KtCallExpression.createElement(type: String, receiver: String? = null): NewElement {
val id = valueArguments[0].text
val receiverWithDot = if (receiver == null) "" else "$receiver."
val newExpression = psiFactory.createExpression("${receiverWithDot}find<$type>($id)")
return NewElement(newExpression, "find")
}
element.require<KtBinaryExpressionWithTypeRHS>() {
val type = right?.text ?: return null
left.requireCall(FIND_VIEW_BY_ID) {
return createElement(type)
}
left.require<KtDotQualifiedExpression> {
selector.requireCall(FIND_VIEW_BY_ID) {
return createElement(type, receiver?.text)
}
}
}
return null
}
private companion object {
val FIND_VIEW_BY_ID = "findViewById"
}
}
| apache-2.0 | 0eeada991abf6f390dbcdcbcdfb16ba2 | 37.962963 | 108 | 0.642586 | 4.962264 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/task/twitter/GetStatusesTask.kt | 1 | 12315 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.task.twitter
import android.accounts.AccountManager
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import org.mariotaku.abstask.library.TaskStarter
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.toLongOr
import org.mariotaku.library.objectcursor.ObjectCursor
import de.vanita5.microblog.library.MicroBlogException
import de.vanita5.microblog.library.twitter.model.Paging
import org.mariotaku.sqliteqb.library.Columns
import org.mariotaku.sqliteqb.library.Expression
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.TwittnukerConstants.LOGTAG
import de.vanita5.twittnuker.TwittnukerConstants.QUERY_PARAM_NOTIFY_CHANGE
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.annotation.FilterScope
import de.vanita5.twittnuker.constant.loadItemLimitKey
import de.vanita5.twittnuker.exception.AccountNotFoundException
import de.vanita5.twittnuker.extension.model.*
import de.vanita5.twittnuker.extension.model.api.applyLoadLimit
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.ParcelableStatus
import de.vanita5.twittnuker.model.RefreshTaskParam
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.event.GetStatusesTaskEvent
import de.vanita5.twittnuker.model.task.GetTimelineResult
import de.vanita5.twittnuker.model.util.AccountUtils
import de.vanita5.twittnuker.provider.TwidereDataStore.AccountSupportColumns
import de.vanita5.twittnuker.provider.TwidereDataStore.Statuses
import de.vanita5.twittnuker.task.BaseAbstractTask
import de.vanita5.twittnuker.task.cache.CacheTimelineResultTask
import de.vanita5.twittnuker.util.DataStoreUtils
import de.vanita5.twittnuker.util.DebugLog
import de.vanita5.twittnuker.util.ErrorInfoStore
import de.vanita5.twittnuker.util.UriUtils
import de.vanita5.twittnuker.util.content.ContentResolverUtils
import de.vanita5.twittnuker.util.sync.SyncTaskRunner
import de.vanita5.twittnuker.util.sync.TimelineSyncManager
abstract class GetStatusesTask(
context: Context
) : BaseAbstractTask<RefreshTaskParam, List<Pair<GetTimelineResult<ParcelableStatus>?, Exception?>>,
(Boolean) -> Unit>(context) {
protected abstract val contentUri: Uri
@FilterScope
protected abstract val filterScopes: Int
protected abstract val errorInfoKey: String
override fun doLongOperation(param: RefreshTaskParam): List<Pair<GetTimelineResult<ParcelableStatus>?, Exception?>> {
if (param.shouldAbort) return emptyList()
val accountKeys = param.accountKeys.takeIf { it.isNotEmpty() } ?: return emptyList()
val loadItemLimit = preferences[loadItemLimitKey]
val result = accountKeys.mapIndexed { i, accountKey ->
try {
val account = AccountUtils.getAccountDetails(AccountManager.get(context),
accountKey, true) ?: throw AccountNotFoundException()
val paging = Paging()
paging.applyLoadLimit(account, loadItemLimit)
val maxId = param.getMaxId(i)
val sinceId = param.getSinceId(i)
val maxSortId = param.getMaxSortId(i)
val sinceSortId = param.getSinceSortId(i)
if (maxId != null) {
paging.maxId(maxId)
}
if (sinceId != null) {
val sinceIdLong = sinceId.toLongOr(-1L)
//TODO handle non-twitter case
if (sinceIdLong != -1L) {
paging.sinceId((sinceIdLong - 1).toString())
} else {
paging.sinceId(sinceId)
}
if (maxId == null) {
paging.setLatestResults(true)
}
}
val timelineResult = getStatuses(account, paging)
val storeResult = storeStatus(account, timelineResult.data, sinceId, maxId,
sinceSortId, maxSortId, loadItemLimit, false)
// TODO cache related data and preload
errorInfoStore.remove(errorInfoKey, accountKey.id)
if (storeResult != 0) {
throw GetTimelineException(storeResult)
}
return@mapIndexed Pair(timelineResult, null)
} catch (e: MicroBlogException) {
DebugLog.w(LOGTAG, tr = e)
if (e.isCausedByNetworkIssue) {
errorInfoStore[errorInfoKey, accountKey.id] = ErrorInfoStore.CODE_NETWORK_ERROR
} else if (e.statusCode == 401) {
// Unauthorized
}
return@mapIndexed Pair(null, e)
} catch (e: GetTimelineException) {
return@mapIndexed Pair(null, e)
}
}
val manager = timelineSyncManagerFactory.get()
if (manager != null && syncPreferences.isSyncEnabled(SyncTaskRunner.SYNC_TYPE_TIMELINE_POSITIONS)) {
if (param.isBackground) {
syncFetchReadPosition(manager, accountKeys)
}
}
return result
}
override fun afterExecute(handler: ((Boolean) -> Unit)?, results: List<Pair<GetTimelineResult<ParcelableStatus>?, Exception?>>) {
context.contentResolver.notifyChange(contentUri, null)
val exception = results.firstOrNull { it.second != null }?.second
bus.post(GetStatusesTaskEvent(contentUri, false, exception))
cacheItems(context, results)
handler?.invoke(true)
}
override fun beforeExecute() {
bus.post(GetStatusesTaskEvent(contentUri, true, null))
}
@Throws(MicroBlogException::class)
protected abstract fun getStatuses(account: AccountDetails, paging: Paging): GetTimelineResult<ParcelableStatus>
protected abstract fun syncFetchReadPosition(manager: TimelineSyncManager, accountKeys: Array<UserKey>)
private fun storeStatus(account: AccountDetails, statuses: List<ParcelableStatus>,
sinceId: String?, maxId: String?, sinceSortId: Long, maxSortId: Long,
loadItemLimit: Int, notify: Boolean): Int {
val accountKey = account.key
val uri = contentUri
val writeUri = UriUtils.appendQueryParameters(uri, QUERY_PARAM_NOTIFY_CHANGE, notify)
val resolver = context.contentResolver
val noItemsBefore = DataStoreUtils.getStatusCount(context, uri, accountKey) <= 0
val values = arrayOfNulls<ContentValues>(statuses.size)
val statusIds = arrayOfNulls<String>(statuses.size)
var minIdx = -1
var minPositionKey: Long = -1
var hasIntersection = false
if (!statuses.isEmpty()) {
val firstSortId = statuses.first().sort_id
val lastSortId = statuses.last().sort_id
// Get id diff of first and last item
val sortDiff = firstSortId - lastSortId
val creator = ObjectCursor.valuesCreatorFrom(ParcelableStatus::class.java)
statuses.forEachIndexed { i, status ->
status.position_key = getPositionKey(status.timestamp, status.sort_id, lastSortId,
sortDiff, i, statuses.size)
status.inserted_date = System.currentTimeMillis()
mediaPreloader.preloadStatus(status)
values[i] = creator.create(status)
if (minIdx == -1 || status < statuses[minIdx]) {
minIdx = i
minPositionKey = status.position_key
}
if (sinceId != null && status.sort_id <= sinceSortId) {
hasIntersection = true
}
statusIds[i] = status.id
}
}
// Delete all rows conflicting before new data inserted.
val accountWhere = Expression.equalsArgs(AccountSupportColumns.ACCOUNT_KEY)
val statusWhere = Expression.inArgs(Columns.Column(Statuses.ID),
statusIds.size)
val deleteWhere = Expression.and(accountWhere, statusWhere).sql
val deleteWhereArgs = arrayOf(accountKey.toString(), *statusIds)
var olderCount = -1
if (minPositionKey > 0) {
olderCount = DataStoreUtils.getStatusesCount(context, preferences, uri, null,
Statuses.POSITION_KEY, minPositionKey, false, arrayOf(accountKey),
filterScopes)
}
val rowsDeleted = resolver.delete(writeUri, deleteWhere, deleteWhereArgs)
// Insert a gap.
val deletedOldGap = rowsDeleted > 0 && maxId in statusIds
val noRowsDeleted = rowsDeleted == 0
// Why loadItemLimit / 2? because it will not acting strange in most cases
val insertGap = minIdx != -1 && olderCount > 0 && (noRowsDeleted || deletedOldGap)
&& !noItemsBefore && !hasIntersection && statuses.size > loadItemLimit / 2
if (insertGap) {
values[minIdx]!!.put(Statuses.IS_GAP, true)
}
// Insert previously fetched items.
ContentResolverUtils.bulkInsert(resolver, writeUri, values)
// Remove gap flag
if (maxId != null && sinceId == null) {
if (statuses.isNotEmpty()) {
// Only remove when actual result returned, otherwise it seems that gap is too old to load
val noGapValues = ContentValues()
noGapValues.put(Statuses.IS_GAP, false)
val noGapWhere = Expression.and(Expression.equalsArgs(Statuses.ACCOUNT_KEY),
Expression.equalsArgs(Statuses.ID)).sql
val noGapWhereArgs = arrayOf(accountKey.toString(), maxId)
resolver.update(writeUri, noGapValues, noGapWhere, noGapWhereArgs)
} else {
return ERROR_LOAD_GAP
}
}
return 0
}
class GetTimelineException(val code: Int) : Exception() {
fun getToastMessage(context: Context): String {
when (code) {
ERROR_LOAD_GAP -> return context.getString(R.string.message_toast_unable_to_load_more_statuses)
}
return context.getString(R.string.error_unknown_error)
}
}
companion object {
const val ERROR_LOAD_GAP = 1
fun getPositionKey(timestamp: Long, sortId: Long, lastSortId: Long, sortDiff: Long,
position: Int, count: Int): Long {
if (sortDiff == 0L) return timestamp
val extraValue: Int
if (sortDiff > 0) {
// descent sorted by time
extraValue = count - 1 - position
} else {
// ascent sorted by time
extraValue = position
}
return timestamp + (sortId - lastSortId) * (499 - count) / sortDiff + extraValue.toLong()
}
fun cacheItems(context: Context, results: List<Pair<GetTimelineResult<*>?, Exception?>>) {
results.forEach { (result, _) ->
if (result == null) return@forEach
val account = result.account
val task = CacheTimelineResultTask(context, result,
account.type == AccountType.STATUSNET || account.isOfficial(context))
TaskStarter.execute(task)
}
}
}
} | gpl-3.0 | 5bb155d7469946fce6a168d25706cdc8 | 44.279412 | 133 | 0.643849 | 4.65068 | false | false | false | false |
Cleverdesk/cleverdesk | src/test/java/PluginExample.kt | 1 | 1867 | /**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import net.cleverdesk.cleverdesk.UIRequest
import net.cleverdesk.cleverdesk.User
import net.cleverdesk.cleverdesk.plugin.Page
import net.cleverdesk.cleverdesk.plugin.Plugin
import net.cleverdesk.cleverdesk.plugin.PluginDescription
import net.cleverdesk.cleverdesk.plugin.PluginInfo
import net.cleverdesk.cleverdesk.ui.UI
import net.cleverdesk.cleverdesk.ui.form.InputField
/**
* Created by jonas on 04.05.16.
*/
@PluginInfo(author = "Jonas", name = "Test-Plugin", description = "A cool Test-Plugin with many features! ")
class PluginExample : Plugin() {
override fun enable() {
description = object : PluginDescription {
override val name: String = "cool_plugin"
override val description: String = "Cool!"
override val author: String = "Jonas"
}
pages.add(CoolPage())
}
override fun disable() {
}
}
class CoolPage() : Page {
override val name: String = "coolpage"
override fun response(user: User?, request: UIRequest): UI {
val ui: UI = UI()
val vorname: InputField = InputField()
vorname.max = 20
vorname.identifer = "vorname"
ui.addComponent(vorname)
return ui
}
} | gpl-3.0 | e10641df6715137c223772f8cdaf3280 | 31.77193 | 108 | 0.698982 | 4.085339 | false | false | false | false |
Popalay/Cardme | presentation/src/main/kotlin/com/popalay/cardme/utils/recycler/StableIdDiffListCallback.kt | 1 | 357 | package com.popalay.cardme.utils.recycler
import com.popalay.cardme.data.models.StableId
class StableIdDiffListCallback<in T : StableId> : DiffObservableList.Callback<T> {
override fun areItemsTheSame(oldItem: T, newItem: T) = oldItem.stableId == newItem.stableId
override fun areContentsTheSame(oldItem: T, newItem: T) = oldItem == newItem
}
| apache-2.0 | 7a21f60f5855ab9a0c9258e5875da946 | 28.75 | 95 | 0.767507 | 3.880435 | false | false | false | false |
alvarlagerlof/temadagar-android | app/src/main/java/com/alvarlagerlof/temadagarapp/Extensions/OtherExtensions.kt | 1 | 1757 | package com.alvarlagerlof.koda.Extensions
import android.content.Context
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.util.TypedValue
import android.view.Menu
import android.view.View
import android.view.inputmethod.InputMethodManager
/**
* Created by alvar on 2017-06-10.
*/
// Shared preferences
inline fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) {
val editor = edit()
editor.func()
editor.apply()
}
// Menu
fun Menu.show(menuId: Int) {
val item = this.findItem(menuId)
if (item != null) {
item.isVisible = true
}
}
fun Menu.hide(menuId: Int) {
val item = this.findItem(menuId)
if (item != null) {
item.isVisible = false
}
}
// Keyboard
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun View.showKeyboard() {
this.requestFocus()
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
// Connectivity
fun Context.isConnected(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return cm.activeNetworkInfo != null && cm.activeNetworkInfo.isConnected
}
// Int
fun Int.constrain(min: Int, max: Int) = if (this <= min) min else if (this >= max) max else this
fun Int.even() = this % 2 == 0
fun Int.odd() = this % 2 != 0
// Float
fun Int.dp(context: Context) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), context.resources.displayMetrics).toInt() | mit | c531ea8d7c3bcfd242aec076e82e19d0 | 23.760563 | 143 | 0.730222 | 4.029817 | false | false | false | false |
exponent/exponent | packages/expo-media-library/android/src/main/java/expo/modules/medialibrary/assets/GetAssetsQuery.kt | 2 | 4421 | package expo.modules.medialibrary.assets
import android.provider.MediaStore
import expo.modules.core.utilities.ifNull
import expo.modules.core.utilities.takeIfInstanceOf
import expo.modules.medialibrary.GET_ASSETS_DEFAULT_LIMIT
import expo.modules.medialibrary.MediaType
import expo.modules.medialibrary.SortBy
import java.util.ArrayList
data class GetAssetsQuery(
val selection: String,
val order: String,
val limit: Int,
val offset: Int,
)
@Throws(IllegalArgumentException::class)
internal fun getQueryFromOptions(input: Map<String, Any?>): GetAssetsQuery {
val limit = input["first"].takeIfInstanceOf<Number>()?.toInt() ?: GET_ASSETS_DEFAULT_LIMIT
// to maintain compatibility with iOS field `after` is string
val offset = input["after"]
.takeIfInstanceOf<String>()
?.runCatching { toInt() } // NumberFormatException
?.getOrNull()
?: 0
val selection = createSelectionString(input)
val sortBy = input["sortBy"] as? List<*>
val order = if (sortBy != null && sortBy.isNotEmpty()) {
convertOrderDescriptors(sortBy)
} else {
MediaStore.Images.Media.DEFAULT_SORT_ORDER
}
return GetAssetsQuery(selection, order, limit, offset)
}
@Throws(IllegalArgumentException::class)
private fun createSelectionString(input: Map<String, Any?>): String {
val selectionBuilder = StringBuilder()
if (input.containsKey("album")) {
selectionBuilder.append("${MediaStore.Images.Media.BUCKET_ID} = ${input["album"]}")
selectionBuilder.append(" AND ")
}
val mediaType = input["mediaType"] as? List<*>
if (mediaType != null && !mediaType.contains(MediaType.ALL.apiName)) {
val mediaTypeInts = mediaType.map { parseMediaType(it.toString()) }
selectionBuilder.append(
"${MediaStore.Files.FileColumns.MEDIA_TYPE} IN (${mediaTypeInts.joinToString(separator = ",")})"
)
} else {
selectionBuilder.append(
"${MediaStore.Files.FileColumns.MEDIA_TYPE} != ${MediaStore.Files.FileColumns.MEDIA_TYPE_NONE}"
)
}
input["createdAfter"].takeIfInstanceOf<Number>()?.let {
selectionBuilder.append(" AND ${MediaStore.Images.Media.DATE_TAKEN} > ${it.toLong()}")
}
input["createdBefore"].takeIfInstanceOf<Number>()?.let {
selectionBuilder.append(" AND ${MediaStore.Images.Media.DATE_TAKEN} < ${it.toLong()}")
}
return selectionBuilder.toString()
}
/**
* Converts media type constant string to media column defined in [MediaType]
* @throws IllegalArgumentException if the value is not defined there
*/
@Throws(IllegalArgumentException::class)
private fun parseMediaType(mediaTypeName: String): Int =
MediaType.fromApiName(mediaTypeName)?.mediaColumn.ifNull {
val errorMessage = "MediaType $mediaTypeName is not supported!"
throw IllegalArgumentException(errorMessage)
}
/**
* Converts sorting key string to column value defined in [SortBy]
* @throws IllegalArgumentException if the value is not defined there
*/
@Throws(IllegalArgumentException::class)
fun parseSortByKey(key: String): String =
SortBy.fromKeyName(key)?.mediaColumnName.ifNull {
val errorMessage = "SortBy key $key is not supported!"
throw IllegalArgumentException(errorMessage)
}
/**
* Converts orderBy options to a value accepted as `order` parameter of
* [android.content.ContentResolver.query] method
*
* Expected input: List of either:
* - `String` representing order key, defined in [MediaLibraryConstants.SORT_KEYS]
* - Two-element tuple (defined as `List[String, Boolean]`), where:
* - first element represents order key, defined in [MediaLibraryConstants.SORT_KEYS]
* - second element: `true` --> ASC, `false` --> DESC order
*
* @throws IllegalArgumentException when conversion fails
*/
@Throws(IllegalArgumentException::class)
fun convertOrderDescriptors(orderDescriptor: List<*>): String {
val results = ArrayList<String>(20)
for (item in orderDescriptor) {
when (item) {
is String -> {
val key = parseSortByKey(item)
results.add("$key DESC")
}
is List<*> -> {
require(item.size == 2) { "Array sortBy in assetsOptions has invalid layout." }
val key = parseSortByKey(item[0] as String)
val order = item[1] as Boolean
results.add(key + if (order) " ASC" else " DESC")
}
else -> throw IllegalArgumentException("Array sortBy in assetsOptions contains invalid items.")
}
}
return results.joinToString(separator = ",")
}
| bsd-3-clause | 837a8e5381f690515668d981d975a1eb | 34.368 | 102 | 0.715901 | 4.218511 | false | false | false | false |
AndroidX/androidx | wear/watchface/watchface/src/main/java/androidx/wear/watchface/control/InteractiveWatchFaceImpl.kt | 3 | 9081 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface.control
import android.os.Build
import android.os.Bundle
import android.support.wearable.watchface.accessibility.ContentDescriptionLabel
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.wear.watchface.utility.TraceEvent
import androidx.wear.watchface.TapEvent
import androidx.wear.watchface.WatchFaceService
import androidx.wear.watchface.control.data.WatchFaceRenderParams
import androidx.wear.watchface.data.IdAndComplicationDataWireFormat
import androidx.wear.watchface.data.IdAndComplicationStateWireFormat
import androidx.wear.watchface.data.WatchFaceOverlayStyleWireFormat
import androidx.wear.watchface.data.WatchUiState
import androidx.wear.watchface.runBlockingWithTracing
import androidx.wear.watchface.style.data.UserStyleSchemaWireFormat
import androidx.wear.watchface.style.data.UserStyleWireFormat
import kotlinx.coroutines.launch
import java.time.Instant
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
/** An interactive watch face instance with SysUI and WCS facing interfaces.*/
internal class InteractiveWatchFaceImpl(
internal var engine: WatchFaceService.EngineWrapper?,
internal var instanceId: String
) : IInteractiveWatchFace.Stub() {
private companion object {
private const val TAG = "InteractiveWatchFaceImpl"
}
private val uiThreadCoroutineScope = engine!!.uiThreadCoroutineScope
private val systemTimeProvider = engine!!.systemTimeProvider
override fun getApiVersion() = IInteractiveWatchFace.API_VERSION
override fun sendTouchEvent(xPos: Int, yPos: Int, tapType: Int) {
val engineCopy = engine ?: return
WatchFaceService.awaitDeferredWatchFaceImplThenRunOnUiThreadBlocking(
engineCopy,
"InteractiveWatchFaceImpl.sendTouchEvent"
) { watchFaceImpl ->
watchFaceImpl.onTapCommand(
tapType,
TapEvent(
xPos,
yPos,
Instant.ofEpochMilli(systemTimeProvider.getSystemTimeMillis())
)
)
}
}
override fun unused18() {}
override fun unused20() {}
override fun addWatchFaceListener(listener: IWatchfaceListener) {
engine?.addWatchFaceListener(listener) ?: Log.w(
TAG,
"addWatchFaceListener ignored due to null engine"
)
}
override fun removeWatchFaceListener(listener: IWatchfaceListener) {
engine?.removeWatchFaceListener(listener) ?: Log.w(
TAG,
"removeWatchFaceListener ignored due to null engine"
)
}
override fun getWatchFaceOverlayStyle(): WatchFaceOverlayStyleWireFormat? =
WatchFaceService.awaitDeferredWatchFaceThenRunOnUiThread(
engine,
"InteractiveWatchFaceImpl.getWatchFaceOverlayStyle"
) { WatchFaceOverlayStyleWireFormat(
it.overlayStyle.backgroundColor,
it.overlayStyle.foregroundColor
)
}
override fun getContentDescriptionLabels(): Array<ContentDescriptionLabel>? {
return WatchFaceService.awaitDeferredWatchFaceImplThenRunOnUiThreadBlocking(
engine,
"InteractiveWatchFaceImpl.getContentDescriptionLabels"
) { engine?.contentDescriptionLabels }
}
@RequiresApi(Build.VERSION_CODES.O_MR1)
override fun renderWatchFaceToBitmap(params: WatchFaceRenderParams): Bundle? {
return WatchFaceService.awaitDeferredWatchFaceImplThenRunOnUiThreadBlocking(
engine,
"InteractiveWatchFaceImpl.renderWatchFaceToBitmap"
) { watchFaceImpl -> watchFaceImpl.renderWatchFaceToBitmap(params) }
}
override fun getPreviewReferenceTimeMillis(): Long {
return WatchFaceService.awaitDeferredWatchFaceImplThenRunOnUiThreadBlocking(
engine,
"InteractiveWatchFaceImpl.getPreviewReferenceTimeMillis"
) { watchFaceImpl -> watchFaceImpl.previewReferenceInstant.toEpochMilli() } ?: 0
}
override fun setWatchUiState(watchUiState: WatchUiState) {
WatchFaceService.awaitDeferredWatchFaceImplThenRunOnUiThreadBlocking(
engine,
"InteractiveWatchFaceImpl.setWatchUiState"
) {
engine?.let {
it.setWatchUiState(watchUiState, fromSysUi = true)
} ?: Log.d(TAG, "setWatchUiState ignored due to null engine id $instanceId")
}
}
override fun getInstanceId(): String = instanceId
override fun ambientTickUpdate() {
uiThreadCoroutineScope.runBlockingWithTracing(
"InteractiveWatchFaceImpl.ambientTickUpdate"
) {
engine?.ambientTickUpdate()
?: Log.d(TAG, "ambientTickUpdate ignored due to null engine id $instanceId")
}
}
override fun release(): Unit = TraceEvent("InteractiveWatchFaceImpl.release").use {
// Note this is a one way method called on a binder thread, so it shouldn't matter if we
// block.
runBlocking {
try {
withContext(uiThreadCoroutineScope.coroutineContext) {
engine?.let {
it.deferredWatchFaceImpl.await()
}
InteractiveInstanceManager.releaseInstance(instanceId)
}
} catch (e: Exception) {
// deferredWatchFaceImpl may have completed with an exception. This will
// have already been reported so we can ignore it.
}
}
}
override fun updateComplicationData(
complicationDatumWireFormats: MutableList<IdAndComplicationDataWireFormat>
): Unit = TraceEvent("InteractiveWatchFaceImpl.updateComplicationData").use {
if ("user" != Build.TYPE) {
Log.d(TAG, "updateComplicationData " + complicationDatumWireFormats.joinToString())
}
engine?.setComplicationDataList(complicationDatumWireFormats)
?: Log.d(TAG, "updateComplicationData ignored due to null engine id $instanceId")
}
override fun updateWatchfaceInstance(
newInstanceId: String,
userStyle: UserStyleWireFormat
) {
/**
* This is blocking to ensure ordering with respect to any subsequent [getInstanceId] and
* [getPreviewReferenceTimeMillis] calls.
*/
uiThreadCoroutineScope.runBlockingWithTracing(
"InteractiveWatchFaceImpl.updateWatchfaceInstance"
) {
if (instanceId != newInstanceId) {
engine?.updateInstance(newInstanceId)
instanceId = newInstanceId
}
engine?.setUserStyle(userStyle)
}
}
override fun getComplicationDetails(): List<IdAndComplicationStateWireFormat>? {
val engineCopy = engine
return WatchFaceService.awaitDeferredEarlyInitDetailsThenRunOnThread(
engineCopy,
"InteractiveWatchFaceImpl.getComplicationDetails",
WatchFaceService.Companion.ExecutionThread.UI
) { it.complicationSlotsManager.getComplicationsState(engineCopy!!.screenBounds) }
}
override fun getUserStyleSchema(): UserStyleSchemaWireFormat? {
return WatchFaceService.awaitDeferredEarlyInitDetailsThenRunOnThread(
engine,
"InteractiveWatchFaceImpl.getUserStyleSchema",
WatchFaceService.Companion.ExecutionThread.CURRENT
) { it.userStyleRepository.schema.toWireFormat() }
}
override fun bringAttentionToComplication(id: Int) {
// Unsupported.
}
override fun addWatchfaceReadyListener(listener: IWatchfaceReadyListener) {
uiThreadCoroutineScope.launch {
engine?.addWatchfaceReadyListener(listener)
?: Log.d(TAG, "addWatchfaceReadyListener ignored due to null engine id $instanceId")
}
}
fun onDestroy() {
// Note this is almost certainly called on the ui thread, from release() above.
runBlocking {
try {
withContext(uiThreadCoroutineScope.coroutineContext) {
Log.d(TAG, "onDestroy id $instanceId")
engine?.onEngineDetached()
engine = null
}
} catch (e: Exception) {
Log.w(TAG, "onDestroy failed to call onEngineDetached", e)
}
}
}
}
| apache-2.0 | 3fb29798e02435bc2f1f5e021af9ec19 | 37.974249 | 100 | 0.67911 | 5.209983 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/TeamOwnerConnection.kt | 1 | 797 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Connection
/**
* Connection data.
*
* @param displayName The team owner's display name.
* @param invitesRemaining The total number of team member invites remaining.
* @param total The total number of owners on this connection.
*/
@JsonClass(generateAdapter = true)
data class TeamOwnerConnection(
@Json(name = "options")
override val options: List<String>? = null,
@Json(name = "uri")
override val uri: String? = null,
@Json(name = "display_name")
val displayName: String? = null,
@Json(name = "invites_remaining")
val invitesRemaining: Int? = null,
@Json(name = "total")
val total: Int? = null
) : Connection
| mit | 23c88f80cf37fa4bf83d04d7f047816a | 23.90625 | 77 | 0.700125 | 3.795238 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/actions/runAnything/wasmpack/WasmPackRunAnythingProvider.kt | 2 | 2280 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions.runAnything.wasmpack
import com.intellij.execution.Executor
import com.intellij.ide.actions.runAnything.items.RunAnythingItem
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import org.rust.cargo.project.model.CargoProject
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.runconfig.getAppropriateCargoProject
import org.rust.cargo.runconfig.wasmpack.util.WasmPackCommandCompletionProvider
import org.rust.cargo.toolchain.WasmPackCommandLine
import org.rust.cargo.util.RsCommandCompletionProvider
import org.rust.ide.actions.runAnything.RsRunAnythingProvider
import org.rust.ide.icons.RsIcons
import java.nio.file.Path
import javax.swing.Icon
class WasmPackRunAnythingProvider : RsRunAnythingProvider() {
override fun getMainListItem(dataContext: DataContext, value: String): RunAnythingItem =
RunAnythingWasmPackItem(getCommand(value), getIcon(value))
override fun run(executor: Executor, command: String, params: List<String>, workingDirectory: Path, cargoProject: CargoProject) {
WasmPackCommandLine(command, workingDirectory, params).run(cargoProject, executor = executor)
}
override fun getCompletionProvider(project: Project, dataContext: DataContext): RsCommandCompletionProvider =
WasmPackCommandCompletionProvider(project.cargoProjects) {
getAppropriateCargoProject(dataContext)?.workspace
}
override fun getCommand(value: String): String = value
override fun getIcon(value: String): Icon = RsIcons.WASM_PACK
@Suppress("DialogTitleCapitalization")
override fun getCompletionGroupTitle(): String = "wasm-pack commands"
@Suppress("DialogTitleCapitalization")
override fun getHelpGroupTitle(): String = "wasm-pack"
override fun getHelpCommandPlaceholder(): String = "wasm-pack <subcommand> <args...>"
override fun getHelpCommand(): String = HELP_COMMAND
override fun getHelpIcon(): Icon = RsIcons.WASM_PACK
override fun getHelpDescription(): String = "Runs wasm-pack command"
companion object {
const val HELP_COMMAND = "wasm-pack"
}
}
| mit | ba5d0c5ec465d09242f71da4b5137b00 | 38.310345 | 133 | 0.77807 | 4.606061 | false | false | false | false |
androidx/androidx | compose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/ComposeIdlingResource.android.kt | 3 | 6218 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test.junit4
import android.view.View
import androidx.compose.runtime.Recomposer
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.platform.ViewRootForTest
import androidx.compose.ui.test.IdlingResource
import kotlin.math.max
/**
* Provides an idle check to be registered into Espresso.
*
* This makes sure that Espresso is able to wait for any pending changes in Compose. This
* resource is automatically registered when any compose testing APIs are used including
* [createAndroidComposeRule].
*/
internal class ComposeIdlingResource(
private val composeRootRegistry: ComposeRootRegistry,
private val clock: MainTestClockImpl,
private val mainRecomposer: Recomposer
) : IdlingResource {
private var hadAwaitersOnMainClock = false
private var hadSnapshotChanges = false
private var hadRecomposerChanges = false
private var hadPendingSetContent = false
private var hadPendingMeasureLayout = false
override val isIdleNow: Boolean
get() {
fun shouldPumpTime(): Boolean {
hadAwaitersOnMainClock = clock.hasAwaiters
hadSnapshotChanges = Snapshot.current.hasPendingChanges()
hadRecomposerChanges = mainRecomposer.hasPendingWork
val needsRecompose = hadAwaitersOnMainClock || hadSnapshotChanges ||
hadRecomposerChanges
return clock.autoAdvance && needsRecompose
}
var i = 0
while (i < 100 && shouldPumpTime()) {
clock.advanceTimeByFrame()
++i
}
// pending set content needs all created compose roots,
// because by definition they will not be in resumed state
hadPendingSetContent =
composeRootRegistry.getCreatedComposeRoots().any { it.isBusyAttaching }
val composeRoots = composeRootRegistry.getRegisteredComposeRoots()
hadPendingMeasureLayout = composeRoots.any { it.shouldWaitForMeasureAndLayout }
return !shouldPumpTime() &&
!hadPendingSetContent &&
!hadPendingMeasureLayout
}
override fun getDiagnosticMessageIfBusy(): String? {
val wasBusy = hadSnapshotChanges || hadRecomposerChanges || hadAwaitersOnMainClock ||
hadPendingSetContent || hadPendingMeasureLayout
if (!wasBusy) {
return null
}
val busyReasons = mutableListOf<String>()
val busyRecomposing = hadSnapshotChanges || hadRecomposerChanges || hadAwaitersOnMainClock
if (busyRecomposing) {
busyReasons.add("pending recompositions")
}
if (hadPendingSetContent) {
busyReasons.add("pending setContent")
}
if (hadPendingMeasureLayout) {
busyReasons.add("pending measure/layout")
}
var message = "${javaClass.simpleName} is busy due to ${busyReasons.joinToString(", ")}.\n"
if (busyRecomposing) {
message += "- Note: Timeout on pending recomposition means that there are most likely" +
" infinite re-compositions happening in the tested code.\n"
message += "- Debug: hadRecomposerChanges = $hadRecomposerChanges, "
message += "hadSnapshotChanges = $hadSnapshotChanges, "
message += "hadAwaitersOnMainClock = $hadAwaitersOnMainClock"
}
return message
}
}
private val ViewRootForTest.isBusyAttaching: Boolean
get() {
// If the rootView has a parent, it is the ViewRootImpl, which is set in
// windowManager.addView(). If the rootView doesn't have a parent, the view hasn't been
// attached to a window yet, or is removed again.
return view.rootView.parent != null && !view.isAttachedToWindow
}
/**
* Whether or not we should wait until this root has done a measure/layout pass. Not necessarily
* the same as if the root has a pending measure/layout pass, e.g. if the pending measure/layout
* pass will never happen because the containing View is GONE anyway.
*/
internal val ViewRootForTest.shouldWaitForMeasureAndLayout: Boolean
get() {
// Should wait if: 1) there actually is a pending measure/layout
return hasPendingMeasureOrLayout &&
// 2) the containing View is not GONE
!view.isEffectivelyGone &&
// 3) the containing View is not INVISIBLE while trying to do the
// measure/layout pass by only invalidating the containing View
!(view.isEffectivelyInvisible && !view.isLayoutRequested)
}
private val View.isEffectivelyGone: Boolean
get() {
return effectiveVisibility == View.GONE
}
private val View.isEffectivelyInvisible: Boolean
get() {
return effectiveVisibility == View.INVISIBLE
}
/**
* Return the effective visibility of the View, which accounts for the visibility of ancestors.
* If the view or any of its ancestors is GONE, this view is GONE. Otherwise, if this view or any
* of its ancestors is INVISIBLE, this view is INVISIBLE. Otherwise, this view is VISIBLE.
*/
private val View.effectiveVisibility: Int
get() {
// Visibility values increase as they express "less visible", so the effective visibility
// is the maximum of all visibility values from this view to the root.
return when (visibility) {
View.GONE -> View.GONE
else -> max(visibility, (parent as? View)?.effectiveVisibility ?: View.VISIBLE)
}
}
| apache-2.0 | 8b89a8f4ba35bed93a81c510c548a235 | 39.116129 | 100 | 0.677549 | 4.835148 | false | true | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/nbt/lang/format/NbttLanguageCodeStyleSettingsProvider.kt | 1 | 4399 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.format
import com.demonwav.mcdev.nbt.lang.NbttLanguage
import com.intellij.application.options.IndentOptionsEditor
import com.intellij.application.options.SmartIndentOptionsEditor
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizable
import com.intellij.psi.codeStyle.CodeStyleSettingsCustomizableOptions
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider
import org.intellij.lang.annotations.Language
class NbttLanguageCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun getCodeSample(settingsType: SettingsType) = SAMPLE
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) {
when (settingsType) {
SettingsType.WRAPPING_AND_BRACES_SETTINGS -> {
consumer.showStandardOptions("RIGHT_MARGIN")
consumer.showCustomOption(
NbttCodeStyleSettings::class.java,
"LIST_WRAPPING",
"Wrap list items",
CodeStyleSettingsCustomizableOptions.getInstance().WRAPPING_BRACES,
arrayOf(
"Do not wrap",
"Wrap as needed",
"Wrap always",
),
intArrayOf(
CommonCodeStyleSettings.DO_NOT_WRAP,
CommonCodeStyleSettings.WRAP_AS_NEEDED,
CommonCodeStyleSettings.WRAP_ALWAYS,
)
)
consumer.showCustomOption(
NbttCodeStyleSettings::class.java,
"ARRAY_WRAPPING",
"Wrap array items",
CodeStyleSettingsCustomizableOptions.getInstance().WRAPPING_BRACES,
arrayOf(
"Do not wrap",
"Wrap as needed",
"Wrap always",
),
intArrayOf(
CommonCodeStyleSettings.DO_NOT_WRAP,
CommonCodeStyleSettings.WRAP_AS_NEEDED,
CommonCodeStyleSettings.WRAP_ALWAYS,
)
)
}
SettingsType.SPACING_SETTINGS -> {
consumer.showStandardOptions(
"SPACE_WITHIN_BRACKETS",
"SPACE_WITHIN_PARENTHESES",
"SPACE_BEFORE_COMMA",
"SPACE_AFTER_COMMA"
)
consumer.showCustomOption(
NbttCodeStyleSettings::class.java,
"SPACE_BEFORE_COLON",
"Space before colon",
CodeStyleSettingsCustomizableOptions.getInstance().SPACES_AROUND_OPERATORS
)
consumer.showCustomOption(
NbttCodeStyleSettings::class.java,
"SPACE_AFTER_COLON",
"Space after colon",
CodeStyleSettingsCustomizableOptions.getInstance().SPACES_AROUND_OPERATORS
)
consumer.renameStandardOption("SPACE_WITHIN_BRACKETS", "List brackets")
consumer.renameStandardOption("SPACE_WITHIN_PARENTHESES", "Array parentheses")
}
else -> {
}
}
}
override fun getIndentOptionsEditor(): IndentOptionsEditor = SmartIndentOptionsEditor()
override fun getLanguage() = NbttLanguage
override fun customizeDefaults(
commonSettings: CommonCodeStyleSettings,
indentOptions: CommonCodeStyleSettings.IndentOptions
) {
commonSettings.RIGHT_MARGIN = 150
indentOptions.USE_TAB_CHARACTER = true
indentOptions.TAB_SIZE = 4
indentOptions.INDENT_SIZE = indentOptions.TAB_SIZE
indentOptions.CONTINUATION_INDENT_SIZE = indentOptions.INDENT_SIZE
}
}
@Language("NBTT")
private const val SAMPLE = """
"": {
list: [
{
"created-on": 1264099775885L
"name": "Compound tag #0"
},
{
primitive list: [ 0B, 1B, false, true, 14B, ]
array: ints(1, 3, 4)
number: 1264099775885L
},
]
}
"""
| mit | 9e91b8206a7312aecf3987f1bc6339aa | 34.764228 | 105 | 0.576722 | 5.526382 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/AnimeActivity.kt | 1 | 4765 | package me.proxer.app.anime
import android.app.Activity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.core.app.ShareCompat
import androidx.fragment.app.commitNow
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.media.MediaActivity
import me.proxer.app.util.extension.getSafeStringExtra
import me.proxer.app.util.extension.startActivity
import me.proxer.app.util.extension.toEpisodeAppString
import me.proxer.library.enums.AnimeLanguage
import me.proxer.library.enums.Category
import me.proxer.library.util.ProxerUrls
import me.proxer.library.util.ProxerUtils
/**
* @author Ruben Gees
*/
class AnimeActivity : DrawerActivity() {
companion object {
private const val ID_EXTRA = "id"
private const val EPISODE_EXTRA = "episode"
private const val LANGUAGE_EXTRA = "language"
private const val NAME_EXTRA = "name"
private const val EPISODE_AMOUNT_EXTRA = "episode_amount"
fun navigateTo(
context: Activity,
id: String,
episode: Int,
language: AnimeLanguage,
name: String? = null,
episodeAmount: Int? = null
) {
context.startActivity<AnimeActivity>(
ID_EXTRA to id,
EPISODE_EXTRA to episode,
LANGUAGE_EXTRA to language,
NAME_EXTRA to name,
EPISODE_AMOUNT_EXTRA to episodeAmount
)
}
}
val id: String
get() = when (intent.hasExtra(ID_EXTRA)) {
true -> intent.getSafeStringExtra(ID_EXTRA)
false -> intent?.data?.pathSegments?.getOrNull(1) ?: "-1"
}
var episode: Int
get() = when (intent.hasExtra(EPISODE_EXTRA)) {
true -> intent.getIntExtra(EPISODE_EXTRA, 1)
false -> intent?.data?.pathSegments?.getOrNull(2)?.toIntOrNull() ?: 1
}
set(value) {
intent.putExtra(EPISODE_EXTRA, value)
updateTitle()
}
val language: AnimeLanguage
get() = when (intent.hasExtra(LANGUAGE_EXTRA)) {
true -> intent.getSerializableExtra(LANGUAGE_EXTRA) as AnimeLanguage
false -> intent?.data?.pathSegments?.getOrNull(3)?.let { ProxerUtils.toApiEnum<AnimeLanguage>(it) }
?: AnimeLanguage.ENGLISH_SUB
}
var name: String?
get() = intent.getStringExtra(NAME_EXTRA)
set(value) {
intent.putExtra(NAME_EXTRA, value)
updateTitle()
}
var episodeAmount: Int?
get() = when (intent.hasExtra(EPISODE_AMOUNT_EXTRA)) {
true -> intent.getIntExtra(EPISODE_AMOUNT_EXTRA, 1)
false -> null
}
set(value) {
if (value == null) {
intent.removeExtra(EPISODE_AMOUNT_EXTRA)
} else {
intent.putExtra(EPISODE_AMOUNT_EXTRA, value)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar()
updateTitle()
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, AnimeFragment.newInstance())
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> name?.let {
ShareCompat.IntentBuilder
.from(this)
.setText(getString(R.string.share_anime, episode, it, ProxerUrls.animeWeb(id, episode, language)))
.setType("text/plain")
.setChooserTitle(getString(R.string.share_title))
.startChooser()
}
}
return super.onOptionsItemSelected(item)
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.clicks()
.autoDisposable(this.scope())
.subscribe {
name?.let {
MediaActivity.navigateTo(this, id, it, Category.ANIME)
}
}
}
private fun updateTitle() {
title = name
supportActionBar?.subtitle = Category.ANIME.toEpisodeAppString(this, episode)
}
}
| gpl-3.0 | 9746911101d2450d072122e0d97678fe | 31.195946 | 118 | 0.607975 | 4.666993 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-db/src/main/java/org/ccci/gto/android/common/db/Dao.kt | 1 | 4866 | package org.ccci.gto.android.common.db
import android.annotation.SuppressLint
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import androidx.annotation.RestrictTo
import androidx.annotation.WorkerThread
import java.util.concurrent.Executor
interface Dao {
@Deprecated("Since v3.11.0, the Dao no longer provides a backgroundExecutor, use coroutines instead.")
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP, RestrictTo.Scope.SUBCLASSES)
val backgroundExecutor: Executor
// region Table Metadata
fun getFullProjection(clazz: Class<*>): Array<String>
// endregion Table Metadata
// region Queries
// region Read-Only
@WorkerThread
fun <T : Any> find(clazz: Class<T>, vararg key: Any): T?
@WorkerThread
fun <T : Any> get(query: Query<T>): List<T>
@WorkerThread
fun getCursor(clazz: Class<*>) = getCursor(Query.select(clazz))
@WorkerThread
fun getCursor(clazz: Class<*>, whereClause: String?, whereBindValues: Array<String>?, orderBy: String?) =
getCursor(Query.select(clazz).where(whereClause, *whereBindValues.orEmpty()).orderBy(orderBy))
@WorkerThread
fun getCursor(query: Query<*>): Cursor
// endregion Read-Only
// region Read-Write
@WorkerThread
fun <T : Any> insert(obj: T) = insert(obj, SQLiteDatabase.CONFLICT_NONE)
@WorkerThread
fun <T : Any> insert(obj: T, conflictAlgorithm: Int): Long
@WorkerThread
fun <T : Any> update(obj: T, where: Expression?, vararg projection: String): Int =
update(obj, where, SQLiteDatabase.CONFLICT_NONE, *projection)
@WorkerThread
fun <T : Any> update(obj: T, vararg projection: String) = update(obj, SQLiteDatabase.CONFLICT_NONE, *projection)
@WorkerThread
fun <T : Any> update(obj: T, conflictAlgorithm: Int, vararg projection: String): Int
/**
* This method updates all objects that match the where Expression based on the provided sample object and projection.
*
* @param obj a sample object that is used to find the type and generate the values being set on other objects.
* @param where a where clause that restricts which objects get updated. If this is null all objects are updated.
* @param conflictAlgorithm the conflict algorithm to use when updating the database
* @param projection the fields to update in this call
* @return the number of rows affected
*/
@WorkerThread
fun <T : Any> update(obj: T, where: Expression?, conflictAlgorithm: Int, vararg projection: String): Int
@WorkerThread
fun updateOrInsert(obj: Any, vararg projection: String) =
updateOrInsert(obj, SQLiteDatabase.CONFLICT_NONE, *projection)
@WorkerThread
fun updateOrInsert(obj: Any, conflictAlgorithm: Int, vararg projection: String)
@WorkerThread
fun delete(obj: Any)
/**
* Delete all objects that match the provided where clause. Sending a null where clause will delete all objects.
*
* @param clazz The Class of the objects to be deleted
* @param where An expression describing which objects to delete. Null indicates all objects should be deleted.
*/
@WorkerThread
fun delete(clazz: Class<*>, where: Expression?)
// endregion Read-Write
// endregion Queries
@WorkerThread
fun <T> transaction(exclusive: Boolean = true, body: () -> T): T
// region Data Invalidation
fun interface InvalidationCallback {
@WorkerThread
fun onInvalidate(clazz: Class<*>)
}
fun registerInvalidationCallback(callback: InvalidationCallback)
fun unregisterInvalidationCallback(callback: InvalidationCallback)
// endregion Data Invalidation
// region Services
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
val services: MutableMap<Class<*>, Any>
@Suppress("UNCHECKED_CAST")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP, RestrictTo.Scope.SUBCLASSES)
fun <T : Any> getService(clazz: Class<T>) = synchronized(services) { services[clazz] } as T?
@Suppress("UNCHECKED_CAST")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP, RestrictTo.Scope.SUBCLASSES)
fun <T : Any> getService(clazz: Class<T>, defaultValue: () -> T) =
synchronized(services) { services.getOrPut(clazz, defaultValue) } as T
// endregion Services
}
inline fun <reified T : Any> Dao.find(vararg key: Any) = find(T::class.java, *key)
inline fun <T : Any> Query<T>.get(dao: Dao) = dao.get(this)
inline fun Query<*>.getCursor(dao: Dao) = dao.getCursor(this)
@SuppressLint("RestrictedApi")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <reified T : Any> Dao.getService() = getService(T::class.java)
@SuppressLint("RestrictedApi")
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
inline fun <reified T : Any> Dao.getService(noinline defaultValue: () -> T) = getService(T::class.java, defaultValue)
| mit | b481da8e1741a1a092c838f1efbbffad | 37.928 | 122 | 0.71044 | 4.268421 | false | false | false | false |
MarcelBlanck/AoC2016 | src/main/kotlin/day1/StreetGridWalker.kt | 1 | 6150 | /*
* MIT License
*
* Copyright (c) 2017 Marcel Blanck
*
* 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 day1
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
enum class Turn {
NONE, LEFT, RIGHT
}
data class IntersectionCoordinates (
var heading: Direction = Direction.NORTH,
var x: Int = 0,
var y: Int = 0) {
fun turnLeft() {
heading = when (heading) {
Direction.NORTH -> Direction.WEST
Direction.WEST -> Direction.SOUTH
Direction.SOUTH -> Direction.EAST
Direction.EAST -> Direction.NORTH
}
}
fun turnRight() {
heading = when (heading) {
Direction.NORTH -> Direction.EAST
Direction.EAST -> Direction.SOUTH
Direction.SOUTH -> Direction.WEST
Direction.WEST -> Direction.NORTH
}
}
fun moveForward(distance: Int) {
when (heading) {
Direction.NORTH -> y += distance
Direction.EAST -> x += distance
Direction.SOUTH -> y -= distance
Direction.WEST -> x -= distance
}
}
fun isAtSamePosition(other: IntersectionCoordinates) : Boolean = other.x == x && other.y == y
}
data class MoveDirection(
var turn: Turn = Turn.LEFT,
var distance: Int = 1) {
companion object {
private val regexp = "([LR])(\\d*)".toRegex()
}
fun fromString(moveDirection: String) {
if (moveDirection.isBlank()) {
turn = Turn.NONE
distance = 0
} else {
val regexpResult = regexp.matchEntire(moveDirection)
if (regexpResult == null || regexpResult.groups.count() < 2) {
throw IllegalArgumentException("Malformed direction input: '$moveDirection'")
}
turn = when (regexpResult.groups[1]?.value) {
"L" -> Turn.LEFT
"R" -> Turn.RIGHT
else -> throw IllegalArgumentException("Malformed direction input: '$moveDirection'")
}
if (regexpResult.groups[2]?.value.isNullOrBlank()) {
distance = 1
} else {
distance = regexpResult.groups[2]?.value?.toInt() ?: 1
}
}
}
fun toSingleStepInstructions() : List<MoveDirection>{
val singleStepDirections: MutableList<MoveDirection> = ArrayList()
(0 until distance).mapTo(singleStepDirections) {
MoveDirection(turn = if(it == 0) turn else Turn.NONE)
}
return singleStepDirections
}
}
class StreetGridWalker {
fun getDistanceToLastDirection(directions: List<String>) : Int {
val moveDirections = transformToMoveDirections(directions)
return getDistanceForDirections(IntersectionCoordinates(), moveDirections)
}
fun getDistanceToFirstIntersection(directions: List<String>) : Int {
val moveDirections = transformToMoveDirections(directions, singleStep = true)
return getDistanceForDirections(IntersectionCoordinates(), moveDirections, stopOnIntersection = true)
}
private tailrec fun getDistanceForDirections(
currentIntersection: IntersectionCoordinates,
moveDirections: List<MoveDirection>,
stopOnIntersection: Boolean = false,
visitedIntersections: MutableList<IntersectionCoordinates> = ArrayList()) : Int =
if(moveDirections.isEmpty()) {
abs(currentIntersection.x) + abs(currentIntersection.y)
} else {
val moveDirection = moveDirections.first()
val nextIntersection = currentIntersection.copy()
when (moveDirection.turn) {
Turn.RIGHT -> nextIntersection.turnRight()
Turn.LEFT -> nextIntersection.turnLeft()
else -> {}
}
nextIntersection.moveForward(moveDirection.distance)
if (stopOnIntersection
&& visitedIntersections.find{ it.isAtSamePosition(nextIntersection) } != null) {
abs(nextIntersection.x) + abs(nextIntersection.y)
} else {
visitedIntersections.add(nextIntersection)
getDistanceForDirections(
nextIntersection,
moveDirections.takeLast(moveDirections.count() - 1),
stopOnIntersection,
visitedIntersections)
}
}
private fun transformToMoveDirections(directionStrings: List<String>, singleStep: Boolean = false)
: List<MoveDirection> {
val moveDirections: MutableList<MoveDirection> = ArrayList()
directionStrings.forEach({
val moveDirection = MoveDirection()
moveDirection.fromString(it)
when (singleStep) {
true -> moveDirections.addAll(moveDirection.toSingleStepInstructions())
false -> moveDirections.add(moveDirection)
}
})
return moveDirections
}
private fun abs(value: Int) = if (value < 0) value * -1 else value
}
| mit | 5aef35a7c62bd031e613a2caa705135e | 35.390533 | 109 | 0.620163 | 4.927885 | false | false | false | false |
fengbaicanhe/intellij-community | platform/configuration-store-impl/src/BaseFileConfigurableStoreImpl.kt | 1 | 2615 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.components.PathMacroManager
import com.intellij.openapi.components.PathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.StorageData
import org.jdom.Element
import kotlin.properties.Delegates
abstract class BaseFileConfigurableStoreImpl(protected val pathMacroManager: PathMacroManager) : ComponentStoreImpl() {
val storageManager by Delegates.lazy { createStorageManager() }
override final fun getStateStorageManager() = storageManager
override final fun getPathMacroManagerForDefaults() = pathMacroManager
protected abstract fun createStorageManager(): StateStorageManagerImpl
}
open class ProjectStorageData : StorageData {
companion object {
val CURRENT_FORMAT_VERSION = 4
val VERSION_OPTION: String = "version"
}
private var version = CURRENT_FORMAT_VERSION
constructor(rootElementName: String) : super(rootElementName) {
}
protected constructor(storageData: ProjectStorageData) : super(storageData) {
}
override fun load(rootElement: Element, pathMacroSubstitutor: PathMacroSubstitutor?, intern: Boolean) {
super.load(rootElement, pathMacroSubstitutor, intern)
version = rootElement.getAttributeValue(VERSION_OPTION)?.toInt() ?: CURRENT_FORMAT_VERSION
}
override fun save(newLiveStates: Map<String, Element>): Element {
var root = super.save(newLiveStates)
if (root == null) {
root = Element(myRootElementName)
}
writeOptions(root, Integer.toString(version))
return root
}
override fun clone() = ProjectStorageData(this)
protected open fun writeOptions(root: Element, versionString: String) {
root.setAttribute(VERSION_OPTION, "4")
}
override fun getChangedComponentNames(newStorageData: StorageData, substitutor: PathMacroSubstitutor?): Set<String>? {
if (version != (newStorageData as ProjectStorageData).version) {
return null
}
return super.getChangedComponentNames(newStorageData, substitutor)
}
}
| apache-2.0 | cce61f939de62d2d0c1650f35cdd74a2 | 33.866667 | 120 | 0.765201 | 4.703237 | false | true | false | false |
nathanial/galaxy-sim | src/main/java/Main.kt | 1 | 1021 | package main
import com.google.common.eventbus.EventBus
import simulation.SimulationView
import simulation.model.basic.Simulation
import java.awt.Color
import javax.swing.JFrame
data class XY(val x: Double, val y: Double)
data class MouseZoomEvent(val zoom: Int)
data class MouseDownEvent(val x: Int, val y: Int)
data class MouseUpEvent(val x: Int, val y: Int)
data class MouseMoveEvent(val x: Int, val y: Int)
class SimulationFrame(val simulation: Simulation, val bus: EventBus) : JFrame("Galactic Simulation") {
init {
isResizable = true
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
background = Color.white
add(SimulationView(simulation, bus))
pack()
isVisible = true
}
}
fun main(args: Array<String>){
val bus = EventBus("Simulation Bus")
val sim = Simulation(bus, systemCount = 1000, planetsRange = 0..9)
SimulationFrame(sim, bus)
while(true){
sim.tick();
Thread.sleep(10);
}
}
| mit | 78103f19c70cbfba388a579b2f09f092 | 24.868421 | 102 | 0.665034 | 3.795539 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/settings/Maintainer.kt | 1 | 3070 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.settings
import net.mm2d.dmsexplorer.BuildConfig
/**
* 設定値のメンテナー。
*
* アプリ設定のバージョンを付与し、
* 元に設定値のマイグレーション処理や初期値の書き込みを行う。
*
* すでに使用しなくなった設定値にアクセスするため、
* `@Deprecated`指定をしたOldKeysに唯一アクセスしてもよいクラス。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
internal object Maintainer {
/**
* 設定データフォーマットのバージョン
*
* | value | App Version | 状態 |
* |-------|-------------|--------------------|
* | 0 | 0.6.20- |サポート終了 v0.7.38|
* | 1 | 0.7.0- | |
* | 2 | 0.7.56- |現在 |
*
* 設定フォーマットを変更した場合は、
* 旧バージョンからのマイグレーション処理を記述し、設定を持ち越せるようにする。
* マイグレーションを打ち切った場合は、
* 設定バージョンが現在のものでなければクリアを行い初期設定で起動するようにする。
*/
private const val SETTINGS_VERSION = 2
/**
* 起動時に一度だけ呼び出され、SharedPreferencesのメンテナンスを行う。
*
* @param storage SettingsStorage
*/
fun maintain(storage: SettingsStorage) {
val version = storage.readInt(Key.SETTINGS_VERSION)
if (version <= 0) {
storage.clear()
storage.writeInt(Key.SETTINGS_VERSION, SETTINGS_VERSION)
} else if (version == 1) {
storage.writeInt(Key.SETTINGS_VERSION, SETTINGS_VERSION)
storage.remove(Key.UPDATE_FETCH_TIME)
storage.remove(Key.UPDATE_AVAILABLE)
storage.remove(Key.UPDATE_JSON)
}
if (storage.readInt(Key.APP_VERSION) != BuildConfig.VERSION_CODE) {
storage.writeInt(Key.APP_VERSION, BuildConfig.VERSION_CODE)
writeDefaultValue(storage, false)
}
}
/**
* 設定値をすべてデフォルト値にもどす
*
* @param storage SettingsStorage
*/
fun reset(storage: SettingsStorage) {
writeDefaultValue(storage, true)
storage.writeInt(Key.SETTINGS_VERSION, SETTINGS_VERSION)
storage.writeInt(Key.APP_VERSION, BuildConfig.VERSION_CODE)
}
/**
* デフォルト値の書き込みを行う
*
* @param storage SettingsStorage
* @param overwrite true:値を上書きする、false:値がない場合のみ書き込む
*/
private fun writeDefaultValue(
storage: SettingsStorage,
overwrite: Boolean
) {
for (key in Key.values()) {
storage.writeDefault(key, overwrite)
}
}
}
| mit | ea3eeda2fd918c0d9b850239e62c8860 | 26.862069 | 75 | 0.588696 | 3.123711 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/kotlin/builder/utils/jars/JarOwner.kt | 1 | 1065 | package io.bazel.kotlin.builder.utils.jars
import io.bazel.kotlin.builder.utils.jars.JarHelper.Companion.INJECTING_RULE_KIND
import io.bazel.kotlin.builder.utils.jars.JarHelper.Companion.TARGET_LABEL
import java.io.IOException
import java.io.UncheckedIOException
import java.nio.file.Path
import java.util.jar.JarFile
data class JarOwner(val jar: Path, val label: String? = null, val aspect: String? = null) {
companion object {
fun readJarOwnerFromManifest(jarPath: Path): JarOwner {
try {
JarFile(jarPath.toFile()).use { jarFile ->
val manifest = jarFile.manifest ?: return JarOwner(jarPath)
val attributes = manifest.mainAttributes
val label = attributes[TARGET_LABEL] as String?
?: return JarOwner(jarPath)
val injectingRuleKind = attributes[INJECTING_RULE_KIND] as String?
return JarOwner(jarPath, label, injectingRuleKind)
}
} catch (e: IOException) {
// This jar file pretty much has to exist.
throw UncheckedIOException(e)
}
}
}
}
| apache-2.0 | b74b44b5239d96da0d0e8a5ad0df03f8 | 37.035714 | 91 | 0.694836 | 4.018868 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/comicastle/src/eu/kanade/tachiyomi/extension/en/comicastle/Comicastle.kt | 1 | 6977 | package eu.kanade.tachiyomi.extension.en.comicastle
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.net.URLEncoder
import java.util.Calendar
import java.util.Locale
class Comicastle : ParsedHttpSource() {
override val name = "Comicastle"
override val versionId = 2
override val baseUrl = "https://www.comicastle.org"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
private fun pageSegments(page: Int): String = if (page > 1) "/index/${(page - 1) * 30}" else ""
// Popular
override fun popularMangaRequest(page: Int): Request {
return GET("$baseUrl/library/popular/desc" + pageSegments(page), headers)
}
override fun popularMangaSelector() = "div.col-lg-2"
override fun popularMangaFromElement(element: Element): SManga {
return SManga.create().apply {
title = element.select("p").text()
setUrlWithoutDomain(element.select("a").first().attr("href"))
thumbnail_url = element.select("img").attr("abs:src")
}
}
override fun popularMangaNextPageSelector() = "li.page-item.next a"
// Latest
override fun latestUpdatesRequest(page: Int): Request {
return GET("$baseUrl/library/postdate/desc" + pageSegments(page), headers)
}
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
// Search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/library/search".toHttpUrlOrNull()!!.newBuilder()
var rBody: RequestBody? = null
(filters.let { if (it.isEmpty()) getFilterList() else filters })
.filterIsInstance<PostFilter>()
.firstOrNull { it.hasSelection() }
?.let { filter ->
url.addPathSegment(filter.pathSegment)
rBody = filter.toRequestBody()
}
if (rBody == null) rBody = createRequestBody(query)
return POST(url.toString(), headers, rBody!!)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
// Details
override fun mangaDetailsParse(document: Document): SManga {
return SManga.create().apply {
with(document.select("div.card-body > div.mb-5")) {
thumbnail_url = select("img").attr("abs:src")
val publisher = select("p:contains(Publisher) button")
.firstOrNull()?.let { "Publisher: ${it.text()}\n" }
description = publisher + select("h5:contains(Description) + p").text()
author = select("p:contains(Writer) button").joinToString { it.text() }
artist = select("p:contains(Artist) button").joinToString { it.text() }
status = select("p span.mr-1 strong").text().toStatus()
genre = select("p:contains(Genre) button").joinToString { it.text() }
}
}
}
private fun String.toStatus() = when {
this.contains("Ongoing", ignoreCase = true) -> SManga.ONGOING
this.contains("Completed", ignoreCase = true) -> SManga.COMPLETED
else -> SManga.UNKNOWN
}
// Chapters
override fun chapterListParse(response: Response): List<SChapter> {
return super.chapterListParse(response).reversed()
}
override fun chapterListSelector() = "table tr a"
override fun chapterFromElement(element: Element): SChapter {
return SChapter.create().apply {
name = element.text()
setUrlWithoutDomain(element.attr("href").replace("pbp", "swiper"))
}
}
// Pages
override fun pageListParse(document: Document): List<Page> {
return document.select(".swiper-wrapper .swiper-slide img").mapIndexed { i, img ->
Page(i, "", img.attr("abs:src"))
}
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
// Filters
override fun getFilterList() = FilterList(
Filter.Header("Cannot combine search types!"),
Filter.Separator(),
PostFilter("Genre", getGenreList()),
PostFilter("Year", getYearList()),
PostFilter("Publisher", getPublisherList())
)
private open class PostFilter(name: String, val vals: Array<String>) : Filter.Select<String>(name, vals) {
val pathSegment = name.toLowerCase(Locale.US)
fun hasSelection(): Boolean = state != 0
fun toRequestBody(): RequestBody = createRequestBody(vals[state])
}
private fun getGenreList() = arrayOf("<Select>", "Action/Adventure", "Anthology", "Anthropomorphic", "Biography", "Children's", "Comedy", "Crime", "Drama", "Fantasy", "Gore", "Graphic Novels", "Historical", "Holiday", "Horror", "Leading Ladies", "LGBTQ", "Literature", "Manga", "Martial Arts", "Mature", "Military", "Movies & TV", "Music", "Mystery", "Mythology", "Non-Fiction", "Original Series", "Political", "Post-Apocalyptic", "Pulp", "Religious", "Risque", "Robots, Cyborgs & Mecha", "Romance", "School Life", "Science Fiction", "Slice of Life", "Spy", "Steampunk", "Superhero", "Supernatural/Occult", "Suspense", "Vampires", "Video Games", "Web Comics", "Werewolves", "Western", "Zombies")
private fun getYearList() = arrayOf("<Select>") + (Calendar.getInstance()[1] downTo 1963).map { it.toString() }.toTypedArray()
private fun getPublisherList() = arrayOf("<Select>", "Action Lab", "Aftershock", "AHOY", "American Mythology", "Aspen", "Avatar Press", "AWA Studios", "Black Mask", "BOOM! Studios", "Dark Horse", "DC", "Death Rattle", "Dynamite", "IDW", "Image", "Magnetic Press", "Marvel", "MAX", "Titan", "Ubiworkshop", "Valiant", "Vault", "Vertigo", "Wildstorm", "Zenescope")
}
private fun createRequestBody(value: String) =
("search=" + URLEncoder.encode(value, "UTF-8")).toRequestBody("application/x-www-form-urlencoded".toMediaTypeOrNull())
| apache-2.0 | 337b630cbf2c2715c8e2995c3bb542d9 | 41.284848 | 699 | 0.669629 | 4.30679 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/geom/polygon/Polygon.kt | 1 | 2430 | package pl.shockah.godwit.geom.polygon
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import pl.shockah.godwit.ObservableList
import pl.shockah.godwit.ease.Easable
import pl.shockah.godwit.geom.*
import pl.shockah.godwit.swift.guard
open class Polygon(
points: List<Vec2>
) : Shape.Outline, Easable<Polygon> {
val points: ObservableList<MutableVec2> = ObservableList(points.map { it.mutableCopy() }.toMutableList())
constructor(vararg points: Vec2) : this(points.toMutableList())
override val boundingBox: Rectangle
get() {
val (minX, minY, maxX, maxY) = guard(
points.map { it.x }::min,
points.map { it.y }::min,
points.map { it.x }::max,
points.map { it.y }::max
) {
return Rectangle(size = ImmutableVec2.ZERO)
}
return Rectangle(vec2(minX, minY), vec2(maxX - minX, maxY - minY))
}
open val lines: List<Line>
get() {
val result: MutableList<Line> = mutableListOf()
for (i in 0 until (points.size - 1)) {
result += Line(points[i], points[i + 1])
}
return result
}
companion object {
init {
Shape.registerCollisionHandler { a: Polygon, b: Polygon ->
for (aLine in a.lines) {
for (bLine in b.lines) {
if (aLine collides bLine)
return@registerCollisionHandler true
}
}
return@registerCollisionHandler false
}
Shape.registerCollisionHandler { polygon: Polygon, line: Line ->
for (polygonLine in polygon.lines) {
if (polygonLine collides line)
return@registerCollisionHandler true
}
return@registerCollisionHandler false
}
}
}
override fun copy(): Polygon {
return Polygon(points)
}
override fun translate(vector: Vec2) {
points.forEach { it.xy += vector }
}
override fun mirror(horizontal: Boolean, vertical: Boolean) {
if (horizontal)
points.forEach { it.x *= -1f }
if (vertical)
points.forEach { it.y *= -1f }
}
override fun scale(scale: Float) {
points.forEach { it.xy *= scale }
}
override fun ease(other: Polygon, f: Float): Polygon {
if (points.size != other.points.size)
throw IllegalArgumentException()
return Polygon(points.mapIndexed { index, point -> point.ease(other.points[index], f) })
}
override fun drawOutline(shapes: ShapeRenderer) {
val vertices = FloatArray(points.size * 2)
for (i in 0 until points.size) {
vertices[i * 2] = points[i].x
vertices[i * 2 + 1] = points[i].y
}
shapes.polygon(vertices)
}
} | apache-2.0 | 82d48f036b1caacc3637991153acff72 | 25.423913 | 106 | 0.67284 | 3.270525 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/VariableHidingCheck.kt | 1 | 2004 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MAJOR)
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class VariableHidingCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.VARIABLE_DECLARATION)
}
override fun visitNode(node: AstNode) {
val identifier = node.getFirstChild(PlSqlGrammar.IDENTIFIER_NAME)
val name = identifier.tokenOriginalValue
val scope = context.symbolTable.getScopeForSymbol(identifier)
if (scope != null) {
val symbols = scope.getSymbolsAcessibleInScope(name)
if (symbols.size > 1) {
val originalVariable = symbols.last.declaration()
if (originalVariable != identifier) {
addIssue(identifier, getLocalizedMessage(), name, originalVariable.tokenLine)
.secondary(originalVariable, "Original")
}
}
}
}
}
| lgpl-3.0 | 593eca214fe87e58a126568b165c97dd | 35.436364 | 97 | 0.696108 | 4.513514 | false | false | false | false |
PublicXiaoWu/XiaoWuMySelf | app/src/main/java/com/xiaowu/myself/main/fragment/TwoFragment.kt | 1 | 1586 | package com.xiaowu.myself.main.fragment
import android.view.View
import com.xiaowu.myself.R
import com.xiaowu.myself.app.base.BaseFragment
import com.xiaowu.myself.app.network.ApiService
import com.xiaowu.myself.app.network.BaseResponseEntity
import com.xiaowu.myself.app.network.HttpObserver
import com.xiaowu.myself.app.network.RetrofitClient
import com.xiaowu.myself.main.bean.Login
import kotlinx.android.synthetic.main.two_fragment.*
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*
/**
*
* @author LSX
*/
class TwoFragment : BaseFragment() {
override fun provideContentViewId(): Int {
return R.layout.two_fragment
}
override fun initView(rootView: View) {
}
override fun initData() {
bt_one.setOnClickListener {
loadData()
}
}
private fun loadData() {
var map = LinkedHashMap<String, String>()
map["userName"] = "xian2"
map["userPassword"] = "xian2"
RetrofitClient.Companion.getInstance(context, ApiService.BASE_URL).mApi
?.login(map)
?.subscribeOn(Schedulers.io())
?.unsubscribeOn(AndroidSchedulers.mainThread())
?.observeOn(AndroidSchedulers.mainThread())
?.subscribe(object : HttpObserver<BaseResponseEntity<Login>>(mContext!!) {
override fun success(t: BaseResponseEntity<Login>) {
if (t.status == 200) tv_show.text = t.toString()
}
}
)
}
}
| apache-2.0 | 4b9ad5293de8374481d5af71f95f9031 | 29.5 | 90 | 0.641866 | 4.357143 | false | false | false | false |
robfletcher/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/migration/TaskTypeDeserializerTest.kt | 2 | 2473 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.migration
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.netflix.spinnaker.orca.TaskResolver
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.TaskResult
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.q.TasksProvider
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
object TaskTypeDeserializerTest : Spek({
val taskResolver = TaskResolver(TasksProvider(listOf(DummyTask())), false)
val objectMapper = ObjectMapper().apply {
registerModule(KotlinModule())
registerModule(
SimpleModule()
.addDeserializer(Class::class.java, TaskTypeDeserializer(taskResolver))
)
}
describe("when 'taskType' is deserialized") {
val canonicalJson =
"""{ "taskType" : "${DummyTask::class.java.canonicalName}" }"""
Assertions.assertThat(
objectMapper.readValue(canonicalJson, Target::class.java).taskType
).isEqualTo(DummyTask::class.java)
val aliasedJson =
"""{ "taskType" : "anotherTaskAlias" }"""
Assertions.assertThat(
objectMapper.readValue(aliasedJson, Target::class.java).taskType
).isEqualTo(DummyTask::class.java)
val notTaskTypeJson =
"""{ "notTaskType" : "java.lang.String" }"""
Assertions.assertThat(
objectMapper.readValue(notTaskTypeJson, Target::class.java).notTaskType
).isEqualTo(String::class.java)
}
})
class Target(val taskType: Class<*>?, val notTaskType: Class<*>?)
@Task.Aliases("anotherTaskAlias")
class DummyTask : Task {
override fun execute(stage: StageExecution): TaskResult {
return TaskResult.SUCCEEDED
}
}
| apache-2.0 | cd7b50b0f46d6c9d5bba25639b2ddc57 | 34.328571 | 79 | 0.745653 | 4.22735 | false | false | false | false |
anrelic/Anci-OSS | util/src/main/kotlin/su/jfdev/anci/util/syntax/SyntaxUtils.kt | 1 | 1309 | package su.jfdev.anci.util.syntax
infix inline fun <T> T.finally(block: (T) -> Unit) = apply(block)
infix inline fun <T: Any> T?.`when null`(block: () -> Unit) = finally {
if (it == null) block()
}
infix inline fun <T: Any> T?.`when not null`(block: (T) -> Unit) = finally {
if (it != null) block(it)
}
infix inline fun <T: Boolean?> T.`when true`(block: (T) -> Unit): T = finally {
if (it == true) block(it)
}
infix inline fun <T: Boolean?> T.`when false`(block: (T) -> Unit): T = finally {
if (it == false) block(it)
}
inline fun <T> T.`when same`(inclusion: T, block: (T) -> Unit): T = finally {
if (it === inclusion) block(it)
}
inline fun <T> T.`when other`(exclusion: T, block: (T) -> Unit): T = finally {
if (it !== exclusion) block(it)
}
inline fun <T> T.`when equal`(inclusion: T, block: (T) -> Unit): T = finally {
if (it == inclusion) block(it)
}
inline fun <T> T.`when not equal`(exclusion: T, block: (T) -> Unit): T = finally {
if (it != exclusion) block(it)
}
inline fun <reified T> Any?.`when is`(action: (T) -> Unit) {
if (this != null && this is T) return action(this)
}
inline fun <reified T> Any?.`when is not`(action: (T) -> Unit) {
if (this != null && this is T) return action(this)
}
inline fun <reified T: Any> reify() = T::class.java | mit | bc878433b6de82b14f251c949926765b | 28.111111 | 82 | 0.588999 | 2.839479 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/activity/GroupActivity.kt | 2 | 4199 | package com.commit451.gitlab.activity
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.palette.graphics.Palette
import coil.api.load
import com.commit451.addendum.design.snackbar
import com.commit451.addendum.themeAttrColor
import com.commit451.alakazam.navigationBarColorAnimator
import com.commit451.easel.Easel
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.adapter.GroupPagerAdapter
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.image.PaletteImageViewTarget
import com.commit451.gitlab.model.api.Group
import kotlinx.android.synthetic.main.activity_group.*
import timber.log.Timber
/**
* See the things about the group
*/
class GroupActivity : BaseActivity() {
companion object {
private const val KEY_GROUP = "key_group"
private const val KEY_GROUP_ID = "key_group_id"
fun newIntent(context: Context, group: Group): Intent {
val intent = Intent(context, GroupActivity::class.java)
intent.putExtra(KEY_GROUP, group)
return intent
}
fun newIntent(context: Context, groupId: Long): Intent {
val intent = Intent(context, GroupActivity::class.java)
intent.putExtra(KEY_GROUP_ID, groupId)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_group)
// Default content and scrim colors
toolbar.setNavigationIcon(R.drawable.ic_back_24dp)
toolbar.setNavigationOnClickListener { onBackPressed() }
if (intent.hasExtra(KEY_GROUP)) {
val group = intent.getParcelableExtra<Group>(KEY_GROUP)!!
bind(group)
} else {
progress.visibility = View.VISIBLE
val groupId = intent.getLongExtra(KEY_GROUP_ID, -1)
App.get().gitLab.getGroup(groupId)
.with(this)
.subscribe({
progress.visibility = View.GONE
bind(it)
}, {
Timber.e(it)
progress.visibility = View.GONE
showError()
})
}
}
override fun onBackPressed() {
supportFinishAfterTransition()
}
override fun hasBrowsableLinks(): Boolean {
return true
}
fun bind(group: Group) {
val paletteTarget = PaletteImageViewTarget(backdrop) {
bindPalette(it)
}
backdrop.load(group.avatarUrl) {
allowHardware(false)
target(paletteTarget)
}
viewPager.adapter = GroupPagerAdapter(this, supportFragmentManager, group)
tabLayout.setupWithViewPager(viewPager)
}
private fun bindPalette(palette: Palette) {
val animationTime = 1000
val vibrantColor = palette.getVibrantColor(this.themeAttrColor(R.attr.colorAccent))
val darkerColor = Easel.darkerColor(vibrantColor)
window.navigationBarColorAnimator(darkerColor)
.setDuration(animationTime.toLong())
.start()
ObjectAnimator.ofObject(collapsingToolbarLayout, "contentScrimColor", ArgbEvaluator(),
this.themeAttrColor(R.attr.colorPrimary), vibrantColor)
.setDuration(animationTime.toLong())
.start()
ObjectAnimator.ofObject(collapsingToolbarLayout, "statusBarScrimColor", ArgbEvaluator(),
this.themeAttrColor(R.attr.colorPrimaryDark), darkerColor)
.setDuration(animationTime.toLong())
.start()
ObjectAnimator.ofObject(toolbar, "titleTextColor", ArgbEvaluator(),
Color.WHITE, palette.getDarkMutedColor(Color.BLACK))
.setDuration(animationTime.toLong())
.start()
}
private fun showError() {
root.snackbar(R.string.connection_error)
}
}
| apache-2.0 | 63a884399d37d50cb565113ad0214178 | 32.592 | 96 | 0.644677 | 4.771591 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/source/LocalSource.kt | 1 | 19357 | package eu.kanade.tachiyomi.source
import android.content.Context
import com.github.junrar.Archive
import com.hippo.unifile.UniFile
import eu.kanade.domain.manga.model.ComicInfo
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.util.chapter.ChapterRecognition
import eu.kanade.tachiyomi.util.lang.compareToCaseInsensitiveNaturalOrder
import eu.kanade.tachiyomi.util.lang.withIOContext
import eu.kanade.tachiyomi.util.storage.DiskUtil
import eu.kanade.tachiyomi.util.storage.EpubFile
import eu.kanade.tachiyomi.util.system.ImageUtil
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import logcat.LogPriority
import nl.adaptivity.xmlutil.AndroidXmlReader
import nl.adaptivity.xmlutil.serialization.XML
import rx.Observable
import uy.kohesive.injekt.injectLazy
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.StandardCharsets
import java.util.concurrent.TimeUnit
import java.util.zip.ZipFile
class LocalSource(
private val context: Context,
) : CatalogueSource, UnmeteredSource {
private val json: Json by injectLazy()
private val xml: XML by injectLazy()
override val name: String = context.getString(R.string.local_source)
override val id: Long = ID
override val lang: String = "other"
override fun toString() = name
override val supportsLatest: Boolean = true
// Browse related
override fun fetchPopularManga(page: Int) = fetchSearchManga(page, "", POPULAR_FILTERS)
override fun fetchLatestUpdates(page: Int) = fetchSearchManga(page, "", LATEST_FILTERS)
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
val baseDirsFiles = getBaseDirectoriesFiles(context)
var mangaDirs = baseDirsFiles
// Filter out files that are hidden and is not a folder
.filter { it.isDirectory && !it.name.startsWith('.') }
.distinctBy { it.name }
val lastModifiedLimit = if (filters === LATEST_FILTERS) System.currentTimeMillis() - LATEST_THRESHOLD else 0L
// Filter by query or last modified
mangaDirs = mangaDirs.filter {
if (lastModifiedLimit == 0L) {
it.name.contains(query, ignoreCase = true)
} else {
it.lastModified() >= lastModifiedLimit
}
}
filters.forEach { filter ->
when (filter) {
is OrderBy -> {
when (filter.state!!.index) {
0 -> {
mangaDirs = if (filter.state!!.ascending) {
mangaDirs.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name })
} else {
mangaDirs.sortedWith(compareByDescending(String.CASE_INSENSITIVE_ORDER) { it.name })
}
}
1 -> {
mangaDirs = if (filter.state!!.ascending) {
mangaDirs.sortedBy(File::lastModified)
} else {
mangaDirs.sortedByDescending(File::lastModified)
}
}
}
}
else -> {
/* Do nothing */
}
}
}
// Transform mangaDirs to list of SManga
val mangas = mangaDirs.map { mangaDir ->
SManga.create().apply {
title = mangaDir.name
url = mangaDir.name
// Try to find the cover
val cover = getCoverFile(mangaDir.name, baseDirsFiles)
if (cover != null && cover.exists()) {
thumbnail_url = cover.absolutePath
}
}
}
// Fetch chapters of all the manga
mangas.forEach { manga ->
runBlocking {
val chapters = getChapterList(manga)
if (chapters.isNotEmpty()) {
val chapter = chapters.last()
val format = getFormat(chapter)
if (format is Format.Epub) {
EpubFile(format.file).use { epub ->
epub.fillMangaMetadata(manga)
}
}
// Copy the cover from the first chapter found if not available
if (manga.thumbnail_url == null) {
updateCover(chapter, manga)
}
}
}
}
return Observable.just(MangasPage(mangas.toList(), false))
}
// Manga details related
override suspend fun getMangaDetails(manga: SManga): SManga = withIOContext {
val baseDirsFile = getBaseDirectoriesFiles(context)
getCoverFile(manga.url, baseDirsFile)?.let {
manga.thumbnail_url = it.absolutePath
}
// Augment manga details based on metadata files
try {
val mangaDirFiles = getMangaDirsFiles(manga.url, baseDirsFile).toList()
val comicInfoFile = mangaDirFiles
.firstOrNull { it.name == COMIC_INFO_FILE }
val noXmlFile = mangaDirFiles
.firstOrNull { it.name == ".noxml" }
if (comicInfoFile != null && noXmlFile != null) noXmlFile.delete()
when {
// Top level ComicInfo.xml
comicInfoFile != null -> {
setMangaDetailsFromComicInfoFile(comicInfoFile.inputStream(), manga)
}
// Copy ComicInfo.xml from chapter archive to top level if found
noXmlFile == null -> {
val chapterArchives = mangaDirFiles
.filter { isSupportedArchiveFile(it.extension) }
.toList()
val mangaDir = getMangaDir(manga.url, baseDirsFile)
val folderPath = mangaDir?.absolutePath
val copiedFile = copyComicInfoFileFromArchive(chapterArchives, folderPath)
if (copiedFile != null) {
setMangaDetailsFromComicInfoFile(copiedFile.inputStream(), manga)
} else {
// Avoid re-scanning
File("$folderPath/.noxml").createNewFile()
}
}
// Fall back to legacy JSON details format
else -> {
mangaDirFiles
.firstOrNull { it.extension == "json" }
?.let { file ->
json.decodeFromStream<MangaDetails>(file.inputStream()).run {
title?.let { manga.title = it }
author?.let { manga.author = it }
artist?.let { manga.artist = it }
description?.let { manga.description = it }
genre?.let { manga.genre = it.joinToString() }
status?.let { manga.status = it }
}
}
}
}
} catch (e: Throwable) {
logcat(LogPriority.ERROR, e) { "Error setting manga details from local metadata for ${manga.title}" }
}
return@withIOContext manga
}
private fun copyComicInfoFileFromArchive(chapterArchives: List<File>, folderPath: String?): File? {
for (chapter in chapterArchives) {
when (getFormat(chapter)) {
is Format.Zip -> {
ZipFile(chapter).use { zip: ZipFile ->
zip.getEntry(COMIC_INFO_FILE)?.let { comicInfoFile ->
zip.getInputStream(comicInfoFile).buffered().use { stream ->
return copyComicInfoFile(stream, folderPath)
}
}
}
}
is Format.Rar -> {
Archive(chapter).use { rar: Archive ->
rar.fileHeaders.firstOrNull { it.fileName == COMIC_INFO_FILE }?.let { comicInfoFile ->
rar.getInputStream(comicInfoFile).buffered().use { stream ->
return copyComicInfoFile(stream, folderPath)
}
}
}
}
else -> {}
}
}
return null
}
private fun copyComicInfoFile(comicInfoFileStream: InputStream, folderPath: String?): File {
return File("$folderPath/$COMIC_INFO_FILE").apply {
outputStream().use { outputStream ->
comicInfoFileStream.use { it.copyTo(outputStream) }
}
}
}
private fun setMangaDetailsFromComicInfoFile(stream: InputStream, manga: SManga) {
val comicInfo = AndroidXmlReader(stream, StandardCharsets.UTF_8.name()).use {
xml.decodeFromReader<ComicInfo>(it)
}
comicInfo.series?.let { manga.title = it.value }
comicInfo.writer?.let { manga.author = it.value }
comicInfo.summary?.let { manga.description = it.value }
listOfNotNull(
comicInfo.genre?.value,
comicInfo.tags?.value,
)
.flatMap { it.split(", ") }
.distinct()
.joinToString(", ") { it.trim() }
.takeIf { it.isNotEmpty() }
?.let { manga.genre = it }
listOfNotNull(
comicInfo.penciller?.value,
comicInfo.inker?.value,
comicInfo.colorist?.value,
comicInfo.letterer?.value,
comicInfo.coverArtist?.value,
)
.flatMap { it.split(", ") }
.distinct()
.joinToString(", ") { it.trim() }
.takeIf { it.isNotEmpty() }
?.let { manga.artist = it }
}
@Serializable
class MangaDetails(
val title: String? = null,
val author: String? = null,
val artist: String? = null,
val description: String? = null,
val genre: List<String>? = null,
val status: Int? = null,
)
// Chapters
override suspend fun getChapterList(manga: SManga): List<SChapter> {
val baseDirsFile = getBaseDirectoriesFiles(context)
return getMangaDirsFiles(manga.url, baseDirsFile)
// Only keep supported formats
.filter { it.isDirectory || isSupportedArchiveFile(it.extension) }
.map { chapterFile ->
SChapter.create().apply {
url = "${manga.url}/${chapterFile.name}"
name = if (chapterFile.isDirectory) {
chapterFile.name
} else {
chapterFile.nameWithoutExtension
}
date_upload = chapterFile.lastModified()
chapter_number = ChapterRecognition.parseChapterNumber(manga.title, this.name, this.chapter_number)
val format = getFormat(chapterFile)
if (format is Format.Epub) {
EpubFile(format.file).use { epub ->
epub.fillChapterMetadata(this)
}
}
}
}
.sortedWith { c1, c2 ->
val c = c2.chapter_number.compareTo(c1.chapter_number)
if (c == 0) c2.name.compareToCaseInsensitiveNaturalOrder(c1.name) else c
}
.toList()
}
// Filters
override fun getFilterList() = FilterList(OrderBy(context))
private val POPULAR_FILTERS = FilterList(OrderBy(context))
private val LATEST_FILTERS = FilterList(OrderBy(context).apply { state = Filter.Sort.Selection(1, false) })
private class OrderBy(context: Context) : Filter.Sort(
context.getString(R.string.local_filter_order_by),
arrayOf(context.getString(R.string.title), context.getString(R.string.date)),
Selection(0, true),
)
// Unused stuff
override suspend fun getPageList(chapter: SChapter) = throw UnsupportedOperationException("Unused")
// Miscellaneous
private fun isSupportedArchiveFile(extension: String): Boolean {
return extension.lowercase() in SUPPORTED_ARCHIVE_TYPES
}
fun getFormat(chapter: SChapter): Format {
val baseDirs = getBaseDirectories(context)
for (dir in baseDirs) {
val chapFile = File(dir, chapter.url)
if (!chapFile.exists()) continue
return getFormat(chapFile)
}
throw Exception(context.getString(R.string.chapter_not_found))
}
private fun getFormat(file: File) = with(file) {
when {
isDirectory -> Format.Directory(this)
extension.equals("zip", true) || extension.equals("cbz", true) -> Format.Zip(this)
extension.equals("rar", true) || extension.equals("cbr", true) -> Format.Rar(this)
extension.equals("epub", true) -> Format.Epub(this)
else -> throw Exception(context.getString(R.string.local_invalid_format))
}
}
private fun updateCover(chapter: SChapter, manga: SManga): File? {
return try {
when (val format = getFormat(chapter)) {
is Format.Directory -> {
val entry = format.file.listFiles()
?.sortedWith { f1, f2 -> f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) }
?.find { !it.isDirectory && ImageUtil.isImage(it.name) { FileInputStream(it) } }
entry?.let { updateCover(context, manga, it.inputStream()) }
}
is Format.Zip -> {
ZipFile(format.file).use { zip ->
val entry = zip.entries().toList()
.sortedWith { f1, f2 -> f1.name.compareToCaseInsensitiveNaturalOrder(f2.name) }
.find { !it.isDirectory && ImageUtil.isImage(it.name) { zip.getInputStream(it) } }
entry?.let { updateCover(context, manga, zip.getInputStream(it)) }
}
}
is Format.Rar -> {
Archive(format.file).use { archive ->
val entry = archive.fileHeaders
.sortedWith { f1, f2 -> f1.fileName.compareToCaseInsensitiveNaturalOrder(f2.fileName) }
.find { !it.isDirectory && ImageUtil.isImage(it.fileName) { archive.getInputStream(it) } }
entry?.let { updateCover(context, manga, archive.getInputStream(it)) }
}
}
is Format.Epub -> {
EpubFile(format.file).use { epub ->
val entry = epub.getImagesFromPages()
.firstOrNull()
?.let { epub.getEntry(it) }
entry?.let { updateCover(context, manga, epub.getInputStream(it)) }
}
}
}
} catch (e: Throwable) {
logcat(LogPriority.ERROR, e) { "Error updating cover for ${manga.title}" }
null
}
}
sealed class Format {
data class Directory(val file: File) : Format()
data class Zip(val file: File) : Format()
data class Rar(val file: File) : Format()
data class Epub(val file: File) : Format()
}
companion object {
const val ID = 0L
const val HELP_URL = "https://tachiyomi.org/help/guides/local-manga/"
private const val DEFAULT_COVER_NAME = "cover.jpg"
private val LATEST_THRESHOLD = TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS)
private fun getBaseDirectories(context: Context): Sequence<File> {
val localFolder = context.getString(R.string.app_name) + File.separator + "local"
return DiskUtil.getExternalStorages(context)
.map { File(it.absolutePath, localFolder) }
.asSequence()
}
private fun getBaseDirectoriesFiles(context: Context): Sequence<File> {
return getBaseDirectories(context)
// Get all the files inside all baseDir
.flatMap { it.listFiles().orEmpty().toList() }
}
private fun getMangaDir(mangaUrl: String, baseDirsFile: Sequence<File>): File? {
return baseDirsFile
// Get the first mangaDir or null
.firstOrNull { it.isDirectory && it.name == mangaUrl }
}
private fun getMangaDirsFiles(mangaUrl: String, baseDirsFile: Sequence<File>): Sequence<File> {
return baseDirsFile
// Filter out ones that are not related to the manga and is not a directory
.filter { it.isDirectory && it.name == mangaUrl }
// Get all the files inside the filtered folders
.flatMap { it.listFiles().orEmpty().toList() }
}
private fun getCoverFile(mangaUrl: String, baseDirsFile: Sequence<File>): File? {
return getMangaDirsFiles(mangaUrl, baseDirsFile)
// Get all file whose names start with 'cover'
.filter { it.isFile && it.nameWithoutExtension.equals("cover", ignoreCase = true) }
// Get the first actual image
.firstOrNull {
ImageUtil.isImage(it.name) { it.inputStream() }
}
}
fun updateCover(context: Context, manga: SManga, inputStream: InputStream): File? {
val baseDirsFiles = getBaseDirectoriesFiles(context)
val mangaDir = getMangaDir(manga.url, baseDirsFiles)
if (mangaDir == null) {
inputStream.close()
return null
}
var coverFile = getCoverFile(manga.url, baseDirsFiles)
if (coverFile == null) {
coverFile = File(mangaDir.absolutePath, DEFAULT_COVER_NAME)
coverFile.createNewFile()
}
// It might not exist at this point
coverFile.parentFile?.mkdirs()
inputStream.use { input ->
coverFile.outputStream().use { output ->
input.copyTo(output)
}
}
DiskUtil.createNoMediaFile(UniFile.fromFile(mangaDir), context)
manga.thumbnail_url = coverFile.absolutePath
return coverFile
}
}
}
private val SUPPORTED_ARCHIVE_TYPES = listOf("zip", "cbz", "rar", "cbr", "epub")
private val COMIC_INFO_FILE = "ComicInfo.xml"
| apache-2.0 | 67aa8ad2fb7da7f2559d445abdcc459a | 38.91134 | 119 | 0.543679 | 5.033021 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt | 1 | 1742 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.complications
import android.app.PendingIntent
import android.support.wearable.complications.ComplicationData
import android.support.wearable.complications.ComplicationText
import dagger.android.AndroidInjection
import info.nightscout.androidaps.data.RawDisplayData
import info.nightscout.shared.logging.LTag
/*
* Created by dlvoy on 2019-11-12
*/
class LongStatusComplication : BaseComplicationProviderService() {
// Not derived from DaggerService, do injection here
override fun onCreate() {
AndroidInjection.inject(this)
super.onCreate()
}
override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
var complicationData: ComplicationData? = null
when (dataType) {
ComplicationData.TYPE_LONG_TEXT -> {
val glucoseLine = displayFormat.longGlucoseLine(raw)
val detailsLine = displayFormat.longDetailsLine(raw)
val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
.setLongTitle(ComplicationText.plainText(glucoseLine))
.setLongText(ComplicationText.plainText(detailsLine))
.setTapAction(complicationPendingIntent)
complicationData = builderLong.build()
}
else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
}
return complicationData
}
override fun getProviderCanonicalName(): String = LongStatusComplication::class.java.canonicalName!!
override fun usesSinceField(): Boolean = true
} | agpl-3.0 | 389b97ef8ce255a72c9b523a4100fa19 | 39.534884 | 137 | 0.704363 | 5.26284 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/DebuggerFieldSyntheticScopeProvider.kt | 3 | 10098 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate
import org.jetbrains.kotlin.codegen.state.GenerationState
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertyGetterDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.PropertySetterDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.components.JavaSourceElementFactoryImpl
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaClassDescriptor
import org.jetbrains.kotlin.load.java.lazy.types.toAttributes
import org.jetbrains.kotlin.load.java.structure.classId
import org.jetbrains.kotlin.load.kotlin.internalName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.DescriptorFactory
import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.SyntheticScope
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.synthetic.JavaSyntheticPropertiesScope
import org.jetbrains.kotlin.synthetic.SyntheticScopeProviderExtension
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections
import org.jetbrains.org.objectweb.asm.Type
class DebuggerFieldSyntheticScopeProvider : SyntheticScopeProviderExtension {
override fun getScopes(
moduleDescriptor: ModuleDescriptor,
javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope
): List<SyntheticScope> {
return listOf<SyntheticScope>(DebuggerFieldSyntheticScope(javaSyntheticPropertiesScope))
}
}
class DebuggerFieldSyntheticScope(val javaSyntheticPropertiesScope: JavaSyntheticPropertiesScope) : SyntheticScope.Default() {
private val javaSourceElementFactory = JavaSourceElementFactoryImpl()
override fun getSyntheticExtensionProperties(
receiverTypes: Collection<KotlinType>,
name: Name,
location: LookupLocation
): Collection<PropertyDescriptor> {
return getSyntheticExtensionProperties(receiverTypes, location).filter { it.name == name }
}
override fun getSyntheticExtensionProperties(
receiverTypes: Collection<KotlinType>,
location: LookupLocation
): Collection<PropertyDescriptor> {
if (!isInEvaluator(location)) {
return emptyList()
}
val result = mutableListOf<PropertyDescriptor>()
for (type in receiverTypes) {
val clazz = type.constructor.declarationDescriptor as? ClassDescriptor ?: continue
result += getSyntheticPropertiesForClass(clazz)
}
return result
}
private fun isInEvaluator(location: LookupLocation): Boolean {
val element = (location as? KotlinLookupLocation)?.element ?: return false
val containingFile = element.containingFile?.takeIf { it.isValid } as? KtFile ?: return false
val platform = containingFile.platform
if (!platform.isJvm() && !platform.isCommon()) {
return false
}
return containingFile is KtCodeFragment && containingFile.getCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) != null
}
private fun getSyntheticPropertiesForClass(clazz: ClassDescriptor): Collection<PropertyDescriptor> {
val collected = mutableMapOf<Name, PropertyDescriptor>()
val syntheticPropertyNames = javaSyntheticPropertiesScope
.getSyntheticExtensionProperties(listOf(clazz.defaultType), NoLookupLocation.FROM_SYNTHETIC_SCOPE)
.mapTo(mutableSetOf()) { it.name }
collectPropertiesWithParent(clazz, syntheticPropertyNames, collected)
return collected.values
}
private tailrec fun collectPropertiesWithParent(
clazz: ClassDescriptor,
syntheticNames: Set<Name>,
consumer: MutableMap<Name, PropertyDescriptor>
) {
when (clazz) {
is LazyJavaClassDescriptor -> collectJavaProperties(clazz, syntheticNames, consumer)
is JavaClassDescriptor -> error("Unsupported Java class type")
else -> collectKotlinProperties(clazz, consumer)
}
val superClass = clazz.getSuperClassNotAny()
if (superClass != null) {
collectPropertiesWithParent(superClass, syntheticNames, consumer)
}
}
private fun collectKotlinProperties(clazz: ClassDescriptor, consumer: MutableMap<Name, PropertyDescriptor>) {
for (descriptor in clazz.unsubstitutedMemberScope.getDescriptorsFiltered(DescriptorKindFilter.VARIABLES)) {
val propertyDescriptor = descriptor as? PropertyDescriptor ?: continue
val name = propertyDescriptor.name
if (propertyDescriptor.backingField == null || name in consumer) continue
val type = propertyDescriptor.type
val sourceElement = propertyDescriptor.source
val isVar = propertyDescriptor.isVar
consumer[name] = createSyntheticPropertyDescriptor(
clazz,
type,
name,
isVar,
KotlinDebuggerEvaluationBundle.message("backing.field"),
sourceElement
) { state ->
state.typeMapper.mapType(clazz.defaultType)
}
}
}
private fun collectJavaProperties(
clazz: LazyJavaClassDescriptor,
syntheticNames: Set<Name>,
consumer: MutableMap<Name, PropertyDescriptor>
) {
val javaClass = clazz.jClass
for (field in javaClass.fields) {
val fieldName = field.name
if (field.isEnumEntry || field.isStatic || fieldName in consumer || fieldName !in syntheticNames) continue
val ownerClassName = javaClass.classId?.internalName ?: continue
val typeResolver = clazz.outerContext.typeResolver
val type = typeResolver.transformJavaType(field.type, TypeUsage.COMMON.toAttributes()).replaceArgumentsWithStarProjections()
val sourceElement = javaSourceElementFactory.source(field)
val isVar = !field.isFinal
consumer[fieldName] = createSyntheticPropertyDescriptor(
clazz,
type,
fieldName,
isVar,
KotlinDebuggerEvaluationBundle.message("java.field"),
sourceElement
) {
Type.getObjectType(ownerClassName)
}
}
}
private fun createSyntheticPropertyDescriptor(
clazz: ClassDescriptor,
type: KotlinType,
fieldName: Name,
isVar: Boolean,
description: String,
sourceElement: SourceElement,
ownerType: (GenerationState) -> Type
): PropertyDescriptor {
val propertyDescriptor = DebuggerFieldPropertyDescriptor(clazz, fieldName.asString(), description, ownerType, isVar)
val extensionReceiverParameter = DescriptorFactory.createExtensionReceiverParameterForCallable(
propertyDescriptor,
clazz.defaultType.replaceArgumentsWithStarProjections(),
Annotations.EMPTY
)
propertyDescriptor.setType(type, emptyList(), null, extensionReceiverParameter, emptyList())
val getter = PropertyGetterDescriptorImpl(
propertyDescriptor, Annotations.EMPTY, Modality.FINAL,
DescriptorVisibilities.PUBLIC, false, false, false,
CallableMemberDescriptor.Kind.SYNTHESIZED,
null, sourceElement
).apply { initialize(type) }
val setter = if (isVar) PropertySetterDescriptorImpl(
propertyDescriptor, Annotations.EMPTY, Modality.FINAL,
DescriptorVisibilities.PUBLIC, false, false, false,
CallableMemberDescriptor.Kind.SYNTHESIZED,
null, sourceElement
).apply {
val setterValueParameter = ValueParameterDescriptorImpl(
this, null, 0, Annotations.EMPTY, Name.identifier("value"), type,
declaresDefaultValue = false, isCrossinline = false, isNoinline = false,
varargElementType = null, source = sourceElement
)
initialize(setterValueParameter)
} else null
propertyDescriptor.initialize(getter, setter)
return propertyDescriptor
}
}
internal class DebuggerFieldPropertyDescriptor(
containingDeclaration: DeclarationDescriptor,
val fieldName: String,
val description: String,
val ownerType: (GenerationState) -> Type,
isVar: Boolean
) : PropertyDescriptorImpl(
containingDeclaration,
null,
Annotations.EMPTY,
Modality.FINAL,
DescriptorVisibilities.PUBLIC,
/*isVar = */isVar,
Name.identifier(fieldName + "_field"),
CallableMemberDescriptor.Kind.SYNTHESIZED,
SourceElement.NO_SOURCE,
/*lateInit = */false,
/*isConst = */false,
/*isExpect = */false,
/*isActual = */false,
/*isExternal = */false,
/*isDelegated = */false
) {
override val getter: PropertyGetterDescriptorImpl?
get() = null
}
| apache-2.0 | 139f904da684af21cbfc3e6283888381 | 40.900415 | 158 | 0.713706 | 5.458378 | false | false | false | false |
Maccimo/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hint/actions/ShowTypeDefinitionAction.kt | 2 | 6090 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.hint.actions
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.codeInsight.hint.*
import com.intellij.codeInsight.navigation.actions.TypeDeclarationProvider
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.psi.presentation.java.SymbolPresentationUtil
import com.intellij.util.Processor
import org.jetbrains.annotations.TestOnly
import java.awt.Component
import kotlin.streams.asSequence
open class ShowTypeDefinitionAction : ShowRelatedElementsActionBase() {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun getSessionFactories(): List<ImplementationViewSessionFactory> = listOf(TypeDefinitionsViewSessionFactory)
override fun getPopupTitle(session: ImplementationViewSession): String {
return CodeInsightBundle.message("type.definition.view.title", session.text)
}
override fun couldPinPopup(): Boolean = false
override fun triggerFeatureUsed(project: Project) {}
override fun getIndexNotReadyMessage(): String {
return CodeInsightBundle.message("show.type.definition.index.not.ready")
}
object TypeDefinitionsViewSessionFactory : ImplementationViewSessionFactory {
override fun createSession(dataContext: DataContext,
project: Project,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean): ImplementationViewSession? {
val file = CommonDataKeys.PSI_FILE.getData(dataContext)
val editor = PsiImplementationViewSession.getEditor(dataContext)
val pair = PsiImplementationViewSession.getElementAndReference(dataContext, project, file, editor) ?: return null
val element = pair.first
return element?.let { TypeDefinitionViewSession(project, editor, file?.virtualFile, it) }
}
override fun createSessionForLookupElement(project: Project,
editor: Editor?,
file: VirtualFile?,
lookupItemObject: Any?,
isSearchDeep: Boolean,
alwaysIncludeSelf: Boolean): ImplementationViewSession? {
val psiFile = file?.let { PsiManager.getInstance(project).findFile(it) }
val element = lookupItemObject as? PsiElement ?: DocumentationManager.getInstance(project).getElementFromLookup(editor, psiFile)
if (element == null) return null
val containingFile = element.containingFile
if (containingFile == null || !containingFile.viewProvider.isPhysical) return null
return TypeDefinitionViewSession(project, editor, file, element)
}
}
class TypeDefinitionViewSession(override val project: Project,
override val editor: Editor?,
override val file: VirtualFile?,
element: PsiElement) : ImplementationViewSession {
override val text: String = SymbolPresentationUtil.getSymbolPresentableText(element)
override val implementationElements: List<ImplementationViewElement> = searchTypeDefinitions(element)
override val factory: ImplementationViewSessionFactory = TypeDefinitionsViewSessionFactory
override fun elementRequiresIncludeSelf(): Boolean = false
override fun needUpdateInBackground(): Boolean = false
override fun dispose() {}
override fun searchImplementationsInBackground(indicator: ProgressIndicator, processor: Processor<in ImplementationViewElement>)
: List<ImplementationViewElement> = emptyList()
companion object {
private fun searchTypeDefinitions(element: PsiElement): List<PsiImplementationViewElement> {
val search = ThrowableComputable<List<PsiElement>, Exception> {
TypeDeclarationProvider.EP_NAME.extensions().asSequence()
.mapNotNull { provider ->
ReadAction.compute<List<PsiElement>?, Throwable> {
provider.getSymbolTypeDeclarations(element)?.mapNotNull { it?.navigationElement }
}
}
.firstOrNull()
?: emptyList()
}
val message = CodeInsightBundle.message("searching.for.definitions")
val definitions = ProgressManager.getInstance().runProcessWithProgressSynchronously(search, message, true, element.project)
return definitions.map { PsiImplementationViewElement(it) }
}
}
}
companion object {
@TestOnly
fun runForTests(context: Component): List<PsiElement> {
val showTypeDefinitionAction = ShowTypeDefinitionActionForTest()
showTypeDefinitionAction.performForContext(DataManager.getInstance().getDataContext(context))
return showTypeDefinitionAction.definitions.get().map { element -> (element as PsiImplementationViewElement).psiElement }
}
private class ShowTypeDefinitionActionForTest(val definitions: Ref<List<ImplementationViewElement>> = Ref()) : ShowTypeDefinitionAction() {
override fun showImplementations(session: ImplementationViewSession, invokedFromEditor: Boolean, invokedByShortcut: Boolean) =
definitions.set(session.implementationElements)
}
}
} | apache-2.0 | 5627ea666759cf2ea68fc7376f0130af | 48.92623 | 143 | 0.727586 | 5.526316 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/showcase/duration/EventsToday.kt | 1 | 678 | @file:Suppress("EXPERIMENTAL_FEATURE_WARNING", "EXPERIMENTAL_API_USAGE")
package arcs.showcase.duration
import arcs.jvm.host.TargetHost
import arcs.sdk.ArcsDuration
import arcs.sdk.ArcsInstant
typealias Agenda = AbstractEventsToday.Event
@TargetHost(arcs.android.integration.IntegrationHost::class)
class EventsToday : AbstractEventsToday() {
override fun onReady() {
handles.agenda.storeAll(
handles.events.fetchAll().filter {
(it.start <= ArcsInstant.now().plus(ArcsDuration.ofDays(1))) &&
(ArcsInstant.now() <= it.start.plus(it.length))
}.map {
Agenda(name = it.name, start = it.start, length = it.length)
}
)
}
}
| bsd-3-clause | caea7f41b59a6973a9e1f07be16fe7c7 | 27.25 | 72 | 0.70059 | 3.704918 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/devtools/ModelUpdateMessage.kt | 1 | 2984 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.devtools
import arcs.android.devtools.DevToolsMessage.Companion.MODEL_UPDATE_MESSAGE
import arcs.android.devtools.DevToolsMessage.Companion.STORAGE_KEY
import arcs.android.devtools.DevToolsMessage.Companion.STORE_TYPE
import arcs.android.devtools.DevToolsMessage.Companion.VERSION_MAP
import arcs.core.common.ReferenceId
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtEntity
import arcs.core.crdt.CrdtOperation
import arcs.core.crdt.CrdtSet
import arcs.core.crdt.CrdtSingleton
import arcs.core.data.FieldName
import arcs.core.storage.ProxyMessage
import arcs.core.util.JsonValue
/**
* An implementation of [StoreMessage] to inform DevTools that a [Store] received a
* [ModelUpdate].
*/
class ModelUpdateMessage(
private val actualMessage: ProxyMessage.ModelUpdate<CrdtData, CrdtOperation, Any?>,
private val storeType: String,
private val storageKey: String
) : DevToolsMessage {
override val kind: String = MODEL_UPDATE_MESSAGE
override val message: JsonValue<*>
get() = JsonValue.JsonObject(
"model" to getModel(actualMessage.model),
STORE_TYPE to JsonValue.JsonString(storeType),
STORAGE_KEY to JsonValue.JsonString(storageKey)
)
/**
* Transform the [CrdtData] into JSON.
*/
private fun getModel(model: CrdtData) = when (model) {
is CrdtEntity.Data -> JsonValue.JsonObject(
VERSION_MAP to model.versionMap.toJson(),
"singletons" to singletonsJson(model.singletons),
"collections" to collectionsJson(model.collections)
)
// TODO(b/162955831): other types
else -> JsonValue.JsonNull
}
/**
* Transform the map of names to collections into JSON.
*/
private fun collectionsJson(
collections: Map<FieldName, CrdtSet<CrdtEntity.Reference>>
) = JsonValue.JsonObject(
collections.map {
(name, collection) -> name to JsonValue.JsonObject(
VERSION_MAP to collection.data.versionMap.toJson(),
"values" to getValues(collection.data.values)
)
}.toMap()
)
/**
* Transform the map of names to singletons into JSON.
*/
private fun singletonsJson(
singletons: Map<FieldName, CrdtSingleton<CrdtEntity.Reference>>
) = JsonValue.JsonObject(
singletons.map {
(name, singleton) -> name to JsonValue.JsonObject(
VERSION_MAP to singleton.data.versionMap.toJson(),
"values" to getValues(singleton.data.values)
)
}.toMap()
)
/**
* Transform the values of fields into JSON.
*/
private fun getValues(
values: MutableMap<ReferenceId, CrdtSet.DataValue<CrdtEntity.Reference>>
) = JsonValue.JsonObject(values.mapValues { (_, value) -> value.value.toJson() })
}
| bsd-3-clause | 56535f0fa8d7a8f65c5d1d2dfedcb66b | 31.434783 | 96 | 0.725536 | 4.191011 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/HintsDescriptorRendererOptions.kt | 3 | 3292 | // 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.parameterInfo
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.ClassifierNamePolicyEx
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.renderer.*
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isDefinitelyNotNullType
import kotlin.properties.Delegates
import kotlin.properties.ReadWriteProperty
interface HintsClassifierNamePolicy {
fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String
}
/**
* Almost copy-paste from [ClassifierNamePolicy.SOURCE_CODE_QUALIFIED]
*
* for local declarations qualified up to function scope
*/
object SOURCE_CODE_QUALIFIED : HintsClassifierNamePolicy {
override fun renderClassifier(classifier: ClassifierDescriptor, renderer: HintsTypeRenderer): String =
qualifiedNameForSourceCode(classifier)
private fun qualifiedNameForSourceCode(descriptor: ClassifierDescriptor): String {
val nameString = descriptor.name.render()
if (descriptor is TypeParameterDescriptor) {
return nameString
}
val qualifier = qualifierName(descriptor.containingDeclaration)
return if (qualifier != null && qualifier != "") "$qualifier.$nameString" else nameString
}
private fun qualifierName(descriptor: DeclarationDescriptor): String? = when (descriptor) {
is ClassDescriptor -> qualifiedNameForSourceCode(descriptor)
is PackageFragmentDescriptor -> descriptor.fqName.toUnsafe().render()
else -> null
}
}
class HintsDescriptorRendererOptions : KotlinIdeDescriptorOptions() {
var hintsClassifierNamePolicy: HintsClassifierNamePolicy by property(SOURCE_CODE_QUALIFIED)
}
/**
* Almost copy-paste from [ClassifierNamePolicy.SOURCE_CODE_QUALIFIED]
*
* for local declarations qualified up to function scope
*/
object SourceCodeQualified: ClassifierNamePolicyEx {
override fun renderClassifierWithType(classifier: ClassifierDescriptor, renderer: DescriptorRenderer, type: KotlinType): String =
qualifiedNameForSourceCode(classifier, type)
override fun renderClassifier(classifier: ClassifierDescriptor, renderer: DescriptorRenderer): String =
qualifiedNameForSourceCode(classifier)
private fun qualifiedNameForSourceCode(descriptor: ClassifierDescriptor, type: KotlinType? = null): String {
val nameString = descriptor.name.render() + (type?.takeIf { it.isDefinitelyNotNullType }?.let { " & Any" } ?: "")
if (descriptor is TypeParameterDescriptor) {
return nameString
}
val qualifier = qualifierName(descriptor.containingDeclaration)
return if (qualifier != null && qualifier != "") "$qualifier.$nameString" else nameString
}
private fun qualifierName(descriptor: DeclarationDescriptor): String? = when (descriptor) {
is ClassDescriptor -> qualifiedNameForSourceCode(descriptor)
is PackageFragmentDescriptor -> descriptor.fqName.toUnsafe().render()
else -> null
}
} | apache-2.0 | 70dd0d26bb20fe55bdb7f4895e5c85e9 | 43.5 | 158 | 0.760024 | 5.217116 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/UnfoldReturnToIfIntention.kt | 2 | 2986 | // 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.intentions.branchedTransformations.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.types.typeUtil.isNothing
class UnfoldReturnToIfIntention : LowPriorityAction, SelfTargetingRangeIntention<KtReturnExpression>(
KtReturnExpression::class.java, KotlinBundle.lazyMessage("replace.return.with.if.expression")
) {
override fun applicabilityRange(element: KtReturnExpression): TextRange? {
val ifExpression = element.returnedExpression as? KtIfExpression ?: return null
return TextRange(element.startOffset, ifExpression.ifKeyword.endOffset)
}
override fun applyTo(element: KtReturnExpression, editor: Editor?) {
val ifExpression = element.returnedExpression as KtIfExpression
val thenExpr = ifExpression.then!!.lastBlockStatementOrThis()
val elseExpr = ifExpression.`else`!!.lastBlockStatementOrThis()
val newIfExpression = ifExpression.copied()
val newThenExpr = newIfExpression.then!!.lastBlockStatementOrThis()
val newElseExpr = newIfExpression.`else`!!.lastBlockStatementOrThis()
val psiFactory = KtPsiFactory(element)
val context = element.analyze()
val labelName = element.getLabelName()
newThenExpr.replace(createReturnExpression(thenExpr, labelName, psiFactory, context))
newElseExpr.replace(createReturnExpression(elseExpr, labelName, psiFactory, context))
element.replace(newIfExpression)
}
companion object {
fun createReturnExpression(
expr: KtExpression,
labelName: String?,
psiFactory: KtPsiFactory,
context: BindingContext
): KtExpression {
val label = labelName?.let { "@$it" } ?: ""
val returnText = when (expr) {
is KtBreakExpression, is KtContinueExpression, is KtReturnExpression, is KtThrowExpression -> ""
else -> if (expr.getResolvedCall(context)?.resultingDescriptor?.returnType?.isNothing() == true) "" else "return$label "
}
return psiFactory.createExpressionByPattern("$returnText$0", expr)
}
}
} | apache-2.0 | 672e718faf39bb5ff5f0d9fd58b2e92e | 46.412698 | 158 | 0.743135 | 5.139415 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/i18n/LocaleBundle.kt | 1 | 1866 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.i18n
import com.acornui.di.Context
import com.acornui.di.ContextImpl
import com.acornui.logging.Log
import com.acornui.system.userInfo
/**
* Sets the default locale bundle to the given value.
* This should be set before any [string] bindings are made, the bundle name is not expected to change.
*/
fun ContextImpl.i18nBundle(bundleName: String) {
dependencies += I18N_BUNDLE to bundleName
}
/**
* The dependency key for getting the default locale bundle.
* This can be set with [ContextImpl.i18nBundle].
*/
val I18N_BUNDLE = object : Context.Key<String> {}
/**
* This context's resource bundle name. This may be set via [i18nBundle].
*/
val Context.i18nBundleName: String
get() = injectOptional(I18N_BUNDLE) ?: error("No default locale bundle set, use i18nBundle()")
/**
* Returns the String associated with the default bundle and current locale chain.
* @param key The
* @see i18nBundle
*/
suspend fun Context.string(key: String, bundleName: String = i18nBundleName, localeChain: List<Locale> = userInfo.systemLocale): String {
return inject(I18n).string(localeChain, bundleName, key) ?: "".also { Log.warn("i18n string not found. key='$key' bundle='$bundleName' localeChain='${localeChain.joinToString { it.value }}'") }
}
| apache-2.0 | c941b6d1d354037043272027e8ceebcd | 35.588235 | 194 | 0.739014 | 3.732 | false | false | false | false |
android/connectivity-samples | BluetoothAdvertisementsKotlin/app/src/main/java/com/example/bluetoothadvertisements/adapter/ScannerAdapter.kt | 1 | 3022 | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.bluetoothadvertisements.adapter
import android.bluetooth.le.ScanResult
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.bluetoothadvertisements.databinding.VhScanResultBinding
private const val TAG = "ScannerAdapter"
/**
* Adapter for displaying remote Bluetooth devices that are being advertised
*/
class ScannerAdapter : RecyclerView.Adapter<ScannerAdapter.ScanResultVh>() {
private var itemsList: MutableList<ScanResult> = arrayListOf()
fun setItems(mutableList: MutableList<ScanResult>) {
if (mutableList != itemsList) {
itemsList = mutableList
notifyDataSetChanged()
}
}
fun addSingleItem(item: ScanResult) {
/**
* In this particular case the data coming in may be duplicate. So check that only unique
* elements are admitted: the device Id + device name should create a unique pair.
* removeIf requires API level 24, so using removeAll here. But feel free to use any of
* a number of options. Remove the previous element so to keep the latest timestamp
*/
itemsList.removeAll {
it.device.name == item.device.name && it.device.address == item.device.address
}
itemsList.add(item)
notifyDataSetChanged()
}
override fun getItemCount() = itemsList.size
private fun getItem(position: Int): ScanResult? = if (itemsList.isEmpty()) null else itemsList[position]
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScanResultVh {
val binding =
VhScanResultBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ScanResultVh(binding)
}
override fun onBindViewHolder(holder: ScanResultVh, position: Int) {
Log.d(TAG, "onBindViewHolder: called for position $position")
holder.bind(getItem(position))
}
inner class ScanResultVh(private val binding: VhScanResultBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: ScanResult?) {
item?.let {
binding.deviceName.text = it.device.name
binding.deviceAddress.text = it.device.address
binding.lastSeen.text = it.timestampNanos.toString()
}
}
}
}
| apache-2.0 | 62085cf55c504c3915bb05d9e7256286 | 36.308642 | 108 | 0.695566 | 4.66358 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/collectors/CommonConstraintsCollector.kt | 2 | 6441 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.*
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.asAssignment
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class CommonConstraintsCollector : ConstraintsCollector() {
override fun ConstraintBuilder.collectConstraints(
element: KtElement,
boundTypeCalculator: BoundTypeCalculator,
inferenceContext: InferenceContext,
resolutionFacade: ResolutionFacade
) = with(boundTypeCalculator) {
when {
element is KtBinaryExpressionWithTypeRHS && KtPsiUtil.isUnsafeCast(element) -> {
element.right?.typeElement?.let { inferenceContext.typeElementToTypeVariable[it] }?.also { typeVariable ->
element.left.isSubtypeOf(typeVariable, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT)
}
}
element is KtBinaryExpression && element.asAssignment() != null -> {
element.right?.isSubtypeOf(element.left ?: return, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT)
}
element is KtVariableDeclaration -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.initializer?.isSubtypeOf(typeVariable, org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.INITIALIZER)
}
}
element is KtParameter -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.defaultValue?.isSubtypeOf(
typeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.INITIALIZER
)
}
}
element is KtReturnExpression -> {
val functionTypeVariable = element.getTargetFunction(element.analyze(resolutionFacade))
?.resolveToDescriptorIfAny(resolutionFacade)
?.let { functionDescriptor ->
inferenceContext.declarationDescriptorToTypeVariable[functionDescriptor]
} ?: return
element.returnedExpression?.isSubtypeOf(
functionTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
element is KtReturnExpression -> {
val targetTypeVariable =
element.getTargetFunction(element.analyze(resolutionFacade))?.let { function ->
inferenceContext.declarationToTypeVariable[function]
}
if (targetTypeVariable != null) {
element.returnedExpression?.isSubtypeOf(
targetTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
}
element is KtLambdaExpression -> {
val targetTypeVariable =
inferenceContext.declarationToTypeVariable[element.functionLiteral] ?: return
element.functionLiteral.bodyExpression?.statements?.lastOrNull()
?.takeIf { it !is KtReturnExpression }
?.also { implicitReturn ->
implicitReturn.isSubtypeOf(
targetTypeVariable,
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.RETURN
)
}
}
element is KtForExpression -> {
val loopParameterTypeVariable =
element.loopParameter?.typeReference?.typeElement?.let { typeElement ->
inferenceContext.typeElementToTypeVariable[typeElement]
}
if (loopParameterTypeVariable != null) {
val loopRangeBoundType = element.loopRange?.boundType(inferenceContext) ?: return
val boundType =
element.loopRangeElementType(resolutionFacade)
?.boundType(
contextBoundType = loopRangeBoundType,
inferenceContext = inferenceContext
) ?: return
boundType.typeParameters.firstOrNull()?.boundType?.isSubtypeOf(
loopParameterTypeVariable.asBoundType(),
org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.ConstraintPriority.ASSIGNMENT
)
}
}
}
Unit
}
private fun KtForExpression.loopRangeElementType(resolutionFacade: ResolutionFacade): KotlinType? {
val loopRangeType = loopRange?.getType(analyze(resolutionFacade)) ?: return null
return loopRangeType
.constructor
.declarationDescriptor
?.safeAs<ClassDescriptor>()
?.getMemberScope(loopRangeType.arguments)
?.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS) {
it.asString() == "iterator"
}?.filterIsInstance<FunctionDescriptor>()
?.firstOrNull { it.valueParameters.isEmpty() }
?.original
?.returnType
}
} | apache-2.0 | 1b0e608efce9f8f2dd72f8d931e76400 | 48.175573 | 161 | 0.626766 | 6.175455 | false | false | false | false |
ingokegel/intellij-community | platform/platform-impl/src/com/intellij/ide/plugins/DynamicPlugins.kt | 1 | 56905 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.plugins
import com.fasterxml.jackson.databind.type.TypeFactory
import com.intellij.application.options.RegistryManager
import com.intellij.configurationStore.jdomSerializer
import com.intellij.configurationStore.runInAutoSaveDisabledMode
import com.intellij.configurationStore.saveProjectsAndApp
import com.intellij.diagnostic.MessagePool
import com.intellij.diagnostic.PerformanceWatcher
import com.intellij.diagnostic.hprof.action.SystemTempFilenameSupplier
import com.intellij.diagnostic.hprof.analysis.AnalyzeClassloaderReferencesGraph
import com.intellij.diagnostic.hprof.analysis.HProfAnalysis
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.actions.RevealFileAction
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.runBlockingUnderModalProgress
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.ide.ui.TopHitCache
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.ide.util.TipAndTrickManager
import com.intellij.idea.IdeaLogger
import com.intellij.lang.Language
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.keymap.impl.BundledKeymapBean
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.PotemkinProgress
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.updateSettings.impl.UpdateChecker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.objectTree.ThrowableInterner
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.newvfs.FileAttribute
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.psi.util.CachedValuesManager
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.IconDeferrer
import com.intellij.ui.mac.touchbar.TouchbarSupport
import com.intellij.util.CachedValuesManagerImpl
import com.intellij.util.MemoryDumpHelper
import com.intellij.util.ReflectionUtil
import com.intellij.util.SystemProperties
import com.intellij.util.containers.WeakList
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.ref.GCWatcher
import net.sf.cglib.core.ClassNameReader
import java.awt.KeyboardFocusManager
import java.awt.Window
import java.nio.channels.FileChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.text.SimpleDateFormat
import java.util.*
import java.util.function.Predicate
import javax.swing.JComponent
import javax.swing.ToolTipManager
import kotlin.collections.component1
import kotlin.collections.component2
private val LOG = logger<DynamicPlugins>()
private val classloadersFromUnloadedPlugins = mutableMapOf<PluginId, WeakList<PluginClassLoader>>()
object DynamicPlugins {
@JvmStatic
@JvmOverloads
fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl,
baseDescriptor: IdeaPluginDescriptorImpl? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList()): Boolean {
val reason = checkCanUnloadWithoutRestart(module = descriptor, parentModule = baseDescriptor, context = context)
if (reason != null) {
LOG.info(reason)
}
return reason == null
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun loadPlugins(descriptors: Collection<IdeaPluginDescriptor>): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = true) {
loadPlugin(it, checkImplementationDetailDependencies = true)
}
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun unloadPlugins(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
parentComponent: JComponent? = null,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true),
): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = false) {
unloadPluginWithProgress(project, parentComponent, it, options)
}
}
private fun updateDescriptorsWithoutRestart(
plugins: Collection<IdeaPluginDescriptor>,
load: Boolean,
executor: (IdeaPluginDescriptorImpl) -> Boolean,
): Boolean {
if (plugins.isEmpty()) {
return true
}
val pluginSet = PluginManagerCore.getPluginSet()
@Suppress("UNCHECKED_CAST")
val descriptors = (plugins as Collection<IdeaPluginDescriptorImpl>).filter { pluginSet.isPluginEnabled(it.pluginId) != load }
val operationText = if (load) "load" else "unload"
val message = descriptors.joinToString(prefix = "Plugins to $operationText: [", postfix = "]")
LOG.info(message)
if (!descriptors.all { allowLoadUnloadWithoutRestart(it, context = descriptors) }) {
return false
}
// todo plugin installation should be done not in this method
var allPlugins = pluginSet.allPlugins
for (descriptor in descriptors) {
if (!allPlugins.contains(descriptor)) {
allPlugins = allPlugins + descriptor
}
}
// todo make internal:
// 1) ModuleGraphBase;
// 2) SortedModuleGraph;
// 3) SortedModuleGraph.topologicalComparator;
// 4) PluginSetBuilder.sortedModuleGraph.
var comparator = PluginSetBuilder(allPlugins)
.moduleGraph
.topologicalComparator
if (!load) {
comparator = comparator.reversed()
}
for (descriptor in descriptors.sortedWith(comparator)) {
descriptor.isEnabled = load
if (!executor.invoke(descriptor)) {
LOG.info("Failed to $operationText: $descriptor, restart required")
InstalledPluginsState.getInstance().isRestartRequired = true
return false
}
}
return true
}
fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl): String? {
return checkCanUnloadWithoutRestart(module, parentModule = null)
}
/**
* @param context Plugins which are being loaded at the same time as [module]
*/
private fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl,
parentModule: IdeaPluginDescriptorImpl?,
optionalDependencyPluginId: PluginId? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList(),
checkImplementationDetailDependencies: Boolean = true): String? {
if (parentModule == null) {
if (module.isRequireRestart) {
return "Plugin ${module.pluginId} is explicitly marked as requiring restart"
}
if (module.productCode != null && !module.isBundled && !PluginManagerCore.isDevelopedByJetBrains(module)) {
return "Plugin ${module.pluginId} is a paid plugin"
}
if (InstalledPluginsState.getInstance().isRestartRequired) {
return InstalledPluginsState.RESTART_REQUIRED_MESSAGE
}
}
val pluginSet = PluginManagerCore.getPluginSet()
if (classloadersFromUnloadedPlugins[module.pluginId]?.isEmpty() == false) {
return "Not allowing load/unload of ${module.pluginId} because of incomplete previous unload operation for that plugin"
}
findMissingRequiredDependency(module, context, pluginSet)?.let { pluginDependency ->
return "Required dependency ${pluginDependency} of plugin ${module.pluginId} is not currently loaded"
}
val app = ApplicationManager.getApplication()
if (parentModule == null) {
if (!RegistryManager.getInstance().`is`("ide.plugins.allow.unload")) {
if (!allowLoadUnloadSynchronously(module)) {
return "ide.plugins.allow.unload is disabled and synchronous load/unload is not possible for ${module.pluginId}"
}
return null
}
try {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(module)
}
catch (e: CannotUnloadPluginException) {
return e.cause?.localizedMessage ?: "checkUnloadPlugin listener blocked plugin unload"
}
}
if (!Registry.`is`("ide.plugins.allow.unload.from.sources")) {
if (pluginSet.findEnabledPlugin(module.pluginId) != null && module === parentModule && !module.isUseIdeaClassLoader) {
val pluginClassLoader = module.pluginClassLoader
if (pluginClassLoader != null && pluginClassLoader !is PluginClassLoader && !app.isUnitTestMode) {
return "Plugin ${module.pluginId} is not unload-safe because of use of ${pluginClassLoader.javaClass.name} as the default class loader. " +
"For example, the IDE is started from the sources with the plugin."
}
}
}
val epNameToExtensions = module.epNameToExtensions
if (epNameToExtensions != null) {
doCheckExtensionsCanUnloadWithoutRestart(
extensions = epNameToExtensions,
descriptor = module,
baseDescriptor = parentModule,
app = app,
optionalDependencyPluginId = optionalDependencyPluginId,
context = context,
pluginSet = pluginSet,
)?.let { return it }
}
checkNoComponentsOrServiceOverrides(module)?.let { return it }
ActionManagerImpl.checkUnloadActions(module)?.let { return it }
for (moduleRef in module.content.modules) {
if (pluginSet.isModuleEnabled(moduleRef.name)) {
val subModule = moduleRef.requireDescriptor()
checkCanUnloadWithoutRestart(module = subModule,
parentModule = module,
optionalDependencyPluginId = null,
context = context)?.let {
return "$it in optional dependency on ${subModule.pluginId}"
}
}
}
for (dependency in module.pluginDependencies) {
if (pluginSet.isPluginEnabled(dependency.pluginId)) {
checkCanUnloadWithoutRestart(dependency.subDescriptor ?: continue, parentModule ?: module, null, context)?.let {
return "$it in optional dependency on ${dependency.pluginId}"
}
}
}
// if not a sub plugin descriptor, then check that any dependent plugin also reloadable
if (parentModule != null && module !== parentModule) {
return null
}
var dependencyMessage: String? = null
processOptionalDependenciesOnPlugin(module, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
if (subDescriptor.packagePrefix == null
|| mainDescriptor.pluginId.idString == "org.jetbrains.kotlin" || mainDescriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID) {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId}" +
" does not have a separate classloader for the dependency"
return@processOptionalDependenciesOnPlugin false
}
dependencyMessage = checkCanUnloadWithoutRestart(subDescriptor, mainDescriptor, subDescriptor.pluginId, context)
if (dependencyMessage == null) {
true
}
else {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId} requires restart: $dependencyMessage"
false
}
}
if (dependencyMessage == null && checkImplementationDetailDependencies) {
val contextWithImplementationDetails = context.toMutableList()
contextWithImplementationDetails.add(module)
processImplementationDetailDependenciesOnPlugin(module, pluginSet, contextWithImplementationDetails::add)
processImplementationDetailDependenciesOnPlugin(module, pluginSet) { dependentDescriptor ->
// don't check a plugin that is an implementation-detail dependency on the current plugin if it has other disabled dependencies
// and won't be loaded anyway
if (findMissingRequiredDependency(dependentDescriptor, contextWithImplementationDetails, pluginSet) == null) {
dependencyMessage = checkCanUnloadWithoutRestart(module = dependentDescriptor,
parentModule = null,
context = contextWithImplementationDetails,
checkImplementationDetailDependencies = false)
if (dependencyMessage != null) {
dependencyMessage = "implementation-detail plugin ${dependentDescriptor.pluginId} which depends on ${module.pluginId}" +
" requires restart: $dependencyMessage"
}
}
dependencyMessage == null
}
}
return dependencyMessage
}
private fun findMissingRequiredDependency(descriptor: IdeaPluginDescriptorImpl,
context: List<IdeaPluginDescriptorImpl>,
pluginSet: PluginSet): PluginId? {
for (dependency in descriptor.pluginDependencies) {
if (!dependency.isOptional &&
!PluginManagerCore.isModuleDependency(dependency.pluginId) &&
!pluginSet.isPluginEnabled(dependency.pluginId) &&
context.none { it.pluginId == dependency.pluginId }) {
return dependency.pluginId
}
}
return null
}
/**
* Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the
* plugins settings, without pressing the Apply button.
*/
@JvmStatic
fun allowLoadUnloadSynchronously(module: IdeaPluginDescriptorImpl): Boolean {
val extensions = (module.unsortedEpNameToExtensionElements.takeIf { it.isNotEmpty() } ?: module.appContainerDescriptor.extensions)
if (extensions != null && !extensions.all {
it.key == UIThemeProvider.EP_NAME.name ||
it.key == BundledKeymapBean.EP_NAME.name
}) {
return false
}
return checkNoComponentsOrServiceOverrides(module) == null && module.actions.isEmpty()
}
private fun checkNoComponentsOrServiceOverrides(module: IdeaPluginDescriptorImpl): String? {
val id = module.pluginId
return checkNoComponentsOrServiceOverrides(id, module.appContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.projectContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.moduleContainerDescriptor)
}
private fun checkNoComponentsOrServiceOverrides(pluginId: PluginId?, containerDescriptor: ContainerDescriptor): String? {
if (!containerDescriptor.components.isNullOrEmpty()) {
return "Plugin $pluginId is not unload-safe because it declares components"
}
if (containerDescriptor.services.any { it.overrides }) {
return "Plugin $pluginId is not unload-safe because it overrides services"
}
return null
}
fun unloadPluginWithProgress(project: Project? = null,
parentComponent: JComponent?,
pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions): Boolean {
var result = false
if (!allowLoadUnloadSynchronously(pluginDescriptor)) {
runInAutoSaveDisabledMode {
val saveAndSyncHandler = SaveAndSyncHandler.getInstance()
saveAndSyncHandler.saveSettingsUnderModalProgress(ApplicationManager.getApplication())
for (openProject in ProjectUtil.getOpenProjects()) {
saveAndSyncHandler.saveSettingsUnderModalProgress(openProject)
}
}
}
val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.unloading.plugin.title", pluginDescriptor.name),
project,
parentComponent,
null)
indicator.runInSwingThread {
result = unloadPlugin(pluginDescriptor, options.withSave(false))
}
return result
}
data class UnloadPluginOptions(
var disable: Boolean = true,
var isUpdate: Boolean = false,
var save: Boolean = true,
var requireMemorySnapshot: Boolean = false,
var waitForClassloaderUnload: Boolean = false,
var checkImplementationDetailDependencies: Boolean = true,
var unloadWaitTimeout: Int? = null,
) {
fun withUpdate(isUpdate: Boolean): UnloadPluginOptions = also {
this.isUpdate = isUpdate
}
fun withWaitForClassloaderUnload(waitForClassloaderUnload: Boolean) = also {
this.waitForClassloaderUnload = waitForClassloaderUnload
}
fun withDisable(disable: Boolean) = also {
this.disable = disable
}
fun withRequireMemorySnapshot(requireMemorySnapshot: Boolean) = also {
this.requireMemorySnapshot = requireMemorySnapshot
}
fun withUnloadWaitTimeout(unloadWaitTimeout: Int) = also {
this.unloadWaitTimeout = unloadWaitTimeout
}
fun withSave(save: Boolean) = also {
this.save = save
}
fun withCheckImplementationDetailDependencies(checkImplementationDetailDependencies: Boolean) = also {
this.checkImplementationDetailDependencies = checkImplementationDetailDependencies
}
}
@JvmOverloads
fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean {
val app = ApplicationManager.getApplication() as ApplicationImpl
val pluginId = pluginDescriptor.pluginId
val pluginSet = PluginManagerCore.getPluginSet()
if (options.checkImplementationDetailDependencies) {
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
dependentDescriptor.isEnabled = false
unloadPlugin(dependentDescriptor, UnloadPluginOptions(save = false,
waitForClassloaderUnload = false,
checkImplementationDetailDependencies = false))
true
}
}
try {
if (options.save) {
runInAutoSaveDisabledMode {
FileDocumentManager.getInstance().saveAllDocuments()
runBlockingUnderModalProgress {
saveProjectsAndApp(true)
}
}
}
TipAndTrickManager.getInstance().closeTipDialog()
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, options.isUpdate)
IdeEventQueue.getInstance().flushQueue()
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
logDescriptorUnload(pluginDescriptor, success = false)
return false
}
var classLoaderUnloaded: Boolean
val classLoaders = WeakList<PluginClassLoader>()
try {
app.runWriteAction {
// must be after flushQueue (e.g. https://youtrack.jetbrains.com/issue/IDEA-252010)
val forbidGettingServicesToken = app.forbidGettingServices("Plugin $pluginId being unloaded.")
try {
(pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.let {
classLoaders.add(it)
}
// https://youtrack.jetbrains.com/issue/IDEA-245031
// mark plugin classloaders as being unloaded to ensure that new extension instances will be not created during unload
setClassLoaderState(pluginDescriptor, PluginClassLoader.UNLOAD_IN_PROGRESS)
unloadLoadedOptionalDependenciesOnPlugin(pluginDescriptor, pluginSet = pluginSet, classLoaders = classLoaders)
unloadDependencyDescriptors(pluginDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(pluginDescriptor)
clearPluginClassLoaderParentListCache(pluginSet)
app.extensionArea.clearUserCache()
for (project in ProjectUtil.getOpenProjects()) {
(project.extensionArea as ExtensionsAreaImpl).clearUserCache()
}
clearCachedValues()
jdomSerializer.clearSerializationCaches()
TypeFactory.defaultInstance().clearCache()
app.getServiceIfCreated(TopHitCache::class.java)?.clear()
ActionToolbarImpl.resetAllToolbars()
PresentationFactory.clearPresentationCaches()
TouchbarSupport.reloadAllActions()
(serviceIfCreated<NotificationsManager>() as? NotificationsManagerImpl)?.expireAll()
MessagePool.getInstance().clearErrors()
LaterInvocator.purgeExpiredItems()
FileAttribute.resetRegisteredIds()
resetFocusCycleRoot()
clearNewFocusOwner()
hideTooltip()
PerformanceWatcher.getInstance().clearFreezeStacktraces()
for (classLoader in classLoaders) {
IconLoader.detachClassLoader(classLoader)
Language.unregisterAllLanguagesIn(classLoader, pluginDescriptor)
}
serviceIfCreated<IconDeferrer>()?.clearCache()
(ApplicationManager.getApplication().messageBus as MessageBusEx).clearPublisherCache()
@Suppress("TestOnlyProblems")
(ProjectManager.getInstanceIfCreated() as? ProjectManagerImpl)?.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests()
val newPluginSet = pluginSet.withoutModule(
module = pluginDescriptor,
disable = options.disable,
).createPluginSetWithEnabledModulesMap()
PluginManagerCore.setPluginSet(newPluginSet)
}
finally {
try {
forbidGettingServicesToken.finish()
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, options.isUpdate)
}
}
}
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
}
finally {
IdeEventQueue.getInstance().flushQueue()
// do it after IdeEventQueue.flushQueue() to ensure that Disposer.isDisposed(...) works as expected in flushed tasks.
Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces
ThrowableInterner.clearInternedBacktraces()
IdeaLogger.ourErrorsOccurred = null // ensure we don't have references to plugin classes in exception stacktraces
clearTemporaryLostComponent()
clearCglibStopBacktrace()
if (app.isUnitTestMode && pluginDescriptor.pluginClassLoader !is PluginClassLoader) {
classLoaderUnloaded = true
}
else {
classloadersFromUnloadedPlugins[pluginId] = classLoaders
ClassLoaderTreeChecker(pluginDescriptor, classLoaders).checkThatClassLoaderNotReferencedByPluginClassLoader()
val checkClassLoaderUnload = options.waitForClassloaderUnload ||
options.requireMemorySnapshot ||
Registry.`is`("ide.plugins.snapshot.on.unload.fail")
val timeout = if (checkClassLoaderUnload) {
options.unloadWaitTimeout ?: Registry.intValue("ide.plugins.unload.timeout", 5000)
}
else {
0
}
classLoaderUnloaded = unloadClassLoader(pluginDescriptor, timeout)
if (classLoaderUnloaded) {
LOG.info("Successfully unloaded plugin $pluginId (classloader unload checked=$checkClassLoaderUnload)")
classloadersFromUnloadedPlugins.remove(pluginId)
}
else {
if ((options.requireMemorySnapshot || (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && !app.isUnitTestMode)) &&
MemoryDumpHelper.memoryDumpAvailable()) {
classLoaderUnloaded = saveMemorySnapshot(pluginId)
}
else {
LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded")
}
}
if (!classLoaderUnloaded) {
InstalledPluginsState.getInstance().isRestartRequired = true
}
logDescriptorUnload(pluginDescriptor, success = classLoaderUnloaded)
}
}
if (!classLoaderUnloaded) {
setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.ACTIVE)
}
ActionToolbarImpl.updateAllToolbarsImmediately(true)
return classLoaderUnloaded
}
private fun resetFocusCycleRoot() {
val focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
var focusCycleRoot = focusManager.currentFocusCycleRoot
if (focusCycleRoot != null) {
while (focusCycleRoot != null && focusCycleRoot !is IdeFrameImpl) {
focusCycleRoot = focusCycleRoot.parent
}
if (focusCycleRoot is IdeFrameImpl) {
focusManager.setGlobalCurrentFocusCycleRoot(focusCycleRoot)
}
else {
focusCycleRoot = focusManager.currentFocusCycleRoot
val dataContext = DataManager.getInstance().getDataContext(focusCycleRoot)
val project = CommonDataKeys.PROJECT.getData(dataContext)
if (project != null) {
val projectFrame = WindowManager.getInstance().getFrame(project)
if (projectFrame != null) {
focusManager.setGlobalCurrentFocusCycleRoot(projectFrame)
}
}
}
}
}
private fun unloadLoadedOptionalDependenciesOnPlugin(dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
val dependencyClassloader = dependencyPlugin.classLoader
processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
val classLoader = subDescriptor.classLoader
unloadModuleDescriptorNotRecursively(subDescriptor)
// this additional code is required because in unit tests PluginClassLoader is not used
if (mainDescriptor !== subDescriptor) {
subDescriptor.pluginClassLoader = null
}
if (dependencyClassloader is PluginClassLoader && classLoader is PluginClassLoader) {
LOG.info("Detach classloader $dependencyClassloader from $classLoader")
if (mainDescriptor !== subDescriptor && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
classLoader.state = PluginClassLoader.UNLOAD_IN_PROGRESS
}
}
true
}
}
private fun unloadDependencyDescriptors(plugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
for (dependency in plugin.pluginDependencies) {
val subDescriptor = dependency.subDescriptor ?: continue
val classLoader = subDescriptor.pluginClassLoader
if (!pluginSet.isPluginEnabled(dependency.pluginId)) {
LOG.assertTrue(classLoader == null,
"Expected not to have any sub descriptor classloader when dependency ${dependency.pluginId} is not loaded")
continue
}
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
}
unloadDependencyDescriptors(subDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
for (module in plugin.content.modules) {
val subDescriptor = module.requireDescriptor()
val classLoader = subDescriptor.pluginClassLoader ?: continue
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
}
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
}
internal fun notify(@NlsContexts.NotificationContent text: String, notificationType: NotificationType, vararg actions: AnAction) {
val notification = UpdateChecker.getNotificationGroupForPluginUpdateResults().createNotification(text, notificationType)
for (action in actions) {
notification.addAction(action)
}
notification.notify(null)
}
// PluginId cannot be used to unload related resources because one plugin descriptor may consist of several sub descriptors,
// each of them depends on presense of another plugin, here not the whole plugin is unloaded, but only one part.
private fun unloadModuleDescriptorNotRecursively(module: IdeaPluginDescriptorImpl) {
val app = ApplicationManager.getApplication() as ApplicationImpl
(ActionManager.getInstance() as ActionManagerImpl).unloadActions(module)
val openedProjects = ProjectUtil.getOpenProjects().asList()
val appExtensionArea = app.extensionArea
val priorityUnloadListeners = mutableListOf<Runnable>()
val unloadListeners = mutableListOf<Runnable>()
unregisterUnknownLevelExtensions(module.unsortedEpNameToExtensionElements, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (epName in (module.appContainerDescriptor.extensions?.keys ?: emptySet())) {
appExtensionArea.unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners)
}
for (epName in (module.projectContainerDescriptor.extensions?.keys ?: emptySet())) {
for (project in openedProjects) {
(project.extensionArea as ExtensionsAreaImpl).unregisterExtensions(epName, module, priorityUnloadListeners,
unloadListeners)
}
}
// not an error - unsorted goes to module level, see registerExtensions
unregisterUnknownLevelExtensions(module.moduleContainerDescriptor.extensions, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (priorityUnloadListener in priorityUnloadListeners) {
priorityUnloadListener.run()
}
for (unloadListener in unloadListeners) {
unloadListener.run()
}
// first, reset all plugin extension points before unregistering, so that listeners don't see plugin in semi-torn-down state
processExtensionPoints(module, openedProjects) { points, area ->
area.resetExtensionPoints(points, module)
}
// unregister plugin extension points
processExtensionPoints(module, openedProjects) { points, area ->
area.unregisterExtensionPoints(points, module)
}
val pluginId = module.pluginId
app.unloadServices(module.appContainerDescriptor.services, pluginId)
val appMessageBus = app.messageBus as MessageBusEx
module.appContainerDescriptor.listeners?.let { appMessageBus.unsubscribeLazyListeners(module, it) }
for (project in openedProjects) {
(project as ComponentManagerImpl).unloadServices(module.projectContainerDescriptor.services, pluginId)
module.projectContainerDescriptor.listeners?.let {
((project as ComponentManagerImpl).messageBus as MessageBusEx).unsubscribeLazyListeners(module, it)
}
val moduleServices = module.moduleContainerDescriptor.services
for (ideaModule in ModuleManager.getInstance(project).modules) {
(ideaModule as ComponentManagerImpl).unloadServices(moduleServices, pluginId)
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ideaModule, it) }
}
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(project, it) }
}
appMessageBus.disconnectPluginConnections(Predicate { aClass ->
(aClass.classLoader as? PluginClassLoader)?.pluginDescriptor === module
})
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ApplicationManager.getApplication(), it) }
}
private fun unregisterUnknownLevelExtensions(extensionMap: Map<String, List<ExtensionDescriptor>>?,
pluginDescriptor: IdeaPluginDescriptorImpl,
appExtensionArea: ExtensionsAreaImpl,
openedProjects: List<Project>,
priorityUnloadListeners: MutableList<Runnable>,
unloadListeners: MutableList<Runnable>) {
for (epName in (extensionMap?.keys ?: return)) {
val isAppLevelEp = appExtensionArea.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners,
unloadListeners)
if (isAppLevelEp) {
continue
}
for (project in openedProjects) {
val isProjectLevelEp = (project.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
if (!isProjectLevelEp) {
for (module in ModuleManager.getInstance(project).modules) {
(module.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
}
}
}
}
}
private inline fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl,
projects: List<Project>,
processor: (points: List<ExtensionPointDescriptor>, area: ExtensionsAreaImpl) -> Unit) {
pluginDescriptor.appContainerDescriptor.extensionPoints?.let {
processor(it, ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
}
pluginDescriptor.projectContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
processor(extensionPoints, project.extensionArea as ExtensionsAreaImpl)
}
}
pluginDescriptor.moduleContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
for (module in ModuleManager.getInstance(project).modules) {
processor(extensionPoints, module.extensionArea as ExtensionsAreaImpl)
}
}
}
}
fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean {
return loadPlugin(pluginDescriptor, checkImplementationDetailDependencies = true)
}
private fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, checkImplementationDetailDependencies: Boolean = true): Boolean {
if (classloadersFromUnloadedPlugins[pluginDescriptor.pluginId]?.isEmpty() == false) {
LOG.info("Requiring restart for loading plugin ${pluginDescriptor.pluginId}" +
" because previous version of the plugin wasn't fully unloaded")
return false
}
val loadStartTime = System.currentTimeMillis()
val pluginSet = PluginManagerCore.getPluginSet()
.withModule(pluginDescriptor)
.createPluginSetWithEnabledModulesMap()
val classLoaderConfigurator = ClassLoaderConfigurator(pluginSet)
// todo loadPlugin should be called per each module, temporary solution
val pluginWithContentModules = pluginSet.getEnabledModules()
.filter { it.pluginId == pluginDescriptor.pluginId }
.filter(classLoaderConfigurator::configureModule)
.toList()
val app = ApplicationManager.getApplication() as ApplicationImpl
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor)
app.runWriteAction {
try {
PluginManagerCore.setPluginSet(pluginSet)
val listenerCallbacks = mutableListOf<Runnable>()
// 4. load into service container
loadModules(pluginWithContentModules, app, listenerCallbacks)
loadModules(
optionalDependenciesOnPlugin(pluginDescriptor, classLoaderConfigurator, pluginSet),
app,
listenerCallbacks,
)
clearPluginClassLoaderParentListCache(pluginSet)
clearCachedValues()
listenerCallbacks.forEach(Runnable::run)
logDescriptorLoad(pluginDescriptor)
LOG.info("Plugin ${pluginDescriptor.pluginId} loaded without restart in ${System.currentTimeMillis() - loadStartTime} ms")
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor)
}
}
if (checkImplementationDetailDependencies) {
var implementationDetailsLoadedWithoutRestart = true
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
val dependencies = dependentDescriptor.pluginDependencies
if (dependencies.all { it.isOptional || PluginManagerCore.getPlugin(it.pluginId) != null }) {
if (!loadPlugin(dependentDescriptor, checkImplementationDetailDependencies = false)) {
implementationDetailsLoadedWithoutRestart = false
}
}
implementationDetailsLoadedWithoutRestart
}
return implementationDetailsLoadedWithoutRestart
}
return true
}
fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable)
.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
callback.run()
}
})
}
}
private fun clearTemporaryLostComponent() {
try {
val clearMethod = Window::class.java.declaredMethods.find { it.name == "setTemporaryLostComponent" }
if (clearMethod == null) {
LOG.info("setTemporaryLostComponent method not found")
return
}
clearMethod.isAccessible = true
loop@ for (frame in WindowManager.getInstance().allProjectFrames) {
val window = when (frame) {
is ProjectFrameHelper -> frame.frameOrNull
is Window -> frame
else -> continue@loop
}
clearMethod.invoke(window, null)
}
}
catch (e: Throwable) {
LOG.info("Failed to clear Window.temporaryLostComponent", e)
}
}
private fun hideTooltip() {
try {
val showMethod = ToolTipManager::class.java.declaredMethods.find { it.name == "show" }
if (showMethod == null) {
LOG.info("ToolTipManager.show method not found")
return
}
showMethod.isAccessible = true
showMethod.invoke(ToolTipManager.sharedInstance(), null)
}
catch (e: Throwable) {
LOG.info("Failed to hide tooltip", e)
}
}
private fun clearCglibStopBacktrace() {
val field = ReflectionUtil.getDeclaredField(ClassNameReader::class.java, "EARLY_EXIT")
if (field != null) {
try {
ThrowableInterner.clearBacktrace((field[null] as Throwable))
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun clearNewFocusOwner() {
val field = ReflectionUtil.getDeclaredField(KeyboardFocusManager::class.java, "newFocusOwner")
if (field != null) {
try {
field.set(null, null)
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun saveMemorySnapshot(pluginId: PluginId): Boolean {
val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date())
val snapshotFileName = "unload-$pluginId-$snapshotDate.hprof"
val snapshotPath = System.getProperty("memory.snapshots.path", SystemProperties.getUserHome()) + "/" + snapshotFileName
MemoryDumpHelper.captureMemoryDump(snapshotPath)
if (classloadersFromUnloadedPlugins[pluginId]?.isEmpty() != false) {
LOG.info("Successfully unloaded plugin $pluginId (classloader collected during memory snapshot generation)")
return true
}
if (Registry.`is`("ide.plugins.analyze.snapshot")) {
val analysisResult = analyzeSnapshot(snapshotPath, pluginId)
@Suppress("ReplaceSizeZeroCheckWithIsEmpty")
if (analysisResult.length == 0) {
LOG.info("Successfully unloaded plugin $pluginId (no strong references to classloader in .hprof file)")
classloadersFromUnloadedPlugins.remove(pluginId)
return true
}
else {
LOG.info("Snapshot analysis result: $analysisResult")
}
}
DynamicPlugins.notify(
IdeBundle.message("memory.snapshot.captured.text", snapshotPath, snapshotFileName),
NotificationType.WARNING,
object : AnAction(IdeBundle.message("ide.restart.action")), DumbAware {
override fun actionPerformed(e: AnActionEvent) = ApplicationManager.getApplication().restart()
},
object : AnAction(
IdeBundle.message("memory.snapshot.captured.action.text", snapshotFileName, RevealFileAction.getFileManagerName())), DumbAware {
override fun actionPerformed(e: AnActionEvent) = RevealFileAction.openFile(Paths.get(snapshotPath))
}
)
LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded. Memory snapshot created at $snapshotPath")
return false
}
private fun processImplementationDetailDependenciesOnPlugin(pluginDescriptor: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
processor: (descriptor: IdeaPluginDescriptorImpl) -> Boolean) {
processDependenciesOnPlugin(dependencyPlugin = pluginDescriptor,
pluginSet = pluginSet,
loadStateFilter = LoadStateFilter.ANY,
onlyOptional = false) { _, module ->
if (module.isImplementationDetail) {
processor(module)
}
else {
true
}
}
}
/**
* Load all sub plugins that depend on specified [dependencyPlugin].
*/
private fun optionalDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
classLoaderConfigurator: ClassLoaderConfigurator,
pluginSet: PluginSet,
): Set<IdeaPluginDescriptorImpl> {
// 1. collect optional descriptors
val modulesToMain = LinkedHashMap<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>()
processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = false) { main, module ->
modulesToMain[module] = main
true
}
if (modulesToMain.isEmpty()) {
return emptySet()
}
// 2. sort topologically
val topologicalComparator = PluginSetBuilder(modulesToMain.values)
.moduleGraph
.topologicalComparator
return modulesToMain.toSortedMap(topologicalComparator)
.filter { (moduleDescriptor, mainDescriptor) ->
// 3. setup classloaders
classLoaderConfigurator.configureDependency(mainDescriptor, moduleDescriptor)
}.keys
}
private fun loadModules(
modules: Collection<IdeaPluginDescriptorImpl>,
app: ApplicationImpl,
listenerCallbacks: MutableList<Runnable>,
) {
fun registerComponents(componentManager: ComponentManager) {
(componentManager as ComponentManagerImpl).registerComponents(
modules = modules.toList(),
app = app,
precomputedExtensionModel = null,
listenerCallbacks = listenerCallbacks,
)
}
registerComponents(app)
for (openProject in ProjectUtil.getOpenProjects()) {
registerComponents(openProject)
for (module in ModuleManager.getInstance(openProject).modules) {
registerComponents(module)
}
}
(ActionManager.getInstance() as ActionManagerImpl).registerActions(modules)
}
private fun analyzeSnapshot(hprofPath: String, pluginId: PluginId): String {
FileChannel.open(Paths.get(hprofPath), StandardOpenOption.READ).use { channel ->
val analysis = HProfAnalysis(channel, SystemTempFilenameSupplier()) { analysisContext, progressIndicator ->
AnalyzeClassloaderReferencesGraph(analysisContext, pluginId.idString).analyze(progressIndicator)
}
analysis.onlyStrongReferences = true
analysis.includeClassesAsRoots = false
analysis.setIncludeMetaInfo(false)
return analysis.analyze(ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator())
}
}
private fun createDisposeTreePredicate(pluginDescriptor: IdeaPluginDescriptorImpl): Predicate<Disposable>? {
val classLoader = pluginDescriptor.pluginClassLoader as? PluginClassLoader
?: return null
return Predicate {
if (it is PluginManager.PluginAwareDisposable) {
it.classLoaderId == classLoader.instanceId
}
else {
it::class.java.classLoader === classLoader
}
}
}
private fun processOptionalDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
isLoaded: Boolean,
processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean,
) {
processDependenciesOnPlugin(
dependencyPlugin = dependencyPlugin,
pluginSet = pluginSet,
onlyOptional = true,
loadStateFilter = if (isLoaded) LoadStateFilter.LOADED else LoadStateFilter.NOT_LOADED,
processor = processor,
)
}
private fun processDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
loadStateFilter: LoadStateFilter,
onlyOptional: Boolean,
processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean,
) {
val wantedIds = HashSet<String>(1 + dependencyPlugin.content.modules.size)
wantedIds.add(dependencyPlugin.pluginId.idString)
for (module in dependencyPlugin.content.modules) {
wantedIds.add(module.name)
}
for (plugin in pluginSet.enabledPlugins) {
if (plugin === dependencyPlugin) {
continue
}
if (!processOptionalDependenciesInOldFormatOnPlugin(dependencyPluginId = dependencyPlugin.pluginId,
mainDescriptor = plugin,
loadStateFilter = loadStateFilter,
onlyOptional = onlyOptional,
processor = processor)) {
return
}
for (moduleItem in plugin.content.modules) {
val module = moduleItem.requireDescriptor()
if (loadStateFilter != LoadStateFilter.ANY) {
val isModuleLoaded = module.pluginClassLoader != null
if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) {
continue
}
}
for (item in module.dependencies.modules) {
if (wantedIds.contains(item.name) && !processor(plugin, module)) {
return
}
}
for (item in module.dependencies.plugins) {
if (dependencyPlugin.pluginId == item.id && !processor(plugin, module)) {
return
}
}
}
}
}
private enum class LoadStateFilter {
LOADED, NOT_LOADED, ANY
}
private fun processOptionalDependenciesInOldFormatOnPlugin(
dependencyPluginId: PluginId,
mainDescriptor: IdeaPluginDescriptorImpl,
loadStateFilter: LoadStateFilter,
onlyOptional: Boolean,
processor: (main: IdeaPluginDescriptorImpl, sub: IdeaPluginDescriptorImpl) -> Boolean
): Boolean {
for (dependency in mainDescriptor.pluginDependencies) {
if (!dependency.isOptional) {
if (!onlyOptional && dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, mainDescriptor)) {
return false
}
continue
}
val subDescriptor = dependency.subDescriptor ?: continue
if (loadStateFilter != LoadStateFilter.ANY) {
val isModuleLoaded = subDescriptor.pluginClassLoader != null
if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) {
continue
}
}
if (dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, subDescriptor)) {
return false
}
if (!processOptionalDependenciesInOldFormatOnPlugin(
dependencyPluginId = dependencyPluginId,
mainDescriptor = subDescriptor,
loadStateFilter = loadStateFilter,
onlyOptional = onlyOptional,
processor = processor)) {
return false
}
}
return true
}
private fun doCheckExtensionsCanUnloadWithoutRestart(
extensions: Map<String, List<ExtensionDescriptor>>,
descriptor: IdeaPluginDescriptorImpl,
baseDescriptor: IdeaPluginDescriptorImpl?,
app: Application,
optionalDependencyPluginId: PluginId?,
context: List<IdeaPluginDescriptorImpl>,
pluginSet: PluginSet,
): String? {
val firstProject = ProjectUtil.getOpenProjects().firstOrNull()
val anyProject = firstProject ?: ProjectManager.getInstance().defaultProject
val anyModule = firstProject?.let { ModuleManager.getInstance(it).modules.firstOrNull() }
val seenPlugins: MutableSet<IdeaPluginDescriptorImpl> = Collections.newSetFromMap(IdentityHashMap())
epLoop@ for (epName in extensions.keys) {
seenPlugins.clear()
fun getNonDynamicUnloadError(optionalDependencyPluginId: PluginId?): String = optionalDependencyPluginId?.let {
"Plugin ${baseDescriptor?.pluginId} is not unload-safe because of use of non-dynamic EP $epName in plugin $it that optionally depends on it"
} ?: "Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName"
val result = findLoadedPluginExtensionPointRecursive(
pluginDescriptor = baseDescriptor ?: descriptor,
epName = epName,
pluginSet = pluginSet,
context = context,
seenPlugins = seenPlugins,
)
if (result != null) {
val (pluginExtensionPoint, foundInDependencies) = result // descriptor.pluginId is null when we check the optional dependencies of the plugin which is being loaded
// if an optional dependency of a plugin extends a non-dynamic EP of that plugin, it shouldn't prevent plugin loading
if (!pluginExtensionPoint.isDynamic) {
if (baseDescriptor == null || foundInDependencies) {
return getNonDynamicUnloadError(null)
}
else if (descriptor === baseDescriptor) {
return getNonDynamicUnloadError(descriptor.pluginId)
}
}
continue
}
@Suppress("RemoveExplicitTypeArguments") val ep = app.extensionArea.getExtensionPointIfRegistered<Any>(epName)
?: anyProject.extensionArea.getExtensionPointIfRegistered<Any>(epName)
?: anyModule?.extensionArea?.getExtensionPointIfRegistered<Any>(epName)
if (ep != null) {
if (!ep.isDynamic) {
return getNonDynamicUnloadError(optionalDependencyPluginId)
}
continue
}
if (anyModule == null) {
val corePlugin = pluginSet.findEnabledPlugin(PluginManagerCore.CORE_ID)
if (corePlugin != null) {
val coreEP = findPluginExtensionPoint(corePlugin, epName)
if (coreEP != null) {
if (!coreEP.isDynamic) {
return getNonDynamicUnloadError(optionalDependencyPluginId)
}
continue
}
}
}
for (contextPlugin in context) {
val contextEp = findPluginExtensionPoint(contextPlugin, epName) ?: continue
if (!contextEp.isDynamic) {
return getNonDynamicUnloadError(null)
}
continue@epLoop
}
// special case Kotlin EPs registered via code in Kotlin compiler
if (epName.startsWith("org.jetbrains.kotlin") && descriptor.pluginId.idString == "org.jetbrains.kotlin") {
continue
}
return "Plugin ${descriptor.pluginId} is not unload-safe because of unresolved extension $epName"
}
return null
}
private fun findPluginExtensionPoint(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String): ExtensionPointDescriptor? {
fun findContainerExtensionPoint(containerDescriptor: ContainerDescriptor): ExtensionPointDescriptor? {
return containerDescriptor.extensionPoints?.find { it.nameEquals(epName, pluginDescriptor) }
}
return findContainerExtensionPoint(pluginDescriptor.appContainerDescriptor)
?: findContainerExtensionPoint(pluginDescriptor.projectContainerDescriptor)
?: findContainerExtensionPoint(pluginDescriptor.moduleContainerDescriptor)
}
private fun findLoadedPluginExtensionPointRecursive(pluginDescriptor: IdeaPluginDescriptorImpl,
epName: String,
pluginSet: PluginSet,
context: List<IdeaPluginDescriptorImpl>,
seenPlugins: MutableSet<IdeaPluginDescriptorImpl>): Pair<ExtensionPointDescriptor, Boolean>? {
if (!seenPlugins.add(pluginDescriptor)) {
return null
}
findPluginExtensionPoint(pluginDescriptor, epName)?.let { return it to false }
for (dependency in pluginDescriptor.pluginDependencies) {
if (pluginSet.isPluginEnabled(dependency.pluginId) || context.any { it.pluginId == dependency.pluginId }) {
dependency.subDescriptor?.let { subDescriptor ->
findLoadedPluginExtensionPointRecursive(subDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it }
}
pluginSet.findEnabledPlugin(dependency.pluginId)?.let { dependencyDescriptor ->
findLoadedPluginExtensionPointRecursive(dependencyDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it.first to true }
}
}
}
processDirectDependencies(pluginDescriptor, pluginSet) { dependency ->
findLoadedPluginExtensionPointRecursive(dependency, epName, pluginSet, context, seenPlugins)?.let { return it.first to true }
}
return null
}
private inline fun processDirectDependencies(module: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
processor: (IdeaPluginDescriptorImpl) -> Unit) {
for (item in module.dependencies.modules) {
val descriptor = pluginSet.findEnabledModule(item.name)
if (descriptor != null) {
processor(descriptor)
}
}
for (item in module.dependencies.plugins) {
val descriptor = pluginSet.findEnabledPlugin(item.id)
if (descriptor != null) {
processor(descriptor)
}
}
}
private fun unloadClassLoader(pluginDescriptor: IdeaPluginDescriptorImpl, timeoutMs: Int): Boolean {
if (timeoutMs == 0) {
pluginDescriptor.pluginClassLoader = null
return true
}
val watcher = GCWatcher.tracking(pluginDescriptor.pluginClassLoader)
pluginDescriptor.pluginClassLoader = null
return watcher.tryCollect(timeoutMs)
}
private fun setClassLoaderState(pluginDescriptor: IdeaPluginDescriptorImpl, state: Int) {
(pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.state = state
for (dependency in pluginDescriptor.pluginDependencies) {
dependency.subDescriptor?.let { setClassLoaderState(it, state) }
}
}
private fun clearPluginClassLoaderParentListCache(pluginSet: PluginSet) {
// yes, clear not only enabled plugins, but all, just to be sure; it's a cheap operation
for (descriptor in pluginSet.allPlugins) {
(descriptor.pluginClassLoader as? PluginClassLoader)?.clearParentListCache()
}
}
private fun clearCachedValues() {
for (project in ProjectUtil.getOpenProjects()) {
(CachedValuesManager.getManager(project) as? CachedValuesManagerImpl)?.clearCachedValues()
}
}
| apache-2.0 | 16b2317d323546aa342b26ef38fa8841 | 40.597222 | 169 | 0.703594 | 5.841203 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.